#!/usr/bin/env python3 from __future__ import annotations import argparse import json import math import random from pathlib import Path from typing import Any Z_95 = 1.959963984540054 def read_jsonl(path: Path) -> list[dict[str, Any]]: records: list[dict[str, Any]] = [] with path.open("r", encoding="utf-8", errors="replace") as handle: for line_no, line in enumerate(handle, 1): line = line.strip() if not line: continue try: records.append(json.loads(line)) except json.JSONDecodeError as exc: raise SystemExit(f"Failed to parse {path}:{line_no}: {exc}") from exc return records def normalize_answer(value: Any) -> str: return str(value or "").strip().upper() def record_key(record: dict[str, Any], key_field: str | None) -> str: if key_field: return str(record.get(key_field) or "").strip() for field in ("task_id", "id", "question"): value = str(record.get(field) or "").strip() if value: return value return "" def is_correct(record: dict[str, Any]) -> bool: return normalize_answer(record.get("answer")) == normalize_answer(record.get("agent_answer")) def load_labeled(path: Path, key_field: str | None = None) -> dict[str, bool]: labeled: dict[str, bool] = {} duplicate_keys: set[str] = set() for index, record in enumerate(read_jsonl(path), 1): key = record_key(record, key_field) if not key: key = f"row:{index}" if key in labeled: duplicate_keys.add(key) labeled[key] = is_correct(record) if duplicate_keys: print(f"warning: {path} has {len(duplicate_keys)} duplicate keys; kept the last occurrence") return labeled def mean(values: list[float]) -> float: return sum(values) / len(values) if values else 0.0 def percentile(sorted_values: list[float], q: float) -> float: if not sorted_values: return 0.0 if len(sorted_values) == 1: return sorted_values[0] position = q * (len(sorted_values) - 1) lower = math.floor(position) upper = math.ceil(position) if lower == upper: return sorted_values[lower] weight = position - lower return sorted_values[lower] * (1 - weight) + sorted_values[upper] * weight def wilson_ci(k: int, n: int, z: float = Z_95) -> tuple[float, float]: if n == 0: return 0.0, 0.0 p = k / n denom = 1 + z * z / n center = (p + z * z / (2 * n)) / denom margin = z * math.sqrt((p * (1 - p) + z * z / (4 * n)) / n) / denom return max(0.0, center - margin), min(1.0, center + margin) def bootstrap_accuracy_ci(correct: list[bool], n_boot: int, seed: int) -> tuple[float, float]: if not correct: return 0.0, 0.0 rng = random.Random(seed) n = len(correct) samples: list[float] = [] for _ in range(n_boot): samples.append(sum(1 for _ in range(n) if correct[rng.randrange(n)]) / n) samples.sort() return percentile(samples, 0.025), percentile(samples, 0.975) def paired_bootstrap_diff_ci(a: list[bool], b: list[bool], n_boot: int, seed: int) -> tuple[float, float]: rng = random.Random(seed) n = len(a) if n == 0: return 0.0, 0.0 diffs: list[float] = [] per_item = [float(x) - float(y) for x, y in zip(a, b)] for _ in range(n_boot): diffs.append(sum(per_item[rng.randrange(n)] for _ in range(n)) / n) diffs.sort() return percentile(diffs, 0.025), percentile(diffs, 0.975) def exact_mcnemar_pvalue(b: int, c: int) -> float: n = b + c if n == 0: return 1.0 tail = min(b, c) probability = sum(math.comb(n, i) for i in range(tail + 1)) / (2**n) return min(1.0, 2 * probability) def pct(value: float) -> str: return f"{100 * value:.2f}" def print_single(name: str, labels: dict[str, bool], n_boot: int, seed: int) -> None: values = list(labels.values()) n = len(values) k = sum(values) acc = k / n if n else 0.0 wilson_low, wilson_high = wilson_ci(k, n) boot_low, boot_high = bootstrap_accuracy_ci(values, n_boot=n_boot, seed=seed) print(f"{name}") print(f" n: {n}") print(f" correct: {k}") print(f" accuracy: {pct(acc)}%") print(f" Wilson 95% CI: [{pct(wilson_low)}%, {pct(wilson_high)}%]") print(f" Bootstrap 95% CI: [{pct(boot_low)}%, {pct(boot_high)}%]") def print_pair( name_a: str, labels_a: dict[str, bool], name_b: str, labels_b: dict[str, bool], n_boot: int, seed: int, ) -> None: keys = sorted(set(labels_a) & set(labels_b)) if not keys: raise SystemExit("No overlapping items for paired comparison.") missing_a = len(set(labels_b) - set(labels_a)) missing_b = len(set(labels_a) - set(labels_b)) a = [labels_a[key] for key in keys] b = [labels_b[key] for key in keys] n = len(keys) acc_a = sum(a) / n acc_b = sum(b) / n diff = acc_a - acc_b a_only = sum(x and not y for x, y in zip(a, b)) b_only = sum((not x) and y for x, y in zip(a, b)) both_correct = sum(x and y for x, y in zip(a, b)) both_wrong = sum((not x) and (not y) for x, y in zip(a, b)) diff_low, diff_high = paired_bootstrap_diff_ci(a, b, n_boot=n_boot, seed=seed) p_value = exact_mcnemar_pvalue(a_only, b_only) print(f"Paired comparison: {name_a} vs {name_b}") print(f" paired n: {n}") if missing_a or missing_b: print(f" unpaired skipped: {missing_a} only in {name_b}, {missing_b} only in {name_a}") print(f" {name_a} accuracy: {pct(acc_a)}%") print(f" {name_b} accuracy: {pct(acc_b)}%") print(f" difference ({name_a} - {name_b}): {pct(diff)} percentage points") print(f" paired bootstrap 95% CI for difference: [{pct(diff_low)}, {pct(diff_high)}] points") print(f" McNemar exact p-value: {p_value:.4g}") print(" contingency:") print(f" both correct: {both_correct}") print(f" both wrong: {both_wrong}") print(f" {name_a} correct only: {a_only}") print(f" {name_b} correct only: {b_only}") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Compute LAB-Bench accuracy error bars and paired significance tests from result JSONL files." ) parser.add_argument("result_a", type=Path, help="First LAB-Bench result JSONL.") parser.add_argument("result_b", nargs="?", type=Path, help="Optional second result JSONL for paired comparison.") parser.add_argument("--name-a", default="method_a") parser.add_argument("--name-b", default="method_b") parser.add_argument("--key-field", default=None, help="Pairing key. Defaults to task_id, then id, then question.") parser.add_argument("--bootstrap", type=int, default=10000, help="Number of bootstrap resamples.") parser.add_argument("--seed", type=int, default=20260709, help="Random seed for bootstrap resampling.") return parser.parse_args() def main() -> int: args = parse_args() labels_a = load_labeled(args.result_a, key_field=args.key_field) print_single(args.name_a, labels_a, n_boot=args.bootstrap, seed=args.seed) if args.result_b: print() labels_b = load_labeled(args.result_b, key_field=args.key_field) print_single(args.name_b, labels_b, n_boot=args.bootstrap, seed=args.seed + 1) print() print_pair(args.name_a, labels_a, args.name_b, labels_b, n_boot=args.bootstrap, seed=args.seed + 2) return 0 if __name__ == "__main__": raise SystemExit(main())