diff --git a/regime.py b/regime.py index e515531..eefb8d9 100644 --- a/regime.py +++ b/regime.py @@ -43,13 +43,35 @@ def _context(kind: str, affect: Affect, regime: int, n_regimes: int) -> torch.Te raise ValueError(kind) +def _metrics(losses: list[float], switched: list[bool], arousals: list[float], window: int) -> dict: + # metrics on the second half only: the first half is training warm-up + steps = len(losses) + half = steps // 2 + switch_idx = [i for i in range(half, steps - window) if switched[i]] + recovery = [statistics.fmean(losses[i + k] for i in switch_idx) for k in range(window)] if switch_idx else [float("nan")] * window + steady_idx = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])] + steady = statistics.fmean(losses[i] for i in steady_idx) if steady_idx else float("nan") + return dict( + recovery=recovery, steady=steady, + # counts switches in the measured second half only, not the whole run + n_switches=len(switch_idx), + arousal_at_switch=statistics.fmean(arousals[i] for i in switch_idx) if switch_idx else float("nan"), + arousal_steady=statistics.fmean(arousals[i] for i in steady_idx) if steady_idx else float("nan"), + ) + + def run(name: str, seed: int, steps: int, window: int = 20, bptt: int = 20, lr: float = 1e-3, hidden: int = 32, kappa: float = 4.0) -> dict: spec = dict(CONDITIONS[name]) if spec["kappa"] == KAPPA_FLAG: spec["kappa"] = kappa - torch.manual_seed(seed) wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"]) + if window >= wcfg.t_min: + raise ValueError( + f"window={window} must be < t_min={wcfg.t_min}: a recovery window that reaches " + "the next switch blends two events into one curve" + ) + torch.manual_seed(seed) world = ParticleWorld(wcfg) ctx_dim = wcfg.n_regimes if spec["ctx"] == "regime" else 2 org = Organism(attr_dim=world.attr_dim, coord_dim=2, target_dim=2, context_dim=ctx_dim, @@ -76,18 +98,7 @@ def run(name: str, seed: int, steps: int, window: int = 20, bptt: int = 20, pending = [] memory = detach_memory(memory) - # metrics on the second half only: the first half is training warm-up - half = steps // 2 - switch_idx = [i for i in range(half, steps - window) if switched[i]] - recovery = [statistics.fmean(losses[i + k] for i in switch_idx) for k in range(window)] if switch_idx else [float("nan")] * window - steady_idx = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])] - steady = statistics.fmean(losses[i] for i in steady_idx) if steady_idx else float("nan") - return dict( - condition=name, seed=seed, steps=steps, - recovery=recovery, steady=steady, n_switches=len(switch_idx), - arousal_at_switch=statistics.fmean(arousals[i] for i in switch_idx) if switch_idx else float("nan"), - arousal_steady=statistics.fmean(arousals[i] for i in steady_idx) if steady_idx else float("nan"), - ) + return dict(condition=name, seed=seed, steps=steps, **_metrics(losses, switched, arousals, window)) def table(results: list[dict]) -> str: diff --git a/tests/test_regime.py b/tests/test_regime.py index 07d6e10..692779d 100644 --- a/tests/test_regime.py +++ b/tests/test_regime.py @@ -1,6 +1,8 @@ +import math + import pytest -from regime import CONDITIONS, run +from regime import CONDITIONS, _metrics, run @pytest.mark.parametrize("name", sorted(CONDITIONS)) @@ -16,3 +18,67 @@ def test_rp_only_has_no_memory_and_zero_kappa(): assert CONDITIONS["grp_k0"]["kappa"] == 0.0 assert CONDITIONS["grp_flag"]["kappa"] == 0.0 and CONDITIONS["grp_flag"]["oracle"] == "change" assert CONDITIONS["grp_regime"]["kappa"] == 0.0 and CONDITIONS["grp_regime"]["oracle"] == "regime" + + +def test_window_too_large_raises(): + with pytest.raises(ValueError): + run("grp_k0", seed=0, steps=100, window=100) + + +def test_metrics_recovery_is_mean_loss_k_steps_after_switch(): + # steps=20, half=10: a single switch at index 12 sits inside the measured + # second half. losses[i] = i, so recovery[k] = 12 + k exactly. + steps, window = 20, 3 + losses = [float(i) for i in range(steps)] + switched = [False] * steps + switched[12] = True + arousals = [i * 0.01 for i in range(steps)] + m = _metrics(losses, switched, arousals, window) + assert m["recovery"] == [12.0, 13.0, 14.0] + assert m["n_switches"] == 1 + assert m["arousal_at_switch"] == pytest.approx(0.12) + + +def test_metrics_ignores_switches_in_the_first_half(): + steps, window = 20, 3 + losses = [float(i) for i in range(steps)] + switched = [False] * steps + switched[12] = True + arousals = [i * 0.01 for i in range(steps)] + baseline = _metrics(losses, switched, arousals, window) + + # a first-half switch with wildly different loss/arousal must not move any metric: + # half=10 and window=3 mean the earliest measured lookback starts at 10-3=7, so + # index 3 never enters any window computation. + losses2 = list(losses); losses2[3] = 999999.0 + switched2 = list(switched); switched2[3] = True + arousals2 = list(arousals); arousals2[3] = 999.0 + perturbed = _metrics(losses2, switched2, arousals2, window) + assert perturbed == baseline + + +def test_metrics_steady_excludes_window_steps_after_a_switch(): + # steps=20, half=10, window=3: switch at 15 excludes i in [15, 15+window] = [15,18] + # from steady. If that exclusion didn't apply, the huge post-switch losses at + # 16-18 would pull steady far from 1.0. + steps, window = 20, 3 + losses = [1.0] * steps + for i in (15, 16, 17, 18): + losses[i] = 999.0 + switched = [False] * steps + switched[15] = True + arousals = [0.0] * steps + m = _metrics(losses, switched, arousals, window) + assert m["steady"] == pytest.approx(1.0) + + +def test_metrics_no_switch_in_range_gives_nan_recovery(): + steps, window = 20, 3 + losses = [1.0] * steps + switched = [False] * steps + arousals = [0.0] * steps + m = _metrics(losses, switched, arousals, window) + assert m["n_switches"] == 0 + assert all(math.isnan(x) for x in m["recovery"]) + assert math.isnan(m["arousal_at_switch"]) + assert m["steady"] == pytest.approx(1.0)