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.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:00 +03:00
parent 5d56237124
commit 69dc566665
611 changed files with 52016 additions and 28 deletions
@@ -0,0 +1,88 @@
Uniform Gaussian orthophoto observation adapter
===============================================
Offline observation adapter for the existing urban-plan qualification. It is
not wired into the installed infrastructure provider. Scene-specific paths,
scan poses, source bundles, cached surveys, masks and results stay in private
qualification storage. There are no scene coordinates, review regions or
priority windows in these components.
The original LCC poses.json supplies scanner positions, not surface geometry.
ortho_terrain.py validates their native Z-up frame against cached Gaussian depth,
estimates scanner height robustly, rejects inconsistent roof observations and
builds one smoothed local height field. The existing automatic survey grid is
reused; this increment does not implement a new trajectory-derived tile planner.
Stacked levels such as bridges above roads are not qualified.
ortho_render.py renders original Gaussian attributes with gsplat into world-
aligned 60 m / 4096 px orthographic windows. It produces context and low-surface
layers relative to the common terrain field. This is a 1.465 cm pixel size,
not demonstrated physical accuracy. Source Gaussian attributes are unchanged.
ortho_segment.py runs the existing pinned SAM3 at common 60/30/15 m scales.
ortho_windows.py merges positive instance masks with maximum union, so a missed
detection in an overlapping window cannot erase a positive instance. Empty
visibility windows may be skipped. No map-specific prompts or selectors exist.
ortho_classes.py resolves road/sidewalk competition after all scene windows
have been merged. The extractor supplies maximum per-class score rasters with
its alpha validity gate, calls resolve_surfaces once, then cleans the exclusive
class masks. It must not give sidewalk unconditional priority over road.
SAM3 instance scores remain uncalibrated. Competing semantic classes can still
be wrong; sharper input alone does not establish correct road topology.
Worker contract
---------------
Run only on the reserved external worker, in the already qualified mapping and
SAM3 images. The adapter requires NumPy, SciPy, OpenCV, Pillow, gsplat/torch and
plyfile; SAM3 uses the existing ai-polygon release/model assets. No dependency
installation is performed by these scripts.
Mounts: /base_survey (read-only prior automatic Gaussian survey), /input
(read-only original Gaussian bundle), /run (per-scene config and original poses),
/survey and /evidence (outputs), /release and /assets (read-only pinned SAM3).
ORTHO_SCENE selects the scene record in /run/config.json. That config contains
method (see method.json) and scenes[ORTHO_SCENE].trajectory (filename in /run).
The base survey request.json supplies source.ply, sha256 and source_to_world;
it also supplies tile-index.json, tile job.json and surface-atlas.npz. The
canonical urban-mapping directory must be on PYTHONPATH for camera/digest.
coordinate_cache.py preserves the exact float64 source-to-world transform.
Execute ortho_render.py, then ortho_segment.py. The outputs retain the legacy
1200 px projection contract alongside native 4096 px images. Existing contour
extraction/assembly still uses its 10 cm working raster and previous geometry
parameters, with review priority disabled. This folder changes observation,
not the fitting engine or the live map. Geometry integration remains private
qualification code; these two scripts do not themselves emit a final road map.
python3 -B -m unittest test_ortho_pass validates local relief, roof rejection,
pose-frame rejection, scanner dwell invariance, unknown-ground rejection and
preservation of positive evidence across overlapping empty predictions,
exclusive semantic class competition and rejection of invalid scores. Run in
the mapping image, with this directory on PYTHONPATH. The full qualification
also exercises the existing continuity/junction/assembly contracts.
Evidence and status
-------------------
Private session: .runtime/simulation-qualifications/ortho-pass-20261011.
Per-stage receipts retain exact images, source hashes, parameters, timestamps,
exit status and resource release. Raw model inputs and outputs are retained on
the worker and hashed. The same method completed both scenes (88 Pokrovka and 68 Maroseyka
windows), with 62 tests per scene. Neither result passed whole-scene visual
acceptance: false shapes and incomplete side roads remain. Pokrovka also has
one inter-chain crossing. Consult the final private REVIEW.txt and each
visual-review.json; passing code tests does not establish mapping quality.
Do not promote this adapter as an accepted automatic mapping provider before
whole-scene semantic/visual acceptance. Point clouds are never consumed.
The provider currently omits poses.json from its working source bundle. The
qualification recovered it read-only from the original archive. Production
integration must preserve poses, their hash and the explicit coordinate frame;
the external Gaussian Pipeline service was not changed.
Primary component references:
https://docs.gsplat.studio/main/apis/rasterization.html
https://samgeo.gishub.org/examples/sam3_tiled_segmentation/
The SamGeo package is not installed; its standard overlapping-window recipe is
implemented by the adapter around the already pinned SAM3 processor.
@@ -0,0 +1,22 @@
"""Memoize the exact chunkwise rigid transform; retain full Gaussian attributes.
This changes repeated I/O only. It does not filter, quantize or change tile masks.
"""
import numpy as np
import json
from pathlib import Path
_cache={}
def transformed(data,transform,identity,proof_path='/survey/coordinate-cache-proof.json'):
key=(identity,tuple(np.asarray(transform).ravel()))
if key not in _cache:
result=np.empty((len(data),3),np.float64)
for start in range(0,len(data),250000):
d=data[start:start+250000];xyz=np.column_stack([d[n]for n in ['x','y','z']])
result[start:start+len(d)]=xyz@transform[:3,:3].T+transform[:3,3]
checked=0
for start in sorted({0,(len(data)//250000//2)*250000,((len(data)-1)//250000)*250000}):
d=data[start:start+250000];xyz=np.column_stack([d[n]for n in ['x','y','z']]);direct=xyz@transform[:3,:3].T+transform[:3,3]
assert np.array_equal(result[start:start+len(d)],direct)
checked+=len(d)
Path(proof_path).write_text(json.dumps(dict(source=str(identity),gaussians=len(data),checked_vertices=checked,comparison='bitwise exact float64 transform',geometry_parameters_changed=False)))
_cache.clear();_cache[key]=result
return _cache[key]
@@ -0,0 +1,22 @@
{
"render_pixels": 4096,
"render_width_m": 60,
"context_height_m": 4.0,
"ground_height_m": 0.8,
"lower_height_m": -0.6,
"terrain_cell_m": 1.0,
"terrain_smooth_m": 2.0,
"detail_width_m": 15.0,
"detail_step_m": 10.0,
"context_width_m": 30.0,
"context_step_m": 20.0,
"prompts": [
"road",
"sidewalk",
"vehicle"
],
"model_threshold": 0.3,
"manual_rois": [],
"review_priority": [],
"class_overlap_policy": "scene-wide exclusive argmax of positive instance scores before boundary extraction"
}
@@ -0,0 +1,12 @@
"""Resolve overlapping categorical proposals once on the scene raster.
Scores rank competing instances; they are not calibrated pixel probabilities.
The same rule is used regardless of scene or feature location.
"""
import numpy as np
def resolve_surfaces(road, sidewalk, road_threshold=.35, sidewalk_threshold=.4):
road=np.asarray(road);sidewalk=np.asarray(sidewalk)
if road.shape!=sidewalk.shape or not np.isfinite(road).all() or not np.isfinite(sidewalk).all():
raise ValueError('Surface evidence must have matching finite rasters')
return ((road>road_threshold)&(road>=sidewalk),
(sidewalk>sidewalk_threshold)&(sidewalk>road))
@@ -0,0 +1,49 @@
"""One location-independent clipped, high-resolution orthographic pass."""
import json,time,gc,math
from pathlib import Path
import numpy as np,torch,cv2
from plyfile import PlyData
from PIL import Image
from gsplat import rasterization
from mapping import camera,digest
from coordinate_cache import transformed
from ortho_terrain import from_survey,sample
S=Path('/base_survey');O=Path('/survey');E=Path('/evidence');P=Path('/input');R=Path('/run');cfg=json.loads((R/'config.json').read_text());method=cfg['method'];scene=__import__('os').environ['ORTHO_SCENE'];start=time.monotonic()
for d in [O,E,R/'diagnostics']:d.mkdir(exist_ok=True)
trajectory=cfg['scenes'][scene]['trajectory'];trajectory=R/trajectory if trajectory else None
field,route=from_survey(S,trajectory);np.savez_compressed(R/'terrain-reference.npz',**field);(R/'terrain-report.json').write_text(json.dumps(route,indent=2));print('TERRAIN',json.dumps(route),flush=True)
request=json.loads((S/'request.json').read_text());(O/'request.json').write_text(json.dumps(request));source=P/request['source']['ply'];assert digest(source)==request['source']['sha256'];T=np.array(request['source']['source_to_world']);data=PlyData.read(source,mmap='r')['vertex'].data;world=transformed(data,T,str(source))
# Precompute the same terrain-relative cut for every splat; no tile-owned planes.
relative=np.empty(len(data),np.float32)
for begin in range(0,len(data),250000):
xyz=world[begin:begin+250000];relative[begin:begin+len(xyz)]=xyz[:,2]-sample(field,xyz[:,:2])
index=json.loads((S/'tile-index.json').read_text());records=[]
for tile in index['tiles']:
old=S/tile['id']/'job.json'
if not old.exists():continue
assert __import__('shutil').disk_usage(R).free>8*2**30, 'Qualification free-disk floor reached'
name=tile['id'];folder=O/name;folder.mkdir(exist_ok=True);job=json.loads(old.read_text());top=next(v for v in job['views']if v['id']=='top');bounds=np.array(job['bounds_xy']);record=dict(tile=name,bounds_xy=bounds.tolist());native_n=method['render_pixels'];top['size']=[native_n,native_n]
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']))
if not len(indices):tile['status']='no-ground-after-cut';continue
d=data[indices].copy();dz=relative[indices];del indices
for mode,upper in [('context',method['context_height_m']),('ground',method['ground_height_m'])]:
selected=d[dz<=upper]
if not len(selected):continue
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();dc=tensor([f'f_dc_{i}'for i in range(3)])[:,None,:];rest=sorted([n for n in d.dtype.names if n.startswith('f_rest_')],key=lambda n:int(n.split('_')[-1]));sh=torch.cat([dc,tensor(rest).reshape(len(selected),3,-1).transpose(1,2)],dim=1)if rest else dc;degree=int(math.sqrt(sh.shape[1]))-1
view,k=camera(top);t=time.monotonic()
with torch.inference_mode():a3,alpha,_=rasterization(means,quats,scales,opacity,sh,torch.tensor(view@T,device='cuda',dtype=torch.float32)[None],torch.tensor(k,device='cuda')[None],native_n,native_n,sh_degree=degree,camera_model='ortho',render_mode='RGB+ED',packed=True)
a=alpha[0,:,:,0].cpu().numpy();v=a3[0].cpu().numpy();v[:,:,:3]+=1-a[:,:,None];im=np.uint8(np.clip(v[:,:,:3],0,1)*255)
high=E/(name+'.'+mode+'.png');Image.fromarray(im).save(high)
# Compatibility views keep exact old world-to-pixel contract; native RGB is retained.
small=cv2.resize(im,(1200,1200),interpolation=cv2.INTER_AREA);ak=k.copy();ak[:2,:]*=1200/native_n
depth=cv2.resize(v[:,:,3],(1200,1200),interpolation=cv2.INTER_AREA);aa=cv2.resize(a,(1200,1200),interpolation=cv2.INTER_AREA)
if mode=='context':
Image.fromarray(small).save(folder/'top.png');np.savez_compressed(folder/'top.geometry.npz',depth=depth,alpha=aa,view=view,intrinsics=ak)
else:
Image.fromarray(small).save(E/(name+'.ground-dc.png'));np.savez_compressed(E/(name+'.ground-dc.geometry.npz'),depth=depth,alpha=aa,view=view,intrinsics=ak)
record[mode]=dict(selected_splats=len(selected),opaque_fraction=float((a>.8).mean()),sha256=digest(high),seconds=time.monotonic()-t)
del means,quats,scales,opacity,dc,sh,a3,alpha,v,a,im,selected;gc.collect();torch.cuda.empty_cache()
del d,dz;gc.collect()
top['size']=[1200,1200];(folder/'job.json').write_text(json.dumps(job));tile['status']='surveyed';records.append(record);(R/'render-report.json').write_text(json.dumps(records,indent=2));print('RENDER',json.dumps(record),flush=True)
(O/'tile-index.json').write_text(json.dumps(index));(R/'render-summary.json').write_text(json.dumps(dict(scene=scene,source_splats=len(data),rendered_tiles=len(records),native_pixel_m=60/native_n,seconds=time.monotonic()-start,trajectory=route,manual_rois=[]),indent=2))
@@ -0,0 +1,58 @@
"""Uniform metric sliding-window segmentation; shared schedule for every location.
The standard overlapping-window instance-union recipe is used at 60/30/15 m; no target ROIs.
Existing pinned SAM3; positive-instance union in calibrated world-aligned raster coordinates.
"""
import sys,json,time,os,gc
from pathlib import Path
sys.path.insert(0,'/release/simulation/ai-polygon/sam3-research')
from qualify import load_exact,sha
import torch,numpy as np,cv2
from PIL import Image
import sam3.model_builder as builder
from sam3.model.sam3_image_processor import Sam3Processor
S=Path('/survey');E=Path('/evidence');R=Path('/run');cfg=json.loads((R/'config.json').read_text());m=cfg['method'];(E/'road-prompt').mkdir(exist_ok=True)
d=json.loads(Path('/release/simulation/ai-polygon/sam3-research/large-model.json').read_text());assets=Path('/assets')
for name,expected in d['files'].items():assert sha(assets/name)==expected
builder._load_checkpoint=load_exact;torch.set_num_threads(3);cv2.setNumThreads(3)
model=builder.build_sam3_image_model(bpe_path='/source/assets/bpe_simple_vocab_16e6.txt.gz',checkpoint_path=str(assets/next(iter(d['files']))),load_from_HF=False,enable_segmentation=True,enable_inst_interactivity=False,compile=False,text_encoder_type=d['text_encoder'],text_encoder_context_length=16,device='cuda');processor=Sam3Processor(model,device='cuda',confidence_threshold=m['model_threshold']);prompts=m['prompts'];records=[];started=time.monotonic()
from ortho_windows import windows,merge_instances
def predict(im):
result={}
with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):
state=processor.set_image(im)
for prompt in prompts:
state=processor.set_text_prompt(prompt,state);found=state['masks'].reshape(-1,im.height,im.width).cpu().numpy();scores=state['scores'].float().cpu().numpy().reshape(-1);plane=np.zeros((im.height,im.width),np.float32)
for mask,score in zip(found,scores):np.maximum(plane,np.where(mask,score,0),out=plane)
result[prompt]=plane
return result
def pass_scale(image,alpha,width,step):
sums=np.zeros((3,1200,1200),np.float32);n=0;skip=0
for x,y,w,h in windows(60,width,step):
x0,y0,x1,y1=np.rint(np.array([x,y,x+w,y+h])*20).astype(int);sl=np.s_[y0:y1,x0:x1]
if (alpha[sl]>.7).mean()<.04:skip+=1;continue
box=tuple(np.rint(np.array([x,y,x+w,y+h])*image.width/60).astype(int));crop=image.crop(box);crop.thumbnail((1024,1024),Image.Resampling.LANCZOS);masks=predict(crop)
ww=x1-x0;hh=y1-y0
for j,prompt in enumerate(prompts):merge_instances(sums[j],cv2.resize(masks[prompt],(ww,hh),interpolation=cv2.INTER_AREA),x0,y0)
n+=1
return sums,n,skip
index=json.loads((S/'tile-index.json').read_text())
for tile in index['tiles']:
if tile['status']!='surveyed':continue
name=tile['id'];t=time.monotonic();normal=Image.open(E/(name+'.context.png')).convert('RGB');ground=Image.open(E/(name+'.ground.png')).convert('RGB');ng=np.load(S/name/'top.geometry.npz');gg=np.load(E/(name+'.ground-dc.geometry.npz'));alpha=ng['alpha'];ag=gg['alpha']
# Fixed coarse context and fixed detail passes run everywhere with image support.
context,n0,s0=pass_scale(normal,alpha,60,60);medium,n1,s1=pass_scale(normal,alpha,m['context_width_m'],m['context_step_m']);detail,n2,s2=pass_scale(ground,ag,m['detail_width_m'],m['detail_step_m'])
normal_masks=np.maximum(context,medium);combined=np.maximum(normal_masks,detail)
# Vehicles are observable in the 4 m context; the low slice intentionally omits them.
combined[2]=normal_masks[2]
valid=np.maximum(alpha,ag)>.5;combined[:,~valid]=0
# Preserve model competition explicitly; scores remain uncalibrated model scores.
road,side,vehicle=combined
normal_out={'roadway':road,'sidewalk':side,'vehicle':vehicle,'road marking':np.zeros_like(road),'crosswalk':np.zeros_like(road)}
ground_out={**normal_out,'roadway':detail[0],'sidewalk':detail[1],'vehicle':np.zeros_like(road)}
np.savez_compressed(E/(name+'.normal.npz'),**normal_out);np.savez_compressed(E/(name+'.ground.npz'),**ground_out);np.savez_compressed(E/'road-prompt'/(name+'.normal.npz'),road=road);np.savez_compressed(E/'road-prompt'/(name+'.ground.npz'),road=detail[0])
preview=np.asarray(normal.resize((1200,1200)),dtype=np.float32).copy();road_area=(road>.35)&(side<=road);side_area=(side>.4)&(side>road);preview[road_area]=.55*preview[road_area]+.45*np.array([65,130,225]);preview[side_area]=.55*preview[side_area]+.45*np.array([25,220,145]);Image.fromarray(np.uint8(preview)).save(E/(name+'.semantic.jpg'),quality=94)
records.append(dict(tile=name,windows=[n0,n1,n2],skipped=[s0,s1,s2],road_pixels=int(road_area.sum()),side_pixels=int(side_area.sum()),seconds=time.monotonic()-t,source_hashes=[sha(E/(name+'.context.png')),sha(E/(name+'.ground.png'))]));(R/'segmentation-report.json').write_text(json.dumps(records,indent=2));print('SEGMENT',json.dumps(records[-1]),flush=True);normal.close();ground.close();gc.collect()
(R/'segmentation-summary.json').write_text(json.dumps(dict(scene=os.environ['ORTHO_SCENE'],method=m,model=d,tiles=len(records),windows=sum(sum(r['windows'])for r in records),seconds=time.monotonic()-started,manual_rois=[],score_interpretation='model scores, not calibrated probabilities'),indent=2))
@@ -0,0 +1,64 @@
"""Shared raster terrain reference from Gaussian depth, with optional scan poses.
SciPy median binning / distance transform / normalized Gaussian smoothing.
No point-cloud geometry, site coordinates, roads or manual selections.
"""
import json
from pathlib import Path
import numpy as np
from scipy.stats import binned_statistic_2d
from scipy.ndimage import distance_transform_edt,gaussian_filter,map_coordinates
from scipy.spatial import cKDTree
def grid_reference(xyz,cell=1.,smooth_m=2.,poses=None):
xyz=np.asarray(xyz,float);xyz=xyz[np.isfinite(xyz).all(1)]
if len(xyz)<100:raise ValueError('Insufficient Gaussian ground-depth reference')
lo=np.floor(xyz[:,:2].min(0)/cell)*cell-25;hi=np.ceil(xyz[:,:2].max(0)/cell)*cell+25
if poses is not None:
poses=np.asarray(poses,float);assert poses.ndim==2 and poses.shape[1]==3 and np.isfinite(poses).all()
lo=np.minimum(lo,np.floor(poses[:,:2].min(0)/cell)*cell-25);hi=np.maximum(hi,np.ceil(poses[:,:2].max(0)/cell)*cell+25)
w,h=np.rint((hi-lo)/cell).astype(int)
if w*h>4000000:raise ValueError('Terrain reference exceeds bounded envelope')
z,_,_,_=binned_statistic_2d(xyz[:,1],xyz[:,0],xyz[:,2],statistic='median',bins=(h,w),range=((lo[1],hi[1]),(lo[0],hi[0])))
known=np.isfinite(z);dist,near=distance_transform_edt(~known,sampling=cell,return_indices=True);filled=z[tuple(near)]
route_record={'available':False,'used':False}
if poses is not None:
xy=np.c_[lo[0]+(np.where(known)[1]+.5)*cell,lo[1]+(np.where(known)[0]+.5)*cell]
dd,ii=cKDTree(xy).query(poses[:,:2]);dz=poses[:,2]-z[known][ii];good=dd<3
if good.sum()<100:raise ValueError('Trajectory XY frame is not supported by Gaussian ground')
offset=float(np.median(dz[good]));mad=float(np.median(abs(dz[good]-offset)))
route_record=dict(available=True,used=False,samples=len(poses),near_ground_fraction=float(good.mean()),sensor_ground_offset_m=offset,residual_mad_m=mad,coordinate_transform='identity, native LCC Z-up; validated against Gaussian ground')
if good.mean()<.25 or len(np.unique(np.floor(poses[good,:2]),axis=0))<100 or not -.5<offset<3 or mad>.8:raise ValueError('Trajectory frame/height validation failed: '+str(route_record))
rz,_,_,_=binned_statistic_2d(poses[:,1],poses[:,0],poses[:,2]-offset,statistic='median',bins=(h,w),range=((lo[1],hi[1]),(lo[0],hi[0])))
rknown=np.isfinite(rz);rd,rn=distance_transform_edt(~rknown,sampling=cell,return_indices=True)
route_ground=rz[tuple(rn)]
# Reject disconnected roof/sky depth observations using the scanner's local height.
implausible=known&((abs(z-route_ground)>1.5)|(rd>25))
known[implausible]=False
if known.sum()<100:raise ValueError('No ground remains after trajectory height validation')
dist,near=distance_transform_edt(~known,sampling=cell,return_indices=True);filled=z[tuple(near)]
add=(dist>3)&(rd<4);filled[add]=route_ground[add];known|=add
route_record['rejected_inconsistent_ground_bins']=int(implausible.sum())
route_record['used']=True
weights=known.astype(float)
numerator=gaussian_filter(np.where(known,filled,0.),smooth_m/cell)
denominator=gaussian_filter(weights,smooth_m/cell)
weighted=np.where(denominator>1e-8,numerator/np.maximum(denominator,1e-8),filled)
# One smooth field in world coordinates, shared by all overlapping render tiles.
height=gaussian_filter(weighted,smooth_m/cell).astype('float32')
return dict(height=height,known=known,ground_distance=dist.astype('float32'),low=lo,cell_m=cell),route_record
def sample(field,xy):
xy=np.asarray(xy);uv=(xy-np.asarray(field['low']))/float(field['cell_m'])-.5
return map_coordinates(field['height'],[uv[:,1],uv[:,0]],order=1,mode='nearest')
def from_survey(survey,poses_path=None):
samples=[]
for t in json.loads((survey/'tile-index.json').read_text())['tiles']:
p=survey/t['id']/'surface-atlas.npz'
if not p.exists():continue
a=np.load(p);z=a['z'];rr,cc=np.where(np.isfinite(z));take=np.arange(0,len(rr),3);rr,cc=rr[take],cc[take];cell=float(a['cell_m']);lo=a['bounds'][0]
samples.append(np.c_[lo[0]+(cc+.5)*cell,lo[1]+(z.shape[0]-rr-.5)*cell,z[rr,cc]])
poses=None
if poses_path:
p=json.loads(Path(poses_path).read_text());poses=np.array([v['T']for v in p['poses']],float)
return grid_reference(np.concatenate(samples),poses=poses)
@@ -0,0 +1,15 @@
"""Metric sliding windows and deterministic overlap weights; no location input."""
import numpy as np
def starts(extent,width,step):
if not 0<step<=width<=extent:raise ValueError('Invalid overlapping window dimensions')
return sorted(set([*np.arange(0,extent-width+1e-6,step).tolist(),extent-width]))
def windows(extent,width,step):
for y in starts(extent,width,step):
for x in starts(extent,width,step):yield x,y,width,width
def merge_instances(canvas,patch,left,top):
h,w=patch.shape;target=canvas[top:top+h,left:left+w]
if target.shape!=patch.shape:raise ValueError('Mask patch outside calibrated raster')
np.maximum(target,patch,out=target)
@@ -0,0 +1,42 @@
import unittest
import numpy as np
from ortho_terrain import grid_reference,sample
from ortho_windows import windows,merge_instances
from ortho_classes import resolve_surfaces
class OrthoPassTests(unittest.TestCase):
def example(self):
x,y=np.meshgrid(np.arange(0.,240.,1.),np.arange(-6.,7.,1.));z=.03*x+1.1*np.sin(x/22)+.015*y
xyz=np.c_[x.ravel(),y.ravel(),z.ravel()];t=np.arange(0.,240.,.3);p=np.c_[t,np.zeros(len(t)),.03*t+1.1*np.sin(t/22)+1.3]
return xyz,p
def test_relief_is_local_not_endpoint_plane(self):
xyz,p=self.example();f,r=grid_reference(xyz,poses=p);expected=p[:,2]-1.3;got=sample(f,p[:,:2]);self.assertLess(np.quantile(abs(got-expected),.95),.15);self.assertTrue(r['used'])
def test_roof_outliers_do_not_raise_cut(self):
xyz,p=self.example();roof=xyz[(xyz[:,0]>100)&(xyz[:,0]<130)].copy();roof[:,1]+=12;roof[:,2]+=12
f,r=grid_reference(np.r_[xyz,roof],poses=p);self.assertGreater(r['rejected_inconsistent_ground_bins'],0);self.assertLess(abs(sample(f,[[115,13]])[0]-(.03*115+1.1*np.sin(115/22))),.5)
def test_wrong_pose_frame_rejected(self):
xyz,p=self.example();p[:,0]+=500
with self.assertRaises(ValueError):grid_reference(xyz,poses=p)
def test_scan_timing_does_not_shift_terrain(self):
xyz,p=self.example();f,_=grid_reference(xyz,poses=p);g,_=grid_reference(xyz,poses=np.r_[p,np.repeat(p[400:401],4000,axis=0)])
self.assertLess(np.max(abs(sample(f,p[:,:2])-sample(g,p[:,:2]))),.03)
def test_overlapping_absence_does_not_erase_detection(self):
canvas=np.zeros((1200,1200),np.float32);coverage=np.zeros_like(canvas)
evidence=np.zeros((300,300),np.float32);evidence[:,100:130]=.8
merge_instances(canvas,evidence,400,400)
for x,y,w,h in windows(60,15,10):
a,b,c,d=np.rint(np.array([x,y,x+w,y+h])*20).astype(int)
merge_instances(canvas,np.zeros((d-b,c-a),np.float32),a,b);coverage[b:d,a:c]+=1
self.assertTrue((coverage>0).all());self.assertTrue((canvas[400:700,500:530]>.79).all());self.assertEqual(np.count_nonzero(canvas),9000)
def test_weaker_sidewalk_instance_cannot_cut_stronger_road(self):
road=np.zeros((20,20));side=np.zeros_like(road)
road[:,8:12]=.9;side[:8,:]=.8;side[12:,:]=.8;side[7:13,7:13]=.45
r,s=resolve_surfaces(road,side)
self.assertTrue(r[:,8:12].all());self.assertFalse(s[:,8:12].any())
self.assertFalse((r&s).any());self.assertTrue(s[:7,:7].all())
def test_unknown_surface_stays_unknown_and_invalid_scores_rejected(self):
r,s=resolve_surfaces(np.array([0,.2,.8]),np.array([0,.3,.8]))
self.assertEqual(r.tolist(),[False,False,True]);self.assertFalse(s.any())
with self.assertRaises(ValueError):resolve_surfaces([float('nan')],[0])
def test_unknown_ground_rejected(self):
with self.assertRaises(ValueError):grid_reference(np.zeros((5,3)))
if __name__=='__main__':unittest.main()