Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
280 lines
11 KiB
Python
280 lines
11 KiB
Python
"""Bounded offline paint-evidence experiment. Never writes production maps.
|
|
|
|
Training: reviewed weak vector interiors. Evaluation: separately frozen sparse
|
|
positive strokes and verified non-paint polygons. This is not a full-map metric.
|
|
"""
|
|
|
|
import hashlib
|
|
import json
|
|
import time
|
|
from datetime import UTC, datetime
|
|
from pathlib import Path
|
|
|
|
import cv2
|
|
import numpy as np
|
|
from PIL import Image, ImageDraw
|
|
from scipy.optimize import minimize
|
|
from scipy.special import expit
|
|
|
|
|
|
def digest(path):
|
|
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
|
|
|
|
def polygon_mask(polygons, size=(512, 512)):
|
|
image = Image.new("L", size)
|
|
draw = ImageDraw.Draw(image)
|
|
for polygon in polygons:
|
|
draw.polygon([tuple(p) for p in polygon], fill=255)
|
|
return np.array(image) > 0
|
|
|
|
|
|
def probe_masks(record):
|
|
image = Image.new("L", (512, 512))
|
|
draw = ImageDraw.Draw(image)
|
|
for stroke in record["positive"]:
|
|
draw.line([tuple(p) for p in stroke], fill=255, width=2)
|
|
positive = np.array(image) > 0
|
|
negative = polygon_mask(record["negative"])
|
|
assert not (positive & negative).any(), "Conflicting review probes"
|
|
return positive, negative
|
|
|
|
|
|
def features(rgb):
|
|
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
|
|
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
|
|
g = gray.astype(np.float32) / 255
|
|
planes = [g, hsv[..., 1] / 255, (rgb[..., 0].astype(float) - rgb[..., 2]) / 255]
|
|
names = ["brightness", "saturation", "red_minus_blue"]
|
|
for size in [9, 25, 51]:
|
|
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size))
|
|
planes.append(cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, kernel) / 255)
|
|
names.append(f"bright_ridge_{size}px")
|
|
avg = cv2.boxFilter(g, -1, (size, size))
|
|
planes.append(g - avg)
|
|
names.append(f"local_contrast_{size}px")
|
|
avg = cv2.boxFilter(g, -1, (9, 9))
|
|
planes.append(np.sqrt(np.maximum(0, cv2.boxFilter(g * g, -1, (9, 9)) - avg * avg)))
|
|
names.append("local_std_9px")
|
|
# Exact pre-morphology predicate from marking_pass.line_reconstruction.extract.
|
|
ridge = cv2.morphologyEx(
|
|
gray, cv2.MORPH_TOPHAT, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (25, 25))
|
|
)
|
|
white = (hsv[..., 1] < 100) & (gray > 100)
|
|
yellow = (hsv[..., 0] > 12) & (hsv[..., 0] < 36) & (hsv[..., 1] > 50) & (gray > 100)
|
|
fixed = (ridge > 12) & (white | yellow)
|
|
return np.stack(planes, axis=-1).astype(np.float32), fixed, names
|
|
|
|
|
|
def spatial_rule(mask):
|
|
closed = cv2.morphologyEx(mask.astype("uint8"), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
|
|
count, labels, stats, _ = cv2.connectedComponentsWithStats(closed, 8)
|
|
eligible = np.zeros(count, bool)
|
|
eligible[1:] = stats[1:, cv2.CC_STAT_AREA] >= 12
|
|
return eligible[labels]
|
|
|
|
|
|
def counts(prediction, positive, negative):
|
|
return dict(
|
|
tp=int((prediction & positive).sum()),
|
|
fn=int((~prediction & positive).sum()),
|
|
fp=int((prediction & negative).sum()),
|
|
tn=int((~prediction & negative).sum()),
|
|
)
|
|
|
|
|
|
def aggregate(rows):
|
|
result = {key: sum(row[key] for row in rows) for key in ["tp", "fn", "fp", "tn"]}
|
|
result["recall"] = result["tp"] / max(1, result["tp"] + result["fn"])
|
|
result["false_positive_rate"] = result["fp"] / max(1, result["fp"] + result["tn"])
|
|
return result
|
|
|
|
|
|
def choose_threshold(rows, grid):
|
|
values = []
|
|
for threshold in grid:
|
|
c = aggregate([counts(p >= threshold, pos, neg) for p, pos, neg in rows])
|
|
values.append(dict(threshold=threshold, **c))
|
|
accepted = [v for v in values if v["false_positive_rate"] <= 0.01]
|
|
best = (
|
|
max(accepted, key=lambda v: (v["recall"], -v["false_positive_rate"]))
|
|
if accepted
|
|
else min(values, key=lambda v: (v["false_positive_rate"], -v["recall"]))
|
|
)
|
|
return best["threshold"], values
|
|
|
|
|
|
def main(root):
|
|
start = time.monotonic()
|
|
split = json.loads((root / "split.json").read_text())
|
|
review = json.loads((root / "review-frozen.json").read_text())
|
|
assert review["reviewed_before_fit"] and not review["human_approved"]
|
|
assert not (root / "result.json").exists(), "Immutable first result already exists"
|
|
method = review["method"]
|
|
rng = np.random.default_rng(method["seed"])
|
|
records = split["records"]
|
|
assert len({a["id"] for a in records}) == len(records)
|
|
for a in records:
|
|
assert digest(Path(a["path"]) / "top.png") == a["raw_sha256"]
|
|
# All Maroseyka train/validation/test windows are physically nonoverlapping.
|
|
local = [a for a in records if "center" in a]
|
|
for a in local:
|
|
for b in local:
|
|
if a["split"] != b["split"]:
|
|
assert abs(a["center"][0] - b["center"][0]) >= 28
|
|
data = {}
|
|
xx, yy, train_counts = [], [], []
|
|
for a in records:
|
|
rgb = np.array(Image.open(Path(a["path"]) / "top.png").convert("RGB").resize((512, 512)))
|
|
f, fixed, names = features(rgb)
|
|
data[a["id"]] = dict(rgb=rgb, f=f, fixed=fixed)
|
|
if a["split"] != "train":
|
|
continue
|
|
target = np.array(Image.open(root / "review" / (a["id"] + "-mask.png"))) > 0
|
|
roi = polygon_mask([a["roi"]])
|
|
positive = cv2.erode(target.astype("uint8"), np.ones((5, 5), np.uint8)) > 0
|
|
positive &= roi
|
|
excluded = cv2.dilate(target.astype("uint8"), np.ones((15, 15), np.uint8)) > 0
|
|
negative = (roi | polygon_mask(review["train_extra_negatives"][a["id"]])) & ~excluded
|
|
assert positive.any() and negative.any()
|
|
train_counts.append(
|
|
dict(id=a["id"], positive=int(positive.sum()), negative=int(negative.sum()))
|
|
)
|
|
for label, mask in [(1, positive), (0, negative)]:
|
|
indices = np.flatnonzero(mask)
|
|
indices = rng.choice(
|
|
indices,
|
|
min(len(indices), method["maximum_samples_per_class_per_window"]),
|
|
replace=False,
|
|
)
|
|
xx.append(f.reshape(-1, f.shape[-1])[indices])
|
|
yy.append(np.full(len(indices), label))
|
|
x = np.concatenate(xx).astype(float)
|
|
y = np.concatenate(yy)
|
|
mean, scale = x.mean(axis=0), np.maximum(x.std(axis=0), 1e-5)
|
|
design = np.column_stack([np.ones(len(x)), (x - mean) / scale])
|
|
weight = np.where(y == 1, 0.5 / max(1, sum(y == 1)), 0.5 / max(1, sum(y == 0)))
|
|
l2 = method["l2"]
|
|
|
|
def objective(w):
|
|
z = design @ w
|
|
loss = np.sum(weight * (np.logaddexp(0, z) - y * z)) + l2 * np.sum(w[1:] ** 2) / 2
|
|
grad = design.T @ (weight * (expit(z) - y))
|
|
grad[1:] += l2 * w[1:]
|
|
return loss, grad
|
|
|
|
fit_start = time.monotonic()
|
|
fit = minimize(
|
|
objective,
|
|
np.zeros(design.shape[1]),
|
|
jac=True,
|
|
method="L-BFGS-B",
|
|
options={"maxiter": method["maximum_iterations"]},
|
|
)
|
|
fit_seconds = time.monotonic() - fit_start
|
|
assert fit.success, str(fit.message)
|
|
validation = []
|
|
for a in records:
|
|
v = data[a["id"]]
|
|
v["probability"] = expit(fit.x[0] + ((v["f"] - mean) / scale) @ fit.x[1:])
|
|
if a["split"] == "validation":
|
|
pos, neg = probe_masks(review["records"][a["id"]])
|
|
validation.append((v["probability"], pos, neg))
|
|
threshold, curve = choose_threshold(validation, method["threshold_grid"])
|
|
model = dict(
|
|
kind="linear-logistic-regression",
|
|
names=names,
|
|
mean=mean.tolist(),
|
|
scale=scale.tolist(),
|
|
coefficients=fit.x.tolist(),
|
|
threshold=threshold,
|
|
seed=method["seed"],
|
|
split_sha256=digest(root / "split.json"),
|
|
review_sha256=digest(root / "review-frozen.json"),
|
|
samples=len(x),
|
|
positive_samples=int(y.sum()),
|
|
converged=bool(fit.success),
|
|
iterations=int(fit.nit),
|
|
fit_seconds=fit_seconds,
|
|
production_eligible=False,
|
|
)
|
|
# Publish immutable model before examining held-out metrics.
|
|
(root / "fitted-model.json").write_text(json.dumps(model, indent=2))
|
|
rows = []
|
|
for a in records:
|
|
if a["split"] == "train":
|
|
continue
|
|
v = data[a["id"]]
|
|
pos, neg = probe_masks(review["records"][a["id"]])
|
|
predictions = dict(
|
|
fixed=v["fixed"],
|
|
fixed_spatial=spatial_rule(v["fixed"]),
|
|
learned=v["probability"] >= threshold,
|
|
learned_spatial=spatial_rule(v["probability"] >= threshold),
|
|
)
|
|
row = dict(
|
|
id=a["id"],
|
|
split=a["split"],
|
|
variants={k: counts(p, pos, neg) for k, p in predictions.items()},
|
|
)
|
|
rows.append(row)
|
|
# Raw frame, fixed predicate, learned predicate, learned + local spatial rule.
|
|
sheet = Image.new("RGB", (2048, 550), "#171717")
|
|
draw = ImageDraw.Draw(sheet)
|
|
for j, key in enumerate(["raw", "fixed", "learned", "learned_spatial"]):
|
|
rgb = v["rgb"].copy()
|
|
if key != "raw":
|
|
pred = predictions[key]
|
|
rgb[pred] = (rgb[pred] * 0.35 + np.array([0, 255, 150]) * 0.65).astype("uint8")
|
|
sheet.paste(Image.fromarray(rgb), (j * 512, 38))
|
|
text = a["id"] + " | " + key
|
|
if key != "raw":
|
|
c = aggregate([row["variants"][key]])
|
|
text += f" R {c['recall']:.1%} FPR {c['false_positive_rate']:.1%}"
|
|
draw.text((j * 512 + 5, 10), text, fill="white")
|
|
sheet.save(root / (a["id"] + "-result.jpg"), quality=94)
|
|
metrics = {}
|
|
for split_name in ["validation", "test", "external"]:
|
|
metrics[split_name] = {
|
|
key: aggregate([row["variants"][key] for row in rows if row["split"] == split_name])
|
|
for key in rows[0]["variants"]
|
|
}
|
|
result = dict(
|
|
schema="missioncore.paint-evidence-result/v1",
|
|
utc=datetime.now(UTC).isoformat(),
|
|
started_monotonic=start,
|
|
elapsed_seconds=time.monotonic() - start,
|
|
model=model,
|
|
train_counts=train_counts,
|
|
threshold_validation=curve,
|
|
metrics=metrics,
|
|
windows=rows,
|
|
source_sha256=digest(Path(__file__)),
|
|
map_writes=False,
|
|
production_eligible=False,
|
|
limitations=[
|
|
"Sparse assistant-reviewed probes, not dense human-verified benchmark.",
|
|
"Fixed comparator is paint-evidence predicate only, not complete production pipeline.",
|
|
"Spatial filter is local image morphology, not GOST or topology reconstruction.",
|
|
"No object-class recognition, no boundary learning, no full-street completion.",
|
|
"Two external windows from historically seen scene; insufficient generalization proof.",
|
|
],
|
|
)
|
|
(root / "result.json").write_text(json.dumps(result, indent=2))
|
|
print(
|
|
json.dumps(
|
|
dict(
|
|
metrics=metrics,
|
|
threshold=threshold,
|
|
fit_seconds=fit_seconds,
|
|
samples=len(x),
|
|
seconds=result["elapsed_seconds"],
|
|
model_sha256=digest(root / "fitted-model.json"),
|
|
)
|
|
)
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main(Path("/experiment"))
|