Files
NODEDC_MISSION_CORE/tests/test_semantic_supervision_balance.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

123 lines
3.9 KiB
Python

import sys
from pathlib import Path
import numpy as np
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
from spatial_decoder_probe import dense_weights
from supervision_balance import assess_balance, release_balanced_weights
def record(name, group, old, target):
return dict(
name=name,
group=group,
split="train",
old_target=np.array(old, dtype="uint8"),
target=np.array(target, dtype="uint8"),
)
def test_cohort_mass_does_not_shrink_with_added_pixel_count():
for count in [1, 20, 1000]:
r = record(
"a", "one", [1, 0] + [255] * (2 * count + 1), [1, 0] + [1] * count + [0] * count + [255]
)
before = dense_weights([r])["a"]
after = release_balanced_weights([r])["a"]
assert after[0] == pytest.approx(0.25) and after[1] == pytest.approx(0.25)
assert after[-1] == 0 and after.sum() == pytest.approx(1)
for label in [0, 1]:
mask = r["target"] == label
assert after[mask].sum() == pytest.approx(before[mask].sum())
def test_preserve_class_street_window_mass_and_unchanged_windows():
records = [
record("a", "one", [1, 0, 255, 255], [1, 0, 1, 0]),
record("b", "one", [1, 0], [1, 0]),
record("c", "two", [0, 255], [0, 0]),
]
before = dense_weights(records)
after = release_balanced_weights(records)
for r in records:
for label in [0, 1]:
mask = r["target"] == label
assert after[r["name"]][mask].sum() == pytest.approx(before[r["name"]][mask].sum())
assert np.array_equal(before["b"], after["b"])
@pytest.mark.parametrize("error", ["control", "changed", "shape", "duplicate", "unknown"])
def test_reject_invalid_supervision(error):
r = record("a", "one", [1, 0, 255], [1, 0, 1])
records = [r]
if error == "control":
r["split"] = "regression"
elif error == "changed":
r["target"][0] = 0
elif error == "shape":
r["old_target"] = r["old_target"][:2]
elif error == "duplicate":
records.append(r)
else:
r["target"][2] = 2
with pytest.raises(ValueError):
release_balanced_weights(records)
def rows():
result = []
for g in "abcd":
arms = {"old-linear": 0.25, "new-linear": 0.20}
for s in [1, 2, 3]:
arms.update(
{
f"uniform-head-{s}": 0.16,
f"uniform-decoder-{s}": 0.14,
f"balanced-head-{s}": 0.12,
f"balanced-decoder-{s}": 0.10,
}
)
for a, fpr in arms.items():
result.append(
dict(
phase="development",
arm=a,
held_out=g,
fitted_groups=[x for x in "abcd" if x != g],
completed=True,
metrics=dict(recall=0.9, fpr=fpr),
)
)
return result
def test_no_seed_or_average_hides_lost_paint():
rr = rows()
assert assess_balance(rr, [1, 2, 3])["eligible_families"] == [
"balanced-head",
"balanced-decoder",
]
next(r for r in rr if r["arm"] == "balanced-decoder-2" and r["held_out"] == "a")["metrics"][
"recall"
] = 0.89
out = assess_balance(rr, [1, 2, 3])
assert "balanced-decoder" not in out["eligible_families"]
assert "balanced-decoder" not in out["paired_policy_pass"]
@pytest.mark.parametrize("error", ["control", "leak", "duplicate", "missing"])
def test_gate_rejects_unpaired_or_contaminated_rows(error):
rr = rows()
if error == "control":
rr[0]["phase"] = "regression"
elif error == "leak":
rr[0]["fitted_groups"].append(rr[0]["held_out"])
elif error == "duplicate":
rr.append(rr[0])
else:
rr.pop()
with pytest.raises(ValueError):
assess_balance(rr, [1, 2, 3])