Files
NODEDC_MISSION_CORE/simulation/urban-plan-research/topdown/depth_audit.py
T
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

80 lines
5.6 KiB
Python

"""Evaluation-only depth contract experiment, without historical geometry."""
from pathlib import Path
import gc,inspect,json,math,time
import cv2
import numpy as np
import torch
from gsplat import rasterization
from plyfile import PlyData
from mapping import camera,digest
from coordinate_cache import transformed
from ortho_terrain import sample
from orthographic_colour import colours
from orthographic_depth import coefficients,decode,VERSION
def synthetic():
device='cuda';dtype=torch.float32
view=torch.eye(4,device=device);n=512;k=torch.tensor([[128.,0,256.],[0,128.,256.],[0,0,1]],device=device)
def render(means,quats,scales,opacity):
coeff=coefficients(means,quats,scales,view,k)
v,a,_=rasterization(means,quats,scales,opacity,coeff,view[None],k[None],n,n,
camera_model='ortho',render_mode='RGB+ED',packed=True)
alpha=a[0,:,:,0];return decode(v[0,:,:,:3],alpha,k),v[0,:,:,3],alpha
rows=[]
for name,slope,step in [('flat',0.,0.),('slope',.35,0.),('step',0.,.35)]:
x=torch.tensor([-.6,0.,.6],device=device);z=5+slope*x+(x>0)*step
means=torch.stack([x,torch.zeros_like(x),z],-1)
angle=-math.atan(slope);q=torch.tensor([math.cos(angle/2),0.,math.sin(angle/2),0.],device=device).repeat(3,1)
scales=torch.tensor([.42,.4,.001],device=device).repeat(3,1);opacity=torch.full((3,),.99,device=device)
conditional,centroid,alpha=render(means,q,scales,opacity)
xx=(torch.arange(n,device=device)+.5-256)/128
expected=(5+slope*xx).repeat(n,1);known=(alpha>.85)&(torch.abs(xx)[None]<.7)
record=dict(name=name,known_pixels=int(known.sum()),conditional_max_plane_error_m=float((conditional-expected)[known].abs().max()),
centroid_max_plane_error_m=float((centroid-expected)[known].abs().max()),
conditional_depth_range_m=float(conditional[known].max()-conditional[known].min()))
if not step:assert record['conditional_max_plane_error_m']<.0001,record
if step:assert record['conditional_depth_range_m']>.20,record
rows.append(record)
return rows
def run(tile_names):
out=Path('/out');root=Path('/ortho');begin=time.monotonic()
report=dict(version=VERSION,evaluation_only=True,reference_input=False,synthetic=synthetic(),
rasterizer_signature=str(inspect.signature(rasterization)),records=[])
(out/'depth-audit.json').write_text(json.dumps(report,indent=2))
config=json.loads((root/'config.json').read_text());method=config['method'];n=method['render_pixels']
request=json.loads((root/'survey/request.json').read_text());source=Path('/input')/request['source']['ply']
assert digest(source)==request['source']['sha256']
data=PlyData.read(source,mmap='r')['vertex'].data;transform=np.asarray(request['source']['source_to_world'])
world=transformed(data,transform,str(source),str(out/'coordinate-cache-proof.json'))
with np.load(root/'terrain-reference.npz') as z:field=dict(z)
relative=np.empty(len(data),np.float32)
for start in range(0,len(data),250000):
xyz=world[start:start+250000];relative[start:start+len(xyz)]=xyz[:,2]-sample(field,xyz[:,:2])
for name in tile_names:
job=json.loads((root/'survey'/name/'job.json').read_text());top=next(v for v in job['views'] if v['id']=='top');top['size']=[n,n]
bounds=np.asarray(job['bounds_xy']);indices=np.flatnonzero(((world[:,:2]>=bounds[0]-10)&(world[:,:2]<=bounds[1]+10)).all(1)&
(relative>=method['lower_height_m'])&(relative<=method['context_height_m']))
d=data[indices].copy();dz=relative[indices]
for mode,upper in [('context',method['context_height_m']),('ground',method['ground_height_m'])]:
selected=d[dz<=upper]
def tensor(names):return torch.tensor(np.column_stack([selected[n] for n in names]),device='cuda',dtype=torch.float32)
means=tensor(['x','y','z']);quats=tensor([f'rot_{i}' for i in range(4)]);scales=tensor([f'scale_{i}' for i in range(3)]).exp();opacity=tensor(['opacity']).squeeze(-1).sigmoid()
view,k=camera(top);vmat=torch.tensor(view@transform,device='cuda',dtype=torch.float32);kt=torch.tensor(k,device='cuda',dtype=torch.float32)
coeff=coefficients(means,quats,scales,vmat,kt)
with torch.inference_mode():
v,a,_=rasterization(means,quats,scales,opacity,coeff,vmat[None],kt[None],n,n,camera_model='ortho',render_mode='RGB+ED',packed=True)
conditional=decode(v[0,:,:,:3],a[0,:,:,0],kt).cpu().numpy()
alpha=a[0,:,:,0].cpu().numpy();centroid=v[0,:,:,3].cpu().numpy()
with np.load(Path('/native_geometry')/(name+'.'+mode+'.npz')) as z:
old=dict(z);depth_error=float(np.abs(centroid-old['depth']).max());alpha_error=float(np.abs(alpha-old['alpha']).max())
assert depth_error<.001 and alpha_error<.0001,(depth_error,alpha_error)
path=out/(name+'.'+mode+'.npz');np.savez_compressed(path,depth=conditional,alpha=alpha,view=view,intrinsics=k,compatibility_resolution=1200)
report['records'].append(dict(tile=name,mode=mode,file=path.name,sha256=digest(path),
centroid_reproduction_error_m=depth_error,alpha_reproduction_error=alpha_error,
source_gaussians=len(means),depth_change_quantiles=np.quantile(np.abs(conditional-centroid)[alpha>=.85],[0,.5,.9,.99,1]).tolist()))
print('DEPTH_AUDIT',name,mode,report['records'][-1],flush=True)
del means,quats,scales,opacity,coeff,v,a,conditional,alpha,centroid,old;gc.collect();torch.cuda.empty_cache()
report.update(seconds=time.monotonic()-begin,complete=True)
(out/'depth-audit.json').write_text(json.dumps(report,indent=2))