An autocorrelation constant for Sidon sets
Find the least possible peak of f*f for a non-negative f of unit mass on [-1/4, 1/4]; it lies between 1.2802 and 1.50286.
| 1 | #!/usr/bin/env python3 |
| 2 | """Tests of the judge, the format checker and the seed. Run: python3 -I checks/test_judge.py""" |
| 3 | import json |
| 4 | import os |
| 5 | import random |
| 6 | import shutil |
| 7 | import subprocess |
| 8 | import sys |
| 9 | import tempfile |
| 10 | import time |
| 11 | from fractions import Fraction |
| 12 | from pathlib import Path |
| 13 | |
| 14 | PKG = Path(__file__).resolve().parent.parent |
| 15 | JUDGE, REPO = PKG / "checks" / "judge", PKG |
| 16 | sys.dont_write_bytecode = True |
| 17 | sys.path.insert(0, str(JUDGE)) |
| 18 | from autocorrelation import MAX_STEPS, CandidateError, ratio # noqa: E402 |
| 19 | |
| 20 | BASELINE = Fraction(35528105221325, 23398155562896) |
| 21 | |
| 22 | |
| 23 | def run(script, *args, cwd, route_dir="routes/x"): |
| 24 | # as the check runs it (python3 checks/judge/check.py), without the environment's PYTHON* variables or user site |
| 25 | env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "SS_ROUTE_DIR": route_dir} |
| 26 | p = subprocess.run([sys.executable, "-E", "-s", "-B", str(script), *map(str, args)], cwd=cwd, capture_output=True, text=True, env=env, timeout=120) |
| 27 | return p.returncode, p.stdout, p.stderr |
| 28 | |
| 29 | |
| 30 | def check(files): |
| 31 | """Runs verify on a route folder holding these files; returns (exit code, stdout, stderr, metrics or None).""" |
| 32 | with tempfile.TemporaryDirectory() as tmp: |
| 33 | folder = Path(tmp, "routes", "x") |
| 34 | folder.mkdir(parents=True) |
| 35 | for name, content in files.items(): |
| 36 | path = folder / name |
| 37 | if isinstance(content, bytes): |
| 38 | path.write_bytes(content) |
| 39 | else: |
| 40 | path.write_text(content if isinstance(content, str) else json.dumps(content)) |
| 41 | code, out, err = run(JUDGE / "check.py", folder, cwd=tmp) |
| 42 | metrics = Path(tmp, "metrics.json") |
| 43 | return code, out, err, json.loads(metrics.read_text()) if metrics.exists() else None |
| 44 | |
| 45 | |
| 46 | def direct(heights): |
| 47 | """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).""" |
| 48 | a = [Fraction(h) for h in heights] |
| 49 | n = len(a) |
| 50 | c = [Fraction(0)] * (2 * n - 1) |
| 51 | for i, x in enumerate(a): |
| 52 | if x: |
| 53 | for j, y in enumerate(a): |
| 54 | c[i + j] += x * y |
| 55 | return 2 * n * max(c) / sum(a) ** 2 |
| 56 | |
| 57 | |
| 58 | def seed(): |
| 59 | return json.loads((REPO / "constructions" / "baseline.json").read_text()) |
| 60 | |
| 61 | |
| 62 | def test_seed_is_the_baseline(): |
| 63 | assert direct(seed()["heights"]) == BASELINE == ratio(seed())[1] |
| 64 | code, out, err, m = check({"baseline.json": seed()}) |
| 65 | 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) |
| 66 | assert out.splitlines() == ["baseline.json: 200 steps, C <= 1.518414779568", "best upper bound C <= 1.518414779568 (baseline.json)"], out |
| 67 | |
| 68 | |
| 69 | def test_known_values(): |
| 70 | assert ratio({"heights": [1]})[1] == 2 # f = 1 on [-1/4, 1/4]: f*f peaks at 1/2, (int f)^2 = 1/4 |
| 71 | assert ratio({"heights": [3, 3, 3]})[1] == 2 |
| 72 | assert ratio({"heights": [1, 0, 1]})[1] == 3 # c = 1, 0, 2, 0, 1 |
| 73 | assert ratio({"heights": ["0.1", "3/10"]})[1] == Fraction(9, 4) # c = 1, 6, 9 over 100; sum 4/10 |
| 74 | floats = ratio({"heights": [0.1, 0.3]})[1] # the binary64 values, not 1/10 and 3/10 |
| 75 | assert floats != Fraction(9, 4) and floats == direct([Fraction(0.1), Fraction(0.3)]) and abs(floats - Fraction(9, 4)) < Fraction(1, 10 ** 15) |
| 76 | |
| 77 | |
| 78 | def test_packing_matches_direct_convolution(): |
| 79 | rng = random.Random(7) |
| 80 | for n in (1, 2, 3, 7, 64, 301): |
| 81 | for kind in ("bit", "int", "float", "fraction", "sparse"): |
| 82 | hs = {"bit": lambda: rng.getrandbits(1), "int": lambda: rng.getrandbits(90), "float": rng.random, |
| 83 | "fraction": lambda: f"{rng.randrange(1000)}/{rng.randrange(1, 1000)}", "sparse": lambda: rng.choice([0, 0, 0, 1e-9, 2.5])}[kind] |
| 84 | heights = [hs() for _ in range(n)] |
| 85 | if not any(Fraction(h) for h in heights): |
| 86 | heights[0] = 1 |
| 87 | assert ratio({"heights": heights})[1] == direct(heights), (n, kind) |
| 88 | |
| 89 | |
| 90 | def test_large_candidate_is_exact_and_fast(): |
| 91 | rng = random.Random(1) |
| 92 | A = [rng.getrandbits(60) for _ in range(2000)] |
| 93 | c = [0] * 3999 |
| 94 | for i, x in enumerate(A): |
| 95 | for j, y in enumerate(A): |
| 96 | c[i + j] += x * y |
| 97 | assert ratio({"heights": A})[1] == Fraction(2 * 2000 * max(c), sum(A) ** 2) |
| 98 | big = {"heights": [rng.random() for _ in range(MAX_STEPS)]} |
| 99 | start = time.perf_counter() |
| 100 | n, r = ratio(big) |
| 101 | assert n == MAX_STEPS and 2 < r < 2.1 and time.perf_counter() - start < 30 |
| 102 | |
| 103 | |
| 104 | def test_invalid_candidates_fail_cleanly(): |
| 105 | cases = { |
| 106 | "negative": ([1, -0.5], "negative"), |
| 107 | "zeros": ([0, "0", 0.0], "all heights are 0"), |
| 108 | "bool": ([1, True], "number or a string"), |
| 109 | "null": ([1, None], "number or a string"), |
| 110 | "text": ([1, "half"], "unreadable height"), |
| 111 | "empty": ([], "list of 1 to"), |
| 112 | "long": ([1] * (MAX_STEPS + 1), "list of 1 to"), |
| 113 | "fine": ([1] * 20000 + [5e-324], "too fine to check"), |
| 114 | } |
| 115 | for name, (heights, message) in cases.items(): |
| 116 | code, out, err, m = check({"ok.json": {"heights": [1]}, f"{name}.json": {"heights": heights}}) |
| 117 | assert code == 1 and message in out and not err and m == {"score": 2.0, "score_exact": "2." + "0" * 25}, (name, out, err, m) |
| 118 | code, out, err, m = check({"nan.json": '{"heights": [1, NaN]}'}) |
| 119 | assert code == 1 and "not finite" in out and m is None, out |
| 120 | for heights in ([1] * 20000 + [5e-324], [1e3] + [1e-12] * (MAX_STEPS - 1)): |
| 121 | try: |
| 122 | ratio({"heights": heights}) |
| 123 | assert heights[0] == 1e3, "the size limit was not applied" |
| 124 | except CandidateError: |
| 125 | assert heights[0] == 1, "floats in [1e-12, 1e3] must stay inside the size limit" |
| 126 | |
| 127 | |
| 128 | def test_malformed_files_fail_cleanly(): |
| 129 | for content in ("{not json", "", b"\xff\xfe{"): |
| 130 | code, out, err, m = check({"bad.json": content}) |
| 131 | assert code == 1 and "unreadable" in out and not err and m is None, (out, err) |
| 132 | assert out.strip().splitlines()[-1] == "no valid candidates: 1 failed", out |
| 133 | |
| 134 | |
| 135 | def test_no_candidates(): |
| 136 | for files in ({}, {"notes.json": {"values": [1]}}, {"README.md": "# x"}): |
| 137 | code, out, err, m = check(files) |
| 138 | assert code == 0 and out.strip() == "no candidates to check" and m is None, out |
| 139 | |
| 140 | |
| 141 | def test_improves(): |
| 142 | with tempfile.TemporaryDirectory() as tmp: |
| 143 | main = Path(tmp, "main") |
| 144 | shutil.copytree(REPO / "constructions", main / "constructions") |
| 145 | route = Path(tmp, "route") |
| 146 | route.mkdir() |
| 147 | (route / "same.json").write_text(json.dumps(seed())) |
| 148 | code, out, _ = run(JUDGE / "improves.py", route, main, cwd=main) |
| 149 | assert code == 1 and out.startswith("no improvement: best upper bound 1.518414779568"), out |
| 150 | (main / "constructions" / "baseline.json").write_text('{"heights": [1]}') |
| 151 | code, out, _ = run(JUDGE / "improves.py", route, main, cwd=main) |
| 152 | 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 |
| 153 | code, out, _ = run(JUDGE / "improves.py", Path(tmp, "empty"), main, cwd=main) |
| 154 | assert code == 1 and out.startswith("no candidate"), out |
| 155 | code, out, _ = run(JUDGE / "improves.py", main / "routes", main, cwd=main, route_dir="routes") |
| 156 | assert code == 0 and out.strip() == "the default branch holds best upper bound 2.000000000000", out |
| 157 | |
| 158 | |
| 159 | def test_check_format(): |
| 160 | tool = REPO / "tools" / "check_format.py" |
| 161 | code, out, err = run(tool, REPO / "constructions", cwd=REPO) |
| 162 | assert code == 0 and out.strip().endswith("1 candidates, 0 files with format errors"), out + err |
| 163 | with tempfile.TemporaryDirectory() as tmp: |
| 164 | files = {"neg.json": {"heights": [1, -1, "x", True]}, "fine.json": {"heights": [1] * 20000 + [5e-324]}, |
| 165 | "broken.json": "{", "other.json": {"values": [1]}, "good.json": {"heights": [0.5, "1/3", 2]}} |
| 166 | for name, content in files.items(): |
| 167 | Path(tmp, name).write_text(content if isinstance(content, str) else json.dumps(content)) |
| 168 | code, out, err = run(tool, tmp, cwd=tmp) |
| 169 | assert code == 1 and "negative" in out and "unreadable" in out and "not a finite number" in out and "too fine" in out, out |
| 170 | assert "not valid JSON" in out and "ignored" in out and "good.json: ok (3 steps)" in out, out |
| 171 | assert out.strip().endswith("3 candidates, 3 files with format errors"), out |
| 172 | |
| 173 | |
| 174 | |
| 175 | if __name__ == "__main__": |
| 176 | failed = 0 |
| 177 | for name, test in list(globals().items()): |
| 178 | if name.startswith("test_"): |
| 179 | try: |
| 180 | test() |
| 181 | print(f"ok {name}") |
| 182 | except Exception as exc: |
| 183 | failed += 1 |
| 184 | print(f"FAIL {name}: {exc!r}") |
| 185 | sys.exit(1 if failed else 0) |
