#!/usr/bin/env python3 """Paired comparison of per-item task results (T5): McNemar exact p + paired bootstrap 95 % CI. python3 stats.py --ref bf16/.jsonl --test armB/.jsonl [--json out.json] Each jsonl line: {"id": "", "correct": true|false}. Items are matched by id; an id present in only one file is an error (the arms must have answered the same items). Pass rule (THRESHOLDS T5): delta >= -2.0 pts OR the CI includes 0. """ import argparse, json, math, random ap = argparse.ArgumentParser() ap.add_argument("--ref", required=True); ap.add_argument("--test", required=True) ap.add_argument("--resamples", type=int, default=10000); ap.add_argument("--json") a = ap.parse_args() load = lambda p: {d["id"]: bool(d["correct"]) for d in map(json.loads, open(p)) if d} R, T = load(a.ref), load(a.test) assert R.keys() == T.keys(), f"item sets differ: {len(R.keys() ^ T.keys())} ids not shared" ids = sorted(R) n = len(ids) acc_r, acc_t = sum(R.values()) / n, sum(T.values()) / n b = sum(1 for i in ids if R[i] and not T[i]) # ref right, test wrong c = sum(1 for i in ids if T[i] and not R[i]) # test right, ref wrong # exact two-sided McNemar = binomial test on the discordant pairs m = b + c p = 1.0 if m == 0 else min(1.0, 2 * sum(math.comb(m, k) for k in range(0, min(b, c) + 1)) / 2 ** m) rng = random.Random(608) diffs = [int(T[i]) - int(R[i]) for i in ids] boots = sorted(sum(diffs[rng.randrange(n)] for _ in range(n)) / n for _ in range(a.resamples)) lo, hi = boots[int(0.025 * a.resamples)], boots[int(0.975 * a.resamples) - 1] delta = 100 * (acc_t - acc_r) res = {"n": n, "acc_ref": 100 * acc_r, "acc_test": 100 * acc_t, "delta_pts": delta, "ci95_pts": [100 * lo, 100 * hi], "ref_only_correct": b, "test_only_correct": c, "mcnemar_p": p, "T5_pass": bool(delta >= -2.0 or lo <= 0 <= hi)} print(json.dumps(res, indent=1)) if a.json: json.dump(res, open(a.json, "w"), indent=1)