import importlib.util import sys from pathlib import Path import numpy as np import pytest SRC = Path(__file__).resolve().parents[1] / "simulation/semantic-learning" sys.path.insert(0, str(SRC)) spec = importlib.util.spec_from_file_location("spatial_probe", SRC / "spatial_decoder_probe.py") probe = importlib.util.module_from_spec(spec) spec.loader.exec_module(probe) sys.path.remove(str(SRC)) def test_loss_is_balanced_by_class_street_window_and_unknown_has_zero_weight(): records = [ dict(name="a1", group="a", split="train", target=np.array([[0, 1, 255], [0, 1, 255]])), dict(name="a2", group="a", split="train", target=np.array([[0, 255, 255], [0, 255, 255]])), dict(name="b", group="b", split="train", target=np.array([[1, 1, 1], [0, 0, 0]])), ] ww = probe.dense_weights(records) for label in (0, 1): assert sum(ww[r["name"]][r["target"] == label].sum() for r in records) == pytest.approx(0.5) for group in ["a", "b"]: assert sum( ww[r["name"]][r["target"] == label].sum() for r in records if r["group"] == group ) == pytest.approx(0.25) assert all(not np.any(ww[r["name"]][r["target"] == 255]) for r in records) with pytest.raises(ValueError, match="training"): probe.dense_weights([dict(records[0], split="regression")]) def rows(arm, errors): return [ dict( phase="development", arm=arm, held_out=str(i), completed=True, metrics=dict(recall=1 - e, fpr=e), ) for i, e in enumerate(errors) ] def test_selection_rejects_single_good_seed_and_control_rows(): rr = rows("old-linear", [0.1, 0.2, 0.3, 0.4]) + rows("new-linear", [0.1, 0.2, 0.3, 0.4]) for family in ["pointwise", "spatial"]: for seed in [20261023, 20261024, 20261025]: errors = ( [0.05, 0.1, 0.2, 0.3] if family == "spatial" and seed != 20261025 else [0.1, 0.2, 0.3, 0.5] ) rr += rows(f"{family}-{seed}", errors) assert probe.choose(rr)["selected_family"] == "old-linear" with pytest.raises(ValueError, match="Development"): probe.choose([dict(rr[0], phase="regression")] + rr[1:]) with pytest.raises(ValueError, match="Incomplete"): probe.choose(rr[:-1]) better = [ dict(r, metrics=dict(recall=0.95, fpr=0.05)) if r["arm"].startswith("spatial") else r for r in rr ] assert probe.choose(better)["selected_arms"] == [ "spatial-20261023", "spatial-20261024", "spatial-20261025", ]