Files
NODEDC_MISSION_CORE/simulation/semantic-learning/region_coverage.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

238 lines
9.9 KiB
Python

"""Complete reviewed ROI -> existing sparse paint/background/unknown contract.
The explicit background declaration is an annotation decision, not evidence
inferred from a missing polygon. Numeric coverage cannot establish visual truth.
"""
import hashlib
import math
from admission_store import Supervision, pixel_runs, pixel_target
from dataset_store import checksum, confined
def sha(data):
return hashlib.sha256(data).hexdigest()
def runs(data, size, view):
width, height = size
result = dict(view=view, paint=[], background=[], unknown=[])
names = {0: "background", 1: "paint", 255: "unknown"}
for y in range(height):
x = 0
while x < width:
value, start = data[y * width + x], x
while x < width and data[y * width + x] == value:
x += 1
result[names[value]].append([y, start, x])
return result
def roi_bounds(size, roi):
if len(size) != 2 or any(type(v) is not int or not 0 < v <= 2048 for v in size):
raise ValueError("Bounded integer image dimensions required")
if len(roi) != 4 or any(type(v) is not int for v in roi):
raise ValueError("Integer exclusive ROI required")
x0, y0, x1, y1 = roi
if not 0 <= x0 < x1 <= size[0] or not 0 <= y0 < y1 <= size[1]:
raise ValueError("ROI outside source view")
if (x1 - x0) * (y1 - y0) > 65536:
raise ValueError("Review at most 65536 native pixels per unit")
return x0, y0, x1, y1
def polygon_contains(points, x, y):
inside = False
for a, b in zip(points, points[1:] + points[:1], strict=True):
if (a[1] > y) != (b[1] > y) and x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0]:
inside = not inside
return inside
def raster_proposal(packet, proposal):
"""Rasterize source-view polygons at pixel centres; uncertain borders ignored."""
size, roi = packet["size"], packet["roi"]
x0, y0, x1, y1 = roi_bounds(size, roi)
if proposal.get("background_reviewed") is not True or not proposal.get("reason", "").strip():
raise ValueError("Explicit whole-ROI background review required")
margin = proposal["boundary_ignore_px"]
if type(margin) is not int or not 1 <= margin <= 4:
raise ValueError("Native-pixel uncertainty margin required")
shapes = proposal["paint_polygons"]
unknown = proposal["unknown_polygons"]
if not 1 <= len(shapes) <= 32 or len(unknown) > 32:
raise ValueError("Bounded visible-paint polygons required")
for points in shapes + unknown:
if not 3 <= len(points) <= 64 or any(
len(p) != 2
or any(type(v) not in (int, float) or not math.isfinite(v) for v in p)
or not x0 <= p[0] <= x1
or not y0 <= p[1] <= y1
for p in points
):
raise ValueError("Polygon outside pinned ROI")
if unknown and not proposal.get("unknown_reason", "").strip():
raise ValueError("Explain uncertain source regions")
width = size[0]
data = bytearray([255]) * (width * size[1])
for y in range(y0, y1):
for x in range(x0, x1):
data[y * width + x] = int(any(polygon_contains(p, x + 0.5, y + 0.5) for p in shapes))
output = data.copy()
explicit_unknown = bytearray(len(data))
for y in range(y0, y1):
for x in range(x0, x1):
i = y * width + x
ambiguous = any(polygon_contains(p, x + 0.5, y + 0.5) for p in unknown)
if ambiguous:
explicit_unknown[i] = 255
for yy in range(max(y0, y - margin), min(y1, y + margin + 1)):
if ambiguous:
break
ambiguous = any(
data[yy * width + xx] != data[i]
for xx in range(max(x0, x - margin), min(x1, x + margin + 1))
)
if ambiguous:
output[i] = 255
record = runs(output, size, packet["view"])
# Outside ROI is not part of the review, even though both use ignore=255.
record["unknown"] = [
[y, max(a, x0), min(b, x1)]
for y, a, b in record["unknown"]
if y0 <= y < y1 and max(a, x0) < min(b, x1)
]
# Keep explicit source uncertainty distinct from automatic edge margins.
record["source_unknown"] = runs(explicit_unknown, size, packet["view"])["unknown"]
return record
def merge(packet, record, original, protected=b""):
"""Require explicit complete ROI, preserve existing labels and protected unknown."""
size, roi = packet["size"], packet["roi"]
x0, y0, x1, y1 = roi_bounds(size, roi)
width, height = size
if (
len(original) != width * height
or set(original) - {0, 1, 255}
or sha(original) != packet["target_sha256"]
):
raise ValueError("Pinned labels changed")
if protected and (len(protected) != len(original) or set(protected) - {0, 1}):
raise ValueError("Aligned protected unknown required")
if protected and any(p and old != 255 for p, old in zip(protected, original, strict=True)):
raise ValueError("Protected mask must contain only unknown labels")
if packet.get("protected_sha256") != sha(protected):
raise ValueError("Protected unknown identity changed")
if record["view"] != packet["view"]:
raise ValueError("Source view mismatch")
checked = pixel_runs(record, size)
covered = set()
for spans in checked.values():
for y, a, b in spans:
if not y0 <= y < y1 or not x0 <= a < b <= x1:
raise ValueError("Labels outside reviewed ROI")
covered.update(range(y * width + a, y * width + b))
if len(covered) != (x1 - x0) * (y1 - y0):
raise ValueError("Incomplete ROI: missing pixels are not background")
candidate = pixel_target(dict(size=size, **record))
source_unknown = pixel_runs(
dict(paint=[], background=[], unknown=record.get("source_unknown", [])), size
)["unknown"]
for y, a, b in source_unknown:
if not y0 <= y < y1 or not x0 <= a < b <= x1:
raise ValueError("Source uncertainty outside reviewed ROI")
for i in range(y * width + a, y * width + b):
if candidate[i] != 255:
raise ValueError("Source uncertainty must be excluded from labels")
if original[i] != 255:
raise ValueError(
"Explicit source uncertainty conflicts with accepted labels; "
"review a separate baseline revision before publication"
)
output, counts = bytearray(original), {"paint": 0, "background": 0, "unknown": 0}
added = {"paint": 0, "background": 0}
for i in covered:
value, old = candidate[i], original[i]
if value != 255 and old != 255 and old != value:
raise ValueError("Proposal conflicts with accepted labels")
if protected and protected[i] and value != 255:
raise ValueError("Proposal fills protected unknown")
if value != 255:
output[i] = value
counts[{0: "background", 1: "paint", 255: "unknown"}[value]] += 1
if old == 255 and value != 255:
added[{0: "background", 1: "paint"}[value]] += 1
return bytes(output), dict(
roi_pixels=len(covered),
coverage=counts,
added=added,
original_sha256=sha(original),
merged_sha256=sha(output),
)
def validate_packet(store, unit):
"""Resolve TRAIN identity from immutable corpus, never trust declared split."""
p = unit["payload"]
if set(p) != {
"supervision",
"sample_id",
"view",
"size",
"roi",
"target_sha256",
"protected_sha256",
}:
raise ValueError("Pinned region packet required")
roi_bounds(p["size"], p["roi"])
pointer = p["supervision"]
with Supervision(store, pointer["path"], pointer["sha256"]) as reader:
reference = reader.corpus.reference(p["sample_id"])
if (
reference["split"] != "train"
or unit["split"] != reference["split"]
or unit["physical_group"] != reference["physical_group"]
):
raise ValueError("Unit disagrees with frozen physical split")
entry = next(
(
e
for b in reader.training_batches("observed_paint")
for e in b
if e["sample_id"] == p["sample_id"]
),
None,
)
if entry is None:
raise ValueError("Sample is not admitted TRAIN")
view = next(
v
for v in entry["inputs"]
if v["sample_id"] == p["sample_id"] and v["view"] == p["view"]
)
target = next(t for t in entry["targets"] if t["view"] == p["view"])
if target["size"] != p["size"] or sha(pixel_target(target)) != p["target_sha256"]:
raise ValueError("Packet target differs from immutable supervision")
# Explicitly excluded pixels are protected; unreviewed complement is not.
protected = bytearray(p["size"][0] * p["size"][1]) if target["unknown"] else b""
for y, a, b in target["unknown"]:
protected[y * p["size"][0] + a : y * p["size"][0] + b] = bytes([1]) * (b - a)
if sha(protected) != p["protected_sha256"]:
raise ValueError("Packet omits protected unknown")
required = {
str(confined(store, reference["dataset"]) / v["name"])
for v in (view["rgb"], view["cameras_member"])
}
required.add(str(reader.root / "supervision.json"))
required.add(str(reader.root / reader.manifest["records"][p["sample_id"]]["path"]))
provided = {str(confined(store, pin["path"])) for pin in unit["sources"]}
if not required.issubset(provided):
raise ValueError("Packet does not pin source camera, image and decision")
if (
checksum(confined(store, reference["dataset"]) / view["rgb"]["name"])
!= view["rgb"]["sha256"]
):
raise ValueError("Raw source changed")