#!/usr/bin/env python3 """Verify the certificate a route handed in. Usage: verify.py FOLDER [--metrics PATH] Only targets with a written verifier are judged automatically: E-6 (N = 30030 has 905 unordered prime pairs, the example) and C-1 (the paper's Appendix B for N = 30030 in exact rationals: B-01's edge pairs and E, its prime-power pairs and C_pp/2, and the identity N*J/2 - C_pp/2 + E = 905). A certificate for another target named in docs/submission.md exits 0 with a line saying no verifier exists yet: the project has not fixed that schema, and a route must not go red for it. An unknown target is an error. E-6 reads FOLDER/CERTIFICATE.json: {"target": "E-6", "N": 30030, "pairs": [[p, q], ...]} Checks: * N is 30030; * every pair has p <= q, p + q = N, and both entries prime; * no unordered pair repeats; * the listed pairs are exactly the set of prime pairs (recomputed here); * the count is 905. C-1 reads FOLDER/CERTIFICATE.json: {"target": "C-1", "N": 30030, "pairs": 905, "edge_pairs": 75, "E": "/", "prime_power_pairs": 26, "Cpp_half": "/", "NJ": "/", "identity": "905"} with every rational in lowest terms; the checker recomputes each exactly (the paper's smooth step P is a polynomial, so every term is a rational) and compares them as fractions. Exit 0 with the last line "E-6: 905" or "C-1: Appendix B exact" when the certificate is valid. Exit 1 with the first problem otherwise. With --metrics PATH, writes {"score": 1, "subtasks": {"": 1}} on success. """ from __future__ import annotations import json import math import sys from fractions import Fraction from pathlib import Path N = 30030 TARGET = "E-6" EXPECTED = 905 class Wrong(Exception): pass class NoVerifier(Exception): """A target this checker does not verify yet; a maintainer reads the certificate instead.""" def prime(n: int) -> bool: if n < 2: return False if n % 2 == 0: return n == 2 limit = math.isqrt(n) d = 3 while d <= limit: if n % d == 0: return False d += 2 return True def expected_pairs() -> set[tuple[int, int]]: out: set[tuple[int, int]] = set() for p in range(2, N // 2 + 1): q = N - p if prime(p) and prime(q): out.add((p, q) if p <= q else (q, p)) return out def load(folder: Path) -> dict: path = folder / "CERTIFICATE.json" if not path.is_file(): raise FileNotFoundError(path) try: text = path.read_text(encoding="utf-8") except OSError as e: raise Wrong(f"{path.name} cannot be read: {e}") from None try: data = json.loads(text) except json.JSONDecodeError as e: raise Wrong(f"{path.name} is not valid JSON: {e}") from None if not isinstance(data, dict): raise Wrong(f"{path.name} must hold a JSON object") return data # The certificates a maintainer reads until their verifier is written (docs/submission.md). PENDING = {"C-2", "C-3", "C-4", "C-5"} # ---- C-1: Appendix B of Li-Liu for N = 30030, exactly ------------------------------------------------------------ # The paper's weight: eta(x) = P((x - A)/(L - A)) P((N - x - A)/(L - A)) with its C^6 step P, a polynomial on [0, 1], # so every term below is a rational. E sums 1 - eta(p)^2 over the prime pairs with p < L; C_pp counts the ordered # pairs p^k + q^l = N with (pq, N) = 1 and max(k, l) >= 2, each with weight eta(n)^2/(kl); N*J is the same sum over # every pair of prime powers. Their combination is the exact count: N*J/2 - C_pp/2 + E = 905. A_, L_ = 16, 1000 def step(t: Fraction) -> Fraction: if t <= 0: return Fraction(0) if t >= 1: return Fraction(1) return sum((math.comb(13, j) * t**j * (1 - t) ** (13 - j) for j in range(7, 14)), Fraction(0)) def eta(x: int) -> Fraction: return step(Fraction(x - A_, L_ - A_)) * step(Fraction(N - x - A_, L_ - A_)) def prime_power(n: int) -> tuple[int, int] | None: """(p, k) when n = p^k with k >= 1, else None.""" d = 2 while d * d <= n: if n % d == 0: k = 0 while n % d == 0: n //= d k += 1 return (d, k) if n == 1 else None d += 1 return (n, 1) if n > 1 else None def appendix_b() -> dict: pairs = sorted(expected_pairs()) edge = [p for p, _ in pairs if p < L_] e = sum((1 - eta(p) ** 2 for p in edge), Fraction(0)) cpp, pp, nj = Fraction(0), 0, Fraction(0) for n in range(2, N - 1): if math.gcd(n, N) != 1: continue a, b = prime_power(n), prime_power(N - n) if not a or not b: continue w = eta(n) ** 2 / (a[1] * b[1]) nj += w if max(a[1], b[1]) >= 2: cpp += w pp += n < N - n return {"pairs": len(pairs), "edge_pairs": len(edge), "E": e, "prime_power_pairs": pp, "Cpp_half": cpp / 2, "NJ": nj, "identity": nj / 2 - cpp / 2 + e} def rational(data: dict, key: str) -> Fraction: v = data.get(key) if not isinstance(v, str) or not v.strip(): raise Wrong(f"{key} must be a rational written as a string, \"/\" or an integer") try: x = Fraction(v.strip()) except (ValueError, ZeroDivisionError): raise Wrong(f"{key} = {v!r} is not a rational") from None if str(x) != v.strip().replace(" ", ""): raise Wrong(f"{key} = {v!r} is not in lowest terms (write {x})") return x def check_c1(data: dict) -> str: want = appendix_b() for key in ("pairs", "edge_pairs", "prime_power_pairs"): if data.get(key) != want[key]: raise Wrong(f"{key} is {data.get(key)!r}; the recount gives a different number") for key in ("E", "Cpp_half", "NJ", "identity"): if rational(data, key) != want[key]: raise Wrong(f"{key} differs from the exact value") if want["identity"] != EXPECTED: raise Wrong(f"the identity gives {want['identity']}, not {EXPECTED}: the checker itself is wrong") return "C-1: Appendix B exact" def check(data: dict) -> str: target = data.get("target") if target in PENDING: raise NoVerifier(str(target)) if target == "C-1": if data.get("N") != N: raise Wrong(f"N must be {N}, found {data.get('N')!r}") return check_c1(data) if target != TARGET: raise Wrong(f"target must be {TARGET!r} or 'C-1', found {data.get('target')!r}") if data.get("N") != N: raise Wrong(f"N must be {N}, found {data.get('N')!r}") pairs = data.get("pairs") if not isinstance(pairs, list): raise Wrong("pairs must be a list of [p, q] pairs") seen: set[tuple[int, int]] = set() for i, pair in enumerate(pairs): if not isinstance(pair, (list, tuple)) or len(pair) != 2: raise Wrong(f"pairs[{i}] must be a pair [p, q]") p, q = pair if not isinstance(p, int) or not isinstance(q, int) or isinstance(p, bool) or isinstance(q, bool): raise Wrong(f"pairs[{i}] must hold two integers") if p > q: raise Wrong(f"pairs[{i}] = [{p}, {q}] has p > q; write the unordered pair as [p, q] with p <= q") if p + q != N: raise Wrong(f"pairs[{i}] = [{p}, {q}] sums to {p + q}, not {N}") if not prime(p): raise Wrong(f"pairs[{i}] = [{p}, {q}]: {p} is not prime") if not prime(q): raise Wrong(f"pairs[{i}] = [{p}, {q}]: {q} is not prime") if (p, q) in seen: raise Wrong(f"pairs[{i}] = [{p}, {q}] repeats an earlier pair") seen.add((p, q)) want = expected_pairs() if seen != want: missing = sorted(want - seen)[:3] extra = sorted(seen - want)[:3] bits = [] if missing: bits.append(f"missing e.g. {missing}") if extra: bits.append(f"not a prime pair e.g. {extra}") raise Wrong("the certificate is not exactly the set of prime pairs" + (": " + "; ".join(bits) if bits else "")) if len(seen) != EXPECTED: raise Wrong(f"count is {len(seen)}, expected {EXPECTED}") return f"{TARGET}: {len(seen)}" def main(argv: list[str]) -> int: args = [a for a in argv[1:]] metrics: str | None = None if "--metrics" in args: i = args.index("--metrics") if i + 1 >= len(args): print("--metrics needs a path", file=sys.stderr) return 2 metrics = args[i + 1] del args[i : i + 2] if len(args) != 1: print(__doc__.strip().splitlines()[0], file=sys.stderr) print("usage: verify.py FOLDER [--metrics PATH]", file=sys.stderr) return 2 folder = Path(args[0]) if not folder.is_dir(): # the default branch, or a route that has not made its folder yet print("Nothing to check here: this commit has no route folder.") return 0 try: data = load(folder) except FileNotFoundError: print("Nothing to check yet: the route's folder holds no CERTIFICATE.json.") return 0 except Wrong as e: print(str(e), file=sys.stderr) return 1 try: said = check(data) except NoVerifier as e: print(f"no automatic verifier for {e} yet: a maintainer reads the certificate, as docs/submission.md says.") return 0 except Wrong as e: print(str(e), file=sys.stderr) return 1 print(said) if metrics: path = Path(metrics) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps({"score": 1, "subtasks": {str(data.get("target")): 1}}) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv))