feat(semantics): version scene edits and refine paint geometry
This commit is contained in:
@@ -13,7 +13,7 @@ import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiE
|
||||
import type { AiWaypoint, ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
import { localScene } from "./localScene";
|
||||
import { EditorTerrain } from "./EditorTerrain";
|
||||
import { EditorCamera } from "./EditorCamera";
|
||||
import { EditorCamera, type NavigationOwner } from "./EditorCamera";
|
||||
import { EditorSurfacePicker } from "./EditorSurfacePicker";
|
||||
import { dragWaypoint, type WaypointAxis } from "../../core/simulation/waypointDrag";
|
||||
|
||||
@@ -240,8 +240,8 @@ export class AiEditorRuntime {
|
||||
}
|
||||
this.dirty = true;
|
||||
}
|
||||
setNavigation(enabled: boolean) {
|
||||
this.controls.setNavigation(enabled);
|
||||
setNavigation(enabled: boolean, owner: NavigationOwner = "planner") {
|
||||
this.controls.setNavigation(enabled, owner);
|
||||
}
|
||||
setSemanticSelection(active:boolean) {this.controls.semanticSelection=active;}
|
||||
setAddMode(add: boolean) { this.controls.setAddMode(add); }
|
||||
|
||||
@@ -5,6 +5,8 @@ import { navigationDepth, orbitCamera, panCamera } from "../../core/simulation/e
|
||||
import { PerspectiveCamera, Vector3 } from "three";
|
||||
import {cameraRay,isOrthographic,switchProjection,type EditorProjection,type ProjectionCamera} from "../../core/simulation/editorProjection";
|
||||
|
||||
export type NavigationOwner = "planner" | "semantic";
|
||||
|
||||
const KEYS = new Set(["KeyW","KeyA","KeyS","KeyD","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","KeyQ","KeyE","ShiftLeft","ShiftRight"]);
|
||||
/** Input/math only: PlayCanvas remains the sole renderer. */
|
||||
export class EditorCamera {
|
||||
@@ -14,7 +16,8 @@ export class EditorCamera {
|
||||
navigation=DEFAULT_PLANNER_PREFERENCES.navigation;
|
||||
get rotationCenter(){return this.gesture&&!this.gesture.pan&&!this.gesture.pending?this.gesture.anchor:null;}
|
||||
private keys = new Set<string>();
|
||||
private enabled=true;
|
||||
private navigationBlocks=new Set<NavigationOwner>();
|
||||
private get enabled(){return this.navigationBlocks.size===0;}
|
||||
private topPoints:number[][]|null=null;
|
||||
private addMode=false;
|
||||
semanticSelection=false;
|
||||
@@ -153,7 +156,10 @@ export class EditorCamera {
|
||||
}
|
||||
setAddMode(add:boolean){this.cancelGesture();this.addMode=add;}
|
||||
invalidateSurface(){this.cancelGesture();this.lastAnchor=null;}
|
||||
setNavigation(enabled:boolean){this.enabled=enabled;if(!enabled)this.clear();}
|
||||
setNavigation(enabled:boolean,owner:NavigationOwner="planner"){
|
||||
if(enabled)this.navigationBlocks.delete(owner);else this.navigationBlocks.add(owner);
|
||||
if(!this.enabled)this.clear();
|
||||
}
|
||||
update(dt:number){
|
||||
if(!this.enabled||!this.keys.size)return;
|
||||
this.cancelGesture();
|
||||
|
||||
@@ -15,7 +15,7 @@ export function PlannerCameraTools({runtime,viewport,disabled}:{runtime:AiEditor
|
||||
return <>
|
||||
<Dropdown placement="bottom-end" width={220} trigger={({toggle,setTriggerRef,open})=><IconButton ref={setTriggerRef}
|
||||
label={`Проекция: ${projection==="orthographic"?"ортографическая":"перспективная"}`} title="Выбрать проекцию" disabled={disabled} aria-expanded={open} onClick={toggle}><Icon name={projection}/></IconButton>}>
|
||||
{({close})=><div className="semantic-tools__menu">{([['orthographic','Ортографическая'],['perspective','Перспективная']] as const).map(([mode,label])=><Button key={mode} width="full" variant={projection===mode?"primary":"secondary"} tone="neutral" aria-pressed={projection===mode} onClick={()=>{updateLayout({projection:mode});close();}}>{label}</Button>)}</div>}
|
||||
{({close})=><div className="semantic-tools__menu">{([['orthographic','Ортографическая'],['perspective','Перспективная']] as const).map(([mode,label])=><Button key={mode} width="full" variant={projection===mode?"primary":"secondary"} tone="neutral" aria-pressed={projection===mode} onClick={()=>{updateLayout({projection:mode});close();}}>{label}</Button>)}<Button width="full" onClick={()=>{runtime.top();close();}}>Показать сцену целиком</Button></div>}
|
||||
</Dropdown>
|
||||
{createPortal(<div className="ai-local-editor__cube"><NavigationCube quaternion={quaternion} {...preferences.cube} disabled={disabled} onSelect={direction=>runtime.view(direction)}/></div>,viewport)}
|
||||
</>;
|
||||
|
||||
@@ -11,7 +11,8 @@ export function SemanticEditOverlay(props:SemanticOverlayProps) {
|
||||
const {runtime,viewport,map,original,layers,selected}=props;
|
||||
const [,redraw]=useState(0);
|
||||
const {hover,ghostMap,marquee,brush}=useSemanticGestures(props);
|
||||
useEffect(()=>{runtime.watchSemantic(()=>redraw(n=>n+1));return()=>runtime.watchSemantic(null);},[runtime]);
|
||||
useEffect(()=>{if(!props.editing&&!original)return;runtime.watchSemantic(()=>redraw(n=>n+1));return()=>runtime.watchSemantic(null);},[runtime,props.editing,original]);
|
||||
if(!props.editing&&!original)return null;
|
||||
const rect=viewport.querySelector("canvas")?.getBoundingClientRect();if(!rect)return null;
|
||||
const project=(v:number[])=>{const q=runtime.projectSemantic(v);return q?[q[0]*rect.width,q[1]*rect.height]:null;};
|
||||
const line=(path:number[][])=>{const p=path.map(project);return p.map((v,i)=>v?`${i&&p[i-1]?"L":"M"}${v[0]},${v[1]}`:"").join(" ");};
|
||||
@@ -20,7 +21,7 @@ export function SemanticEditOverlay(props:SemanticOverlayProps) {
|
||||
const point=semanticAnchor(props),g=point?runtime.semanticGizmo(point):null,base=point?project(point):null;
|
||||
const featureColor=(id:string)=>`rgb(${(URBAN_COLORS[id]??URBAN_COLORS.road_boundary).join(",")})`;
|
||||
const color=featureColor(chosen[0]?.properties.class??layers.at(-1)??"road_boundary");
|
||||
const visible=map.features.filter(f=>layers.includes(f.properties.class as typeof layers[number])&&f.properties.review_status!=="rejected");
|
||||
const visible=map.features.filter(f=>(chosen.includes(f)||highlight.includes(f))&&layers.includes(f.properties.class as typeof layers[number])&&f.properties.review_status!=="rejected");
|
||||
const node=selected&&!selected.object&&chosen[0]&&!isRigidMarking(chosen[0])?knots(chosen[0],selected.path)[selected.index]:null;
|
||||
const handleScale=node?curveControlScale(knots(chosen[0],selected!.path),selected!.index,chosen[0].geometry.type==="Polygon",project):1;
|
||||
return createPortal(<svg className="ai-local-editor__markers" width="100%" height="100%" aria-label="Редактор контуров">
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import {useSimulationLayout} from "./useSimulationLayout";
|
||||
import {useSemanticDocument} from "./useSemanticDocument";
|
||||
import {useEffect,useRef,useState} from "react";
|
||||
import {createPortal} from "react-dom";
|
||||
import {Button,Icon,IconButton,SegmentedControl,ToastStack,Window} from "@nodedc/ui-react";
|
||||
import {Button,FieldFrame,Icon,IconButton,Select,SegmentedControl,ToastStack,Window} from "@nodedc/ui-react";
|
||||
import {URBAN_LABELS,availableUrbanClasses,visibleUrbanMap,type UrbanMap,type UrbanClassId} from "../../core/simulation/urbanMap";
|
||||
import {isRigidMarking,isEditableMarking,semanticMembers,commitSemantic,redoSemantic,semanticDraft,semanticOperation,semanticRequest,undoSemantic,
|
||||
type SemanticDraft,type SemanticOperation,type SemanticRevision,type Vertex} from "../../core/simulation/semanticEdits";
|
||||
import {isRigidMarking,isEditableMarking,semanticMembers,commitSemantic,redoSemantic,semanticOperation,undoSemantic,
|
||||
type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
|
||||
import type {AiEditorRuntime} from "./AiEditorRuntime";
|
||||
import {SemanticEditOverlay,type SemanticChoice} from "./SemanticEditOverlay";
|
||||
import {SemanticTools} from "./SemanticTools";
|
||||
@@ -14,12 +15,11 @@ import {duplicateIndex,type SemanticAxis} from "../../core/simulation/semanticVe
|
||||
export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,source,headerHost}:{
|
||||
headerHost:HTMLElement|null;worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;active:boolean;busy:boolean;source:UrbanMap;
|
||||
}) {
|
||||
const [revision,setRevision]=useState<SemanticRevision|null>(null);
|
||||
const [draft,setDraft]=useState<SemanticDraft|null>(null);
|
||||
const [error,setError]=useState<string|null>(null),[saving,setSaving]=useState(false);
|
||||
const [loading,setLoading]=useState(true);
|
||||
const [editing,setEditing]=useState(true);
|
||||
const [error,setError]=useState<string|null>(null);
|
||||
const [confirmDiscard,setConfirmDiscard]=useState(false);
|
||||
const [layout,updateLayout]=useSimulationLayout();
|
||||
const document=useSemanticDocument(worldId,worldSha,active,source,layout.semanticVersion,setError);
|
||||
const {revision,draft,setDraft,saving,loading,editing,setEditing,save}=document;
|
||||
const visible=layout.visible,setVisible=(v:typeof visible|((prior:typeof visible)=>typeof visible))=>updateLayout({visible:typeof v==="function"?v(visible):v});
|
||||
const [selection,setSelection]=useState<Vertex[]>([]),[wholeContour,setWholeContour]=useState(false);
|
||||
const selectVertices=(vertices:Vertex[],whole=false)=>{setSelection(vertices);setWholeContour(whole);};
|
||||
@@ -32,28 +32,18 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
|
||||
const [tool,setTool]=useState<SemanticTool>("select");
|
||||
const [template,setTemplate]=useState<string|null>(null);
|
||||
const [preview,setPreview]=useState<SemanticOperation|null>(null);
|
||||
const attempt=useRef<{key:string;signature:string}|null>(null);
|
||||
const current=useRef({draft,revision});current.current={draft,revision};
|
||||
const accept=(value:SemanticRevision)=>{
|
||||
if(value.model.source.world_sha256!==worldSha||value.edited.source.world_sha256!==worldSha)
|
||||
throw new Error("Правки относятся к другой сцене.");
|
||||
setRevision(value);setDraft(semanticDraft(value.edited));attempt.current=null;setSelected(null);
|
||||
|
||||
};
|
||||
useEffect(()=>{
|
||||
if(!active||revision)return;
|
||||
const abort=new AbortController();
|
||||
setLoading(true);setError(null);
|
||||
void semanticRequest(worldId,undefined,abort.signal).then(accept)
|
||||
.catch(e=>{if(!abort.signal.aborted)setError(e.message);})
|
||||
.finally(()=>{if(!abort.signal.aborted)setLoading(false);});
|
||||
return()=>abort.abort();
|
||||
},[active,worldId,worldSha,revision]);
|
||||
useEffect(()=>{if(active){setEditing(true);}},[active]);
|
||||
setSelected(null);setPreview(null);setTool("select");setTemplate(null);
|
||||
if(!revision)return;
|
||||
const available=availableUrbanClasses(revision.edited);
|
||||
if(layers.length&&available.length&&!layers.some(layer=>available.includes(layer)))setLayers(available);
|
||||
if(revision.revision)updateLayout({semanticVersion:"manual"});
|
||||
},[revision]);
|
||||
useEffect(()=>{runtime.setSemanticSelection(active&&editing);viewport.dataset.semanticEditing=String(active&&editing);
|
||||
return()=>{runtime.setSemanticSelection(false);delete viewport.dataset.semanticEditing;};},[runtime,viewport,active,editing]);
|
||||
const operate=(op:SemanticOperation)=>{
|
||||
if(busy||saving)return;
|
||||
if(busy||saving||loading||!editing||!document.canEdit||!current.current.draft)return;
|
||||
try{const prior=current.current.draft!,next=commitSemantic(prior,op);setDraft(next);setError(null);
|
||||
if(op.kind==="duplicate_vertex"&&next!==prior)setSelected({feature_id:op.feature_id,path:op.path,index:duplicateIndex(op.index,prior.map.features.find(f=>f.id===op.feature_id)!.geometry.type==="Polygon",op.side)});
|
||||
if(op.kind==="duplicate_marking"&&next!==prior)setSelected({feature_id:op.new_feature_id,path:0,index:0,object:true});
|
||||
@@ -79,7 +69,7 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
|
||||
if(!active)return;
|
||||
runtime.setAddMode(false);
|
||||
const keyboard=(e:KeyboardEvent)=>{
|
||||
if(!editing||busy||saving||preview||(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"]')||document.querySelector('[data-dropdown-lineage]'))return;
|
||||
if(!editing||busy||saving||loading||preview||(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"]')||window.document.querySelector('[data-dropdown-lineage]'))return;
|
||||
if((e.metaKey||e.ctrlKey)&&e.code==="KeyZ"){
|
||||
e.preventDefault();e.stopImmediatePropagation();setPreview(null);
|
||||
setDraft(s=>s?(e.shiftKey?redoSemantic(s):undoSemantic(s)):s);setSelected(null);
|
||||
@@ -91,24 +81,14 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
|
||||
e.preventDefault();e.stopImmediatePropagation();removeSelected();
|
||||
}
|
||||
};
|
||||
document.addEventListener("keydown",keyboard,true);
|
||||
return()=>document.removeEventListener("keydown",keyboard,true);
|
||||
},[active,editing,busy,saving,preview,selection,layers,viewport,runtime,display]);
|
||||
window.document.addEventListener("keydown",keyboard,true);
|
||||
return()=>window.document.removeEventListener("keydown",keyboard,true);
|
||||
},[active,editing,busy,saving,loading,preview,selection,layers,viewport,runtime,display]);
|
||||
useEffect(()=>{
|
||||
if(!draft?.operations.length)return;
|
||||
const warn=(e:BeforeUnloadEvent)=>{e.preventDefault();};
|
||||
window.addEventListener("beforeunload",warn);return()=>window.removeEventListener("beforeunload",warn);
|
||||
},[draft?.operations.length]);
|
||||
const save=async()=>{
|
||||
const s=current.current;if(!s.draft?.operations.length||!s.revision||saving)return;
|
||||
const body={expected_revision:s.revision.revision,model_sha256:s.revision.model_sha256,operations:s.draft.operations};
|
||||
const signature=JSON.stringify(body);
|
||||
if(attempt.current?.signature!==signature)attempt.current={signature,key:crypto.randomUUID()};
|
||||
setSaving(true);setError(null);
|
||||
try{accept(await semanticRequest(worldId,{...body,request_id:attempt.current.key}));}
|
||||
catch(e){setError((e as Error).message);}
|
||||
finally{setSaving(false);}
|
||||
};
|
||||
if(!active)return null;
|
||||
const classes=availableUrbanClasses(display);
|
||||
if(!classes.includes("road_marking"))classes.push("road_marking");
|
||||
@@ -119,29 +99,36 @@ export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,so
|
||||
const undo=()=>{setDraft(s=>s?undoSemantic(s):s);setSelected(null);};
|
||||
const redo=()=>{setDraft(s=>s?redoSemantic(s):s);setSelected(null);};
|
||||
const controls=<>
|
||||
{revision?<IconButton label={editing?"Завершить редактирование":"Редактировать разметку"} title={editing?"Завершить редактирование · Escape":"Редактировать разметку"} aria-pressed={editing}
|
||||
onClick={()=>{setEditing(v=>!v);setSelected(null);chooseTool("select");setVisible(v=>({...v,user:true}));}}><Icon name="edit"/></IconButton>:null}
|
||||
{document.options.length?<FieldFrame label="Версия разметки" labelPlacement="below" className="ai-polygon__semantic-version-field"><Select label="Версия разметки" value={document.selected} options={document.options.map(option=>({...option,label:option.value===document.selected&&document.dirty?`${option.label} · несохранённые правки`:option.label}))}
|
||||
disabled={loading||saving||document.dirty} onChange={v=>{document.select(v);updateLayout({semanticVersion:v.startsWith("manual:")?"manual":v as "raw"|"algorithmic"});}}/></FieldFrame>:null}
|
||||
{revision?<IconButton label={editing?"Завершить редактирование":"Редактировать разметку"} title={document.selected==="raw"?"Сырая разметка доступна только для просмотра":editing?"Завершить редактирование · Escape":"Редактировать разметку"} aria-pressed={editing} disabled={!document.canEdit||busy}
|
||||
onClick={()=>{document.toggleEditing();setSelected(null);chooseTool("select");setVisible(v=>({...v,user:true}));}}><Icon name="edit"/></IconButton>:null}
|
||||
{draft?.operations.length?<IconButton label="Сохранить правки" title="Сохранить правки" loading={saving} onClick={()=>void save()}><Icon name="save"/></IconButton>:null}
|
||||
{document.dirty?<Button disabled={saving} onClick={()=>setConfirmDiscard(true)}>Отменить правки</Button>:null}
|
||||
</>;
|
||||
return <>
|
||||
{headerHost?createPortal(controls,headerHost):null}
|
||||
{!revision?<Button loading={loading} onClick={()=>{setLoading(true);setError(null);void semanticRequest(worldId).then(accept).catch(e=>setError(e.message)).finally(()=>setLoading(false));}}>{loading?"Открываем разметку":"Повторить открытие"}</Button>:null}
|
||||
{revision?<SemanticTools viewport={viewport} editing={editing&&visible.user&&layers.length>0&&!busy&&!saving} tool={tool} setTool={chooseTool} marking={marking} contours={contours}
|
||||
{loading||!revision?<Button loading={loading} onClick={document.refresh}>{loading?"Открываем разметку":"Повторить открытие"}</Button>:null}
|
||||
{revision?<SemanticTools viewport={viewport} editing={editing&&document.canEdit&&visible.user&&layers.length>0&&!busy} tool={tool} setTool={chooseTool} marking={marking} contours={contours}
|
||||
area={layers.some(id=>["pedestrian_area","sidewalk"].includes(id))} template={template} setTemplate={id=>{setTemplate(id);setSelected(null);setTool("select");}}
|
||||
selection={selection} map={display} operate={operate} remove={removeSelected} undo={undo} redo={redo} canUndo={!!draft?.operations.length} canRedo={!!draft?.future.length}
|
||||
axis={axis} setAxis={setAxis} visible={visible} setVisible={v=>{setVisible(v);if(!v.user)setSelected(null);}} areaMode={areaMode} setAreaMode={setAreaMode} onError={setError}/>:null}
|
||||
axis={axis} setAxis={setAxis} visible={visible} compareAvailable={document.selected.startsWith("manual:")||document.dirty} setVisible={v=>{setVisible(v);if(!v.user)setSelected(null);}} areaMode={areaMode} setAreaMode={setAreaMode} onError={setError}/>:null}
|
||||
{createPortal(<div className="ai-local-editor__legend nodedc-scene-controls">
|
||||
{classes.length?<SegmentedControl label="Видимые и редактируемые слои" selectionMode="multiple" value={layers} onChange={v=>{setLayers(v);setSelection(s=>s.filter(x=>v.includes(display.features.find(f=>f.id===x.feature_id)?.properties.class as UrbanClassId)));chooseTool("select");}}
|
||||
items={classes.map(id=>({value:id,label:URBAN_LABELS[id]}))}/>:null}
|
||||
</div>,viewport)}
|
||||
<SemanticEditOverlay runtime={runtime} viewport={viewport} map={visibleUrbanMap(overlay,visible.user?layers:[])}
|
||||
original={visible.model&&revision?visibleUrbanMap(revision.model,layers):null} layers={layers} selected={overlaySelection[0]??null} selection={overlaySelection} wholeContour={wholeContour}
|
||||
editing={editing&&visible.user&&layers.length>0} blocked={busy||saving} tool={tool} template={template} onPlaced={()=>chooseTool("select")}
|
||||
original={visible.model&&revision&&(document.selected.startsWith("manual:")||document.dirty)?visibleUrbanMap(revision.model,layers):null} layers={layers} selected={overlaySelection[0]??null} selection={overlaySelection} wholeContour={wholeContour}
|
||||
editing={editing&&document.canEdit&&visible.user&&layers.length>0} blocked={busy||saving||loading} tool={tool} template={template} onPlaced={()=>chooseTool("select")}
|
||||
axis={axis} areaMode={areaMode} onSelect={setSelected} onSelection={selectVertices} onChoose={setChoices} onOperation={operate} onPreview={setPreview} onError={setError}
|
||||
onExit={()=>{setEditing(false);setSelected(null);chooseTool("select");}}/>
|
||||
<Window open={choices.length>0} onClose={()=>setChoices([])} title="Выберите контур">
|
||||
{choices.map(({vertex,selection,wholeContour,operation},index)=><Button key={vertex.feature_id} onClick={()=>{selectVertices(selection,wholeContour);if(operation)operate(operation);setChoices([]);}}>{URBAN_LABELS[display.features.find(f=>f.id===vertex.feature_id)?.properties.class as UrbanClassId]} · {index+1}</Button>)}
|
||||
</Window>
|
||||
<Window open={confirmDiscard} onClose={()=>setConfirmDiscard(false)} title="Отменить несохранённые правки?">
|
||||
<Button onClick={()=>setConfirmDiscard(false)}>Продолжить редактирование</Button>
|
||||
<Button variant="danger" onClick={()=>{document.discard();setSelected(null);setConfirmDiscard(false);}}>Отменить правки</Button>
|
||||
</Window>
|
||||
<ToastStack items={error?[{id:"semantic",tone:"error",title:"Не удалось выполнить действие",description:error}]:[]} onDismiss={()=>setError(null)}/>
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import type {SemanticTool} from "./semanticEditorTypes";
|
||||
import {usePlannerPreferences} from "./usePlannerPreferences";
|
||||
export function SemanticTools(p:{viewport:HTMLElement;editing:boolean;tool:SemanticTool;setTool:(v:SemanticTool)=>void;marking:boolean;contours:boolean;area:boolean;template:string|null;setTemplate:(v:string)=>void;
|
||||
selection:Vertex[];map:UrbanMap;operate:(op:SemanticOperation)=>void;remove:()=>void;undo:()=>void;redo:()=>void;canUndo:boolean;canRedo:boolean;axis:SemanticAxis;setAxis:(v:SemanticAxis)=>void;
|
||||
visible:{model:boolean;user:boolean};setVisible:(v:{model:boolean;user:boolean})=>void;areaMode:"union"|"difference";setAreaMode:(m:"union"|"difference")=>void;onError:(s:string)=>void}) {
|
||||
visible:{model:boolean;user:boolean};compareAvailable:boolean;setVisible:(v:{model:boolean;user:boolean})=>void;areaMode:"union"|"difference";setAreaMode:(m:"union"|"difference")=>void;onError:(s:string)=>void}) {
|
||||
const [prefs,update]=usePlannerPreferences();
|
||||
const items:ToolbarItem[]=[{id:"hold",label:prefs.toolbar.autoHide?"Hold · Закрепить тулбар":"Hold · Открепить тулбар",icon:"lock",active:!prefs.toolbar.autoHide,onSelect:()=>{try{update({...prefs,toolbar:{...prefs.toolbar,autoHide:!prefs.toolbar.autoHide}});}catch{p.onError("Не удалось сохранить закрепление тулбара.");}}}];
|
||||
const editableMarking=p.selection.some(v=>{const f=p.map.features.find(f=>f.id===v.feature_id);return f&&isEditableMarking(f);});
|
||||
@@ -39,8 +39,8 @@ export function SemanticTools(p:{viewport:HTMLElement;editing:boolean;tool:Seman
|
||||
if(p.canRedo)items.push({id:"redo",label:"Повторить",shortcut:"Control+Shift+Z Meta+Shift+Z",icon:"redo",onSelect:p.redo});
|
||||
}
|
||||
items.push({id:"visibility",label:"Видимость разметки",icon:"eye",onSelect:()=>{},menu:menu(<>
|
||||
<Checker label="Алгоритмическая разметка" checked={p.visible.model} onChange={model=>p.setVisible({...p.visible,model})}/>
|
||||
<Checker label="Ручная разметка" checked={p.visible.user} onChange={user=>p.setVisible({...p.visible,user})}/>
|
||||
<Checker label="Показывать разметку" checked={p.visible.user} onChange={user=>p.setVisible({...p.visible,user})}/>
|
||||
{p.compareAvailable?<Checker label="Сравнить с исходной алгоритмической" checked={p.visible.model} onChange={model=>p.setVisible({...p.visible,model})}/>:null}
|
||||
</>)}, {id:"quality",label:"Качество Gaussian-сцены",icon:"sliders",onSelect:()=>{},menu:close=>menu(([["low","Низкое"],["medium","Среднее"],["high","Высокое"],["ultra","Ультра"],["maximum","Максимум"]] as const).map(([quality,label])=><Button key={quality} width="full" variant={prefs.quality===quality?"primary":"secondary"} tone="neutral" aria-pressed={prefs.quality===quality} onClick={()=>{try{update({...prefs,quality});close();}catch{p.onError("Не удалось сохранить качество.");}}}>{label}</Button>))});
|
||||
if(p.editing&&p.marking)items.push({id:"marking",label:"Добавить элемент разметки",icon:"plus",active:!!p.template,onSelect:()=>{},menu:close=>menu(MARKING_TEMPLATES.templates.filter(t=>!(t as {hidden?:boolean}).hidden).map(t=><Button key={t.id} width="full" onClick={()=>{p.setTemplate(t.id);close();}}>{t.label}</Button>))});
|
||||
return createPortal(<Toolbar container={p.viewport} {...prefs.toolbar} label="Инструменты семантики" items={items}/>,p.viewport);
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import {useEffect,useMemo,useSyncExternalStore} from "react";
|
||||
import {getSemanticSession,hasUnsavedSemanticSessions} from "../../core/simulation/semanticDocument";
|
||||
|
||||
// Protection belongs to all retained scenes, not only the mounted editor.
|
||||
window.addEventListener("beforeunload",event=>{if(hasUnsavedSemanticSessions())event.preventDefault();});
|
||||
export function useSemanticDocument(worldId:string,worldSha:string,active:boolean,source:object,preferred:string,onError:(error:string|null)=>void) {
|
||||
const session=useMemo(()=>getSemanticSession(worldId,worldSha,preferred),[worldId,worldSha]);
|
||||
const state=useSyncExternalStore(session.subscribe,session.snapshot);
|
||||
useEffect(()=>{if(active)void session.open();else session.setEditing(false);},[session,active,source]);
|
||||
useEffect(()=>{onError(state.error);},[state.error,onError]);
|
||||
return {...state,options:session.options(),dirty:session.dirty,canEdit:session.canEdit,
|
||||
select:session.select,setDraft:session.setDraft,setEditing:session.setEditing,
|
||||
toggleEditing:session.toggleEditing,save:session.save,discard:session.discard,refresh:()=>void session.open()};
|
||||
}
|
||||
@@ -33,7 +33,7 @@ export function useSemanticGestures(props:SemanticOverlayProps) {
|
||||
const d=drag;drag=null;latest.current.onPreview(null);
|
||||
if(d){if(!cancel&&d.op)latest.current.onOperation(d.op);release(d.id);}
|
||||
if(box){const id=box.id;box=null;release(id);}setMarquee(null);
|
||||
runtime.setNavigation(!latest.current.blocked);
|
||||
runtime.setNavigation(!latest.current.blocked,"semantic");
|
||||
};
|
||||
const commitShape=(points:number[][])=>{
|
||||
try{const p=latest.current,f=p.map.features.find(f=>f.id===p.selected?.feature_id&&["pedestrian_area","sidewalk"].includes(f.properties.class));
|
||||
@@ -52,7 +52,7 @@ export function useSemanticGestures(props:SemanticOverlayProps) {
|
||||
duplicate:duplicate?{feature_id:selected.feature_id,path:selected.path,index:selected.index}:undefined,
|
||||
copy:copy?{feature_id:selected.feature_id,new_feature_id:`user-${crypto.randomUUID()}`}:undefined};
|
||||
if(handle){const nodes=knots(f,selected.path);drag.handleScale=curveControlScale(nodes,selected.index,f.geometry.type==="Polygon",project);drag.handleStart=nodes[selected.index][handle];}
|
||||
runtime.setNavigation(false);viewport.setPointerCapture(e.pointerId);
|
||||
runtime.setNavigation(false,"semantic");viewport.setPointerCapture(e.pointerId);
|
||||
};
|
||||
const down=(e:PointerEvent)=>{
|
||||
const p=latest.current;if(!p.editing||p.blocked)return;
|
||||
@@ -160,11 +160,13 @@ export function useSemanticGestures(props:SemanticOverlayProps) {
|
||||
}else if(e.key==="Enter"&&shape.length>=3){stop(e);commitShape(shape);}
|
||||
};
|
||||
const leave=()=>{if(!drag&&!box){generation++;pending=null;setGhost(null);setHover(null);}};
|
||||
// Loading owns a temporary semantic lock; completion must restore input without blur.
|
||||
runtime.setNavigation(!props.blocked,"semantic");
|
||||
viewport.addEventListener("pointerdown",down,true);viewport.addEventListener("pointermove",move,true);viewport.addEventListener("pointerup",up,true);
|
||||
viewport.addEventListener("pointercancel",cancel,true);viewport.addEventListener("pointerleave",leave);document.addEventListener("keydown",key,true);
|
||||
window.addEventListener("blur",cancel);
|
||||
return()=>{disposed=true;cancel();viewport.removeEventListener("pointerdown",down,true);viewport.removeEventListener("pointermove",move,true);viewport.removeEventListener("pointerup",up,true);viewport.removeEventListener("pointercancel",cancel,true);viewport.removeEventListener("pointerleave",leave);document.removeEventListener("keydown",key,true);window.removeEventListener("blur",cancel);};
|
||||
},[props.runtime,props.viewport,props.editing,props.tool,props.template,props.layers]);
|
||||
return()=>{disposed=true;cancel();runtime.setNavigation(true,"semantic");viewport.removeEventListener("pointerdown",down,true);viewport.removeEventListener("pointermove",move,true);viewport.removeEventListener("pointerup",up,true);viewport.removeEventListener("pointercancel",cancel,true);viewport.removeEventListener("pointerleave",leave);document.removeEventListener("keydown",key,true);window.removeEventListener("blur",cancel);};
|
||||
},[props.runtime,props.viewport,props.editing,props.blocked,props.tool,props.template,props.layers]);
|
||||
const ghostMap=ghost?semanticOperation({...props.map,features:[]},ghost):null;
|
||||
return {hover,ghostMap,marquee,brush};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import {semanticDraft,semanticRequest,type SemanticDraft,type SemanticRevision} from "./semanticEdits";
|
||||
import {checkSemanticWorld,chooseVersion,manualKey,semanticVersions,versionOptions,versionQuery,type SemanticVersions} from "./semanticVersions";
|
||||
|
||||
interface DocumentState {
|
||||
revision:SemanticRevision|null;draft:SemanticDraft|null;versions:SemanticVersions|null;
|
||||
selected:string;editing:boolean;saving:boolean;loading:boolean;error:string|null;
|
||||
}
|
||||
export interface SemanticDocumentApi {
|
||||
versions:typeof semanticVersions;request:typeof semanticRequest;uuid:()=>string;
|
||||
}
|
||||
const api:SemanticDocumentApi={versions:semanticVersions,request:semanticRequest,uuid:()=>crypto.randomUUID()};
|
||||
|
||||
/** One session owns the draft AND its pending save across scene mounts. */
|
||||
export class SemanticDocumentSession {
|
||||
private value:DocumentState;
|
||||
private listeners=new Set<()=>void>();
|
||||
private generation=0;
|
||||
private abort:AbortController|null=null;
|
||||
private branch:string|null=null;
|
||||
private attempt:{key:string;signature:string}|null=null;
|
||||
constructor(readonly worldId:string,readonly worldSha:string,preferred:string,private transport=api){
|
||||
this.value={revision:null,draft:null,versions:null,selected:preferred,editing:false,saving:false,loading:false,error:null};
|
||||
}
|
||||
snapshot=()=>this.value;
|
||||
subscribe=(listener:()=>void)=>{this.listeners.add(listener);return()=>{this.listeners.delete(listener);};};
|
||||
private update(patch:Partial<DocumentState>){this.value={...this.value,...patch};this.listeners.forEach(listener=>listener());}
|
||||
get dirty(){return !!this.value.draft?.operations.length;}
|
||||
get protected(){return this.dirty||this.value.saving;}
|
||||
get canEdit(){return this.value.selected!=="raw"&&!this.value.loading&&!this.value.saving&&!!this.value.revision;}
|
||||
async open(preferred=this.value.selected){
|
||||
if(this.protected)return;
|
||||
this.abort?.abort();const abort=this.abort=new AbortController(),id=++this.generation;
|
||||
this.update({loading:true,editing:false,error:null});
|
||||
try {
|
||||
const versions=await this.transport.versions(this.worldId,abort.signal);
|
||||
const selected=chooseVersion(preferred,versions);
|
||||
const revision=await this.transport.request(this.worldId,undefined,abort.signal,versionQuery(selected,versions));
|
||||
checkSemanticWorld(revision,this.worldSha);
|
||||
if(abort.signal.aborted||id!==this.generation)return;
|
||||
this.branch=null;this.attempt=null;
|
||||
// Commit the identity, label and geometry together. A failed GET retains
|
||||
// the previous view, and a late response cannot overwrite a newer view.
|
||||
this.update({versions,selected,revision,draft:semanticDraft(revision.edited),loading:false});
|
||||
} catch(error){if(!abort.signal.aborted&&id===this.generation)this.update({error:(error as Error).message,loading:false});}
|
||||
}
|
||||
select=(selected:string)=>{if(!this.protected&&!this.value.loading)void this.open(selected);};
|
||||
setEditing=(next:boolean)=>{if(!next){this.update({editing:false});return;}if(!this.canEdit)return;
|
||||
if(this.value.selected==="algorithmic"&&!this.branch)this.branch=this.transport.uuid();
|
||||
this.update({editing:true});};
|
||||
toggleEditing=()=>this.setEditing(!this.value.editing);
|
||||
setDraft=(value:SemanticDraft|null|((prior:SemanticDraft|null)=>SemanticDraft|null))=>{
|
||||
if(!this.canEdit||!this.value.editing)return;
|
||||
this.update({draft:typeof value==="function"?value(this.value.draft):value});
|
||||
};
|
||||
discard=()=>{if(this.value.saving||!this.value.revision)return;this.branch=null;this.attempt=null;
|
||||
this.update({draft:semanticDraft(this.value.revision.edited),editing:false});};
|
||||
save=async()=>{
|
||||
const {draft,revision,selected,versions}=this.value;
|
||||
if(!draft?.operations.length||!revision||!versions||this.value.saving||selected==="raw")return;
|
||||
const branch=selected==="algorithmic"?this.branch:revision.branch_id;
|
||||
if(selected==="algorithmic"&&!branch){this.update({error:"Не удалось создать ручную версию."});return;}
|
||||
const body={expected_revision:revision.revision,model_sha256:revision.model_sha256,operations:draft.operations,
|
||||
...(branch?{branch_id:branch}:{})};
|
||||
const signature=JSON.stringify(body);
|
||||
if(this.attempt?.signature!==signature)this.attempt={signature,key:this.transport.uuid()};
|
||||
this.update({saving:true,error:null});
|
||||
try {
|
||||
const saved=await this.transport.request(this.worldId,{...body,request_id:this.attempt.key});
|
||||
checkSemanticWorld(saved,this.worldSha);
|
||||
if(!saved.revision||saved.model_sha256!==revision.model_sha256||(saved.branch_id??null)!==(branch??null))
|
||||
throw new Error("Ответ сохранения относится к другой версии. Черновик сохранён в этом окне.");
|
||||
const row={branch_id:saved.branch_id??null,revision:saved.revision,model_sha256:saved.model_sha256,
|
||||
created_at:saved.history.at(-1)!.created_at};
|
||||
this.branch=null;this.attempt=null;
|
||||
this.update({revision:saved,draft:semanticDraft(saved.edited),selected:manualKey(saved.branch_id??null),editing:false,
|
||||
versions:{...versions,manual:[row,...versions.manual.filter(v=>v.branch_id!==row.branch_id)]}});
|
||||
} catch(error){this.update({error:(error as Error).message});}
|
||||
finally{this.update({saving:false});}
|
||||
};
|
||||
options=()=>this.value.versions?versionOptions(this.value.versions):[];
|
||||
}
|
||||
|
||||
const sessions=new Map<string,SemanticDocumentSession>();
|
||||
export function getSemanticSession(worldId:string,worldSha:string,preferred:string) {
|
||||
for(const [key,session] of sessions)if(key!==worldSha&&!session.protected&&!session.snapshot().loading)sessions.delete(key);
|
||||
let session=sessions.get(worldSha);
|
||||
if(!session){session=new SemanticDocumentSession(worldId,worldSha,preferred);sessions.set(worldSha,session);}
|
||||
return session;
|
||||
}
|
||||
export const hasUnsavedSemanticSessions=()=>[...sessions.values()].some(session=>session.protected);
|
||||
@@ -68,7 +68,7 @@ function objectOperation(map:UrbanMap,op:Exclude<SemanticOperation,VertexOperati
|
||||
}
|
||||
export interface SemanticRevision {
|
||||
schema_version:"missioncore.semantic-editor/v1";
|
||||
revision:string|null;model_sha256:string;latest_model_sha256:string;
|
||||
branch_id?:string|null;revision:string|null;model_sha256:string;latest_model_sha256:string|null;
|
||||
model:UrbanMap;edited:UrbanMap;
|
||||
history:{revision:string;created_at:string;actions:number}[];
|
||||
learning:{state:string;dataset_ready:boolean};
|
||||
@@ -138,8 +138,9 @@ export function segmentHit(p:number[],a:number[],b:number[]) {
|
||||
const t=l?Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/l)):0;
|
||||
return {t,distance:Math.hypot(p[0]-a[0]-t*dx,p[1]-a[1]-t*dy)};
|
||||
}
|
||||
export async function semanticRequest(worldId:string,body?:object,signal?:AbortSignal):Promise<SemanticRevision> {
|
||||
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-edits`,{
|
||||
export async function semanticRequest(worldId:string,body?:object,signal?:AbortSignal,query?:Record<string,string>):Promise<SemanticRevision> {
|
||||
const search=query?`?${new URLSearchParams(query)}`:"";
|
||||
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-edits${search}`,{
|
||||
method:body?"POST":"GET",cache:"no-store",signal,
|
||||
...(body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}:{}),
|
||||
});
|
||||
@@ -149,6 +150,7 @@ export async function semanticRequest(worldId:string,body?:object,signal?:AbortS
|
||||
}
|
||||
const result=await response.json() as SemanticRevision;
|
||||
if(result.schema_version!=="missioncore.semantic-editor/v1")throw new Error("Неизвестная версия редактора.");
|
||||
if(query?.source==="raw"&&(result as SemanticRevision&{read_only?:boolean}).read_only===true)result.edited=result.model;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import type {SemanticRevision} from "./semanticEdits";
|
||||
|
||||
export interface SemanticVersions {
|
||||
raw_sha256:string|null; algorithmic_sha256:string|null;
|
||||
manual:{branch_id:string|null;revision:string;model_sha256:string;created_at:string}[];
|
||||
}
|
||||
export const manualKey=(branch:string|null)=>`manual:${branch??"legacy"}`;
|
||||
export function versionOptions(versions:SemanticVersions):{value:string;label:string;disabled?:boolean}[] {
|
||||
return [
|
||||
{value:"raw",label:"Сырая алгоритмическая",disabled:!versions.raw_sha256},
|
||||
{value:"algorithmic",label:"Алгоритмическая",disabled:!versions.algorithmic_sha256},
|
||||
...versions.manual.map((row,i)=>({value:manualKey(row.branch_id),
|
||||
label:versions.manual.length===1?"Ручная":`Ручная · ${new Date(row.created_at).toLocaleString("ru-RU")}${i===0?" · последняя":""}`})),
|
||||
];
|
||||
}
|
||||
export function versionQuery(key:string,versions:SemanticVersions):Record<string,string> {
|
||||
if(key==="raw"||key==="algorithmic")return {source:key,
|
||||
model_sha256:(key==="raw"?versions.raw_sha256:versions.algorithmic_sha256)??""};
|
||||
const branch=versions.manual.find(row=>manualKey(row.branch_id)===key);
|
||||
if(!branch)throw new Error("Ручная версия не найдена.");
|
||||
return {source:"manual",...(branch.branch_id?{branch_id:branch.branch_id}:{})};
|
||||
}
|
||||
export function chooseVersion(preferred:string,versions:SemanticVersions):string {
|
||||
if(preferred==="manual"&&versions.manual.length)return manualKey(versions.manual[0].branch_id);
|
||||
const options=versionOptions(versions);
|
||||
if(options.some(row=>row.value===preferred&&!row.disabled))return preferred;
|
||||
return versions.algorithmic_sha256?"algorithmic":versions.manual.length?manualKey(versions.manual[0].branch_id):"raw";
|
||||
}
|
||||
export async function semanticVersions(worldId:string,signal?:AbortSignal):Promise<SemanticVersions> {
|
||||
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-versions`,{cache:"no-store",signal});
|
||||
if(!response.ok)throw new Error("Не удалось получить версии разметки.");
|
||||
return response.json();
|
||||
}
|
||||
export function checkSemanticWorld(value:SemanticRevision,worldSha:string) {
|
||||
if(value.model.source.world_sha256!==worldSha||value.edited.source.world_sha256!==worldSha)
|
||||
throw new Error("Правки относятся к другой сцене.");
|
||||
}
|
||||
@@ -3,18 +3,20 @@ import type {EditorProjection} from "./editorProjection";
|
||||
import type {SemanticAxis} from "./semanticVector";
|
||||
export interface SimulationLayout {
|
||||
mode:"view"|"semantic"|"planning"; projection:EditorProjection;
|
||||
semanticVersion:"raw"|"algorithmic"|"manual";
|
||||
sceneLayers:{gaussian:boolean;collision:boolean}; infrastructure:boolean; memory:boolean;
|
||||
layers:UrbanClassId[]; urbanLayers:UrbanClassId[];
|
||||
visible:{model:boolean;user:boolean}; axis:SemanticAxis; areaMode:"union"|"difference";
|
||||
}
|
||||
const classes:UrbanClassId[]=["road_boundary","pedestrian_boundary","building_facade","curb","curb_cut","sidewalk","pedestrian_area","carriageway","service_lane","bike_lane","parking","crosswalk_area","crosswalk_marking","road_marking"];
|
||||
export const DEFAULT_SIMULATION_LAYOUT:SimulationLayout={mode:"view",projection:"perspective",sceneLayers:{gaussian:true,collision:false},infrastructure:false,memory:false,layers:["road_boundary"],urbanLayers:classes,visible:{model:false,user:true},axis:"xy",areaMode:"union"};
|
||||
export const DEFAULT_SIMULATION_LAYOUT:SimulationLayout={mode:"view",projection:"perspective",semanticVersion:"algorithmic",sceneLayers:{gaussian:true,collision:false},infrastructure:false,memory:false,layers:["road_boundary"],urbanLayers:classes,visible:{model:false,user:true},axis:"xy",areaMode:"union"};
|
||||
export function normalizeSimulationLayout(raw:unknown):SimulationLayout {
|
||||
const v=(raw&&typeof raw==="object"?raw:{}) as Partial<SimulationLayout>,d=DEFAULT_SIMULATION_LAYOUT;
|
||||
const pick=<T extends string>(x:unknown,values:readonly T[],fallback:T):T=>values.includes(x as T)?x as T:fallback;
|
||||
const bool=(x:unknown,f:boolean)=>typeof x==="boolean"?x:f;
|
||||
const layers=(x:unknown,f:UrbanClassId[])=>Array.isArray(x)?Array.from(new Set(x.filter((k):k is UrbanClassId=>classes.includes(k)))):f;
|
||||
return {mode:pick(v.mode,["view","semantic","planning"],d.mode),projection:pick(v.projection,["perspective","orthographic"],d.projection),
|
||||
semanticVersion:pick(v.semanticVersion,["raw","algorithmic","manual"],d.semanticVersion),
|
||||
sceneLayers:{gaussian:bool(v.sceneLayers?.gaussian,true),collision:bool(v.sceneLayers?.collision,false)},infrastructure:bool(v.infrastructure,false),memory:bool(v.memory,false),
|
||||
layers:layers(v.layers,d.layers),urbanLayers:layers(v.urbanLayers,d.urbanLayers),visible:{model:bool(v.visible?.model,false),user:bool(v.visible?.user,true)},
|
||||
axis:pick(v.axis,["x","y","z","xy","xz","yz"],d.axis),areaMode:pick(v.areaMode,["union","difference"],d.areaMode)};
|
||||
|
||||
@@ -196,5 +196,6 @@
|
||||
|
||||
.semantic-tools__menu { display: flex; flex-direction: column; gap: .25rem; }
|
||||
.ai-polygon__semantic-actions { display: contents; }
|
||||
.ai-polygon__semantic-version-field { width: 18rem; min-width: 0; max-width: 100%; }
|
||||
|
||||
.ai-local-editor__cube { position: absolute; top: 8px; left: 4px; z-index: 5; }
|
||||
|
||||
@@ -144,3 +144,15 @@ test('camera snapshot restores exact pose, orthographic scale and orbit anchor a
|
||||
assert.deepEqual(next.c.snapshot(),old);next.c.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('navigation blockers are independent and only their owners can release them',()=>{
|
||||
const f=fixture();f.c.setProjection('orthographic');
|
||||
const wheel=()=>f.event('wheel',{deltaX:0,deltaY:-120,deltaMode:0});
|
||||
const span=()=>f.c.camera.top;
|
||||
try{
|
||||
const initial=span();f.c.setNavigation(false);f.c.setNavigation(false,'semantic');
|
||||
f.c.setNavigation(true);wheel();assert.equal(span(),initial,'planner release must not clear semantic lock');
|
||||
f.c.setNavigation(false);f.c.setNavigation(true,'semantic');wheel();assert.equal(span(),initial,'semantic release must not clear planner lock');
|
||||
f.c.setNavigation(true);wheel();assert.ok(span()<initial,'input resumes immediately without blur');
|
||||
}finally{f.c.dispose();}
|
||||
});
|
||||
|
||||
@@ -5,7 +5,12 @@ import {fileURLToPath} from 'node:url';
|
||||
import path from 'node:path';
|
||||
import ts from 'typescript';
|
||||
const url=s=>`data:text/javascript;base64,${Buffer.from(s).toString('base64')}`;
|
||||
const hooks=url('export const useRef=x=>({current:x});export const useState=x=>[x,()=>{}];export const useEffect=f=>{globalThis.cleanups.push(f());};');
|
||||
const hooks=url(`
|
||||
export function useRef(x){const h=globalThis.semanticHooks,i=h.cursor++;return h.slots[i]??(h.slots[i]={current:x});}
|
||||
export function useState(x){const h=globalThis.semanticHooks,i=h.cursor++;const s=h.slots[i]??(h.slots[i]={value:x});return [s.value,()=>{}];}
|
||||
export function useEffect(f,deps){const h=globalThis.semanticHooks,i=h.cursor++,s=h.slots[i];
|
||||
if(!s||!deps||deps.some((v,k)=>!Object.is(v,s.deps[k])))h.pending.push({i,f,deps,cleanup:s?.cleanup});}
|
||||
`);
|
||||
const cache=new Map();
|
||||
function module(p){
|
||||
p=path.resolve(p);if(cache.has(p))return cache.get(p);
|
||||
@@ -26,19 +31,23 @@ class Target {
|
||||
setPointerCapture(i){this.capture.add(i);}hasPointerCapture(i){return this.capture.has(i);}releasePointerCapture(i){this.capture.delete(i);}
|
||||
}
|
||||
function setup({marking=false,whole=false}={}){
|
||||
globalThis.cleanups=[];globalThis.document=new Target();document.querySelector=()=>null;globalThis.window=new Target();
|
||||
globalThis.semanticHooks={slots:[],cursor:0,pending:[]};globalThis.document=new Target();document.querySelector=()=>null;globalThis.window=new Target();
|
||||
const canvas={clientWidth:100,clientHeight:100,getBoundingClientRect:()=>({left:0,top:0}),focus(){},closest:()=>null};
|
||||
const viewport=new Target();viewport.querySelector=()=>canvas;
|
||||
const map={features:[{id:'line',properties:{class:marking?'road_marking':'road_boundary',...(marking?{subtype:'linear_marking'}:{})},geometry:marking?{type:'Polygon',coordinates:[[[0,0,2],[10,0,2],[10,1,2],[0,1,2],[0,0,2]]]}:{type:'LineString',coordinates:[[0,0,2],[10,0,2],[20,0,2]]}}]};
|
||||
const selected={feature_id:'line',path:0,index:marking?1:2,...(whole?{object:true}:{})};
|
||||
const previews=[],commits=[],errors=[],selections=[];let navigation=true;
|
||||
const p={map,viewport,layers:[map.features[0].properties.class],selected,selection:[selected],editing:true,blocked:false,tool:'select',template:null,axis:'x',areaMode:'union',
|
||||
runtime:{semanticSegmentParameter:(_a,_b,t)=>t,projectSemantic:v=>[v[0]/100,v[1]/100],moveSemantic:(v,x,y)=>[x*100,y*100,v[2]],setNavigation:v=>{navigation=v;}},
|
||||
const previews=[],commits=[],errors=[],selections=[];const navigationBlocks=new Set();
|
||||
let p={map,viewport,layers:[map.features[0].properties.class],selected,selection:[selected],editing:true,blocked:false,tool:'select',template:null,axis:'x',areaMode:'union',
|
||||
runtime:{semanticSegmentParameter:(_a,_b,t)=>t,projectSemantic:v=>[v[0]/100,v[1]/100],moveSemantic:(v,x,y)=>[x*100,y*100,v[2]],setNavigation:(v,owner='planner')=>{if(v)navigationBlocks.delete(owner);else navigationBlocks.add(owner);}},
|
||||
onPreview:op=>previews.push(op),onOperation:op=>{semanticOperation(map,op);commits.push(op);},onSelection:v=>selections.push(v),onSelect:v=>selections.push(v?[v]:[]),onChoose(){},onError:e=>errors.push(e),onPlaced(){},onExit(){}};
|
||||
useSemanticGestures(p);
|
||||
const hooks=globalThis.semanticHooks;
|
||||
const render=next=>{p={...p,...next};hooks.cursor=0;hooks.pending=[];useSemanticGestures(p);
|
||||
for(const effect of hooks.pending)effect.cleanup?.();
|
||||
for(const effect of hooks.pending)hooks.slots[effect.i]={deps:effect.deps,cleanup:effect.f()};};
|
||||
render({});
|
||||
const axis={closest:q=>q.includes('axis')?{dataset:{semanticAxis:'x'}}:null};
|
||||
const event=(x,o={})=>({target:axis,button:0,pointerId:1,clientX:x,clientY:0,shiftKey:true,...o});
|
||||
return {p,canvas,viewport,event,previews,commits,selections,errors,navigation:()=>navigation,dispose:()=>{for(const c of cleanups)c();}};
|
||||
return {get p(){return p;},render,canvas,viewport,event,previews,commits,selections,errors,navigation:()=>navigationBlocks.size===0,dispose:()=>{for(const slot of hooks.slots)slot?.cleanup?.();}};
|
||||
}
|
||||
test('Shift pivot duplicates once on release; click and Escape do not commit',()=>{
|
||||
const s=setup(),snapshot=JSON.stringify(s.p.map);
|
||||
@@ -191,3 +200,32 @@ test('Shift Y at a facade endpoint extends around a corner and commits preview o
|
||||
assert.deepEqual(semanticOperation(s.p.map,s.commits[0]).features[0].geometry.coordinates,[[0,.1,2],[10,0,2],[10,3,2]]);
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
|
||||
test('version load releases camera without blur after overlay changes while blocked',()=>{
|
||||
const s=setup();
|
||||
try{
|
||||
s.render({editing:false});
|
||||
for(let i=0;i<3;i++){
|
||||
s.render({blocked:true,layers:[...s.p.layers]});assert.equal(s.navigation(),false);
|
||||
s.render({blocked:false});assert.equal(s.navigation(),true,'load completion must restore input without window blur');
|
||||
}
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
test('loading cancels a captured edit and stale pointerup cannot commit it',()=>{
|
||||
const s=setup();
|
||||
try{
|
||||
s.viewport.emit('pointerdown',s.event(30));s.viewport.emit('pointermove',s.event(45));
|
||||
assert.equal(s.viewport.capture.size,1);
|
||||
s.render({blocked:true});assert.equal(s.viewport.capture.size,0);assert.equal(s.navigation(),false);
|
||||
s.viewport.emit('pointerup',s.event(45));assert.equal(s.commits.length,0);
|
||||
s.render({blocked:false});assert.equal(s.navigation(),true);
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
test('semantic cleanup releases its lock but never clears an independent planner block',()=>{
|
||||
const s=setup();
|
||||
s.p.runtime.setNavigation(false);s.render({blocked:true});s.render({blocked:false});
|
||||
assert.equal(s.navigation(),false,'planner remains blocked');
|
||||
s.dispose();assert.equal(s.navigation(),false);
|
||||
s.p.runtime.setNavigation(true);assert.equal(s.navigation(),true);
|
||||
const t=setup();t.render({blocked:true});t.dispose();assert.equal(t.navigation(),true,'leaving semantic view releases its own loading lock');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {test} from 'node:test';
|
||||
import ts from 'typescript';
|
||||
const url=code=>`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`;
|
||||
const compile=path=>ts.transpileModule(readFileSync(new URL(path,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
const versionsUrl=url(compile('../src/core/simulation/semanticVersions.ts'));
|
||||
const draftUrl=url(`export const semanticDraft=base=>({base,map:base,operations:[],future:[]});export const semanticRequest=(...args)=>globalThis.docRequest(...args);`);
|
||||
const sessionUrl=url(compile('../src/core/simulation/semanticDocument.ts').replace('"./semanticEdits"',JSON.stringify(draftUrl)).replace('"./semanticVersions"',JSON.stringify(versionsUrl)));
|
||||
const {SemanticDocumentSession,getSemanticSession,hasUnsavedSemanticSessions}=await import(sessionUrl);
|
||||
const {chooseVersion,versionQuery,versionOptions}=await import(versionsUrl);
|
||||
const list={raw_sha256:'raw-sha',algorithmic_sha256:'auto-sha',manual:[{branch_id:null,revision:'legacy',model_sha256:'old-sha',created_at:'2026-10-29T09:00:00Z'}]};
|
||||
const map={source:{world_sha256:'world'},features:[]};
|
||||
const value=(sha='auto-sha')=>({schema_version:'missioncore.semantic-editor/v1',branch_id:null,revision:null,model_sha256:sha,latest_model_sha256:sha,model:map,edited:map,history:[]});
|
||||
const deferred=()=>{let resolve,reject;const promise=new Promise((a,b)=>{resolve=a;reject=b;});return {promise,resolve,reject};};
|
||||
const setup=()=>{let ids=0;const bodies=[];const transport={uuid:()=>`uuid-${++ids}`,versions:async()=>list,request:async(_w,body,_s,q)=>{if(body)bodies.push(body);return value(q?.model_sha256);}};return {s:new SemanticDocumentSession('id','world','algorithmic',transport),transport,bodies};};
|
||||
const modify=s=>{s.setEditing(true);s.setDraft(d=>({...d,operations:[{kind:'move'}],map:{...d.map,modified:true}}));};
|
||||
const saved=body=>({...value(body.model_sha256),branch_id:body.branch_id??null,revision:'saved',edited:{...map,modified:true},history:[{revision:'saved',created_at:'2026-10-29T10:00:00Z',actions:1}]});
|
||||
|
||||
test('three representations and no fabricated manual',()=>{
|
||||
assert.equal(versionOptions({...list,manual:[]}).length,2);
|
||||
assert.equal(chooseVersion('manual',list),'manual:legacy');
|
||||
assert.equal(chooseVersion('raw',{...list,raw_sha256:null}),'algorithmic');
|
||||
assert.deepEqual(versionQuery('manual:legacy',list),{source:'manual'});
|
||||
assert.deepEqual(versionQuery('raw',list),{source:'raw',model_sha256:'raw-sha'});
|
||||
assert.throws(()=>versionQuery('manual:missing',list));
|
||||
});
|
||||
test('failed selection retains matching old identity and geometry; late GET cannot replace newer selection',async()=>{
|
||||
const {s,transport}=setup();await s.open();const before=s.snapshot();
|
||||
transport.request=async()=>{throw new Error('unavailable');};
|
||||
await s.open('manual:legacy');
|
||||
assert.equal(s.snapshot().selected,'algorithmic');assert.equal(s.snapshot().revision,before.revision);assert.equal(s.snapshot().error,'unavailable');
|
||||
const old=deferred(),fresh=deferred();let calls=0;
|
||||
transport.request=()=>++calls===1?old.promise:fresh.promise;
|
||||
const a=s.open('raw');await Promise.resolve();const b=s.open('algorithmic');await Promise.resolve();
|
||||
fresh.resolve(value('fresh'));await b;old.resolve(value('old'));await a;
|
||||
assert.equal(s.snapshot().selected,'algorithmic');assert.equal(s.snapshot().revision.model_sha256,'fresh');
|
||||
});
|
||||
test('raw remains read-only including direct session mutation',async()=>{
|
||||
const {s}=setup();await s.open('raw');modify(s);await s.save();
|
||||
assert.equal(s.canEdit,false);assert.equal(s.snapshot().editing,false);assert.equal(s.dirty,false);
|
||||
});
|
||||
test('save survives detached subscriber, blocks duplicate save/edit, and publishes manual only after success',async()=>{
|
||||
const {s,transport,bodies}=setup();await s.open();modify(s);const pending=deferred();
|
||||
transport.request=async(_w,body)=>{bodies.push(body);return pending.promise;};
|
||||
let oldNotices=0;const detach=s.subscribe(()=>oldNotices++);const saving=s.save();detach();
|
||||
let newNotices=0;const detachNew=s.subscribe(()=>newNotices++);
|
||||
assert.equal(s.snapshot().saving,true);assert.equal(s.protected,true);assert.equal(s.snapshot().selected,'algorithmic');
|
||||
await s.save();s.select('raw');s.setDraft(null);assert.equal(bodies.length,1);assert.equal(s.dirty,true);
|
||||
pending.resolve(saved(bodies[0]));await saving;detachNew();
|
||||
assert.ok(oldNotices>0);assert.ok(newNotices>0);assert.equal(s.dirty,false);assert.equal(s.snapshot().selected,'manual:uuid-1');
|
||||
assert.equal(s.snapshot().versions.manual.length,2);assert.equal(s.snapshot().versions.manual[1].revision,'legacy');
|
||||
});
|
||||
test('409 retains draft and exact idempotency key for retry; cancellation never creates manual',async()=>{
|
||||
const {s,transport,bodies}=setup();await s.open();modify(s);
|
||||
transport.request=async(_w,body)=>{bodies.push(body);throw new Error('409 conflict');};
|
||||
await s.save();await s.save();assert.equal(bodies[0].request_id,bodies[1].request_id);
|
||||
assert.equal(s.dirty,true);assert.equal(s.snapshot().revision.revision,null);assert.equal(s.snapshot().versions.manual.length,1);
|
||||
s.discard();assert.equal(s.dirty,false);assert.equal(s.snapshot().versions.manual.length,1);
|
||||
});
|
||||
test('dirty scene remains protected while another scene mounts and pending request belongs to same session',async()=>{
|
||||
globalThis.fetch=async()=>({ok:true,json:async()=>list});
|
||||
globalThis.docRequest=async(_w,body,_signal,q)=>value(q?.model_sha256);
|
||||
const a=getSemanticSession('A','world','algorithmic');await a.open();assert.equal(a.snapshot().error,null);modify(a);assert.equal(a.dirty,true,JSON.stringify(a.snapshot()));
|
||||
const b=getSemanticSession('B','clean','algorithmic');assert.notEqual(a,b);
|
||||
assert.equal(hasUnsavedSemanticSessions(),true);assert.equal(getSemanticSession('A','world','raw'),a);
|
||||
a.discard();assert.equal(hasUnsavedSemanticSessions(),false);
|
||||
});
|
||||
@@ -42,4 +42,13 @@
|
||||
|
||||
Географический поиск и address-check-v1 остаются историческими инженерными материалами. Они не являются обязательным этапом архитектуры, разрешением на продолжение поиска или доказательством качества детектора. Принятые маски и связи с собственными источниками сохраняются.
|
||||
|
||||
Следующее сравнение G12 / RGB SegFormer B0 проводится на зафиксированных сканах и исходной области проверенных меток. Сначала необходимы входы, код оценки, версии весов/среды и разрешение вычислений. Четыре локальных окна не дают полного покрытия всех классов разметки. Критерии качества не ослабляются, старые результаты и критерии опытов не переписываются задним числом. Готовность локализации, обучения и производственного исполнения отражается отдельными фактическими приёмками.
|
||||
Исторические сравнения G12 / RGB SegFormer B0 и их критерии сохраняются в отчётах и не переписываются задним числом. Готовность локализации, обучения и производственного исполнения отражается отдельными фактическими приёмками.
|
||||
|
||||
Уточнение владельца 29.10.2026: ближайший результат — автоматически собранная разметка из компактных примитивов и действующего каталога редактора, без ручной доводки результата. На первом сквозном сравнении детектор фиксируется. Точная обводка краски остаётся диагностическим наблюдением; её не требуется доводить до идеала или превращать в пользовательский объект. Тип, размещение и нормализованная форма проверяются по конечной карте; пропуски допустимы, но явно показаны вместе с ложными объектами. Подробная постановка, реализованные интерфейсы и границы — [SEMANTIC_PRIMITIVE_OUTPUT.md](SEMANTIC_PRIMITIVE_OUTPUT.md).
|
||||
|
||||
|
||||
## Роли контрольных сцен · уточнение 31.10.2026
|
||||
|
||||
Для проверки полноты и формы дорожной разметки владелец выделяет проспект Мира, Покровку, Маросейку, Сретенку и два скана Цветного бульвара (владелец подтвердил их вместо первоначального названия «Трубная»). Новинский и другие сканы Садового с дублёрами, малым количеством краски или слабым захватом используются отдельно для проверки ложных объектов и работы при недостаточной наблюдаемости. Достоверно пустая поверхность и невидимая поверхность имеют разные метки. Отсутствующая краска не достраивается из правил.
|
||||
|
||||
Этот выбор задаёт роли данных для оценки, а не ветвление алгоритма по названию улицы. История TRAIN/development сохраняется; знакомые сцены не объявляются новым независимым контролем. Новые источники сначала идентифицируются и визуально проверяются; сам импорт не означает готовность датасета. Текущий инвентарь и уточнение следующего шага: [проверка источников](../outputs/semantic-source-priority-20261031/REPORT.md).
|
||||
|
||||
@@ -229,3 +229,32 @@ Root и повторно используемый критик просмотр
|
||||
В этом же заходе реализован `observed_topology.py`: 22 теста, Ruff, 32 реальные комбинации четырёх кадров и четырёх моделей при связности 4/8; 20 проверок путей, без отказов по ресурсу. N51-07 подтверждает различие в целостности покрытия полосы зебры, N52-08 — более сильную фрагментацию тонких частей у обоих D4. Проверяется покрытие известной части, а не split полного объекта. Unknown и область вне ROI не дают гарантии соединения или раздельности. Модуль принят root и критиком и включён в исследовательский audit. Прежние решения по моделям не пересматривались по дополнительным метрикам.
|
||||
|
||||
Рабочий детектор не прошёл совместную приёмку. Полезный выход — проверенная версия данных, восстановленная детализация provenance и проверка формы с конкретными свидетелями. Следующий пакет требует содержательного основания для модуля, совместно сохраняющего тонкую краску и промежутки; такой модуль пока не выбран. Не повторять те же 170 пикселей, sweep, BN, representation или уже выполненный topology audit под новым названием. Историческое предложение `next-package-review.json` выполнено дополнением текущего пакета. Результаты, исходники, pins, продолжение и closeout: `outputs/semantic-object-support-20261027/`. Пользовательская карта и питание не менялись.
|
||||
|
||||
|
||||
## Сравнение исходной карты, маски и модели · 29.10.2026
|
||||
|
||||
`outputs/semantic-scene-comparison-20261029/REPORT.md`: три полных окна M1/M3/M4
|
||||
одной TRAIN-сцены. А — исходная автоматическая карта без ручных ревизий; Б —
|
||||
частичная проверенная маска; В — точное воспроизведение исходного B0. Б/В имеют
|
||||
общую сборку, XY и политику высоты; ожидания объектов остаются у проверяющего.
|
||||
При nearly-perfect known IoU на полном кадре В видны ложные контуры мощения.
|
||||
Не считать ни partial known score, ни число admitted компонентов успехом карты.
|
||||
|
||||
Принят отдельный `editor_components`: локальный отказ не блокирует пригодных
|
||||
соседей, исходная 2D-геометрия отказов сохраняется. Строгий API и общие лимиты
|
||||
остались; callback/source ошибки не превращаются в штатный deferred. Полезные
|
||||
свидетели M1/В и M3/Б проверены root/критиком. Но C/M3 и C/M4 имеют 0% known paint
|
||||
в 3D-допуске; политика alpha/depth экспериментальна и не калибрована. 9 изолированных
|
||||
store/API циклов прошли save/restart; 24 live-файла неизменны; 0 fits.
|
||||
|
||||
Это backend-исправление и закрытое ограниченное сравнение, не новый принятый
|
||||
детектор, UI-приёмка или измерение труда человека. Не расширять выводы до целой
|
||||
улицы, готовой инженерной формы или неизвестной сцены. Новый fit не запускается
|
||||
из этого решения; точка входа — текущий root-decision и report в том же каталоге.
|
||||
|
||||
|
||||
## Конечные объекты вместо raw-контуров · 29.10.2026
|
||||
|
||||
Последнее поручение владельца: реализовать [автоматическую сборку из примитивов](SEMANTIC_PRIMITIVE_OUTPUT.md) на фиксированном детекторе и показать конечную карту без ручных правок. Это текущая точка продолжения, заменяющая исторический next-step по raw-contour admission/порогам высоты. Root реализует сквозной результат; критик проверяет происхождение, ложные/пропущенные объекты и интеграцию. Наличие одного хорошего кадра, pixel score или тестов не заменяет полный визуальный просмотр объявленного объёма. Никакого нового fit или расширения агентной платформы как обязательного этапа.
|
||||
|
||||
Пакет `outputs/semantic-primitive-output-20261029`: три сохранённых полноразмерных окна M1/M3/M4, не вся улица и не независимый контроль. Исходные объекты каталога, общие параметры сборки, 2D-распознавание и Gaussian-оценка высоты раздельны. Неподдержанное остаётся unresolved; исходные параметры в редакторе помечены как immutable recognition snapshot, человеческая геометрия живёт отдельно. Новые UI-переключатели отложены; результат даётся отдельным review-артефактом, рабочая пользовательская карта не подменяется.
|
||||
|
||||
@@ -56,3 +56,24 @@ Next candidate: one full-network SegFormer MiT-B0 recipe against the frozen G re
|
||||
Bounded specification: `outputs/semantic-geometry-gate-20261026/next-experiment.json`. It is not an executable release yet: exact data/weights/dependencies must be pinned, geographic separation established, whole objects/background reviewed, and Worker execution authorized. Existing 26 heavily used windows are development evidence; they cannot become a new independent test by renaming the split. Preserve the preceding admission requirements in `parent-refresh-1/NEXT_EXPERIMENT_ADMISSION.md`.
|
||||
|
||||
The owner's current instruction remains: do not touch Worker. No Worker command, training, model installation, live-map mutation or power operation occurred in this gate.
|
||||
|
||||
|
||||
## Explicit partial admission · 29.10.2026
|
||||
|
||||
`editor_components()` is an opt-in offline adapter next to the unchanged strict
|
||||
`editor_features()`. Whole-proposal identity and resource checks remain atomic.
|
||||
Each original component is either lifted without changing XY/topology, or kept
|
||||
verbatim in `deferred` with its reason. Callers must retain the deferred data;
|
||||
admitted geometry is not a declaration that an object is road paint.
|
||||
|
||||
Only explicit `ComponentRefusal` is local. Sampler/source exceptions and invalid
|
||||
callback shape propagate; missing support is represented by non-finite heights.
|
||||
The existing rigid marking semantics are retained: this adds no vertex editing,
|
||||
shape fitting, cross-tile grouping or automatic live-map publication.
|
||||
|
||||
Real M1/M3/M4 A/B/C comparison and before/after evidence are in
|
||||
[the report](../outputs/semantic-scene-comparison-20261029/REPORT.md). All six strict
|
||||
B/C batches failed; partial mode retained useful components, but C/M3 and C/M4
|
||||
still retained zero known paint in admitted 3D geometry. Nine actual stores and
|
||||
the HTTP router passed save/restart/idempotency/conflict checks. 62 focused tests
|
||||
and Ruff passed. Browser UI and human correction time were not measured.
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# Автоматическая разметка из примитивов
|
||||
|
||||
Постановка владельца и первый эксперимент: 29.10.2026. Фундамент —
|
||||
[отдельная сцена](SCENE_SEMANTICS_PRODUCT_CONCEPT.md). Результат для пользователя:
|
||||
автоматически распознанные объекты существующего каталога, затем отдельные
|
||||
пользовательские исправления. Неровный контур наблюдаемой краски — свидетельство,
|
||||
а не обязательная редактируемая форма.
|
||||
|
||||
## Исполняемый путь
|
||||
|
||||
Зафиксированный детектор → кандидаты из его предсказания → проверка формы и RGB
|
||||
поддержки → компактная полоса либо экземпляр каталога → оценка поверхности →
|
||||
отдельная автоматическая карта → визуальная проверка и пользовательские правки.
|
||||
|
||||
- Линии: управляющая полилиния с шириной, прямая полоса — два конца. Сохранять
|
||||
реальные разрывы; не соединять штрихи и не продолжать за пределы наблюдения.
|
||||
- Символы: `template_id`, центр, угол и общий масштаб. Канонический artwork —
|
||||
`src/k1link/simulation/ai_polygon/marking-templates.json`; скрытые старые версии
|
||||
не распознавать как действующий каталог. Пропорции готового символа сохраняются.
|
||||
- Зебра: группа наблюдаемых прямоугольных полос. Каталожный шестиполосный образец
|
||||
не определяет число полос на дороге. Первый сборщик группирует полосы; общей
|
||||
оптимизации их угла/ширины пока нет.
|
||||
- Недостаточная поддержка → unresolved, без raw-polygon fallback и без перевода
|
||||
неизвестного в обучающий background. Параллельно проверять полезные пропуски.
|
||||
- Высота: отдельная оценка поверхности внутри объекта; отказ оставляет весь
|
||||
распознанный 2D-объект. Нулевой Z и Z цели камеры не являются запасной высотой.
|
||||
|
||||
## Реализация и пределы
|
||||
|
||||
`simulation/semantic-learning/paint_objects.py` содержит сборку, восстановление
|
||||
из параметров, RGB contrast gate, ограниченное сопоставление каталога,
|
||||
группировку полос и материализацию для редактора. Это начальный геометрический
|
||||
классификатор с локальным RGB-признаком, не новая обученная модель объектов.
|
||||
Fit-score не равен вероятности правильного класса. Веса B0 не изменялись.
|
||||
|
||||
Сборщик не принимает готовую карту, дорожные границы, target или адрес. Его
|
||||
ограничения общие для всех кадров и записываются в результат. Сопоставление
|
||||
шаблонов ограничено по числу кандидатов/оптимизаций. Нет обещания, что весь
|
||||
каталог уже распознаётся надёжно; первые реальные примеры проверяют только
|
||||
линии, полосы перехода и `letter_A_v3`.
|
||||
|
||||
Автоматический JSON хранит параметры и результат их восстановления. Экспорт
|
||||
в действующий редактор материализует геометрию, с которой уже работают его
|
||||
операции. `recognition_snapshot` — **неизменное исходное автоматическое
|
||||
предложение**, не параметры текущей пользовательской ревизии. После правки
|
||||
истиной текущей формы являются её координаты. `support_boundary` и
|
||||
`instance_completeness=not-assessed` сохраняются в карте; концы у края окна
|
||||
не объявляются физическими концами разметки.
|
||||
|
||||
## Первый сквозной результат
|
||||
|
||||
`outputs/semantic-primitive-output-20261029/review.html` — просмотр исходника и
|
||||
автоматического результата; `automatic-map.json` — материализованная карта;
|
||||
`automatic-objects.json` — параметры, provenance и отказы; `REPORT.md` —
|
||||
ограничения, проверка и источники. Три полных окна M1/M3/M4 по 12 м — весь
|
||||
объявленный объём этого опыта, **не вся Маросейка**. Они знакомы B0 по обучению.
|
||||
|
||||
Следующий тюнинг выбирается по конечному результату: пропущенное наблюдение —
|
||||
детектор; неверный/отклонённый класс — классификация/группировка; неверная форма —
|
||||
подгонка; неверная высота — поверхность. Новый fit, полный рендер, расширение
|
||||
агентной платформы и новые переключатели продукта не являются обязательными
|
||||
предпосылками этой проверки. Внешние карты и ручные эталонные объекты не
|
||||
используются для автоматической подстановки.
|
||||
|
||||
|
||||
## Полная Покровка и пользовательские версии · 29.10.2026
|
||||
|
||||
[Контракт raw/algorithmic/manual, публикация и доказательства](SEMANTIC_REPRESENTATION_VERSIONS.md). Обработаны88/88 обследованных тайлов; в интерфейсе395 автоматически размещённых объектов и26710сырых фрагментов. Визуальное качество не принято: ложные стрелки и пропуски сохраняются. Это текущий результат для проверки, не эталон и не доказанная переносимость. Старые ручные правки сохранены на исходных версиях.
|
||||
@@ -0,0 +1,58 @@
|
||||
# Представления разметки и полный прогон Покровки
|
||||
|
||||
Состояние: 2026-10-30. Опубликована v3 всей доступной Покровки, проверенная через живой API и Chrome. В сырой версии восстановлены наблюдения «А»/перехода; на присланном перекрёстке ложная стрелка заменена полосой. Это **не принятая эталонная разметка**: остаются пропуски и шум, полная точность и переносимость не доказаны. [Текущий отчёт и фактические снимки UI](../outputs/pokrovka-ui-integration-20261030/REPORT.md).
|
||||
|
||||
## Пользовательский договор
|
||||
|
||||
В LAB → Симуляции → Покровка → Семантика переключатель «Версия разметки» показывает:
|
||||
|
||||
- **Сырая алгоритмическая** — контуры детектора, только просмотр. Недоступна, если raw-артефакта ещё нет. Нельзя начать редактирование или сохранить изменения через API. Для просмотра контуры упрощены на 0,02 м; точные бинарные маски остаются на Worker.
|
||||
- **Алгоритмическая** — нормализованные полосы и экземпляры существующего каталога. Редактирование создаёт отдельный черновик от показанной версии, а не изменяет исходный файл.
|
||||
- **Ручная** — появляется только после успешного сохранения реальных правок. Несколько сохранённых веток имеют дату; каждая сохраняет свой исходный SHA. Пустое открытие редактора не создаёт ручную версию.
|
||||
|
||||
Несохранённый черновик явно обозначен, запрещает смену версии, переживает переключение сцены/режима и размонтирование редактора. Escape завершает жест/редактирование, но не удаляет черновик. Удаление несохранённых правок — отдельная подтверждаемая команда. Закрытие страницы защищено beforeunload. Повтор Save после сетевой ошибки использует тот же request_id; конфликт не очищает черновик.
|
||||
|
||||
Сохранённые ручные данные при публикации новой автоматической карты **не перебазируются**. Старые исходные карты остаются адресуемыми по SHA; старый export/receipt также сохраняет исходную историю. На момент публикации Покровка не имела сохранённых ручных ревизий; прежний интерфейс отображал исходную карту и как «ручную».
|
||||
|
||||
В меню проекции доступна команда «Показать сцену целиком» для обзора большого скана. Отдельные классы по-прежнему переключаются легендой. Сравнение с исходной алгоритмической версией доступно у ручной карты/черновика; raw не является редактируемой геометрией.
|
||||
|
||||
## Что именно обработано
|
||||
|
||||
Обработаны все 88 существующих обследованных тайлов этого скана: 4096×4096 RGB на тайл, 60×60 м, 40 м ядро с перекрытием. Это полный доступный набор наблюдений Покровки, включая видимые стороны улицы. 224 позиции `no-surface` не считаются подтверждённым фоном. Невидимые поверхности и стёртые линии не дорисовывались.
|
||||
|
||||
Frozen B0: 2200 проходов 1024×1024 с перекрытием, без обучения. Далее — геометрические кандидаты, проверка каталога/полос, устранение дубликатов, сшивка только при пересечении наблюдений, размещение по Gaussian depth/alpha. Объект без надёжной высоты остаётся 2D unresolved; Z=0 не подставляется. Координаты локальные, внешние карты/GPS и пользовательская геометрия не используются.
|
||||
|
||||
Первая сборка дала 857 размещённых объектов, но визуально выявлены выдуманные стрелки. Исправлен общий выбор гипотез: полосы конкурируют с символом на тех же наблюдениях, отличительные части символа требуют собственного подтверждения. Повторная сборка использовала готовые кандидаты/маски всех 88 тайлов без повторного детектора и обучения.
|
||||
|
||||
Текущая v3: 849 нормализованных объектов, из них 440 размещены в 3D, 409 остаются без надёжной высоты. В 3D: 253 линейных объекта, 108 полос переходов, 14 «А» и 65 стрелок разных классов. Raw: 29693 размещённых фрагмента и 26668 только в 2D; из размещённых 2981 использует проверенную внутреннюю плоскость наблюдения. Исправлены работа с нулевыми весами билинейного чтения и отбрасывание полос с небольшими отверстиями износа. XY исходного наблюдения не заменяется шаблоном. Все 88 тайлов/2200 окон повторно собраны из frozen масок, без обучения и нового inference. Эти числа — объём выхода, **не precision/recall и не число правильных объектов**. Предыдущая v2b (395 объектов, 58 полос переходов) сохранена для отката.
|
||||
|
||||
## Код и API
|
||||
|
||||
- [Клиентская сессия документа](../apps/control-station/src/core/simulation/semanticDocument.ts) — identity, async save/load, idempotency, lifetime черновика.
|
||||
- [React adapter](../apps/control-station/src/components/simulation/useSemanticDocument.ts), [версии](../apps/control-station/src/core/simulation/semanticVersions.ts), [редактор](../apps/control-station/src/components/simulation/SemanticEditor.tsx).
|
||||
- [Хранилище карт](../src/k1link/simulation/ai_polygon/urban_maps.py): immutable files, атомарная публикация raw/algorithmic одним latest.json. Raw: до50k features/32MiB/400k XYZ-вершин; algorithmic: до20k/12MiB/300k XYZ-вершин. Отдельный предел raw сохраняет все контуры полного скана без расширения редактируемой карты.
|
||||
- [Ручные ветки](../src/k1link/simulation/ai_polygon/semantic_edits.py): legacy `<world-sha>.json` сохранён; новые `<world-sha>/branches/<uuid>.json`.
|
||||
- [HTTP](../src/k1link/web/semantic_edits_api.py): GET semantic-versions; GET semantic-edits с `source=raw|algorithmic|manual`, `branch_id`, `model_sha256`; POST semantic-edits сохраняет только editable base. Raw возвращает модель один раз, без дубликата edited; клиентский адаптер использует тот же объект для просмотра.
|
||||
- [Сборщик примитивов](../simulation/semantic-learning/paint_objects.py), [проекция raw](../simulation/semantic-learning/paint_projection.py), [каталог](../src/k1link/simulation/ai_polygon/marking-templates.json).
|
||||
- [Проверки версий](../tests/test_semantic_versions.py), [HTTP](../tests/test_semantic_edits_api.py), [клиентской сессии](../apps/control-station/test/semanticVersions.test.mjs), [геометрии](../tests/test_paint_objects.py).
|
||||
|
||||
## Артефакты и восстановление
|
||||
|
||||
Текущий пакет 30.10: [отчёт](../outputs/pokrovka-ui-integration-20261030/REPORT.md), [validation v3](../outputs/pokrovka-primitive-output-20261029/v3/validation.json), [публикация](../outputs/pokrovka-ui-integration-20261030/publication.json), [API](../outputs/pokrovka-ui-integration-20261030/api-readback.json), [Chrome](../outputs/pokrovka-ui-integration-20261030/ui-acceptance.json), [архив/cleanup](../outputs/pokrovka-ui-integration-20261030/worker-closeout.json). Два снимка из интерфейса — [algorithmic](../outputs/pokrovka-ui-integration-20261030/ui-automatic.jpg) и [raw](../outputs/pokrovka-ui-integration-20261030/ui-raw.jpg). Ниже сохранена история предыдущего пакета 29.10.
|
||||
|
||||
- [Полный отчёт и ограничение качества v2b](../outputs/pokrovka-primitive-output-20261029/REPORT-v2.md).
|
||||
- [Результат и количества](../outputs/pokrovka-primitive-output-20261029/v2b/result.json), [техническая проверка](../outputs/pokrovka-primitive-output-20261029/v2b/validation.json).
|
||||
- [Обзор всего скана](../outputs/pokrovka-primitive-output-20261029/v2b/full-scene-review.jpg), [одинаковые четыре фрагмента source/raw/automatic](../outputs/pokrovka-primitive-output-20261029/v2b/detail-review.jpg).
|
||||
- [Raw JSON](../outputs/pokrovka-primitive-output-20261029/v2b/raw-map.json), [automatic JSON](../outputs/pokrovka-primitive-output-20261029/v2b/automatic-map.json).
|
||||
- [Публикация в интерфейс](../outputs/pokrovka-ui-integration-20261029/publication.json), [HTTP readback](../outputs/pokrovka-ui-integration-20261029/api-readback.json), [предыдущий pointer](../outputs/pokrovka-ui-integration-20261029/previous-pointer.json), [хеши всех ручных файлов до публикации](../outputs/pokrovka-ui-integration-20261029/manual-files-before.json).
|
||||
- [Проверенный архив](../outputs/pokrovka-primitive-output-20261029/archive-verification.json).
|
||||
|
||||
Worker: `D:\NDC_MISSIONCORE\datasets\urban-learning\experiments\pokrovka-primitive-output-20261029`. Большие маски/наблюдения/объекты остаются там; Mac получает карты, код, квитанции и два итоговых JPEG. Временные контейнеры завершены; питание Worker не менялось.
|
||||
|
||||
Опубликованный automatic SHA: `41face498601743fc90b02eeb4dcd8c5f9568e06f1691f0c053251d450a4054a`.
|
||||
Raw SHA: `23e896959fc8a74ee3fdd2ad1bf864fb1dc799780adb802730edb8d9c1c1fe49`.
|
||||
[Предыдущая пара для отката](../outputs/pokrovka-ui-integration-20261030/previous-pointer.json): v2b `214f8931…` / `eb5f448e…`.
|
||||
World SHA: `9660c67c005262646c9777419a4c239984c4d85c1d52a3283313ed771db24a62`.
|
||||
Предыдущая automatic карта сохранена: `09ec7d7311bd358776e192efc70be993314f94a137827636fcd035e1093b6361`.
|
||||
|
||||
Откат публикации — атомарно восстановить сохранённый previous-pointer.json в каталоге этого world, предварительно сверив текущий pointer и отсутствие другой публикации. Ручные ветки/истории при откате не удалять. Маросейка и её правки не менялись.
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Conservative second-pass strip admission using frozen strict automatic seeds.
|
||||
|
||||
Seeds are machine output from the SAME observations, never manual geometry.
|
||||
New candidates cannot become seeds. Existing primitives are retained verbatim.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
import paint_objects as po
|
||||
from paint_geometry import digest
|
||||
from shapely.geometry import LineString, mapping, shape
|
||||
from shapely.ops import unary_union
|
||||
|
||||
|
||||
def strip_contrast(parameters, rgb, matrix):
|
||||
"""Measure paint against EACH lateral flank; a bright-region edge is insufficient.
|
||||
|
||||
All samples belong to the novel fitted part. Missing flank coverage abstains.
|
||||
Coordinates follow the same pixel-centre affine as observation extraction.
|
||||
"""
|
||||
q = np.asarray(parameters["centerline"], dtype=float)
|
||||
if q.shape != (2, 2):
|
||||
return None
|
||||
u = q[1] - q[0]
|
||||
length = np.linalg.norm(u)
|
||||
if length < 0.35:
|
||||
return None
|
||||
u /= length
|
||||
n = np.array([-u[1], u[0]])
|
||||
half = float(parameters["width_m"]) / 2
|
||||
a, b, d, e, x0, y0 = matrix
|
||||
inverse = np.linalg.inv([[a, b], [d, e]])
|
||||
corners = np.array([point + sign * (half + 0.18) * n for point in q for sign in [-1, 1]])
|
||||
uv = (corners - [x0, y0]) @ inverse.T
|
||||
left, top = np.floor(uv.min(0)).astype(int)
|
||||
right, bottom = np.ceil(uv.max(0)).astype(int)
|
||||
if left < 0 or top < 0 or right > rgb.shape[1] or bottom > rgb.shape[0]:
|
||||
return None
|
||||
yy, xx = np.mgrid[top:bottom, left:right]
|
||||
X = a * (xx + 0.5) + b * (yy + 0.5) + x0 - q[0, 0]
|
||||
Y = d * (xx + 0.5) + e * (yy + 0.5) + y0 - q[0, 1]
|
||||
along = X * u[0] + Y * u[1]
|
||||
across = X * n[0] + Y * n[1]
|
||||
interior = (along > 0.05) & (along < length - 0.05)
|
||||
masks = [
|
||||
interior & (np.abs(across) < half),
|
||||
interior & (across > half + 0.06) & (across < half + 0.18),
|
||||
interior & (across < -half - 0.06) & (across > -half - 0.18),
|
||||
]
|
||||
if any(mask.sum() < 4 for mask in masks):
|
||||
return None
|
||||
lum = rgb[top:bottom, left:right].astype(float).mean(axis=2) / 255
|
||||
values = [float(np.median(lum[mask])) for mask in masks]
|
||||
contrasts = [values[0] - v for v in values[1:]]
|
||||
return dict(
|
||||
contrast=min(contrasts),
|
||||
flank_contrasts=contrasts,
|
||||
sample_counts=[int(m.sum()) for m in masks],
|
||||
)
|
||||
|
||||
|
||||
def line_relation(candidate, seed):
|
||||
a = np.asarray(candidate["parameters"]["centerline"], dtype=float)
|
||||
b = np.asarray(seed["parameters"]["centerline"], dtype=float)
|
||||
if len(a) != 2 or len(b) != 2:
|
||||
return False
|
||||
u = a[1] - a[0]
|
||||
v = b[1] - b[0]
|
||||
length = np.linalg.norm(u)
|
||||
other = np.linalg.norm(v)
|
||||
if min(length, other) < 1e-6:
|
||||
return False
|
||||
u /= length
|
||||
v /= other
|
||||
if abs(u @ v) < math.cos(math.radians(5)):
|
||||
return False
|
||||
width = candidate["parameters"]["width_m"]
|
||||
sw = seed["parameters"]["width_m"]
|
||||
if not 0.75 <= width / sw <= 1.333:
|
||||
return False
|
||||
n = np.array([-v[1], v[0]])
|
||||
if np.max(np.abs((a - b[0]) @ n)) > max(0.08, 0.5 * sw):
|
||||
return False
|
||||
# Classification may continue only the same observed paint, not a nearby
|
||||
# parallel stripe or a chain across an unobserved interval.
|
||||
observed = shape(candidate["observation_geometry"])
|
||||
seed_observed = shape(seed["observation_geometry"])
|
||||
if observed.intersection(seed_observed).area <= 1e-6:
|
||||
return False
|
||||
projected = (a - b[0]) @ v
|
||||
return projected.min() < -0.1 or projected.max() > other + 0.1
|
||||
|
||||
|
||||
def crosswalk_support(candidate, groups):
|
||||
q = np.asarray(candidate["parameters"]["centerline"], dtype=float)
|
||||
if len(q) != 2:
|
||||
return []
|
||||
length = np.linalg.norm(q[1] - q[0])
|
||||
width = candidate["parameters"]["width_m"]
|
||||
if length < 1e-6:
|
||||
return []
|
||||
direction = (q[1] - q[0]) / length
|
||||
center = q.mean(0)
|
||||
for g in groups:
|
||||
bars = g["bars"]
|
||||
u = g["direction"]
|
||||
n = g["normal"]
|
||||
offsets = g["offsets"]
|
||||
step = g["step_m"]
|
||||
if abs(direction @ u) < math.cos(math.radians(8)):
|
||||
continue
|
||||
if not 0.8 < length / np.median([b[3] for b in bars]) < 1.25:
|
||||
continue
|
||||
if not 0.7 < width / np.median([b[0]["parameters"]["width_m"] for b in bars]) < 1.43:
|
||||
continue
|
||||
if abs(center @ u - np.median([b[1] @ u for b in bars])) >= 0.5:
|
||||
continue
|
||||
across = center @ n
|
||||
if not offsets.min() - step * 1.18 <= across <= offsets.max() + step * 1.18:
|
||||
continue
|
||||
if abs((across - offsets[0]) / step - round((across - offsets[0]) / step)) > 0.18:
|
||||
continue
|
||||
return [b[0]["id"] for b in bars]
|
||||
return []
|
||||
|
||||
|
||||
def contextual_additions(
|
||||
strict_objects, candidates, *, contrast_fn, experimental_continuations=False
|
||||
):
|
||||
"""Return additions + decisions. Does not edit, replace or reclassify seeds.
|
||||
|
||||
Both input lists are automatically normalized proposals with RGB/surface
|
||||
checks already performed. The qualified default only recovers observed
|
||||
crosswalk bars. Continuation is an explicit research branch: geometric/RGB
|
||||
checks cannot yet distinguish road paint from bright curbs reliably.
|
||||
"""
|
||||
seeds = [
|
||||
o
|
||||
for o in strict_objects
|
||||
if o["placement_status"] == "placed" and o["representation"] == "strip"
|
||||
]
|
||||
catalog = [
|
||||
shape(o["geometry"])
|
||||
for o in strict_objects
|
||||
if o["placement_status"] == "placed" and o["representation"] == "catalog"
|
||||
]
|
||||
groups = po.crosswalk_groups(seeds)
|
||||
seed_by_id = {o["id"]: o for o in seeds}
|
||||
occupied = unary_union(
|
||||
[shape(o["geometry"]) for o in strict_objects if o["placement_status"] == "placed"]
|
||||
)
|
||||
additions = []
|
||||
decisions = []
|
||||
eligible = [
|
||||
o
|
||||
for o in candidates
|
||||
if o["placement_status"] == "placed" and o["representation"] == "strip"
|
||||
]
|
||||
direct = {o["id"]: [s["id"] for s in seeds if line_relation(o, s)] for o in eligible}
|
||||
junction_anchors = [o for o in eligible if direct[o["id"]] and o.get("junction_components")]
|
||||
for original in sorted(candidates, key=lambda o: (-o["fit"]["score"], o["id"])):
|
||||
if original["placement_status"] != "placed" or original["representation"] != "strip":
|
||||
continue
|
||||
q = np.asarray(original["parameters"]["centerline"], dtype=float)
|
||||
if len(q) != 2:
|
||||
continue
|
||||
g = shape(original["geometry"])
|
||||
if g.difference(occupied.buffer(0.04)).area < 0.05 * g.area:
|
||||
continue
|
||||
crossing = crosswalk_support(original, groups)
|
||||
group_id = None
|
||||
if crossing:
|
||||
group_ids = {seed_by_id[i].get("group_id") for i in crossing}
|
||||
if len(group_ids) != 1 or None in group_ids:
|
||||
decisions.append(
|
||||
dict(
|
||||
id=original["id"], accepted=False, reason="ambiguous-strict-crosswalk-group"
|
||||
)
|
||||
)
|
||||
continue
|
||||
group_id = next(iter(group_ids))
|
||||
supporting = direct[original["id"]]
|
||||
junction = []
|
||||
if not crossing and not supporting and original.get("junction_components"):
|
||||
components = set(original["junction_components"])
|
||||
for anchor in junction_anchors:
|
||||
if (
|
||||
components.intersection(anchor["junction_components"])
|
||||
and shape(anchor["geometry"]).distance(g) <= 0.08
|
||||
):
|
||||
junction.extend(direct[anchor["id"]])
|
||||
reason = (
|
||||
"crosswalk-group"
|
||||
if crossing
|
||||
else "observed-continuation"
|
||||
if supporting
|
||||
else "anchored-junction"
|
||||
if junction
|
||||
else None
|
||||
)
|
||||
if reason is not None and reason != "crosswalk-group" and not experimental_continuations:
|
||||
decisions.append(
|
||||
dict(id=original["id"], accepted=False, reason="unqualified-continuation-disabled")
|
||||
)
|
||||
continue
|
||||
if reason is None:
|
||||
decisions.append(
|
||||
dict(id=original["id"], accepted=False, reason="no-independent-strict-context")
|
||||
)
|
||||
continue
|
||||
if any(g.intersection(c).area > 0.05 * g.area for c in catalog):
|
||||
decisions.append(dict(id=original["id"], accepted=False, reason="catalog-conflict"))
|
||||
continue
|
||||
# Keep existing seed geometry exactly. Only the observed, non-overlapping
|
||||
# part of a proposed continuation is added; never extend across a gap.
|
||||
remaining = LineString(q).difference(occupied.buffer(0.02))
|
||||
segments = (
|
||||
[remaining]
|
||||
if remaining.geom_type == "LineString"
|
||||
else list(getattr(remaining, "geoms", []))
|
||||
)
|
||||
accepted = []
|
||||
for segment in segments:
|
||||
if segment.geom_type != "LineString" or segment.length < 0.35:
|
||||
continue
|
||||
params = dict(
|
||||
centerline=[list(segment.coords[0]), list(segment.coords[-1])],
|
||||
width_m=original["parameters"]["width_m"],
|
||||
)
|
||||
fitted = po.strip_geometry(params["centerline"], params["width_m"])
|
||||
if fitted.difference(g.buffer(1e-8)).area > 1e-6:
|
||||
continue
|
||||
support = shape(original["observation_geometry"]).intersection(fitted.buffer(0.06))
|
||||
if support.is_empty:
|
||||
continue
|
||||
metrics = po.agreement(support, fitted, 0.06)
|
||||
immediate = support.intersection(fitted).area / fitted.area
|
||||
if (
|
||||
metrics["score"] < 0.78
|
||||
or metrics["precision"] < 0.85
|
||||
or metrics["recall"] < 0.85
|
||||
or immediate < 0.70
|
||||
):
|
||||
continue
|
||||
rgb = contrast_fn(original, fitted)
|
||||
if rgb is None or rgb["contrast"] < po.Policy().min_luminance_contrast:
|
||||
continue
|
||||
o = copy.deepcopy(original)
|
||||
for key in ("group_id", "observed_bar_count", "crosswalk_parameters"):
|
||||
o.pop(key, None)
|
||||
if crossing:
|
||||
o["group_id"] = group_id
|
||||
o["luminance_contrast"] = rgb["contrast"]
|
||||
o["novel_rgb_evidence"] = rgb
|
||||
o["parameters"] = params
|
||||
o["geometry"] = mapping(fitted)
|
||||
o["observation_geometry"] = mapping(support)
|
||||
o["fit"] = metrics
|
||||
o["novel_unbuffered_support"] = immediate
|
||||
o["context_admission"] = dict(
|
||||
method=reason,
|
||||
seed_ids=sorted(set(crossing or supporting or junction)),
|
||||
candidate_id=original["id"],
|
||||
seeds_frozen=True,
|
||||
)
|
||||
o["id"] = (
|
||||
"object-"
|
||||
+ digest(["contextual-strip-v1", original["id"], params, o["context_admission"]])[
|
||||
:24
|
||||
]
|
||||
)
|
||||
o["kind"] = "crosswalk_bar" if crossing else "linear_marking"
|
||||
additions.append(o)
|
||||
accepted.append(o["id"])
|
||||
occupied = unary_union([occupied, fitted])
|
||||
decisions.append(
|
||||
dict(id=original["id"], accepted=bool(accepted), reason=reason, additions=accepted)
|
||||
)
|
||||
return additions, decisions
|
||||
@@ -20,6 +20,10 @@ MAX_EDITOR_RINGS = 128
|
||||
MAX_EDITOR_WORK = 2_000_000
|
||||
|
||||
|
||||
class ComponentRefusal(ValueError):
|
||||
"""Expected local geometry/support failure; never a sampler/source exception."""
|
||||
|
||||
|
||||
def digest(value):
|
||||
return hashlib.sha256(
|
||||
json.dumps(value, sort_keys=True, allow_nan=False, separators=(",", ":")).encode()
|
||||
@@ -114,15 +118,7 @@ def vectorize(labels, *, pixel_to_scene, source_id):
|
||||
return result
|
||||
|
||||
|
||||
def editor_features(proposal, *, height_at, height_source):
|
||||
"""Validate and lift exact components, WITHOUT inferring a subtype/template/group.
|
||||
|
||||
Caller supplies observed surface heights at the returned XY vertices. There
|
||||
is no flat/nearest-height fallback. This creates features only: the caller
|
||||
must independently verify scene identity/admission before any map import.
|
||||
"""
|
||||
from k1link.simulation.ai_polygon.semantic_edits import validate_holes, validate_path
|
||||
|
||||
def _editor_preflight(proposal, height_source):
|
||||
payload = {k: v for k, v in proposal.items() if k != "proposal_sha256"}
|
||||
if proposal.get("schema_version") != SCHEMA or digest(payload) != proposal.get(
|
||||
"proposal_sha256"
|
||||
@@ -136,6 +132,11 @@ def editor_features(proposal, *, height_at, height_source):
|
||||
vertices = 0
|
||||
if len(proposal["features"]) > 20000:
|
||||
raise ValueError("Editor feature budget exceeded")
|
||||
identifiers = [f.get("id") for f in proposal["features"]]
|
||||
if any(not isinstance(i, str) or not i for i in identifiers) or len(
|
||||
set(identifiers)
|
||||
) != len(identifiers):
|
||||
raise ValueError("Missing or duplicate component identity")
|
||||
for raw in proposal["features"]:
|
||||
geo = raw["geometry"]
|
||||
if geo["type"] != "Polygon":
|
||||
@@ -150,23 +151,43 @@ def editor_features(proposal, *, height_at, height_source):
|
||||
work += edges * edges
|
||||
if vertices > 300000 or work > MAX_EDITOR_WORK:
|
||||
raise ValueError("Editor validation work budget exceeded; no lossy fallback")
|
||||
|
||||
|
||||
def editor_features(proposal, *, height_at, height_source):
|
||||
"""Strict all-or-nothing lift, WITHOUT inferring a subtype/template/group.
|
||||
|
||||
Caller supplies observed surface heights at the returned XY vertices. There
|
||||
is no flat/nearest-height fallback. This creates features only: the caller
|
||||
must independently verify scene identity/admission before any map import.
|
||||
"""
|
||||
from k1link.simulation.ai_polygon.semantic_edits import validate_holes, validate_path
|
||||
|
||||
_editor_preflight(proposal, height_source)
|
||||
result = []
|
||||
for raw in proposal["features"]:
|
||||
feature = copy.deepcopy(raw)
|
||||
geometry = feature["geometry"]
|
||||
if geometry["type"] != "Polygon" or not shape(geometry).is_valid:
|
||||
raise ValueError("Unsupported editor geometry")
|
||||
raise ComponentRefusal("Unsupported editor geometry")
|
||||
rings = []
|
||||
for ring in geometry["coordinates"]:
|
||||
xy = np.asarray(ring[:-1], dtype=float)
|
||||
z = np.asarray(height_at(xy.copy()), dtype=float)
|
||||
if z.shape != (len(xy),) or not np.isfinite(z).all():
|
||||
raise ValueError("Missing observed height support")
|
||||
if z.shape != (len(xy),):
|
||||
raise ValueError("Height callback returned an invalid shape")
|
||||
if not np.isfinite(z).all():
|
||||
raise ComponentRefusal("Missing observed height support")
|
||||
points = np.column_stack([xy, z]).tolist()
|
||||
points.append(points[0][:])
|
||||
validate_path(points, True)
|
||||
try:
|
||||
validate_path(points, True)
|
||||
except ValueError as error:
|
||||
raise ComponentRefusal(str(error)) from error
|
||||
rings.append(points)
|
||||
validate_holes(rings)
|
||||
try:
|
||||
validate_holes(rings)
|
||||
except ValueError as error:
|
||||
raise ComponentRefusal(str(error)) from error
|
||||
feature["geometry"]["coordinates"] = rings
|
||||
feature["properties"].update({
|
||||
"class": "road_marking", "authority": "observation-only",
|
||||
@@ -176,3 +197,33 @@ def editor_features(proposal, *, height_at, height_source):
|
||||
})
|
||||
result.append(feature)
|
||||
return result
|
||||
|
||||
|
||||
def editor_components(proposal, *, height_at, height_source):
|
||||
"""Explicit partial lift; every original component is admitted OR deferred.
|
||||
|
||||
Integrity and total resource bounds remain atomic, before any sampling.
|
||||
A component-level geometry/height refusal keeps the exact original 2-D
|
||||
feature and reason. No vertex removal, repair, height inference or semantic
|
||||
class inference occurs. Admission is NOT confirmation of road paint.
|
||||
The caller must retain/display deferred data alongside admitted features.
|
||||
"""
|
||||
_editor_preflight(proposal, height_source)
|
||||
admitted, deferred = [], []
|
||||
for raw in proposal["features"]:
|
||||
single = {k: v for k, v in proposal.items() if k != "proposal_sha256"}
|
||||
single["features"] = [raw]
|
||||
single["proposal_sha256"] = digest(single)
|
||||
try:
|
||||
admitted.extend(editor_features(
|
||||
single, height_at=height_at, height_source=height_source
|
||||
))
|
||||
except ComponentRefusal as error:
|
||||
deferred.append(dict(feature=copy.deepcopy(raw), reason=str(error)))
|
||||
return dict(
|
||||
schema_version="missioncore.paint-editor-admission/v1",
|
||||
proposal_sha256=proposal["proposal_sha256"],
|
||||
source_sha256=proposal["source_sha256"], height_source=height_source,
|
||||
features=admitted, deferred=deferred,
|
||||
complete=not deferred, review_status="unreviewed",
|
||||
)
|
||||
|
||||
@@ -0,0 +1,855 @@
|
||||
"""Bounded paint observations -> editable primitives and catalog instances.
|
||||
|
||||
No map, annotation, street name, or world position is a recognition feature.
|
||||
Fit scores measure agreement, not calibrated semantic confidence. Unsupported
|
||||
observations stay unresolved; raw contours are never an output fallback.
|
||||
"""
|
||||
|
||||
import json
|
||||
import math
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
import numpy as np
|
||||
from paint_geometry import digest, vectorize
|
||||
from scipy.ndimage import binary_closing
|
||||
from scipy.optimize import minimize
|
||||
from shapely import affinity, intersects_xy
|
||||
from shapely.geometry import LineString, Polygon, box, mapping, shape
|
||||
from shapely.ops import transform, unary_union
|
||||
from shapely.strtree import STRtree
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Policy:
|
||||
min_area_m2: float = 0.035
|
||||
min_length_m: float = 0.35
|
||||
min_width_m: float = 0.06
|
||||
max_strip_width_m: float = 1.0
|
||||
rectangle_fill: float = 0.72
|
||||
shape_tolerance_m: float = 0.06
|
||||
min_symbol_score: float = 0.68
|
||||
min_symbol_precision: float = 0.65
|
||||
min_symbol_recall: float = 0.65
|
||||
min_class_margin: float = 0.035
|
||||
min_luminance_contrast: float = 0.025
|
||||
max_candidates: int = 512
|
||||
max_symbol_fits: int = 48
|
||||
max_strip_hole_fraction: float = 0.10
|
||||
min_unanchored_wear_length_m: float = 3.0
|
||||
|
||||
|
||||
def parts(geometry):
|
||||
return [geometry] if geometry.geom_type == "Polygon" else list(geometry.geoms)
|
||||
|
||||
|
||||
def rectangle(geometry):
|
||||
q = np.asarray(geometry.minimum_rotated_rectangle.exterior.coords)[:4, :2]
|
||||
edges = np.roll(q, -1, axis=0) - q
|
||||
lengths = np.linalg.norm(edges, axis=1)
|
||||
i = int(np.argmax(lengths))
|
||||
u = edges[i] / lengths[i]
|
||||
return q.mean(0), float(math.atan2(u[1], u[0])), float(max(lengths)), float(min(lengths))
|
||||
|
||||
|
||||
def strip_geometry(centerline, width):
|
||||
return LineString(centerline).buffer(width / 2, cap_style=2, join_style=2)
|
||||
|
||||
|
||||
def catalog_geometry(template, center, angle, scale):
|
||||
g = unary_union([Polygon(p[0], p[1:]) for p in template["polygons"]])
|
||||
lo, bottom, hi, top = g.bounds
|
||||
g = affinity.translate(g, -(lo + hi) / 2, -(bottom + top) / 2)
|
||||
g = affinity.scale(g, xfact=scale, yfact=scale, origin=(0, 0))
|
||||
g = affinity.rotate(g, angle, origin=(0, 0), use_radians=True)
|
||||
return affinity.translate(g, *center)
|
||||
|
||||
|
||||
def reconstruct(obj, catalog):
|
||||
"""Regenerate product geometry from compact parameters, never raw vertices."""
|
||||
p = obj["parameters"]
|
||||
if obj["representation"] == "strip":
|
||||
return strip_geometry(p["centerline"], p["width_m"])
|
||||
template = next(t for t in catalog["templates"] if t["id"] == p["template_id"])
|
||||
return catalog_geometry(template, p["center"], p["angle_radians"], p["scale"])
|
||||
|
||||
|
||||
def agreement(observed, fitted, tolerance, *, observed_buffer=None):
|
||||
# Pure geometry reuse: identical observed polygon and tolerance throughout a fit.
|
||||
buffered = observed.buffer(tolerance) if observed_buffer is None else observed_buffer
|
||||
precision = fitted.intersection(buffered).area / max(fitted.area, 1e-9)
|
||||
recall = observed.intersection(fitted.buffer(tolerance)).area / max(observed.area, 1e-9)
|
||||
overlap = observed.intersection(fitted).area / max(observed.union(fitted).area, 1e-9)
|
||||
f1 = 2 * precision * recall / max(precision + recall, 1e-9)
|
||||
return dict(precision=precision, recall=recall, overlap=overlap, score=0.6 * f1 + 0.4 * overlap)
|
||||
|
||||
|
||||
def contrast(geometry, rgb, matrix):
|
||||
"""Local RGB evidence, not a claim that all bright rectangles are road paint."""
|
||||
a, b, d, e, x0, y0 = matrix
|
||||
inverse = np.linalg.inv([[a, b], [d, e]])
|
||||
q = np.asarray(geometry.envelope.exterior.coords)[:, :2]
|
||||
uv = (q - [x0, y0]) @ inverse.T
|
||||
padding = int(math.ceil(0.18 / min(np.hypot(a, d), np.hypot(b, e)))) + 2
|
||||
left, top = np.maximum(np.floor(uv.min(0)).astype(int) - padding, 0)
|
||||
right, bottom = np.minimum(np.ceil(uv.max(0)).astype(int) + padding, rgb.shape[1::-1])
|
||||
if right <= left or bottom <= top:
|
||||
return None
|
||||
yy, xx = np.mgrid[top:bottom, left:right]
|
||||
X = a * (xx + 0.5) + b * (yy + 0.5) + x0
|
||||
Y = d * (xx + 0.5) + e * (yy + 0.5) + y0
|
||||
inside = intersects_xy(geometry, X, Y)
|
||||
outside = intersects_xy(geometry.buffer(0.18).difference(geometry.buffer(0.06)), X, Y)
|
||||
if inside.sum() < 4 or outside.sum() < 4:
|
||||
return None
|
||||
lum = rgb[top:bottom, left:right].astype(float).mean(axis=2) / 255
|
||||
return float(np.median(lum[inside]) - np.median(lum[outside]))
|
||||
|
||||
|
||||
def fit_strip(p, policy):
|
||||
center, angle, length, width = rectangle(p)
|
||||
if length < policy.min_length_m or width < policy.min_width_m:
|
||||
return None
|
||||
# Wear is a shape hypothesis only: retain the original observation for all
|
||||
# agreement checks. Large/elongated negative spaces remain real structure.
|
||||
shell = Polygon(p.exterior)
|
||||
if p.interiors and (
|
||||
(shell.area - p.area) / max(shell.area, 1e-9) > policy.max_strip_hole_fraction
|
||||
or any(rectangle(Polygon(h))[2] > width for h in p.interiors)
|
||||
):
|
||||
return None
|
||||
u = np.array([math.cos(angle), math.sin(angle)])
|
||||
if (
|
||||
width <= policy.max_strip_width_m
|
||||
and length / width >= 3
|
||||
and p.area / (length * width) >= policy.rectangle_fill
|
||||
):
|
||||
line = [center - u * length / 2, center + u * length / 2]
|
||||
return dict(centerline=np.asarray(line).tolist(), width_m=width)
|
||||
# Reuse the existing centreline/cross-section approach. Explicit refusal
|
||||
# replaces its historical raw-polygon fallback; real bends need few knots.
|
||||
if length < 1.5 or length / max(width, 0.01) < 3:
|
||||
return None
|
||||
n = np.array([-u[1], u[0]])
|
||||
stations = np.linspace(
|
||||
-length / 2 + 0.03, length / 2 - 0.03, max(8, min(256, int(length / 0.10)))
|
||||
)
|
||||
centers, widths = [], []
|
||||
for t in stations:
|
||||
cross = shell.intersection(
|
||||
LineString(center + t * u + np.array([-width - 1, width + 1])[:, None] * n)
|
||||
)
|
||||
if cross.geom_type != "LineString" or cross.length < 0.025:
|
||||
continue
|
||||
centers.append(cross.interpolate(0.5, normalized=True).coords[0][:2])
|
||||
widths.append(cross.length)
|
||||
if len(centers) < max(8, 0.9 * len(stations)):
|
||||
return None
|
||||
points = np.asarray(centers)
|
||||
tangent = np.gradient(points, axis=0)
|
||||
tangent /= np.maximum(np.linalg.norm(tangent, axis=1)[:, None], 1e-9)
|
||||
widths = np.asarray(widths) * np.abs(tangent @ u)
|
||||
w = float(np.median(widths))
|
||||
if not policy.min_width_m <= w <= 0.65:
|
||||
return None
|
||||
variable_width = np.ptp(np.quantile(widths, [0.1, 0.9])) > 0.5 * w
|
||||
# Prefer a rectangle when the observed strip supports one. Boundary nicks
|
||||
# must not force needless bends into an otherwise straight crossing bar.
|
||||
offset = float(np.median((points - center) @ n))
|
||||
straight = [center + offset * n - u * length / 2, center + offset * n + u * length / 2]
|
||||
rectangle_fit = strip_geometry(straight, w)
|
||||
if (
|
||||
(not variable_width or length >= policy.min_unanchored_wear_length_m)
|
||||
and agreement(p, rectangle_fit, policy.shape_tolerance_m)["score"] >= 0.78
|
||||
and p.hausdorff_distance(rectangle_fit) <= 0.25
|
||||
):
|
||||
return dict(centerline=np.asarray(straight).tolist(), width_m=w)
|
||||
# A worn straight stripe can have variable cross-sections while its full
|
||||
# rectangular explanation is strong. Width consistency constrains the bent
|
||||
# fallback, not the already verified straight candidate above.
|
||||
if variable_width:
|
||||
return None
|
||||
line = LineString(points).simplify(policy.shape_tolerance_m)
|
||||
if not line.is_simple or len(line.coords) > 12:
|
||||
return None
|
||||
g = strip_geometry(list(line.coords), w)
|
||||
if agreement(p, g, policy.shape_tolerance_m)["score"] < 0.78 or p.hausdorff_distance(g) > 0.25:
|
||||
return None
|
||||
return dict(centerline=[list(q) for q in line.coords], width_m=w)
|
||||
|
||||
|
||||
def fit_junction_strips(p, policy):
|
||||
"""Explain thin, near-orthogonal junctions with a few observed rectangles.
|
||||
|
||||
Long boundary directions propose axes, not coordinates or road rules.
|
||||
Require local support for every arm AND agreement of the complete union.
|
||||
A shaft alone cannot explain a missing arrow head or other residual shape.
|
||||
"""
|
||||
if p.area < .3 or len(p.interiors) > 8:
|
||||
return []
|
||||
_, _, length, width = rectangle(p)
|
||||
if width < 1 or p.area / max(length * width, 1e-9) > .6:
|
||||
return []
|
||||
q = np.asarray(p.simplify(.08, preserve_topology=True).exterior.coords)[:, :2]
|
||||
edges = np.diff(q, axis=0)
|
||||
modes = []
|
||||
for v in sorted(edges, key=lambda v: -float(np.linalg.norm(v))):
|
||||
length = float(np.linalg.norm(v))
|
||||
if length < 1.5:
|
||||
continue
|
||||
u = v / length
|
||||
if not any(abs(u @ old) > math.cos(math.radians(10)) for old in modes):
|
||||
modes.append(u)
|
||||
if len(modes) == 4:
|
||||
break
|
||||
pairs = [(u, v) for i, u in enumerate(modes) for v in modes[i+1:]
|
||||
if abs(u @ v) < math.sin(math.radians(10))]
|
||||
if not pairs:
|
||||
return []
|
||||
for axes in pairs:
|
||||
proposals = []
|
||||
directions = []
|
||||
for axis_index, u in enumerate(axes):
|
||||
n = np.array([-u[1], u[0]])
|
||||
coords = np.asarray(p.exterior.coords)[:, :2]
|
||||
along, across = coords @ u, coords @ n
|
||||
low, high = float(along.min()), float(along.max())
|
||||
count = max(20, min(512, int((high-low)/.08)))
|
||||
step = (high-low) / count
|
||||
samples = []
|
||||
for t in np.linspace(low+step/2, high-step/2, count):
|
||||
cross = p.intersection(LineString([u*t+n*(across.min()-1),
|
||||
u*t+n*(across.max()+1)]))
|
||||
segments = ([cross] if cross.geom_type == "LineString"
|
||||
else getattr(cross, "geoms", []))
|
||||
for segment in segments:
|
||||
if (segment.geom_type != "LineString"
|
||||
or not policy.min_width_m <= segment.length <= .65):
|
||||
continue
|
||||
mid = np.asarray(segment.interpolate(.5, normalized=True).coords[0])[:2]
|
||||
samples.append((float(mid @ n), t, segment.length))
|
||||
samples.sort()
|
||||
clusters = []
|
||||
for sample in samples:
|
||||
if not clusters or sample[0]-clusters[-1][-1][0] > .10:
|
||||
clusters.append([])
|
||||
clusters[-1].append(sample)
|
||||
for cluster in clusters:
|
||||
c = np.asarray(cluster)
|
||||
if len(c) < 16:
|
||||
continue
|
||||
offset, width = float(np.median(c[:, 0])), float(np.median(c[:, 2]))
|
||||
if np.ptp(np.quantile(c[:, 0], [.1,.9])) > width/2:
|
||||
continue
|
||||
ordered = c[np.argsort(c[:, 1])]
|
||||
# A wide junction may omit a few cross-sections, not a real gap.
|
||||
splits = np.where(np.diff(ordered[:, 1]) > max(.25, 2*width))[0]+1
|
||||
for run in np.split(ordered, splits):
|
||||
lo, hi = float(run[:,1].min()-step/2), float(run[:,1].max()+step/2)
|
||||
if len(run) < 16 or hi-lo < 1.5 or hi-lo < 4*width:
|
||||
continue
|
||||
line = [u*lo+n*offset, u*hi+n*offset]
|
||||
fitted = strip_geometry(line,width)
|
||||
holes = [Polygon(h) for h in p.interiors if Polygon(h).intersects(fitted)]
|
||||
if (any(rectangle(h)[2] > width for h in holes)
|
||||
or sum(h.intersection(fitted).area for h in holes)
|
||||
> policy.max_strip_hole_fraction * fitted.area):
|
||||
continue
|
||||
# Every interior longitudinal interval needs observed paint.
|
||||
# A wide junction has support; a true gap stays an interval
|
||||
# gap even when the enclosing component is connected elsewhere.
|
||||
intervals = []
|
||||
for piece in parts(p.intersection(fitted)):
|
||||
if piece.geom_type == "Polygon" and piece.area > 0:
|
||||
projections = np.asarray(piece.exterior.coords)[:, :2] @ u
|
||||
intervals.append((float(projections.min()),float(projections.max())))
|
||||
end = lo+step
|
||||
continuous = True
|
||||
for begin, finish in sorted(intervals):
|
||||
if finish < end:
|
||||
continue
|
||||
if begin > end+1e-6:
|
||||
continuous = False
|
||||
break
|
||||
end = max(end,finish)
|
||||
if not continuous or end < hi-step:
|
||||
continue
|
||||
if fitted.intersection(p).area/fitted.area < .70:
|
||||
continue
|
||||
local = p.intersection(fitted.buffer(policy.shape_tolerance_m))
|
||||
if agreement(local,fitted,policy.shape_tolerance_m)["score"] < .78:
|
||||
continue
|
||||
proposals.append(dict(centerline=np.asarray(line).tolist(),width_m=width))
|
||||
directions.append(axis_index)
|
||||
if not 2 <= len(proposals) <= 4 or len(set(directions)) != 2:
|
||||
continue
|
||||
shapes = [strip_geometry(x["centerline"],x["width_m"]) for x in proposals]
|
||||
fitted = unary_union(shapes)
|
||||
if not fitted.is_valid or not all(any(i != j and a.intersects(b.buffer(.08))
|
||||
for j,b in enumerate(shapes)) for i,a in enumerate(shapes)):
|
||||
continue
|
||||
metrics = agreement(p,fitted,policy.shape_tolerance_m)
|
||||
if (metrics["score"] >= .78 and metrics["recall"] >= .90
|
||||
and metrics["precision"] >= .85 and p.hausdorff_distance(fitted) <= .25):
|
||||
return proposals
|
||||
return []
|
||||
|
||||
|
||||
def fit_strips(p, policy):
|
||||
params = fit_strip(p, policy)
|
||||
return [params] if params is not None else fit_junction_strips(p, policy)
|
||||
|
||||
|
||||
def fit_symbol(p, templates, policy, budget):
|
||||
center, angle, length, width = rectangle(p)
|
||||
if not (0.6 < length < 9 and 0.25 < width < 4 and 0.07 < p.area / (length * width) < 0.8):
|
||||
return None, "not-symbol-shaped"
|
||||
observed_buffer = p.buffer(policy.shape_tolerance_m)
|
||||
|
||||
def metrics_for(g):
|
||||
return agreement(p, g, policy.shape_tolerance_m, observed_buffer=observed_buffer)
|
||||
|
||||
hypotheses = []
|
||||
for template in templates:
|
||||
base = catalog_geometry(template, [0, 0], 0, 1)
|
||||
_, _, L, W = rectangle(base)
|
||||
if not 0.65 < (length / width) / (L / W) < 1.5:
|
||||
continue
|
||||
scale = math.sqrt(length * width / (L * W))
|
||||
for flip in (0, math.pi):
|
||||
x0 = [center[0], center[1], angle + flip, scale]
|
||||
g = catalog_geometry(template, x0[:2], x0[2], x0[3])
|
||||
score = metrics_for(g)["score"]
|
||||
hypotheses.append((score, template, x0))
|
||||
# Bound optimization work per frame and per object, including bad inputs.
|
||||
fits = []
|
||||
for initial, template, x0 in sorted(hypotheses, key=lambda h: -h[0])[:4]:
|
||||
if initial < 0.35:
|
||||
continue
|
||||
if budget[0] >= policy.max_symbol_fits:
|
||||
return None, "symbol-fit-budget"
|
||||
budget[0] += 1
|
||||
bounds = [
|
||||
(x0[0] - 0.25, x0[0] + 0.25),
|
||||
(x0[1] - 0.25, x0[1] + 0.25),
|
||||
(x0[2] - 0.20, x0[2] + 0.20),
|
||||
(x0[3] * 0.8, x0[3] * 1.2),
|
||||
]
|
||||
|
||||
def objective(x, template=template):
|
||||
return 1 - metrics_for(catalog_geometry(template, x[:2], x[2], x[3]))["score"]
|
||||
|
||||
result = minimize(
|
||||
objective,
|
||||
x0,
|
||||
method="Powell",
|
||||
bounds=bounds,
|
||||
options=dict(maxiter=12, maxfev=240, xtol=0.002, ftol=0.002),
|
||||
)
|
||||
# The initial candidate remains admissible when the bounded optimizer
|
||||
# terminates early; the final measured evidence gates still apply.
|
||||
x = result.x if result.fun < objective(x0) else x0
|
||||
g = catalog_geometry(template, x[:2], x[2], x[3])
|
||||
metrics = metrics_for(g)
|
||||
fits.append((metrics["score"], template, list(x), metrics))
|
||||
fits.sort(key=lambda f: -f[0])
|
||||
if not fits:
|
||||
return None, "no-template-supported"
|
||||
_, template, x, metrics = fits[0]
|
||||
runner = next((f[0] for f in fits[1:] if f[1]["id"] != template["id"]), 0)
|
||||
if (
|
||||
metrics["score"] < policy.min_symbol_score
|
||||
or metrics["precision"] < policy.min_symbol_precision
|
||||
or metrics["recall"] < policy.min_symbol_recall
|
||||
):
|
||||
return None, "insufficient-template-support"
|
||||
if metrics["score"] - runner < policy.min_class_margin:
|
||||
return None, "ambiguous-template-class"
|
||||
g = catalog_geometry(template, x[:2], x[2], x[3])
|
||||
holes = unary_union([Polygon(h) for part in parts(g) for h in part.interiors])
|
||||
if not holes.is_empty and holes.intersection(p).area / max(holes.area, 1e-9) > 0.25:
|
||||
return None, "template-negative-space-conflict"
|
||||
params = dict(template_id=template["id"], center=x[:2], angle_radians=x[2], scale=x[3])
|
||||
return (params, metrics), None
|
||||
|
||||
|
||||
|
||||
def arbitrate_symbol(observed, fitted, policy, *, center, angle, rgb, pixel_to_scene):
|
||||
"""Compare on identical evidence; every local template part needs actual paint.
|
||||
|
||||
The 3x3 partition lives in the fitted template frame, never scene coordinates.
|
||||
Local precision permits at most half a native pixel diagonal of uncertainty.
|
||||
Each part also needs an unbuffered witness, so that uncertainty cannot conceal
|
||||
a wholly absent small arrowhead. Existing global tolerance remains unchanged.
|
||||
No per-class, per-scale, per-location, or learned acceptance threshold is used.
|
||||
"""
|
||||
local = affinity.rotate(
|
||||
affinity.translate(fitted, -center[0], -center[1]),
|
||||
-angle,
|
||||
origin=(0, 0),
|
||||
use_radians=True,
|
||||
)
|
||||
xs = np.linspace(local.bounds[0], local.bounds[2], 4)
|
||||
ys = np.linspace(local.bounds[1], local.bounds[3], 4)
|
||||
a, b, d, e, _, _ = pixel_to_scene
|
||||
pixel_radius = 0.5 * max(np.hypot(a + b, d + e), np.hypot(a - b, d - e))
|
||||
local_tolerance = min(policy.shape_tolerance_m, pixel_radius)
|
||||
# Intersect in the normalized frame: rotating clipped fragments back into
|
||||
# world space can create degenerate hole/shell contacts through roundoff.
|
||||
local_observed = affinity.rotate(
|
||||
affinity.translate(observed, -center[0], -center[1]),
|
||||
-angle, origin=(0, 0), use_radians=True,
|
||||
)
|
||||
supported = local_observed.buffer(local_tolerance)
|
||||
support = []
|
||||
for iy in range(3):
|
||||
for ix in range(3):
|
||||
piece = local.intersection(box(xs[ix], ys[iy], xs[ix + 1], ys[iy + 1]))
|
||||
if piece.area <= 1e-12:
|
||||
continue
|
||||
support.append(
|
||||
dict(cell=[ix, iy], area_m2=piece.area,
|
||||
precision=piece.intersection(supported).area / piece.area,
|
||||
unbuffered_precision=piece.intersection(local_observed).area / piece.area)
|
||||
)
|
||||
strips = []
|
||||
for component in parts(observed):
|
||||
params = fit_strip(component, policy) if component.area >= policy.min_area_m2 else None
|
||||
if params is None:
|
||||
continue
|
||||
g = strip_geometry(params["centerline"], params["width_m"])
|
||||
delta = contrast(g, rgb, pixel_to_scene)
|
||||
if delta is not None and delta >= policy.min_luminance_contrast:
|
||||
strips.append(g)
|
||||
symbol_score = agreement(observed, fitted, policy.shape_tolerance_m)["score"]
|
||||
competitor = (
|
||||
agreement(observed, unary_union(strips), policy.shape_tolerance_m) if strips else None
|
||||
)
|
||||
audit = dict(
|
||||
template_partition="3x3-in-template-frame",
|
||||
local_support_buffer_m=local_tolerance,
|
||||
unbuffered_witness_required=True,
|
||||
min_required_precision=policy.min_symbol_precision,
|
||||
parts=support,
|
||||
symbol_score=symbol_score,
|
||||
strip_competitor=competitor,
|
||||
min_required_margin=policy.min_class_margin,
|
||||
)
|
||||
if not support or any(
|
||||
p["precision"] < policy.min_symbol_precision or p["unbuffered_precision"] <= 1e-12
|
||||
for p in support
|
||||
):
|
||||
return audit, "unsupported-template-part"
|
||||
if competitor is not None and symbol_score - competitor["score"] < policy.min_class_margin:
|
||||
return audit, "strip-competitor-not-beaten"
|
||||
return audit, None
|
||||
|
||||
|
||||
def crosswalk_groups(objects):
|
||||
"""Deterministic groups of independent, parallel observed bars.
|
||||
|
||||
Compare direction/length against an anchor, not a transitive angle chain.
|
||||
Overlapping windows of one bar cannot supply independent votes.
|
||||
"""
|
||||
bars = []
|
||||
for obj in sorted(objects, key=lambda o: o["id"]):
|
||||
if obj["representation"] != "strip" or len(obj["parameters"]["centerline"]) != 2:
|
||||
continue
|
||||
p = obj["parameters"]
|
||||
q = np.asarray(p["centerline"])
|
||||
length = np.linalg.norm(q[1] - q[0])
|
||||
if 0.28 <= p["width_m"] <= 1 and 1.5 <= length <= 8:
|
||||
bars.append((obj, q.mean(0), (q[1] - q[0]) / length, length))
|
||||
remaining = set(range(len(bars)))
|
||||
groups = []
|
||||
while remaining:
|
||||
seed = min(remaining)
|
||||
remaining.remove(seed)
|
||||
first, center, u, length = bars[seed]
|
||||
n = np.array([-u[1], u[0]])
|
||||
aligned = [seed] + [j for j in sorted(remaining) if
|
||||
abs(u @ bars[j][2]) > math.cos(math.radians(8))
|
||||
and abs((bars[j][1] - center) @ u) < 0.5
|
||||
and 0.8 < bars[j][3] / length < 1.25
|
||||
and 0.7 < bars[j][0]["parameters"]["width_m"] / first["parameters"]["width_m"] < 1.43]
|
||||
aligned.sort(key=lambda j: float(bars[j][1] @ n))
|
||||
clusters, current = [], []
|
||||
for j in aligned:
|
||||
if current and float((bars[j][1] - bars[current[-1]][1]) @ n) > 2 + 1e-6:
|
||||
clusters.append(current)
|
||||
current = []
|
||||
# Duplicate support or nearly coincident bars never count twice.
|
||||
if current and (float((bars[j][1] - bars[current[-1]][1]) @ n) <= .45
|
||||
or any(set(bars[j][0]["observation_ids"]) & set(bars[i][0]["observation_ids"])
|
||||
for i in current)):
|
||||
continue
|
||||
current.append(j)
|
||||
if current:
|
||||
clusters.append(current)
|
||||
for cluster in clusters:
|
||||
if len(cluster) < 3:
|
||||
continue
|
||||
offsets = np.array([bars[j][1] @ n for j in cluster])
|
||||
gaps = np.diff(offsets)
|
||||
step = float(np.median(gaps[gaps <= np.median(gaps)]))
|
||||
multiples = np.maximum(1, np.rint(gaps / step))
|
||||
if (multiples > 2).any() or (np.abs(gaps - multiples * step) > .18 * step).any():
|
||||
continue
|
||||
remaining.difference_update(cluster)
|
||||
groups.append(dict(bars=[bars[j] for j in cluster], direction=u,
|
||||
normal=n, step_m=step, offsets=offsets))
|
||||
return groups
|
||||
|
||||
|
||||
def group_crosswalks(objects):
|
||||
"""Classify actual bars after reconciliation; no fixed six-bar template."""
|
||||
for obj in objects:
|
||||
for key in ("group_id", "observed_bar_count", "crosswalk_parameters"):
|
||||
obj.pop(key, None)
|
||||
if obj["kind"] == "crosswalk_bar":
|
||||
obj["kind"] = "linear_marking"
|
||||
for group in crosswalk_groups(objects):
|
||||
bars = group["bars"]
|
||||
gid = "crossing-" + digest(sorted(b[0]["id"] for b in bars))[:20]
|
||||
parameters = dict(direction=group["direction"].tolist(), step_m=group["step_m"],
|
||||
median_width_m=float(np.median(
|
||||
[b[0]["parameters"]["width_m"] for b in bars])),
|
||||
median_length_m=float(np.median([b[3] for b in bars])))
|
||||
for obj, *_ in bars:
|
||||
obj.update(kind="crosswalk_bar", group_id=gid, observed_bar_count=len(bars),
|
||||
crosswalk_parameters=parameters)
|
||||
|
||||
|
||||
def recover_crosswalks(objects, observations, *, rgb, pixel_to_scene, policy):
|
||||
"""Recheck rejected observations in an independently supported group frame.
|
||||
|
||||
No synthetic slots: a candidate needs its own area, full observed extent,
|
||||
width, bounded holes, whole-shape agreement and RGB contrast. Recovered
|
||||
candidates do not seed further recovery in this pass.
|
||||
"""
|
||||
groups = crosswalk_groups(objects)
|
||||
used = {i for o in objects for i in o["observation_ids"]}
|
||||
recovered = []
|
||||
for feature in sorted(observations, key=lambda f: f["id"]):
|
||||
if feature["id"] in used:
|
||||
continue
|
||||
p = shape(feature["geometry"])
|
||||
if p.area < policy.min_area_m2:
|
||||
continue
|
||||
for group in groups:
|
||||
u, n, bars = group["direction"], group["normal"], group["bars"]
|
||||
q = np.asarray(p.exterior.coords)[:, :2]
|
||||
along, across = q @ u, q @ n
|
||||
lo, hi = float(along.min()), float(along.max())
|
||||
mid = float((across.min() + across.max()) / 2)
|
||||
length = hi - lo
|
||||
width = float(np.median([b[0]["parameters"]["width_m"] for b in bars]))
|
||||
reference_length = float(np.median([b[3] for b in bars]))
|
||||
offsets, step = group["offsets"], group["step_m"]
|
||||
# Only observed intervals near the demonstrated sequence, never
|
||||
# arbitrary continuation or a tiny spot promoted to a full bar.
|
||||
if not (offsets.min() - step * 1.18 <= mid <= offsets.max() + step * 1.18
|
||||
and .8 < length / reference_length < 1.25
|
||||
and .7 < p.area / max(length * width, 1e-9) < 1.43
|
||||
and np.min(np.abs(offsets - mid)) > .45
|
||||
and abs((mid - offsets[0]) / step - round((mid - offsets[0]) / step)) <= .18
|
||||
and abs((lo + hi) / 2 - np.median([b[1] @ u for b in bars])) < .5):
|
||||
continue
|
||||
shell = Polygon(p.exterior)
|
||||
if p.interiors and ((shell.area - p.area) / shell.area > policy.max_strip_hole_fraction
|
||||
or any(rectangle(Polygon(h))[2] > min(width, rectangle(p)[3])
|
||||
for h in p.interiors)):
|
||||
continue
|
||||
line = [u * lo + n * mid, u * hi + n * mid]
|
||||
fitted = strip_geometry(line, width)
|
||||
metrics = agreement(p, fitted, policy.shape_tolerance_m)
|
||||
if metrics["score"] < .78 or p.hausdorff_distance(fitted) > .25:
|
||||
continue
|
||||
delta = contrast(fitted, rgb, pixel_to_scene)
|
||||
if delta is None or delta < policy.min_luminance_contrast:
|
||||
continue
|
||||
obj = dict(representation="strip", kind="linear_marking",
|
||||
parameters=dict(centerline=np.asarray(line).tolist(), width_m=width),
|
||||
observation_ids=[feature["id"]], fit=metrics, luminance_contrast=delta,
|
||||
support_boundary=feature["properties"]["support_boundary"],
|
||||
recovery=dict(method="observed-crosswalk-group",
|
||||
seed_ids=sorted(b[0]["id"] for b in bars),
|
||||
slot=int(round((mid-offsets[0])/step))))
|
||||
obj["id"] = "object-" + digest(obj)[:24]
|
||||
recovered.append(obj)
|
||||
used.add(feature["id"])
|
||||
break
|
||||
conflicts = set()
|
||||
for i,a in enumerate(recovered):
|
||||
ga = strip_geometry(a["parameters"]["centerline"],a["parameters"]["width_m"])
|
||||
for j,b in enumerate(recovered[:i]):
|
||||
same_slot = (a["recovery"]["seed_ids"] == b["recovery"]["seed_ids"]
|
||||
and a["recovery"]["slot"] == b["recovery"]["slot"])
|
||||
gb = strip_geometry(b["parameters"]["centerline"],b["parameters"]["width_m"])
|
||||
if same_slot or ga.intersection(gb).area > 1e-6:
|
||||
conflicts.update((i,j))
|
||||
return [o for i,o in enumerate(recovered) if i not in conflicts]
|
||||
|
||||
|
||||
def assemble(mask, rgb, *, pixel_to_scene, source_id, catalog, policy=None):
|
||||
policy = policy or Policy()
|
||||
mask = np.asarray(mask)
|
||||
rgb = np.asarray(rgb)
|
||||
if mask.ndim != 2 or mask.dtype.kind not in "biu" or not np.isin(mask, [0, 1]).all():
|
||||
raise ValueError("Binary automatic prediction required; targets/unknown are not inputs")
|
||||
if rgb.shape != mask.shape + (3,) or rgb.dtype != np.uint8:
|
||||
raise ValueError("Matching uint8 RGB evidence required")
|
||||
raw = vectorize(mask, pixel_to_scene=pixel_to_scene, source_id=source_id)
|
||||
if len(raw["features"]) > policy.max_candidates:
|
||||
raise ValueError("Candidate budget exceeded")
|
||||
catalog_sha = digest(catalog)
|
||||
templates = [
|
||||
t
|
||||
for t in catalog["templates"]
|
||||
if not t.get("hidden") and t["id"] not in ("linear_marking", "zebra")
|
||||
]
|
||||
objects, rejected, budget = [], [], [0]
|
||||
# Only symbol proposals may join small wear gaps. Strip intervals use the
|
||||
# original components so neighboring dashes are not closed into one line.
|
||||
cell = min(
|
||||
np.linalg.norm(np.asarray(pixel_to_scene)[[0, 2]]),
|
||||
np.linalg.norm(np.asarray(pixel_to_scene)[[1, 3]]),
|
||||
)
|
||||
radius = max(1, min(8, int(round(0.04 / cell))))
|
||||
closed = binary_closing(mask, iterations=radius, border_value=0)
|
||||
proposals = vectorize(
|
||||
closed.astype(np.uint8),
|
||||
pixel_to_scene=pixel_to_scene,
|
||||
source_id=source_id + "-symbol-proposals",
|
||||
)
|
||||
raw_geometries = [shape(r["geometry"]) for r in raw["features"]]
|
||||
spatial = STRtree(raw_geometries)
|
||||
consumed = set()
|
||||
for f in sorted(proposals["features"], key=lambda f: -shape(f["geometry"]).area):
|
||||
p = shape(f["geometry"])
|
||||
if p.area < 0.20:
|
||||
continue
|
||||
# Bounding-box pruning only; preserve original component order and predicate.
|
||||
members = [
|
||||
raw["features"][i]
|
||||
for i in sorted(int(index) for index in spatial.query(p))
|
||||
if raw_geometries[i].intersection(p).area > 0.5 * raw_geometries[i].area
|
||||
]
|
||||
if not members:
|
||||
continue
|
||||
observed = unary_union([shape(r["geometry"]) for r in members])
|
||||
# A component grouping is a hypothesis, not a replacement for evidence.
|
||||
result, reason = fit_symbol(observed, templates, policy, budget)
|
||||
if result is None:
|
||||
continue
|
||||
params, metrics = result
|
||||
g = catalog_geometry(
|
||||
next(t for t in templates if t["id"] == params["template_id"]),
|
||||
params["center"],
|
||||
params["angle_radians"],
|
||||
params["scale"],
|
||||
)
|
||||
delta = contrast(g, rgb, pixel_to_scene)
|
||||
if delta is None or delta < policy.min_luminance_contrast:
|
||||
continue
|
||||
arbitration, reason = arbitrate_symbol(
|
||||
observed, g, policy, center=params["center"], angle=params["angle_radians"],
|
||||
rgb=rgb, pixel_to_scene=pixel_to_scene,
|
||||
)
|
||||
if reason is not None:
|
||||
continue
|
||||
ids = sorted(r["id"] for r in members)
|
||||
obj = dict(
|
||||
representation="catalog",
|
||||
arbitration=arbitration,
|
||||
kind=params["template_id"],
|
||||
parameters=params,
|
||||
observation_ids=ids,
|
||||
fit=metrics,
|
||||
luminance_contrast=delta,
|
||||
)
|
||||
obj["support_boundary"] = sorted(
|
||||
{flag for member in members for flag in member["properties"]["support_boundary"]}
|
||||
)
|
||||
obj["id"] = "object-" + digest([raw["source_sha256"], catalog_sha, obj])[:24]
|
||||
objects.append(obj)
|
||||
consumed.update(ids)
|
||||
for f in raw["features"]:
|
||||
if f["id"] in consumed:
|
||||
continue
|
||||
p = shape(f["geometry"])
|
||||
proposals = fit_strips(p, policy) if p.area >= policy.min_area_m2 else []
|
||||
reason = "too-small" if p.area < policy.min_area_m2 else "unsupported-shape"
|
||||
candidates = []
|
||||
for params in proposals:
|
||||
g = strip_geometry(params["centerline"], params["width_m"])
|
||||
delta = contrast(g, rgb, pixel_to_scene)
|
||||
if delta is None or delta < policy.min_luminance_contrast:
|
||||
reason = "insufficient-rgb-contrast"
|
||||
break
|
||||
support = (p if len(proposals) == 1
|
||||
else p.intersection(g.buffer(policy.shape_tolerance_m)))
|
||||
obj = dict(representation="strip", kind="linear_marking", parameters=params,
|
||||
observation_ids=[f["id"]], fit=agreement(support,g,policy.shape_tolerance_m),
|
||||
luminance_contrast=delta,
|
||||
support_boundary=f["properties"]["support_boundary"])
|
||||
if len(proposals) > 1:
|
||||
obj["decomposition"] = "observed-orthogonal-junction"
|
||||
obj["id"] = "object-" + digest([raw["source_sha256"],obj])[:24]
|
||||
candidates.append(obj)
|
||||
if proposals and len(candidates) == len(proposals):
|
||||
objects.extend(candidates)
|
||||
continue
|
||||
rejected.append(
|
||||
dict(observation_id=f["id"], reason=reason, status="unresolved-not-background")
|
||||
)
|
||||
recovered = recover_crosswalks(objects, raw["features"], rgb=rgb,
|
||||
pixel_to_scene=pixel_to_scene, policy=policy)
|
||||
recovered_ids = {i for o in recovered for i in o["observation_ids"]}
|
||||
rejected = [r for r in rejected if r["observation_id"] not in recovered_ids]
|
||||
objects.extend(recovered)
|
||||
group_crosswalks(objects)
|
||||
for obj in objects:
|
||||
obj["instance_completeness"] = "not-assessed"
|
||||
obj["geometry"] = mapping(reconstruct(obj, catalog))
|
||||
return dict(
|
||||
schema="missioncore.paint-objects/v1",
|
||||
source=raw["source"],
|
||||
catalog_sha256=catalog_sha,
|
||||
policy=asdict(policy),
|
||||
objects=objects,
|
||||
rejected=rejected,
|
||||
symbol_fits=budget[0],
|
||||
raw_components=len(raw["features"]),
|
||||
labels_used=False,
|
||||
human_geometry_used=False,
|
||||
)
|
||||
|
||||
|
||||
def surface_plane(obj, *, depth, alpha, camera_eye_z, pixel_to_scene, catalog):
|
||||
"""Fit observed interior surface, then place a compact object on that plane.
|
||||
|
||||
This is Gaussian-derived placement, not surveyed height. No zero-height or
|
||||
camera-target fallback. Unreliable support preserves the entire 2-D object.
|
||||
"""
|
||||
return surface_geometry_plane(
|
||||
reconstruct(obj, catalog), depth=depth, alpha=alpha,
|
||||
camera_eye_z=camera_eye_z, pixel_to_scene=pixel_to_scene,
|
||||
)
|
||||
|
||||
|
||||
def surface_geometry_plane(g, *, depth, alpha, camera_eye_z, pixel_to_scene):
|
||||
"""Observed surface estimate for arbitrary geometry, without catalog input."""
|
||||
depth, alpha = np.asarray(depth), np.asarray(alpha)
|
||||
if (
|
||||
depth.ndim != 2
|
||||
or alpha.shape != depth.shape
|
||||
or not np.isfinite(camera_eye_z)
|
||||
or not np.isfinite(pixel_to_scene).all()
|
||||
):
|
||||
raise ValueError("Invalid surface inputs")
|
||||
a, b, d, e, x0, y0 = pixel_to_scene
|
||||
yy, xx = np.indices(depth.shape)
|
||||
X = a * (xx + 0.5) + b * (yy + 0.5) + x0
|
||||
Y = d * (xx + 0.5) + e * (yy + 0.5) + y0
|
||||
support = (
|
||||
intersects_xy(g, X, Y)
|
||||
& np.isfinite(depth)
|
||||
& (depth > 0)
|
||||
& np.isfinite(alpha)
|
||||
& (alpha >= 0.95)
|
||||
)
|
||||
if support.sum() < 24:
|
||||
return None, dict(reason="insufficient-surface-support", samples=int(support.sum()))
|
||||
xy = np.column_stack([X[support], Y[support]])
|
||||
z = camera_eye_z - depth[support]
|
||||
stride = max(1, math.ceil(len(xy) / 4096))
|
||||
xy = xy[::stride]
|
||||
z = z[::stride]
|
||||
origin = xy.mean(0)
|
||||
design = np.column_stack([xy - origin, np.ones(len(xy))])
|
||||
keep = np.ones(len(xy), bool)
|
||||
for _ in range(4):
|
||||
coeff = np.linalg.lstsq(design[keep], z[keep], rcond=None)[0]
|
||||
residual = np.abs(design @ coeff - z)
|
||||
keep = residual <= max(0.03, 3 * np.median(residual))
|
||||
if keep.sum() < 24:
|
||||
return None, dict(reason="unstable-surface-fit")
|
||||
center, angle, length, width = rectangle(g)
|
||||
u = np.array([math.cos(angle), math.sin(angle)])
|
||||
n = np.array([-u[1], u[0]])
|
||||
q = xy[keep]
|
||||
spans = [float(np.ptp(q @ u) / length), float(np.ptp(q @ n) / width)]
|
||||
p95 = float(np.quantile(np.abs(design[keep] @ coeff - z[keep]), 0.95))
|
||||
info = dict(
|
||||
samples=int(keep.sum()),
|
||||
support_spans=spans,
|
||||
residual_p95_m=p95,
|
||||
slopes=coeff[:2].tolist(),
|
||||
origin=origin.tolist(),
|
||||
intercept=float(coeff[2]),
|
||||
source="gaussian-interior-plane",
|
||||
survey_verified=False,
|
||||
)
|
||||
if min(spans) < 0.7 or p95 > 0.15 or np.linalg.norm(coeff[:2]) > 0.5 or keep.mean() < 0.6:
|
||||
return None, dict(info, reason="unreliable-surface-fit")
|
||||
|
||||
def height(x, y):
|
||||
return (
|
||||
coeff[0] * (np.asarray(x) - origin[0])
|
||||
+ coeff[1] * (np.asarray(y) - origin[1])
|
||||
+ coeff[2]
|
||||
)
|
||||
|
||||
return height, info
|
||||
|
||||
|
||||
def editor_features(obj, *, catalog, height, surface, height_source, observation_source):
|
||||
"""Materialize an immutable automatic proposal for the existing editor.
|
||||
|
||||
Editable geometry is authoritative after a user operation. Recognition
|
||||
parameters are explicitly an immutable SOURCE snapshot, never current
|
||||
editable parameters or a reconstruction command for a human revision.
|
||||
"""
|
||||
if height is None:
|
||||
return []
|
||||
g = transform(lambda x, y, z=None: (x, y, height(x, y)), reconstruct(obj, catalog))
|
||||
coordinates = [q for p in parts(g) for ring in [p.exterior, *p.interiors] for q in ring.coords]
|
||||
if not np.isfinite(coordinates).all():
|
||||
raise ValueError("Invalid materialized height")
|
||||
props = dict(
|
||||
subtype=obj["kind"],
|
||||
authority="observation-only",
|
||||
route_permission="unassigned",
|
||||
confidence=None,
|
||||
confidence_status="not-assessed",
|
||||
review_status="unreviewed",
|
||||
annotation_origin="automatic-primitive-assembly",
|
||||
method="catalog-and-strip-fit-v1",
|
||||
semantic_element_id=obj.get("group_id", obj["id"]),
|
||||
support_boundary=obj.get("support_boundary", []),
|
||||
instance_completeness="not-assessed",
|
||||
source_observation_sha256=observation_source,
|
||||
height_source=height_source,
|
||||
catalog_sha256=digest(catalog),
|
||||
recognition_snapshot=dict(
|
||||
role="immutable-automatic-source-not-current-edited-geometry",
|
||||
representation=obj["representation"],
|
||||
parameters=obj["parameters"],
|
||||
surface_model=surface,
|
||||
),
|
||||
)
|
||||
props["class"] = "road_marking"
|
||||
if obj["representation"] == "catalog":
|
||||
template = next(
|
||||
t for t in catalog["templates"] if t["id"] == obj["parameters"]["template_id"]
|
||||
)
|
||||
props.update(template_id=template["id"], template_source=template.get("source"))
|
||||
if "observed_bar_count" in obj:
|
||||
props["observed_bar_count"] = obj["observed_bar_count"]
|
||||
features = [
|
||||
dict(type="Feature", id=obj["id"] + "-" + str(i), geometry=mapping(p), properties=props)
|
||||
for i, p in enumerate(parts(g))
|
||||
]
|
||||
# Core's editing operations mutate coordinate lists. Return the actual JSON
|
||||
# contract even before disk serialization, with no shared caller metadata.
|
||||
return json.loads(json.dumps(features, allow_nan=False))
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Observed XY contours -> qualified Gaussian heights; never reconstruct paint."""
|
||||
import numpy as np
|
||||
from paint_objects import surface_geometry_plane
|
||||
from shapely.ops import transform
|
||||
|
||||
|
||||
class HeightRefusal(ValueError):
|
||||
"""Expected missing height evidence, not a malformed input or code error."""
|
||||
|
||||
|
||||
def _inputs(depth, alpha, camera_eye_z, matrix):
|
||||
depth, alpha = np.asarray(depth), np.asarray(alpha)
|
||||
m = np.asarray(matrix, dtype=float)
|
||||
if (depth.ndim != 2 or depth.shape != alpha.shape or not depth.size
|
||||
or m.shape != (6,) or not np.isfinite(m).all()
|
||||
or not np.isfinite(camera_eye_z)
|
||||
or abs(m[0] * m[3] - m[1] * m[2]) < 1e-12):
|
||||
raise ValueError("Invalid projection inputs")
|
||||
return depth, alpha, m
|
||||
|
||||
|
||||
def bilinear_geometry(g, *, depth, alpha, camera_eye_z, pixel_to_scene):
|
||||
"""Require each contributing sample; ignore only exactly zero weights."""
|
||||
depth, alpha, m = _inputs(depth, alpha, camera_eye_z, pixel_to_scene)
|
||||
inverse = np.linalg.inv([[m[0], m[1]], [m[2], m[3]]])
|
||||
|
||||
def lift(x, y, z=None):
|
||||
uv = (np.column_stack([x, y]) - m[4:]) @ inverse.T - 0.5
|
||||
base = np.floor(uv).astype(int)
|
||||
fraction = uv - base
|
||||
height = np.zeros(len(uv))
|
||||
for dx, dy in ((0, 0), (1, 0), (0, 1), (1, 1)):
|
||||
weight = ((fraction[:, 0] if dx else 1 - fraction[:, 0])
|
||||
* (fraction[:, 1] if dy else 1 - fraction[:, 1]))
|
||||
needed = weight > 0
|
||||
ix, iy = base[needed, 0] + dx, base[needed, 1] + dy
|
||||
if (np.any(ix < 0) or np.any(iy < 0)
|
||||
or np.any(ix >= depth.shape[1]) or np.any(iy >= depth.shape[0])):
|
||||
raise HeightRefusal("outside-depth")
|
||||
dd, aa = depth[iy, ix], alpha[iy, ix]
|
||||
if not (np.isfinite(dd) & (dd > 0) & np.isfinite(aa) & (aa >= 0.95)).all():
|
||||
raise HeightRefusal("missing-observed-vertex-height")
|
||||
height[needed] += weight[needed] * (camera_eye_z - dd)
|
||||
return x, y, height
|
||||
|
||||
return transform(lift, g)
|
||||
|
||||
|
||||
def project_observation(g, *, depth, alpha, camera_eye_z, pixel_to_scene):
|
||||
"""Preserve every XY ring. Return explicit 2D-only refusal without fake Z.
|
||||
|
||||
A local plane is estimated from the original contour's interior evidence,
|
||||
never from a catalog template. The existing surface acceptance guards apply.
|
||||
"""
|
||||
depth, alpha, m = _inputs(depth, alpha, camera_eye_z, pixel_to_scene)
|
||||
if g.is_empty or not g.is_valid or g.geom_type != "Polygon":
|
||||
raise ValueError("A valid observation Polygon is required")
|
||||
try:
|
||||
placed = bilinear_geometry(g, depth=depth, alpha=alpha,
|
||||
camera_eye_z=camera_eye_z, pixel_to_scene=m)
|
||||
return placed, dict(method="observed-bilinear", placement_status="placed")
|
||||
except HeightRefusal as error:
|
||||
direct_refusal = str(error)
|
||||
# Crop by an inverse affine of the envelope. This bounds per-object work
|
||||
# without changing the support pixels (works for rotated grids as well).
|
||||
inverse = np.linalg.inv([[m[0], m[1]], [m[2], m[3]]])
|
||||
uv = (np.asarray(g.envelope.exterior.coords)[:, :2] - m[4:]) @ inverse.T
|
||||
x0, y0 = np.maximum(np.floor(uv.min(0)).astype(int) - 2, 0)
|
||||
x1, y1 = np.minimum(np.ceil(uv.max(0)).astype(int) + 2, depth.shape[1::-1])
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return None, dict(placement_status="2d-only", reason="outside-depth")
|
||||
cropped = [*m[:4], m[4] + m[0] * x0 + m[1] * y0,
|
||||
m[5] + m[2] * x0 + m[3] * y0]
|
||||
height, info = surface_geometry_plane(
|
||||
g, depth=depth[y0:y1, x0:x1], alpha=alpha[y0:y1, x0:x1],
|
||||
camera_eye_z=camera_eye_z, pixel_to_scene=cropped,
|
||||
)
|
||||
info = dict(info, direct_refusal=direct_refusal)
|
||||
if height is None:
|
||||
return None, dict(info, placement_status="2d-only")
|
||||
placed = transform(lambda x, y, z=None: (x, y, height(x, y)), g)
|
||||
return placed, dict(info, method="observed-interior-plane", placement_status="placed")
|
||||
@@ -15,6 +15,7 @@ from k1link.simulation.ai_polygon.worlds import write_json
|
||||
|
||||
HASH = re.compile(r"[0-9a-f]{64}")
|
||||
REQUEST = re.compile(r"[a-zA-Z0-9_-]{16,80}")
|
||||
BRANCH = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||
MAX_STATE = 8 * 1024**2
|
||||
# A collection contains at most 256 bounded four-window shards. This is receipt
|
||||
# metadata, not a relaxation of geometry or training admission.
|
||||
@@ -229,28 +230,39 @@ class SemanticEdits:
|
||||
self.root = data_dir / "ai-polygon" / "semantic-edits"
|
||||
self.maps = maps
|
||||
|
||||
def _path(self, world):
|
||||
def _path(self, world, branch_id=None):
|
||||
if not HASH.fullmatch(world["sha256"]):
|
||||
raise ValueError("Некорректная версия сцены.")
|
||||
return self.root / (world["sha256"] + ".json")
|
||||
if branch_id is None:
|
||||
return self.root / (world["sha256"] + ".json")
|
||||
if not isinstance(branch_id, str) or not BRANCH.fullmatch(branch_id):
|
||||
raise ValueError("Некорректная ручная версия.")
|
||||
directory = self.root / world["sha256"] / "branches"
|
||||
if directory.is_symlink() or directory.parent.is_symlink():
|
||||
raise ValueError("Недопустимая ссылка на историю.")
|
||||
return directory / (branch_id + ".json")
|
||||
|
||||
def _read(self, world):
|
||||
path = self._path(world)
|
||||
def _read(self, world, branch_id=None):
|
||||
path = self._path(world, branch_id)
|
||||
if not path.exists():
|
||||
return {"schema_version": "missioncore.semantic-edits/v1", "revisions": []}
|
||||
if path.is_symlink() or path.stat().st_size > MAX_STATE:
|
||||
raise ValueError("Хранилище правок не прошло проверку.")
|
||||
state = json.loads(path.read_text())
|
||||
revisions = state["revisions"]
|
||||
if state.get("branch_id") != branch_id:
|
||||
raise ValueError("История относится к другой ручной версии.")
|
||||
for i, row in enumerate(revisions):
|
||||
payload = {k: v for k, v in row.items() if k != "revision"}
|
||||
if digest(payload) != row["revision"] or row["parent"] != (
|
||||
revisions[i - 1]["revision"] if i else None
|
||||
if (
|
||||
row.get("branch_id") != branch_id
|
||||
or digest(payload) != row["revision"]
|
||||
or row["parent"] != (revisions[i - 1]["revision"] if i else None)
|
||||
):
|
||||
raise ValueError("Нарушена целостность истории правок.")
|
||||
return state
|
||||
|
||||
def _model(self, world, sha):
|
||||
def _model(self, world, sha, *, for_edit=True):
|
||||
if not isinstance(sha, str) or not HASH.fullmatch(sha):
|
||||
raise ValueError("Некорректная версия алгоритма.")
|
||||
path = self.maps.directory(world) / (sha + ".json")
|
||||
@@ -260,14 +272,16 @@ class SemanticEdits:
|
||||
if digest(document) != sha:
|
||||
raise ValueError("Исходная карта изменилась.")
|
||||
validate_map(document, world)
|
||||
if for_edit and document.get("semantic_stage") == "raw":
|
||||
raise ValueError("Сырая алгоритмическая разметка доступна только для просмотра.")
|
||||
if document["schema_version"] == "missioncore.urban-map/v1":
|
||||
raise ValueError("Для редактора нужна векторная карта инфраструктуры.")
|
||||
return document
|
||||
|
||||
def _view(self, world, state):
|
||||
revisions = state["revisions"]
|
||||
latest = self.maps.get(world)
|
||||
sha = revisions[0]["model_sha256"] if revisions else digest(latest)
|
||||
latest_sha = self._latest_sha(world)
|
||||
sha = revisions[0]["model_sha256"] if revisions else latest_sha
|
||||
model = self._model(world, sha)
|
||||
edited = copy.deepcopy(model) if revisions else model
|
||||
for row in revisions:
|
||||
@@ -279,7 +293,59 @@ class SemanticEdits:
|
||||
verified_history=True,
|
||||
origin=row.get("origin", "human-edit"),
|
||||
)
|
||||
return self._response(state, model, edited, sha, digest(latest))
|
||||
return self._response(state, model, edited, sha, latest_sha)
|
||||
|
||||
def _latest_sha(self, world):
|
||||
# A broken current publication cannot hide an intact pinned manual base.
|
||||
try:
|
||||
return digest(self.maps.get(world))
|
||||
except (FileNotFoundError, ValueError, KeyError):
|
||||
return None
|
||||
|
||||
def _states(self, world):
|
||||
yield None, self._read(world)
|
||||
directory = self.root / world["sha256"] / "branches"
|
||||
if directory.is_symlink() or directory.parent.is_symlink():
|
||||
raise ValueError("Недопустимая ссылка на историю.")
|
||||
if directory.exists():
|
||||
for path in sorted(directory.glob("*.json")):
|
||||
yield path.stem, self._read(world, path.stem)
|
||||
|
||||
def versions(self, world):
|
||||
try:
|
||||
pointer = self.maps.versions(world)
|
||||
for sha in pointer.values():
|
||||
self.maps.get_version(world, sha)
|
||||
except (FileNotFoundError, ValueError, KeyError):
|
||||
pointer = {}
|
||||
manual = []
|
||||
for branch_id, state in self._states(world):
|
||||
if not state["revisions"]:
|
||||
continue
|
||||
head = state["revisions"][-1]
|
||||
manual.append(
|
||||
{
|
||||
"branch_id": branch_id,
|
||||
"revision": head["revision"],
|
||||
"model_sha256": head["model_sha256"],
|
||||
"created_at": head["created_at"],
|
||||
}
|
||||
)
|
||||
return {
|
||||
"raw_sha256": pointer.get("raw_sha256"),
|
||||
"algorithmic_sha256": pointer.get("sha256"),
|
||||
"manual": sorted(manual, key=lambda row: row["created_at"], reverse=True),
|
||||
}
|
||||
|
||||
def _find_revision(self, world, revision):
|
||||
matches = [
|
||||
(branch, state)
|
||||
for branch, state in self._states(world)
|
||||
if any(row["revision"] == revision for row in state["revisions"])
|
||||
]
|
||||
if len(matches) != 1:
|
||||
raise FileNotFoundError("Ревизия не найдена однозначно.")
|
||||
return matches[0]
|
||||
|
||||
@staticmethod
|
||||
def _response(state, model, edited, sha, latest_sha):
|
||||
@@ -287,6 +353,7 @@ class SemanticEdits:
|
||||
head = revisions[-1] if revisions else None
|
||||
return {
|
||||
"schema_version": "missioncore.semantic-editor/v1",
|
||||
"branch_id": state.get("branch_id"),
|
||||
"model_sha256": sha,
|
||||
"latest_model_sha256": latest_sha,
|
||||
"revision": head["revision"] if head else None,
|
||||
@@ -307,12 +374,33 @@ class SemanticEdits:
|
||||
},
|
||||
}
|
||||
|
||||
def get(self, world):
|
||||
return self._view(world, self._read(world))
|
||||
def get(self, world, source=None, branch_id=None, model_sha256=None):
|
||||
if source in ("raw", "algorithmic"):
|
||||
if branch_id is not None:
|
||||
raise ValueError("Алгоритмическая версия не имеет ручной ветки.")
|
||||
pointer = self.maps.versions(world)
|
||||
sha = model_sha256 or pointer.get("raw_sha256" if source == "raw" else "sha256")
|
||||
if not sha:
|
||||
raise FileNotFoundError("Эта версия разметки ещё не рассчитана.")
|
||||
model = self._model(world, sha, for_edit=source != "raw")
|
||||
if source == "raw" and model.get("semantic_stage") != "raw":
|
||||
raise ValueError("Версия не является сырой разметкой.")
|
||||
response = self._response({"revisions": []}, model, model, sha, pointer["sha256"])
|
||||
if source == "raw":
|
||||
# Dense diagnostics travel once, never as a duplicate draft.
|
||||
response.pop("edited")
|
||||
response["read_only"] = True
|
||||
return response
|
||||
if source not in (None, "manual") or model_sha256 is not None:
|
||||
raise ValueError("Неизвестное представление разметки.")
|
||||
state = self._read(world, branch_id)
|
||||
if (source == "manual" or branch_id) and not state["revisions"]:
|
||||
raise FileNotFoundError("Ручная версия ещё не сохранена.")
|
||||
return self._view(world, state)
|
||||
|
||||
def export(self, world, revision):
|
||||
"""Portable annotation metadata, explicitly not an image dataset."""
|
||||
state = self._read(world)
|
||||
_, state = self._find_revision(world, revision)
|
||||
index = next(
|
||||
(i for i, row in enumerate(state["revisions"]) if row["revision"] == revision),
|
||||
None,
|
||||
@@ -335,7 +423,7 @@ class SemanticEdits:
|
||||
return {"sha256": digest(package), "package": package}
|
||||
|
||||
def save(self, world, body):
|
||||
if not isinstance(body, dict) or set(body) - {"origin"} != {
|
||||
if not isinstance(body, dict) or set(body) - {"origin", "branch_id"} != {
|
||||
"expected_revision",
|
||||
"model_sha256",
|
||||
"request_id",
|
||||
@@ -347,10 +435,14 @@ class SemanticEdits:
|
||||
if body.get("origin", "human-edit") not in ("human-edit", "agent-proposal"):
|
||||
raise ValueError("Некорректное происхождение правки.")
|
||||
request_hash = digest(body)
|
||||
branch_id = body.get("branch_id")
|
||||
self._path(world, branch_id)
|
||||
# Reserve a bounded complete atomic replacement. Shared lock handles
|
||||
# concurrent tabs/processes; an idempotent replay needs no new capacity.
|
||||
with cache_publication(self.root, 0, limit=64 * 1024**2):
|
||||
state = self._read(world)
|
||||
state = self._read(world, branch_id)
|
||||
if branch_id is not None:
|
||||
state["branch_id"] = branch_id
|
||||
revisions = state["revisions"]
|
||||
for row in revisions:
|
||||
if row["request_id"] == body["request_id"]:
|
||||
@@ -367,7 +459,7 @@ class SemanticEdits:
|
||||
# published; never silently rebase a human operation by index.
|
||||
model = self._model(world, body["model_sha256"])
|
||||
view = self._response(
|
||||
state, model, model, body["model_sha256"], digest(self.maps.get(world))
|
||||
state, model, model, body["model_sha256"], self._latest_sha(world)
|
||||
)
|
||||
else:
|
||||
view = self._view(world, state)
|
||||
@@ -400,7 +492,9 @@ class SemanticEdits:
|
||||
self.root
|
||||
).free < FREE_RESERVE + len(raw):
|
||||
raise ValueError("Недостаточно места для сохранения правок.")
|
||||
write_json(self._path(world), state)
|
||||
path = self._path(world, branch_id)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
write_json(path, state)
|
||||
# Return the exact admitted geometry. Replaying the entire history
|
||||
# here duplicated work and could fail after a successful commit.
|
||||
return self._response(
|
||||
@@ -411,17 +505,18 @@ class SemanticEdits:
|
||||
"""The revision itself is the durable outbox: no dual-write window."""
|
||||
rows = []
|
||||
for world in worlds:
|
||||
state = self._read(world)
|
||||
for revision in state["revisions"]:
|
||||
if revision["revision"] not in state.get("deliveries", {}):
|
||||
rows.append(
|
||||
{
|
||||
"world_id": world["world_id"],
|
||||
"world_sha256": world["sha256"],
|
||||
"revision": revision["revision"],
|
||||
"created_at": revision["created_at"],
|
||||
}
|
||||
)
|
||||
for branch_id, state in self._states(world):
|
||||
for revision in state["revisions"]:
|
||||
if revision["revision"] not in state.get("deliveries", {}):
|
||||
rows.append(
|
||||
{
|
||||
"world_id": world["world_id"],
|
||||
"world_sha256": world["sha256"],
|
||||
"revision": revision["revision"],
|
||||
"created_at": revision["created_at"],
|
||||
**({"branch_id": branch_id} if branch_id else {}),
|
||||
}
|
||||
)
|
||||
return sorted(rows, key=lambda r: (r["created_at"], r["revision"]))[:20]
|
||||
|
||||
def receipt(self, world, revision, body):
|
||||
@@ -446,7 +541,7 @@ class SemanticEdits:
|
||||
package = self.export(world, revision)
|
||||
if body["package_sha256"] != package["sha256"]:
|
||||
raise ValueError("Квитанция относится к другой аннотации.")
|
||||
state = self._read(world)
|
||||
branch_id, state = self._find_revision(world, revision)
|
||||
deliveries = state.setdefault("deliveries", {})
|
||||
previous = deliveries.get(revision)
|
||||
if previous:
|
||||
@@ -466,5 +561,5 @@ class SemanticEdits:
|
||||
or shutil.disk_usage(self.root).free < FREE_RESERVE + len(raw)
|
||||
):
|
||||
raise ValueError("Недостаточно места для квитанции.")
|
||||
write_json(self._path(world), state)
|
||||
write_json(self._path(world, branch_id), state)
|
||||
return body
|
||||
|
||||
@@ -49,21 +49,25 @@ def validate_map(document: dict, world: dict) -> dict:
|
||||
"collider_sha256"
|
||||
):
|
||||
raise ValueError("Infrastructure map belongs to a different scene revision")
|
||||
if document["schema_version"] == "missioncore.urban-map/v3":
|
||||
if source.get("gaussian_only") is not True or not re.fullmatch(
|
||||
"[0-9a-f]{64}", str(source.get("artifact_sha256", ""))
|
||||
):
|
||||
raise ValueError("Missing Gaussian derivation identity")
|
||||
if document["schema_version"] == "missioncore.urban-map/v3" and (
|
||||
source.get("gaussian_only") is not True
|
||||
or not re.fullmatch("[0-9a-f]{64}", str(source.get("artifact_sha256", "")))
|
||||
):
|
||||
raise ValueError("Missing Gaussian derivation identity")
|
||||
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:
|
||||
if type(cell) not in (int, float) or not math.isfinite(cell) or not 0.005 <= 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:
|
||||
# Raw is a read-only diagnostic, not an editable object collection. Its
|
||||
# denser contours have a separate bounded display budget; editable maps
|
||||
# retain their existing smaller limit.
|
||||
feature_limit = 50000 if document.get("semantic_stage") == "raw" else 20000
|
||||
if not isinstance(features, list) or len(features) > feature_limit:
|
||||
raise ValueError("Invalid infrastructure feature count")
|
||||
vertices = 0
|
||||
identifiers = set()
|
||||
@@ -80,7 +84,10 @@ def validate_map(document: dict, world: dict) -> dict:
|
||||
or prop.get("route_permission") != "unassigned"
|
||||
):
|
||||
raise ValueError("Infrastructure observations cannot grant route permissions")
|
||||
vector = document["schema_version"] in {"missioncore.urban-map/v2", "missioncore.urban-map/v3"}
|
||||
vector = document["schema_version"] in {
|
||||
"missioncore.urban-map/v2",
|
||||
"missioncore.urban-map/v3",
|
||||
}
|
||||
if vector:
|
||||
identifier = feature.get("id")
|
||||
score = prop.get("confidence")
|
||||
@@ -125,7 +132,8 @@ def validate_map(document: dict, world: dict) -> dict:
|
||||
)
|
||||
):
|
||||
raise ValueError("Invalid infrastructure XYZ")
|
||||
if vertices > 300000:
|
||||
vertex_limit = 400000 if document.get("semantic_stage") == "raw" else 300000
|
||||
if vertices > vertex_limit:
|
||||
raise ValueError("Infrastructure map exceeds vertex limit")
|
||||
return document
|
||||
|
||||
@@ -140,25 +148,73 @@ class UrbanMapStore:
|
||||
raise ValueError("Invalid world identity")
|
||||
return self.root / key
|
||||
|
||||
def save(self, world, document):
|
||||
def store_immutable(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:
|
||||
byte_limit = (32 if document.get("semantic_stage") == "raw" else 12) * 1024**2
|
||||
if len(raw) > byte_limit:
|
||||
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})
|
||||
path = directory / (sha + ".json")
|
||||
if path.is_symlink():
|
||||
raise ValueError("Invalid infrastructure link")
|
||||
if path.exists():
|
||||
self.get_version(world, sha)
|
||||
else:
|
||||
write_json(path, document)
|
||||
return {"sha256": sha, "features": len(document["features"])}
|
||||
|
||||
def get(self, world):
|
||||
def save(self, world, document):
|
||||
if document.get("semantic_stage") == "raw":
|
||||
raise ValueError("Raw observations cannot replace the algorithmic map")
|
||||
result = self.store_immutable(world, document)
|
||||
write_json(self.directory(world) / "latest.json", {"sha256": result["sha256"]})
|
||||
return result
|
||||
|
||||
def publish_pair(self, world, raw, algorithmic):
|
||||
"""Publish a complete pair with one atomic pointer replacement."""
|
||||
for document, stage in ((raw, "raw"), (algorithmic, "algorithmic")):
|
||||
validate_map(document, world)
|
||||
if document.get("semantic_stage") != stage:
|
||||
raise ValueError("Incorrect semantic representation role")
|
||||
if raw["source"] != algorithmic["source"]:
|
||||
raise ValueError("Semantic representations must share their source")
|
||||
raw_result = self.store_immutable(world, raw)
|
||||
result = self.store_immutable(world, algorithmic)
|
||||
pointer = {"sha256": result["sha256"], "raw_sha256": raw_result["sha256"]}
|
||||
write_json(self.directory(world) / "latest.json", pointer)
|
||||
return pointer
|
||||
|
||||
def versions(self, world):
|
||||
directory = self.directory(world)
|
||||
sha = json.loads((directory / "latest.json").read_text())["sha256"]
|
||||
if not re.fullmatch("[0-9a-f]{64}", sha):
|
||||
path = directory / "latest.json"
|
||||
if path.is_symlink():
|
||||
raise ValueError("Invalid infrastructure pointer")
|
||||
pointer = json.loads(path.read_text())
|
||||
if (
|
||||
not isinstance(pointer, dict)
|
||||
or "sha256" not in pointer
|
||||
or set(pointer) - {"sha256", "raw_sha256"}
|
||||
):
|
||||
raise ValueError("Invalid infrastructure pointer")
|
||||
for field in ("sha256", "raw_sha256"):
|
||||
if field in pointer and not re.fullmatch("[0-9a-f]{64}", str(pointer[field])):
|
||||
raise ValueError("Invalid infrastructure identity")
|
||||
return pointer
|
||||
|
||||
def get_version(self, world, sha):
|
||||
if not isinstance(sha, str) or not re.fullmatch("[0-9a-f]{64}", sha):
|
||||
raise ValueError("Invalid infrastructure identity")
|
||||
document = json.loads((directory / (sha + ".json")).read_text())
|
||||
path = self.directory(world) / (sha + ".json")
|
||||
if path.is_symlink():
|
||||
raise ValueError("Invalid infrastructure link")
|
||||
document = json.loads(path.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)
|
||||
|
||||
def get(self, world):
|
||||
return self.get_version(world, self.versions(world)["sha256"])
|
||||
|
||||
@@ -18,8 +18,17 @@ def build_semantic_edits_router(data_dir, worlds, maps, invoke, authenticate):
|
||||
return catalog()
|
||||
|
||||
@router.get("/worlds/{world_id}/semantic-edits")
|
||||
def get(world_id: str):
|
||||
return invoke(store.get, invoke(worlds.get, world_id))
|
||||
def get(
|
||||
world_id: str,
|
||||
source: str | None = None,
|
||||
branch_id: str | None = None,
|
||||
model_sha256: str | None = None,
|
||||
):
|
||||
return invoke(store.get, invoke(worlds.get, world_id), source, branch_id, model_sha256)
|
||||
|
||||
@router.get("/worlds/{world_id}/semantic-versions")
|
||||
def versions(world_id: str):
|
||||
return invoke(store.versions, invoke(worlds.get, world_id))
|
||||
|
||||
@router.post("/worlds/{world_id}/semantic-edits")
|
||||
async def save(world_id: str, request: Request):
|
||||
@@ -54,9 +63,9 @@ def build_semantic_edits_router(data_dir, worlds, maps, invoke, authenticate):
|
||||
return {"jobs": invoke(store.pending, invoke(worlds.list))}
|
||||
|
||||
@router.get("/worlds/{world_id}/semantic-edits/status")
|
||||
def status(world_id: str):
|
||||
def status(world_id: str, branch_id: str | None = None):
|
||||
world = invoke(worlds.get, world_id)
|
||||
state = invoke(store._read, world)
|
||||
state = invoke(store._read, world, branch_id)
|
||||
head = state["revisions"][-1]["revision"] if state["revisions"] else None
|
||||
return {
|
||||
"revision": head,
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import copy
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from shapely.geometry import mapping, shape
|
||||
from shapely.ops import unary_union
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
import paint_objects as po
|
||||
from paint_context import contextual_additions as admit
|
||||
|
||||
|
||||
def contextual_additions(*args, contrast_fn=None):
|
||||
return admit(
|
||||
*args,
|
||||
experimental_continuations=True,
|
||||
contrast_fn=contrast_fn or (lambda *_: {"contrast": 0.3, "source": "synthetic"}),
|
||||
)
|
||||
|
||||
|
||||
def strip(name, start, end, width=0.2, **extra):
|
||||
g = po.strip_geometry([start, end], width)
|
||||
return dict(
|
||||
id=name,
|
||||
kind="linear_marking",
|
||||
representation="strip",
|
||||
placement_status="placed",
|
||||
parameters=dict(centerline=[start, end], width_m=width),
|
||||
geometry=mapping(g),
|
||||
observation_geometry=mapping(g),
|
||||
observation_ids=[name],
|
||||
fit=dict(score=0.9),
|
||||
sources=["synthetic"],
|
||||
**extra,
|
||||
)
|
||||
|
||||
|
||||
def test_same_observed_line_extends_without_changing_seed():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
candidate = strip("candidate", (4, 0), (9, 0))
|
||||
before = copy.deepcopy(seed)
|
||||
added, log = contextual_additions([seed], [candidate])
|
||||
assert seed == before and len(added) == 1 and log[0]["accepted"]
|
||||
g = shape(added[0]["geometry"])
|
||||
assert g.bounds[0] > 5 and g.bounds[2] == 9
|
||||
assert added[0]["context_admission"]["method"] == "observed-continuation"
|
||||
|
||||
|
||||
def test_parallel_offset_and_real_gap_cannot_supply_continuation():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
for candidate in [strip("offset", (4, 0.4), (9, 0.4)), strip("gap", (5.2, 0), (9, 0))]:
|
||||
added, _ = contextual_additions([seed], [candidate])
|
||||
assert not added
|
||||
|
||||
|
||||
def test_added_candidates_never_seed_a_chain_and_order_is_stable():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
a = strip("a", (4, 0), (9, 0))
|
||||
b = strip("b", (8, 0), (13, 0))
|
||||
first, _ = contextual_additions([seed], [a, b])
|
||||
second, _ = contextual_additions([seed], [b, a])
|
||||
assert first == second and len(first) == 1
|
||||
assert shape(first[0]["geometry"]).bounds[2] == 9
|
||||
|
||||
|
||||
def test_actual_missing_crosswalk_bar_requires_independent_strict_bars():
|
||||
seeds = [strip(str(i), (i, 0), (i, 4), 0.45, group_id="strict-zebra") for i in [0, 1, 3, 4]]
|
||||
candidate = strip("missing", (2, 0), (2, 4), 0.45)
|
||||
added, _ = contextual_additions(seeds, [candidate])
|
||||
assert len(added) == 1
|
||||
assert added[0]["kind"] == "crosswalk_bar"
|
||||
assert not contextual_additions(seeds, [strip("spot", (2, 1), (2, 1.5), 0.45)])[0]
|
||||
duplicates = [strip(str(i), (0, 0), (0, 4), 0.45) for i in range(4)]
|
||||
assert not contextual_additions(duplicates, [candidate])[0]
|
||||
|
||||
|
||||
def test_connected_junction_needs_a_direct_frozen_anchor():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
a = strip("a", (4, 0), (9, 0), junction_components=["component"])
|
||||
b = strip("b", (8, 0), (8, 3), junction_components=["component"])
|
||||
added, _ = contextual_additions([seed], [a, b])
|
||||
assert len(added) == 2
|
||||
assert {o["context_admission"]["method"] for o in added} == {
|
||||
"observed-continuation",
|
||||
"anchored-junction",
|
||||
}
|
||||
assert not contextual_additions([], [a, b])[0]
|
||||
detached = strip("detached", (12, 0), (12, 3), junction_components=["component"])
|
||||
assert len(contextual_additions([seed], [a, detached])[0]) == 1
|
||||
|
||||
|
||||
def test_catalog_overlap_cannot_be_relabelled_a_strip():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
symbol = strip("symbol", (6, 0), (8, 0))
|
||||
symbol["representation"] = "catalog"
|
||||
added, log = contextual_additions([seed, symbol], [strip("candidate", (4, 0), (9, 0))])
|
||||
assert not added and log[0]["reason"] == "catalog-conflict"
|
||||
|
||||
|
||||
def test_no_new_geometry_outside_observed_candidate():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
candidate = strip("candidate", (4, 0), (9, 0))
|
||||
added, _ = contextual_additions([seed], [candidate])
|
||||
assert (
|
||||
unary_union([shape(o["geometry"]) for o in added])
|
||||
.difference(shape(candidate["geometry"]))
|
||||
.area
|
||||
< 1e-8
|
||||
)
|
||||
|
||||
|
||||
def test_old_well_supported_part_cannot_pay_for_bad_tail():
|
||||
from shapely.geometry import box
|
||||
|
||||
seed = strip("seed", (0, 0), (8, 0))
|
||||
candidate = strip("tail", (4, 0), (9, 0))
|
||||
support = unary_union([box(4, -0.1, 7, 0.1), box(7, -0.03, 8, 0.03), box(8, -0.02, 9, 0.02)])
|
||||
candidate["observation_geometry"] = mapping(support)
|
||||
assert not contextual_additions([seed], [candidate])[0]
|
||||
|
||||
|
||||
def test_novel_part_requires_own_rgb_and_clears_old_group_metadata():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
candidate = strip(
|
||||
"candidate",
|
||||
(4, 0),
|
||||
(9, 0),
|
||||
group_id="obsolete",
|
||||
observed_bar_count=99,
|
||||
crosswalk_parameters={"step_m": 17},
|
||||
)
|
||||
assert not contextual_additions([seed], [candidate], contrast_fn=lambda *_: {"contrast": 0})[0]
|
||||
result = contextual_additions([seed], [candidate])[0][0]
|
||||
assert all(k not in result for k in ["group_id", "observed_bar_count", "crosswalk_parameters"])
|
||||
|
||||
|
||||
def test_crosswalk_addition_uses_strict_group_not_proposal_group():
|
||||
seeds = [strip(str(i), (i, 0), (i, 4), 0.45, group_id="strict") for i in [0, 1, 3, 4]]
|
||||
candidate = strip("missing", (2, 0), (2, 4), 0.45, group_id="obsolete", observed_bar_count=99)
|
||||
result = contextual_additions(seeds, [candidate])[0][0]
|
||||
assert result["group_id"] == "strict" and "observed_bar_count" not in result
|
||||
seeds[0]["group_id"] = "ambiguous"
|
||||
assert not contextual_additions(seeds, [candidate])[0]
|
||||
|
||||
|
||||
def test_bilateral_rgb_rejects_bright_region_edge_and_accepts_paint():
|
||||
import numpy as np
|
||||
from paint_context import strip_contrast
|
||||
|
||||
params = dict(centerline=[[1, 2], [4, 2]], width_m=0.2)
|
||||
matrix = [0.01, 0, 0, 0.01, 0, 0]
|
||||
rgb = np.full((400, 600, 3), 60, dtype=np.uint8)
|
||||
rgb[190:210, 100:400] = 220
|
||||
evidence = strip_contrast(params, rgb, matrix)
|
||||
assert evidence["contrast"] > 0.5 and min(evidence["sample_counts"]) >= 4
|
||||
rgb[210:] = 250
|
||||
assert strip_contrast(params, rgb, matrix)["contrast"] < 0
|
||||
params["centerline"] = [[1, 0.15], [4, 0.15]]
|
||||
assert strip_contrast(params, rgb, matrix) is None
|
||||
|
||||
|
||||
def test_bilateral_rgb_is_rotation_invariant():
|
||||
import numpy as np
|
||||
from paint_context import strip_contrast
|
||||
|
||||
rgb = np.full((600, 600, 3), 60, dtype=np.uint8)
|
||||
yy, xx = np.mgrid[:600, :600]
|
||||
angle = 0.7
|
||||
u = np.array([np.cos(angle), np.sin(angle)])
|
||||
n = np.array([-u[1], u[0]])
|
||||
q = np.array([1, 1])
|
||||
end = q + 3 * u
|
||||
x = (xx + 0.5) * 0.01 - q[0]
|
||||
y = (yy + 0.5) * 0.01 - q[1]
|
||||
along = x * u[0] + y * u[1]
|
||||
across = x * n[0] + y * n[1]
|
||||
rgb[(along > 0) & (along < 3) & (np.abs(across) < 0.1)] = 220
|
||||
params = dict(centerline=[q.tolist(), end.tolist()], width_m=0.2)
|
||||
assert strip_contrast(params, rgb, [0.01, 0, 0, 0.01, 0, 0])["contrast"] > 0.5
|
||||
|
||||
|
||||
def test_shipping_default_never_extends_even_a_bright_supported_seed():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
candidate = strip("candidate", (4, 0), (9, 0))
|
||||
additions, decisions = admit([seed], [candidate], contrast_fn=lambda *_: {"contrast": 0.9})
|
||||
assert not additions
|
||||
assert decisions[0]["reason"] == "unqualified-continuation-disabled"
|
||||
@@ -220,3 +220,86 @@ def test_height_callback_cannot_move_xy():
|
||||
assert [[p[:2] for p in ring] for ring in after["geometry"]["coordinates"]] == (
|
||||
before["geometry"]["coordinates"]
|
||||
)
|
||||
|
||||
|
||||
def test_partial_admission_preserves_deferred_and_valid_holes():
|
||||
labels = np.zeros((7, 14), dtype=np.uint8)
|
||||
labels[1:6, 1:6] = 1
|
||||
labels[3, 3] = 0
|
||||
labels[1:6, 9:13] = 1
|
||||
p = proposal(labels)
|
||||
before = copy.deepcopy(p)
|
||||
|
||||
def heights(xy):
|
||||
return np.where(xy[:, 0] > 8, np.nan, 2.)
|
||||
|
||||
with pytest.raises(ValueError, match="height"):
|
||||
geometry.editor_features(p, height_at=heights, height_source="synthetic-support")
|
||||
result = geometry.editor_components(p, height_at=heights, height_source="synthetic-support")
|
||||
assert p == before
|
||||
assert not result["complete"]
|
||||
assert len(result["features"]) == len(result["deferred"]) == 1
|
||||
admitted = result["features"][0]
|
||||
assert len(admitted["geometry"]["coordinates"]) == 2
|
||||
deferred = result["deferred"][0]
|
||||
assert "height" in deferred["reason"]
|
||||
original = {f["id"]: f for f in p["features"]}
|
||||
assert deferred["feature"] == original[deferred["feature"]["id"]]
|
||||
assert set(original) == {admitted["id"], deferred["feature"]["id"]}
|
||||
assert [[v[:2] for v in ring] for ring in admitted["geometry"]["coordinates"]] == (
|
||||
original[admitted["id"]]["geometry"]["coordinates"]
|
||||
)
|
||||
assert "subtype" not in admitted["properties"]
|
||||
assert result["proposal_sha256"] == p["proposal_sha256"]
|
||||
|
||||
|
||||
def test_partial_admission_does_not_hide_touching_hole():
|
||||
p = proposal([[1, 1, 1, 0, 1], [1, 0, 1, 0, 1], [1, 1, 0, 0, 1]])
|
||||
result = geometry.editor_components(
|
||||
p, height_at=lambda xy: np.ones(len(xy)), height_source="synthetic-plane"
|
||||
)
|
||||
assert len(result["features"]) == len(result["deferred"]) == 1
|
||||
assert shape(result["deferred"][0]["feature"]["geometry"]).area == 7
|
||||
assert shape(result["features"][0]["geometry"]).area == 3
|
||||
|
||||
|
||||
def test_partial_admission_keeps_atomic_integrity_and_batch_budget(monkeypatch):
|
||||
p = proposal([[1, 0, 1]])
|
||||
|
||||
def forbidden(xy):
|
||||
raise AssertionError("Must reject entire batch before callback")
|
||||
|
||||
changed = copy.deepcopy(p)
|
||||
changed["features"][0]["geometry"]["coordinates"][0][0][0] += 1
|
||||
with pytest.raises(ValueError, match="Changed"):
|
||||
geometry.editor_components(changed, height_at=forbidden, height_source="test")
|
||||
duplicate = copy.deepcopy(p)
|
||||
duplicate["features"][1]["id"] = duplicate["features"][0]["id"]
|
||||
duplicate.pop("proposal_sha256")
|
||||
duplicate["proposal_sha256"] = geometry.digest(duplicate)
|
||||
with pytest.raises(ValueError, match="identity"):
|
||||
geometry.editor_components(duplicate, height_at=forbidden, height_source="test")
|
||||
monkeypatch.setattr(geometry, "MAX_EDITOR_WORK", 20)
|
||||
with pytest.raises(ValueError, match="work budget"):
|
||||
geometry.editor_components(p, height_at=forbidden, height_source="test")
|
||||
|
||||
|
||||
def test_partial_all_valid_equals_strict_and_propagates_programming_error():
|
||||
p = proposal([[1, 0, 1]])
|
||||
result = geometry.editor_components(
|
||||
p, height_at=lambda xy: np.ones(len(xy)), height_source="test"
|
||||
)
|
||||
assert result["complete"] and result["deferred"] == []
|
||||
assert result["features"] == geometry.editor_features(
|
||||
p, height_at=lambda xy: np.ones(len(xy)), height_source="test"
|
||||
)
|
||||
|
||||
for error_type in (ValueError, RuntimeError):
|
||||
def broken(xy, error_type=error_type):
|
||||
raise error_type("Unexpected sampler implementation failure")
|
||||
|
||||
with pytest.raises(error_type, match="Unexpected"):
|
||||
geometry.editor_components(p, height_at=broken, height_source="test")
|
||||
|
||||
with pytest.raises(ValueError, match="invalid shape"):
|
||||
geometry.editor_components(p, height_at=lambda xy: 3., height_source="test")
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
"""Product-level geometry, abstention and provenance regression checks."""
|
||||
|
||||
import copy
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from shapely import affinity, intersects_xy
|
||||
from shapely.geometry import Polygon, box, shape
|
||||
from shapely.ops import unary_union
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "simulation/semantic-learning"))
|
||||
import paint_objects as po # noqa: E402
|
||||
|
||||
CATALOG = json.loads((ROOT / "src/k1link/simulation/ai_polygon/marking-templates.json").read_text())
|
||||
MATRIX = [0.04, 0, 0, -0.04, 0, 10.24]
|
||||
|
||||
|
||||
def raster(g, matrix=MATRIX):
|
||||
yy, xx = np.indices((256, 256))
|
||||
a, b, d, e, x, y = matrix
|
||||
return intersects_xy(
|
||||
g, a * (xx + 0.5) + b * (yy + 0.5) + x, d * (xx + 0.5) + e * (yy + 0.5) + y
|
||||
).astype("uint8")
|
||||
|
||||
|
||||
def assemble(g, *, matrix=MATRIX, rgb=None):
|
||||
mask = raster(g, matrix)
|
||||
if rgb is None:
|
||||
rgb = np.repeat((30 + mask * 180)[:, :, None], 3, axis=2)
|
||||
return po.assemble(mask, rgb, pixel_to_scene=matrix, source_id="synthetic", catalog=CATALOG)
|
||||
|
||||
|
||||
def test_separate_dashes_stay_separate_and_are_rectangles():
|
||||
g = unary_union([box(1, 4, 3, 4.16), box(3.5, 4, 5.5, 4.16)])
|
||||
out = assemble(g)
|
||||
assert len(out["objects"]) == 2
|
||||
for obj in out["objects"]:
|
||||
assert obj["representation"] == "strip"
|
||||
assert len(obj["parameters"]["centerline"]) == 2
|
||||
assert len(shape(obj["geometry"]).exterior.coords) == 5
|
||||
assert po.reconstruct(obj, CATALOG).equals(shape(obj["geometry"]))
|
||||
assert not unary_union([shape(o["geometry"]) for o in out["objects"]]).intersects(
|
||||
box(3.1, 4, 3.4, 4.16)
|
||||
)
|
||||
|
||||
|
||||
def test_crosswalk_keeps_four_observed_bars_not_catalog_six():
|
||||
out = assemble(unary_union([box(1 + i, 2, 1.48 + i, 6) for i in range(4)]))
|
||||
bars = out["objects"]
|
||||
assert len(bars) == 4
|
||||
assert {o["kind"] for o in bars} == {"crosswalk_bar"}
|
||||
assert len({o["group_id"] for o in bars}) == 1
|
||||
assert {o["observed_bar_count"] for o in bars} == {4}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("angle", [0, .43, 1.67])
|
||||
def test_small_paint_wear_becomes_rectangle_without_filling_real_large_void(angle):
|
||||
original = box(1, 2, 5, 2.5).difference(box(2, 2.18, 2.13, 2.30))
|
||||
observed = affinity.translate(affinity.rotate(original, angle, use_radians=True), 47, -23)
|
||||
params = po.fit_strip(observed, po.Policy())
|
||||
assert params is not None and len(params["centerline"]) == 2
|
||||
fitted = po.strip_geometry(params["centerline"], params["width_m"])
|
||||
assert len(fitted.exterior.coords) == 5 and not fitted.interiors
|
||||
assert po.agreement(observed, fitted, .06)["score"] > .95
|
||||
assert len(observed.interiors) == 1 # raw observation was not rewritten
|
||||
large_void = box(1, 2, 5, 2.5).difference(box(1.8, 2.08, 4.2, 2.42))
|
||||
assert po.fit_strip(large_void, po.Policy()) is None
|
||||
|
||||
|
||||
def test_worn_crosswalk_bars_are_grouped_without_imaginary_bars():
|
||||
bars = [box(1+i, 2, 1.48+i, 6).difference(box(1.15+i, 3, 1.27+i, 3.16))
|
||||
for i in range(4)]
|
||||
out = assemble(unary_union(bars))
|
||||
assert len(out["objects"]) == 4
|
||||
assert {o["kind"] for o in out["objects"]} == {"crosswalk_bar"}
|
||||
assert all(len(o["parameters"]["centerline"]) == 2 for o in out["objects"])
|
||||
|
||||
|
||||
def test_actual_visible_a_catalog_and_uniform_scale():
|
||||
template = next(t for t in CATALOG["templates"] if t["id"] == "letter_A_v3")
|
||||
g = po.catalog_geometry(template, [5, 5], 0.23, 1)
|
||||
out = assemble(g)
|
||||
assert len(out["objects"]) == 1
|
||||
obj = out["objects"][0]
|
||||
assert obj["kind"] == "letter_A_v3"
|
||||
assert obj["representation"] == "catalog"
|
||||
assert len(shape(obj["geometry"]).interiors) == 1
|
||||
assert set(obj["parameters"]) == {"center", "angle_radians", "scale", "template_id"}
|
||||
assert po.reconstruct(obj, CATALOG).equals(shape(obj["geometry"]))
|
||||
assert out["human_geometry_used"] is False and out["labels_used"] is False
|
||||
|
||||
|
||||
def test_unknown_shapes_and_uniform_background_have_no_fallback():
|
||||
g = Polygon([(1, 1), (4, 1), (5, 4), (2, 5), (1, 1)])
|
||||
out = assemble(g)
|
||||
assert not out["objects"] and out["rejected"]
|
||||
assert {r["status"] for r in out["rejected"]} == {"unresolved-not-background"}
|
||||
out = assemble(box(1, 3, 7, 3.2), rgb=np.full((256, 256, 3), 100, np.uint8))
|
||||
assert not out["objects"]
|
||||
|
||||
|
||||
def test_translation_and_rotation_do_not_depend_on_scene_coordinates():
|
||||
g = box(1, 4, 5, 4.2)
|
||||
one = assemble(g)
|
||||
theta = 0.7
|
||||
c, s = np.cos(theta), np.sin(theta)
|
||||
shifted = affinity.translate(
|
||||
affinity.rotate(g, theta, origin=(0, 0), use_radians=True), 500, -200
|
||||
)
|
||||
a, b, d, e, x, y = MATRIX
|
||||
matrix = [
|
||||
c * a - s * d,
|
||||
c * b - s * e,
|
||||
s * a + c * d,
|
||||
s * b + c * e,
|
||||
c * x - s * y + 500,
|
||||
s * x + c * y - 200,
|
||||
]
|
||||
two = assemble(shifted, matrix=matrix)
|
||||
assert len(one["objects"]) == len(two["objects"]) == 1
|
||||
restored = affinity.rotate(
|
||||
affinity.translate(shape(two["objects"][0]["geometry"]), -500, 200),
|
||||
-theta,
|
||||
origin=(0, 0),
|
||||
use_radians=True,
|
||||
)
|
||||
assert restored.hausdorff_distance(shape(one["objects"][0]["geometry"])) < 1e-6
|
||||
|
||||
|
||||
def test_surface_uses_interior_and_keeps_2d_when_unsupported():
|
||||
obj = assemble(box(1, 4, 5, 4.2))["objects"][0]
|
||||
original = copy.deepcopy(obj)
|
||||
yy, xx = np.indices((256, 256))
|
||||
X = (xx + 0.5) * 0.04
|
||||
Y = 10.24 - (yy + 0.5) * 0.04
|
||||
z = 2 + 0.03 * X - 0.01 * Y
|
||||
args = dict(depth=20 - z, camera_eye_z=20, pixel_to_scene=MATRIX, catalog=CATALOG)
|
||||
height, info = po.surface_plane(obj, alpha=np.ones_like(z), **args)
|
||||
assert height is not None and info["residual_p95_m"] < 1e-8
|
||||
assert height(2, 4) == pytest.approx(2.02)
|
||||
height, info = po.surface_plane(obj, alpha=np.zeros_like(z), **args)
|
||||
assert height is None and info["reason"] == "insufficient-surface-support"
|
||||
assert obj == original
|
||||
|
||||
|
||||
def test_export_keeps_window_flags_and_source_parameters_after_editor_move():
|
||||
from k1link.simulation.ai_polygon.semantic_edits import apply_operations
|
||||
|
||||
obj = assemble(box(-1, 4, 5, 4.2))["objects"][0]
|
||||
assert "tile-edge" in obj["support_boundary"]
|
||||
features = po.editor_features(
|
||||
obj,
|
||||
catalog=CATALOG,
|
||||
height=lambda x, y: np.asarray(x) * 0 + 2,
|
||||
surface={"source": "synthetic-plane"},
|
||||
height_source="a" * 64,
|
||||
observation_source="b" * 64,
|
||||
)
|
||||
before = copy.deepcopy(features)
|
||||
doc = {"features": features, "source": {"gaussian_only": True}}
|
||||
changed = apply_operations(
|
||||
doc, [dict(kind="transform", feature_id=features[0]["id"], delta=[0.5, 0.25], angle=0)]
|
||||
)
|
||||
after = changed["features"][0]
|
||||
assert after["geometry"] != before[0]["geometry"]
|
||||
assert (
|
||||
after["properties"]["recognition_snapshot"]
|
||||
== before[0]["properties"]["recognition_snapshot"]
|
||||
)
|
||||
assert (
|
||||
after["properties"]["recognition_snapshot"]["role"]
|
||||
== "immutable-automatic-source-not-current-edited-geometry"
|
||||
)
|
||||
assert after["properties"]["support_boundary"] == ["tile-edge"]
|
||||
assert after["properties"]["instance_completeness"] == "not-assessed"
|
||||
assert "primitive_parameters" not in after["properties"]
|
||||
assert "template_frame" not in after["properties"]
|
||||
|
||||
|
||||
def test_invalid_surface_evidence_propagates_instead_of_fake_height():
|
||||
obj = assemble(box(1, 4, 5, 4.2))["objects"][0]
|
||||
with pytest.raises(ValueError, match="Invalid surface"):
|
||||
po.surface_plane(
|
||||
obj,
|
||||
depth=np.ones((10, 10)),
|
||||
alpha=np.ones((5, 5)),
|
||||
camera_eye_z=20,
|
||||
pixel_to_scene=MATRIX,
|
||||
catalog=CATALOG,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [255, 2, -1])
|
||||
def test_annotation_or_unknown_is_not_an_automatic_input(value):
|
||||
with pytest.raises(ValueError, match="Binary automatic"):
|
||||
po.assemble(
|
||||
np.full((8, 8), value, dtype=int),
|
||||
np.zeros((8, 8, 3), np.uint8),
|
||||
pixel_to_scene=MATRIX,
|
||||
source_id="bad",
|
||||
catalog=CATALOG,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scale", [0.05, 0.12, 0.2, 0.5, 1.0, 2.0])
|
||||
def test_distinctive_parts_do_not_invent_missing_head_even_below_tolerance(scale):
|
||||
template = next(t for t in CATALOG["templates"] if t["id"] == "straight_arrow")
|
||||
fitted = po.catalog_geometry(template, [5, 5], 0, scale)
|
||||
# A shaft extends the whole candidate length, but has no head or wings.
|
||||
observed = box(5 - 2.5 * scale, 5 - .075 * scale,
|
||||
5 + 2.5 * scale, 5 + .075 * scale)
|
||||
mask = raster(observed)
|
||||
rgb = np.repeat((30 + mask * 180)[:, :, None], 3, axis=2)
|
||||
audit, reason = po.arbitrate_symbol(
|
||||
observed, fitted, po.Policy(), center=[5, 5], angle=0,
|
||||
rgb=rgb, pixel_to_scene=MATRIX,
|
||||
)
|
||||
assert reason == "unsupported-template-part"
|
||||
assert min(p["unbuffered_precision"] for p in audit["parts"]) == 0
|
||||
assert audit["local_support_buffer_m"] <= .06
|
||||
assert audit["unbuffered_witness_required"] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kind", ["straight_arrow", "right_arrow", "straight_left_arrow", "letter_A_v3"]
|
||||
)
|
||||
@pytest.mark.parametrize("scale", [0.2, 0.5, 1.0, 2.0])
|
||||
def test_true_symbol_parts_remain_supported(kind, scale):
|
||||
template = next(t for t in CATALOG["templates"] if t["id"] == kind)
|
||||
g = po.catalog_geometry(template, [5, 5], .37, scale)
|
||||
rgb = np.repeat((30 + raster(g) * 180)[:, :, None], 3, axis=2)
|
||||
audit, reason = po.arbitrate_symbol(
|
||||
g, g, po.Policy(), center=[5, 5], angle=.37, rgb=rgb, pixel_to_scene=MATRIX,
|
||||
)
|
||||
assert reason is None
|
||||
assert min(p["precision"] for p in audit["parts"]) == pytest.approx(1)
|
||||
|
||||
|
||||
def test_missing_one_head_wing_cannot_be_paid_for_by_shaft():
|
||||
template = next(t for t in CATALOG["templates"] if t["id"] == "straight_arrow")
|
||||
fitted = po.catalog_geometry(template, [5, 5], 0, 1)
|
||||
observed = fitted.difference(box(5.45, 5.075, 7.5, 5.4))
|
||||
rgb = np.repeat((30 + raster(observed) * 180)[:, :, None], 3, axis=2)
|
||||
# The old whole-shape score is acceptable despite the absent distinctive wing.
|
||||
assert po.agreement(observed, fitted, .06)["score"] >= po.Policy().min_symbol_score
|
||||
_, reason = po.arbitrate_symbol(
|
||||
observed, fitted, po.Policy(), center=[5, 5], angle=0,
|
||||
rgb=rgb, pixel_to_scene=MATRIX,
|
||||
)
|
||||
assert reason == "unsupported-template-part"
|
||||
|
||||
|
||||
def test_valid_strip_competes_on_the_same_observed_support():
|
||||
observed = box(1, 4, 7, 4.2)
|
||||
rgb = np.repeat((30 + raster(observed) * 180)[:, :, None], 3, axis=2)
|
||||
audit, reason = po.arbitrate_symbol(
|
||||
observed, observed, po.Policy(), center=[4, 4.1], angle=0,
|
||||
rgb=rgb, pixel_to_scene=MATRIX,
|
||||
)
|
||||
assert min(p["precision"] for p in audit["parts"]) == pytest.approx(1)
|
||||
assert audit["strip_competitor"]["score"] == pytest.approx(1)
|
||||
assert reason == "strip-competitor-not-beaten"
|
||||
|
||||
|
||||
def test_true_raster_arrow_survives_final_arbitration():
|
||||
template = next(t for t in CATALOG["templates"] if t["id"] == "straight_arrow")
|
||||
out = assemble(po.catalog_geometry(template, [5, 5], .23, 1))
|
||||
assert len(out["objects"]) == 1
|
||||
obj = out["objects"][0]
|
||||
assert obj["kind"] == "straight_arrow"
|
||||
assert min(p["precision"] for p in obj["arbitration"]["parts"]) >= .65
|
||||
|
||||
|
||||
def test_bent_strip_explanation_not_overruled_by_identical_symbol():
|
||||
observed = po.strip_geometry([[1, 3], [3, 3.1], [5, 3.3]], .15)
|
||||
rgb = np.repeat((30 + raster(observed) * 180)[:, :, None], 3, axis=2)
|
||||
params = po.fit_strip(observed, po.Policy())
|
||||
assert params is not None
|
||||
fitted = po.strip_geometry(params["centerline"], params["width_m"])
|
||||
audit, reason = po.arbitrate_symbol(
|
||||
observed, fitted, po.Policy(), center=[3, 3.15], angle=0,
|
||||
rgb=rgb, pixel_to_scene=MATRIX,
|
||||
)
|
||||
assert audit["strip_competitor"] is not None
|
||||
assert reason == "strip-competitor-not-beaten"
|
||||
|
||||
|
||||
def test_local_part_support_with_hole_is_world_rigid_transform_invariant():
|
||||
template = next(t for t in CATALOG["templates"] if t["id"] == "letter_A_v3")
|
||||
g = po.catalog_geometry(template, [5, 5], .23, 1)
|
||||
observed = g.difference(box(4.2, 4.2, 4.3, 5.5))
|
||||
rgb = np.repeat((30 + raster(observed) * 180)[:, :, None], 3, axis=2)
|
||||
one, reason_one = po.arbitrate_symbol(
|
||||
observed, g, po.Policy(), center=[5, 5], angle=.23, rgb=rgb, pixel_to_scene=MATRIX,
|
||||
)
|
||||
theta = .61
|
||||
c, s = np.cos(theta), np.sin(theta)
|
||||
def moved(q):
|
||||
return affinity.translate(
|
||||
affinity.rotate(q, theta, origin=(0, 0), use_radians=True), 800, -130
|
||||
)
|
||||
center = np.array([5,5]) @ np.array([[c,s],[-s,c]]) + [800,-130]
|
||||
a,b,d,e,x,y = MATRIX
|
||||
matrix = [c*a-s*d,c*b-s*e,s*a+c*d,s*b+c*e,c*x-s*y+800,s*x+c*y-130]
|
||||
two, reason_two = po.arbitrate_symbol(
|
||||
moved(observed), moved(g), po.Policy(), center=center, angle=.23+theta,
|
||||
rgb=rgb, pixel_to_scene=matrix,
|
||||
)
|
||||
assert reason_two == reason_one
|
||||
assert [p["cell"] for p in one["parts"]] == [p["cell"] for p in two["parts"]]
|
||||
for a,b in zip(one["parts"], two["parts"], strict=True):
|
||||
assert b["precision"] == pytest.approx(a["precision"], abs=1e-8)
|
||||
assert b["unbuffered_precision"] == pytest.approx(a["unbuffered_precision"], abs=1e-8)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("angle", [0, .71, 2.1])
|
||||
def test_width_wear_does_not_reject_supported_straight_bar(angle):
|
||||
# Edge wear widens the percentile spread, while the whole observed stripe
|
||||
# still strongly supports one straight primitive.
|
||||
observed = box(1, 2, 5, 2.5).difference(box(2, 2.28, 3, 2.6))
|
||||
observed = affinity.rotate(observed, angle, use_radians=True)
|
||||
params = po.fit_strip(observed, po.Policy())
|
||||
assert params is not None
|
||||
assert len(params["centerline"]) == 2
|
||||
g = po.strip_geometry(params["centerline"], params["width_m"])
|
||||
assert po.agreement(observed, g, .06)["score"] >= .78
|
||||
assert observed.hausdorff_distance(g) <= .25
|
||||
|
||||
|
||||
def test_large_bend_is_not_straightened_into_unobserved_paint():
|
||||
observed = po.strip_geometry([[1, 2], [3, 3], [5, 2]], .16)
|
||||
params = po.fit_strip(observed, po.Policy())
|
||||
if params is not None:
|
||||
assert len(params["centerline"]) > 2
|
||||
g = po.strip_geometry(params["centerline"], params["width_m"])
|
||||
assert not g.intersects(box(2.9, 1.9, 3.1, 2.1))
|
||||
|
||||
|
||||
def crosswalk_seed(x, identity):
|
||||
p = dict(centerline=[[x, 2], [x, 6]], width_m=.48)
|
||||
return dict(id=identity, representation="strip", kind="linear_marking", parameters=p,
|
||||
observation_ids=[identity], support_boundary=[])
|
||||
|
||||
|
||||
def test_crosswalk_group_recovers_existing_bar_but_not_missing_slot_or_speck():
|
||||
seeds = [crosswalk_seed(x, str(i)) for i, x in enumerate([1.2, 2.1, 3.9])]
|
||||
observed = box(2.76, 2, 3.24, 6).difference(box(2.76, 3.2, 2.84, 4.0))
|
||||
feature = dict(id="weak", geometry=po.mapping(observed), properties={"support_boundary": []})
|
||||
mask = raster(observed)
|
||||
rgb = np.repeat((30 + mask * 180)[:, :, None], 3, axis=2)
|
||||
args = dict(rgb=rgb, pixel_to_scene=MATRIX, policy=po.Policy())
|
||||
out = po.recover_crosswalks(seeds, [feature], **args)
|
||||
assert len(out) == 1 and out[0]["observation_ids"] == ["weak"]
|
||||
assert set(out[0]["recovery"]["seed_ids"]) == {"0", "1", "2"}
|
||||
assert not po.recover_crosswalks(seeds, [], **args)
|
||||
speck = dict(feature, geometry=po.mapping(box(2.9, 3.5, 3.1, 3.7)))
|
||||
assert not po.recover_crosswalks(seeds, [speck], **args)
|
||||
assert not po.recover_crosswalks(seeds, [feature], **dict(args, rgb=np.full_like(rgb, 90)))
|
||||
po.group_crosswalks(seeds + out)
|
||||
assert {o["observed_bar_count"] for o in seeds + out} == {4}
|
||||
|
||||
|
||||
def test_crosswalk_duplicate_windows_are_not_independent_group_seeds():
|
||||
seeds = [crosswalk_seed(1.2, str(i)) for i in range(3)]
|
||||
po.group_crosswalks(seeds)
|
||||
assert all("group_id" not in s for s in seeds)
|
||||
|
||||
|
||||
def test_crosswalk_group_is_order_independent_and_clears_stale_metadata():
|
||||
seeds = [crosswalk_seed(x, str(i)) for i, x in enumerate([1.2, 2.1, 3.0, 3.9])]
|
||||
shuffled = list(reversed(copy.deepcopy(seeds)))
|
||||
po.group_crosswalks(seeds)
|
||||
po.group_crosswalks(shuffled)
|
||||
assert {s["id"]: s["group_id"] for s in seeds} == {s["id"]: s["group_id"] for s in shuffled}
|
||||
remaining = seeds[:2]
|
||||
po.group_crosswalks(remaining)
|
||||
assert all("group_id" not in s and s["kind"] == "linear_marking" for s in remaining)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reverse", [False, True])
|
||||
@pytest.mark.parametrize("holes", [False, True])
|
||||
def test_group_never_merges_two_separate_candidates_in_one_slot(reverse, holes):
|
||||
seeds = [crosswalk_seed(x, str(i)) for i, x in enumerate([1.2, 2.1, 3.9])]
|
||||
for o in seeds:
|
||||
o["parameters"]["width_m"] = .30
|
||||
geometries = [box(x-.11, 2, x+.11, 6).difference(box(x-.01,3,x+.01,3.25))
|
||||
for x in [2.86, 3.14]]
|
||||
if not holes:
|
||||
geometries = [box(x-.11, 2, x+.11, 6) for x in [2.86, 3.14]]
|
||||
observations = [dict(id=str(i+10),geometry=po.mapping(g),properties={"support_boundary": []})
|
||||
for i,g in enumerate(geometries)]
|
||||
if reverse:
|
||||
observations.reverse()
|
||||
mask=raster(unary_union(geometries))
|
||||
rgb=np.repeat((30+mask*180)[:,:,None],3,axis=2)
|
||||
assert not po.recover_crosswalks(seeds,observations,rgb=rgb,
|
||||
pixel_to_scene=MATRIX,policy=po.Policy())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("angle", [0, .61, 1.47])
|
||||
def test_observed_t_junction_is_two_strips_without_lost_arm(angle):
|
||||
g = box(1,2,7,2.2).union(box(4,2,4.3,6))
|
||||
g = affinity.rotate(g,angle,use_radians=True)
|
||||
params=po.fit_junction_strips(g,po.Policy())
|
||||
assert len(params)==2
|
||||
rebuilt=unary_union([po.strip_geometry(p["centerline"],p["width_m"]) for p in params])
|
||||
assert po.agreement(g,rebuilt,.06)["recall"]>=.90
|
||||
assert g.hausdorff_distance(rebuilt)<=.25
|
||||
|
||||
|
||||
def test_final_assembler_exports_each_junction_arm_with_same_observation():
|
||||
out=assemble(box(1,2,7,2.2).union(box(4,2,4.3,6)))
|
||||
arms=[o for o in out["objects"] if o.get("decomposition")=="observed-orthogonal-junction"]
|
||||
assert len(arms)==2
|
||||
assert arms[0]["observation_ids"]==arms[1]["observation_ids"]
|
||||
assert all(len(o["parameters"]["centerline"])==2 for o in arms)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kind", ["letter_A_v3", "straight_arrow", "right_arrow", "straight_left_arrow"]
|
||||
)
|
||||
def test_junction_decomposition_does_not_consume_symbol(kind):
|
||||
template=next(t for t in CATALOG["templates"] if t["id"]==kind)
|
||||
g=po.catalog_geometry(template,[5,5],.37,1)
|
||||
assert not po.fit_junction_strips(g,po.Policy())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("angle", [0, .61, 1.47])
|
||||
def test_junction_preserves_true_open_gap_even_inside_connected_component(angle):
|
||||
frame = unary_union([box(1,2,7,2.2),box(1,5.8,7,6),
|
||||
box(1,2,1.2,6),box(6.8,2,7,6)])
|
||||
gap=box(3.85,5.7,4.15,6.1)
|
||||
observed=affinity.rotate(frame.difference(gap),angle,use_radians=True)
|
||||
absent=affinity.rotate(box(3.90,5.81,4.10,5.99),angle,origin=(4,4),use_radians=True)
|
||||
# The default affine origin above equals frame centre, fixed explicitly for the gap.
|
||||
params=po.fit_junction_strips(observed,po.Policy())
|
||||
rebuilt=unary_union([po.strip_geometry(p["centerline"],p["width_m"]) for p in params])
|
||||
assert rebuilt.intersection(absent).area < 1e-8
|
||||
|
||||
|
||||
def test_short_irregular_width_needs_group_support_not_just_rgb():
|
||||
g=box(1,2,3.4,2.5).difference(box(1.4,2.25,3.0,2.6))
|
||||
assert po.fit_strip(g,po.Policy()) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("angle", [0,.61])
|
||||
def test_junction_does_not_fill_elongated_internal_negative_space(angle):
|
||||
g=box(1,2,7,2.2).union(box(4,2,4.3,6))
|
||||
hole=box(2.7,2.02,2.95,2.18)
|
||||
g=affinity.rotate(g.difference(hole),angle,origin=(0,0),use_radians=True)
|
||||
hole=affinity.rotate(hole,angle,origin=(0,0),use_radians=True)
|
||||
params=po.fit_junction_strips(g,po.Policy())
|
||||
union=unary_union([po.strip_geometry(p["centerline"],p["width_m"]) for p in params])
|
||||
assert union.intersection(hole).area<1e-8
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Raw observation projection must preserve holes, XY and explicit refusals."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from shapely.geometry import Polygon, box
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
import paint_projection as pp # noqa: E402
|
||||
|
||||
|
||||
def test_zero_weight_neighbours_and_boundary_do_not_remove_observation():
|
||||
d = np.full((3, 3), 20.)
|
||||
alpha = np.ones_like(d)
|
||||
alpha[1, 1] = 0
|
||||
args = dict(depth=d, alpha=alpha, camera_eye_z=25., pixel_to_scene=[1, 0, 0, 1, 0, 0])
|
||||
placed = pp.bilinear_geometry(box(.5, .5, 2.5, 2.5), **args)
|
||||
assert all(q[2] == 5 for q in placed.exterior.coords)
|
||||
with pytest.raises(pp.HeightRefusal, match="missing-observed"):
|
||||
pp.bilinear_geometry(box(.6, .6, 2.4, 2.4), **args)
|
||||
|
||||
|
||||
def test_raw_interior_plane_preserves_exact_xy_and_hole_with_unreliable_edge():
|
||||
d = np.full((60, 60), 20.)
|
||||
alpha = np.ones_like(d)
|
||||
alpha[9:11, 9:11] = 0
|
||||
g = Polygon(box(1, 1, 4, 4).exterior.coords, [box(2, 2, 2.5, 2.5).exterior.coords])
|
||||
before = [list(r.coords) for r in [g.exterior, *g.interiors]]
|
||||
placed, info = pp.project_observation(
|
||||
g, depth=d, alpha=alpha, camera_eye_z=25., pixel_to_scene=[.1, 0, 0, .1, 0, 0],
|
||||
)
|
||||
assert info["method"] == "observed-interior-plane"
|
||||
assert info["samples"] >= 24 and info["residual_p95_m"] < 1e-10
|
||||
for old, ring in zip(before, [placed.exterior, *placed.interiors], strict=True):
|
||||
assert [q[:2] for q in ring.coords] == old
|
||||
assert np.allclose(np.asarray(ring.coords)[:, 2], 5)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["missing", "discontinuity"])
|
||||
def test_unreliable_raw_surface_remains_2d_without_invented_height(bad):
|
||||
d = np.full((60, 60), 20.)
|
||||
alpha = np.ones_like(d)
|
||||
if bad == "missing":
|
||||
alpha[:] = 0
|
||||
else:
|
||||
alpha[9:11, 9:11] = 0
|
||||
d[:, 25:] += 4
|
||||
placed, info = pp.project_observation(
|
||||
box(1, 1, 4, 4), depth=d, alpha=alpha,
|
||||
camera_eye_z=25., pixel_to_scene=[.1, 0, 0, .1, 0, 0],
|
||||
)
|
||||
assert placed is None and info["placement_status"] == "2d-only" and info["reason"]
|
||||
|
||||
|
||||
def test_invalid_projection_inputs_are_not_hidden_as_missing_support():
|
||||
with pytest.raises(ValueError, match="Invalid projection"):
|
||||
pp.project_observation(box(0, 0, 1, 1), depth=np.ones((2, 2)),
|
||||
alpha=np.ones((3, 3)), camera_eye_z=25,
|
||||
pixel_to_scene=[1, 0, 0, 1, 0, 0])
|
||||
@@ -160,3 +160,55 @@ def test_save_and_worker_receipt_run_outside_the_event_loop(tmp_path, monkeypatc
|
||||
response = client.post(path, json={})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["thread"] != event_loop
|
||||
|
||||
|
||||
def test_http_representation_selection_and_pinned_manual_branch(tmp_path):
|
||||
import uuid
|
||||
|
||||
world, model, maps, store, old_sha = make_setup(tmp_path)
|
||||
raw, auto = copy.deepcopy(model), copy.deepcopy(model)
|
||||
raw['semantic_stage'] = 'raw'
|
||||
auto['semantic_stage'] = 'algorithmic'
|
||||
published = maps.publish_pair(world, raw, auto)
|
||||
|
||||
def invoke(fn, *args):
|
||||
try:
|
||||
return fn(*args)
|
||||
except FileNotFoundError as exc:
|
||||
raise HTTPException(404) from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(build_semantic_edits_router(
|
||||
tmp_path, SimpleNamespace(get=lambda _: world, list=lambda: [world]), maps,
|
||||
invoke, lambda _: None,
|
||||
))
|
||||
path = '/worlds/fixture/semantic-edits'
|
||||
branch = str(uuid.uuid4())
|
||||
with TestClient(app) as client:
|
||||
versions = client.get('/worlds/fixture/semantic-versions').json()
|
||||
assert versions['manual'] == []
|
||||
assert versions['raw_sha256'] == published['raw_sha256']
|
||||
observed = client.get(path, params={'source': 'raw'}).json()
|
||||
assert observed['read_only'] and 'edited' not in observed
|
||||
assert observed['model'] == raw
|
||||
assert client.post(path, json={
|
||||
**change(published['raw_sha256']), 'branch_id': branch,
|
||||
}).status_code == 400
|
||||
assert client.get(path, params={'source': 'manual', 'branch_id': branch}).status_code == 404
|
||||
pinned = client.get(path, params={
|
||||
'source': 'algorithmic', 'model_sha256': old_sha,
|
||||
}).json()
|
||||
assert pinned['model'] == model
|
||||
saved = client.post(path, json={**change(old_sha), 'branch_id': branch})
|
||||
assert saved.status_code == 200, saved.text
|
||||
assert saved.json()['model_sha256'] == old_sha
|
||||
assert client.get(path, params={
|
||||
'source': 'manual', 'branch_id': branch,
|
||||
}).json()['revision'] == saved.json()['revision']
|
||||
assert client.get(path, params={'source': 'algorithmic'}).json()['model'] == auto
|
||||
assert len(client.get('/worlds/fixture/semantic-versions').json()['manual']) == 1
|
||||
assert not store._path(world).exists()
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Whole-scene publications never rebase human work or admit raw edits."""
|
||||
|
||||
import copy
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import pytest
|
||||
from test_semantic_edits import change, make_setup
|
||||
|
||||
from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits
|
||||
|
||||
|
||||
def pair(model):
|
||||
raw, automatic = copy.deepcopy(model), copy.deepcopy(model)
|
||||
raw["semantic_stage"] = "raw"
|
||||
automatic["semantic_stage"] = "algorithmic"
|
||||
return raw, automatic
|
||||
|
||||
|
||||
def test_publication_keeps_manual_base_export_and_legacy_receipt(tmp_path):
|
||||
world, model, maps, edits, sha = make_setup(tmp_path)
|
||||
legacy = edits.save(world, change(sha))
|
||||
before = edits.export(world, legacy["revision"])
|
||||
raw, automatic = pair(model)
|
||||
automatic["features"][0]["geometry"]["coordinates"][1][1] = -1
|
||||
published = maps.publish_pair(world, raw, automatic)
|
||||
assert maps.get(world) == automatic
|
||||
assert edits.get(world)["edited"] == legacy["edited"]
|
||||
assert edits.export(world, legacy["revision"]) == before
|
||||
assert edits.get(world, "raw")["model"] == raw
|
||||
assert edits.get(world, "algorithmic")["revision"] is None
|
||||
assert edits.versions(world)["manual"][0]["branch_id"] is None
|
||||
assert published["raw_sha256"] != published["sha256"]
|
||||
receipt = dict(
|
||||
state="received", package_sha256=before["sha256"], dataset_sha256=None, sample_count=0
|
||||
)
|
||||
assert edits.receipt(world, legacy["revision"], receipt) == receipt
|
||||
assert edits.export(world, legacy["revision"]) == before
|
||||
|
||||
|
||||
def test_new_branch_does_not_inherit_manual_and_pins_stale_display(tmp_path):
|
||||
world, model, maps, edits, sha = make_setup(tmp_path)
|
||||
legacy = edits.save(world, change(sha))
|
||||
raw, auto = pair(model)
|
||||
maps.publish_pair(world, raw, auto)
|
||||
branch = str(uuid.uuid4())
|
||||
body = {**change(sha), "branch_id": branch}
|
||||
saved = edits.save(world, body)
|
||||
assert saved["branch_id"] == branch
|
||||
assert saved["model_sha256"] == sha
|
||||
assert len(saved["history"]) == 1
|
||||
assert edits.get(world)["revision"] == legacy["revision"]
|
||||
assert edits.get(world, "manual", branch)["edited"] == saved["edited"]
|
||||
reopened = SemanticEdits(tmp_path, maps)
|
||||
assert reopened.save(world, body) == saved
|
||||
assert len(reopened.versions(world)["manual"]) == 2
|
||||
exported = reopened.export(world, saved["revision"])
|
||||
assert exported["package"]["revisions"][0]["branch_id"] == branch
|
||||
assert any(
|
||||
row.get("branch_id") == branch for row in edits.pending([{**world, "world_id": "world"}])
|
||||
)
|
||||
|
||||
|
||||
def test_raw_cannot_be_saved_or_used_as_a_draft_base(tmp_path):
|
||||
world, model, maps, edits, _ = make_setup(tmp_path)
|
||||
raw, auto = pair(model)
|
||||
pointer = maps.publish_pair(world, raw, auto)
|
||||
view = edits.get(world, "raw")
|
||||
assert view["read_only"] is True and "edited" not in view
|
||||
for branch in [None, str(uuid.uuid4())]:
|
||||
body = change(pointer["raw_sha256"])
|
||||
if branch:
|
||||
body["branch_id"] = branch
|
||||
with pytest.raises(ValueError, match="только для просмотра"):
|
||||
edits.save(world, body)
|
||||
assert not edits._path(world, branch).exists()
|
||||
with pytest.raises(ValueError, match="Raw"):
|
||||
maps.save(world, raw)
|
||||
assert maps.versions(world) == pointer
|
||||
|
||||
|
||||
def test_unknown_branch_and_corrupt_latest_do_not_fallback(tmp_path):
|
||||
world, _, maps, edits, sha = make_setup(tmp_path)
|
||||
branch = str(uuid.uuid4())
|
||||
with pytest.raises(FileNotFoundError):
|
||||
edits.get(world, "manual", branch)
|
||||
assert not edits._path(world, branch).exists()
|
||||
saved = edits.save(world, {**change(sha), "branch_id": branch})
|
||||
export = edits.export(world, saved["revision"])
|
||||
(maps.directory(world) / "latest.json").write_text("broken")
|
||||
assert edits.get(world, "manual", branch)["edited"] == saved["edited"]
|
||||
assert edits.export(world, saved["revision"]) == export
|
||||
assert edits.versions(world)["algorithmic_sha256"] is None
|
||||
(maps.directory(world) / f"{sha}.json").write_text("broken")
|
||||
with pytest.raises(ValueError):
|
||||
edits.get(world, "manual", branch)
|
||||
|
||||
|
||||
def test_pair_failure_preserves_pointer_and_ordinary_save_clears_raw(tmp_path, monkeypatch):
|
||||
world, model, maps, _, _ = make_setup(tmp_path)
|
||||
raw, auto = pair(model)
|
||||
previous = maps.versions(world)
|
||||
original = maps.store_immutable
|
||||
|
||||
def fail_second(world, document):
|
||||
if document.get("semantic_stage") == "algorithmic":
|
||||
raise OSError("interrupted")
|
||||
return original(world, document)
|
||||
|
||||
monkeypatch.setattr(maps, "store_immutable", fail_second)
|
||||
with pytest.raises(OSError):
|
||||
maps.publish_pair(world, raw, auto)
|
||||
assert maps.versions(world) == previous
|
||||
monkeypatch.setattr(maps, "store_immutable", original)
|
||||
maps.publish_pair(world, raw, auto)
|
||||
maps.save(world, model)
|
||||
assert "raw_sha256" not in maps.versions(world)
|
||||
|
||||
|
||||
def test_branch_concurrency_and_path_validation(tmp_path):
|
||||
world, _, _, edits, sha = make_setup(tmp_path)
|
||||
branch = str(uuid.uuid4())
|
||||
|
||||
def save(i):
|
||||
try:
|
||||
return edits.save(
|
||||
world, {**change(sha, request=f"parallel-branch-{i:04}"), "branch_id": branch}
|
||||
)
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
results = list(pool.map(save, range(2)))
|
||||
assert sum(result is not None for result in results) == 1
|
||||
for invalid in ["../../other", "", "legacy", 4]:
|
||||
with pytest.raises(ValueError):
|
||||
edits.get(world, "manual", invalid)
|
||||
|
||||
|
||||
def test_dense_raw_has_bounded_display_budget_and_does_not_expand_editable_maps(tmp_path):
|
||||
from k1link.simulation.ai_polygon.urban_maps import validate_map
|
||||
|
||||
world, model, _, _, _ = make_setup(tmp_path)
|
||||
raw, auto = pair(model)
|
||||
raw["coverage"]["cell_m"] = 60 / 4096
|
||||
raw["features"] = [{**model["features"][0], "id": f"raw-{i}"} for i in range(20001)]
|
||||
assert validate_map(raw, world) is raw
|
||||
auto["features"] = raw["features"]
|
||||
with pytest.raises(ValueError, match="feature count"):
|
||||
validate_map(auto, world)
|
||||
raw["features"] = raw["features"] * 3
|
||||
with pytest.raises(ValueError, match="feature count"):
|
||||
validate_map(raw, world)
|
||||
raw["features"] = [{**model["features"][0], "geometry": {
|
||||
"type": "LineString", "coordinates": [[0, 0, 1]] * 300001}}]
|
||||
assert validate_map(raw, world) is raw
|
||||
auto["features"] = raw["features"]
|
||||
with pytest.raises(ValueError, match="vertex limit"):
|
||||
validate_map(auto, world)
|
||||
raw["features"][0]["geometry"]["coordinates"] = [[0, 0, 1]] * 400001
|
||||
with pytest.raises(ValueError, match="vertex limit"):
|
||||
validate_map(raw, world)
|
||||
Reference in New Issue
Block a user