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:
@@ -0,0 +1,102 @@
|
||||
"""Topology, provenance and fit bounds for automatic infrastructure consolidation."""
|
||||
import copy
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import pytest
|
||||
pytest.importorskip('shapely')
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'simulation/urban-mapping/vector'))
|
||||
from refine_contours import consolidate
|
||||
from contour_geometry import smooth, sample
|
||||
from shapely.geometry import LineString
|
||||
|
||||
|
||||
def feature(name, xy, cls='curb', score=.6, z=3, source=None):
|
||||
return dict(type='Feature',id=name,geometry=dict(type='LineString',coordinates=[[x,y,z] for x,y in xy]),
|
||||
properties={'class':cls,'source_class':source or ('curb' if cls=='curb' else 'lane'),
|
||||
'geometry_role':'boundary' if cls=='curb' else 'paint-axis','confidence':score,
|
||||
'authority':'observation-only','route_permission':'unassigned','review_status':'unreviewed'})
|
||||
|
||||
|
||||
class Evidence:
|
||||
def __init__(self, supported=True):self.supported=supported
|
||||
def bridge(self,p,key):return self.supported
|
||||
def support(self,p,key):return np.ones(len(p),bool),np.full(len(p),self.supported,bool)
|
||||
|
||||
|
||||
def run(features,evidence=None):return consolidate(dict(features=features),evidence)
|
||||
|
||||
|
||||
def test_tile_seams_join_and_original_is_immutable():
|
||||
f=[feature('a',[(0,0),(4,0)]),feature('b',[(4,0),(8,.01)])]
|
||||
original=copy.deepcopy(f);result,report=run(f)
|
||||
assert f==original
|
||||
assert len(result['features'])==1 and len(report['joins'])==1
|
||||
assert result['features'][0]['properties']['consolidation']['source_ids']==['a','b']
|
||||
assert result['features'][0]['geometry']['coordinates'][0]==[0.,0.,3.]
|
||||
assert result['features'][0]['properties']['route_permission']=='unassigned'
|
||||
|
||||
|
||||
def test_gap_requires_support_and_is_recorded_as_inference():
|
||||
f=[feature('a',[(0,0),(4,0)]),feature('b',[(4.6,0),(8,0)])]
|
||||
assert len(run(f)[0]['features'])==2
|
||||
assert len(run(f,Evidence(False))[0]['features'])==2
|
||||
result,report=run(f,Evidence())
|
||||
assert len(result['features'])==1 and report['inferred_gap_m']==.6
|
||||
assert result['features'][0]['properties']['consolidation']['inferred_gaps'][0]['evidence']=='image-and-ground'
|
||||
|
||||
|
||||
def test_parallel_curbs_different_heights_and_classes_stay_separate():
|
||||
f=[feature('a',[(0,0),(4,0)]),feature('b',[(0,.5),(4,.5)]),
|
||||
feature('c',[(4.05,0),(8,0)],z=4),feature('d',[(4.05,0),(8,0)],cls='road_marking')]
|
||||
assert len(run(f,Evidence())[0]['features'])==4
|
||||
|
||||
|
||||
def test_branching_junction_is_not_shortcut():
|
||||
f=[feature('a',[(0,0),(4,0)]),feature('b',[(4,0),(8,0)]),feature('c',[(4,0),(4,4)])]
|
||||
result,report=run(f,Evidence())
|
||||
assert len(result['features'])==3 and not report['joins']
|
||||
|
||||
|
||||
def test_dashes_and_stopline_have_different_semantics():
|
||||
f=[feature('a',[(0,0),(3,0)],cls='road_marking'),feature('b',[(4,0),(7,0)],cls='road_marking'),
|
||||
feature('c',[(3,0),(3,1)],cls='road_marking',source='stopline')]
|
||||
assert len(run(f,Evidence())[0]['features'])==3
|
||||
|
||||
|
||||
def test_duplicate_removed_but_crossing_line_retained():
|
||||
f=[feature('a',[(0,0),(8,0)],score=.8),feature('b',[(0,.04),(8,.04)],score=.4),
|
||||
feature('c',[(4,-2),(4,2)])]
|
||||
result,report=run(f)
|
||||
assert len(result['features'])==2 and report['duplicates']==['b']
|
||||
|
||||
|
||||
def test_short_noise_needs_negative_evidence_and_isolation():
|
||||
f=[feature('a',[(0,0),(.7,0)],score=.4)]
|
||||
assert len(run(f)[0]['features'])==1
|
||||
assert len(run(f,Evidence())[0]['features'])==1
|
||||
assert len(run(f,Evidence(False))[0]['features'])==0
|
||||
|
||||
|
||||
def test_spline_is_bounded_preserves_corners_heights_and_endpoints():
|
||||
p=np.array([[x,.06*np.sin(x*5),3+.02*x] for x in np.linspace(0,8,60)])
|
||||
fitted,curves=smooth(p)
|
||||
assert np.max(np.abs(fitted[[0,-1]]-p[[0,-1]]))==0
|
||||
assert LineString(fitted[:,:2]).hausdorff_distance(LineString(p[:,:2]))<=.12
|
||||
assert any(c['degree']==3 for c in curves)
|
||||
corner=np.array([[0,0,3],[1,0,3],[2,0,3],[2,1,3],[2,2,3]],float)
|
||||
fitted,_=smooth(corner)
|
||||
assert any(np.array_equal(q,[2,0,3]) for q in fitted)
|
||||
|
||||
|
||||
def test_bridge_cannot_cross_another_boundary_or_known_opening():
|
||||
f=[feature('a',[(0,0),(4,0)]),feature('b',[(5,0),(8,0)]),feature('c',[(4.5,-2),(4.5,2)])]
|
||||
assert len(run(f,Evidence())[0]['features'])==3
|
||||
opening=dict(type='Feature',id='cut',properties={'class':'curb_cut'},geometry=dict(type='Polygon',coordinates=[[[4.2,-1,3],[4.8,-1,3],[4.8,1,3],[4.2,1,3],[4.2,-1,3]]]))
|
||||
assert len(run(f[:2]+[opening],Evidence())[0]['features'])==3
|
||||
|
||||
|
||||
def test_order_independent_geometry_and_ids():
|
||||
f=[feature('a',[(0,0),(4,0)]),feature('b',[(4,0),(8,0)]),feature('c',[(0,.03),(4,.03)],score=.3)]
|
||||
assert run(f)[0]==run(list(reversed(f)))[0]
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Protect graph/provenance boundaries and unchanged independent admission."""
|
||||
import ast
|
||||
import json
|
||||
from pathlib import Path
|
||||
import importlib.util
|
||||
import numpy as np
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
MODULE=ROOT/'simulation/urban-plan-research'
|
||||
|
||||
def definition():return json.loads((MODULE/'systematic/definition.json').read_text())
|
||||
|
||||
def test_primary_discovery_does_not_read_an_existing_map():
|
||||
d=definition();groups=d['groups'];primary=next(g for g in groups if g['group']=='primary_search')
|
||||
assert groups.index(primary)<next(i for i,g in enumerate(groups)if g['group']=='paint_assembly')
|
||||
for stage in ['extract_observations','observation_tiles','prepare_primary_symbols']:
|
||||
tree=ast.parse((MODULE/primary['files'][stage+'.py']).read_text())
|
||||
assert not any(isinstance(n,ast.Constant)and isinstance(n.value,str)and ('full-map.json'in n.value or 'baseline.json'in n.value)for n in ast.walk(tree))
|
||||
assert not any(s in {'prepare_symbols','prepare_uniform_symbols','prepare_compact_symbols','render_coverage','refine_recall'}for g in groups for s in g['stages'])
|
||||
assert sum(s=='semantic_symbols'for g in groups for s in g['stages'])==1
|
||||
|
||||
def test_candidate_keeps_independent_verifiers_and_frozen_policy_files():
|
||||
d=definition();legacy=json.loads((MODULE/'pipeline/definition.json').read_text())
|
||||
expected={}
|
||||
for g in legacy['groups']:
|
||||
for name,path in g['files'].items():
|
||||
if name.endswith(('_rules.py','_evidence.py'))or name.startswith('verify_'):expected.setdefault(name,set()).add(path)
|
||||
seen=set()
|
||||
for group in d['groups']:
|
||||
for name,path in group['files'].items():
|
||||
if name in expected and group['group']!='primary_arrows':
|
||||
if path=='systematic/marking_rules.py':
|
||||
assert name=='marking_rules.py'
|
||||
assert 'marking_pass/marking_rules.py' in expected[name]
|
||||
assert_frozen_strip_gates()
|
||||
elif path=='systematic/batched_row_evidence.py':
|
||||
assert name=='row_evidence.py' and group['group']=='marking_pass'
|
||||
assert_frozen_camera_reader()
|
||||
else:assert path in expected[name],(group['group'],name)
|
||||
seen.update(group['stages'])
|
||||
assert {'admit_primary_arrows','admit_marking_contracts','audit_compact_symbols','revalidate_strips','verify_discovered_crossings','audit_linear_windows'}<=seen
|
||||
assert d['manual_rois']==[] and d['gaussian_only']
|
||||
|
||||
def test_candidate_definition_has_only_canonical_safe_sources():
|
||||
d=definition()
|
||||
assert len({g['group']for g in d['groups']})==len(d['groups'])
|
||||
groups={g['group']for g in d['groups']}
|
||||
for group in d['groups']:
|
||||
assert all(stage+'.py'in group['files']for stage in group['stages'])
|
||||
for relative in group['files'].values():
|
||||
p=Path(relative)
|
||||
assert not p.is_absolute()and '..'not in p.parts and (MODULE/p).is_file()
|
||||
assert '.runtime'not in relative
|
||||
for relative in group.get('input_files',{}).values():assert relative.split('/')[0]in groups|{'ortho'}
|
||||
|
||||
def test_spatial_index_preserves_exact_membership_order_at_boundaries():
|
||||
spec=importlib.util.spec_from_file_location('systematic_spatial',MODULE/'topdown/spatial_index.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
|
||||
rng=np.random.default_rng(9);world=rng.uniform(-200,200,(10000,3));relative=rng.uniform(-2,6,len(world))
|
||||
world[:4,:2]=[[-20,-20],[0,0],[20,20],[40,40]];relative[:4]=[-.6,4.,.8,4.00001]
|
||||
index=m.SpatialIndex(world,relative,-.6,4.)
|
||||
for bounds in [np.array([[-20,-20],[20,20]]),np.array([[300,300],[400,400]])]+[np.sort(rng.uniform(-200,200,(2,2)),axis=0)for _ in range(15)]:
|
||||
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)
|
||||
|
||||
|
||||
def test_primary_arrows_use_exact_qualified_contract_closure():
|
||||
import hashlib
|
||||
d=definition();g=next(g for g in d['groups']if g['group']=='primary_arrows')
|
||||
locked=json.loads((MODULE/'systematic/arrow-contract-lock.json').read_text())
|
||||
for name,digest in locked['files'].items():
|
||||
assert hashlib.sha256((MODULE/g['files'][name]).read_bytes()).hexdigest()==digest
|
||||
assert g['files']['verify_topdown.py']=='topdown/verify_topdown.py'
|
||||
|
||||
|
||||
def assert_frozen_strip_gates():
|
||||
# Only seam ownership changed: a distinct parallel track is not an
|
||||
# end-to-end seam. Body, visibility, contrast, dark flanks, replacement,
|
||||
# overlap and every numeric POLICY value remain the original AST.
|
||||
def frozen(relative):
|
||||
tree=ast.parse((MODULE/relative).read_text())
|
||||
tree.body=[n for n in tree.body if not (isinstance(n,ast.FunctionDef)and n.name=='isolated_addition')]
|
||||
return ast.dump(tree,include_attributes=False)
|
||||
assert frozen('systematic/marking_rules.py')==frozen('marking_pass/marking_rules.py')
|
||||
|
||||
|
||||
def test_all_numeric_strip_admission_and_replacement_gates_are_unchanged():
|
||||
assert_frozen_strip_gates()
|
||||
|
||||
|
||||
def test_initial_coverage_is_complete_distinct_and_deterministic():
|
||||
spec=importlib.util.spec_from_file_location('initial_coverage',MODULE/'systematic/observation_coverage.py')
|
||||
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
|
||||
points=np.c_[np.arange(-75,80,5),np.zeros(31)];centers=np.array([[-40.,0.],[0.,0.],[40.,0.]])
|
||||
original=centers.copy();extra,report=m.complete_coverage(points,centers)
|
||||
assert report['initial_two_view_samples']<len(points)
|
||||
assert report['planned_two_view_samples']==len(points)
|
||||
assert m.complete_coverage(points,centers)==(extra,report)
|
||||
combined=np.r_[centers,[r['center']for r in extra]]
|
||||
assert len(np.unique(combined,axis=0))==len(combined)
|
||||
assert ((abs(points[:,None]-combined).max(2)<=m.POLICY['usable_half_width_m']).sum(1)>=2).all()
|
||||
np.testing.assert_array_equal(centers,original)
|
||||
assert m.complete_coverage(points,combined)[0]==[]
|
||||
|
||||
|
||||
def test_crossing_fit_keeps_independent_boundary_gate_and_optimizer_limits():
|
||||
old=ast.parse((MODULE/'full_plan/crosswalk_family.py').read_text())
|
||||
new=ast.parse((MODULE/'systematic/crossing_fit.py').read_text())
|
||||
original=next(n for n in ast.walk(old)if isinstance(n,ast.FunctionDef)and n.name=='residual')
|
||||
independent=next(n for n in ast.walk(new)if isinstance(n,ast.FunctionDef)and n.name=='boundary_residual')
|
||||
assert [ast.dump(n)for n in original.body]==[ast.dump(n)for n in independent.body]
|
||||
def solver_keywords(tree):
|
||||
call=next(n for n in ast.walk(tree)if isinstance(n,ast.Call)and isinstance(n.func,ast.Name)and n.func.id=='least_squares')
|
||||
return [ast.dump(k)for k in call.keywords]
|
||||
assert solver_keywords(old)==solver_keywords(new)
|
||||
|
||||
|
||||
def test_family_admission_precedes_overlap_selection_without_changing_its_rules():
|
||||
original=ast.parse((MODULE/'marking_pass/beta_profiles.py').read_text())
|
||||
changed=ast.parse((MODULE/'systematic/row_discovery.py').read_text())
|
||||
old=next(n for n in original.body if isinstance(n,ast.FunctionDef)and n.name=='discover')
|
||||
new=next(n for n in changed.body if isinstance(n,ast.FunctionDef)and n.name=='discover')
|
||||
transformations=[n for n in new.body if isinstance(n,ast.Assign)and isinstance(n.value,ast.Call)and isinstance(n.value.func,ast.Name)and n.value.func.id=='measured_rows']
|
||||
assert len(transformations)==1
|
||||
index=new.body.index(transformations[0])
|
||||
assert isinstance(new.body[index+1],ast.Assign)and new.body[index+1].targets[0].id=='accepted'
|
||||
old_modes=next(n for n in old.body if isinstance(n,ast.For) and isinstance(n.target,ast.Name) and n.target.id=='mode')
|
||||
new_modes=next(n for n in new.body if isinstance(n,ast.For) and isinstance(n.target,ast.Name) and n.target.id=='mode')
|
||||
# The identical fit list is shared by two measured interpretations; every
|
||||
# admission statement inside the fit loop remains the original AST.
|
||||
assert [ast.dump(n,include_attributes=False) for n in old_modes.body[0].body]==[ast.dump(n,include_attributes=False) for n in new_modes.body[0].body]
|
||||
old_setup=next(n for n in old.body if isinstance(n,ast.Assign) and isinstance(n.targets[0],ast.Tuple))
|
||||
new_setup=next(n for n in new.body if isinstance(n,ast.Assign) and isinstance(n.targets[0],ast.Tuple))
|
||||
assert ast.dump(old_setup,include_attributes=False)==ast.dump(new_setup,include_attributes=False)
|
||||
|
||||
|
||||
def assert_frozen_camera_reader():
|
||||
original=ast.parse((MODULE/'marking_pass/row_evidence.py').read_text())
|
||||
changed=ast.parse((MODULE/'systematic/batched_row_evidence.py').read_text())
|
||||
def functions(tree,name):return [ast.dump(n,include_attributes=False) for n in ast.walk(tree) if isinstance(n,ast.FunctionDef) and n.name==name]
|
||||
# Only camera projection scheduling changes. Stable ownership ordering and
|
||||
# every pixel/road/vehicle/protected gate must remain byte-for-byte AST equal.
|
||||
for name in ['choose_owners','read']:
|
||||
assert functions(original,name)==functions(changed,name)
|
||||
|
||||
|
||||
def test_batched_observer_keeps_sampling_gates_and_stable_ownership():
|
||||
assert_frozen_camera_reader()
|
||||
|
||||
|
||||
def test_complete_initial_view_plan_preserves_structural_observers_and_coverage(monkeypatch):
|
||||
monkeypatch.syspath_prepend(str(MODULE/'systematic'))
|
||||
import test_initial_views
|
||||
test_initial_views.run()
|
||||
d=definition();base=next(g for g in d['groups']if g['group']=='base')
|
||||
assert base['files']['initial_views.py']=='systematic/initial_views.py'
|
||||
assert base['files']['test_initial_views.py']=='systematic/test_initial_views.py'
|
||||
|
||||
|
||||
def test_all_survey_readers_use_manifest_identity(monkeypatch):
|
||||
monkeypatch.syspath_prepend(str(MODULE))
|
||||
import test_survey_index
|
||||
test_survey_index.run()
|
||||
@@ -0,0 +1,49 @@
|
||||
import copy
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location('urban_ablation', Path(__file__).parents[1] /
|
||||
'simulation/urban-plan-research/evaluation/ablation.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
def test_equal_geometry_counts_do_not_hide_property_or_position_changes():
|
||||
doc = dict(features=[dict(id='a', properties={'class': 'road_marking', 'subtype': 'crosswalk'},
|
||||
geometry={'type': 'Point', 'coordinates': [0, 0, 0]})])
|
||||
changed = copy.deepcopy(doc)
|
||||
changed['features'][0]['geometry']['coordinates'][0] = .1
|
||||
result = module.compare(doc, changed)
|
||||
assert not result['features_equal'] and result['changed_ids'] == ['a']
|
||||
assert not result['recall_measured']
|
||||
changed['features'][0]['geometry'] = doc['features'][0]['geometry']
|
||||
changed['features'][0]['properties']['subtype'] = 'linear_marking'
|
||||
assert not module.compare(doc, changed)['features_equal']
|
||||
|
||||
|
||||
def test_duplicate_id_is_not_collapsed():
|
||||
with pytest.raises(ValueError, match='Duplicate'):
|
||||
module.features(dict(features=[dict(id='a'), dict(id='a')]))
|
||||
|
||||
|
||||
def test_omission_replays_all_later_stages_and_rejects_missing_named_input():
|
||||
d = dict(groups=[dict(group='a', stages=['one']), dict(group='b', stages=['two']),
|
||||
dict(group='c', stages=['three'])])
|
||||
p = module.tail_plan(d, 'a', ['b'])
|
||||
assert p['groups'] == ['a', 'c'] and not p['downstream_cache_reuse']
|
||||
d['groups'][2]['input_files'] = {'/evidence': 'b'}
|
||||
with pytest.raises(ValueError, match='producer'):
|
||||
module.tail_plan(d, 'a', ['b'])
|
||||
with pytest.raises(ValueError, match='outside'):
|
||||
module.tail_plan(d, 'b', ['a'])
|
||||
|
||||
|
||||
def test_holdout_requires_unseen_source_and_street_group():
|
||||
development = [dict(source_sha256='one', location_group='street')]
|
||||
for item in [dict(source_sha256='one', location_group='new'),
|
||||
dict(source_sha256='two', location_group='street')]:
|
||||
with pytest.raises(ValueError, match='leakage'):
|
||||
module.validate_split(development, [item])
|
||||
assert module.validate_split(development, [dict(source_sha256='two', location_group='new')])
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Evidence preservation and shared-policy regression for the final gate."""
|
||||
import copy
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(os.environ.get("ADMISSION_SOURCE", str(Path(__file__).resolve().parents[1] /
|
||||
"simulation/urban-plan-research/replay/final_symbol_admission.py")))
|
||||
spec = importlib.util.spec_from_file_location("final_symbol_admission", SOURCE)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
def feature(name, score, kind="bicycle", cls="road_marking"):
|
||||
return dict(id=name, geometry=dict(type="Polygon", coordinates=[[[0, 0, 2], [1, 0, 2], [0, 1, 2], [0, 0, 2]]]),
|
||||
properties=dict(subtype=kind, **{"class": cls}, template_fit_score=score))
|
||||
|
||||
|
||||
class AdmissionTests(unittest.TestCase):
|
||||
def test_threshold_and_geometry_preservation(self):
|
||||
source = dict(features=[feature("weak", .7399), feature("edge", .74), feature("strong", .92)])
|
||||
before = copy.deepcopy(source)
|
||||
result, report = module.admit(source, .74)
|
||||
self.assertEqual(source, before)
|
||||
self.assertEqual(result["features"], source["features"][1:])
|
||||
self.assertEqual(report["rejected"][0]["feature"], source["features"][0])
|
||||
|
||||
def test_missing_evidence_is_explicit_and_not_fabricated(self):
|
||||
f = feature("legacy", None, "straight_arrow")
|
||||
result, report = module.admit(dict(features=[f]), .74)
|
||||
self.assertEqual(result["features"], [f])
|
||||
self.assertEqual(report["unassessed"], [dict(id="legacy", reason="missing-template-fit")])
|
||||
|
||||
def test_unrelated_layers_and_other_score_domains_unchanged(self):
|
||||
features = [feature("line", .1, "linear_marking"), feature("zigzag", .2, "zigzag"),
|
||||
feature("road", .1, "bicycle", "road_boundary")]
|
||||
result, report = module.admit(dict(features=features), .74)
|
||||
self.assertEqual(result["features"], features)
|
||||
self.assertFalse(report["rejected"])
|
||||
|
||||
def test_identifiers_coordinates_and_order_cannot_select_a_location(self):
|
||||
fs = [feature("a", .71), feature("b", .89, "right_arrow")]
|
||||
for f in fs:
|
||||
f["id"] = "unseen-" + f["id"]
|
||||
for ring in f["geometry"]["coordinates"]:
|
||||
for p in ring:
|
||||
p[0] += 1_000_000
|
||||
p[1] -= 100_000
|
||||
result, report = module.admit(dict(features=fs[::-1], scene="unseen"), .74)
|
||||
self.assertEqual(result["features"], [fs[1]])
|
||||
self.assertEqual(report["rejected"][0]["feature"], fs[0])
|
||||
|
||||
def test_invalid_present_scores_are_not_admitted(self):
|
||||
fs = [feature(str(i), value) for i, value in enumerate([False, "0.9", -1, 2, float("nan")])]
|
||||
result, report = module.admit(dict(features=fs), .74)
|
||||
self.assertFalse(result["features"])
|
||||
self.assertTrue(all(r["reason"] == "invalid-template-fit" for r in report["rejected"]))
|
||||
|
||||
def test_policy_is_read_without_executing_it(self):
|
||||
self.assertEqual(module.existing_fit_floor("raise RuntimeError('must not execute')\nPOLICY=dict(fit_score=.74, other=True)"), .74)
|
||||
for source in ["POLICY=dict(fit_score=True)", "POLICY=dict(fit_score=bad())", "OTHER=1"]:
|
||||
with self.assertRaises((ValueError, KeyError)):
|
||||
module.existing_fit_floor(source)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Geometric ownership, missing evidence, and translation invariance of window checks."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
import shapely
|
||||
from shapely.affinity import translate
|
||||
from shapely.geometry import box, LineString
|
||||
|
||||
source = Path(os.environ.get('WINDOW_SOURCE', str(Path(__file__).resolve().parents[1] /
|
||||
'simulation/urban-plan-research/replay/linear_window_support.py')))
|
||||
spec = importlib.util.spec_from_file_location('linear_window_support', source)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
class WindowTests(unittest.TestCase):
|
||||
def test_curved_disjoint_cells_preserve_area_and_holes(self):
|
||||
p = LineString([(0, 0), (13, 2), (17, 7), (24, 10)]).buffer(.1)
|
||||
ps = list(m.cells(p))
|
||||
self.assertLess(shapely.union_all(ps).symmetric_difference(p).area, 1e-10)
|
||||
self.assertAlmostEqual(sum(x.area for x in ps), p.area)
|
||||
ring = box(0, 0, 12, 12).difference(box(3, 3, 9, 9))
|
||||
self.assertAlmostEqual(shapely.union_all(list(m.cells(ring))).area, ring.area)
|
||||
|
||||
def test_long_chain_gets_two_view_local_checks(self):
|
||||
p = box(0, 0, 70, .15)
|
||||
def sample(part):
|
||||
self.assertLessEqual(part.bounds[2]-part.bounds[0], 3.000001)
|
||||
return [dict(valid=1., support=.94)]*2, ['a', 'b']
|
||||
summary, rows = m.inspect(p, sample)
|
||||
self.assertAlmostEqual(summary['measured_fraction'], 1.)
|
||||
self.assertGreater(len(rows), 20)
|
||||
self.assertAlmostEqual(summary['area_fractions']['paint-supported'], 1.)
|
||||
|
||||
def test_missing_occluded_and_disagreeing_views_never_become_negative(self):
|
||||
for ev, expected in [([], 'missing-two-view-coverage'),
|
||||
([dict(valid=1., support=0.)], 'missing-two-view-coverage'),
|
||||
([dict(valid=.4, support=0.)]*2, 'occluded-or-outside-road'),
|
||||
([dict(valid=1., support=0.), dict(valid=1., support=.99)], 'mixed-paint'),
|
||||
([dict(valid=1., support=float('nan'))]*2, 'invalid-evidence')]:
|
||||
self.assertEqual(m.classify(ev, 20), expected)
|
||||
self.assertEqual(m.classify([dict(valid=1., support=0.)]*2, 0), 'unmeasured-footprint')
|
||||
self.assertEqual(m.classify([dict(valid=1., support=0.)]*2, 20), 'weak-paint')
|
||||
self.assertFalse(m.POLICY['automatic_removal'])
|
||||
|
||||
def test_translation_does_not_select_a_location(self):
|
||||
p = box(0, 0, 30, .15)
|
||||
read = lambda part: ([dict(valid=1., support=.9)]*2, ['a', 'b'])
|
||||
before, a = m.inspect(p, read)
|
||||
after, b = m.inspect(translate(p, 100000.31, -10000.7), read)
|
||||
self.assertEqual(len(a), len(b))
|
||||
self.assertAlmostEqual(before['measured_fraction'], after['measured_fraction'])
|
||||
self.assertEqual([r['status'] for r in a], [r['status'] for r in b])
|
||||
|
||||
def test_mixed_visibility_is_not_hidden_by_average(self):
|
||||
rows = [dict(status='paint-supported', area_m2=8), dict(status='weak-paint', area_m2=1),
|
||||
dict(status='missing-two-view-coverage', area_m2=1)]
|
||||
summary = m.summarize(rows, 10)
|
||||
self.assertAlmostEqual(summary['measured_fraction'], .9)
|
||||
self.assertAlmostEqual(summary['area_fractions']['weak-paint'], .1)
|
||||
with self.assertRaises(ValueError):
|
||||
m.summarize(rows, 9)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user