Files
DCCONSTRUCTIONS 69dc566665 feat(research): preserve urban geometry pipelines and qualification suites
Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
2026-10-29 09:10:00 +03:00

131 lines
7.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Fixed structural observers plus a complete initial paint coverage plan.
The bootstrap structural camera set defines the road/facade evidence. Coverage
optimization may add distinct paint observers; it cannot replace these cameras
or change their bounds, identity or ordering. All cameras are planned before
rendering, without an existing map, missed-object list or recovery pass.
"""
from pathlib import Path
import copy,json
import numpy as np
from observation_coverage import POLICY
def targets(survey,index):
points=[]
for tile in index['tiles']:
path=Path(survey)/tile['id']/'surface-atlas.npz'
if not path.is_file():continue
with np.load(path)as z:
depth=z['z'];cell=float(z['cell_m']);low=z['bounds'][0]
stride=max(1,round(POLICY['sample_m']/cell))
rr,cc=np.where(np.isfinite(depth[::stride,::stride]));rr*=stride;cc*=stride
points.append(np.c_[low[0]+(cc+.5)*cell,low[1]+(depth.shape[0]-rr-.5)*cell])
if not points:raise ValueError('Missing bootstrap observations')
return np.unique(np.concatenate(points),axis=0)
def counts_at(points,centers):
counts=np.zeros(len(points),np.int32)
for center in centers:counts+=(abs(points-center).max(1)<=POLICY['usable_half_width_m'])
return counts
def unique_centers(centers):
chosen=[]
for c in np.unique(np.asarray(centers,float).reshape(-1,2),axis=0):
if not chosen or np.all(np.max(abs(np.asarray(chosen)-c),axis=1)>=1e-6):chosen.append(c)
return np.asarray(chosen,float).reshape(-1,2)
class CoverageBudgetExceeded(ValueError):pass
def greedy(points,initial,candidates,limit):
counts=counts_at(points,initial);selected=list(np.asarray(initial,float).reshape(-1,2))
pool=np.asarray([c for c in candidates if not len(initial) or not np.any(np.max(abs(np.asarray(initial)-c),axis=1)<1e-6)],float).reshape(-1,2)
# Exact same <= footprint predicate as the original planner. Each Boolean
# row is packed once instead of rebuilding a candidate×point×XY tensor on
# every iteration. Storage is O(cameras*targets/8), not float64 XYZ cubes.
masks=[int.from_bytes(np.packbits(abs(points-c).max(1)<=POLICY['usable_half_width_m'],bitorder='little').tobytes(),'little')for c in pool]
available=np.ones(len(pool),bool)
while np.any(counts<POLICY['required_views']):
if len(selected)>=limit:raise CoverageBudgetExceeded('Initial observation budget exceeded')
needed=int.from_bytes(np.packbits(counts<POLICY['required_views'],bitorder='little').tobytes(),'little')
gains=[(mask&needed).bit_count()if available[i]else -1 for i,mask in enumerate(masks)]
if not gains or max(gains)<=0:raise CoverageBudgetExceeded('Cannot provide distinct footprints')
i=int(np.argmax(gains));c=pool[i];selected.append(c);available[i]=False
counts+=(abs(points-c).max(1)<=POLICY['usable_half_width_m'])
return np.asarray(selected,float),counts
def minimum_cover(points,pool,incumbent,seconds=15.,fixed=()):
"""Bounded binary covering problem; equivalent rows retain every sample."""
import time
from scipy.optimize import milp,Bounds,LinearConstraint
from scipy.sparse import csc_matrix,vstack
start=time.monotonic()
cover=np.column_stack([abs(points-c).max(1)<=POLICY['usable_half_width_m'] for c in pool])
packed=np.packbits(cover,axis=1,bitorder='little')
_,indices=np.unique(packed,axis=0,return_index=True)
matrix=vstack([csc_matrix(cover[indices].astype(float)),csc_matrix(np.ones((1,len(pool))))],format='csc')
fixed=unique_centers(fixed)
lower=np.zeros(len(pool))
for center in fixed:
ids=np.flatnonzero(np.max(abs(pool-center),axis=1)<1e-6)
if len(ids)!=1:raise ValueError('Structural camera missing or duplicated in coverage pool')
lower[ids[0]]=1.
result=milp(np.ones(len(pool)),integrality=np.ones(len(pool)),bounds=Bounds(lower,1.),
constraints=LinearConstraint(matrix,np.r_[np.full(len(indices),POLICY['required_views']),0.],np.r_[np.full(len(indices),np.inf),len(incumbent)]),
options=dict(time_limit=seconds,mip_rel_gap=0.))
selected=incumbent;state='feasible-greedy-fallback'
if result.x is not None and np.isfinite(result.x).all():
x=np.rint(result.x)
proposed=pool[x>.5]
if np.max(abs(result.x-x))<1e-5 and len(proposed)<=len(incumbent) and np.all(x>=lower) and np.all(counts_at(points,proposed)>=POLICY['required_views']):
selected=proposed;state='optimal'if result.status==0 else 'feasible-at-limit'
bound=getattr(result,'mip_dual_bound',None)
return selected,dict(status=state,solver_status=int(result.status),seconds=time.monotonic()-start,
camera_candidates=len(pool),original_sample_constraints=len(points),equivalent_sample_constraints=len(indices),
lower_bound=float(bound)if bound is not None and np.isfinite(bound)else None,
greedy_views=len(incumbent),selected_views=len(selected))
def choose(points,original,optimize=True):
points=np.unique(np.asarray(points,float).reshape(-1,2),axis=0)
original=unique_centers(original)
if not len(points)or not np.isfinite(points).all()or not np.isfinite(original).all():raise ValueError('Invalid observed coverage geometry')
grid=np.unique(np.round(points/POLICY['camera_grid_m'])*POLICY['camera_grid_m'],axis=0)
limit=len(original)+POLICY['max_additional_views']
legacy,legacy_counts=greedy(points,original,grid,limit)
pool=unique_centers(np.r_[grid,original])
selected,counts,method=legacy,legacy_counts,'fixed-structure-complete-cover'
solver=None
if optimize:
selected,solver=minimum_cover(points,pool,selected,fixed=original)
counts=counts_at(points,selected)
if len(selected)<len(legacy):method='fixed-structure-joint-cover'
assert np.all(counts>=POLICY['required_views'])
assert len(unique_centers(selected))==len(selected)
assert len(selected)<=len(legacy)
assert all(np.any(np.max(abs(selected-c),axis=1)<1e-6)for c in original)
return selected,dict(target_samples=len(points),initial_two_view_samples=int((counts_at(points,original)>=POLICY['required_views']).sum()),planned_two_view_samples=int((counts>=POLICY['required_views']).sum()),minimum_views=int(counts.min()),bootstrap_views=len(original),legacy_complete_views=len(legacy),planned_views=len(selected),plan_method=method,solver=solver,unknown_ground_inferred=False,object_input=False,additional_views=len(selected)-len(original),structural_views=len(original),structural_cameras_preserved=True)
def plan(survey,index,selection=None):
points=targets(survey,index)
originals=np.array([np.mean(t['bounds_xy'],axis=0)for t in index['tiles']])
centers,report=choose(points,originals) if selection is None else selection
if not all(np.any(np.max(abs(centers-c),axis=1)<1e-6)for c in originals):raise ValueError('Coverage plan replaced a structural camera')
tiles=[];jobs={}
additions=[c for c in centers if not np.any(np.max(abs(originals-c),axis=1)<1e-6)]
for i,center in enumerate(additions):
nearest=index['tiles'][int(np.argmin(np.linalg.norm(originals-center,axis=1)))]
job=copy.deepcopy(json.loads((Path(survey)/nearest['id']/'job.json').read_text()))
name=f'primary-support-{i:03d}';bounds=[(center-30).tolist(),(center+30).tolist()]
top=next(v for v in job['views']if v['id']=='top');delta=center-np.asarray(top['eye'][:2])
top['eye'][:2]=center.tolist();top['target'][:2]=(np.asarray(top['target'][:2])+delta).tolist()
job['bounds_xy']=bounds;jobs[name]=job
tiles.append(dict(id=name,status='planned',bounds_xy=bounds,role='initial-two-view-support',center=center.tolist()))
return tiles,jobs,dict(schema='missioncore.initial-observation-coverage/v2',structural_ids=[t['id']for t in index['tiles']],policy=POLICY,**report)