feat(semantics): version scene edits and refine paint geometry
This commit is contained in:
@@ -0,0 +1,187 @@
|
||||
import copy
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from shapely.geometry import mapping, shape
|
||||
from shapely.ops import unary_union
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
import paint_objects as po
|
||||
from paint_context import contextual_additions as admit
|
||||
|
||||
|
||||
def contextual_additions(*args, contrast_fn=None):
|
||||
return admit(
|
||||
*args,
|
||||
experimental_continuations=True,
|
||||
contrast_fn=contrast_fn or (lambda *_: {"contrast": 0.3, "source": "synthetic"}),
|
||||
)
|
||||
|
||||
|
||||
def strip(name, start, end, width=0.2, **extra):
|
||||
g = po.strip_geometry([start, end], width)
|
||||
return dict(
|
||||
id=name,
|
||||
kind="linear_marking",
|
||||
representation="strip",
|
||||
placement_status="placed",
|
||||
parameters=dict(centerline=[start, end], width_m=width),
|
||||
geometry=mapping(g),
|
||||
observation_geometry=mapping(g),
|
||||
observation_ids=[name],
|
||||
fit=dict(score=0.9),
|
||||
sources=["synthetic"],
|
||||
**extra,
|
||||
)
|
||||
|
||||
|
||||
def test_same_observed_line_extends_without_changing_seed():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
candidate = strip("candidate", (4, 0), (9, 0))
|
||||
before = copy.deepcopy(seed)
|
||||
added, log = contextual_additions([seed], [candidate])
|
||||
assert seed == before and len(added) == 1 and log[0]["accepted"]
|
||||
g = shape(added[0]["geometry"])
|
||||
assert g.bounds[0] > 5 and g.bounds[2] == 9
|
||||
assert added[0]["context_admission"]["method"] == "observed-continuation"
|
||||
|
||||
|
||||
def test_parallel_offset_and_real_gap_cannot_supply_continuation():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
for candidate in [strip("offset", (4, 0.4), (9, 0.4)), strip("gap", (5.2, 0), (9, 0))]:
|
||||
added, _ = contextual_additions([seed], [candidate])
|
||||
assert not added
|
||||
|
||||
|
||||
def test_added_candidates_never_seed_a_chain_and_order_is_stable():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
a = strip("a", (4, 0), (9, 0))
|
||||
b = strip("b", (8, 0), (13, 0))
|
||||
first, _ = contextual_additions([seed], [a, b])
|
||||
second, _ = contextual_additions([seed], [b, a])
|
||||
assert first == second and len(first) == 1
|
||||
assert shape(first[0]["geometry"]).bounds[2] == 9
|
||||
|
||||
|
||||
def test_actual_missing_crosswalk_bar_requires_independent_strict_bars():
|
||||
seeds = [strip(str(i), (i, 0), (i, 4), 0.45, group_id="strict-zebra") for i in [0, 1, 3, 4]]
|
||||
candidate = strip("missing", (2, 0), (2, 4), 0.45)
|
||||
added, _ = contextual_additions(seeds, [candidate])
|
||||
assert len(added) == 1
|
||||
assert added[0]["kind"] == "crosswalk_bar"
|
||||
assert not contextual_additions(seeds, [strip("spot", (2, 1), (2, 1.5), 0.45)])[0]
|
||||
duplicates = [strip(str(i), (0, 0), (0, 4), 0.45) for i in range(4)]
|
||||
assert not contextual_additions(duplicates, [candidate])[0]
|
||||
|
||||
|
||||
def test_connected_junction_needs_a_direct_frozen_anchor():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
a = strip("a", (4, 0), (9, 0), junction_components=["component"])
|
||||
b = strip("b", (8, 0), (8, 3), junction_components=["component"])
|
||||
added, _ = contextual_additions([seed], [a, b])
|
||||
assert len(added) == 2
|
||||
assert {o["context_admission"]["method"] for o in added} == {
|
||||
"observed-continuation",
|
||||
"anchored-junction",
|
||||
}
|
||||
assert not contextual_additions([], [a, b])[0]
|
||||
detached = strip("detached", (12, 0), (12, 3), junction_components=["component"])
|
||||
assert len(contextual_additions([seed], [a, detached])[0]) == 1
|
||||
|
||||
|
||||
def test_catalog_overlap_cannot_be_relabelled_a_strip():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
symbol = strip("symbol", (6, 0), (8, 0))
|
||||
symbol["representation"] = "catalog"
|
||||
added, log = contextual_additions([seed, symbol], [strip("candidate", (4, 0), (9, 0))])
|
||||
assert not added and log[0]["reason"] == "catalog-conflict"
|
||||
|
||||
|
||||
def test_no_new_geometry_outside_observed_candidate():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
candidate = strip("candidate", (4, 0), (9, 0))
|
||||
added, _ = contextual_additions([seed], [candidate])
|
||||
assert (
|
||||
unary_union([shape(o["geometry"]) for o in added])
|
||||
.difference(shape(candidate["geometry"]))
|
||||
.area
|
||||
< 1e-8
|
||||
)
|
||||
|
||||
|
||||
def test_old_well_supported_part_cannot_pay_for_bad_tail():
|
||||
from shapely.geometry import box
|
||||
|
||||
seed = strip("seed", (0, 0), (8, 0))
|
||||
candidate = strip("tail", (4, 0), (9, 0))
|
||||
support = unary_union([box(4, -0.1, 7, 0.1), box(7, -0.03, 8, 0.03), box(8, -0.02, 9, 0.02)])
|
||||
candidate["observation_geometry"] = mapping(support)
|
||||
assert not contextual_additions([seed], [candidate])[0]
|
||||
|
||||
|
||||
def test_novel_part_requires_own_rgb_and_clears_old_group_metadata():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
candidate = strip(
|
||||
"candidate",
|
||||
(4, 0),
|
||||
(9, 0),
|
||||
group_id="obsolete",
|
||||
observed_bar_count=99,
|
||||
crosswalk_parameters={"step_m": 17},
|
||||
)
|
||||
assert not contextual_additions([seed], [candidate], contrast_fn=lambda *_: {"contrast": 0})[0]
|
||||
result = contextual_additions([seed], [candidate])[0][0]
|
||||
assert all(k not in result for k in ["group_id", "observed_bar_count", "crosswalk_parameters"])
|
||||
|
||||
|
||||
def test_crosswalk_addition_uses_strict_group_not_proposal_group():
|
||||
seeds = [strip(str(i), (i, 0), (i, 4), 0.45, group_id="strict") for i in [0, 1, 3, 4]]
|
||||
candidate = strip("missing", (2, 0), (2, 4), 0.45, group_id="obsolete", observed_bar_count=99)
|
||||
result = contextual_additions(seeds, [candidate])[0][0]
|
||||
assert result["group_id"] == "strict" and "observed_bar_count" not in result
|
||||
seeds[0]["group_id"] = "ambiguous"
|
||||
assert not contextual_additions(seeds, [candidate])[0]
|
||||
|
||||
|
||||
def test_bilateral_rgb_rejects_bright_region_edge_and_accepts_paint():
|
||||
import numpy as np
|
||||
from paint_context import strip_contrast
|
||||
|
||||
params = dict(centerline=[[1, 2], [4, 2]], width_m=0.2)
|
||||
matrix = [0.01, 0, 0, 0.01, 0, 0]
|
||||
rgb = np.full((400, 600, 3), 60, dtype=np.uint8)
|
||||
rgb[190:210, 100:400] = 220
|
||||
evidence = strip_contrast(params, rgb, matrix)
|
||||
assert evidence["contrast"] > 0.5 and min(evidence["sample_counts"]) >= 4
|
||||
rgb[210:] = 250
|
||||
assert strip_contrast(params, rgb, matrix)["contrast"] < 0
|
||||
params["centerline"] = [[1, 0.15], [4, 0.15]]
|
||||
assert strip_contrast(params, rgb, matrix) is None
|
||||
|
||||
|
||||
def test_bilateral_rgb_is_rotation_invariant():
|
||||
import numpy as np
|
||||
from paint_context import strip_contrast
|
||||
|
||||
rgb = np.full((600, 600, 3), 60, dtype=np.uint8)
|
||||
yy, xx = np.mgrid[:600, :600]
|
||||
angle = 0.7
|
||||
u = np.array([np.cos(angle), np.sin(angle)])
|
||||
n = np.array([-u[1], u[0]])
|
||||
q = np.array([1, 1])
|
||||
end = q + 3 * u
|
||||
x = (xx + 0.5) * 0.01 - q[0]
|
||||
y = (yy + 0.5) * 0.01 - q[1]
|
||||
along = x * u[0] + y * u[1]
|
||||
across = x * n[0] + y * n[1]
|
||||
rgb[(along > 0) & (along < 3) & (np.abs(across) < 0.1)] = 220
|
||||
params = dict(centerline=[q.tolist(), end.tolist()], width_m=0.2)
|
||||
assert strip_contrast(params, rgb, [0.01, 0, 0, 0.01, 0, 0])["contrast"] > 0.5
|
||||
|
||||
|
||||
def test_shipping_default_never_extends_even_a_bright_supported_seed():
|
||||
seed = strip("seed", (0, 0), (5, 0))
|
||||
candidate = strip("candidate", (4, 0), (9, 0))
|
||||
additions, decisions = admit([seed], [candidate], contrast_fn=lambda *_: {"contrast": 0.9})
|
||||
assert not additions
|
||||
assert decisions[0]["reason"] == "unqualified-continuation-disabled"
|
||||
@@ -220,3 +220,86 @@ def test_height_callback_cannot_move_xy():
|
||||
assert [[p[:2] for p in ring] for ring in after["geometry"]["coordinates"]] == (
|
||||
before["geometry"]["coordinates"]
|
||||
)
|
||||
|
||||
|
||||
def test_partial_admission_preserves_deferred_and_valid_holes():
|
||||
labels = np.zeros((7, 14), dtype=np.uint8)
|
||||
labels[1:6, 1:6] = 1
|
||||
labels[3, 3] = 0
|
||||
labels[1:6, 9:13] = 1
|
||||
p = proposal(labels)
|
||||
before = copy.deepcopy(p)
|
||||
|
||||
def heights(xy):
|
||||
return np.where(xy[:, 0] > 8, np.nan, 2.)
|
||||
|
||||
with pytest.raises(ValueError, match="height"):
|
||||
geometry.editor_features(p, height_at=heights, height_source="synthetic-support")
|
||||
result = geometry.editor_components(p, height_at=heights, height_source="synthetic-support")
|
||||
assert p == before
|
||||
assert not result["complete"]
|
||||
assert len(result["features"]) == len(result["deferred"]) == 1
|
||||
admitted = result["features"][0]
|
||||
assert len(admitted["geometry"]["coordinates"]) == 2
|
||||
deferred = result["deferred"][0]
|
||||
assert "height" in deferred["reason"]
|
||||
original = {f["id"]: f for f in p["features"]}
|
||||
assert deferred["feature"] == original[deferred["feature"]["id"]]
|
||||
assert set(original) == {admitted["id"], deferred["feature"]["id"]}
|
||||
assert [[v[:2] for v in ring] for ring in admitted["geometry"]["coordinates"]] == (
|
||||
original[admitted["id"]]["geometry"]["coordinates"]
|
||||
)
|
||||
assert "subtype" not in admitted["properties"]
|
||||
assert result["proposal_sha256"] == p["proposal_sha256"]
|
||||
|
||||
|
||||
def test_partial_admission_does_not_hide_touching_hole():
|
||||
p = proposal([[1, 1, 1, 0, 1], [1, 0, 1, 0, 1], [1, 1, 0, 0, 1]])
|
||||
result = geometry.editor_components(
|
||||
p, height_at=lambda xy: np.ones(len(xy)), height_source="synthetic-plane"
|
||||
)
|
||||
assert len(result["features"]) == len(result["deferred"]) == 1
|
||||
assert shape(result["deferred"][0]["feature"]["geometry"]).area == 7
|
||||
assert shape(result["features"][0]["geometry"]).area == 3
|
||||
|
||||
|
||||
def test_partial_admission_keeps_atomic_integrity_and_batch_budget(monkeypatch):
|
||||
p = proposal([[1, 0, 1]])
|
||||
|
||||
def forbidden(xy):
|
||||
raise AssertionError("Must reject entire batch before callback")
|
||||
|
||||
changed = copy.deepcopy(p)
|
||||
changed["features"][0]["geometry"]["coordinates"][0][0][0] += 1
|
||||
with pytest.raises(ValueError, match="Changed"):
|
||||
geometry.editor_components(changed, height_at=forbidden, height_source="test")
|
||||
duplicate = copy.deepcopy(p)
|
||||
duplicate["features"][1]["id"] = duplicate["features"][0]["id"]
|
||||
duplicate.pop("proposal_sha256")
|
||||
duplicate["proposal_sha256"] = geometry.digest(duplicate)
|
||||
with pytest.raises(ValueError, match="identity"):
|
||||
geometry.editor_components(duplicate, height_at=forbidden, height_source="test")
|
||||
monkeypatch.setattr(geometry, "MAX_EDITOR_WORK", 20)
|
||||
with pytest.raises(ValueError, match="work budget"):
|
||||
geometry.editor_components(p, height_at=forbidden, height_source="test")
|
||||
|
||||
|
||||
def test_partial_all_valid_equals_strict_and_propagates_programming_error():
|
||||
p = proposal([[1, 0, 1]])
|
||||
result = geometry.editor_components(
|
||||
p, height_at=lambda xy: np.ones(len(xy)), height_source="test"
|
||||
)
|
||||
assert result["complete"] and result["deferred"] == []
|
||||
assert result["features"] == geometry.editor_features(
|
||||
p, height_at=lambda xy: np.ones(len(xy)), height_source="test"
|
||||
)
|
||||
|
||||
for error_type in (ValueError, RuntimeError):
|
||||
def broken(xy, error_type=error_type):
|
||||
raise error_type("Unexpected sampler implementation failure")
|
||||
|
||||
with pytest.raises(error_type, match="Unexpected"):
|
||||
geometry.editor_components(p, height_at=broken, height_source="test")
|
||||
|
||||
with pytest.raises(ValueError, match="invalid shape"):
|
||||
geometry.editor_components(p, height_at=lambda xy: 3., height_source="test")
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
"""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
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Raw observation projection must preserve holes, XY and explicit refusals."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from shapely.geometry import Polygon, box
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
||||
import paint_projection as pp # noqa: E402
|
||||
|
||||
|
||||
def test_zero_weight_neighbours_and_boundary_do_not_remove_observation():
|
||||
d = np.full((3, 3), 20.)
|
||||
alpha = np.ones_like(d)
|
||||
alpha[1, 1] = 0
|
||||
args = dict(depth=d, alpha=alpha, camera_eye_z=25., pixel_to_scene=[1, 0, 0, 1, 0, 0])
|
||||
placed = pp.bilinear_geometry(box(.5, .5, 2.5, 2.5), **args)
|
||||
assert all(q[2] == 5 for q in placed.exterior.coords)
|
||||
with pytest.raises(pp.HeightRefusal, match="missing-observed"):
|
||||
pp.bilinear_geometry(box(.6, .6, 2.4, 2.4), **args)
|
||||
|
||||
|
||||
def test_raw_interior_plane_preserves_exact_xy_and_hole_with_unreliable_edge():
|
||||
d = np.full((60, 60), 20.)
|
||||
alpha = np.ones_like(d)
|
||||
alpha[9:11, 9:11] = 0
|
||||
g = Polygon(box(1, 1, 4, 4).exterior.coords, [box(2, 2, 2.5, 2.5).exterior.coords])
|
||||
before = [list(r.coords) for r in [g.exterior, *g.interiors]]
|
||||
placed, info = pp.project_observation(
|
||||
g, depth=d, alpha=alpha, camera_eye_z=25., pixel_to_scene=[.1, 0, 0, .1, 0, 0],
|
||||
)
|
||||
assert info["method"] == "observed-interior-plane"
|
||||
assert info["samples"] >= 24 and info["residual_p95_m"] < 1e-10
|
||||
for old, ring in zip(before, [placed.exterior, *placed.interiors], strict=True):
|
||||
assert [q[:2] for q in ring.coords] == old
|
||||
assert np.allclose(np.asarray(ring.coords)[:, 2], 5)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["missing", "discontinuity"])
|
||||
def test_unreliable_raw_surface_remains_2d_without_invented_height(bad):
|
||||
d = np.full((60, 60), 20.)
|
||||
alpha = np.ones_like(d)
|
||||
if bad == "missing":
|
||||
alpha[:] = 0
|
||||
else:
|
||||
alpha[9:11, 9:11] = 0
|
||||
d[:, 25:] += 4
|
||||
placed, info = pp.project_observation(
|
||||
box(1, 1, 4, 4), depth=d, alpha=alpha,
|
||||
camera_eye_z=25., pixel_to_scene=[.1, 0, 0, .1, 0, 0],
|
||||
)
|
||||
assert placed is None and info["placement_status"] == "2d-only" and info["reason"]
|
||||
|
||||
|
||||
def test_invalid_projection_inputs_are_not_hidden_as_missing_support():
|
||||
with pytest.raises(ValueError, match="Invalid projection"):
|
||||
pp.project_observation(box(0, 0, 1, 1), depth=np.ones((2, 2)),
|
||||
alpha=np.ones((3, 3)), camera_eye_z=25,
|
||||
pixel_to_scene=[1, 0, 0, 1, 0, 0])
|
||||
@@ -160,3 +160,55 @@ def test_save_and_worker_receipt_run_outside_the_event_loop(tmp_path, monkeypatc
|
||||
response = client.post(path, json={})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["thread"] != event_loop
|
||||
|
||||
|
||||
def test_http_representation_selection_and_pinned_manual_branch(tmp_path):
|
||||
import uuid
|
||||
|
||||
world, model, maps, store, old_sha = make_setup(tmp_path)
|
||||
raw, auto = copy.deepcopy(model), copy.deepcopy(model)
|
||||
raw['semantic_stage'] = 'raw'
|
||||
auto['semantic_stage'] = 'algorithmic'
|
||||
published = maps.publish_pair(world, raw, auto)
|
||||
|
||||
def invoke(fn, *args):
|
||||
try:
|
||||
return fn(*args)
|
||||
except FileNotFoundError as exc:
|
||||
raise HTTPException(404) from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(build_semantic_edits_router(
|
||||
tmp_path, SimpleNamespace(get=lambda _: world, list=lambda: [world]), maps,
|
||||
invoke, lambda _: None,
|
||||
))
|
||||
path = '/worlds/fixture/semantic-edits'
|
||||
branch = str(uuid.uuid4())
|
||||
with TestClient(app) as client:
|
||||
versions = client.get('/worlds/fixture/semantic-versions').json()
|
||||
assert versions['manual'] == []
|
||||
assert versions['raw_sha256'] == published['raw_sha256']
|
||||
observed = client.get(path, params={'source': 'raw'}).json()
|
||||
assert observed['read_only'] and 'edited' not in observed
|
||||
assert observed['model'] == raw
|
||||
assert client.post(path, json={
|
||||
**change(published['raw_sha256']), 'branch_id': branch,
|
||||
}).status_code == 400
|
||||
assert client.get(path, params={'source': 'manual', 'branch_id': branch}).status_code == 404
|
||||
pinned = client.get(path, params={
|
||||
'source': 'algorithmic', 'model_sha256': old_sha,
|
||||
}).json()
|
||||
assert pinned['model'] == model
|
||||
saved = client.post(path, json={**change(old_sha), 'branch_id': branch})
|
||||
assert saved.status_code == 200, saved.text
|
||||
assert saved.json()['model_sha256'] == old_sha
|
||||
assert client.get(path, params={
|
||||
'source': 'manual', 'branch_id': branch,
|
||||
}).json()['revision'] == saved.json()['revision']
|
||||
assert client.get(path, params={'source': 'algorithmic'}).json()['model'] == auto
|
||||
assert len(client.get('/worlds/fixture/semantic-versions').json()['manual']) == 1
|
||||
assert not store._path(world).exists()
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Whole-scene publications never rebase human work or admit raw edits."""
|
||||
|
||||
import copy
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import pytest
|
||||
from test_semantic_edits import change, make_setup
|
||||
|
||||
from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits
|
||||
|
||||
|
||||
def pair(model):
|
||||
raw, automatic = copy.deepcopy(model), copy.deepcopy(model)
|
||||
raw["semantic_stage"] = "raw"
|
||||
automatic["semantic_stage"] = "algorithmic"
|
||||
return raw, automatic
|
||||
|
||||
|
||||
def test_publication_keeps_manual_base_export_and_legacy_receipt(tmp_path):
|
||||
world, model, maps, edits, sha = make_setup(tmp_path)
|
||||
legacy = edits.save(world, change(sha))
|
||||
before = edits.export(world, legacy["revision"])
|
||||
raw, automatic = pair(model)
|
||||
automatic["features"][0]["geometry"]["coordinates"][1][1] = -1
|
||||
published = maps.publish_pair(world, raw, automatic)
|
||||
assert maps.get(world) == automatic
|
||||
assert edits.get(world)["edited"] == legacy["edited"]
|
||||
assert edits.export(world, legacy["revision"]) == before
|
||||
assert edits.get(world, "raw")["model"] == raw
|
||||
assert edits.get(world, "algorithmic")["revision"] is None
|
||||
assert edits.versions(world)["manual"][0]["branch_id"] is None
|
||||
assert published["raw_sha256"] != published["sha256"]
|
||||
receipt = dict(
|
||||
state="received", package_sha256=before["sha256"], dataset_sha256=None, sample_count=0
|
||||
)
|
||||
assert edits.receipt(world, legacy["revision"], receipt) == receipt
|
||||
assert edits.export(world, legacy["revision"]) == before
|
||||
|
||||
|
||||
def test_new_branch_does_not_inherit_manual_and_pins_stale_display(tmp_path):
|
||||
world, model, maps, edits, sha = make_setup(tmp_path)
|
||||
legacy = edits.save(world, change(sha))
|
||||
raw, auto = pair(model)
|
||||
maps.publish_pair(world, raw, auto)
|
||||
branch = str(uuid.uuid4())
|
||||
body = {**change(sha), "branch_id": branch}
|
||||
saved = edits.save(world, body)
|
||||
assert saved["branch_id"] == branch
|
||||
assert saved["model_sha256"] == sha
|
||||
assert len(saved["history"]) == 1
|
||||
assert edits.get(world)["revision"] == legacy["revision"]
|
||||
assert edits.get(world, "manual", branch)["edited"] == saved["edited"]
|
||||
reopened = SemanticEdits(tmp_path, maps)
|
||||
assert reopened.save(world, body) == saved
|
||||
assert len(reopened.versions(world)["manual"]) == 2
|
||||
exported = reopened.export(world, saved["revision"])
|
||||
assert exported["package"]["revisions"][0]["branch_id"] == branch
|
||||
assert any(
|
||||
row.get("branch_id") == branch for row in edits.pending([{**world, "world_id": "world"}])
|
||||
)
|
||||
|
||||
|
||||
def test_raw_cannot_be_saved_or_used_as_a_draft_base(tmp_path):
|
||||
world, model, maps, edits, _ = make_setup(tmp_path)
|
||||
raw, auto = pair(model)
|
||||
pointer = maps.publish_pair(world, raw, auto)
|
||||
view = edits.get(world, "raw")
|
||||
assert view["read_only"] is True and "edited" not in view
|
||||
for branch in [None, str(uuid.uuid4())]:
|
||||
body = change(pointer["raw_sha256"])
|
||||
if branch:
|
||||
body["branch_id"] = branch
|
||||
with pytest.raises(ValueError, match="только для просмотра"):
|
||||
edits.save(world, body)
|
||||
assert not edits._path(world, branch).exists()
|
||||
with pytest.raises(ValueError, match="Raw"):
|
||||
maps.save(world, raw)
|
||||
assert maps.versions(world) == pointer
|
||||
|
||||
|
||||
def test_unknown_branch_and_corrupt_latest_do_not_fallback(tmp_path):
|
||||
world, _, maps, edits, sha = make_setup(tmp_path)
|
||||
branch = str(uuid.uuid4())
|
||||
with pytest.raises(FileNotFoundError):
|
||||
edits.get(world, "manual", branch)
|
||||
assert not edits._path(world, branch).exists()
|
||||
saved = edits.save(world, {**change(sha), "branch_id": branch})
|
||||
export = edits.export(world, saved["revision"])
|
||||
(maps.directory(world) / "latest.json").write_text("broken")
|
||||
assert edits.get(world, "manual", branch)["edited"] == saved["edited"]
|
||||
assert edits.export(world, saved["revision"]) == export
|
||||
assert edits.versions(world)["algorithmic_sha256"] is None
|
||||
(maps.directory(world) / f"{sha}.json").write_text("broken")
|
||||
with pytest.raises(ValueError):
|
||||
edits.get(world, "manual", branch)
|
||||
|
||||
|
||||
def test_pair_failure_preserves_pointer_and_ordinary_save_clears_raw(tmp_path, monkeypatch):
|
||||
world, model, maps, _, _ = make_setup(tmp_path)
|
||||
raw, auto = pair(model)
|
||||
previous = maps.versions(world)
|
||||
original = maps.store_immutable
|
||||
|
||||
def fail_second(world, document):
|
||||
if document.get("semantic_stage") == "algorithmic":
|
||||
raise OSError("interrupted")
|
||||
return original(world, document)
|
||||
|
||||
monkeypatch.setattr(maps, "store_immutable", fail_second)
|
||||
with pytest.raises(OSError):
|
||||
maps.publish_pair(world, raw, auto)
|
||||
assert maps.versions(world) == previous
|
||||
monkeypatch.setattr(maps, "store_immutable", original)
|
||||
maps.publish_pair(world, raw, auto)
|
||||
maps.save(world, model)
|
||||
assert "raw_sha256" not in maps.versions(world)
|
||||
|
||||
|
||||
def test_branch_concurrency_and_path_validation(tmp_path):
|
||||
world, _, _, edits, sha = make_setup(tmp_path)
|
||||
branch = str(uuid.uuid4())
|
||||
|
||||
def save(i):
|
||||
try:
|
||||
return edits.save(
|
||||
world, {**change(sha, request=f"parallel-branch-{i:04}"), "branch_id": branch}
|
||||
)
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
results = list(pool.map(save, range(2)))
|
||||
assert sum(result is not None for result in results) == 1
|
||||
for invalid in ["../../other", "", "legacy", 4]:
|
||||
with pytest.raises(ValueError):
|
||||
edits.get(world, "manual", invalid)
|
||||
|
||||
|
||||
def test_dense_raw_has_bounded_display_budget_and_does_not_expand_editable_maps(tmp_path):
|
||||
from k1link.simulation.ai_polygon.urban_maps import validate_map
|
||||
|
||||
world, model, _, _, _ = make_setup(tmp_path)
|
||||
raw, auto = pair(model)
|
||||
raw["coverage"]["cell_m"] = 60 / 4096
|
||||
raw["features"] = [{**model["features"][0], "id": f"raw-{i}"} for i in range(20001)]
|
||||
assert validate_map(raw, world) is raw
|
||||
auto["features"] = raw["features"]
|
||||
with pytest.raises(ValueError, match="feature count"):
|
||||
validate_map(auto, world)
|
||||
raw["features"] = raw["features"] * 3
|
||||
with pytest.raises(ValueError, match="feature count"):
|
||||
validate_map(raw, world)
|
||||
raw["features"] = [{**model["features"][0], "geometry": {
|
||||
"type": "LineString", "coordinates": [[0, 0, 1]] * 300001}}]
|
||||
assert validate_map(raw, world) is raw
|
||||
auto["features"] = raw["features"]
|
||||
with pytest.raises(ValueError, match="vertex limit"):
|
||||
validate_map(auto, world)
|
||||
raw["features"][0]["geometry"]["coordinates"] = [[0, 0, 1]] * 400001
|
||||
with pytest.raises(ValueError, match="vertex limit"):
|
||||
validate_map(raw, world)
|
||||
Reference in New Issue
Block a user