"""Exact unweighted, full-ranking AP null arithmetic; no sampled fleet data.""" import argparse from fractions import Fraction import json from pathlib import Path def counts(n, m): if type(n) is not int or type(m) is not int or not 1 <= m <= n: raise ValueError("Require integer N >= M >= 1 (no-positive AP is undefined here).") def expected_ap(n, m): """Uniform ordering of fixed labels, distinct scores, no sample weights.""" counts(n, m) if n == 1: return Fraction(1) harmonic = sum((Fraction(1, k) for k in range(1, n + 1)), Fraction()) return Fraction(m, n) + Fraction(n - m, n * (n - 1)) * (harmonic - 1) def ap_from_groups(groups): """Groups (positive count, total count) in descending score order.""" if not groups: raise ValueError("Require at least one score group.") for positive, total in groups: if type(positive) is not int or type(total) is not int or not 0 <= positive <= total or total < 1: raise ValueError("Invalid score group.") positives = sum(positive for positive, _ in groups) if positives == 0: raise ValueError("No-positive AP is undefined here.") seen = found = 0 result = Fraction() for positive, total in groups: seen += total found += positive result += Fraction(positive, positives) * Fraction(found, seen) return result def results(): rows = [] for n, m in [(4, 1), (4, 2), (100, 1), (1000, 10), (100, 100)]: expected = expected_ap(n, m) rows.append({ "n": n, "m": m, "constant_score_ap": format(m / n, ".6f"), "random_ranking_mean_ap": format(float(expected), ".6f"), "random_mean_exact": str(expected), }) return { "schema_version": 1, "kind": "exact null-model arithmetic, not fleet data", "formula": "M/N + (N-M)*(H_N-1)/(N*(N-1))", "assumptions": ["fixed N and M", "1 <= M <= N", "equal observation weights", "full ranking", "uniform ordering independent of labels", "distinct scores for random ranking", "constant scores evaluated as one tied group"], "source": "https://www.vmsta.org/journal/VMSTA/article/353/text", "source_location": "Theorem 1, equation (4), cutoff k=N", "generated_on": "2026-11-22", "rows": rows, } if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--write", action="store_true") args = parser.parse_args() output = json.dumps(results(), indent=2) + "\n" path = Path(__file__).with_name("results.json") if args.write: path.write_text(output, encoding="utf-8") elif path.read_text(encoding="utf-8") != output: raise SystemExit("Stale AP results; run model.py --write.") else: print("Five exact AP baseline rows verified.")