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

346 lines
13 KiB
Python

"""Controlled label-coverage experiment. Offline; no production map writes."""
import json
import sys
from collections import Counter, defaultdict
from pathlib import Path
import numpy as np
from c4_admission_study import loaded
from grouped_selection_study import objective, select, transfer_gate
from object_assembly_study import measured
from object_proposal_study import labels, overlap, save_new, sha, timestamp
from paint_hypothesis_study import fit_classifier
from shapely.geometry import shape
from shapely.ops import unary_union
from visual_admission_study import check_inputs, evaluation, fit_head, predict, rank
def expanded_labels(candidates, reviewed):
result = labels(candidates, reviewed)
background = unary_union([shape(g) for g in reviewed.get("complete_background", [])])
for i, c in enumerate(candidates):
p = shape(c["geometry"])
if (
result[i] < 0
and not background.is_empty
and p.area > 0
and p.intersection(background).area / p.area >= 0.9
):
result[i] = 0
return result
def training_records(records, arm):
return [
r
for r in records
if r["split"] == "development" and (arm == "expanded" or "-coverage-" not in r["id"])
]
def fit(records, review, data, l2, expanded):
if not expanded:
return fit_head(records, review, data, "c4_512", l2)
x, y = [], []
for r in records:
ls = expanded_labels(r["variants"]["retained"], review[r["id"]])
x.append(data[r["id"]]["c4_512"][ls >= 0])
y.append(ls[ls >= 0])
xx, yy = np.concatenate(x), np.concatenate(y)
if min(np.sum(yy == 0), np.sum(yy == 1)) < 2:
raise ValueError("Insufficient reviewed classes")
model = fit_classifier(xx, yy, l2, 500)
model.update(positive=int(sum(yy == 1)), negative=int(sum(yy == 0)))
return model
def partial_gate(baseline, candidate):
found = {
o["id"]
for r in candidate["rows"]
for o in r["clipped_components"]["objects"]
if o["matched"]
}
return [
o["id"]
for r in baseline["rows"]
for o in r["clipped_components"]["objects"]
if o["matched"] and o["id"] not in found
]
def freeze(root):
protocol = dict(
**timestamp(),
session="coverage-admission-20261022",
hypothesis=(
"Does corrected and expanded raw-reviewed supervision improve unchanged "
"C4 candidate admission?"
),
scope=(
"Offline linear paint/background coverage. No map publication, topology "
"completion or full pipeline claim."
),
arms=["old104", "expanded"],
regularization=[0.01, 0.1, 1.0],
thresholds=[i / 20 for i in range(1, 20)],
development=(
"17 previous +12 new windows, same6 development streets; controls "
"excluded from every fit."
),
controls=(
"31 exposed regression +6 new raw-only windows >=18m from prior "
"same-street centers.2 control streets never fit."
),
annotations=(
"18 new windows inspected raw and overlay before fitting.54 full or "
"clipped objects.9 old negative region corrections; ambiguous scan "
"patches unknown.Original104 labels preserved for comparator.Explicit "
"background used only expanded training and both-arm evaluation."
),
representation=(
"Immutable installed Mask2FormerMapillary65; unchanged uniform C4 mean "
"of512 inside/ring descriptors. No backbone fine-tuning."
),
training=(
"Same balanced logistic500L-BFGS, training-fold normalization,6-fold "
"leave-street-out. No street IDs as features."
),
selection=(
"Zero reviewed OOF false positives; maximize worst street complete "
"matchable recall, macrofamily, found; lower median tied threshold; "
"regularization ties strongerL2. Exactly same selection in both arms."
),
acceptance=(
"Expanded must preserve every matched whole identity of old14 and old104 "
"C4 in BOTH cohorts; no extra reviewedFP on each street; strict gain in "
"each cohort; no lost clipped matched identity. Report failures without "
"tuning on controls."
),
limitations=(
"Single reviewer, sparse/unknown boundaries, few control streets; "
"geometric labels approximate, objects may duplicate proposals. New full "
"and clipped linear positives should cover>=3development streets; "
"otherwise coverage hypothesis is unqualified."
),
visual=(
"Inspect new18 annotations, all37 controls with acceptance overlays after "
"frozen evaluation. Keep2proofs."
),
resources=(
"Worker006 only, fixed installedimage, no network,3CPU8GiBGPU batch1,12GiBfree reserve."
),
retention=(
"Content-addressed verified textarchive, inventoried removal of "
"derivedmedia/arrays,2proofimages only; raw/models/acceptedmaps "
"preserved."
),
)
save_new(root / "protocol.json", protocol)
save_new(
root / "review-original.json",
json.loads(Path("/c4study/review-audit-corrected.json").read_text()),
)
save_new(root / "review-frozen.json", json.loads((root / "review-draft.json").read_text()))
names = [
"protocol.json",
"review-original.json",
"review-frozen.json",
"inputs.json",
"model-inventory.json",
]
names += [p.name for p in root.glob("*.py")]
names += [str(p.relative_to(root)) for p in (root / "data").iterdir()]
save_new(root / "input-hashes.json", {n: sha(root / n) for n in sorted(names)})
print("frozen", len(names))
def audit(root):
check_inputs(root)
records = json.loads((root / "candidates.json").read_text())["records"]
old = {a["id"]: a for a in json.loads(Path("/c4study/candidates.json").read_text())["records"]}
original = json.loads((root / "review-original.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
changes = []
counts = defaultdict(Counter)
families = defaultdict(lambda: defaultdict(Counter))
compared = 0
for r in records:
cs = r["variants"]["retained"]
rid = r["id"]
if rid in old:
assert cs == old[rid]["variants"]["retained"], rid
compared += 1
if r["split"] != "development":
continue
new = expanded_labels(cs, review[rid])
for c, y in zip(cs, new, strict=True):
counts["expanded"][str(y)] += 1
if y == 1:
targets = review[rid]["objects"]
match = max(
targets, key=lambda o: overlap(shape(o["geometry"]), shape(c["geometry"]))
)
families["expanded"][match["family"]][r["street"]] += 1
if rid in original:
ls = labels(cs, original[rid])
for c, a, b in zip(cs, ls, new, strict=True):
counts["old104"][str(a)] += 1
if a != b:
changes.append(dict(window=rid, candidate=c["id"], old=int(a), new=int(b)))
assert counts["old104"]["1"] == 36 and counts["old104"]["0"] == 68, counts
assert compared == 48, compared
result = dict(
**timestamp(),
labels=counts,
families=families,
changes=changes,
old_candidate_windows_bitexact=compared,
)
save_new(root / "label-audit.json", result)
print(json.dumps(result))
def train(root):
check_inputs(root)
records, review, data = loaded(root)
original = json.loads((root / "review-original.json").read_text())["records"]
protocol = json.loads((root / "protocol.json").read_text())
arms = {}
for arm in protocol["arms"]:
dev = training_records(records, arm)
rr = review if arm == "expanded" else original
assert not ({r["street"] for r in dev} & {"pokrovka", "sadovaya-karetnaya"})
ceiling = {r["id"]: measured(r["variants"]["retained"], rr[r["id"]]) for r in dev}
experiments = []
for l2 in protocol["regularization"]:
scores = {}
folds = {}
for street in sorted({r["street"] for r in dev}):
tr = [r for r in dev if r["street"] != street]
va = [r for r in dev if r["street"] == street]
model = fit(tr, rr, data, l2, arm == "expanded")
scores.update(predict(va, data, "c4_512", model))
folds[street] = dict(training_ids=[r["id"] for r in tr], model=model)
sweep = []
for threshold in protocol["thresholds"]:
result = evaluation(dev, rr, scores, threshold)
sweep.append(
dict(
threshold=threshold,
**result["summary"],
**objective(result["rows"], ceiling),
)
)
experiments.append(dict(l2=l2, selected=select(sweep), folds=folds, sweep=sweep))
feasible = [e for e in experiments if e["selected"] is not None]
best = max(feasible, key=lambda e: (*rank(e["selected"]), e["l2"])) if feasible else None
arms[arm] = dict(
selected=best["selected"] if best else None,
l2=best["l2"] if best else None,
model=fit(dev, rr, data, best["l2"], arm == "expanded") if best else None,
experiments=experiments,
)
print(
json.dumps(dict(arm=arm, l2=arms[arm]["l2"], selected=arms[arm]["selected"])),
flush=True,
)
save_new(
root / "models-frozen.json",
dict(
**timestamp(),
arms=arms,
hashes={
n: sha(root / n)
for n in [
"protocol.json",
"review-frozen.json",
"review-original.json",
"input-hashes.json",
"candidates.json",
"features.json",
"coverage_admission_study.py",
]
},
),
)
def evaluate(root):
check_inputs(root)
records, review, data = loaded(root)
frozen = json.loads((root / "models-frozen.json").read_text())
for n, h in frozen["hashes"].items():
assert sha(root / n) == h, n
ref = json.loads(Path("/objectstudy/models-frozen.json").read_text())["models"][
"shape_appearance"
]
prior = json.loads(Path("/c4study/models-frozen.json").read_text())["variants"]["c4_512"]
# Exact reproduction must precede interpretation of the new arm.
old = frozen["arms"]["old104"]
assert (
old["l2"] == prior["l2"] and old["selected"]["threshold"] == prior["selected"]["threshold"]
)
old_scores = predict(records, data, "c4_512", old["model"])
prior_scores = predict(records, data, "c4_512", prior["model"])
error = max(
[
abs(a - b)
for rid in old_scores
for a, b in zip(old_scores[rid], prior_scores[rid], strict=True)
],
default=0,
)
assert error < 1e-8, error
results = {}
gates = {}
for split in ["regression", "heldout"]:
subset = [r for r in records if r["split"] == split]
result = {}
result["old14"] = evaluation(
subset,
review,
predict(subset, data, "handcrafted14", ref["model"]),
ref["selected"]["threshold"],
)
for arm, info in frozen["arms"].items():
ps = (
predict(subset, data, "c4_512", info["model"])
if info["model"]
else {r["id"]: [0] * len(r["variants"]["retained"]) for r in subset}
)
result[arm] = evaluation(
subset, review, ps, info["selected"]["threshold"] if info["selected"] else 1
)
gates[split] = {}
for comparator in ["old14", "old104"]:
gate = transfer_gate(result[comparator], result["expanded"])
lost = partial_gate(result[comparator], result["expanded"])
gate.update(lost_clipped_objects=lost, passed=gate["passed"] and not lost)
gates[split][comparator] = gate
results[split] = result
out = dict(
**timestamp(),
results=results,
gates=gates,
passed=all(g["passed"] for split in gates.values() for g in split.values()),
old104_reproduction_max_score_error=error,
)
save_new(root / "results.json", out)
print(
json.dumps(
dict(
passed=out["passed"],
gates=gates,
summaries={
s: {a: v["summary"] for a, v in rr.items()} for s, rr in results.items()
},
)
)
)
if __name__ == "__main__":
globals()[sys.argv[1]](Path(sys.argv[2]) if len(sys.argv) > 2 else Path("/experiment"))