"""Product-level geometry, abstention and provenance regression checks.""" import copy import json import sys from pathlib import Path import numpy as np import pytest from shapely import affinity, intersects_xy from shapely.geometry import Polygon, box, shape from shapely.ops import unary_union ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "simulation/semantic-learning")) import paint_objects as po # noqa: E402 CATALOG = json.loads((ROOT / "src/k1link/simulation/ai_polygon/marking-templates.json").read_text()) MATRIX = [0.04, 0, 0, -0.04, 0, 10.24] def raster(g, matrix=MATRIX): yy, xx = np.indices((256, 256)) a, b, d, e, x, y = matrix return intersects_xy( g, a * (xx + 0.5) + b * (yy + 0.5) + x, d * (xx + 0.5) + e * (yy + 0.5) + y ).astype("uint8") def assemble(g, *, matrix=MATRIX, rgb=None): mask = raster(g, matrix) if rgb is None: rgb = np.repeat((30 + mask * 180)[:, :, None], 3, axis=2) return po.assemble(mask, rgb, pixel_to_scene=matrix, source_id="synthetic", catalog=CATALOG) def test_separate_dashes_stay_separate_and_are_rectangles(): g = unary_union([box(1, 4, 3, 4.16), box(3.5, 4, 5.5, 4.16)]) out = assemble(g) assert len(out["objects"]) == 2 for obj in out["objects"]: assert obj["representation"] == "strip" assert len(obj["parameters"]["centerline"]) == 2 assert len(shape(obj["geometry"]).exterior.coords) == 5 assert po.reconstruct(obj, CATALOG).equals(shape(obj["geometry"])) assert not unary_union([shape(o["geometry"]) for o in out["objects"]]).intersects( box(3.1, 4, 3.4, 4.16) ) def test_crosswalk_keeps_four_observed_bars_not_catalog_six(): out = assemble(unary_union([box(1 + i, 2, 1.48 + i, 6) for i in range(4)])) bars = out["objects"] assert len(bars) == 4 assert {o["kind"] for o in bars} == {"crosswalk_bar"} assert len({o["group_id"] for o in bars}) == 1 assert {o["observed_bar_count"] for o in bars} == {4} @pytest.mark.parametrize("angle", [0, .43, 1.67]) def test_small_paint_wear_becomes_rectangle_without_filling_real_large_void(angle): original = box(1, 2, 5, 2.5).difference(box(2, 2.18, 2.13, 2.30)) observed = affinity.translate(affinity.rotate(original, angle, use_radians=True), 47, -23) params = po.fit_strip(observed, po.Policy()) assert params is not None and len(params["centerline"]) == 2 fitted = po.strip_geometry(params["centerline"], params["width_m"]) assert len(fitted.exterior.coords) == 5 and not fitted.interiors assert po.agreement(observed, fitted, .06)["score"] > .95 assert len(observed.interiors) == 1 # raw observation was not rewritten large_void = box(1, 2, 5, 2.5).difference(box(1.8, 2.08, 4.2, 2.42)) assert po.fit_strip(large_void, po.Policy()) is None def test_worn_crosswalk_bars_are_grouped_without_imaginary_bars(): bars = [box(1+i, 2, 1.48+i, 6).difference(box(1.15+i, 3, 1.27+i, 3.16)) for i in range(4)] out = assemble(unary_union(bars)) assert len(out["objects"]) == 4 assert {o["kind"] for o in out["objects"]} == {"crosswalk_bar"} assert all(len(o["parameters"]["centerline"]) == 2 for o in out["objects"]) def test_actual_visible_a_catalog_and_uniform_scale(): template = next(t for t in CATALOG["templates"] if t["id"] == "letter_A_v3") g = po.catalog_geometry(template, [5, 5], 0.23, 1) out = assemble(g) assert len(out["objects"]) == 1 obj = out["objects"][0] assert obj["kind"] == "letter_A_v3" assert obj["representation"] == "catalog" assert len(shape(obj["geometry"]).interiors) == 1 assert set(obj["parameters"]) == {"center", "angle_radians", "scale", "template_id"} assert po.reconstruct(obj, CATALOG).equals(shape(obj["geometry"])) assert out["human_geometry_used"] is False and out["labels_used"] is False def test_unknown_shapes_and_uniform_background_have_no_fallback(): g = Polygon([(1, 1), (4, 1), (5, 4), (2, 5), (1, 1)]) out = assemble(g) assert not out["objects"] and out["rejected"] assert {r["status"] for r in out["rejected"]} == {"unresolved-not-background"} out = assemble(box(1, 3, 7, 3.2), rgb=np.full((256, 256, 3), 100, np.uint8)) assert not out["objects"] def test_translation_and_rotation_do_not_depend_on_scene_coordinates(): g = box(1, 4, 5, 4.2) one = assemble(g) theta = 0.7 c, s = np.cos(theta), np.sin(theta) shifted = affinity.translate( affinity.rotate(g, theta, origin=(0, 0), use_radians=True), 500, -200 ) a, b, d, e, x, y = MATRIX matrix = [ c * a - s * d, c * b - s * e, s * a + c * d, s * b + c * e, c * x - s * y + 500, s * x + c * y - 200, ] two = assemble(shifted, matrix=matrix) assert len(one["objects"]) == len(two["objects"]) == 1 restored = affinity.rotate( affinity.translate(shape(two["objects"][0]["geometry"]), -500, 200), -theta, origin=(0, 0), use_radians=True, ) assert restored.hausdorff_distance(shape(one["objects"][0]["geometry"])) < 1e-6 def test_surface_uses_interior_and_keeps_2d_when_unsupported(): obj = assemble(box(1, 4, 5, 4.2))["objects"][0] original = copy.deepcopy(obj) yy, xx = np.indices((256, 256)) X = (xx + 0.5) * 0.04 Y = 10.24 - (yy + 0.5) * 0.04 z = 2 + 0.03 * X - 0.01 * Y args = dict(depth=20 - z, camera_eye_z=20, pixel_to_scene=MATRIX, catalog=CATALOG) height, info = po.surface_plane(obj, alpha=np.ones_like(z), **args) assert height is not None and info["residual_p95_m"] < 1e-8 assert height(2, 4) == pytest.approx(2.02) height, info = po.surface_plane(obj, alpha=np.zeros_like(z), **args) assert height is None and info["reason"] == "insufficient-surface-support" assert obj == original def test_export_keeps_window_flags_and_source_parameters_after_editor_move(): from k1link.simulation.ai_polygon.semantic_edits import apply_operations obj = assemble(box(-1, 4, 5, 4.2))["objects"][0] assert "tile-edge" in obj["support_boundary"] features = po.editor_features( obj, catalog=CATALOG, height=lambda x, y: np.asarray(x) * 0 + 2, surface={"source": "synthetic-plane"}, height_source="a" * 64, observation_source="b" * 64, ) before = copy.deepcopy(features) doc = {"features": features, "source": {"gaussian_only": True}} changed = apply_operations( doc, [dict(kind="transform", feature_id=features[0]["id"], delta=[0.5, 0.25], angle=0)] ) after = changed["features"][0] assert after["geometry"] != before[0]["geometry"] assert ( after["properties"]["recognition_snapshot"] == before[0]["properties"]["recognition_snapshot"] ) assert ( after["properties"]["recognition_snapshot"]["role"] == "immutable-automatic-source-not-current-edited-geometry" ) assert after["properties"]["support_boundary"] == ["tile-edge"] assert after["properties"]["instance_completeness"] == "not-assessed" assert "primitive_parameters" not in after["properties"] assert "template_frame" not in after["properties"] def test_invalid_surface_evidence_propagates_instead_of_fake_height(): obj = assemble(box(1, 4, 5, 4.2))["objects"][0] with pytest.raises(ValueError, match="Invalid surface"): po.surface_plane( obj, depth=np.ones((10, 10)), alpha=np.ones((5, 5)), camera_eye_z=20, pixel_to_scene=MATRIX, catalog=CATALOG, ) @pytest.mark.parametrize("value", [255, 2, -1]) def test_annotation_or_unknown_is_not_an_automatic_input(value): with pytest.raises(ValueError, match="Binary automatic"): po.assemble( np.full((8, 8), value, dtype=int), np.zeros((8, 8, 3), np.uint8), pixel_to_scene=MATRIX, source_id="bad", catalog=CATALOG, ) @pytest.mark.parametrize("scale", [0.05, 0.12, 0.2, 0.5, 1.0, 2.0]) def test_distinctive_parts_do_not_invent_missing_head_even_below_tolerance(scale): template = next(t for t in CATALOG["templates"] if t["id"] == "straight_arrow") fitted = po.catalog_geometry(template, [5, 5], 0, scale) # A shaft extends the whole candidate length, but has no head or wings. observed = box(5 - 2.5 * scale, 5 - .075 * scale, 5 + 2.5 * scale, 5 + .075 * scale) mask = raster(observed) rgb = np.repeat((30 + mask * 180)[:, :, None], 3, axis=2) audit, reason = po.arbitrate_symbol( observed, fitted, po.Policy(), center=[5, 5], angle=0, rgb=rgb, pixel_to_scene=MATRIX, ) assert reason == "unsupported-template-part" assert min(p["unbuffered_precision"] for p in audit["parts"]) == 0 assert audit["local_support_buffer_m"] <= .06 assert audit["unbuffered_witness_required"] is True @pytest.mark.parametrize( "kind", ["straight_arrow", "right_arrow", "straight_left_arrow", "letter_A_v3"] ) @pytest.mark.parametrize("scale", [0.2, 0.5, 1.0, 2.0]) def test_true_symbol_parts_remain_supported(kind, scale): template = next(t for t in CATALOG["templates"] if t["id"] == kind) g = po.catalog_geometry(template, [5, 5], .37, scale) rgb = np.repeat((30 + raster(g) * 180)[:, :, None], 3, axis=2) audit, reason = po.arbitrate_symbol( g, g, po.Policy(), center=[5, 5], angle=.37, rgb=rgb, pixel_to_scene=MATRIX, ) assert reason is None assert min(p["precision"] for p in audit["parts"]) == pytest.approx(1) def test_missing_one_head_wing_cannot_be_paid_for_by_shaft(): template = next(t for t in CATALOG["templates"] if t["id"] == "straight_arrow") fitted = po.catalog_geometry(template, [5, 5], 0, 1) observed = fitted.difference(box(5.45, 5.075, 7.5, 5.4)) rgb = np.repeat((30 + raster(observed) * 180)[:, :, None], 3, axis=2) # The old whole-shape score is acceptable despite the absent distinctive wing. assert po.agreement(observed, fitted, .06)["score"] >= po.Policy().min_symbol_score _, reason = po.arbitrate_symbol( observed, fitted, po.Policy(), center=[5, 5], angle=0, rgb=rgb, pixel_to_scene=MATRIX, ) assert reason == "unsupported-template-part" def test_valid_strip_competes_on_the_same_observed_support(): observed = box(1, 4, 7, 4.2) rgb = np.repeat((30 + raster(observed) * 180)[:, :, None], 3, axis=2) audit, reason = po.arbitrate_symbol( observed, observed, po.Policy(), center=[4, 4.1], angle=0, rgb=rgb, pixel_to_scene=MATRIX, ) assert min(p["precision"] for p in audit["parts"]) == pytest.approx(1) assert audit["strip_competitor"]["score"] == pytest.approx(1) assert reason == "strip-competitor-not-beaten" def test_true_raster_arrow_survives_final_arbitration(): template = next(t for t in CATALOG["templates"] if t["id"] == "straight_arrow") out = assemble(po.catalog_geometry(template, [5, 5], .23, 1)) assert len(out["objects"]) == 1 obj = out["objects"][0] assert obj["kind"] == "straight_arrow" assert min(p["precision"] for p in obj["arbitration"]["parts"]) >= .65 def test_bent_strip_explanation_not_overruled_by_identical_symbol(): observed = po.strip_geometry([[1, 3], [3, 3.1], [5, 3.3]], .15) rgb = np.repeat((30 + raster(observed) * 180)[:, :, None], 3, axis=2) params = po.fit_strip(observed, po.Policy()) assert params is not None fitted = po.strip_geometry(params["centerline"], params["width_m"]) audit, reason = po.arbitrate_symbol( observed, fitted, po.Policy(), center=[3, 3.15], angle=0, rgb=rgb, pixel_to_scene=MATRIX, ) assert audit["strip_competitor"] is not None assert reason == "strip-competitor-not-beaten" def test_local_part_support_with_hole_is_world_rigid_transform_invariant(): template = next(t for t in CATALOG["templates"] if t["id"] == "letter_A_v3") g = po.catalog_geometry(template, [5, 5], .23, 1) observed = g.difference(box(4.2, 4.2, 4.3, 5.5)) rgb = np.repeat((30 + raster(observed) * 180)[:, :, None], 3, axis=2) one, reason_one = po.arbitrate_symbol( observed, g, po.Policy(), center=[5, 5], angle=.23, rgb=rgb, pixel_to_scene=MATRIX, ) theta = .61 c, s = np.cos(theta), np.sin(theta) def moved(q): return affinity.translate( affinity.rotate(q, theta, origin=(0, 0), use_radians=True), 800, -130 ) center = np.array([5,5]) @ np.array([[c,s],[-s,c]]) + [800,-130] a,b,d,e,x,y = MATRIX matrix = [c*a-s*d,c*b-s*e,s*a+c*d,s*b+c*e,c*x-s*y+800,s*x+c*y-130] two, reason_two = po.arbitrate_symbol( moved(observed), moved(g), po.Policy(), center=center, angle=.23+theta, rgb=rgb, pixel_to_scene=matrix, ) assert reason_two == reason_one assert [p["cell"] for p in one["parts"]] == [p["cell"] for p in two["parts"]] for a,b in zip(one["parts"], two["parts"], strict=True): assert b["precision"] == pytest.approx(a["precision"], abs=1e-8) assert b["unbuffered_precision"] == pytest.approx(a["unbuffered_precision"], abs=1e-8) @pytest.mark.parametrize("angle", [0, .71, 2.1]) def test_width_wear_does_not_reject_supported_straight_bar(angle): # Edge wear widens the percentile spread, while the whole observed stripe # still strongly supports one straight primitive. observed = box(1, 2, 5, 2.5).difference(box(2, 2.28, 3, 2.6)) observed = affinity.rotate(observed, angle, use_radians=True) params = po.fit_strip(observed, po.Policy()) assert params is not None assert len(params["centerline"]) == 2 g = po.strip_geometry(params["centerline"], params["width_m"]) assert po.agreement(observed, g, .06)["score"] >= .78 assert observed.hausdorff_distance(g) <= .25 def test_large_bend_is_not_straightened_into_unobserved_paint(): observed = po.strip_geometry([[1, 2], [3, 3], [5, 2]], .16) params = po.fit_strip(observed, po.Policy()) if params is not None: assert len(params["centerline"]) > 2 g = po.strip_geometry(params["centerline"], params["width_m"]) assert not g.intersects(box(2.9, 1.9, 3.1, 2.1)) def crosswalk_seed(x, identity): p = dict(centerline=[[x, 2], [x, 6]], width_m=.48) return dict(id=identity, representation="strip", kind="linear_marking", parameters=p, observation_ids=[identity], support_boundary=[]) def test_crosswalk_group_recovers_existing_bar_but_not_missing_slot_or_speck(): seeds = [crosswalk_seed(x, str(i)) for i, x in enumerate([1.2, 2.1, 3.9])] observed = box(2.76, 2, 3.24, 6).difference(box(2.76, 3.2, 2.84, 4.0)) feature = dict(id="weak", geometry=po.mapping(observed), properties={"support_boundary": []}) mask = raster(observed) rgb = np.repeat((30 + mask * 180)[:, :, None], 3, axis=2) args = dict(rgb=rgb, pixel_to_scene=MATRIX, policy=po.Policy()) out = po.recover_crosswalks(seeds, [feature], **args) assert len(out) == 1 and out[0]["observation_ids"] == ["weak"] assert set(out[0]["recovery"]["seed_ids"]) == {"0", "1", "2"} assert not po.recover_crosswalks(seeds, [], **args) speck = dict(feature, geometry=po.mapping(box(2.9, 3.5, 3.1, 3.7))) assert not po.recover_crosswalks(seeds, [speck], **args) assert not po.recover_crosswalks(seeds, [feature], **dict(args, rgb=np.full_like(rgb, 90))) po.group_crosswalks(seeds + out) assert {o["observed_bar_count"] for o in seeds + out} == {4} def test_crosswalk_duplicate_windows_are_not_independent_group_seeds(): seeds = [crosswalk_seed(1.2, str(i)) for i in range(3)] po.group_crosswalks(seeds) assert all("group_id" not in s for s in seeds) def test_crosswalk_group_is_order_independent_and_clears_stale_metadata(): seeds = [crosswalk_seed(x, str(i)) for i, x in enumerate([1.2, 2.1, 3.0, 3.9])] shuffled = list(reversed(copy.deepcopy(seeds))) po.group_crosswalks(seeds) po.group_crosswalks(shuffled) assert {s["id"]: s["group_id"] for s in seeds} == {s["id"]: s["group_id"] for s in shuffled} remaining = seeds[:2] po.group_crosswalks(remaining) assert all("group_id" not in s and s["kind"] == "linear_marking" for s in remaining) @pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize("holes", [False, True]) def test_group_never_merges_two_separate_candidates_in_one_slot(reverse, holes): seeds = [crosswalk_seed(x, str(i)) for i, x in enumerate([1.2, 2.1, 3.9])] for o in seeds: o["parameters"]["width_m"] = .30 geometries = [box(x-.11, 2, x+.11, 6).difference(box(x-.01,3,x+.01,3.25)) for x in [2.86, 3.14]] if not holes: geometries = [box(x-.11, 2, x+.11, 6) for x in [2.86, 3.14]] observations = [dict(id=str(i+10),geometry=po.mapping(g),properties={"support_boundary": []}) for i,g in enumerate(geometries)] if reverse: observations.reverse() mask=raster(unary_union(geometries)) rgb=np.repeat((30+mask*180)[:,:,None],3,axis=2) assert not po.recover_crosswalks(seeds,observations,rgb=rgb, pixel_to_scene=MATRIX,policy=po.Policy()) @pytest.mark.parametrize("angle", [0, .61, 1.47]) def test_observed_t_junction_is_two_strips_without_lost_arm(angle): g = box(1,2,7,2.2).union(box(4,2,4.3,6)) g = affinity.rotate(g,angle,use_radians=True) params=po.fit_junction_strips(g,po.Policy()) assert len(params)==2 rebuilt=unary_union([po.strip_geometry(p["centerline"],p["width_m"]) for p in params]) assert po.agreement(g,rebuilt,.06)["recall"]>=.90 assert g.hausdorff_distance(rebuilt)<=.25 def test_final_assembler_exports_each_junction_arm_with_same_observation(): out=assemble(box(1,2,7,2.2).union(box(4,2,4.3,6))) arms=[o for o in out["objects"] if o.get("decomposition")=="observed-orthogonal-junction"] assert len(arms)==2 assert arms[0]["observation_ids"]==arms[1]["observation_ids"] assert all(len(o["parameters"]["centerline"])==2 for o in arms) @pytest.mark.parametrize( "kind", ["letter_A_v3", "straight_arrow", "right_arrow", "straight_left_arrow"] ) def test_junction_decomposition_does_not_consume_symbol(kind): template=next(t for t in CATALOG["templates"] if t["id"]==kind) g=po.catalog_geometry(template,[5,5],.37,1) assert not po.fit_junction_strips(g,po.Policy()) @pytest.mark.parametrize("angle", [0, .61, 1.47]) def test_junction_preserves_true_open_gap_even_inside_connected_component(angle): frame = unary_union([box(1,2,7,2.2),box(1,5.8,7,6), box(1,2,1.2,6),box(6.8,2,7,6)]) gap=box(3.85,5.7,4.15,6.1) observed=affinity.rotate(frame.difference(gap),angle,use_radians=True) absent=affinity.rotate(box(3.90,5.81,4.10,5.99),angle,origin=(4,4),use_radians=True) # The default affine origin above equals frame centre, fixed explicitly for the gap. params=po.fit_junction_strips(observed,po.Policy()) rebuilt=unary_union([po.strip_geometry(p["centerline"],p["width_m"]) for p in params]) assert rebuilt.intersection(absent).area < 1e-8 def test_short_irregular_width_needs_group_support_not_just_rgb(): g=box(1,2,3.4,2.5).difference(box(1.4,2.25,3.0,2.6)) assert po.fit_strip(g,po.Policy()) is None @pytest.mark.parametrize("angle", [0,.61]) def test_junction_does_not_fill_elongated_internal_negative_space(angle): g=box(1,2,7,2.2).union(box(4,2,4.3,6)) hole=box(2.7,2.02,2.95,2.18) g=affinity.rotate(g.difference(hole),angle,origin=(0,0),use_radians=True) hole=affinity.rotate(hole,angle,origin=(0,0),use_radians=True) params=po.fit_junction_strips(g,po.Policy()) union=unary_union([po.strip_geometry(p["centerline"],p["width_m"]) for p in params]) assert union.intersection(hole).area<1e-8