#!/usr/bin/env python3 """Self-test for count.py. Runs, in order: * the twelve sample fixtures and the 80-point grid fixture through the CLI; * a set of adversarial configurations invented here (written to ./adversarial); * a set of invalid configurations that must be rejected; * a randomized cross-check of count.py against altcount.py, an independently written second solver that enumerates pairs instead of triples; * a check that count.py runs from an unrelated working directory. Exit status 0 iff every expectation holds. """ import json import os import random import subprocess import sys import time from math import gcd HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.abspath(os.path.join(HERE, os.pardir, os.pardir, os.pardir, os.pardir)) COUNT = os.path.join(HERE, "count.py") ALT = os.path.join(HERE, "altcount.py") CASE_DIR = os.path.join(HERE, "adversarial") PY = sys.executable FAILURES = [] def run_cli(script, path, cwd=None): started = time.time() proc = subprocess.run([PY, "-I", script, path], capture_output=True, text=True, cwd=cwd) return proc.returncode, proc.stdout, proc.stderr, time.time() - started def check(ok, label, detail=""): if not ok: FAILURES.append("%s: %s" % (label, detail)) return ok def load_count(exit_code, stdout): if exit_code != 0: return None try: return json.loads(stdout) except ValueError: return None # -------------------------------------------------------------------------- # 1. fixtures # -------------------------------------------------------------------------- FIXTURE_DIR = os.path.join(ROOT, "routes", "rusirui-repro-verifier", "fixtures") # expectation kinds: "match" = exit 0 and computed == claimed, # "mismatch" = exit 0 and computed != claimed, # "invalid" = exit 1, nothing on stdout. FIXTURES = [ ("samples/accept/collinear", "match"), ("samples/accept/dedup", "match"), ("samples/accept/grid", "match"), ("samples/accept/nonunit", "match"), ("samples/accept/rational-center", "match"), ("samples/accept/three", "match"), ("samples/reject/collinear", "mismatch"), ("samples/reject/duplicate", "invalid"), ("samples/reject/float", "invalid"), ("samples/reject/nearly-unit", "mismatch"), ("samples/reject/overcount", "mismatch"), ("samples/reject/undercount", "mismatch"), ("grid80", "match"), ] def fixture_report(): print("== fixtures ==") for rel, kind in FIXTURES: path = os.path.join(FIXTURE_DIR, rel, "configuration.json") with open(path, "rb") as handle: claimed = json.loads(handle.read()).get("unit_circles", "-") code, out, err, elapsed = run_cli(COUNT, path) parsed = load_count(code, out) computed = parsed["unit_circles"] if parsed else "-" print("%s | %s | %s | %s (%.2fs)" % (rel + "/configuration.json", code, computed, claimed, elapsed)) if kind == "invalid": check(code == 1, rel, "expected exit 1, got %d" % code) check(out == "", rel, "expected empty stdout on invalid input") else: check(code == 0, rel, "expected exit 0, got %d (%s)" % (code, err.strip())) if kind == "match": check(computed == claimed, rel, "computed %s != claimed %s" % (computed, claimed)) else: check(computed != claimed, rel, "computed %s equals claimed %s" % (computed, claimed)) # second implementation must agree with the first, byte for byte alt_code, alt_out, alt_err, _ = run_cli(ALT, path) check((alt_code, alt_out) == (code, out), rel, "altcount disagreed: exit %d vs %d, stdout %r vs %r (%s)" % (alt_code, code, alt_out, out, alt_err.strip())) # -------------------------------------------------------------------------- # 2. adversarial cases # -------------------------------------------------------------------------- def rat(num, den=1): if den < 0: num, den = -num, -den g = gcd(abs(num), den) return (num // g, den // g) def add(left, right): return rat(left[0] * right[1] + right[0] * left[1], left[1] * right[1]) def text(pair): return str(pair[0]) if pair[1] == 1 else "%d/%d" % pair def doc_of(points, claimed=None): """points: [( (xn,xd), (yn,yd) ), ...] -> configuration document. Integral coordinates are written as JSON integers and non-integral ones as "p/q" strings, the only two forms the input schema allows. """ def wire(pair): return pair[0] if pair[1] == 1 else "%d/%d" % pair body = [[wire(px), wire(py)] for px, py in points] document = {"schema": 1, "points": body} if claimed is not None: document["unit_circles"] = claimed return document UNIT_VECTORS = [] for _u, _v in ((0, 1), (1, 0), (1, 1), (1, 2), (2, 1), (1, 3), (3, 1), (2, 3), (3, 2), (1, 4), (4, 1), (2, 5), (5, 2)): _d = _v * _v + _u * _u UNIT_VECTORS.append(((rat(_v * _v - _u * _u, _d), rat(2 * _u * _v, _d)))) def circle_points(center, vectors): cx, cy = center return [(add(cx, vx), add(cy, vy)) for vx, vy in vectors] def adversarial_cases(): cases = [] # (a) eight rational points on one circle; ten cocircular triples must fold # into a single center, with denominators 5 and 13 forcing L = 65. pts = [((1, 1), (0, 1)), ((-1, 1), (0, 1)), ((0, 1), (1, 1)), ((0, 1), (-1, 1)), ((rat(3, 5), rat(4, 5))), ((rat(-3, 5), rat(4, 5))), ((rat(5, 13), rat(12, 13))), ((rat(-5, 13), rat(12, 13)))] cases.append(("four_on_one_circle", doc_of(pts, 1), 1, [((0, 1), (0, 1))])) # (b) two points exactly 2 apart: the unit circle through them is centred at # the midpoint and also carries two more points. pts = [((0, 1), (0, 1)), ((2, 1), (0, 1)), ((1, 1), (1, 1)), ((1, 1), (-1, 1))] cases.append(("distance_two", doc_of(pts, 1), 1, [((1, 1), (0, 1))])) # (c) same pair at distance 2 but the third point misses: circumcentre # (1, 3/4), radius 5/4. Must not count. pts = [((0, 1), (0, 1)), ((2, 1), (0, 1)), ((1, 1), (2, 1))] cases.append(("distance_two_miss", doc_of(pts, 1), 0, [])) # (d) four collinear points. pts = [((i, 1), (0, 1)) for i in range(4)] cases.append(("collinear_four", doc_of(pts, 1), 0, [])) # (e) (0,0),(1,0) lie on a unit circle only with an irrational centre, so a # third rational point can never complete one; here the circumradius of # the triangle is sqrt(2)/2 anyway. pts = [((0, 1), (0, 1)), ((1, 1), (0, 1)), ((1, 1), (1, 1))] cases.append(("irrational_center_pair", doc_of(pts, 1), 0, [])) # (f) four points on the unit circle centred at (1/3, 2/7); the common # denominator is 105 and the answer has a non-integral centre. centre = (rat(1, 3), rat(2, 7)) pts = circle_points(centre, [UNIT_VECTORS[2], UNIT_VECTORS[5], UNIT_VECTORS[10], UNIT_VECTORS[8]]) cases.append(("rational_center_105", doc_of(pts, 1), 1, [centre])) # (g) two disjoint unit circles, exercising sort order and dedup across # many triples. pts = circle_points(((0, 1), (0, 1)), [UNIT_VECTORS[0], UNIT_VECTORS[2], UNIT_VECTORS[4], UNIT_VECTORS[6]]) pts += circle_points(((10, 1), (0, 1)), [UNIT_VECTORS[1], UNIT_VECTORS[3], UNIT_VECTORS[5], UNIT_VECTORS[7]]) cases.append(("two_circles", doc_of(pts, 2), 2, [((0, 1), (0, 1)), ((10, 1), (0, 1))])) # (h) centres at (-1,0), (0,1) and (1,0) -- three of them, since (-1,1), # (0,0), (1,1) are also unit apart from (0,1). The printed order must # be the exact rational ascending order, not string order. pts = [((-2, 1), (0, 1)), ((-1, 1), (1, 1)), ((0, 1), (0, 1)), ((2, 1), (0, 1)), ((1, 1), (1, 1))] cases.append(("sorted_negative", doc_of(pts, 3), 3, [((-1, 1), (0, 1)), ((0, 1), (1, 1)), ((1, 1), (0, 1))])) # (i) a near miss whose radius is 1 + 1.25e-25: a double would round it to # exactly 1 and count it. Exact arithmetic must say no. big = 10 ** 12 pts = [((0, 1), (0, 1)), ((2, 1), (0, 1)), ((1, 1), rat(big + 1, big))] cases.append(("nearly_unit_tiny", doc_of(pts, 1), 0, [])) # (j) the same with v = 1 exactly: a real unit circle through all three. pts = [((0, 1), (0, 1)), ((2, 1), (0, 1)), ((1, 1), (1, 1))] cases.append(("exact_unit", doc_of(pts, 1), 1, [((1, 1), (0, 1))])) # (k) 80 points of the half-integer 10x8 grid. Scaling by 2 turns them # into the full 10x8 lattice with radius 2. A pair at distance^2 q has # a rational centre iff (16-q)q is a square, and among the sums of two # squares q <= 16 only q = 16 (axis pairs, lattice centre) and q = 8 # (diagonal pairs, half-integer centre) qualify; a half-integer centre # meets no lattice point at distance 2 (odd squares are 1 mod 8, so # their sum is 2 mod 8, never 16). Lattice centres with at least three # of their four two-step neighbours: 6*4 = 24 interior ones with four # and 8+8+12+12 = 40 on the two-step edge bands with three, so 64. pts = [] for j in range(8): for i in range(10): pts.append(((rat(i, 2)), (rat(j, 2)))) cases.append(("half_grid_80", doc_of(pts, 64), 64, None)) # (l) fifteen disjoint unit circles, four points each: 60 points, and all # fifteen centres must be reported. pts = [] centres = [] for k in range(15): centre = ((20 * k, 1), (0, 1)) centres.append(centre) vecs = [UNIT_VECTORS[(4 * k + t) % len(UNIT_VECTORS)] for t in range(4)] pts += circle_points(centre, vecs) cases.append(("many_circles", doc_of(pts, 15), 15, centres)) # (m) a unit circle far from the origin, so that the modular pre-filter sees # residues that differ from the coordinates themselves. centre = ((10 ** 12, 1), (10 ** 12, 1)) pts = circle_points(centre, [UNIT_VECTORS[0], UNIT_VECTORS[1], UNIT_VECTORS[2], UNIT_VECTORS[4]]) cases.append(("huge_offset_circle", doc_of(pts, 1), 1, [centre])) # (n) a unit circle whose points have 32-digit denominators: a true # positive that the pre-filter must not lose, cross-checked against the # unfiltered pair-based solver. a = 10 ** 16 + 1 b = 10 ** 16 + 3 d = b * b + a * a huge_vectors = [(rat(b * b - a * a, d), rat(2 * a * b, d)), (rat(a * a - b * b, d), rat(2 * a * b, d)), ((0, 1), (1, 1)), ((1, 1), (0, 1))] centre = (rat(1, 3), rat(2, 7)) pts = circle_points(centre, huge_vectors) cases.append(("huge_denominator_circle", doc_of(pts, 1), 1, [centre])) return cases def adversarial_report(): print("== adversarial cases ==") os.makedirs(CASE_DIR, exist_ok=True) for name, document, expected, centres in adversarial_cases(): path = os.path.join(CASE_DIR, name + ".json") with open(path, "w", encoding="utf-8") as handle: json.dump(document, handle, indent=1) handle.write("\n") code, out, err, elapsed = run_cli(COUNT, path) alt_code, alt_out, alt_err, _ = run_cli(ALT, path) parsed = load_count(code, out) computed = parsed["unit_circles"] if parsed else "-" print("%s | %d | %s | claimed %s (%.2fs)" % (name, code, computed, document.get("unit_circles"), elapsed)) check(code == 0, name, "expected exit 0, got %d (%s)" % (code, err.strip())) check(computed == expected, name, "expected %s circles, got %s" % (expected, computed)) check((alt_code, alt_out) == (code, out), name, "altcount disagreed: %r vs %r" % (alt_out, out)) if centres is not None and parsed is not None: reported = [tuple(centre) for centre in parsed["centers"]] for centre in centres: want = (text(centre[0]), text(centre[1])) check(want in reported, name, "missing centre %s" % (want,)) # -------------------------------------------------------------------------- # 3. invalid inputs # -------------------------------------------------------------------------- def invalid_report(): print("== invalid inputs ==") folder = os.path.join(CASE_DIR, "invalid") os.makedirs(folder, exist_ok=True) good = [[0, 0], [1, 0], [0, 1]] cases = [ ("schema_2", {"schema": 2, "points": good, "unit_circles": 0}), ("schema_float", {"schema": 1.0, "points": good, "unit_circles": 0}), ("schema_bool", {"schema": True, "points": good, "unit_circles": 0}), ("schema_missing", {"points": good, "unit_circles": 0}), ("n_2", {"schema": 1, "points": [[0, 0], [1, 0]]}), ("n_81", {"schema": 1, "points": [[i, 0] for i in range(81)]}), ("duplicate_repr", {"schema": 1, "points": [["1/2", 0], ["2/4", 0], [0, 1]]}), ("bool_coord", {"schema": 1, "points": [[True, 0], [1, 0], [0, 1]]}), ("float_coord", {"schema": 1, "points": [[1.0, 0], [1, 0], [0, 1]]}), ("string_decimal", {"schema": 1, "points": [["0.5", 0], [1, 0], [0, 1]]}), ("string_space", {"schema": 1, "points": [[" 1/2", 0], [1, 0], [0, 1]]}), ("string_integer", {"schema": 1, "points": [["1", 0], [1, 0], [0, 1]]}), ("zero_denominator", {"schema": 1, "points": [["1/0", 0], [1, 0], [0, 1]]}), ("negative_denominator", {"schema": 1, "points": [["1/-2", 0], [1, 0], [0, 1]]}), ("point_len_3", {"schema": 1, "points": [[1, 2, 3], [1, 0], [0, 1]]}), ("point_not_pair", {"schema": 1, "points": ["12", [1, 0], [0, 1]]}), ("points_not_list", {"schema": 1, "points": {"a": 1}}), ("unicode_digits", {"schema": 1, "points": [["١/٢", 0], [1, 0], [0, 1]]}), ] for name, document in cases: path = os.path.join(folder, name + ".json") with open(path, "w", encoding="utf-8") as handle: json.dump(document, handle) handle.write("\n") code, out, err, _ = run_cli(COUNT, path) alt = run_cli(ALT, path) print("%s | %d | %s" % (name, code, (err.strip().splitlines() or [""])[0])) check(code == 1, name, "expected exit 1, got %d" % code) check(out == "", name, "expected empty stdout") check((alt[0], alt[1]) == (code, out), name, "altcount differed: %r" % (alt[2].strip(),)) raw_cases = [("float_exponent", '{"schema": 1, "points": [[1e3, 0], [1, 0], [0, 1]]}'), ("not_object", '[]'), ("bad_json", '{"schema": 1, "points": ['), ("empty_file", "")] for name, body in raw_cases: path = os.path.join(folder, name + ".json") with open(path, "w", encoding="utf-8") as handle: handle.write(body) code, out, err, _ = run_cli(COUNT, path) alt = run_cli(ALT, path) print("%s | %d | %s" % (name, code, (err.strip().splitlines() or [""])[0])) check(code == 1, name, "expected exit 1, got %d" % code) check(out == "", name, "expected empty stdout") check((alt[0], alt[1]) == (code, out), name, "altcount differed") missing = os.path.join(folder, "does-not-exist.json") code, out, err, _ = run_cli(COUNT, missing) print("missing_file | %d | %s" % (code, (err.strip().splitlines() or [""])[0])) check(code == 1 and out == "", "missing_file", "expected exit 1, no stdout") # -------------------------------------------------------------------------- # 4. randomized cross-check against the pair-based solver # -------------------------------------------------------------------------- def randomized_report(): print("== randomized cross-check (count.py vs altcount.py) ==") sys.path.insert(0, HERE) import count as impl import altcount as altimpl rng = random.Random(20261128) denoms = [1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12] mismatches = 0 trials = 0 def compare(document, label): nonlocal mismatches, trials trials += 1 try: _, pts_a = impl.read_points(json.loads(json.dumps(document))) want = impl.solve(pts_a) status = "solved" except impl.Invalid: want = None status = "invalid" try: _, pts_b = altimpl.read_points(json.loads(json.dumps(document))) got = altimpl.solve(pts_b) except altimpl.Invalid: got = None if (want is None) != (got is None) or (want is not None and want != got): mismatches += 1 print("MISMATCH %s: %r -> %r vs %r" % (label, document, want, got)) return want, status # purely random point sets for round_index in range(40): count_points = rng.randint(3, 14) points = [] seen = set() while len(points) < count_points: px = rat(rng.randint(-25, 25), rng.choice(denoms)) py = rat(rng.randint(-25, 25), rng.choice(denoms)) if (px, py) in seen: continue seen.add((px, py)) points.append((px, py)) compare(doc_of(points), "random-%d" % round_index) # constructed unions of unit circles plus noise constructed_failures = 0 for round_index in range(20): points = [] seen = set() centres = [] ks = rng.randint(1, 4) for _ in range(ks): centre = (rat(rng.randint(-30, 30), rng.choice(denoms)), rat(rng.randint(-30, 30), rng.choice(denoms))) if centre in centres: continue centres.append(centre) for vec in rng.sample(UNIT_VECTORS, rng.randint(3, 5)): pt = (add(centre[0], vec[0]), add(centre[1], vec[1])) if pt not in seen: seen.add(pt) points.append(pt) while len(points) < 3: px = rat(rng.randint(-9, 9), 1) py = rat(rng.randint(-9, 9), 1) if (px, py) in seen: continue seen.add((px, py)) points.append((px, py)) rng.shuffle(points) document = doc_of(points[:80]) found, _ = compare(document, "constructed-%d" % round_index) if found is None: constructed_failures += 1 continue for centre in centres: if centre not in found: constructed_failures += 1 print("MISSING CONSTRUCTED CENTRE %s in %s" % (centre, [text(c) for c in centre])) print("trials: %d, mismatches: %d, constructed failures: %d" % (trials, mismatches, constructed_failures)) check(mismatches == 0, "randomized", "%d mismatches" % mismatches) check(constructed_failures == 0, "constructive", "%d constructed circles missing" % constructed_failures) # -------------------------------------------------------------------------- # 5. positional independence # -------------------------------------------------------------------------- def cwd_report(): print("== working-directory independence ==") path = os.path.join(FIXTURE_DIR, "samples", "accept", "grid", "configuration.json") import tempfile with tempfile.TemporaryDirectory() as scratch: code, out, err, _ = run_cli(COUNT, path, cwd=scratch) print("run from %s | exit %d | %s" % ("a temp dir", code, out.strip()[:60])) check(code == 0 and json.loads(out)["unit_circles"] == 5, "cwd", "expected exit 0 and 5 circles, got %d %r %r" % (code, out, err)) def main(): fixture_report() adversarial_report() invalid_report() randomized_report() cwd_report() print("== summary ==") if FAILURES: print("FAILURES: %d" % len(FAILURES)) for item in FAILURES: print(" " + item) return 1 print("all checks passed") return 0 if __name__ == "__main__": sys.exit(main())