Add vector infrastructure maps and persistent location experience
This commit is contained in:
@@ -1,3 +1,5 @@
|
|||||||
|
import { EditorUrbanMapLayer } from "./EditorUrbanMapLayer";
|
||||||
|
import { urbanPaths, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||||
import { EditorCollisionLayer } from "./EditorCollisionLayer";
|
import { EditorCollisionLayer } from "./EditorCollisionLayer";
|
||||||
import type { SimulationViewMode } from "./PlayCanvasRuntime";
|
import type { SimulationViewMode } from "./PlayCanvasRuntime";
|
||||||
import { waypointHit } from "../../core/simulation/waypointHit";
|
import { waypointHit } from "../../core/simulation/waypointHit";
|
||||||
@@ -24,6 +26,11 @@ export class AiEditorRuntime {
|
|||||||
private preferences = DEFAULT_PLANNER_PREFERENCES;
|
private preferences = DEFAULT_PLANNER_PREFERENCES;
|
||||||
private selected: string|null = null;
|
private selected: string|null = null;
|
||||||
private terrain = new EditorTerrain();
|
private terrain = new EditorTerrain();
|
||||||
|
private urbanLayer: EditorUrbanMapLayer | null = null;
|
||||||
|
private experienceLayer: EditorUrbanMapLayer | null = null;
|
||||||
|
private experiencePoints: number[][] = [];
|
||||||
|
private onExperienceProject: (p: ScreenPoint[])=>void = ()=>undefined;
|
||||||
|
private urbanMap: UrbanMap | null = null;
|
||||||
private collisionLayer: EditorCollisionLayer | null = null;
|
private collisionLayer: EditorCollisionLayer | null = null;
|
||||||
private resize: ResizeObserver;
|
private resize: ResizeObserver;
|
||||||
private abort = new AbortController();
|
private abort = new AbortController();
|
||||||
@@ -70,6 +77,7 @@ export class AiEditorRuntime {
|
|||||||
const matrix = this.camera.getWorldTransform().data.join(",");
|
const matrix = this.camera.getWorldTransform().data.join(",");
|
||||||
if (matrix !== this.previous || this.dirty) {
|
if (matrix !== this.previous || this.dirty) {
|
||||||
this.previous = matrix; this.dirty = false; app.renderNextFrame = true;
|
this.previous = matrix; this.dirty = false; app.renderNextFrame = true;
|
||||||
|
this.onExperienceProject(this.experiencePoints.map(p=>this.project(...toEditor(p) as [number,number,number])));
|
||||||
this.onRouteProject(this.route.map(p=>this.project(...toEditor(p) as [number,number,number])));
|
this.onRouteProject(this.route.map(p=>this.project(...toEditor(p) as [number,number,number])));
|
||||||
this.onProject(this.points.map((p) => {
|
this.onProject(this.points.map((p) => {
|
||||||
const [x,y,z] = toEditor(p.position);
|
const [x,y,z] = toEditor(p.position);
|
||||||
@@ -106,13 +114,28 @@ export class AiEditorRuntime {
|
|||||||
this.controls.sceneCenter = this.terrain.bounds.getCenter(this.controls.sceneCenter);
|
this.controls.sceneCenter = this.terrain.bounds.getCenter(this.controls.sceneCenter);
|
||||||
this.setClip(Infinity); this.dirty = true;
|
this.setClip(Infinity); this.dirty = true;
|
||||||
}
|
}
|
||||||
setViewMode(mode: SimulationViewMode) {
|
setExperience(document: UrbanMap, points: number[][], callback: (p: ScreenPoint[])=>void) {
|
||||||
if (mode !== "visual" && !this.collisionLayer) {
|
this.experienceLayer?.dispose();this.experienceLayer=new EditorUrbanMapLayer(this.app,this.camera,document);
|
||||||
|
this.experiencePoints=points;this.onExperienceProject=callback;this.experienceLayer.setClip(this.clip);this.dirty=true;
|
||||||
|
}
|
||||||
|
showExperience(visible: boolean) {this.experienceLayer?.setVisible(visible);this.dirty=true;}
|
||||||
|
clearExperience() {this.experienceLayer?.dispose();this.experienceLayer=null;this.experiencePoints=[];this.onExperienceProject=()=>undefined;this.dirty=true;}
|
||||||
|
setUrbanMap(document: UrbanMap) {
|
||||||
|
this.urbanLayer?.dispose(); this.urbanMap=document;
|
||||||
|
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip);this.dirty=true;
|
||||||
|
}
|
||||||
|
showUrbanMap(visible: boolean) { this.urbanLayer?.setVisible(visible);this.dirty=true; }
|
||||||
|
focusUrbanMap() {
|
||||||
|
const points=this.urbanMap?.features.flatMap(f=>urbanPaths(f).flat()).map(toEditor)??[];
|
||||||
|
if(points.length)this.controls.top(points);this.syncCamera();this.dirty=true;
|
||||||
|
}
|
||||||
|
setViewMode(mode: SimulationViewMode|"map") {
|
||||||
|
if (mode !== "visual" && mode !== "map" && !this.collisionLayer) {
|
||||||
this.collisionLayer = new EditorCollisionLayer(this.app, this.camera, this.terrain.renderData());
|
this.collisionLayer = new EditorCollisionLayer(this.app, this.camera, this.terrain.renderData());
|
||||||
this.collisionLayer.setClip(this.clip);
|
this.collisionLayer.setClip(this.clip);
|
||||||
}
|
}
|
||||||
this.scan.enabled = mode !== "collision";
|
this.scan.enabled = mode === "visual" || mode === "combined";
|
||||||
this.collisionLayer?.setMode(mode);
|
this.collisionLayer?.setMode(mode === "map" ? "visual" : mode);
|
||||||
this.dirty = true;
|
this.dirty = true;
|
||||||
}
|
}
|
||||||
setRoute(points:number[][]) {this.route=points;this.dirty=true;}
|
setRoute(points:number[][]) {this.route=points;this.dirty=true;}
|
||||||
@@ -133,6 +156,7 @@ export class AiEditorRuntime {
|
|||||||
setClip(height: number) {
|
setClip(height: number) {
|
||||||
this.clip = height;
|
this.clip = height;
|
||||||
this.collisionLayer?.setClip(height);
|
this.collisionLayer?.setClip(height);
|
||||||
|
this.urbanLayer?.setClip(height);this.experienceLayer?.setClip(height);
|
||||||
if (this.scan.gsplat) {
|
if (this.scan.gsplat) {
|
||||||
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
|
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
|
||||||
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
|
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
|
||||||
@@ -189,6 +213,7 @@ export class AiEditorRuntime {
|
|||||||
this.abort.abort(); this.resize.disconnect(); this.terrain.dispose();
|
this.abort.abort(); this.resize.disconnect(); this.terrain.dispose();
|
||||||
this.annotations.dispose();
|
this.annotations.dispose();
|
||||||
this.collisionLayer?.dispose();
|
this.collisionLayer?.dispose();
|
||||||
|
this.urbanLayer?.dispose();this.clearExperience();
|
||||||
this.asset?.unload(); this.app.destroy(); this.canvas.width=1; this.canvas.height=1;
|
this.asset?.unload(); this.app.destroy(); this.canvas.width=1; this.canvas.height=1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { PlannerExperience } from "./PlannerExperience";
|
||||||
|
import { loadUrbanMap, URBAN_COLORS, URBAN_LABELS, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||||
import type { SimulationViewMode } from "./PlayCanvasRuntime";
|
import type { SimulationViewMode } from "./PlayCanvasRuntime";
|
||||||
import type { PreparedRoute } from "../../core/simulation/routePreparation";
|
import type { PreparedRoute } from "../../core/simulation/routePreparation";
|
||||||
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
|
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||||
@@ -31,7 +33,10 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
|||||||
const {points,selected,sequence} = editing;
|
const {points,selected,sequence} = editing;
|
||||||
const press=useRef<{id:number;x:number;y:number}|null>(null);
|
const press=useRef<{id:number;x:number;y:number}|null>(null);
|
||||||
const [routeProjection,setRouteProjection]=useState<ScreenPoint[]>([]);
|
const [routeProjection,setRouteProjection]=useState<ScreenPoint[]>([]);
|
||||||
const [layerMode,setLayerMode]=useState<SimulationViewMode>("visual");
|
const [layerMode,setLayerMode]=useState<SimulationViewMode|"map">("visual");
|
||||||
|
const [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null);
|
||||||
|
const [urbanVisible,setUrbanVisible]=useState(false);
|
||||||
|
const [urbanError,setUrbanError]=useState<string|null>(null);
|
||||||
const [viewMode,setViewMode]=useState<"3d"|"top">("3d");
|
const [viewMode,setViewMode]=useState<"3d"|"top">("3d");
|
||||||
const [markers, setMarkers] = useState<EditorMarker[]>([]);
|
const [markers, setMarkers] = useState<EditorMarker[]>([]);
|
||||||
const [mode,setMode] = useState<"view" | "add">("view");
|
const [mode,setMode] = useState<"view" | "add">("view");
|
||||||
@@ -42,14 +47,21 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (cache?.status !== "ready" || !canvas.current) return;
|
if (cache?.status !== "ready" || !canvas.current) return;
|
||||||
let active = true;
|
let active = true;
|
||||||
|
const abort=new AbortController();
|
||||||
|
setUrbanMap(null);setUrbanVisible(false);setUrbanError(null);
|
||||||
setReady(false); setError(null); setClip(Infinity); setLayerMode("visual");
|
setReady(false); setError(null); setClip(Infinity); setLayerMode("visual");
|
||||||
let view: AiEditorRuntime;
|
let view: AiEditorRuntime;
|
||||||
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
|
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
|
||||||
catch (e) { setError((e as Error).message); return; }
|
catch (e) { setError((e as Error).message); return; }
|
||||||
runtime.current = view;
|
runtime.current = view;
|
||||||
view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
|
view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
|
||||||
void view.load().then(() => { if (active) setReady(true); }).catch((e: Error) => { if (active) setError(e.message); });
|
void view.load().then(() => { if (active) {
|
||||||
return () => { active=false; runtime.current=null; view.dispose(); callback.current(null); };
|
setReady(true);
|
||||||
|
void loadUrbanMap(cache.world.world_id,cache.world.sha256!,abort.signal).then(map=>{
|
||||||
|
if(active && map){view.setUrbanMap(map);setUrbanMap(map);}
|
||||||
|
}).catch((e:Error)=>{if(active)setUrbanError(e.message);});
|
||||||
|
} }).catch((e: Error) => { if (active) setError(e.message); });
|
||||||
|
return () => { active=false; abort.abort(); runtime.current=null; view.dispose(); callback.current(null); };
|
||||||
}, [cache?.key,cache?.status,retry]);
|
}, [cache?.key,cache?.status,retry]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
runtime.current?.setPoints(points);
|
runtime.current?.setPoints(points);
|
||||||
@@ -86,7 +98,13 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
|||||||
{expanded ? <div className="ai-polygon__actions">{headerActions}</div> : actionsHost ? createPortal(headerActions,actionsHost) : null}
|
{expanded ? <div className="ai-polygon__actions">{headerActions}</div> : actionsHost ? createPortal(headerActions,actionsHost) : null}
|
||||||
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
|
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
|
||||||
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? "Планирование на этом компьютере" : message}</StatusBadge>
|
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? "Планирование на этом компьютере" : message}</StatusBadge>
|
||||||
<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p></div>
|
<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p>
|
||||||
|
{urbanVisible && urbanMap ? <p>Генплан · {urbanMap.coverage.kind === "objects-only" ? `участок · ${urbanMap.features.length} объектов · распознано автоматически` : `${(urbanMap.coverage.accepted_cells * urbanMap.coverage.cell_m ** 2).toFixed(0)} м² · неполное покрытие`}</p> : null}
|
||||||
|
</div>
|
||||||
|
{urbanVisible?<span className="ai-inference-preview__legend" aria-label="Классы инфраструктуры">
|
||||||
|
{Object.keys(URBAN_LABELS).filter(id=>urbanMap?.features.some(f=>f.properties.class===id)).map(id=>
|
||||||
|
<span key={id}><i style={{background:`rgb(${URBAN_COLORS[id].join(',')})`}}/>{URBAN_LABELS[id]}</span>)}
|
||||||
|
</span>:null}
|
||||||
<div className="ai-polygon__viewer">
|
<div className="ai-polygon__viewer">
|
||||||
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
|
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
|
||||||
onKeyDown={(e)=>{
|
onKeyDown={(e)=>{
|
||||||
@@ -99,11 +117,15 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
|||||||
{points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
|
{points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
|
||||||
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
|
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
|
||||||
}}><Icon name="trash"/></IconButton>:null}
|
}}><Icon name="trash"/></IconButton>:null}
|
||||||
|
{runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!} runtime={runtime.current} viewport={viewport.current}/> : null}
|
||||||
<SegmentedControl label="Слои сцены" value={layerMode}
|
<SegmentedControl label="Слои сцены" value={layerMode}
|
||||||
items={[{value:"visual",label:"Gaussian"},{value:"collision",label:"Коллизии"},{value:"combined",label:"Вместе"}]}
|
items={[{value:"visual",label:"Gaussian"},{value:"collision",label:"Коллизии"},{value:"combined",label:"Вместе"},...(urbanMap?[{value:"map" as const,label:"Генплан"}]:[])]}
|
||||||
onChange={v=>{try {runtime.current?.setViewMode(v);setLayerMode(v);setError(null);}
|
onChange={v=>{try {runtime.current?.setViewMode(v);setLayerMode(v);if(v==="map"){setUrbanVisible(true);runtime.current?.showUrbanMap(true);runtime.current?.focusUrbanMap();setViewMode("top");}setError(null);}
|
||||||
catch (e) {setError(e instanceof Error?e.message:"Не удалось показать слой коллизий.");}}}/>
|
catch (e) {setError(e instanceof Error?e.message:"Не удалось показать слой коллизий.");}}}/>
|
||||||
{preparedRoute?<SegmentedControl label="Ракурс маршрута" value={viewMode}
|
<IconButton label={urbanError??(urbanMap?"Карта дорожной инфраструктуры":"Карта инфраструктуры ещё не подготовлена")}
|
||||||
|
disabled={!urbanMap || layerMode==="map"} aria-pressed={urbanVisible} onClick={()=>{const visible=!urbanVisible;setUrbanVisible(visible);runtime.current?.showUrbanMap(visible);}}><Icon name="layers"/></IconButton>
|
||||||
|
{urbanVisible?<IconButton label="Показать участок карты" onClick={()=>{runtime.current?.focusUrbanMap();setViewMode("top");}}><Icon name="plan"/></IconButton>:null}
|
||||||
|
{preparedRoute||urbanMap?<SegmentedControl label="Ракурс" value={viewMode}
|
||||||
items={[{value:"3d",label:"3D"},{value:"top",label:"Вид сверху"}]}
|
items={[{value:"3d",label:"3D"},{value:"top",label:"Вид сверху"}]}
|
||||||
onChange={v=>{setViewMode(v);if(v==="top")runtime.current?.top();else runtime.current?.home();}}/>:null}
|
onChange={v=>{setViewMode(v);if(v==="top")runtime.current?.top();else runtime.current?.home();}}/>:null}
|
||||||
<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
|
<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { Application, Entity, Layer, LAYERID_WORLD, Mesh, MeshInstance, PRIMITIVE_LINES, SEMANTIC_COLOR, SEMANTIC_POSITION, ShaderMaterial } from "playcanvas";
|
||||||
|
import { toEditor } from "../../core/simulation/aiEditor";
|
||||||
|
import { URBAN_COLORS, urbanPaths, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||||
|
|
||||||
|
/** Read-only contours. This layer never enters terrain picking, collision or routing. */
|
||||||
|
export class EditorUrbanMapLayer {
|
||||||
|
private entity: Entity;
|
||||||
|
private mesh: Mesh;
|
||||||
|
private material: ShaderMaterial;
|
||||||
|
private layer = new Layer({ name: "Urban infrastructure observations" });
|
||||||
|
constructor(private app: Application, private camera: Entity, document: UrbanMap) {
|
||||||
|
app.scene.layers.insert(this.layer, app.scene.layers.getTransparentIndex(app.scene.layers.getLayerById(LAYERID_WORLD)!) + 1);
|
||||||
|
camera.camera!.layers = [...camera.camera!.layers, this.layer.id];
|
||||||
|
this.material = new ShaderMaterial({ uniqueName: "urban-map-contours", attributes: { vertex_position: SEMANTIC_POSITION, vertex_color: SEMANTIC_COLOR },
|
||||||
|
vertexGLSL: `attribute vec3 vertex_position; attribute vec4 vertex_color;
|
||||||
|
uniform mat4 matrix_model; uniform mat4 matrix_viewProjection;
|
||||||
|
varying vec4 mapColor; varying float mapHeight;
|
||||||
|
void main(void) { vec4 p=matrix_model*vec4(vertex_position,1.0); mapColor=vertex_color; mapHeight=p.y; gl_Position=matrix_viewProjection*p; }`,
|
||||||
|
fragmentGLSL: `precision highp float; varying vec4 mapColor; varying float mapHeight; uniform float mapClip;
|
||||||
|
void main(void) { if(mapHeight>mapClip) discard; gl_FragColor=mapColor; }` });
|
||||||
|
this.material.depthTest = false; this.material.depthWrite = false;
|
||||||
|
const positions: number[] = [], colors: number[] = [];
|
||||||
|
for (const feature of document.features) {
|
||||||
|
const color = URBAN_COLORS[feature.properties.class]; if (!color) continue;
|
||||||
|
for (const ring of urbanPaths(feature)) for (let i=1;i<ring.length;i++) {
|
||||||
|
positions.push(...toEditor(ring[i-1]), ...toEditor(ring[i]));
|
||||||
|
colors.push(...color,255,...color,255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.mesh = new Mesh(app.graphicsDevice); this.mesh.setPositions(positions); this.mesh.setColors32(colors); this.mesh.update(PRIMITIVE_LINES);
|
||||||
|
this.entity = new Entity("Urban infrastructure",app);
|
||||||
|
this.entity.addComponent("render", { meshInstances: [new MeshInstance(this.mesh,this.material)], layers: [this.layer.id] });
|
||||||
|
this.entity.enabled=false; app.root.addChild(this.entity); this.setClip(Infinity);
|
||||||
|
}
|
||||||
|
setVisible(visible: boolean) { this.entity.enabled=visible; }
|
||||||
|
setClip(height: number) { this.material.setParameter("mapClip",Number.isFinite(height)?height:1e9); }
|
||||||
|
dispose() { this.camera.camera!.layers=this.camera.camera!.layers.filter(id=>id!==this.layer.id); this.app.scene.layers.remove(this.layer); this.entity.destroy();this.mesh.destroy();this.material.destroy(); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Icon, IconButton } from "@nodedc/ui-react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
import { loadExperience, attemptLabel, experienceMap, type SpatialExperience } from "../../core/simulation/spatialExperience";
|
||||||
|
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||||
|
import type { AiEditorRuntime } from "./AiEditorRuntime";
|
||||||
|
import { URBAN_COLORS } from "../../core/simulation/urbanMap";
|
||||||
|
|
||||||
|
export function PlannerExperience({worldId,worldSha,runtime,viewport}: {
|
||||||
|
worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;
|
||||||
|
}) {
|
||||||
|
const [memory,setMemory]=useState<SpatialExperience|null>(null),[visible,setVisible]=useState(false);
|
||||||
|
const [projected,setProjected]=useState<ScreenPoint[]>([]),[error,setError]=useState<string|null>(null);
|
||||||
|
useEffect(()=>{
|
||||||
|
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
|
||||||
|
const refresh=async()=>{
|
||||||
|
try {const value=await loadExperience(worldId,worldSha,abort.signal);
|
||||||
|
if(abort.signal.aborted)return;setMemory(value);setError(null);
|
||||||
|
if(value)runtime.setExperience(experienceMap(value),value.attempts.map(a=>a.xyz),setProjected);
|
||||||
|
} catch(e) {if(!abort.signal.aborted)setError((e as Error).message);}
|
||||||
|
if(!abort.signal.aborted)timer=setTimeout(refresh,5000);
|
||||||
|
};
|
||||||
|
void refresh();return ()=>{abort.abort();clearTimeout(timer);runtime.clearExperience();};
|
||||||
|
},[worldId,worldSha,runtime]);
|
||||||
|
useEffect(()=>runtime.showExperience(visible),[runtime,visible,memory]);
|
||||||
|
return <>
|
||||||
|
<IconButton label={error??(memory?`Память локации · посещено ${memory.visits.length} участков · ${memory.attempts.length} попыток`:"В этой локации ещё нет сохранённого опыта")}
|
||||||
|
disabled={!memory} aria-pressed={visible} onClick={()=>setVisible(v=>!v)}><Icon name="database"/></IconButton>
|
||||||
|
{visible&&memory?createPortal(<svg className="ai-local-editor__markers" viewBox="0 0 1280 720" preserveAspectRatio="none" aria-label="Память проездов">
|
||||||
|
{memory.attempts.map((attempt,i)=>{const p=projected[i];if(!p)return null;
|
||||||
|
const label=attemptLabel(attempt),color=URBAN_COLORS[attempt.status==="unresolved"?"attempt":"revisited"];
|
||||||
|
return <g key={attempt.id} role="img" aria-label={label} tabIndex={0} style={{pointerEvents:"auto"}}>
|
||||||
|
<title>{label}</title><circle cx={p[0]*1280} cy={p[1]*720} r="7" fill={`rgb(${color.join(",")})`}/>
|
||||||
|
</g>;
|
||||||
|
})}
|
||||||
|
</svg>,viewport):null}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import type { UrbanMap, UrbanMapFeature } from "./urbanMap";
|
||||||
|
export interface PlaceAttempt {
|
||||||
|
id:string;xyz:number[];origin:number[];reason:string;status:"unresolved"|"revisited-successfully";
|
||||||
|
first_seen:number;last_seen:number;count:number;run_id:string;observation_id:string;
|
||||||
|
}
|
||||||
|
export interface SpatialExperience {
|
||||||
|
schema_version:"missioncore.spatial-experience/v1";
|
||||||
|
source:{world_sha256:string;collider_sha256:string;robot_sha256:string};
|
||||||
|
visits:{id:string;xyz:number[];count:number;last_seen:number}[];
|
||||||
|
attempts:PlaceAttempt[];
|
||||||
|
}
|
||||||
|
const REASONS:Record<string,string>={"no-path":"Путь не найден","no-permitted-goal":"Не найдена разрешённая поверхность","footprint":"Недостаточно места для корпуса",
|
||||||
|
"observed-unsafe-support":"Ненадёжная опора","forbidden-surface-sweep":"Запрещённая поверхность",
|
||||||
|
"detected-object-sweep":"Препятствие на пути"};
|
||||||
|
export function attemptLabel(a:PlaceAttempt) {
|
||||||
|
return `${a.status==="revisited-successfully"?"Позже проехал":"Попытка проезда"} · ${REASONS[a.reason]??a.reason} · ${a.count} · ${new Date(a.last_seen*1000).toLocaleString("ru")}`;
|
||||||
|
}
|
||||||
|
/** Cell marks and attempted direction; no invented connections between visits. */
|
||||||
|
export function experienceMap(memory:SpatialExperience):UrbanMap {
|
||||||
|
const feature=(id:string,cls:string,points:number[][]):UrbanMapFeature=>({id,
|
||||||
|
properties:{class:cls,authority:"observation-only",route_permission:"unassigned"},geometry:{type:"LineString",coordinates:points}});
|
||||||
|
return {schema_version:"missioncore.urban-map/v2",source:memory.source,coverage:{cell_m:.5,accepted_cells:memory.visits.length},features:[
|
||||||
|
...memory.visits.map(v=>feature(v.id,"visited",[[v.xyz[0]-.12,v.xyz[1],v.xyz[2]],[v.xyz[0]+.12,v.xyz[1],v.xyz[2]]])),
|
||||||
|
...memory.attempts.map(a=>feature(a.id,a.status==="unresolved"?"attempt":"revisited",[a.origin,a.xyz])),
|
||||||
|
]};
|
||||||
|
}
|
||||||
|
export async function loadExperience(worldId:string,worldSha:string,signal:AbortSignal):Promise<SpatialExperience|null> {
|
||||||
|
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/spatial-experience`,{signal,cache:"no-store"});
|
||||||
|
if(response.status===404)return null;
|
||||||
|
if(!response.ok)throw new Error("Не удалось загрузить память локации.");
|
||||||
|
const data=await response.json() as SpatialExperience;
|
||||||
|
if(data.schema_version!=="missioncore.spatial-experience/v1"||data.source.world_sha256!==worldSha)throw new Error("Память относится к другой локации.");
|
||||||
|
return data;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
export interface UrbanMapFeature {
|
||||||
|
id: string;
|
||||||
|
properties: { class: string; authority: "observation-only"; route_permission: "unassigned"; confidence?: number; review_status?: "unreviewed"|"accepted"|"rejected" };
|
||||||
|
geometry: { type: "Polygon"; coordinates: number[][][] } | { type: "LineString"; coordinates: number[][] };
|
||||||
|
}
|
||||||
|
export interface UrbanMap {
|
||||||
|
schema_version: "missioncore.urban-map/v1"|"missioncore.urban-map/v2";
|
||||||
|
source: { world_sha256: string; collider_sha256: string };
|
||||||
|
features: UrbanMapFeature[];
|
||||||
|
coverage: { accepted_cells: number; cell_m: number; kind?: "objects-only" };
|
||||||
|
}
|
||||||
|
export const URBAN_COLORS: Record<string, [number, number, number]> = {
|
||||||
|
visited: [60,220,200], attempt: [245,130,48], revisited: [245,245,245],
|
||||||
|
curb: [245,130,48], curb_cut: [255,150,80], sidewalk: [60,220,200], pedestrian_area: [60,220,200],
|
||||||
|
carriageway: [90,130,200], service_lane: [110,150,210], bike_lane: [150,110,220], parking: [140,140,150],
|
||||||
|
crosswalk_area: [255,225,35], crosswalk_marking: [255,225,35], road_marking: [245,245,245],
|
||||||
|
};
|
||||||
|
export const URBAN_LABELS: Record<string, string> = {
|
||||||
|
curb: "Бордюр", curb_cut: "Съезд", sidewalk: "Тротуар", pedestrian_area: "Пешеходная зона",
|
||||||
|
carriageway: "Проезжая часть", service_lane: "Служебный проезд", bike_lane: "Велополоса", parking: "Парковка",
|
||||||
|
crosswalk_area: "Переход", crosswalk_marking: "Зебра", road_marking: "Разметка",
|
||||||
|
};
|
||||||
|
export async function loadUrbanMap(worldId: string, worldSha: string, signal: AbortSignal): Promise<UrbanMap|null> {
|
||||||
|
const response = await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/urban-map`, { signal, cache: "no-store" });
|
||||||
|
if (response.status === 404) return null;
|
||||||
|
if (!response.ok) throw new Error("Не удалось загрузить карту инфраструктуры.");
|
||||||
|
const result = await response.json() as UrbanMap;
|
||||||
|
if (!["missioncore.urban-map/v1","missioncore.urban-map/v2"].includes(result.schema_version) || result.source.world_sha256 !== worldSha) {
|
||||||
|
throw new Error("Карта относится к другой версии сцены.");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function urbanPaths(feature: UrbanMapFeature): number[][][] {
|
||||||
|
return feature.properties.review_status === "rejected" ? [] : feature.geometry.type === "Polygon" ? feature.geometry.coordinates : [feature.geometry.coordinates];
|
||||||
|
}
|
||||||
@@ -77,7 +77,7 @@
|
|||||||
.ai-simulation__speed { position: absolute; left: .75rem; bottom: .75rem; pointer-events: none; font-size: var(--nodedc-font-size-sm); }
|
.ai-simulation__speed { position: absolute; left: .75rem; bottom: .75rem; pointer-events: none; font-size: var(--nodedc-font-size-sm); }
|
||||||
/* Equal visible padding on all three sides; owner requested twice the radius-centred inset. */
|
/* Equal visible padding on all three sides; owner requested twice the radius-centred inset. */
|
||||||
.ai-local-editor .ai-route__height { --ai-clip-inset: calc(var(--nodedc-radius-panel) * 2 - var(--nodedc-control-height) * .4); top: var(--ai-clip-inset); bottom: var(--ai-clip-inset); left: var(--ai-clip-inset); right: auto; width: calc(var(--nodedc-control-height) * .4); }
|
.ai-local-editor .ai-route__height { --ai-clip-inset: calc(var(--nodedc-radius-panel) * 2 - var(--nodedc-control-height) * .4); top: var(--ai-clip-inset); bottom: var(--ai-clip-inset); left: var(--ai-clip-inset); right: auto; width: calc(var(--nodedc-control-height) * .4); }
|
||||||
.ai-local-editor__tools { display: flex; align-items: center; gap: .5rem; }
|
.ai-local-editor__tools { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: .5rem; max-width: 100%; }
|
||||||
.ai-local-editor .ai-route__tools { left: 5.5rem; right: .75rem; }
|
.ai-local-editor .ai-route__tools { left: 5.5rem; right: .75rem; }
|
||||||
/* The renderer has no perimeter; canonical controls retain their focus indicators. */
|
/* The renderer has no perimeter; canonical controls retain their focus indicators. */
|
||||||
.ai-local-editor canvas { outline: none; }
|
.ai-local-editor canvas { outline: none; }
|
||||||
|
|||||||
@@ -35,6 +35,10 @@ foreach($entry in $manifest.PSObject.Properties) {
|
|||||||
$count++
|
$count++
|
||||||
}
|
}
|
||||||
if($count -eq 0) { throw 'Empty release' }
|
if($count -eq 0) { throw 'Empty release' }
|
||||||
|
# Validate startup imports with the installed interpreter while the old service
|
||||||
|
# still owns the runtime. --help cannot acquire a service lock or start models.
|
||||||
|
$preflight = & $old.Execute "$source\simulation\ai-polygon\realtime_worker.py" --help 2>&1
|
||||||
|
if($LASTEXITCODE -ne 0) { throw 'Worker startup preflight failed; installed service preserved' }
|
||||||
$arguments=$old.Arguments.Replace('ai-polygon-'+$ExpectedCurrentRelease,'ai-polygon-'+$Release)
|
$arguments=$old.Arguments.Replace('ai-polygon-'+$ExpectedCurrentRelease,'ai-polygon-'+$Release)
|
||||||
if($EvidenceRoot) {
|
if($EvidenceRoot) {
|
||||||
$EvidenceRoot=[IO.Path]::GetFullPath($EvidenceRoot)
|
$EvidenceRoot=[IO.Path]::GetFullPath($EvidenceRoot)
|
||||||
@@ -70,6 +74,10 @@ if($Apply) {
|
|||||||
}
|
}
|
||||||
Set-ScheduledTask -TaskName $name -Action $action | Out-Null
|
Set-ScheduledTask -TaskName $name -Action $action | Out-Null
|
||||||
Start-ScheduledTask -TaskName $name
|
Start-ScheduledTask -TaskName $name
|
||||||
|
Start-Sleep -Seconds 3
|
||||||
|
if((Get-ScheduledTask -TaskName $name).State -ne 'Running') {
|
||||||
|
throw 'Worker exited after activation'
|
||||||
|
}
|
||||||
$report.applied=$true
|
$report.applied=$true
|
||||||
} catch {
|
} catch {
|
||||||
Set-ScheduledTask -TaskName $name -Action $old | Out-Null
|
Set-ScheduledTask -TaskName $name -Action $old | Out-Null
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
"""Package current source plus simulation adapters into a digest-addressed archive."""
|
"""Package current source plus simulation adapters into a digest-addressed archive."""
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import ast
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import tarfile
|
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"]
|
asset = root / json.loads(profile.read_text())["visual"]["source"]
|
||||||
if asset not in files:
|
if asset not in files:
|
||||||
files.append(asset)
|
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 = {
|
manifest = {
|
||||||
p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files
|
p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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))
|
count = min(2*count, len(barriers))
|
||||||
return cost
|
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.
|
"""Measured local destinations may temporarily move away from the task.
|
||||||
|
|
||||||
This removes the greedy progress constraint ONLY during a surveyed
|
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 = np.linalg.norm(candidates[:, :2]-target, axis=1) + .2*turning + .15*distance
|
||||||
score += self.boundary_cost(candidates, geometry, now)
|
score += self.boundary_cost(candidates, geometry, now)
|
||||||
score += self.clearance_cost(candidates, pose, geometry, now)[0]
|
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
|
# Recovery actions need a fair turn, as in Nav2's RoundRobin recovery
|
||||||
# subtree. Distance-to-task alone can spend every retry on almost the
|
# subtree. Distance-to-task alone can spend every retry on almost the
|
||||||
# same forward approach before ever considering a measured retreat.
|
# same forward approach before ever considering a measured retreat.
|
||||||
|
|||||||
@@ -380,6 +380,7 @@ class NavigationClient:
|
|||||||
|
|
||||||
|
|
||||||
class ComposedInference:
|
class ComposedInference:
|
||||||
|
experience = None
|
||||||
def __init__(self, root: Path, run, directory: Path, mission=None):
|
def __init__(self, root: Path, run, directory: Path, mission=None):
|
||||||
profile = json.loads((root / "models.worker-006.json").read_text())
|
profile = json.loads((root / "models.worker-006.json").read_text())
|
||||||
self.graph = compose(root, run["request"].get("composition"))
|
self.graph = compose(root, run["request"].get("composition"))
|
||||||
@@ -433,6 +434,10 @@ class ComposedInference:
|
|||||||
self.navigation_evidence = {}
|
self.navigation_evidence = {}
|
||||||
self.pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="simulation-module")
|
self.pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="simulation-module")
|
||||||
self.directory = directory
|
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
|
names = self.models.labels
|
||||||
if self.segmenter_id == "simulation-sam3-surfaces":
|
if self.segmenter_id == "simulation-sam3-surfaces":
|
||||||
from k1link.simulation.ai_polygon.concept_surfaces import LABELS
|
from k1link.simulation.ai_polygon.concept_surfaces import LABELS
|
||||||
@@ -655,7 +660,8 @@ class ComposedInference:
|
|||||||
return observed_goals.maneuver(
|
return observed_goals.maneuver(
|
||||||
inputs["source.lidar"], inputs["source.pose"], target, prior, excluded,
|
inputs["source.lidar"], inputs["source.pose"], target, prior, excluded,
|
||||||
self.geometry, time.monotonic(), self.mission.goals_permitted
|
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(
|
self.goal, intent = self.mission.update(
|
||||||
inputs["source.pose"],
|
inputs["source.pose"],
|
||||||
@@ -1020,6 +1026,8 @@ class ComposedInference:
|
|||||||
# direction and this transaction's range/support gates. It does
|
# direction and this transaction's range/support gates. It does
|
||||||
# not use the older local translation goal retained during survey.
|
# not use the older local translation goal retained during survey.
|
||||||
self.intent_captured_at = calibration["captured_at"]
|
self.intent_captured_at = calibration["captured_at"]
|
||||||
|
if self.experience is not None:
|
||||||
|
self.experience.observe(inputs, self.goal, result)
|
||||||
self.navigation_evidence = {
|
self.navigation_evidence = {
|
||||||
"mission": intent,
|
"mission": intent,
|
||||||
"environment": self.environment,
|
"environment": self.environment,
|
||||||
@@ -1199,6 +1207,8 @@ class ComposedInference:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
|
if self.experience is not None:
|
||||||
|
self.experience.close()
|
||||||
self.pool.shutdown(wait=True, cancel_futures=True)
|
self.pool.shutdown(wait=True, cancel_futures=True)
|
||||||
self.models.close()
|
self.models.close()
|
||||||
self.navigation.close()
|
self.navigation.close()
|
||||||
|
|||||||
@@ -93,6 +93,15 @@ def publish_previews(client, episode, run_id, stopped):
|
|||||||
stopped.wait(1)
|
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):
|
def preparation_heartbeat(client, hello, run_id):
|
||||||
"""One-thread lease/control pulse; reconnect only this same expired owner."""
|
"""One-thread lease/control pulse; reconnect only this same expired owner."""
|
||||||
last_poll = -float("inf")
|
last_poll = -float("inf")
|
||||||
@@ -189,6 +198,7 @@ def main():
|
|||||||
"project_assets.py",
|
"project_assets.py",
|
||||||
"decode_collision.cjs",
|
"decode_collision.cjs",
|
||||||
"navigation_client.py",
|
"navigation_client.py",
|
||||||
|
"experience_adapter.py",
|
||||||
"route_view.py",
|
"route_view.py",
|
||||||
"observer_camera.py",
|
"observer_camera.py",
|
||||||
"inference_preview.py",
|
"inference_preview.py",
|
||||||
@@ -384,6 +394,7 @@ def main():
|
|||||||
raise RuntimeError("An existing episode must never be replayed")
|
raise RuntimeError("An existing episode must never be replayed")
|
||||||
episode = create_episode(args.state, run["run_id"], args.evidence_root)
|
episode = create_episode(args.state, run["run_id"], args.evidence_root)
|
||||||
run_file = episode / "run.json"
|
run_file = episode / "run.json"
|
||||||
|
run["_spatial_experience_root"] = str(args.state / "spatial-experience")
|
||||||
write_json(run_file, run)
|
write_json(run_file, run)
|
||||||
channel = StateChannel(episode)
|
channel = StateChannel(episode)
|
||||||
channel.write("control", run)
|
channel.write("control", run)
|
||||||
@@ -438,6 +449,7 @@ def main():
|
|||||||
):
|
):
|
||||||
raise ValueError("Saved task and simulation surface identities differ")
|
raise ValueError("Saved task and simulation surface identities differ")
|
||||||
run["terrain_manifest"] = str(terrain_path)
|
run["terrain_manifest"] = str(terrain_path)
|
||||||
|
run["_spatial_experience_root"] = str(args.state / "spatial-experience")
|
||||||
write_json(run_file, run)
|
write_json(run_file, run)
|
||||||
with (episode / "isaac.log").open("wb") as output:
|
with (episode / "isaac.log").open("wb") as output:
|
||||||
child = subprocess.Popen(
|
child = subprocess.Popen(
|
||||||
@@ -484,6 +496,8 @@ def main():
|
|||||||
|
|
||||||
stop_deadline = None
|
stop_deadline = None
|
||||||
last_snapshot = -1
|
last_snapshot = -1
|
||||||
|
experience_stamp = None
|
||||||
|
experience_checked = -float("inf")
|
||||||
preview_sender = threading.Thread(
|
preview_sender = threading.Thread(
|
||||||
target=publish_previews,
|
target=publish_previews,
|
||||||
args=(client, episode, run["run_id"], preview_stopped),
|
args=(client, episode, run["run_id"], preview_stopped),
|
||||||
@@ -531,6 +545,14 @@ def main():
|
|||||||
if snapshot and snapshot["sequence"] > last_snapshot:
|
if snapshot and snapshot["sequence"] > last_snapshot:
|
||||||
client.request("/worker/runs/" + run["run_id"] + "/snapshot", snapshot)
|
client.request("/worker/runs/" + run["run_id"] + "/snapshot", snapshot)
|
||||||
last_snapshot = snapshot["sequence"]
|
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:
|
except Exception as exc:
|
||||||
registered = False
|
registered = False
|
||||||
logging.warning(
|
logging.warning(
|
||||||
@@ -595,6 +617,10 @@ def main():
|
|||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
client.request("/worker/register", hello)
|
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(
|
client.request(
|
||||||
"/worker/runs/" + run["run_id"] + "/finish",
|
"/worker/runs/" + run["run_id"] + "/finish",
|
||||||
finish,
|
finish,
|
||||||
|
|||||||
@@ -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"]
|
||||||
@@ -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.
|
||||||
@@ -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)
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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
|
||||||
@@ -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())
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
"""Bounded location experience. Observations and soft preferences, never occupancy.
|
||||||
|
|
||||||
|
Coordinates cannot migrate between world/collider/robot revisions. Runtime sensor
|
||||||
|
memory remains separate. Persistent records are summaries, not raw telemetry.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
|
||||||
|
SCHEMA = "missioncore.spatial-experience/v1"
|
||||||
|
MAX_VISITS, MAX_ATTEMPTS = 20000, 1000
|
||||||
|
FAILURES = {
|
||||||
|
"no-path",
|
||||||
|
"footprint",
|
||||||
|
"observed-unsafe-support",
|
||||||
|
"forbidden-surface-sweep",
|
||||||
|
"detected-object-sweep",
|
||||||
|
"no-permitted-goal",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def source_key(source):
|
||||||
|
if (
|
||||||
|
not isinstance(source, dict)
|
||||||
|
or set(source) != {"world_sha256", "collider_sha256", "robot_sha256"}
|
||||||
|
or any(
|
||||||
|
not isinstance(v, str) or len(v) != 64 or any(c not in "0123456789abcdef" for c in v)
|
||||||
|
for v in source.values()
|
||||||
|
)
|
||||||
|
):
|
||||||
|
raise ValueError("Invalid spatial experience revision")
|
||||||
|
return hashlib.sha256(json.dumps(source, sort_keys=True).encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def valid_xyz(value):
|
||||||
|
return (
|
||||||
|
isinstance(value, list)
|
||||||
|
and len(value) == 3
|
||||||
|
and all(type(v) in (float, int) and math.isfinite(v) and abs(v) < 1e6 for v in value)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def validate(document, source=None):
|
||||||
|
if not isinstance(document, dict) or document.get("schema_version") != SCHEMA:
|
||||||
|
raise ValueError("Invalid location experience")
|
||||||
|
source_key(document.get("source", {}))
|
||||||
|
if source is not None and source != document["source"]:
|
||||||
|
raise ValueError("Location revision mismatch")
|
||||||
|
if document.get("authority") != "experience-only":
|
||||||
|
raise ValueError("Experience cannot grant motion")
|
||||||
|
for field, limit in [("visits", MAX_VISITS), ("attempts", MAX_ATTEMPTS)]:
|
||||||
|
items = document.get(field)
|
||||||
|
if not isinstance(items, list) or len(items) > limit:
|
||||||
|
raise ValueError("Experience exceeds bounds")
|
||||||
|
ids = set()
|
||||||
|
for item in items:
|
||||||
|
if not isinstance(item, dict) or not valid_xyz(item.get("xyz")):
|
||||||
|
raise ValueError("Invalid experience point")
|
||||||
|
key = item.get("id")
|
||||||
|
if not isinstance(key, str) or len(key) > 80 or key in ids:
|
||||||
|
raise ValueError("Invalid experience identity")
|
||||||
|
ids.add(key)
|
||||||
|
for name in ["first_seen", "last_seen"]:
|
||||||
|
v = item.get(name)
|
||||||
|
if type(v) not in (int, float) or not math.isfinite(v) or v < 0:
|
||||||
|
raise ValueError("Invalid experience time")
|
||||||
|
if type(item.get("count")) is not int or not 1 <= item["count"] <= 1000000:
|
||||||
|
raise ValueError("Invalid experience count")
|
||||||
|
if field == "attempts":
|
||||||
|
if not valid_xyz(item.get("origin")) or item.get("reason") not in FAILURES:
|
||||||
|
raise ValueError("Invalid attempt")
|
||||||
|
if item.get("status") not in {"unresolved", "revisited-successfully"}:
|
||||||
|
raise ValueError("Invalid attempt state")
|
||||||
|
if not isinstance(item.get("run_id"), str) or len(item["run_id"]) > 80:
|
||||||
|
raise ValueError("Invalid attempt source")
|
||||||
|
if (
|
||||||
|
not isinstance(item.get("observation_id"), str)
|
||||||
|
or len(item["observation_id"]) > 120
|
||||||
|
):
|
||||||
|
raise ValueError("Invalid attempt observation")
|
||||||
|
return document
|
||||||
|
|
||||||
|
|
||||||
|
class LocationExperience:
|
||||||
|
def __init__(self, source, document=None):
|
||||||
|
source_key(source)
|
||||||
|
self.source = source
|
||||||
|
self.revision = 0
|
||||||
|
self.previous = None
|
||||||
|
self.blockage = None
|
||||||
|
self.latched = None
|
||||||
|
doc = validate(document, source) if document is not None else {"visits": [], "attempts": []}
|
||||||
|
self.visits = {r["id"]: dict(r) for r in doc["visits"]}
|
||||||
|
self.attempts = {r["id"]: dict(r) for r in doc["attempts"]}
|
||||||
|
|
||||||
|
def document(self):
|
||||||
|
return dict(
|
||||||
|
schema_version=SCHEMA,
|
||||||
|
source=self.source,
|
||||||
|
authority="experience-only",
|
||||||
|
visits=list(self.visits.values()),
|
||||||
|
attempts=list(self.attempts.values()),
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def trim(items, limit):
|
||||||
|
while len(items) > limit:
|
||||||
|
del items[min(items, key=lambda key: items[key]["last_seen"])]
|
||||||
|
|
||||||
|
def observe(
|
||||||
|
self,
|
||||||
|
xyz,
|
||||||
|
goal,
|
||||||
|
navigation,
|
||||||
|
simulation_seconds,
|
||||||
|
now,
|
||||||
|
run_id,
|
||||||
|
observation_id,
|
||||||
|
execution_sha,
|
||||||
|
pose,
|
||||||
|
):
|
||||||
|
"""Require matched current navigation evidence; transport failures are not places."""
|
||||||
|
xyz = [float(v) for v in xyz]
|
||||||
|
if not valid_xyz(xyz):
|
||||||
|
return
|
||||||
|
moved = self.previous is not None and math.dist(xyz, self.previous) >= 0.2
|
||||||
|
if self.previous is None or moved:
|
||||||
|
old = self.previous
|
||||||
|
self.previous = xyz
|
||||||
|
key = ",".join(str(math.floor(v / 0.5)) for v in xyz[:2])
|
||||||
|
entry = self.visits.get(key)
|
||||||
|
self.visits[key] = dict(
|
||||||
|
id=key,
|
||||||
|
xyz=xyz,
|
||||||
|
first_seen=entry["first_seen"] if entry else now,
|
||||||
|
last_seen=now,
|
||||||
|
count=min(1000000, (entry["count"] if entry else 0) + 1),
|
||||||
|
)
|
||||||
|
self.trim(self.visits, MAX_VISITS)
|
||||||
|
self.revision += 1
|
||||||
|
if moved:
|
||||||
|
self.latched = None
|
||||||
|
for item in self.attempts.values():
|
||||||
|
if item["status"] != "unresolved" or math.dist(xyz, item["xyz"]) > 0.4:
|
||||||
|
continue
|
||||||
|
direction = [item["xyz"][i] - item["origin"][i] for i in range(2)]
|
||||||
|
if sum(direction[i] * (xyz[i] - old[i]) for i in range(2)) > 0:
|
||||||
|
item["status"] = "revisited-successfully"
|
||||||
|
item["resolved_at"] = now
|
||||||
|
self.revision += 1
|
||||||
|
failure = navigation.get("diagnostic", {}).get("failure")
|
||||||
|
expected = dict(
|
||||||
|
pose=list(pose),
|
||||||
|
simulation_time_seconds=simulation_seconds,
|
||||||
|
execution_inputs_sha256=execution_sha,
|
||||||
|
)
|
||||||
|
bound = navigation.get("route_observation", {}).get("observation") == expected
|
||||||
|
if goal is None and failure == "no-permitted-goal":
|
||||||
|
goal = xyz
|
||||||
|
if (
|
||||||
|
not bound
|
||||||
|
or failure not in FAILURES
|
||||||
|
or navigation.get("status") != "blocked"
|
||||||
|
or abs(navigation.get("speed_mps", 0)) + abs(navigation.get("yaw_rate_rps", 0)) > 1e-5
|
||||||
|
or goal is None
|
||||||
|
or not valid_xyz(list(goal))
|
||||||
|
):
|
||||||
|
self.blockage = None
|
||||||
|
return
|
||||||
|
delta = [goal[i] - xyz[i] for i in range(2)]
|
||||||
|
sector = round(math.atan2(delta[1], delta[0]) / (math.pi / 4)) % 8
|
||||||
|
key = ",".join(
|
||||||
|
map(str, [math.floor(xyz[0] / 0.5), math.floor(xyz[1] / 0.5), sector, failure])
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
self.blockage is None
|
||||||
|
or self.blockage[0] != key
|
||||||
|
or simulation_seconds < self.blockage[1]
|
||||||
|
):
|
||||||
|
self.blockage = (key, simulation_seconds)
|
||||||
|
return
|
||||||
|
if simulation_seconds - self.blockage[1] < 0.5 or self.latched == key:
|
||||||
|
return
|
||||||
|
self.latched = key
|
||||||
|
entry = self.attempts.get(key)
|
||||||
|
self.attempts[key] = dict(
|
||||||
|
id=key,
|
||||||
|
xyz=list(goal),
|
||||||
|
origin=xyz,
|
||||||
|
reason=failure,
|
||||||
|
status="unresolved",
|
||||||
|
first_seen=entry["first_seen"] if entry else now,
|
||||||
|
last_seen=now,
|
||||||
|
count=min(1000000, (entry["count"] if entry else 0) + 1),
|
||||||
|
run_id=run_id,
|
||||||
|
observation_id=observation_id,
|
||||||
|
)
|
||||||
|
self.trim(self.attempts, MAX_ATTEMPTS)
|
||||||
|
self.revision += 1
|
||||||
|
|
||||||
|
def costs(self, origin, candidates, now):
|
||||||
|
"""Only rank already-admissible recovery intentions from the same approach.
|
||||||
|
|
||||||
|
Temporary failures fade in ten minutes; records remain for inspection.
|
||||||
|
A cost never removes a candidate or bypasses current collision checks.
|
||||||
|
"""
|
||||||
|
result = []
|
||||||
|
nearby = [
|
||||||
|
a
|
||||||
|
for a in self.attempts.values()
|
||||||
|
if a["status"] == "unresolved"
|
||||||
|
and 0 <= now - a["last_seen"] < 600
|
||||||
|
and math.dist(origin[:2], a["origin"][:2]) <= 1.5
|
||||||
|
]
|
||||||
|
for point in candidates:
|
||||||
|
cost = 0.0
|
||||||
|
for a in nearby:
|
||||||
|
u = [point[i] - origin[i] for i in range(2)]
|
||||||
|
v = [a["xyz"][i] - a["origin"][i] for i in range(2)]
|
||||||
|
norm = math.hypot(*u) * math.hypot(*v)
|
||||||
|
if (
|
||||||
|
norm > 0
|
||||||
|
and sum(u[i] * v[i] for i in range(2)) / norm > 0.8
|
||||||
|
and math.dist(point[:2], a["xyz"][:2]) < 1.0
|
||||||
|
):
|
||||||
|
cost = max(cost, 2.0 * (1 - (now - a["last_seen"]) / 600))
|
||||||
|
result.append(cost)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def read(path, source=None):
|
||||||
|
if path.stat().st_size > 8 * 1024**2:
|
||||||
|
raise ValueError("Experience exceeds size limit")
|
||||||
|
return validate(json.loads(path.read_text()), source)
|
||||||
|
|
||||||
|
|
||||||
|
def save(path, document):
|
||||||
|
validate(document)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
data = json.dumps(document, allow_nan=False, separators=(",", ":"))
|
||||||
|
if len(data.encode()) > 8 * 1024**2:
|
||||||
|
raise ValueError("Experience exceeds size limit")
|
||||||
|
temp = path.with_suffix(".tmp")
|
||||||
|
temp.write_text(data)
|
||||||
|
temp.replace(path)
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
"""Derived infrastructure observations, bound to the exact simulation world."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from k1link.simulation.ai_polygon.worlds import write_json
|
||||||
|
|
||||||
|
CLASSES = {
|
||||||
|
"curb",
|
||||||
|
"bike_lane",
|
||||||
|
"crosswalk_area",
|
||||||
|
"curb_cut",
|
||||||
|
"parking",
|
||||||
|
"pedestrian_area",
|
||||||
|
"carriageway",
|
||||||
|
"service_lane",
|
||||||
|
"sidewalk",
|
||||||
|
"crosswalk_marking",
|
||||||
|
"road_marking",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_map(document: dict, world: dict) -> dict:
|
||||||
|
if not isinstance(document, dict):
|
||||||
|
raise ValueError("Infrastructure map must be an object")
|
||||||
|
if (
|
||||||
|
document.get("schema_version")
|
||||||
|
not in {"missioncore.urban-map/v1", "missioncore.urban-map/v2"}
|
||||||
|
or document.get("type") != "FeatureCollection"
|
||||||
|
):
|
||||||
|
raise ValueError("Unsupported infrastructure map")
|
||||||
|
if document.get("coordinate_system") != {
|
||||||
|
"frame": "scene-local",
|
||||||
|
"units": "metres",
|
||||||
|
"up": "Z",
|
||||||
|
"georeferenced": False,
|
||||||
|
}:
|
||||||
|
raise ValueError("Infrastructure map coordinate frame mismatch")
|
||||||
|
source = document.get("source", {})
|
||||||
|
if not isinstance(source, dict):
|
||||||
|
raise ValueError("Invalid infrastructure source")
|
||||||
|
if source.get("world_sha256") != world["sha256"] or source.get("collider_sha256") != world.get(
|
||||||
|
"collider_sha256"
|
||||||
|
):
|
||||||
|
raise ValueError("Infrastructure map belongs to a different scene revision")
|
||||||
|
coverage = document.get("coverage")
|
||||||
|
if not isinstance(coverage, dict):
|
||||||
|
raise ValueError("Missing infrastructure coverage")
|
||||||
|
cell, cells = coverage.get("cell_m"), coverage.get("accepted_cells")
|
||||||
|
if type(cell) not in (int, float) or not math.isfinite(cell) or not 0.02 <= cell <= 1:
|
||||||
|
raise ValueError("Invalid infrastructure sampling resolution")
|
||||||
|
if type(cells) is not int or not 0 <= cells <= 1_000_000:
|
||||||
|
raise ValueError("Invalid infrastructure coverage count")
|
||||||
|
features = document.get("features")
|
||||||
|
if not isinstance(features, list) or len(features) > 20000:
|
||||||
|
raise ValueError("Invalid infrastructure feature count")
|
||||||
|
vertices = 0
|
||||||
|
identifiers = set()
|
||||||
|
for feature in features:
|
||||||
|
if not isinstance(feature, dict) or feature.get("type") != "Feature":
|
||||||
|
raise ValueError("Invalid infrastructure feature")
|
||||||
|
prop, geo = feature.get("properties", {}), feature.get("geometry", {})
|
||||||
|
if not isinstance(prop, dict) or not isinstance(geo, dict):
|
||||||
|
raise ValueError("Invalid infrastructure feature")
|
||||||
|
if (
|
||||||
|
not isinstance(prop.get("class"), str)
|
||||||
|
or prop.get("class") not in CLASSES
|
||||||
|
or prop.get("authority") != "observation-only"
|
||||||
|
or prop.get("route_permission") != "unassigned"
|
||||||
|
):
|
||||||
|
raise ValueError("Infrastructure observations cannot grant route permissions")
|
||||||
|
vector = document["schema_version"] == "missioncore.urban-map/v2"
|
||||||
|
if vector:
|
||||||
|
identifier = feature.get("id")
|
||||||
|
score = prop.get("confidence")
|
||||||
|
if (
|
||||||
|
not isinstance(identifier, str)
|
||||||
|
or not re.fullmatch("[a-zA-Z0-9_-]{1,80}", identifier)
|
||||||
|
or identifier in identifiers
|
||||||
|
):
|
||||||
|
raise ValueError("Invalid or duplicate infrastructure identity")
|
||||||
|
identifiers.add(identifier)
|
||||||
|
if type(score) not in (int, float) or not math.isfinite(score) or not 0 <= score <= 1:
|
||||||
|
raise ValueError("Invalid infrastructure confidence")
|
||||||
|
if prop.get("review_status") not in {"unreviewed", "accepted", "rejected"}:
|
||||||
|
raise ValueError("Invalid infrastructure review state")
|
||||||
|
kind, coordinates = geo.get("type"), geo.get("coordinates")
|
||||||
|
if (
|
||||||
|
kind not in ({"Polygon", "LineString"} if vector else {"Polygon"})
|
||||||
|
or not isinstance(coordinates, list)
|
||||||
|
or not coordinates
|
||||||
|
):
|
||||||
|
raise ValueError("Invalid infrastructure geometry")
|
||||||
|
paths = coordinates if kind == "Polygon" else [coordinates]
|
||||||
|
for ring in paths:
|
||||||
|
if not isinstance(ring, list) or len(ring) < (4 if kind == "Polygon" else 2):
|
||||||
|
raise ValueError("Invalid infrastructure path")
|
||||||
|
if kind == "Polygon" and ring[0] != ring[-1]:
|
||||||
|
raise ValueError("Infrastructure ring must be closed")
|
||||||
|
vertices += len(ring)
|
||||||
|
for point in ring:
|
||||||
|
if (
|
||||||
|
not isinstance(point, list)
|
||||||
|
or len(point) != 3
|
||||||
|
or any(
|
||||||
|
type(v) not in (int, float) or not math.isfinite(v) or abs(v) > 1e6
|
||||||
|
for v in point
|
||||||
|
)
|
||||||
|
):
|
||||||
|
raise ValueError("Invalid infrastructure XYZ")
|
||||||
|
if vertices > 300000:
|
||||||
|
raise ValueError("Infrastructure map exceeds vertex limit")
|
||||||
|
return document
|
||||||
|
|
||||||
|
|
||||||
|
class UrbanMapStore:
|
||||||
|
def __init__(self, data_dir: Path):
|
||||||
|
self.root = data_dir / "ai-polygon" / "urban-maps"
|
||||||
|
|
||||||
|
def directory(self, world):
|
||||||
|
key = world["sha256"]
|
||||||
|
if not re.fullmatch("[0-9a-f]{64}", key):
|
||||||
|
raise ValueError("Invalid world identity")
|
||||||
|
return self.root / key
|
||||||
|
|
||||||
|
def save(self, world, document):
|
||||||
|
validate_map(document, world)
|
||||||
|
raw = json.dumps(document, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
|
||||||
|
if len(raw) > 12 * 1024**2:
|
||||||
|
raise ValueError("Infrastructure map exceeds size limit")
|
||||||
|
sha = hashlib.sha256(raw).hexdigest()
|
||||||
|
directory = self.directory(world)
|
||||||
|
directory.mkdir(parents=True, exist_ok=True)
|
||||||
|
write_json(directory / (sha + ".json"), document)
|
||||||
|
write_json(directory / "latest.json", {"sha256": sha})
|
||||||
|
return {"sha256": sha, "features": len(document["features"])}
|
||||||
|
|
||||||
|
def get(self, world):
|
||||||
|
directory = self.directory(world)
|
||||||
|
sha = json.loads((directory / "latest.json").read_text())["sha256"]
|
||||||
|
if not re.fullmatch("[0-9a-f]{64}", sha):
|
||||||
|
raise ValueError("Invalid infrastructure identity")
|
||||||
|
document = json.loads((directory / (sha + ".json")).read_text())
|
||||||
|
raw = json.dumps(document, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
|
||||||
|
if hashlib.sha256(raw).hexdigest() != sha:
|
||||||
|
raise ValueError("Infrastructure content changed")
|
||||||
|
return validate_map(document, world)
|
||||||
@@ -68,6 +68,33 @@ def build_ai_polygon_router(
|
|||||||
|
|
||||||
router.include_router(build_route_preparation_router(routes, worlds, editor, runs, invoke, authenticate))
|
router.include_router(build_route_preparation_router(routes, worlds, editor, runs, invoke, authenticate))
|
||||||
|
|
||||||
|
from k1link.web.spatial_experience_api import build_spatial_experience_router
|
||||||
|
router.include_router(build_spatial_experience_router(data_dir, worlds, invoke, authenticate))
|
||||||
|
|
||||||
|
from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore
|
||||||
|
urban_maps = UrbanMapStore(data_dir)
|
||||||
|
|
||||||
|
@router.get("/worlds/{world_id}/urban-map")
|
||||||
|
def urban_map(world_id: str):
|
||||||
|
return invoke(urban_maps.get, invoke(worlds.get, world_id))
|
||||||
|
|
||||||
|
@router.post("/worker/worlds/{world_id}/urban-map")
|
||||||
|
async def publish_urban_map(world_id: str, request: Request, authorization: str | None = Header(default=None)):
|
||||||
|
authenticate(authorization)
|
||||||
|
import json
|
||||||
|
body = bytearray()
|
||||||
|
async for chunk in request.stream():
|
||||||
|
body.extend(chunk)
|
||||||
|
if len(body) > 12 * 1024**2:
|
||||||
|
raise HTTPException(413, "Infrastructure map exceeds size limit")
|
||||||
|
try:
|
||||||
|
document = json.loads(body)
|
||||||
|
if not isinstance(document, dict):
|
||||||
|
raise ValueError("Infrastructure map must be an object")
|
||||||
|
return invoke(urban_maps.save, invoke(worlds.get, world_id), document)
|
||||||
|
except (ValueError, UnicodeDecodeError, TypeError, KeyError) as exc:
|
||||||
|
raise HTTPException(400, "Invalid infrastructure map") from exc
|
||||||
|
|
||||||
@router.get("/catalog")
|
@router.get("/catalog")
|
||||||
def catalog():
|
def catalog():
|
||||||
runtime = runs.status()
|
runtime = runs.status()
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Authenticated worker summaries, separate from live operator telemetry."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, HTTPException, Request
|
||||||
|
|
||||||
|
from k1link.simulation.ai_polygon.spatial_experience import read, save, validate
|
||||||
|
from k1link.simulation.ai_polygon.worlds import write_json
|
||||||
|
|
||||||
|
|
||||||
|
def build_spatial_experience_router(data_dir, worlds, invoke, authenticate):
|
||||||
|
router = APIRouter()
|
||||||
|
root = data_dir / "ai-polygon" / "spatial-experience"
|
||||||
|
|
||||||
|
def bound(world_id, document):
|
||||||
|
world = worlds.get(world_id)
|
||||||
|
validate(document)
|
||||||
|
source = document["source"]
|
||||||
|
if source["world_sha256"] != world["sha256"] or source["collider_sha256"] != world.get(
|
||||||
|
"collider_sha256"
|
||||||
|
):
|
||||||
|
raise ValueError("Experience belongs to another scene revision")
|
||||||
|
return root / world["sha256"]
|
||||||
|
|
||||||
|
def get(world_id):
|
||||||
|
world = worlds.get(world_id)
|
||||||
|
directory = root / world["sha256"]
|
||||||
|
key = json.loads((directory / "latest.json").read_text())["robot_sha256"]
|
||||||
|
if not re.fullmatch("[a-f0-9]{64}", key):
|
||||||
|
raise ValueError("Invalid robot revision")
|
||||||
|
document = read(directory / (key + ".json"))
|
||||||
|
bound(world_id, document)
|
||||||
|
return document
|
||||||
|
|
||||||
|
def store(world_id, document):
|
||||||
|
directory = bound(world_id, document)
|
||||||
|
key = document["source"]["robot_sha256"]
|
||||||
|
save(directory / (key + ".json"), document)
|
||||||
|
write_json(directory / "latest.json", {"robot_sha256": key})
|
||||||
|
return {"visits": len(document["visits"]), "attempts": len(document["attempts"])}
|
||||||
|
|
||||||
|
@router.get("/worlds/{world_id}/spatial-experience")
|
||||||
|
def experience(world_id: str):
|
||||||
|
return invoke(get, world_id)
|
||||||
|
|
||||||
|
@router.post("/worker/worlds/{world_id}/spatial-experience")
|
||||||
|
async def publish(
|
||||||
|
world_id: str, request: Request, authorization: str | None = Header(default=None)
|
||||||
|
):
|
||||||
|
authenticate(authorization)
|
||||||
|
body = bytearray()
|
||||||
|
async for chunk in request.stream():
|
||||||
|
body.extend(chunk)
|
||||||
|
if len(body) > 8 * 1024**2:
|
||||||
|
raise HTTPException(413, "Experience exceeds size limit")
|
||||||
|
try:
|
||||||
|
return invoke(store, world_id, json.loads(body))
|
||||||
|
except (UnicodeDecodeError, json.JSONDecodeError, TypeError, KeyError) as exc:
|
||||||
|
raise HTTPException(400, "Invalid location experience") from exc
|
||||||
|
|
||||||
|
return router
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
import copy
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from k1link.simulation.ai_polygon.spatial_experience import LocationExperience, read, save, validate
|
||||||
|
|
||||||
|
SOURCE = dict(world_sha256="a" * 64, collider_sha256="b" * 64, robot_sha256="c" * 64)
|
||||||
|
POSE = [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
|
||||||
|
|
||||||
|
|
||||||
|
def feed(memory, t, xyz=(0.0, 0.0, 0.0), goal=(1.0, 0.0, 0.0), failure="footprint", bound=True):
|
||||||
|
pose = [*xyz[:2], xyz[2] + 1, 0.0, 0.0, 0.0, 1.0]
|
||||||
|
result = dict(
|
||||||
|
status="blocked",
|
||||||
|
speed_mps=0.0,
|
||||||
|
yaw_rate_rps=0.0,
|
||||||
|
diagnostic={"failure": failure},
|
||||||
|
route_observation={
|
||||||
|
"observation": dict(
|
||||||
|
pose=pose, simulation_time_seconds=t, execution_inputs_sha256="exec"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if bound
|
||||||
|
else {},
|
||||||
|
)
|
||||||
|
memory.observe(
|
||||||
|
list(xyz), list(goal), result, t, 100 + t, "airun-test", "packet-" + str(t), "exec", pose
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_restart_revisit_and_directions(tmp_path):
|
||||||
|
m = LocationExperience(SOURCE)
|
||||||
|
feed(m, 0)
|
||||||
|
feed(m, 0.6)
|
||||||
|
feed(m, 0.7)
|
||||||
|
assert len(m.attempts) == 1 and next(iter(m.attempts.values()))["count"] == 1
|
||||||
|
path = tmp_path / "memory.json"
|
||||||
|
save(path, m.document())
|
||||||
|
n = LocationExperience(SOURCE, read(path, SOURCE))
|
||||||
|
assert n.costs([0, 0], [[1, 0], [0, 1], [-1, 0]], 102) == pytest.approx([1.995333333, 0, 0])
|
||||||
|
assert n.costs([2, 0], [[1, 0]], 102) == [0] # opposite approach
|
||||||
|
assert n.costs([0, 0], [[1, 0]], 800) == [0] # evidence retained; temporary cost expires
|
||||||
|
n.observe([0.5, 0, 0], None, {}, 2, 103, "r", "o", "exec", POSE)
|
||||||
|
n.observe([1, 0, 0], None, {}, 3, 104, "r", "o", "exec", POSE)
|
||||||
|
assert next(iter(n.attempts.values()))["status"] == "revisited-successfully"
|
||||||
|
assert n.costs([0, 0], [[1, 0]], 105) == [0]
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
read(path, {**SOURCE, "collider_sha256": "d" * 64})
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"failure,bound", [("timeout", True), ("footprint", False), ("stale-range", True)]
|
||||||
|
)
|
||||||
|
def test_no_invented_obstacles(failure, bound):
|
||||||
|
m = LocationExperience(SOURCE)
|
||||||
|
feed(m, 0, failure=failure, bound=bound)
|
||||||
|
feed(m, 10, failure=failure, bound=bound)
|
||||||
|
assert not m.attempts
|
||||||
|
|
||||||
|
|
||||||
|
def test_pose_teleport_does_not_connect_cells_or_mark_passed():
|
||||||
|
m = LocationExperience(SOURCE)
|
||||||
|
feed(m, 0)
|
||||||
|
feed(m, 1)
|
||||||
|
feed(m, 2, xyz=(20.0, 0.0, 0.0))
|
||||||
|
assert len(m.visits) == 2 and next(iter(m.attempts.values()))["status"] == "unresolved"
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_summaries():
|
||||||
|
m = LocationExperience(SOURCE)
|
||||||
|
feed(m, 0)
|
||||||
|
doc = m.document()
|
||||||
|
for mutation in [
|
||||||
|
lambda d: d["visits"][0].update(xyz=[0, 0, float("nan")]),
|
||||||
|
lambda d: d.update(authority="motion"),
|
||||||
|
lambda d: d["visits"][0].update(count=-1),
|
||||||
|
lambda d: d["source"].update(world_sha256="../escape"),
|
||||||
|
lambda d: d.update(source=None),
|
||||||
|
]:
|
||||||
|
bad = copy.deepcopy(doc)
|
||||||
|
mutation(bad)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
validate(bad)
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_auth_revision_and_reload(tmp_path):
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from test_ai_polygon import make_world
|
||||||
|
|
||||||
|
from k1link.simulation.ai_polygon.runs import RunStore
|
||||||
|
from k1link.simulation.ai_polygon.worlds import WorldStore
|
||||||
|
from k1link.web.ai_polygon_api import build_ai_polygon_router
|
||||||
|
|
||||||
|
worlds = WorldStore(tmp_path)
|
||||||
|
world = make_world(worlds)
|
||||||
|
runs = RunStore(worlds)
|
||||||
|
world["collider_sha256"] = "b" * 64
|
||||||
|
from k1link.simulation.ai_polygon.worlds import write_json
|
||||||
|
|
||||||
|
write_json(worlds.directory(world["world_id"]) / "world.json", world)
|
||||||
|
source = {
|
||||||
|
**SOURCE,
|
||||||
|
"world_sha256": world["sha256"],
|
||||||
|
"collider_sha256": world["collider_sha256"],
|
||||||
|
}
|
||||||
|
memory = LocationExperience(source)
|
||||||
|
feed(memory, 0)
|
||||||
|
feed(memory, 1)
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(build_ai_polygon_router(tmp_path))
|
||||||
|
client = TestClient(app)
|
||||||
|
suffix = "/worlds/" + world["world_id"] + "/spatial-experience"
|
||||||
|
write = "/api/v1/ai-polygon/worker" + suffix
|
||||||
|
url = "/api/v1/ai-polygon" + suffix
|
||||||
|
assert client.get(url).status_code == 404
|
||||||
|
assert client.post(write, json=memory.document()).status_code == 401
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
write, json=memory.document(), headers={"Authorization": "Bearer " + runs.token}
|
||||||
|
).status_code
|
||||||
|
== 200
|
||||||
|
)
|
||||||
|
assert client.get(url).json() == memory.document()
|
||||||
|
wrong = memory.document()
|
||||||
|
wrong["source"] = {**source, "collider_sha256": "d" * 64}
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
write, json=wrong, headers={"Authorization": "Bearer " + runs.token}
|
||||||
|
).status_code
|
||||||
|
== 400
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_surface_uncertainty_is_a_note_without_geometry_permission():
|
||||||
|
m = LocationExperience(SOURCE)
|
||||||
|
feed(m, 0, goal=(0.0, 0.0, 0.0), failure="no-permitted-goal")
|
||||||
|
feed(m, 1, goal=(0.0, 0.0, 0.0), failure="no-permitted-goal")
|
||||||
|
assert len(m.attempts) == 1
|
||||||
|
assert m.costs([0, 0], [[1, 0], [0, 1]], 102) == [0, 0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_worker_adapter_survives_process_restart(tmp_path, monkeypatch):
|
||||||
|
import importlib
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
|
||||||
|
adapter = importlib.import_module("experience_adapter").ExperienceAdapter
|
||||||
|
run = dict(
|
||||||
|
run_id="airun-evidence",
|
||||||
|
world=dict(sha256="a" * 64, collider_sha256="b" * 64),
|
||||||
|
_spatial_experience_root=str(tmp_path / "persistent"),
|
||||||
|
)
|
||||||
|
inputs = dict(
|
||||||
|
sha256="exec", robot=dict(sha256="c" * 64, geometry=dict(body_contact_height_m=1))
|
||||||
|
)
|
||||||
|
camera = tmp_path / "run" / "camera"
|
||||||
|
camera.mkdir(parents=True)
|
||||||
|
a = adapter(run, inputs, camera)
|
||||||
|
feed(a.memory, 0)
|
||||||
|
feed(a.memory, 1)
|
||||||
|
a.close()
|
||||||
|
b = adapter(run, inputs, camera)
|
||||||
|
assert b.memory.document() == a.memory.document()
|
||||||
|
b.close()
|
||||||
|
assert read(camera.parent / "spatial-experience.json") == a.memory.document()
|
||||||
|
|
||||||
|
|
||||||
|
def test_final_worker_sync_includes_latest_flushed_summary(tmp_path, monkeypatch):
|
||||||
|
import importlib
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
|
||||||
|
sync = importlib.import_module("realtime_worker").publish_experience
|
||||||
|
m = LocationExperience(SOURCE)
|
||||||
|
feed(m, 0)
|
||||||
|
feed(m, 1)
|
||||||
|
save(tmp_path / "spatial-experience.json", m.document())
|
||||||
|
sent = []
|
||||||
|
|
||||||
|
class Client:
|
||||||
|
def request(self, path, body):
|
||||||
|
sent.append((path, body))
|
||||||
|
|
||||||
|
sync(Client(), tmp_path, "aiworld-test")
|
||||||
|
assert sent == [("/worker/worlds/aiworld-test/spatial-experience", m.document())]
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
"""Infrastructure observations cannot silently migrate between scene revisions."""
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from test_ai_polygon import make_world
|
||||||
|
|
||||||
|
from k1link.simulation.ai_polygon.runs import RunStore
|
||||||
|
from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore, validate_map
|
||||||
|
from k1link.simulation.ai_polygon.worlds import WorldStore
|
||||||
|
from k1link.web.ai_polygon_api import build_ai_polygon_router
|
||||||
|
|
||||||
|
|
||||||
|
def document(world):
|
||||||
|
return {
|
||||||
|
"schema_version": "missioncore.urban-map/v1",
|
||||||
|
"type": "FeatureCollection",
|
||||||
|
"coordinate_system": {
|
||||||
|
"frame": "scene-local",
|
||||||
|
"units": "metres",
|
||||||
|
"up": "Z",
|
||||||
|
"georeferenced": False,
|
||||||
|
},
|
||||||
|
"source": {
|
||||||
|
"world_sha256": world["sha256"],
|
||||||
|
"collider_sha256": world.get("collider_sha256"),
|
||||||
|
},
|
||||||
|
"coverage": {"cell_m": 0.1, "accepted_cells": 100},
|
||||||
|
"features": [
|
||||||
|
{
|
||||||
|
"type": "Feature",
|
||||||
|
"properties": {
|
||||||
|
"class": "sidewalk",
|
||||||
|
"authority": "observation-only",
|
||||||
|
"route_permission": "unassigned",
|
||||||
|
},
|
||||||
|
"geometry": {
|
||||||
|
"type": "Polygon",
|
||||||
|
"coordinates": [[[0, 0, 2], [1, 0, 2], [1, 1, 2], [0, 0, 2]]],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_revision_binding_and_integrity(tmp_path):
|
||||||
|
world = {"sha256": "a" * 64, "collider_sha256": "b" * 64}
|
||||||
|
data = document(world)
|
||||||
|
store = UrbanMapStore(tmp_path)
|
||||||
|
receipt = store.save(world, data)
|
||||||
|
assert store.get(world) == data
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
validate_map(data, {**world, "collider_sha256": "c" * 64})
|
||||||
|
with pytest.raises(FileNotFoundError):
|
||||||
|
store.get({**world, "sha256": "c" * 64})
|
||||||
|
path = store.directory(world) / (receipt["sha256"] + ".json")
|
||||||
|
data["features"] = []
|
||||||
|
path.write_text(json.dumps(data))
|
||||||
|
with pytest.raises(ValueError, match="changed"):
|
||||||
|
store.get(world)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"bad",
|
||||||
|
[
|
||||||
|
None,
|
||||||
|
{},
|
||||||
|
{"properties": None},
|
||||||
|
{"type": "Feature", "properties": {"class": []}},
|
||||||
|
{
|
||||||
|
"type": "Feature",
|
||||||
|
"properties": {
|
||||||
|
"class": "sidewalk",
|
||||||
|
"authority": "observation-only",
|
||||||
|
"route_permission": "unassigned",
|
||||||
|
},
|
||||||
|
"geometry": {"type": "Polygon", "coordinates": [None]},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_malformed_features_rejected(bad):
|
||||||
|
world = {"sha256": "a" * 64}
|
||||||
|
data = document(world)
|
||||||
|
data["features"] = [bad]
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
validate_map(data, world)
|
||||||
|
|
||||||
|
|
||||||
|
def test_permission_and_geometry_rejected():
|
||||||
|
world = {"sha256": "a" * 64}
|
||||||
|
data = document(world)
|
||||||
|
for mutate in [
|
||||||
|
lambda d: d["features"][0]["properties"].update(route_permission="allowed"),
|
||||||
|
lambda d: d["features"][0]["geometry"].update(
|
||||||
|
coordinates=[[[0, 0, 0], [1, 0, 0], [1, 1, 0]]]
|
||||||
|
),
|
||||||
|
lambda d: d["features"][0]["geometry"].update(coordinates=[[[0, 0, float("nan")]]] * 4),
|
||||||
|
]:
|
||||||
|
value = copy.deepcopy(data)
|
||||||
|
mutate(value)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
validate_map(value, world)
|
||||||
|
|
||||||
|
|
||||||
|
def test_worker_api_auth_and_publish(tmp_path):
|
||||||
|
worlds = WorldStore(tmp_path)
|
||||||
|
world = make_world(worlds)
|
||||||
|
runs = RunStore(worlds)
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(build_ai_polygon_router(tmp_path))
|
||||||
|
client = TestClient(app)
|
||||||
|
suffix = f"/worlds/{world['world_id']}/urban-map"
|
||||||
|
worker = "/api/v1/ai-polygon/worker" + suffix
|
||||||
|
read = "/api/v1/ai-polygon" + suffix
|
||||||
|
assert client.get(read).status_code == 404
|
||||||
|
assert client.post(worker, json=document(world)).status_code == 401
|
||||||
|
headers = {"Authorization": f"Bearer {runs.token}"}
|
||||||
|
assert client.post(worker, json=[], headers=headers).status_code == 400
|
||||||
|
assert client.post(worker, json=document(world), headers=headers).status_code == 200
|
||||||
|
assert client.get(read).json() == document(world)
|
||||||
|
|
||||||
|
|
||||||
|
def test_vector_lines_roundtrip_and_admission(tmp_path):
|
||||||
|
world = {"sha256": "a" * 64, "collider_sha256": "b" * 64}
|
||||||
|
data = document(world)
|
||||||
|
data["schema_version"] = "missioncore.urban-map/v2"
|
||||||
|
f = data["features"][0]
|
||||||
|
f["id"] = "curb-1"
|
||||||
|
f["properties"].update(confidence=0.8, review_status="unreviewed", **{"class": "curb"})
|
||||||
|
f["geometry"] = {"type": "LineString", "coordinates": [[1, 2, 3], [2, 3, 4]]}
|
||||||
|
store = UrbanMapStore(tmp_path)
|
||||||
|
store.save(world, data)
|
||||||
|
assert store.get(world) == data
|
||||||
|
for change in [
|
||||||
|
lambda d: d["features"].append(copy.deepcopy(d["features"][0])),
|
||||||
|
lambda d: d["features"][0]["properties"].update(confidence=float("nan")),
|
||||||
|
lambda d: d["features"][0]["geometry"].update(coordinates=[[1, 2, 3]]),
|
||||||
|
lambda d: d["features"][0]["geometry"].update(
|
||||||
|
coordinates=[[1, 2, 3], [1, 2, float("inf")]]
|
||||||
|
),
|
||||||
|
]:
|
||||||
|
bad = copy.deepcopy(data)
|
||||||
|
change(bad)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
validate_map(bad, world)
|
||||||
Reference in New Issue
Block a user