Files
NODEDC_MISSION_CORE/simulation/semantic-learning/condition_inventory.py
T
DCCONSTRUCTIONS 25dc0a1b44 feat(semantics): add portable annotation, learning and review contracts
Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
2026-10-29 09:10:00 +03:00

173 lines
7.1 KiB
Python

"""TRAIN-only visual condition sidecars over immutable observed-paint targets.
Tags describe raw evidence quality, not annotation age or an inference rule.
Region masks only select already reviewed class-compatible pixels. Unreviewed
candidate windows remain unsupervised; no target is inferred from a tag.
"""
import hashlib
import math
import numpy as np
from PIL import Image, ImageDraw
SCHEMA = "missioncore.semantic-condition-review/v1"
TAGS = {
"paint_clear": 1,
"paint_weak_visible": 1,
"background_asphalt": 0,
"background_paving": 0,
"background_utility_cover": 0,
"background_curb": 0,
}
FAMILIES = {"line", "crossing", "symbol", "hatching", "surface"}
def raster(polygon, size):
"""Convex review polygon in the explicit 512-square review coordinate frame."""
if not isinstance(polygon, list) or not 3 <= len(polygon) <= 32:
raise ValueError("Bounded convex polygon required")
if any(
not isinstance(p, list)
or len(p) != 2
or any(type(v) not in (int, float) or not math.isfinite(v) or not 0 <= v <= 512 for v in p)
for p in polygon
):
raise ValueError("Invalid review coordinates")
# Convex, consistently wound polygons have no ambiguous self-intersections.
signs = []
for i, a in enumerate(polygon):
b, c = polygon[(i + 1) % len(polygon)], polygon[(i + 2) % len(polygon)]
cross = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
if cross:
signs.append(cross > 0)
area = sum(
a[0] * b[1] - b[0] * a[1] for a, b in zip(polygon, polygon[1:] + polygon[:1], strict=True)
)
if (
not signs
or len(set(signs)) != 1
or not area
or len(set(map(tuple, polygon))) != len(polygon)
):
raise ValueError("Degenerate or nonconvex review polygon")
# Also require every vertex to be on the same side of every edge: rejects stars.
for a, b in zip(polygon, polygon[1:] + polygon[:1], strict=True):
side = [(b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) for c in polygon]
if min(side) < 0 < max(side):
raise ValueError("Self-intersecting review polygon")
out = Image.new("1", tuple(size))
points = [(math.floor(x * size[0] / 512), math.floor(y * size[1] / 512)) for x, y in polygon]
ImageDraw.Draw(out).polygon(points, fill=1)
return np.asarray(out, dtype=bool)
def compile_record(sample, review, target):
if sample["split"] != "train" or review["name"] != sample["name"]:
raise ValueError("Conditions may only annotate the pinned TRAIN sample")
if target.dtype != np.uint8 or target.ndim != 2 or target.size > 4 * 1024**2:
raise ValueError("Bounded uint8 target required")
if list(target.shape[::-1]) != sample["size"] or not np.isin(target, [0, 1, 255]).all():
raise ValueError("Invalid target shape/classes")
expected = sample.get("target_sha256")
if sample["kind"] not in {"existing", "candidate"}:
raise ValueError("Unsupported sample kind")
if sample["kind"] == "existing" and (
not isinstance(expected, str)
or len(expected) != 64
or any(c not in "0123456789abcdef" for c in expected)
):
raise ValueError("Existing targets require an explicit SHA-256 pin")
actual = hashlib.sha256(target.tobytes()).hexdigest()
if expected is not None and actual != expected:
raise ValueError("Pinned target changed")
if sample["kind"] == "candidate" and (expected is not None or np.any(target != 255)):
raise ValueError("Unadmitted candidates cannot acquire targets from conditions")
if review["target_sha256"] != expected or review["input_sha256"] != sample["rgb_sha256"]:
raise ValueError("Review input/target identity mismatch")
regions = review["regions"]
if not isinstance(regions, list) or len(regions) > 64:
raise ValueError("Region budget exceeded")
occupied = np.zeros(target.shape, dtype=bool)
counts, masks, ids = [], {}, set()
for r in regions:
if not isinstance(r["id"], str) or not r["id"] or r["id"] in ids:
raise ValueError("Unique region identities required")
ids.add(r["id"])
if r["tag"] not in TAGS or r["family"] not in FAMILIES or not r.get("reason", "").strip():
raise ValueError("Explicit supported condition and review reason required")
if (r["family"] == "surface") != (TAGS[r["tag"]] == 0):
raise ValueError("Condition class/family mismatch")
roi = raster(r["polygon"], sample["size"])
mask = roi & (target == TAGS[r["tag"]])
if np.any(mask & occupied):
raise ValueError("Overlapping reviewed condition pixels")
occupied |= mask
masks[r["id"]] = mask
counts.append(
dict(
id=r["id"],
tag=r["tag"],
family=r["family"],
reviewed_pixels=int(mask.sum()),
region_pixels=int(roi.sum()),
unknown_region_pixels=int((roi & (target == 255)).sum()),
)
)
return dict(
name=sample["name"],
group=sample["group"],
kind=sample["kind"],
regions=counts,
untagged_paint=int(((target == 1) & ~occupied).sum()),
untagged_background=int(((target == 0) & ~occupied).sum()),
target_sha256=actual,
targets_changed=False,
), masks
def footprint(camera):
"""Axis-aligned top-view footprint in its source-local physical coordinate frame."""
if camera["projection"] != "ortho":
raise ValueError("Orthographic footprint required")
w, h = camera["size"]
if "view_matrix" not in camera:
eye, target = camera["eye"], camera["target"]
if eye[:2] != target[:2] or camera["up"] != [0, 1, 0] or eye[2] <= target[2]:
raise ValueError("Unsupported top camera")
half = camera["width_m"] / 2
return [
target[0] - half,
target[1] - half * h / w,
target[0] + half,
target[1] + half * h / w,
]
v, k = np.asarray(camera["view_matrix"], float), np.asarray(camera["intrinsics"], float)
if (
v.shape != (4, 4)
or k.shape != (3, 3)
or not np.isfinite(v).all()
or not np.isfinite(k).all()
):
raise ValueError("Invalid camera matrices")
if not np.allclose(v[:2, 2], 0) or not np.allclose([v[0, 1], v[1, 0], k[0, 1], k[1, 0]], 0):
raise ValueError("Only axis-aligned top cameras supported")
if min(k[0, 0], k[1, 1]) <= 0 or min(abs(v[0, 0]), abs(v[1, 1])) == 0:
raise ValueError("Degenerate camera")
xy = [
np.linalg.solve(v[:2, :2], (np.array([u, t]) - k[:2, 2]) / np.diag(k)[:2] - v[:2, 3])
for u, t in [(0, 0), (w, h)]
]
return [float(min(a)) for a in zip(*xy, strict=True)] + [
float(max(a)) for a in zip(*xy, strict=True)
]
def overlap_fraction(a, b):
intersection = max(0, min(a[2], b[2]) - max(a[0], b[0])) * max(
0, min(a[3], b[3]) - max(a[1], b[1])
)
if intersection < 1e-8:
return 0.0
return intersection / min((a[2] - a[0]) * (a[3] - a[1]), (b[2] - b[0]) * (b[3] - b[1]))