#!/usr/bin/env python3 """Self-test for count.py. Runs the required fixtures plus adversarial and randomised configurations. count.py is checked two ways: its own reported centre set is validated for canonical form and ordering, and it is compared against an independent pair-based method that constructs rational unit-circle centres from pairs of points and tests rationality with an exact integer square test. The pair method is independent of count.py's circle-equation triple route: every circle through at least three rational points has a rational centre, hence it is generated by one of its pairs, and for a pair P,Q the centre is M +- (h/d) * (-dy, dx), M = (P+Q)/2, d^2 = |Q-P|^2, h^2 = 1 - d^2/4, so the centre is rational exactly when (h/d)^2 = (1/d^2 - 1/4) is a square of a rational, which is decided by exact integer square tests. """ import json import math import random import shutil import subprocess import sys import tempfile from fractions import Fraction from pathlib import Path HERE = Path(__file__).resolve().parent ROOT = HERE.parents[3] COUNT = HERE / "count.py" FIX = ROOT / "routes" / "rusirui-repro-verifier" / "fixtures" PY = sys.executable failures = [] results = [] def fail(msg): failures.append(msg) print("FAIL: " + msg) def run_count(path, cwd=None): proc = subprocess.run( [PY, str(COUNT), str(path)], capture_output=True, text=True, cwd=str(cwd if cwd is not None else Path(tempfile.gettempdir())), timeout=600, ) return proc.returncode, proc.stdout, proc.stderr def parse_json_coord(v): if isinstance(v, bool): raise ValueError("boolean") if isinstance(v, int): return Fraction(v) p, q = v.split("/") return Fraction(int(p), int(q)) def points_from_obj(obj): return [(parse_json_coord(a), parse_json_coord(b)) for a, b in obj["points"]] def canonical(fr): if fr.denominator == 1: return str(fr.numerator) return "%d/%d" % (fr.numerator, fr.denominator) def rational_sqrt(fr): """Return the non-negative rational square root of fr, or None.""" if fr < 0: return None a, b = fr.numerator, fr.denominator ra, rb = math.isqrt(a), math.isqrt(b) if ra * ra == a and rb * rb == b: return Fraction(ra, rb) return None def pair_method(points): """Independent exact set of unit-circle centres with >=3 input points.""" n = len(points) candidates = set() one = Fraction(1, 1) two = Fraction(2, 1) four = Fraction(4, 1) for i in range(n): xi, yi = points[i] for j in range(i + 1, n): xj, yj = points[j] dx = xj - xi dy = yj - yi d2 = dx * dx + dy * dy if d2 == 0 or d2 > four: continue h2 = one - d2 / four t2 = h2 / d2 mx = (xi + xj) / two my = (yi + yj) / two if t2 == 0: candidates.add((mx, my)) continue t = rational_sqrt(t2) if t is None: continue candidates.add((mx - t * dy, my + t * dx)) candidates.add((mx + t * dy, my - t * dx)) out = set() for cx, cy in candidates: hits = 0 for x, y in points: dx = x - cx dy = y - cy if dx * dx + dy * dy == one: hits += 1 if hits >= 3: break if hits >= 3: out.add((cx, cy)) return out def parse_output_centres(out, npoints): try: data = json.loads(out) except Exception as exc: fail("stdout is not JSON: %s" % exc) return None if not isinstance(data, dict): fail("stdout JSON is not an object") return None if set(data.keys()) != {"n", "unit_circles", "centers"}: fail("stdout keys are %r" % sorted(data.keys())) return None if type(data["n"]) is not int or data["n"] != npoints: fail("n is %r, expected %d" % (data["n"], npoints)) return None count = data["unit_circles"] if type(count) is not int or count < 0: fail("unit_circles is not a non-negative integer: %r" % (count,)) return None centres = data["centers"] if not isinstance(centres, list): fail("centers is not a list") return None if count != len(centres): fail("unit_circles=%d but len(centers)=%d" % (count, len(centres))) return None parsed = [] seen = set() for k, pair in enumerate(centres): if not isinstance(pair, list) or len(pair) != 2: fail("center %d is not a pair" % k) return None vals = [] for s in pair: if not isinstance(s, str): fail("center %d has a non-string coordinate" % k) return None try: fr = Fraction(s) except Exception: fail("center %d coordinate %r is not a rational" % (k, s)) return None if s != canonical(fr): fail("center %d coordinate %r is not reduced/canonical" % (k, s)) return None vals.append(fr) tup = tuple(vals) if tup in seen: fail("duplicate centre %r" % (tup,)) return None seen.add(tup) parsed.append(tup) if parsed != sorted(parsed): fail("centers are not sorted by (x,y)") return None return parsed def check_valid(path, obj, claimed=None, require_claim=True, label=None): points = points_from_obj(obj) code, out, err = run_count(path) name = label or str(path) if code != 0: fail("%s: expected exit 0, got %d; stderr=%r" % (name, code, err.strip())) results.append((name, code, "-", claimed)) return None centres = parse_output_centres(out, len(points)) if centres is None: results.append((name, code, "-", claimed)) return None expected = pair_method(points) if set(centres) != expected: fail( "%s: centre set differs from pair method: got %d %r, expected %d %r" % (name, len(centres), sorted(centres), len(expected), sorted(expected)) ) if require_claim and centres_count(centres) != claimed: fail("%s: computed %d but claimed %r" % (name, len(centres), claimed)) results.append((name, code, len(centres), claimed)) return centres def centres_count(centres): return len(centres) def check_invalid(path, label=None): name = label or str(path) code, out, err = run_count(path) if code == 0: fail("%s: expected nonzero exit, got 0; stdout=%r" % (name, out.strip())) if out.strip() != "": fail("%s: invalid input wrote to stdout: %r" % (name, out)) if not err.strip(): fail("%s: invalid input wrote no reason to stderr" % name) results.append((name, code, "-", "-")) def write_case(tmpdir, name, obj): path = Path(tmpdir) / (name + ".json") path.write_text(json.dumps(obj), encoding="utf-8") return path def write_raw_case(tmpdir, name, text): path = Path(tmpdir) / (name + ".json") path.write_text(text, encoding="utf-8") return path def adversarial_cases(): return [ ( "four_on_unit_circle", [[1, 0], [0, 1], [-1, 0], [0, -1]], 1, ), ( "eight_on_unit_circle", [ [1, 0], [0, 1], [-1, 0], [0, -1], ["3/5", "4/5"], ["-3/5", "4/5"], ["3/5", "-4/5"], ["-5/13", "12/13"], ], 1, ), ( "distance_two_pair_only", [[-1, 0], [1, 0], [0, 2]], 0, ), ( "distance_two_pair_on_circle", [[-1, 0], [1, 0], [0, 1]], 1, ), ( "three_collinear", [[0, 0], [1, 1], [2, 2]], 0, ), ( "irrational_centre_two_points", [[0, 0], [1, 0], [0, 2]], 0, ), ( "rational_centre_four", [["3/2", 0], ["-1/2", 0], ["1/2", 1], ["1/2", -1]], 1, ), ( "two_tangent_circles", [[1, 0], [0, 1], [0, -1], [2, 1], [2, -1]], 4, ), ( "nonreduced_three", [["0/5", "0/7"], ["5/5", "0/1"], ["0/1", "5/5"]], 0, ), ( "two_by_two_grid", [[0, 0], [1, 0], [0, 1], [1, 1]], 0, ), ] def random_cases(seed=20261128, count=80): rnd = random.Random(seed) cases = [] def rand_fraction(): return Fraction(rnd.randint(-5, 5), rnd.randint(1, 5)) def make_points(n, on_circle=False): pts = [] seen = set() if on_circle: cx = Fraction(rnd.randint(-2, 2), rnd.randint(1, 3)) cy = Fraction(rnd.randint(-2, 2), rnd.randint(1, 3)) ts = rnd.sample(range(-6, 7), 4) for t in ts: t = Fraction(t) u = Fraction(1 - t * t, 1 + t * t) v = Fraction(2 * t, 1 + t * t) p = (cx + u, cy + v) if p not in seen: seen.add(p) pts.append(p) while len(pts) < n: p = (rand_fraction(), rand_fraction()) if p not in seen: seen.add(p) pts.append(p) rnd.shuffle(pts) return pts for k in range(count): n = rnd.randint(3, 9) pts = make_points(n, on_circle=(k % 4 == 0)) cases.append(("random_%03d" % k, pts)) return cases def serialize_points(points, rnd): raw = [] for x, y in points: def one(fr): if rnd.random() < 0.5 and fr.denominator == 1: return int(fr) k = rnd.randint(1, 3) return "%d/%d" % (fr.numerator * k, fr.denominator * k) raw.append([one(x), one(y)]) return raw def main(): ok = True if not COUNT.exists(): fail("count.py is missing") return 1 accept = { "collinear": 0, "dedup": 1, "grid": 5, "nonunit": 0, "rational-center": 1, "three": 1, } for name, claimed in accept.items(): path = FIX / "samples" / "accept" / name / "configuration.json" obj = json.loads(path.read_text(encoding="utf-8")) check_valid(path, obj, claimed) # Invalid configurations. for name in ["duplicate", "float"]: path = FIX / "samples" / "reject" / name / "configuration.json" check_invalid(path) # Valid configurations whose declared count is wrong. misclaim = ["collinear", "nearly-unit", "overcount", "undercount"] for name in misclaim: path = FIX / "samples" / "reject" / name / "configuration.json" obj = json.loads(path.read_text(encoding="utf-8")) centres = check_valid(path, obj, obj.get("unit_circles"), require_claim=False) if centres is not None: computed = len(centres) if computed == obj.get("unit_circles"): fail("%s: expected a mismatch with claimed count" % path) grid80 = FIX / "grid80" / "configuration.json" obj = json.loads(grid80.read_text(encoding="utf-8")) check_valid(grid80, obj, obj.get("unit_circles"), require_claim=False, label=str(grid80)) tmpdir = Path(tempfile.mkdtemp(prefix="selftest-", dir=str(HERE))) rnd = random.Random(424242) try: # Adversarial cases. adv = adversarial_cases() for name, rawpoints, expected in adv: obj = {"schema": 1, "points": rawpoints, "unit_circles": expected} path = write_case(tmpdir, name, obj) pts = [(parse_json_coord(a), parse_json_coord(b)) for a, b in rawpoints] indep = pair_method(pts) if len(indep) != expected: fail("%s: pair method gives %d, hand expectation %d" % (name, len(indep), expected)) check_valid(path, obj, expected, label=name) # Randomised cross-checks. for name, pts in random_cases(): raw = serialize_points(pts, rnd) indep = pair_method(pts) obj = {"schema": 1, "points": raw, "unit_circles": len(indep)} path = write_case(tmpdir, name, obj) check_valid(path, obj, len(indep), label=name) # Invalid input cases. bad_objs = { "schema_2": {"schema": 2, "points": [[0, 0], [1, 0], [0, 1]], "unit_circles": 0}, "schema_string": {"schema": "1", "points": [[0, 0], [1, 0], [0, 1]], "unit_circles": 0}, "schema_float": {"schema": 1.0, "points": [[0, 0], [1, 0], [0, 1]], "unit_circles": 0}, "schema_bool": {"schema": True, "points": [[0, 0], [1, 0], [0, 1]], "unit_circles": 0}, "schema_missing": {"points": [[0, 0], [1, 0], [0, 1]], "unit_circles": 0}, "points_not_list": {"schema": 1, "points": "nope", "unit_circles": 0}, "too_few": {"schema": 1, "points": [[0, 0], [1, 0]], "unit_circles": 0}, "too_many": {"schema": 1, "points": [[i, 1000 + i] for i in range(81)], "unit_circles": 0}, "point_length": {"schema": 1, "points": [[0, 0, 0], [1, 0], [0, 1]], "unit_circles": 0}, "point_not_list": {"schema": 1, "points": [0, [1, 0], [0, 1]], "unit_circles": 0}, "coord_float": {"schema": 1, "points": [[0.0, 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_float_exp": {"schema": 1, "points": [[1e2, 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_bool": {"schema": 1, "points": [[True, 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_null": {"schema": 1, "points": [[None, 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_list": {"schema": 1, "points": [[[1], 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_decimal_string": {"schema": 1, "points": [["1.0", 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_exp_string": {"schema": 1, "points": [["1e2", 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_space": {"schema": 1, "points": [[" 1/2", 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_space2": {"schema": 1, "points": [["1/2 ", 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_newline": {"schema": 1, "points": [["1/2\n", 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_neg_den": {"schema": 1, "points": [["1/-2", 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_zero_den": {"schema": 1, "points": [["1/0", 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_double_slash": {"schema": 1, "points": [["1/2/3", 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_bare_int_string": {"schema": 1, "points": [["3", 0], [1, 0], [0, 1]], "unit_circles": 0}, "coord_plus": {"schema": 1, "points": [["+1/2", 0], [1, 0], [0, 1]], "unit_circles": 0}, "duplicate_reduced": {"schema": 1, "points": [[1, 0], ["2/2", 0], [0, 1]], "unit_circles": 0}, "duplicate_int": {"schema": 1, "points": [[1, 2], [1, 2], [0, 1]], "unit_circles": 0}, } for name, obj in bad_objs.items(): path = write_case(tmpdir, name, obj) check_invalid(path, label=name) path = write_raw_case(tmpdir, "malformed_json", "{not json") check_invalid(path, label="malformed_json") path = write_raw_case(tmpdir, "top_level_list", "[1,2,3]") check_invalid(path, label="top_level_list") path = tmpdir / "missing_file.json" check_invalid(path, label="missing_file") # Valid edge cases that must be accepted. edge_objs = { "zero_numerators": {"schema": 1, "points": [["0/5", "0/7"], ["5/5", "0/1"], ["0/1", "5/5"]], "unit_circles": 0}, "integral_fractions": {"schema": 1, "points": [["1/1", "0/1"], ["0/1", "1/1"], ["-1/1", "0/1"]], "unit_circles": 1}, } for name, obj in edge_objs.items(): path = write_case(tmpdir, name, obj) check_valid(path, obj, obj["unit_circles"], label=name) finally: shutil.rmtree(tmpdir, ignore_errors=True) print() print("RESULTS") for name, code, computed, claimed in results: print("%s | %s | %s | %s" % (name, code, computed, claimed)) print() if failures: print("%d FAILURE(S)" % len(failures)) return 1 print("ALL CHECKS PASSED (%d cases)" % len(results)) return 0 if __name__ == "__main__": sys.exit(main())