#!/usr/bin/env python3 """Exact certification of an upper bound on the Erdos minimum overlap constant mu. A certificate is a step function on [-1, 1] with n cells of equal width h = 2/n and heights f_1, ..., f_n (environment/certificate_format.md). With F the step function and G = (1 - F) on [-1, 1], both zero outside, M(x) = int F(t) G(t + x) dt is continuous and piecewise linear with breakpoints in hZ (Russell 2026, Lemma 1; see environment/papers/russell-2026). Hence sup_x M(x) = max_{|m| <= n-1} M(mh) = (2/n) max_m sum_i f_i (1 - f_{i+m}), and by the continuum formulation (Swinnerton-Dyer; Haugland 1996) mu <= sup_x M(x) for every admissible F: heights in [0, 1] and integral 1, i.e. sum_i f_i = n/2. Heights may be given with any positive sum: they are rescaled exactly to sum n/2 (as the EinsteinArena board does), and the certificate is admissible only if every rescaled height lies in [0, 1]. Everything below is exact integer arithmetic; no floating-point number enters. Python >= 3.8, standard library only. """ from __future__ import annotations import json import sys from fractions import Fraction from math import gcd from operator import mul MAX_CELLS = 16384 DIGITS = 25 class CertificateError(ValueError): pass def parse_height(value, denominator: int | None) -> Fraction: """A height: a JSON number (a float is read as the exact binary value it denotes), an integer numerator over the certificate's common `denominator`, or a string 'p/q'.""" if isinstance(value, bool): raise CertificateError("a height cannot be a boolean") if isinstance(value, str): try: height = Fraction(value.strip()) except (ValueError, ZeroDivisionError) as exc: raise CertificateError(f"unreadable height {value!r}") from exc elif isinstance(value, int): height = Fraction(value) elif isinstance(value, float): if value != value or value in (float("inf"), float("-inf")): raise CertificateError("a height is not finite") height = Fraction(value) else: raise CertificateError(f"a height must be a number or a string, not {type(value).__name__}") return height / denominator if denominator else height def heights(certificate: dict) -> list[Fraction]: values = certificate.get("values") if not isinstance(values, list) or not values: raise CertificateError('the certificate needs a nonempty list "values"') if len(values) > MAX_CELLS: raise CertificateError(f"at most {MAX_CELLS} cells are checked (got {len(values)})") denominator = certificate.get("denominator") if denominator is not None: if isinstance(denominator, bool) or not isinstance(denominator, int) or denominator <= 0: raise CertificateError('"denominator" must be a positive integer') return [parse_height(value, denominator) for value in values] def certify(certificate: dict) -> dict: """The exact bound a certificate proves. Raises CertificateError if it is not admissible.""" values = heights(certificate) n = len(values) common = 1 for value in values: common = common * value.denominator // gcd(common, value.denominator) A = [int(value * common) for value in values] # integers, f_i = A_i / common S = sum(A) if S <= 0: raise CertificateError("the heights must have a positive sum") # rescaled heights f_i' = (n/2) A_i / S must lie in [0, 1]: 0 <= n A_i <= 2 S low = [i for i, a in enumerate(A) if a < 0] high = [i for i, a in enumerate(A) if n * a > 2 * S] if low or high: raise CertificateError(f"not admissible: after rescaling to sum n/2, {len(low)} heights are below 0 " f"and {len(high)} above 1 (first cells {(low + high)[:5]})") # f_i' g_{i+m}' = [n A_i / (2S)] [(2S - n A_{i+m}) / (2S)], and M(mh) = (2/n) sum_i f_i' g_{i+m}', # so M(mh) = C_m / (2 S^2) with the integer C_m = sum_i A_i B_{i+m}, B_j = 2S - n A_j. B = [2 * S - n * a for a in A] best, lag = None, None for m in range(-(n - 1), n): lo, hi = max(0, -m), min(n, n - m) c = sum(map(mul, A[lo:hi], B[lo + m:hi + m])) if best is None or c > best: best, lag = c, m bound = Fraction(best, 2 * S * S) return {"n": n, "bound": bound, "argmax_lag": lag, "x_star": Fraction(2 * lag, n), "rescaled": S * 2 != n * common} def decimal_up(value: Fraction, digits: int = DIGITS) -> str: scaled = -((-value.numerator * 10 ** digits) // value.denominator) text = str(scaled).rjust(digits + 1, "0") return f"{text[:-digits]}.{text[-digits:]}" def main(argv: list[str]) -> int: if len(argv) != 2: print("usage: verify_overlap.py CERTIFICATE.json", file=sys.stderr) return 2 with open(argv[1], encoding="utf-8") as handle: result = certify(json.load(handle)) print(json.dumps({"n": result["n"], "bound": f"{result['bound'].numerator}/{result['bound'].denominator}", "bound_decimal_up": decimal_up(result["bound"]), "argmax_lag": result["argmax_lag"], "x_star": str(result["x_star"]), "rescaled": result["rescaled"]}, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv))