Files
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

381 lines
14 KiB
Python

"""Frozen factorial diagnostic of photometry, label quality and road context.
Two explicit phases prevent holdout outcomes from selecting thresholds/models.
No production maps, inferred labels, street IDs or coordinates enter the fit.
"""
import argparse
import hashlib
import json
import time
from datetime import UTC, datetime
from pathlib import Path
import cv2
import numpy as np
from paint_evidence_probe import (
aggregate,
choose_threshold,
counts,
features,
polygon_mask,
probe_masks,
)
from PIL import Image, ImageDraw
from scipy.optimize import minimize
from scipy.special import expit
APPEARANCES = ("absolute", "augmented", "relative")
CONTEXTS = ("none", "semantic", "fused")
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def save_new(path, value):
with path.open("x") as stream:
json.dump(value, stream, indent=2)
def transformed(rgb, kind, value):
if kind == "identity":
return rgb.copy()
x = rgb.astype(np.float32) / 255
x = x * value if kind == "gain" else x**value
return np.rint(np.clip(x, 0, 1) * 255).astype(np.uint8)
def representation(rgb, kind):
f, fixed, names = features(rgb)
if kind != "relative":
return f, fixed, names
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32) / 255
saturation = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)[..., 1] / 255
chroma = (rgb[..., 0].astype(float) - rgb[..., 2]) / np.maximum(
rgb.astype(float).sum(axis=2), 1
)
planes = [saturation, chroma]
names = ["saturation", "normalized_red_blue"]
for index, size in enumerate([9, 25, 51]):
avg = cv2.boxFilter(gray, -1, (size, size))
planes.extend([f[..., 3 + index * 2] / (avg + 0.05), (gray - avg) / (avg + 0.05)])
names.extend([f"relative_ridge_{size}", f"relative_contrast_{size}"])
avg = cv2.boxFilter(gray, -1, (9, 9))
planes.append(f[..., -1] / (avg + 0.05))
names.append("relative_std_9")
return np.stack(planes, axis=-1).astype(np.float32), fixed, names
def fit_classifier(x, y, l2, maxiter):
mean, scale = x.mean(axis=0), np.maximum(x.std(axis=0), 1e-5)
design = np.c_[np.ones(len(x)), (x - mean) / scale]
weights = np.where(y == 1, 0.5 / sum(y == 1), 0.5 / sum(y == 0))
def objective(w):
z = design @ w
loss = np.sum(weights * (np.logaddexp(0, z) - y * z)) + l2 * np.sum(w[1:] ** 2) / 2
grad = design.T @ (weights * (expit(z) - y))
grad[1:] += l2 * w[1:]
return loss, grad
fit = minimize(
objective,
np.zeros(design.shape[1]),
jac=True,
method="L-BFGS-B",
options={"maxiter": maxiter},
)
if not fit.success:
raise RuntimeError(str(fit.message))
return dict(
mean=mean.tolist(),
scale=scale.tolist(),
coefficients=fit.x.tolist(),
iterations=int(fit.nit),
samples=len(y),
)
def probability(f, model):
w = np.array(model["coefficients"])
return expit(w[0] + ((f - np.array(model["mean"])) / np.array(model["scale"])) @ w[1:])
def context(root, record, mode):
if mode == "none":
return np.ones((512, 512), bool)
path = root / "data" / (record["id"] + "-context.npz")
if not path.exists():
return None
with np.load(path) as z:
if mode == "fused":
return z["fused"].astype(bool)
return (z["road"] > 0.35) & (z["road"] >= z["sidewalk"])
def load(root):
for name, digest in json.loads((root / "input-hashes.json").read_text()).items():
if sha(root / name) != digest:
raise ValueError(f"Changed input: {name}")
inputs = json.loads((root / "study-inputs.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())
prior = json.loads(Path("/prior/review-frozen.json").read_text())
protocol = json.loads((root / "protocol.json").read_text())
return inputs, review, prior, protocol
def rgb(root, record):
return np.array(Image.open(root / "data" / record["raw_file"]).convert("RGB"))
def choose_candidate(rows):
admissible = [a for a in rows if a["false_positive_rate"] <= 0.01]
if admissible:
return sorted(
admissible, key=lambda a: (-a["recall"], a["false_positive_rate"], a["variant"])
)[0]
return sorted(rows, key=lambda a: (a["false_positive_rate"], -a["recall"], a["variant"]))[0]
def train(root):
start = time.monotonic()
records, review, prior, protocol = load(root)
method = protocol["design"]
rng = np.random.default_rng(method["seed"])
sampling, audit = {}, []
for a in records:
if a["split"] != "train":
continue
pos, neg = probe_masks(review["train"][a["id"]])
weak = np.array(Image.open(root / "data" / (a["id"] + "-weak.png"))) > 0
weak = (cv2.erode(weak.astype("uint8"), np.ones((5, 5), np.uint8)) > 0) & polygon_mask(
[a["roi"]]
)
if (weak & neg).any():
raise ValueError("Weak positives conflict with certain negatives")
n = min(2500, int(weak.sum()), int(pos.sum()), int(neg.sum()))
if n < 50:
raise ValueError("Insufficient matched training samples")
sampling[a["id"]] = {
name: rng.choice(np.flatnonzero(mask), n, replace=False)
for name, mask in [("weak", weak), ("reviewed", pos), ("negative", neg)]
}
audit.append(
dict(
id=a["id"],
matched_per_class=n,
weak=int(weak.sum()),
reviewed=int(pos.sum()),
negative=int(neg.sum()),
reviewed_inside_weak=int((pos & weak).sum()),
)
)
models, validation = {}, []
for label in ["weak", "reviewed"]:
for appearance in APPEARANCES:
key = label + "-" + appearance
xx, yy = [], []
for a in records:
if a["split"] != "train":
continue
image = rgb(root, a)
transforms = (
method["augmentation"] if appearance == "augmented" else [["identity", 1]]
)
for kind, value in transforms:
f, _, names = representation(transformed(image, kind, value), appearance)
for target, indices in [
(1, sampling[a["id"]][label]),
(0, sampling[a["id"]]["negative"]),
]:
xx.append(f.reshape(-1, f.shape[-1])[indices])
yy.append(np.full(len(indices), target))
model = fit_classifier(
np.concatenate(xx).astype(float),
np.concatenate(yy),
method["l2"],
method["maxiter"],
)
model.update(appearance=appearance, labels=label, names=names)
rows = []
validation_records = [a for a in records if a["split"] == "validation"]
for a in validation_records:
f, _, _ = representation(rgb(root, a), appearance)
pos, neg = probe_masks(prior["records"][a["id"]])
rows.append((probability(f, model), pos, neg))
model["threshold"], model["validation_curve"] = choose_threshold(
rows, method["threshold_grid"]
)
models[key] = model
for mode in CONTEXTS:
values = [
counts((p >= model["threshold"]) & context(root, a, mode), pos, neg)
for a, (p, pos, neg) in zip(validation_records, rows, strict=True)
]
validation.append(dict(variant=key + "/" + mode, **aggregate(values)))
chosen = choose_candidate(validation)
artifact = dict(
schema="paint-hypothesis-models/v1",
utc=datetime.now(UTC).isoformat(),
monotonic=start,
seconds=time.monotonic() - start,
models=models,
validation=validation,
chosen=chosen,
sampling=audit,
source_sha256=sha(Path(__file__)),
inputs_sha256=sha(root / "input-hashes.json"),
review_sha256=sha(root / "review-frozen.json"),
protocol_sha256=sha(root / "protocol.json"),
production_eligible=False,
)
save_new(root / "models-frozen.json", artifact)
print(
json.dumps(
dict(chosen=chosen, validation=validation, sampling=audit, seconds=artifact["seconds"])
)
)
def evaluate(root):
start = time.monotonic()
records, review, prior, protocol = load(root)
artifact = json.loads((root / "models-frozen.json").read_text())
if artifact["source_sha256"] != sha(Path(__file__)):
raise ValueError("Source changed between fit and evaluation")
models = artifact["models"]
results, stress, gates = [], [], []
chosen_key, chosen_mode = artifact["chosen"]["variant"].split("/")
for a in records:
if a["split"] == "train":
continue
probes = (
review["holdout"][a["id"]] if a["split"] == "holdout" else prior["records"][a["id"]]
)
pos, neg = probe_masks(probes)
image = rgb(root, a)
f, fixed, _ = representation(image, "absolute")
relative, _, _ = representation(image, "relative")
group = a.get("street", a["split"])
masks = {mode: context(root, a, mode) for mode in CONTEXTS}
preds = {"fixed/none": fixed}
for mode in CONTEXTS[1:]:
if masks[mode] is not None:
preds["fixed/" + mode] = fixed & masks[mode]
gates.append(
dict(id=a["id"], group=group, mode=mode, **counts(masks[mode], pos, neg))
)
for key, model in models.items():
predicted = (
probability(relative if model["appearance"] == "relative" else f, model)
>= model["threshold"]
)
for mode in CONTEXTS:
if masks[mode] is not None:
preds[key + "/" + mode] = predicted & masks[mode]
results.append(
dict(
id=a["id"],
group=group,
positive=int(pos.sum()),
negative=int(neg.sum()),
variants={key: counts(value, pos, neg) for key, value in preds.items()},
)
)
# Controlled photometric counterfactuals use identical labels; never tune on them.
if a["split"] in ["test", "external"]:
for kind, value in protocol["design"]["stress"]:
transformed_rgb = transformed(image, kind, value)
fs = {k: representation(transformed_rgb, k)[0] for k in ["absolute", "relative"]}
stress.append(
dict(
id=a["id"],
group=group,
transform=[kind, value],
variants={
key: counts(
probability(
fs["relative" if m["appearance"] == "relative" else "absolute"],
m,
)
>= m["threshold"],
pos,
neg,
)
for key, m in models.items()
},
)
)
if a["id"] in ["sretenka-2", "sadovaya-triumfalnaya-3", "control-05", "tile-59--2"]:
keys = ["raw", "weak-absolute/none", chosen_key + "/none"]
if masks.get(chosen_mode) is not None and chosen_mode != "none":
keys.append(chosen_key + "/" + chosen_mode)
elif masks["fused"] is not None:
keys.append(chosen_key + "/fused")
sheet = Image.new("RGB", (512 * len(keys), 552), "#171717")
draw = ImageDraw.Draw(sheet)
for j, key in enumerate(keys):
im = image.copy()
caption = key
if key != "raw":
pred = preds[key]
im[pred] = (im[pred] * 0.35 + np.array([0, 255, 145]) * 0.65).astype("uint8")
m = aggregate([counts(pred, pos, neg)])
caption += f" R={m['recall']:.1%} FP={m['false_positive_rate']:.1%}"
sheet.paste(Image.fromarray(im), (512 * j, 40))
draw.text((512 * j + 5, 5), a["id"], fill="white")
draw.text((512 * j + 5, 20), caption, fill="white")
sheet.save(root / (a["id"] + "-study.jpg"), quality=95)
metrics = {}
for group in sorted({r["group"] for r in results}):
rows = [r for r in results if r["group"] == group]
keys = set.intersection(*(set(r["variants"]) for r in rows))
metrics[group] = {
key: aggregate([r["variants"][key] for r in rows]) for key in sorted(keys)
}
candidate = {
group: variants.get(artifact["chosen"]["variant"]) for group, variants in metrics.items()
}
qualified = all(
candidate.get(group)
and candidate[group]["recall"] >= 0.95
and candidate[group]["false_positive_rate"] <= 0.02
for group in ["sretenka", "sadovaya-triumfalnaya"]
)
save_new(
root / "evaluation.json",
dict(
utc=datetime.now(UTC).isoformat(),
monotonic=start,
seconds=time.monotonic() - start,
models_sha256=sha(root / "models-frozen.json"),
rows=results,
stress=stress,
gate_rows=gates,
metrics=metrics,
candidate=candidate,
qualifies_sparse_gate=qualified,
production_eligible=False,
),
)
print(
json.dumps(
dict(
candidate=artifact["chosen"]["variant"],
metrics=metrics,
qualifies_sparse_gate=qualified,
seconds=time.monotonic() - start,
)
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("phase", choices=["train", "evaluate"])
parser.add_argument("--root", type=Path, default=Path("/experiment"))
args = parser.parse_args()
cv2.setNumThreads(1)
(train if args.phase == "train" else evaluate)(args.root)