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 nested_calibration import calibrate_inner, nested_folds GROUPS = ["a", "b", "c", "d"] def rows(): out = [] for p in nested_folds(GROUPS): if p["outer"] != "a": continue out.append( dict( group=p["inner"], training_groups=p["training_groups"], initialization_groups=p["training_groups"], split="train", sample_ids=[p["inner"]], old=np.array([2.0, -1.0, -2.0, 99.0]), new=np.array([1.0, -2.0, -3.0, 100.0]), paint=np.array([True, False, False, False]), original_bg=np.array([False, True, False, False]), added_bg=np.array([False, False, True, False]), ) ) return out def test_nested_folds_no_leakage_and_reusable_fit_sets(): plans = nested_folds(GROUPS) assert len(plans) == 12 assert len({tuple(p["training_groups"]) for p in plans}) == 6 for p in plans: assert set(p["training_groups"]) == set(GROUPS) - {p["outer"], p["inner"]} def test_common_threshold_ties_and_unknown_excluded(): rs = rows() rs[0]["new"] = np.array([1.0, 1.0, -3.0, 100.0]) result = calibrate_inner(rs, "a", GROUPS) assert result["new"]["threshold"] is None assert result["new"]["counts"]["paint"] == 0 assert result["old"]["counts"]["paint"] == 3 def test_uniform_shift_changes_threshold_not_predictions(): rs = rows() for r in rs: r["new"] = r["old"] - 4 out = calibrate_inner(rs, "a", GROUPS) assert out["new"]["threshold"] == out["old"]["threshold"] - 4 assert out["new"]["counts"] == out["old"]["counts"] @pytest.mark.parametrize("field", ["training_groups", "initialization_groups"]) def test_excluded_street_in_fit_or_normalization_rejected(field): rs = rows() rs[0][field] = ["a", "c"] with pytest.raises(ValueError, match="exclude both"): calibrate_inner(rs, "a", GROUPS) @pytest.mark.parametrize("mutation", ["missing", "duplicate", "outer", "control", "duplicate_id"]) def test_bad_calibration_membership_rejected(mutation): rs = rows() if mutation == "missing": rs.pop() elif mutation == "duplicate": rs[1] = rs[0] elif mutation == "outer": rs[0]["group"] = "a" elif mutation == "control": rs[0]["split"] = "regression" else: rs[1]["sample_ids"] = rs[0]["sample_ids"] with pytest.raises(ValueError): calibrate_inner(rs, "a", GROUPS) def test_exact_threshold_matches_independent_bruteforce(): rng = np.random.default_rng(123) for _ in range(30): rs = rows() for r in rs: r["old"] = rng.integers(-4, 5, 4).astype(float) r["new"] = rng.integers(-4, 5, 4).astype(float) out = calibrate_inner(rs, "a", GROUPS) for origin in ["old", "new"]: candidates = sorted( {np.inf} | {float(v) for r in rs for v in r[origin][:3]}, reverse=True ) valid = [ t for t in candidates if all( int(np.count_nonzero((r[origin] >= t) & r[k])) <= int(np.count_nonzero((r["old"] >= 0) & r[k])) for r in rs for k in ["original_bg", "added_bg"] ) ] expected = valid[-1] assert out[origin]["threshold"] == (None if np.isinf(expected) else expected) def test_invalid_masks_rejected(): rs = rows() rs[0]["added_bg"] = rs[0]["paint"] with pytest.raises(ValueError): calibrate_inner(rs, "a", GROUPS)