Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
648 lines
42 KiB
Python
648 lines
42 KiB
Python
"""Scientific invariants for the isolated top-down reconstruction path."""
|
|
import json
|
|
from pathlib import Path
|
|
import tempfile
|
|
import unittest
|
|
import numpy as np
|
|
import shapely
|
|
from shapely.geometry import box
|
|
from direct_fixed import fit_target
|
|
from standard_arrow_templates import polygon
|
|
from ground_observations import ground_support, sha
|
|
from candidate_registry import verify
|
|
|
|
|
|
class TopDownTests(unittest.TestCase):
|
|
|
|
def test_registration_area_is_continuous_at_pixel_edges(self):
|
|
from plan_registration import fields,area_iou
|
|
# One observed painted 1 m pixel occupies [-.5,.5] in both axes.
|
|
g=dict(size=(1,1),cell=1.,lo=np.array([0.,0.]))
|
|
known=np.ones((1,1),bool);field=fields(g,dict(target=known,allowed=known,observed=known))
|
|
for dx in [0.,.1,.49,.5,.51,.9]:
|
|
q=box(-.5+dx,-.5,.5+dx,.5)
|
|
# Only the known part contributes: no unseen cell becomes evidence.
|
|
self.assertAlmostEqual(area_iou(q,field),1.-dx,12)
|
|
# On a fully known larger field, translation has the analytic IoU.
|
|
g=dict(size=(3,3),cell=1.,lo=np.array([-1.,-1.]));ink=np.zeros((3,3),bool);ink[1,1]=True
|
|
field=fields(g,dict(target=ink,allowed=np.ones((3,3),bool),observed=np.ones((3,3),bool)))
|
|
for dx in [.1,.49,.5,.51,.9]:
|
|
self.assertAlmostEqual(area_iou(box(-.5+dx,-.5,.5+dx,.5),field),(1.-dx)/(1.+dx),12)
|
|
|
|
def test_straight_stripe_cannot_supply_an_arrow_head(self):
|
|
from object_evidence import evidence
|
|
from observation_checks import assess
|
|
from standard_arrow_templates import dimensions
|
|
from ground_observations import metric_grid
|
|
for profile in ['short','long']:
|
|
pose=[0.,0.,0.,.8];q=polygon('straight_arrow',profile,pose)
|
|
params=dimensions('straight_arrow',profile,pose);g=metric_grid(q,.04,1.2)
|
|
x,y=g['points'].T;ink=shapely.contains_xy(q,x,y).reshape(g['size'])
|
|
known=np.ones(g['size'],bool)
|
|
for label,paint in [('arrow',ink),('stripe',((x>0)&(x<params[3])&(abs(y)<params[5]/2)).reshape(g['size'])),('missing-wing',ink&(y.reshape(g['size'])<params[5]/2))]:
|
|
v=dict(rgb=np.repeat((paint*255).astype('uint8')[:,:,None],3,axis=2),paint=paint,allowed=known,observed=known,names=['synthetic'])
|
|
g['views']=[v,v];a=assess(evidence(q,'straight_arrow',params,q,g),1.,1.,1.,'straight_arrow')
|
|
if label=='arrow':self.assertTrue(a['accepted'],a['failures'])
|
|
else:
|
|
self.assertFalse(a['accepted'])
|
|
self.assertTrue(any(f['check'].startswith('head_support') for f in a['failures']))
|
|
|
|
def test_yellow_crossing_does_not_join_white_marking(self):
|
|
from paint_channels_fast import paint_mask
|
|
from paint_channels import paint_mask as previous
|
|
import cv2
|
|
x,y=np.meshgrid(np.arange(-1,7,.025),np.arange(-2,2,.025))
|
|
rgb=np.full((*x.shape,3),90,'uint8');known=np.ones(x.shape,bool)
|
|
yellow=(abs(y-(x-3)*.7)<.08)&(x>1)&(x<5)
|
|
white=(abs(y)<.07)&(x>0)&(x<6)
|
|
# This muted yellow lies in both old channel predicates.
|
|
rgb[yellow]=[200,190,160];rgb[white]=225
|
|
old=previous(rgb,cell=.025,observed=known,calibration=known)
|
|
new=paint_mask(rgb,cell=.025,observed=known,calibration=known)
|
|
self.assertGreater(float(old[yellow&~white].mean()),.9)
|
|
self.assertEqual(int(new[yellow&~white].sum()),0)
|
|
self.assertGreater(float(new[white].mean()),.99)
|
|
yellow_pixels=paint_mask(rgb,'yellow',cell=.025,observed=known,calibration=known)
|
|
self.assertFalse((new&yellow_pixels).any())
|
|
def test_visible_marking_does_not_require_smooth_expected_depth(self):
|
|
from ground_observations import sample_visible_support,sample_ground_support
|
|
a=dict(view=np.eye(4),intrinsics=np.eye(3),depth=np.full((21,21),50.,'float32'),alpha=np.ones((21,21),'float32'))
|
|
b={k:v.copy() for k,v in a.items()};a['depth'][10,10]=b['depth'][10,10]=50.3
|
|
before=a['depth'].tobytes(),b['depth'].tobytes();uv=np.array([[10.,10.]])
|
|
self.assertTrue(sample_visible_support(a,b,uv)[0]);self.assertFalse(sample_ground_support(a,b,uv)[0])
|
|
self.assertEqual(before,(a['depth'].tobytes(),b['depth'].tobytes()))
|
|
a['depth'][10,10]+= .3;self.assertFalse(sample_visible_support(a,b,uv)[0])
|
|
a['depth'][10,10]=b['depth'][10,10];b['alpha'][10,10]=.5
|
|
self.assertFalse(sample_visible_support(a,b,uv)[0]);b['alpha'][10,10]=1.;b['depth'][10,10]=np.nan
|
|
self.assertFalse(sample_visible_support(a,b,uv)[0])
|
|
|
|
def test_ideal_corner_defect_is_diagnostic_but_wrong_boundary_rejects(self):
|
|
from plan_marking_policy import registration_passes
|
|
from registration_evaluator import RegistrationEvaluator
|
|
m=dict(coverage=1.,valid=1.,iou=.9,boundary_mean_m=.01,boundary_p90_m=.025,landmark_max_error_m=.2)
|
|
self.assertTrue(registration_passes([m,m]));self.assertGreaterEqual(min(RegistrationEvaluator.constraints_from([m,m])),0.)
|
|
for key,value in [('iou',.4),('boundary_mean_m',.1),('boundary_p90_m',.2),('valid',.8),('coverage',.9)]:
|
|
bad=dict(m,**{key:value});self.assertFalse(registration_passes([bad,m]))
|
|
self.assertLess(min(RegistrationEvaluator.constraints_from([bad,m])),0.)
|
|
|
|
def test_boundary_only_failure_is_not_reported_as_admitted(self):
|
|
from admission_contract import AdmissionContract
|
|
from ground_observations import metric_grid
|
|
from shapely.geometry import mapping
|
|
q=polygon('straight_arrow','short',[0.,0.,0.,1.])
|
|
def make_grid(cell):
|
|
g=metric_grid(q,cell,1.2);x,y=g['points'].T;ink=shapely.contains_xy(q,x,y).reshape(g['size']);known=np.ones(g['size'],bool)
|
|
g['views']=[dict(rgb=np.repeat((ink*255).astype('uint8')[:,:,None],3,axis=2),paint=ink,target=ink,observed=known,allowed=known,names=['synthetic']) for _ in range(2)]
|
|
return g
|
|
row=dict(id='same-source',semantic_score=.9,region=mapping(q),target=mapping(q))
|
|
c=AdmissionContract([row],q,make_grid(.025),make_grid(.04));original=c.registration.measure
|
|
def displaced_corner(poly):
|
|
records=original(poly);records[0]['boundary_p90_m']=.16;return records
|
|
c.registration.measure=displaced_corner
|
|
result=c.measure(q,'straight_arrow','short',[0.,0.,0.,1.])
|
|
self.assertFalse(result['accepted']);self.assertFalse(result['admission']['accepted'])
|
|
self.assertEqual([r['check'] for r in result['admission']['failures']],['registration_boundary_p90'])
|
|
self.assertEqual(result['constraint_values'],result['admission']['constraint_values'])
|
|
self.assertEqual(len(result['constraint_values']),len(result['admission']['constraint_names']))
|
|
|
|
def test_surface_explanation_preserves_every_veto(self):
|
|
from ground_observations import surface_sample_evidence, sample_ground_support
|
|
a=dict(view=np.eye(4),intrinsics=np.eye(3),depth=np.full((31,31),50.,'float32'),alpha=np.ones((31,31),'float32'))
|
|
b={k:v.copy() for k,v in a.items()}
|
|
probes=np.array([[10.,10.],[10.25,10.],[9.,10.],[1.,1.],[-2.,-2.]])
|
|
for case in ['flat','low-alpha','occlusion','ridge','missing']:
|
|
with self.subTest(case=case):
|
|
c={k:v.copy() for k,v in a.items()};g={k:v.copy() for k,v in b.items()}
|
|
if case=='low-alpha':g['alpha'][10,10]=.5
|
|
if case=='occlusion':c['depth'][10,10]+=.3
|
|
if case=='ridge':c['depth'][10,10]+= .19;g['depth'][10,10]+=.19
|
|
if case=='missing':g['depth'][10,10]=np.nan
|
|
rows=surface_sample_evidence(c,g,probes)
|
|
self.assertEqual([r['accepted'] for r in rows],sample_ground_support(c,g,probes).tolist())
|
|
if case=='ridge':self.assertEqual(rows[0]['causes'],['rendered_depth_span'])
|
|
if case=='low-alpha':self.assertIn('ground_opacity',rows[0]['causes'])
|
|
if case=='occlusion':self.assertIn('context_ground_disagreement',rows[0]['causes'])
|
|
if case=='missing':self.assertIn('missing_or_nonpositive_depth',rows[0]['causes'])
|
|
self.assertEqual(surface_sample_evidence(a,b,np.empty((0,2))),[])
|
|
|
|
def test_proposal_witness_cannot_mix_sources(self):
|
|
from admission_contract import ProposalPool
|
|
from shapely.geometry import mapping
|
|
q=box(0,0,1,1);far=box(5,0,6,1)
|
|
def row(identity,region,target,score):
|
|
return dict(id=identity,region=mapping(region),target=mapping(target),semantic_score=score)
|
|
invalid=[row('region-only',q,far,.9),row('target-only',far,q,.9),row('low-score',q,q,.1)]
|
|
self.assertLess(ProposalPool(invalid).measure(q,'straight_arrow')['minimum_margin'],0)
|
|
good=row('complete',q,q,.9)
|
|
for rows in [invalid+[good],[good]+invalid[::-1],invalid+[good,dict(good,id='duplicate')]]:
|
|
result=ProposalPool(rows).measure(q,'straight_arrow')
|
|
self.assertGreaterEqual(result['minimum_margin'],0)
|
|
self.assertEqual(result['candidate_id'],'complete')
|
|
self.assertEqual(result['target_iou'],1.)
|
|
self.assertEqual(result['containment'],1.)
|
|
|
|
def test_search_and_independent_admission_agree_under_order_and_duplicates(self):
|
|
from admission_contract import AdmissionContract
|
|
from ground_observations import metric_grid
|
|
from shapely.geometry import mapping
|
|
from plan_marking_policy import registration_passes as passes
|
|
q=polygon('straight_arrow','short',[0.,0.,0.,1.]);extent=q
|
|
def grid(cell):
|
|
g=metric_grid(q,cell,1.2);x,y=g['points'].T
|
|
paint=shapely.contains_xy(q,x,y).reshape(g['size']);known=np.ones(g['size'],bool)
|
|
g['views']=[dict(rgb=np.repeat((paint*255).astype('uint8')[:,:,None],3,axis=2),paint=paint,target=paint,
|
|
observed=known,allowed=known,names=['synthetic']) for _ in range(2)]
|
|
return g
|
|
good=dict(id='complete',semantic_score=.9,region=mapping(q),target=mapping(q))
|
|
bad=dict(id='unrelated',semantic_score=.99,region=mapping(box(10,10,11,11)),target=mapping(q))
|
|
contracts=[AdmissionContract(rows,extent,grid(.025),grid(.04)) for rows in
|
|
[[bad,good],[good,bad],[good,dict(good,id='duplicate'),bad]]]
|
|
for dx in [0.,.015,.05,.2]:
|
|
pose=[dx,0.,0.,1.];candidate=polygon('straight_arrow','short',pose)
|
|
baseline=contracts[0].measure(candidate,'straight_arrow','short',pose)
|
|
for contract in contracts:
|
|
fast=contract.measure(candidate,'straight_arrow','short',pose)
|
|
measured=contract.measure(candidate,'straight_arrow','short',pose,independent=True)
|
|
self.assertEqual(fast['accepted'],measured['accepted'])
|
|
self.assertEqual(min(fast['constraint_values'])>=0,measured['accepted'])
|
|
self.assertTrue(np.allclose(fast['constraint_values'],measured['constraint_values'],atol=1e-7))
|
|
self.assertTrue(np.array_equal(baseline['constraint_values'],fast['constraint_values']))
|
|
self.assertEqual(measured['accepted'],passes(measured['metrics']) and measured['admission']['accepted'] and measured['recall']>=.85)
|
|
|
|
def test_fixed_geometry_from_unregistered_observations(self):
|
|
for kind, angle in [('straight_arrow', .71), ('left_arrow', 1.91),
|
|
('right_arrow', -2.51), ('straight_left_arrow', -.42),
|
|
('straight_right_arrow', 2.87), ('merge_left_arrow', 1.2),
|
|
('merge_right_arrow', -1.2)]:
|
|
with self.subTest(kind=kind):
|
|
target = polygon(kind, 'short', [13., -9., angle, 1.08])
|
|
result = fit_target(target)
|
|
matching = [r for r in result if r['kind'] == kind]
|
|
self.assertTrue(matching, kind)
|
|
self.assertGreater(matching[0]['score'], .65)
|
|
self.assertLess(matching[0]['geometry'].hausdorff_distance(target), .20)
|
|
# An output is exactly reproducible using four parameters.
|
|
for r in result:
|
|
expected = polygon(r['kind'], r['profile'], r['pose'])
|
|
self.assertLess(expected.symmetric_difference(r['geometry']).area, 1e-12)
|
|
|
|
def test_long_profile_and_scale_limits(self):
|
|
target = polygon('straight_arrow', 'long', [-3., 4., .2, .9])
|
|
result = fit_target(target)
|
|
self.assertTrue(result)
|
|
self.assertGreater(result[0]['score'], .7)
|
|
self.assertTrue(all(.75 <= r['pose'][3] <= 1.25 for r in result))
|
|
|
|
def test_non_symbol_does_not_become_a_proposal(self):
|
|
self.assertFalse(fit_target(box(0, 0, 4., 4.)))
|
|
self.assertFalse(fit_target(box(0, 0, 100., .1)))
|
|
|
|
def test_coverage_keeps_unknown_and_occlusion(self):
|
|
geometry = dict(view=np.eye(4), intrinsics=np.eye(3),
|
|
depth=np.full((21,21), 10., 'float32'), alpha=np.ones((21,21)))
|
|
ground = {k:v.copy() for k,v in geometry.items()}
|
|
self.assertTrue(ground_support(geometry, ground).all())
|
|
ground['alpha'][10,10] = 0
|
|
self.assertFalse(ground_support(geometry, ground)[10,10])
|
|
ground['alpha'][10,10] = 1
|
|
ground['depth'][8:13,8:13] = 11
|
|
self.assertFalse(ground_support(geometry, ground)[10,10])
|
|
ground['depth'][10,10] = np.nan
|
|
self.assertFalse(ground_support(geometry, ground)[10,10])
|
|
|
|
def test_direct_fit_to_original_pixel_grid(self):
|
|
from observed_fixed import fit_grid
|
|
for kind, angle in [('straight_arrow', .71), ('left_arrow', -1.2),
|
|
('straight_right_arrow', 2.1), ('merge_left_arrow', -.6)]:
|
|
with self.subTest(kind=kind):
|
|
q = polygon(kind, 'short', [0., 0., angle, 1.])
|
|
lo = np.asarray(q.bounds[:2])-.5
|
|
hi = np.asarray(q.bounds[2:])+.5
|
|
x,y = np.meshgrid(np.arange(lo[0],hi[0],.025), np.arange(lo[1],hi[1],.025))
|
|
paint = shapely.contains_xy(q,x,y)
|
|
view = dict(target=paint, allowed=np.ones(x.shape,bool), observed=np.ones(x.shape,bool))
|
|
grid = dict(lo=lo, size=x.shape, cell=.025, views=[view,view])
|
|
results = [r for r in fit_grid(grid) if r['kind']==kind]
|
|
self.assertTrue(results)
|
|
self.assertLess(results[0]['geometry'].hausdorff_distance(q), .12)
|
|
view['allowed'][:]=False
|
|
self.assertEqual(fit_grid(grid), [])
|
|
|
|
def test_opacity_hole_is_not_a_zero_depth_cliff(self):
|
|
a = dict(view=np.eye(4), intrinsics=np.eye(3),
|
|
depth=np.full((21,21),50.,'float32'), alpha=np.ones((21,21)))
|
|
b = {k:v.copy() for k,v in a.items()}
|
|
b['alpha'][10,10] = .5
|
|
supported = ground_support(a,b)
|
|
self.assertFalse(supported[10,10])
|
|
self.assertTrue(supported[10,9])
|
|
self.assertEqual(int(supported.sum()), 21*21-1)
|
|
# Real geometry discontinuities and absent depth remain vetoes even
|
|
# when both renders agree about an elevated surface.
|
|
a['depth'][10,10] = b['depth'][10,10] = 50.3
|
|
self.assertFalse(ground_support(a,b)[10,9])
|
|
a['depth'][10,10] = b['depth'][10,10] = np.nan
|
|
self.assertFalse(ground_support(a,b)[10,9])
|
|
|
|
def test_named_object_constraints_are_fixed_and_preserve_admission(self):
|
|
from observation_checks import assess
|
|
from reconstruct_topdown import evidence
|
|
from standard_arrow_templates import dimensions
|
|
names=None
|
|
for kind in ['straight_arrow','straight_right_arrow']:
|
|
q=polygon(kind,'short',[0.,0.,0.,1.]);params=dimensions(kind,'short',[0.,0.,0.,1.])
|
|
x,y=np.meshgrid(np.arange(-1,7,.04),np.arange(-2,2,.04));points=np.c_[x.ravel(),y.ravel()]
|
|
paint=shapely.contains_xy(q,x,y);full=np.ones(x.shape,bool)
|
|
def view(known,ink):return dict(rgb=np.zeros((*x.shape,3),'uint8'),paint=ink,allowed=known,observed=known,names=['synthetic'])
|
|
for partial in [full,x>1.4,np.zeros(x.shape,bool)]:
|
|
for ink in [paint,np.zeros(x.shape,bool)]:
|
|
grid=dict(points=points,size=x.shape,cell=.04,views=[view(full,ink),view(partial,ink&partial)])
|
|
score=assess(evidence(q,kind,params,q,grid),1.,1.,1.,kind)
|
|
if names is None:names=score['constraint_names']
|
|
self.assertEqual(score['constraint_names'],names)
|
|
self.assertEqual(min(score['constraint_values'])>=0,score['accepted'])
|
|
missing=assess([],1.,1.,1.,kind)
|
|
self.assertEqual(names,missing['constraint_names']);self.assertLess(min(missing['constraint_values']),0)
|
|
|
|
def test_separable_disk_is_bit_exact_for_paint_observations(self):
|
|
import cv2,time
|
|
from paint_channels import paint_mask as original
|
|
from paint_channels_fast import opening,paint_mask
|
|
rng=np.random.default_rng(17);gray=rng.integers(0,256,(96,128),dtype='uint8')
|
|
for k in [5,31,49,75,121,205]:
|
|
expected=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k)))
|
|
self.assertTrue(np.array_equal(opening(gray,k),expected))
|
|
rgb=np.repeat(gray[:,:,None],3,axis=2);rgb[20:40,30:60]=[220,190,40]
|
|
observed=rng.random(gray.shape)>.1;calibration=rng.random(gray.shape)>.2
|
|
for channel in ['white','yellow']:
|
|
for cell in [.015,.025,.04,.1]:
|
|
for known in [None,observed]:
|
|
self.assertTrue(np.array_equal(paint_mask(rgb,channel,cell,known,calibration),original(rgb,channel,cell,known,calibration)))
|
|
large=rng.integers(0,256,(512,512),dtype='uint8');k=205
|
|
start=time.monotonic();expected=cv2.morphologyEx(large,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k)));old=time.monotonic()-start
|
|
start=time.monotonic();actual=opening(large,k);new=time.monotonic()-start
|
|
self.assertTrue(np.array_equal(actual,expected));print('MORPHOLOGY_SECONDS',old,new,flush=True)
|
|
|
|
def test_observation_lattice_is_independent_of_proposal_bounds(self):
|
|
from ground_observations import metric_grid
|
|
for cell in [.025,.04]:
|
|
a=metric_grid(box(13.003,-9.002,18.004,-7.001),cell,1.2)
|
|
b=metric_grid(box(13.006,-9.005,18.007,-6.998),cell,1.2)
|
|
def indexed(grid):return {tuple(np.rint(p/cell).astype(int)):tuple(p) for p in grid['points']}
|
|
left,right=indexed(a),indexed(b);common=left.keys()&right.keys()
|
|
self.assertGreater(len(common),len(left)*.95)
|
|
self.assertTrue(all(left[k]==right[k] for k in common))
|
|
|
|
def test_native_geometry_keeps_physical_neighbourhood(self):
|
|
a=dict(view=np.eye(4),intrinsics=np.eye(3),depth=np.full((84,84),50.,'float32'),
|
|
alpha=np.ones((84,84),'float32'),compatibility_resolution=21)
|
|
b={k:v.copy() if hasattr(v,'copy') else v for k,v in a.items()}
|
|
a['depth'][42,42]=b['depth'][42,42]=50.3
|
|
supported=ground_support(a,b)
|
|
self.assertFalse(supported[42,50])
|
|
self.assertTrue(supported[42,51])
|
|
|
|
def test_opacity_is_sampled_before_thresholding(self):
|
|
from ground_observations import sample_ground_support
|
|
a=dict(view=np.eye(4),intrinsics=np.eye(3),depth=np.full((21,21),50.,'float32'),alpha=np.ones((21,21),'float32'))
|
|
b={k:v.copy() for k,v in a.items()};a['alpha'][10,10]=b['alpha'][10,10]=.8
|
|
measured=sample_ground_support(a,b,np.array([[10.,10.],[10.1,10.],[10.4,10.]]))
|
|
self.assertEqual(measured.tolist(),[False,False,True])
|
|
a['depth'][10,10]=b['depth'][10,10]=50.4
|
|
self.assertFalse(sample_ground_support(a,b,np.array([[10.4,10.]])).any())
|
|
|
|
def test_constraint_dimension_is_stable_across_view_boundary(self):
|
|
from observed_fixed import constraints_for
|
|
q=polygon('straight_arrow','short',[0.,0.,0.,1.])
|
|
x,y=np.meshgrid(np.arange(-1,7,.025),np.arange(-2,2,.025))
|
|
paint=shapely.contains_xy(q,x,y);observed=x>1.
|
|
full=dict(paint=paint,target=paint,allowed=np.ones(x.shape,bool),observed=np.ones(x.shape,bool))
|
|
partial=dict(paint=paint&observed,target=paint&observed,allowed=observed,observed=observed)
|
|
grid=dict(lo=np.array([-1.,-2.]),size=x.shape,cell=.025,views=[full,partial])
|
|
constraints=constraints_for(grid)
|
|
values=[constraints(polygon('straight_arrow','short',[dx,0.,0.,1.])) for dx in [0.,.9,1.1]]
|
|
self.assertEqual(len({len(v) for v in values}),1)
|
|
self.assertTrue(all(np.isfinite(v).all() for v in values))
|
|
|
|
def test_partial_view_connection_is_unknown_not_broken(self):
|
|
from observation_checks import branch_evidence, assess
|
|
from reconstruct_topdown import evidence
|
|
from standard_arrow_templates import dimensions
|
|
q=polygon('straight_right_arrow','short',[0.,0.,0.,1.]);params=dimensions('straight_right_arrow','short',[0.,0.,0.,1.])
|
|
x,y=np.meshgrid(np.arange(-1,6,.04),np.arange(-2,2,.04));points=np.c_[x.ravel(),y.ravel()]
|
|
paint=shapely.contains_xy(q,x,y);all_known=np.ones(x.shape,bool)
|
|
# The fixed short branch joins the stem by x=1.2 m. This crop
|
|
# retains its tip and the straight head but hides that connection.
|
|
partial=x>1.4
|
|
full=branch_evidence(paint,all_known,all_known,points,q,'straight_right_arrow',params)
|
|
clipped=branch_evidence(paint&partial,partial,partial,points,q,'straight_right_arrow',params)
|
|
broken=branch_evidence(paint&partial,all_known,all_known,points,q,'straight_right_arrow',params)
|
|
self.assertGreater(full['head_connected_support'],.85)
|
|
self.assertGreater(clipped['connection_unobserved_pixels'],0)
|
|
self.assertEqual(broken['connection_unobserved_pixels'],0)
|
|
self.assertLess(broken['head_connected_support'],.85)
|
|
rgb=np.zeros((*x.shape,3),'uint8')
|
|
def view(known,ink):return dict(rgb=rgb,paint=ink,allowed=known,observed=known,names=['synthetic'])
|
|
grid=dict(points=points,size=x.shape,cell=.04,views=[view(all_known,paint),view(partial,paint&partial)])
|
|
ev=evidence(q,'straight_right_arrow',params,q,grid)
|
|
self.assertTrue(assess(ev,1.,1.,1.,'straight_right_arrow')['accepted'])
|
|
grid['views'][1]=view(all_known,paint&partial)
|
|
self.assertFalse(assess(evidence(q,'straight_right_arrow',params,q,grid),1.,1.,1.,'straight_right_arrow')['accepted'])
|
|
|
|
def test_complete_view_admission_preserves_all_existing_limits(self):
|
|
from observation_checks import assess
|
|
from arrow_admission import accept_symbol as prior
|
|
from reconstruct_topdown import evidence
|
|
from standard_arrow_templates import dimensions
|
|
import copy
|
|
q=polygon('straight_arrow','short',[0.,0.,0.,1.]);params=dimensions('straight_arrow','short',[0.,0.,0.,1.])
|
|
x,y=np.meshgrid(np.arange(-1,6,.04),np.arange(-1,1,.04));points=np.c_[x.ravel(),y.ravel()]
|
|
paint=shapely.contains_xy(q,x,y);known=np.ones(x.shape,bool)
|
|
v=dict(rgb=np.zeros((*x.shape,3),'uint8'),paint=paint,allowed=known,observed=known,names=['synthetic'])
|
|
ev=evidence(q,'straight_arrow',params,q,dict(points=points,size=x.shape,cell=.04,views=[v,v]))
|
|
self.assertTrue(prior(ev,1.,1.,1.,'straight_arrow'))
|
|
for key in ['paint_valid','observed_support','negative_paint','recall','connected_recall','head_flank_paint']:
|
|
for value in [0.,.1,.5,.79,.849,.949,.969,.97,1.]:
|
|
for rank in [0,1]:
|
|
data=copy.deepcopy(ev);data[rank][key]=value
|
|
self.assertEqual(assess(data,1.,1.,1.,'straight_arrow')['accepted'],prior(data,1.,1.,1.,'straight_arrow'))
|
|
|
|
def test_camera_mismatch_fails_closed(self):
|
|
a = dict(view=np.eye(4), intrinsics=np.eye(3), depth=np.ones((9,9)), alpha=np.ones((9,9)))
|
|
b = {k:v.copy() for k,v in a.items()}; b['view'][0,3] = 1.
|
|
with self.assertRaises(ValueError):
|
|
ground_support(a, b)
|
|
|
|
def test_compiled_registration_matches_original_metrics(self):
|
|
from registration_evaluator import RegistrationEvaluator
|
|
from plan_registration import metrics
|
|
from plan_marking_policy import registration_passes as passes
|
|
from standard_arrow_templates import KINDS
|
|
for kind in KINDS:
|
|
q=polygon(kind,'short',[0.,0.,.1,1.]);x,y=np.meshgrid(np.arange(-1,7,.025),np.arange(-2,2,.025))
|
|
points=np.c_[x.ravel(),y.ravel()];paint=shapely.contains_xy(q,x,y);allowed=np.ones(x.shape,bool);allowed[20:24,50:53]=False
|
|
def view(obs):return dict(target=paint&obs,paint=paint&obs,allowed=allowed&obs,observed=obs)
|
|
grid=dict(lo=np.array([-1.,-2.]),points=points,size=x.shape,cell=.025,views=[view(np.ones(x.shape,bool)),view(x>1.4)])
|
|
fast=RegistrationEvaluator(grid)
|
|
for delta in [0.,.03,-.17]:
|
|
testq=polygon(kind,'short',[delta,delta,.1,1.]);slow=[metrics(testq,grid,v) for v in grid['views']]
|
|
for a,b in zip(fast.measure(testq),slow):self.assertEqual(a,{k:b[k] for k in a})
|
|
self.assertEqual(fast.margin(testq)>=0,passes(slow))
|
|
|
|
def test_compiled_evaluator_matches_independent_original_pixels(self):
|
|
from observation_evaluator import ObservationEvaluator
|
|
from reconstruct_topdown import evidence
|
|
from standard_arrow_templates import KINDS,dimensions
|
|
for kind in KINDS:
|
|
params=dimensions(kind,'short',[0.,0.,.1,1.]);q=polygon(kind,'short',[0.,0.,.1,1.])
|
|
x,y=np.meshgrid(np.arange(-1,7,.04),np.arange(-2,2,.04));points=np.c_[x.ravel(),y.ravel()]
|
|
paint=shapely.contains_xy(q,x,y);allowed=np.ones(x.shape,bool);allowed[20:24,50:53]=False
|
|
def view(obs):return dict(rgb=np.zeros((*x.shape,3),'uint8'),paint=paint&obs,allowed=allowed&obs,observed=obs,names=['synthetic'])
|
|
grid=dict(points=points,size=x.shape,cell=.04,views=[view(np.ones(x.shape,bool)),view(x>1.4)])
|
|
fast=ObservationEvaluator(q,grid)
|
|
for delta in [0.,.03,-.07]:
|
|
pose=[delta,delta,.1,1.];testq=polygon(kind,'short',pose);parameters=dimensions(kind,'short',pose)
|
|
self.assertEqual(fast.evaluate(testq,kind,parameters),evidence(testq,kind,parameters,q,grid))
|
|
|
|
def test_pixel_geometry_preserves_cell_area_and_holes(self):
|
|
from pixel_geometry import vector
|
|
mask=np.ones((7,9),bool);mask[2:5,3:6]=False;mask[0,:]=False;mask[0,0]=True
|
|
# A rotated world grid exercises axis orientation, origin, thin stems
|
|
# and holes without fitting to a specific street or arrow.
|
|
origin=np.array([1000.,-200.]);u=np.array([.02,.01]);v=np.array([-.01,.02])
|
|
corners=np.array([origin,origin+9*u,origin+9*u+7*v,origin+7*v])
|
|
q=vector(mask,dict(world_corners=corners,width_px=9,height_px=7))
|
|
self.assertAlmostEqual(q.area,mask.sum()*abs(np.linalg.det(np.array([u,v]))),10)
|
|
y,x=np.indices(mask.shape);points=origin+x[...,None]*u+y[...,None]*v
|
|
self.assertTrue(np.array_equal(shapely.contains_xy(q,points[:,:,0],points[:,:,1]),mask))
|
|
|
|
def test_preservation_requires_unique_same_class_objects(self):
|
|
from preservation import compare
|
|
from shapely.geometry import mapping
|
|
def f(identity,x,kind='straight_arrow'):
|
|
return dict(id=identity,properties=dict(subtype=kind),geometry=mapping(box(x,0,x+1,1)))
|
|
old=dict(features=[f('a',0),f('b',.1)])
|
|
self.assertEqual(compare(old,dict(features=[f('one',0)]))['matched'],1)
|
|
self.assertFalse(compare(old,dict(features=[f('wrong',0,'left_arrow')]))['passed'])
|
|
self.assertTrue(compare(old,dict(features=[f('one',0),f('two',.1)]))['passed'])
|
|
self.assertEqual(compare(old,dict(features=[]))['matched'],0)
|
|
|
|
def test_dark_crack_does_not_turn_adjacent_asphalt_into_paint(self):
|
|
from paint_channels_fast import paint_mask
|
|
x,y=np.meshgrid(np.arange(0,8,.025),np.arange(2.7,5.3,.025))
|
|
gray=np.full(x.shape,125,'uint8');gray[abs(y-3.25)<.12]=70
|
|
truth=(x>1)&(x<7)&(abs(y-4)<.12);gray[truth]=155
|
|
rgb=np.repeat(gray[:,:,None],3,axis=2);known=np.ones(x.shape,bool)
|
|
old=paint_mask(rgb,cell=.025,observed=known,calibration=known)
|
|
measured=paint_mask(rgb,cell=.025,observed=known,calibration=known,background='median')
|
|
# Both methods face the same 1% background-error limit: old must
|
|
# demonstrate the failure, the replacement must actually pass it.
|
|
self.assertGreater(float(old[~truth].mean()),.01)
|
|
print('CRACK_BACKGROUND_FALSE_PAINT',float(old[~truth].mean()),float(measured[~truth].mean()),flush=True)
|
|
self.assertGreater(float(measured[truth].mean()),.98)
|
|
self.assertLess(float(measured[~truth].mean()),.01)
|
|
|
|
def test_competing_pose_family_cannot_erase_semantic_hypothesis(self):
|
|
# The first appearance channel resembles a merge; another initial
|
|
# observation supports a straight arrow. Only the latter class is
|
|
# semantically admissible in this synthetic scene.
|
|
straight=polygon('straight_arrow','short',[0.,0.,0.,1.])
|
|
merge=polygon('merge_left_arrow','short',[0.,0.,0.,1.])
|
|
target=merge.union(straight)
|
|
results=fit_target(target,seed_targets=[straight],geometric_constraints=lambda q:[1.],
|
|
object_constraints=lambda q,kind,profile,pose:[1. if kind=='straight_arrow' else -1.])
|
|
self.assertTrue(any(r['kind']=='straight_arrow' for r in results))
|
|
self.assertTrue(any(r['kind']=='straight_arrow' and r['feasible'] for r in results))
|
|
|
|
def test_semantic_overlap_cannot_compensate_for_missing_original_paint(self):
|
|
from direct_fixed import observation_score
|
|
from registration import POLICY as geometry
|
|
from arrow_admission import POLICY as objects
|
|
# A semantic-perfect unsupported pose must rank below one satisfying
|
|
# both measured channels, regardless of duplicate semantic proposals.
|
|
unsupported=[.4,1.,1.,1.]
|
|
supported=[geometry['min_iou'],objects['arrow_fit_score']]
|
|
self.assertLess(observation_score(unsupported),observation_score(supported))
|
|
self.assertAlmostEqual(observation_score(supported),1.)
|
|
self.assertEqual(observation_score([.7,.7]),observation_score([.7,1.,1.]))
|
|
|
|
def test_illumination_filter_has_real_halo_and_fixed_calibration_domain(self):
|
|
from ground_observations import GroundObservations,metric_grid
|
|
from paint_channels_fast import paint_mask
|
|
class Synthetic(GroundObservations):
|
|
def __init__(self):pass
|
|
def raw_views(self,lattice):
|
|
x=lattice['points'][:,0].reshape(lattice['size']);y=lattice['points'][:,1].reshape(lattice['size'])
|
|
gray=125+30*np.sin(x*.9)+9*np.cos(y*.7)
|
|
gray[(x>1)&(x<7)&(abs(y-4)<.12)]+=60
|
|
rgb=np.repeat(np.clip(gray,0,255).astype('uint8')[:,:,None],3,axis=2);known=np.ones(x.shape,bool)
|
|
return [dict(rgb=rgb,observed=known,allowed=known,names=['synthetic']) for _ in range(2)]
|
|
obs=Synthetic();grid=obs.grid(box(1,3.88,7,4.12));low=grid['points'].min(0);high=grid['points'].max(0)
|
|
parent=metric_grid(box(*low,*high),.025,2.);raw=obs.raw_views(parent)[0]
|
|
indices=np.rint((grid['points']-parent['lo'])/.025).astype(int)
|
|
calibration=np.zeros(parent['size'],bool);calibration[indices[:,1],indices[:,0]]=True
|
|
full=paint_mask(raw['rgb'],cell=.025,observed=raw['observed'],calibration=calibration,background='median')
|
|
self.assertTrue(np.array_equal(grid['views'][0]['paint'].ravel(),full[indices[:,1],indices[:,0]]))
|
|
|
|
def test_object_measurement_separates_paint_from_uneven_background(self):
|
|
from ground_observations import GroundObservations
|
|
class Synthetic(GroundObservations):
|
|
def __init__(self):pass
|
|
def raw_views(self,lattice):
|
|
x=lattice['points'][:,0].reshape(lattice['size']);y=lattice['points'][:,1].reshape(lattice['size'])
|
|
gray=125+12*np.sin(x*1.7)+9*np.cos(y*2.1)+3*np.sin(x*12+y*9)
|
|
painted=(x>1)&(x<7)&(abs(y-4)<.12);gray[painted]=230
|
|
rgb=np.repeat(np.clip(gray,0,255).astype('uint8')[:,:,None],3,axis=2);known=np.ones(x.shape,bool)
|
|
return [dict(rgb=rgb,observed=known,allowed=known,names=['synthetic']) for _ in range(2)]
|
|
grid=Synthetic().grid(box(1,3.88,7,4.12));x=grid['points'][:,0].reshape(grid['size']);y=grid['points'][:,1].reshape(grid['size'])
|
|
truth=(x>1)&(x<7)&(abs(y-4)<.12);mask=grid['views'][0]['paint']
|
|
self.assertGreater(float(mask[truth].mean()),.98)
|
|
self.assertLess(float(mask[~truth].mean()),.01)
|
|
|
|
def test_camera_broad_phase_preserves_original_geometric_owners(self):
|
|
from ground_observations import GroundObservations,metric_grid
|
|
from fit_scene import project
|
|
from row_evidence import choose_owners
|
|
class Synthetic(GroundObservations):
|
|
def __init__(self):
|
|
self.tiles=[dict(id=str(i)) for i in range(4)]
|
|
self.centers=np.array([[-80.,0.],[0.,0.],[40.,0.],[300.,0.]])
|
|
def camera(self,name):
|
|
view=np.eye(4);view[:2,3]=-self.centers[int(name)]
|
|
return dict(view=view,intrinsics=np.array([[20.,0.,600.],[0.,20.,600.],[0.,0.,1.]]))
|
|
def rgb(self,name):return np.full((32,32,3),30+int(name)*40,'uint8')
|
|
def surface(self,name,points):return np.ones(len(points),bool)
|
|
obs=Synthetic()
|
|
for region in [box(-2,-1,15,1),box(180,-1,190,1)]:
|
|
grid=metric_grid(region,.5,0);points=grid['points']
|
|
distance=np.linalg.norm(points[:,None]-obs.centers[None],axis=2)
|
|
cover=np.zeros(distance.shape,bool)
|
|
for i,tile in enumerate(obs.tiles):
|
|
uv=project(points,obs.camera(tile['id']));cover[:,i]=(uv.min(1)>=20)&(uv.max(1)<1180)
|
|
expected=choose_owners(distance,cover);views=obs.raw_views(grid)
|
|
for rank,view in enumerate(views):
|
|
known=expected[:,rank]>=0
|
|
self.assertTrue(np.array_equal(known,view['observed'].ravel()))
|
|
self.assertTrue(np.array_equal(view['rgb'].reshape(-1,3)[known,0],30+expected[known,rank]*40))
|
|
|
|
def test_consumers_share_one_object_paint_measurement(self):
|
|
from ground_observations import GroundObservations
|
|
class Synthetic(GroundObservations):
|
|
def __init__(self):self.calls=0
|
|
def raw_views(self,lattice):
|
|
self.calls+=1;points=lattice['points'];x=points[:,0];y=points[:,1]
|
|
values=80+15*np.sin(x*4)+12*np.cos(y*5)
|
|
values+=130*((abs(y-.3)<.13)&(x>1)&(x<6))
|
|
gray=np.clip(values,0,255).astype('uint8').reshape(lattice['size'])
|
|
rgb=np.repeat(gray[:,:,None],3,axis=2);known=np.ones(gray.shape,bool)
|
|
return [dict(rgb=rgb,allowed=known,observed=known,names=['synthetic']) for _ in range(2)]
|
|
obs=Synthetic();region=box(1,0,6,.6)
|
|
fine=obs.grid(region);coarse=obs.grid(region,cell=.04)
|
|
count=obs.calls;again=obs.grid(region)
|
|
self.assertEqual(obs.calls,count)
|
|
self.assertTrue(np.array_equal(fine['views'][0]['paint'],again['views'][0]['paint']))
|
|
# Different consumers sample the same measured paint, never rerun Otsu.
|
|
uv=np.rint((coarse['points']-fine['lo'])/.025).astype(int)
|
|
inside=(uv>=0).all(1)&(uv<np.array(fine['size'][::-1])).all(1)
|
|
self.assertTrue(inside.all())
|
|
actual=coarse['views'][0]['paint'].ravel()[inside]
|
|
expected=fine['views'][0]['paint'][uv[inside,1],uv[inside,0]]
|
|
self.assertTrue(np.array_equal(actual,expected))
|
|
|
|
def test_object_association_retains_all_original_measurements(self):
|
|
from candidate_registry import group_observations
|
|
from shapely.affinity import translate
|
|
q=polygon('straight_arrow','short',[0.,0.,0.,1.])
|
|
observations=[dict(patch=str(i),source='semantic-silhouette',semantic_score=.9-i*.01,
|
|
extent=translate(q,xoff=.01*i),region=q,target=q) for i in range(6)]
|
|
groups=group_observations(observations)
|
|
self.assertEqual(len(groups),1)
|
|
self.assertEqual(len(groups[0]),6)
|
|
self.assertEqual({id(v) for v in groups[0]},{id(v) for v in observations})
|
|
other=dict(observations[0],patch='neighbor',extent=translate(q,yoff=3.))
|
|
self.assertEqual(len(group_observations(observations+[other])),2)
|
|
|
|
def test_reconciliation_preserves_missing_and_unrelated_objects(self):
|
|
from reconcile_objects import reconcile
|
|
import hashlib,copy
|
|
from shapely.geometry import mapping
|
|
def f(identity,x,kind='straight_arrow'):
|
|
return dict(id=identity,properties=dict(subtype=kind,authority='observation-only',route_permission='unassigned',review_status='unreviewed',**{'class':'road_marking'}),geometry=mapping(box(x,0,x+1,1)))
|
|
base=dict(type='FeatureCollection',features=[f('old-a',0),f('old-b',3),f('stripe',10,'linear_marking')])
|
|
result=dict(type='FeatureCollection',features=[f('new-a',.01),f('new-c',6)])
|
|
bb=json.dumps(base).encode();rb=json.dumps(result).encode()
|
|
receipt=dict(passed=True,original_pixels_remeasured=True,immutable_presets=True,source_registry_verified=True,
|
|
source_result_sha256=hashlib.sha256(rb).hexdigest(),accepted=2,checks=[dict(id=v['id']) for v in result['features']])
|
|
assembled,ledger=reconcile(bb,rb,receipt);byid={v['id']:v for v in assembled['features']}
|
|
self.assertEqual(set(byid),{'old-a','old-b','stripe','new-c'})
|
|
saved=json.loads(bb)
|
|
self.assertEqual(byid['old-b'],saved['features'][1]);self.assertEqual(byid['stripe'],saved['features'][2])
|
|
self.assertEqual(ledger['retained_previous_arrow_geometry'],['old-b']);self.assertEqual(ledger['deleted'],[])
|
|
modified=copy.deepcopy(result);modified['features'][0]['geometry']=mapping(box(100,0,101,1))
|
|
with self.assertRaises(ValueError):reconcile(bb,json.dumps(modified).encode(),receipt)
|
|
bad=copy.deepcopy(receipt);bad['checks'].pop()
|
|
with self.assertRaises(ValueError):reconcile(bb,rb,bad)
|
|
|
|
def test_reconciliation_upgrades_only_contained_unreviewed_fragments(self):
|
|
from reconcile_objects import reconcile
|
|
from shapely.geometry import mapping
|
|
import hashlib
|
|
def feature(identity,geometry,kind,authority='observation-only'):
|
|
return dict(id=identity,geometry=mapping(geometry),properties=dict(subtype=kind,
|
|
authority=authority,review_status='unreviewed',**{'class':'road_marking'}))
|
|
arrow=polygon('straight_arrow','short',[0.,0.,0.,1.])
|
|
proposal=feature('complete',arrow,'straight_arrow');rb=json.dumps(dict(features=[proposal])).encode()
|
|
receipt=dict(passed=True,original_pixels_remeasured=True,immutable_presets=True,source_registry_verified=True,
|
|
source_result_sha256=hashlib.sha256(rb).hexdigest(),accepted=1,checks=[dict(id='complete')])
|
|
center=arrow.representative_point();contained=arrow.intersection(center.buffer(.2))
|
|
self.assertGreater(contained.area,.005)
|
|
for geometry,authority,allowed in [(contained,'observation-only',True),
|
|
(box(-20,-.05,20,.05),'observation-only',False),(contained,'manual',False)]:
|
|
old=feature('fragment',geometry,'linear_marking',authority);base=dict(features=[old])
|
|
assembled,ledger=reconcile(json.dumps(base).encode(),rb,receipt)
|
|
if allowed:
|
|
self.assertEqual(len(assembled['features']),1)
|
|
self.assertEqual(assembled['features'][0]['id'],'fragment')
|
|
self.assertEqual(assembled['features'][0]['properties']['subtype'],'straight_arrow')
|
|
self.assertEqual(ledger['fragment_upgrades'][0]['previous_records'],json.loads(json.dumps([old])))
|
|
self.assertEqual(ledger['conflicts'],[])
|
|
else:
|
|
self.assertEqual(assembled,json.loads(json.dumps(base)))
|
|
self.assertEqual(len(ledger['conflicts']),1)
|
|
|
|
def test_source_changes_invalidate_registry(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
root = Path(directory)
|
|
for folder in ['symbol-patches','symbol-masks']:
|
|
(root/folder).mkdir()
|
|
files = ['symbol-patches.json','symbol-semantics.json','symbol-patches/a.png','symbol-masks/a.npz']
|
|
for filename in files:
|
|
(root/filename).write_bytes(b'original')
|
|
from candidate_registry import VERSION
|
|
from ground_observations import PHOTOMETRY
|
|
registry = dict(version=VERSION,photometry=PHOTOMETRY,patch_manifest_sha256=sha(root/files[0]), semantics_sha256=sha(root/files[1]),
|
|
inputs={'a':dict(image_sha256=sha(root/files[2]), masks_sha256=sha(root/files[3]))})
|
|
self.assertTrue(verify(root, registry))
|
|
(root/files[2]).write_bytes(b'changed')
|
|
with self.assertRaises(ValueError):
|
|
verify(root, registry)
|
|
|
|
|
|
class SpatialMembershipTests(unittest.TestCase):
|
|
def test_index_equals_full_scan(self):
|
|
from spatial_index import SpatialIndex
|
|
rng=np.random.default_rng(812);world=rng.uniform(-100,100,(10000,3));relative=rng.uniform(-2,8,len(world))
|
|
world[:4,:2]=[[-20,-20],[0,0],[20,20],[20,20]];relative[:4]=[0,0,0,5]
|
|
index=SpatialIndex(world,relative,-.6,4.)
|
|
for bounds in [[[-20,-20],[20,20]],[[0,0],[0,0]],[[150,150],[180,180]]]+[
|
|
[a,a+rng.uniform(1,70,2)] for a in rng.uniform(-120,100,(30,2))]:
|
|
bounds=np.asarray(bounds)
|
|
expected=np.flatnonzero(((world[:,:2]>=bounds[0])&(world[:,:2]<=bounds[1])).all(1)&(relative>=-.6)&(relative<=4.))
|
|
np.testing.assert_array_equal(index.query(bounds),expected)
|
|
empty=SpatialIndex(world,relative,20,30)
|
|
self.assertEqual(len(empty.query([[-100,-100],[100,100]])),0)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|