#!/usr/bin/env python3 """Tests of the judge, the format checker and the seed. Run: python3 -I checks/test_judge.py""" import json import os import random import shutil import subprocess import sys import tempfile import time from fractions import Fraction from pathlib import Path PKG = Path(__file__).resolve().parent.parent JUDGE, REPO = PKG / "checks" / "judge", PKG sys.dont_write_bytecode = True sys.path.insert(0, str(JUDGE)) from autocorrelation import MAX_STEPS, CandidateError, ratio # noqa: E402 BASELINE = Fraction(35528105221325, 23398155562896) def run(script, *args, cwd, route_dir="routes/x"): # as the check runs it (python3 checks/judge/check.py), without the environment's PYTHON* variables or user site env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "SS_ROUTE_DIR": route_dir} p = subprocess.run([sys.executable, "-E", "-s", "-B", str(script), *map(str, args)], cwd=cwd, capture_output=True, text=True, env=env, timeout=120) return p.returncode, p.stdout, p.stderr def check(files): """Runs verify on a route folder holding these files; returns (exit code, stdout, stderr, metrics or None).""" with tempfile.TemporaryDirectory() as tmp: folder = Path(tmp, "routes", "x") folder.mkdir(parents=True) for name, content in files.items(): path = folder / name if isinstance(content, bytes): path.write_bytes(content) else: path.write_text(content if isinstance(content, str) else json.dumps(content)) code, out, err = run(JUDGE / "check.py", folder, cwd=tmp) metrics = Path(tmp, "metrics.json") return code, out, err, json.loads(metrics.read_text()) if metrics.exists() else None def direct(heights): """Independent of the judge: R = 2N max_k sum_{i+j=k} a_i a_j / (sum a)^2 in plain Fractions, O(N^2).""" a = [Fraction(h) for h in heights] n = len(a) c = [Fraction(0)] * (2 * n - 1) for i, x in enumerate(a): if x: for j, y in enumerate(a): c[i + j] += x * y return 2 * n * max(c) / sum(a) ** 2 def seed(): return json.loads((REPO / "constructions" / "baseline.json").read_text()) def test_seed_is_the_baseline(): assert direct(seed()["heights"]) == BASELINE == ratio(seed())[1] code, out, err, m = check({"baseline.json": seed()}) assert code == 0 and not err and m == {"score": float(BASELINE), "score_exact": m["score_exact"]} and abs(float(m["score_exact"]) - float(BASELINE)) < 1e-15, (out, err, m) assert out.splitlines() == ["baseline.json: 200 steps, C <= 1.518414779568", "best upper bound C <= 1.518414779568 (baseline.json)"], out def test_known_values(): assert ratio({"heights": [1]})[1] == 2 # f = 1 on [-1/4, 1/4]: f*f peaks at 1/2, (int f)^2 = 1/4 assert ratio({"heights": [3, 3, 3]})[1] == 2 assert ratio({"heights": [1, 0, 1]})[1] == 3 # c = 1, 0, 2, 0, 1 assert ratio({"heights": ["0.1", "3/10"]})[1] == Fraction(9, 4) # c = 1, 6, 9 over 100; sum 4/10 floats = ratio({"heights": [0.1, 0.3]})[1] # the binary64 values, not 1/10 and 3/10 assert floats != Fraction(9, 4) and floats == direct([Fraction(0.1), Fraction(0.3)]) and abs(floats - Fraction(9, 4)) < Fraction(1, 10 ** 15) def test_packing_matches_direct_convolution(): rng = random.Random(7) for n in (1, 2, 3, 7, 64, 301): for kind in ("bit", "int", "float", "fraction", "sparse"): hs = {"bit": lambda: rng.getrandbits(1), "int": lambda: rng.getrandbits(90), "float": rng.random, "fraction": lambda: f"{rng.randrange(1000)}/{rng.randrange(1, 1000)}", "sparse": lambda: rng.choice([0, 0, 0, 1e-9, 2.5])}[kind] heights = [hs() for _ in range(n)] if not any(Fraction(h) for h in heights): heights[0] = 1 assert ratio({"heights": heights})[1] == direct(heights), (n, kind) def test_large_candidate_is_exact_and_fast(): rng = random.Random(1) A = [rng.getrandbits(60) for _ in range(2000)] c = [0] * 3999 for i, x in enumerate(A): for j, y in enumerate(A): c[i + j] += x * y assert ratio({"heights": A})[1] == Fraction(2 * 2000 * max(c), sum(A) ** 2) big = {"heights": [rng.random() for _ in range(MAX_STEPS)]} start = time.perf_counter() n, r = ratio(big) assert n == MAX_STEPS and 2 < r < 2.1 and time.perf_counter() - start < 30 def test_invalid_candidates_fail_cleanly(): cases = { "negative": ([1, -0.5], "negative"), "zeros": ([0, "0", 0.0], "all heights are 0"), "bool": ([1, True], "number or a string"), "null": ([1, None], "number or a string"), "text": ([1, "half"], "unreadable height"), "empty": ([], "list of 1 to"), "long": ([1] * (MAX_STEPS + 1), "list of 1 to"), "fine": ([1] * 20000 + [5e-324], "too fine to check"), } for name, (heights, message) in cases.items(): code, out, err, m = check({"ok.json": {"heights": [1]}, f"{name}.json": {"heights": heights}}) assert code == 1 and message in out and not err and m == {"score": 2.0, "score_exact": "2." + "0" * 25}, (name, out, err, m) code, out, err, m = check({"nan.json": '{"heights": [1, NaN]}'}) assert code == 1 and "not finite" in out and m is None, out for heights in ([1] * 20000 + [5e-324], [1e3] + [1e-12] * (MAX_STEPS - 1)): try: ratio({"heights": heights}) assert heights[0] == 1e3, "the size limit was not applied" except CandidateError: assert heights[0] == 1, "floats in [1e-12, 1e3] must stay inside the size limit" def test_malformed_files_fail_cleanly(): for content in ("{not json", "", b"\xff\xfe{"): code, out, err, m = check({"bad.json": content}) assert code == 1 and "unreadable" in out and not err and m is None, (out, err) assert out.strip().splitlines()[-1] == "no valid candidates: 1 failed", out def test_no_candidates(): for files in ({}, {"notes.json": {"values": [1]}}, {"README.md": "# x"}): code, out, err, m = check(files) assert code == 0 and out.strip() == "no candidates to check" and m is None, out def test_improves(): with tempfile.TemporaryDirectory() as tmp: main = Path(tmp, "main") shutil.copytree(REPO / "constructions", main / "constructions") route = Path(tmp, "route") route.mkdir() (route / "same.json").write_text(json.dumps(seed())) code, out, _ = run(JUDGE / "improves.py", route, main, cwd=main) assert code == 1 and out.startswith("no improvement: best upper bound 1.518414779568"), out (main / "constructions" / "baseline.json").write_text('{"heights": [1]}') code, out, _ = run(JUDGE / "improves.py", route, main, cwd=main) assert code == 0 and out.startswith("improves on the default branch by 0.482 (at least 1e-8): best upper bound 1.518414779568 (same.json), against 2.000000000000; not a new result"), out code, out, _ = run(JUDGE / "improves.py", Path(tmp, "empty"), main, cwd=main) assert code == 1 and out.startswith("no candidate"), out code, out, _ = run(JUDGE / "improves.py", main / "routes", main, cwd=main, route_dir="routes") assert code == 0 and out.strip() == "the default branch holds best upper bound 2.000000000000", out def test_check_format(): tool = REPO / "tools" / "check_format.py" code, out, err = run(tool, REPO / "constructions", cwd=REPO) assert code == 0 and out.strip().endswith("1 candidates, 0 files with format errors"), out + err with tempfile.TemporaryDirectory() as tmp: files = {"neg.json": {"heights": [1, -1, "x", True]}, "fine.json": {"heights": [1] * 20000 + [5e-324]}, "broken.json": "{", "other.json": {"values": [1]}, "good.json": {"heights": [0.5, "1/3", 2]}} for name, content in files.items(): Path(tmp, name).write_text(content if isinstance(content, str) else json.dumps(content)) code, out, err = run(tool, tmp, cwd=tmp) assert code == 1 and "negative" in out and "unreadable" in out and "not a finite number" in out and "too fine" in out, out assert "not valid JSON" in out and "ignored" in out and "good.json: ok (3 steps)" in out, out assert out.strip().endswith("3 candidates, 3 files with format errors"), out if __name__ == "__main__": failed = 0 for name, test in list(globals().items()): if name.startswith("test_"): try: test() print(f"ok {name}") except Exception as exc: failed += 1 print(f"FAIL {name}: {exc!r}") sys.exit(1 if failed else 0)