306 lines
13 KiB
Python
306 lines
13 KiB
Python
"""Exact observed paint survives a supported editor path; lossy cases fail closed."""
|
|
import copy
|
|
import importlib
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits, apply_operations
|
|
from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore
|
|
|
|
np = pytest.importorskip("numpy")
|
|
pytest.importorskip("shapely", minversion="2.0")
|
|
from shapely import affinity # noqa: E402
|
|
from shapely.geometry import Polygon, box, shape # noqa: E402
|
|
from shapely.ops import unary_union # noqa: E402
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
|
geometry = importlib.import_module("paint_geometry")
|
|
gate = importlib.import_module("geometry_contract_gate")
|
|
|
|
IDENTITY = [1, 0, 0, 1, 0, 0]
|
|
|
|
|
|
def proposal(labels, matrix=IDENTITY):
|
|
return geometry.vectorize(labels, pixel_to_scene=matrix, source_id="synthetic-test-only")
|
|
|
|
|
|
def lifted(p):
|
|
return geometry.editor_features(
|
|
p, height_at=lambda xy: 2 + .01 * xy[:, 0], height_source="synthetic-known-plane"
|
|
)
|
|
|
|
|
|
def test_all_512_three_by_three_masks_are_exact():
|
|
# Exhaustive small topology oracle, independent of run polygonization.
|
|
for bits in range(512):
|
|
labels = np.array([(bits >> k) & 1 for k in range(9)], dtype=np.uint8).reshape(3, 3)
|
|
p = proposal(labels)
|
|
union = unary_union([shape(f["geometry"]) for f in p["features"]])
|
|
assert union.area == np.count_nonzero(labels)
|
|
assert np.array_equal(gate.rasterize(p["features"], labels.shape, IDENTITY), labels == 1)
|
|
|
|
|
|
@pytest.mark.parametrize("matrix", [IDENTITY, [.2, .03, .04, -.3, 123.25, -72.125]])
|
|
def test_unknown_holes_gap_and_affine_pixel_edges(matrix):
|
|
labels = np.zeros((9, 13), np.uint8)
|
|
labels[1:8, 1:5] = 1
|
|
labels[3, 2] = 255
|
|
labels[4, 3] = 0
|
|
labels[1:8, 6:12] = 1
|
|
p = proposal(labels, matrix)
|
|
assert len(p["features"]) == 2
|
|
polys = [shape(f["geometry"]) for f in p["features"]]
|
|
assert sum(len(poly.interiors) for poly in polys) == 2
|
|
det = abs(matrix[0] * matrix[3] - matrix[1] * matrix[2])
|
|
assert sum(poly.area for poly in polys) == pytest.approx(np.count_nonzero(labels == 1) * det)
|
|
assert np.array_equal(gate.rasterize(p["features"], labels.shape, matrix), labels == 1)
|
|
single = shape(proposal([[1]], matrix)["features"][0]["geometry"])
|
|
assert single.equals(affinity.affine_transform(box(0, 0, 1, 1), matrix))
|
|
assert p == proposal(labels.copy(), matrix)
|
|
assert p["source_sha256"] != proposal(labels, [1, 0, 0, 1, 1, 0])["source_sha256"]
|
|
|
|
|
|
def test_empty_unknown_diagonal_and_edge_connectivity():
|
|
for value in [0, 255]:
|
|
p = proposal(np.full((3, 3), value, dtype=np.uint8))
|
|
assert p["features"] == []
|
|
assert lifted(p) == []
|
|
assert len(proposal([[1, 0], [0, 1]])["features"]) == 2
|
|
assert len(proposal([[1, 1], [0, 1]])["features"]) == 1
|
|
|
|
|
|
def test_support_flags_never_claim_complete_instances():
|
|
labels = np.zeros((6, 12), np.uint8)
|
|
labels[2:4, :3] = 1
|
|
labels[2:4, 7:9] = 1
|
|
labels[:, 9:] = 255
|
|
p = proposal(labels)
|
|
assert sorted(f["properties"]["support_boundary"] for f in p["features"]) == [
|
|
["tile-edge"], ["unknown-support"]
|
|
]
|
|
assert all(f["properties"]["instance_completeness"] == "not-assessed" for f in p["features"])
|
|
|
|
|
|
def test_point_touching_hole_preserved_but_editor_refuses():
|
|
p = proposal([[1, 1, 1], [1, 0, 1], [1, 1, 0]])
|
|
assert sum(shape(f["geometry"]).area for f in p["features"]) == 7
|
|
assert np.array_equal(gate.rasterize(p["features"], (3, 3), IDENTITY),
|
|
np.array([[1, 1, 1], [1, 0, 1], [1, 1, 0]], bool))
|
|
with pytest.raises(ValueError, match="пересекаются|самопересечение"):
|
|
lifted(p)
|
|
|
|
|
|
@pytest.mark.parametrize("labels,matrix", [
|
|
([[2]], IDENTITY), ([[1.0]], IDENTITY), ([[1]], [0, 0, 0, 0, 0, 0]),
|
|
([[1]], [1, 0, 0, 1, float("nan"), 0]), ([], IDENTITY),
|
|
])
|
|
def test_invalid_input_refused(labels, matrix):
|
|
with pytest.raises(ValueError):
|
|
proposal(labels, matrix)
|
|
|
|
|
|
def test_complexity_bound_and_unsupported_height_fail_closed(monkeypatch):
|
|
monkeypatch.setattr(geometry, "MAX_RUNS", 2)
|
|
with pytest.raises(ValueError, match="budget"):
|
|
proposal([[1, 0, 1, 0, 1]])
|
|
p = proposal([[1]])
|
|
with pytest.raises(ValueError, match="height"):
|
|
geometry.editor_features(p, height_at=lambda xy: np.full(len(xy), np.nan),
|
|
height_source="missing")
|
|
changed = copy.deepcopy(p)
|
|
changed["features"][0]["geometry"]["coordinates"][0][0][0] += 1
|
|
with pytest.raises(ValueError, match="Changed"):
|
|
lifted(changed)
|
|
|
|
|
|
def synthetic_document(features):
|
|
# This envelope exists ONLY in pytest's deleted temporary store. It exercises
|
|
# the v3 API requirement; it is not an actual qualified Gaussian derivation.
|
|
return dict(
|
|
schema_version="missioncore.urban-map/v3", type="FeatureCollection",
|
|
coordinate_system=dict(frame="scene-local", units="metres", up="Z", georeferenced=False),
|
|
source=dict(world_sha256="a" * 64, collider_sha256=None, gaussian_only=True,
|
|
artifact_sha256="c" * 64, synthetic_fixture=True),
|
|
coverage=dict(cell_m=.1, accepted_cells=0), features=features,
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("name", list(gate.fixtures()))
|
|
def test_actual_map_store_edit_store_restart_keep_components_and_holes(tmp_path, name):
|
|
labels = gate.fixtures()[name]
|
|
p = proposal(labels, [.1, 0, 0, -.1, 10, 20])
|
|
original = copy.deepcopy(p)
|
|
features = lifted(p)
|
|
assert p == original
|
|
assert all("subtype" not in f["properties"] and "semantic_element_id" not in f["properties"]
|
|
for f in features)
|
|
document = synthetic_document(features)
|
|
world = dict(sha256="a" * 64)
|
|
maps = UrbanMapStore(tmp_path)
|
|
receipt = maps.save(world, document)
|
|
assert maps.get(world) == document
|
|
chosen = features[0]
|
|
delta = [.5, -.25]
|
|
operation = dict(kind="transform", feature_id=chosen["id"], delta=delta, angle=0)
|
|
edits = SemanticEdits(tmp_path, maps)
|
|
saved = edits.save(world, dict(expected_revision=None, model_sha256=receipt["sha256"],
|
|
request_id="synthetic-geometry-0001", operations=[operation]))
|
|
assert saved["edited"]["schema_version"] == "missioncore.urban-edit/v1"
|
|
assert SemanticEdits(tmp_path, maps).get(world) == saved
|
|
assert not saved["learning"]["dataset_ready"]
|
|
assert maps.get(world) == document
|
|
for before, after in zip(features, saved["edited"]["features"], strict=True):
|
|
if before["id"] == chosen["id"]:
|
|
assert shape(after["geometry"]).equals(
|
|
affinity.translate(shape(before["geometry"]), *delta))
|
|
assert len(after["geometry"]["coordinates"]) == len(before["geometry"]["coordinates"])
|
|
else:
|
|
assert before == after
|
|
# Don't disguise arbitrary components as linear markings to claim vertex editing.
|
|
with pytest.raises(ValueError, match="вершины"):
|
|
apply_operations(document, [dict(kind="move", feature_id=chosen["id"], path=0, index=0,
|
|
position=[0, 0, 2])])
|
|
assert json.loads(json.dumps(p)) == p
|
|
|
|
|
|
def test_native_summary_representations_are_not_invertible():
|
|
# Information-content counterexamples, NOT execution of the upstream VMA model.
|
|
dashes_a = unary_union([box(0, 0, 2, 1), box(4, 0, 6, 1), box(8, 0, 12, 1)])
|
|
dashes_b = unary_union([box(0, 0, 3, 1), box(5, 0, 7, 1), box(9, 0, 12, 1)])
|
|
zebra_a = unary_union([box(x, 0, x + 1, 8) for x in [0, 3, 6, 9]])
|
|
zebra_b = unary_union([box(x, 0, x + 2, 8) for x in [0, 4, 8]])
|
|
for a, b in [(dashes_a, dashes_b), (zebra_a, zebra_b)]:
|
|
assert not a.equals(b)
|
|
assert a.envelope.equals(b.envelope)
|
|
holed = Polygon([(0, 0), (6, 0), (3, 8)], [[(2, 2), (4, 2), (3, 5)]])
|
|
solid = Polygon(holed.exterior)
|
|
assert holed.exterior.equals(solid.exterior)
|
|
assert not holed.equals(solid)
|
|
|
|
|
|
def test_editor_preflight_bounds_holes_before_callbacks(monkeypatch):
|
|
from k1link.simulation.ai_polygon import semantic_edits
|
|
|
|
labels = np.ones((40, 40), dtype=np.uint8)
|
|
labels[2:-1:3, 2:-1:3] = 0
|
|
p = proposal(labels)
|
|
|
|
def forbidden(*args):
|
|
raise AssertionError("Expensive validation or sampling ran before budget check")
|
|
|
|
monkeypatch.setattr(semantic_edits, "validate_path", forbidden)
|
|
monkeypatch.setattr(semantic_edits, "validate_holes", forbidden)
|
|
with pytest.raises(ValueError, match="budget"):
|
|
geometry.editor_features(p, height_at=forbidden, height_source="test")
|
|
|
|
|
|
def test_editor_work_bound_applies_to_whole_batch_before_sampling(monkeypatch):
|
|
p = proposal([[1, 0, 1]])
|
|
monkeypatch.setattr(geometry, "MAX_EDITOR_WORK", 20)
|
|
|
|
def forbidden(*args):
|
|
raise AssertionError("Height callback ran for partial batch")
|
|
|
|
with pytest.raises(ValueError, match="work budget"):
|
|
geometry.editor_features(p, height_at=forbidden, height_source="test")
|
|
|
|
|
|
def test_height_callback_cannot_move_xy():
|
|
p = proposal([[1, 1]])
|
|
|
|
def mutating_sampler(xy):
|
|
xy += 100
|
|
return np.full(len(xy), 3.)
|
|
|
|
features = geometry.editor_features(p, height_at=mutating_sampler, height_source="test")
|
|
for before, after in zip(p["features"], features, strict=True):
|
|
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")
|