"""Exact null law for two independent samples from the same fair two-point population.""" import argparse from datetime import datetime, timezone from fractions import Fraction import hashlib import json from math import comb from pathlib import Path import platform from numeric import sqrt_rational def sample_size(n): if isinstance(n, bool) or not isinstance(n, int): raise TypeError("Sample size must be an integer") if n <= 0: raise ValueError("Sample size must be positive") return n def latency(value): if isinstance(value, bool) or not isinstance(value, (int, Fraction)): raise TypeError("Latency must be an int or Fraction") if value < 0: raise ValueError("Latency must be nonnegative") return Fraction(value) def count_difference_law(n): """P(abs(X-Y)=k), for independent X,Y ~ Binomial(n, 1/2). X+(n-Y) ~ Binomial(2*n, 1/2). Reflect its upper half and retain the central outcome once. Generate adjacent integer coefficients exactly. """ n = sample_size(n) denominator = 4 ** n coefficient = comb(2 * n, n) rows = [(0, Fraction(coefficient, denominator))] for k in range(1, n + 1): coefficient = coefficient * (n - k + 1) // (n + k) rows.append((k, Fraction(2 * coefficient, denominator))) return tuple(rows) def summarize(n, low=1, high=101): n = sample_size(n) low, high = latency(low), latency(high) if high <= low: raise ValueError("The two support points must be distinct and increasing") gap_squared = (high - low) ** 2 law = count_difference_law(n) expected = sum((probability * gap_squared * Fraction(k, n) for k, probability in law), Fraction(0)) return { "count_per_sample": n, "support_ms_exact": [str(low), str(high)], "probability_per_support_point_exact": "1/2", "true_population_distance_ms_exact": "0", "expected_squared_distance_ms2_exact": str(expected), "sqrt_expected_squared_distance_ms": sqrt_rational(expected), "probability_nonzero_distance_exact": str(1 - law[0][1]), "probability_nonzero_distance": float(1 - law[0][1]), "count_difference_outcomes": len(law), } def payload(): directory = Path(__file__).resolve().parent return { "schema_version": 1, "kind": "exact-null-model-calculation", "sampling": "Two independent iid samples, each of size n, with replacement.", "population": "Both populations put probability 1/2 at 1 ms and 1/2 at 101 ms.", "distance": "Inverse-ECDF squared distance: D^2 = 10000 * abs(X-Y) / n (ms^2).", "expectation": "Expectation over all independent sample pairs, not a measured average.", "source_sha256": {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in ("null_sampling.py", "numeric.py")}, "limits": [ "Constructed sampling model, not measured disk requests or fitted latency data.", "sqrt(E[D^2]) is not E[D], a confidence interval or a rejection threshold.", "No relative-demerit percentage: the sample reference mean is random.", "Independence and equal two-point probabilities are assumptions, not defaults for storage traces.", "Duplicating a recorded sample does not provide additional independent observations.", ], "cases": [summarize(n) for n in (1, 4, 16, 64, 256)], } def main(): parser = argparse.ArgumentParser() actions = parser.add_mutually_exclusive_group(required=True) actions.add_argument("--write", type=Path) actions.add_argument("--check", type=Path) args = parser.parse_args() result = payload() if args.check: existing = json.loads(args.check.read_text()) expected = {key: value for key, value in existing.items() if key not in ("generated_at", "runtime")} if result != expected: raise SystemExit("Null-sampling replay mismatch") print("PASS: five exact null-model cases and source hashes") else: result["generated_at"] = datetime.now(timezone.utc).isoformat() result["runtime"] = {"python": platform.python_version()} args.write.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n") if __name__ == "__main__": main()