"""How much of a benchmark gap is noise?

Error bars for published LLM benchmark scores, following Miller (2024),
"Adding Error Bars to Evals", arXiv:2411.00640. Only public numbers are used:
the score each lab reports and the number of tasks in the benchmark.

Limits, on purpose:
- Labs do not publish per-question results, so the difference test is the
  unpaired one. A paired test (same questions for both models) gives a
  smaller error, so "not significant" here means "not significant with the
  data they chose to publish".
- Repeated runs per task (avg@3, 5 trials) shrink the per-task noise but
  not the question-sampling noise, which is what n below captures.

Run: python3 intervals.py
"""

from math import sqrt

Z95 = 1.96


def se(p: float, n: int) -> float:
    """Standard error of an accuracy p (0-1) measured on n binary tasks."""
    return sqrt(p * (1 - p) / n)


def gap(name: str, n: int, a: tuple[str, float], b: tuple[str, float]) -> None:
    (na, pa), (nb, pb) = a, b
    sa, sb = se(pa, n), se(pb, n)
    d = pa - pb
    sd = sqrt(sa**2 + sb**2)
    verdict = "distinguishable" if abs(d) > Z95 * sd else "not distinguishable from published aggregates"
    print(
        f"{name} (n={n}): {na} {pa:.1%} ±{Z95 * sa:.1%} vs {nb} {pb:.1%} ±{Z95 * sb:.1%}"
        f" | gap {d * 100:+.1f} pts, 95% CI ±{Z95 * sd * 100:.1f} -> {verdict}"
    )


def min_detectable(n: int, p: float = 0.5) -> float:
    """Smallest gap (in points) an unpaired 95% test can tell apart at accuracy p."""
    return Z95 * sqrt(2) * se(p, n) * 100


def elo_win(diff: float) -> float:
    """Expected win rate for a rating gap, as LMArena-style Elo defines it."""
    return 1 / (1 + 10 ** (-diff / 400))


def clustered_ci(pass1: float, pass2: float, tasks: int, trials: int) -> float:
    """95% half-width (0-1) when each task is run several times.

    Trials of the same task are not independent: a hard task fails all five.
    Assumes exactly `trials` runs per task. pass@2 gives E[(1-p)^2] over tasks, hence the between-task variance of the
    per-task success rate p, which is what generalises to unseen tasks
    (Miller 2024, clustered standard errors).
    """
    mean_p2 = (1 - pass2) - 1 + 2 * pass1  # E[p^2]
    between = mean_p2 - pass1**2
    within = pass1 - mean_p2  # E[p(1-p)]
    return Z95 * sqrt((between + within / trials) / tasks)


def tb4_table(path: str = "tb4-leaderboard.json") -> None:
    import json

    rows = json.load(open(path))["rows"]
    for r in sorted(rows, key=lambda r: -r["accuracy"])[:12]:
        p1, tasks = r["accuracy"] / 100, r["n_trials"] // 5
        ci = clustered_ci(p1, r["pass_at_2"], tasks, 5)
        print(
            f"{r['model']:>18} {r['effort'] or '-':>6} ({r['agent']}): {p1:.1%}"
            f" | site {r['display_accuracy'].split('±')[-1].strip(' %*')} pts"
            f" | clustered ±{ci * 100:.1f} pts | pass@5 {r['pass_at_5']:.1%}"
            f" | ${r['total_cost_usd']:,.0f}"
        )


if __name__ == "__main__":
    # Scores: official tables (OpenAI GPT-6 Astra page, Anthropic Opus 5.5 page).
    # Task counts: GPQA Diamond 198 (Rein et al. 2023); Terminal-Bench 4.0 66 and
    # FrontierCode v1.1 100 (Artificial Analysis methodology pages, 2026-10-31).
    gap("GPQA Diamond", 198, ("GPT-6 Astra", 0.960), ("GPT-5.6 Sol", 0.946))
    gap("GPQA Diamond", 198, ("GPT-6 Astra", 0.960), ("Opus 5", 0.937))
    gap("Terminal-Bench 4.0", 66, ("Opus 5.5", 0.664), ("GPT-6 Astra", 0.579))
    gap("FrontierCode v1.1 Main", 100, ("Opus 5.5", 0.544), ("GPT-6 Astra", 0.533))
    print()
    for n in (30, 66, 100, 198, 500, 2500):
        print(f"n={n:>5}: two models must differ by > {min_detectable(n):.1f} pts (at 50% accuracy)")
    print()
    for diff in (5, 20, 50, 138, 400):
        print(f"Elo gap {diff:>3}: the stronger model wins {elo_win(diff):.1%} of head-to-head votes")

    print()
    tb4_table()

    # Self-checks.
    assert abs(clustered_ci(0.5, 0.5, 100, 5) - Z95 * sqrt(0.25 / 100)) < 1e-12  # all-or-nothing tasks

    assert abs(se(0.5, 100) - 0.05) < 1e-12
    assert abs(elo_win(0) - 0.5) < 1e-12
    assert abs(elo_win(400) - 10 / 11) < 1e-12
