"""Paired binary estimates with the question as the resampling unit. Callers should map every non-error, scheduled generation to ``True`` only for a verified correct final answer. For author-aligned solve-by-cap accuracy, unboxed/unparseable/abstained generations are ``False``. Keep the original grading and termination statuses in the output for secondary reporting. When there is one sample per question, exact McNemar tests the paired binary outcomes. With repeated seeds, the exact test is omitted; bootstrap resampling is over question clusters after averaging within each question, so repeated seeds are never treated as independent questions. """ from __future__ import annotations import math import random from collections.abc import Hashable, Mapping from typing import Any def _percentile(values: list[float], probability: float) -> float: if not values: raise ValueError("Cannot calculate a percentile of an empty sample") ordered = sorted(values) position = (len(ordered) - 1) * probability low = math.floor(position) high = math.ceil(position) if low == high: return ordered[low] fraction = position - low return ordered[low] * (1 - fraction) + ordered[high] * fraction def exact_mcnemar_pvalue(first_only: int, second_only: int) -> float | None: """Two-sided exact McNemar p-value from the two discordant pair counts.""" if first_only < 0 or second_only < 0: raise ValueError("Discordant counts cannot be negative") discordant = first_only + second_only if discordant == 0: return 1.0 tail = min(first_only, second_only) probability = sum(math.comb(discordant, k) for k in range(tail + 1)) / (2**discordant) return min(1.0, 2 * probability) def paired_cluster_summary( first: Mapping[Hashable, Mapping[Hashable, bool]], second: Mapping[Hashable, Mapping[Hashable, bool]], *, bootstrap_samples: int = 10_000, bootstrap_seed: int = 14353, ) -> dict[str, Any]: """Summarize two conditions matched by question and seed. Each outer key is a question ID; each inner key is a shared seed or generation replicate ID. Unmatched questions and replicate IDs are excluded and listed. The point estimate gives every matched question equal weight, averaging its paired replicate differences first. """ if bootstrap_samples < 0: raise ValueError("bootstrap_samples cannot be negative") questions = sorted(set(first) & set(second), key=lambda value: str(value)) excluded_questions = sorted(set(first) ^ set(second), key=lambda value: str(value)) question_differences: list[float] = [] per_question: list[dict[str, Any]] = [] paired_first: list[bool] = [] paired_second: list[bool] = [] unmatched_replicates = 0 for question in questions: first_reps = first[question] second_reps = second[question] common_reps = sorted(set(first_reps) & set(second_reps), key=lambda value: str(value)) unmatched_replicates += len(set(first_reps) ^ set(second_reps)) if not common_reps: excluded_questions.append(question) continue first_values = [bool(first_reps[replicate]) for replicate in common_reps] second_values = [bool(second_reps[replicate]) for replicate in common_reps] difference = sum(a - b for a, b in zip(first_values, second_values)) / len(common_reps) question_differences.append(difference) paired_first.extend(first_values) paired_second.extend(second_values) per_question.append( { "question_id": question, "paired_replicates": len(common_reps), "first_accuracy": sum(first_values) / len(first_values), "second_accuracy": sum(second_values) / len(second_values), "difference": difference, } ) n_questions = len(question_differences) if n_questions == 0: return { "n_questions": 0, "n_paired_generations": 0, "excluded_questions": excluded_questions, "unmatched_replicate_count": unmatched_replicates, "mean_question_weighted_difference": None, "question_bootstrap_percentile_95": None, "first_only": 0, "second_only": 0, "exact_mcnemar_two_sided_p": None, "per_question": [], } mean_difference = sum(question_differences) / n_questions bootstrap_ci: list[float] | None = None if bootstrap_samples: rng = random.Random(bootstrap_seed) bootstrap_means = [ sum(rng.choice(question_differences) for _ in range(n_questions)) / n_questions for _ in range(bootstrap_samples) ] bootstrap_ci = [ _percentile(bootstrap_means, 0.025), _percentile(bootstrap_means, 0.975), ] first_only = sum(a and not b for a, b in zip(paired_first, paired_second)) second_only = sum(b and not a for a, b in zip(paired_first, paired_second)) one_replicate_per_question = all( item["paired_replicates"] == 1 for item in per_question ) return { "n_questions": n_questions, "n_paired_generations": len(paired_first), "excluded_questions": sorted(set(excluded_questions), key=lambda value: str(value)), "unmatched_replicate_count": unmatched_replicates, "mean_question_weighted_difference": mean_difference, "question_bootstrap_percentile_95": bootstrap_ci, "first_only": first_only, "second_only": second_only, "exact_mcnemar_two_sided_p": ( exact_mcnemar_pvalue(first_only, second_only) if one_replicate_per_question else None ), "per_question": per_question, "bootstrap_seed": bootstrap_seed, "bootstrap_samples": bootstrap_samples, "interpretation_note": ( "Bootstrap resamples questions, not generations. Small numbers of questions can yield unstable or degenerate intervals; a zero-width interval does not establish equivalence." ), } __all__ = ["exact_mcnemar_pvalue", "paired_cluster_summary"]