#!/usr/bin/env python3 """Exact count of unit circles through at least three of n rational points. Usage: python3 repro.py Independent of routes/rusirui-rational-verifier in method: this is the chord construction, not circumcentre enumeration by triples. For a circle of radius 1 through two points p and q, the centre lies on the perpendicular bisector of the chord. Write m for the midpoint, v = q - p with squared length d2, and v' = (-v_y, v_x) for a perpendicular of the same length. A centre on the bisector is c = m + s v' with s rational, since m and v' are rational and c is rational. The radius condition |c - p|^2 = 1 becomes |m - p|^2 + s^2 |v'|^2 = 1, so s^2 = (1 - d2/4) / d2 = (4 - d2) / (4 d2), because m - p is perpendicular to v'. Hence a pair has rational centres on a unit circle exactly when s^2 is the square of a rational: * d2 = 4: s = 0 and the single centre is m (the points are antipodal); * 0 < d2 < 4 with (4 - d2) / (4 d2) a perfect square: the two centres m +/- s v'; * otherwise: none. Completeness on rational input: a unit circle through three input points has three of its pairs on it, and its rational centre is of the form above for any of them, so at least one pair yields it here. A line meets a circle in at most two points, so three points on a circle are never collinear and no case is missed. A first version of this file tested the chord length and the height separately for being rational, which is wrong: on the unit circle, (1,0) and (0,1) have chord sqrt(2) and height sqrt(2)/2, neither rational, yet their centres are (0,0) and (1,1). Only the ratio is rational. The corpus in this route has a case (three-on-unit-circle) that fails immediately under the wrong test. Points must be distinct after reduction and 3 <= n <= 80; coordinates are JSON integers or strings "p/q" with q > 0. JSON floats, JSON booleans and strings that are not exactly such a fraction are refused. """ import json import re import sys from fractions import Fraction from itertools import combinations from math import isqrt, gcd RATIONAL = re.compile(r"-?[0-9]{1,32}(?:/[1-9][0-9]{0,31})?\Z") MAX_POINTS = 80 class Invalid(ValueError): pass def coordinate(value): if type(value) is not int: if not isinstance(value, str) or not RATIONAL.fullmatch(value): raise Invalid("coordinate is not an integer or a fraction p/q") value = value else: value = str(value) return Fraction(value) def perfect_square(value): """Return sqrt(value) as a Fraction when value is the square of a rational, else None.""" if value <= 0: return None numerator, denominator = value.numerator, value.denominator top, bottom = isqrt(numerator), isqrt(denominator) if top * top != numerator or bottom * bottom != denominator: return None return Fraction(top, bottom) def read(path): with open(path, "rb") as stream: raw = stream.read() payload = json.loads(raw) if not isinstance(payload, dict) or payload.get("schema") != 1 or type(payload.get("schema")) is not int: raise Invalid("schema must be the integer 1") raw_points = payload.get("points") if not isinstance(raw_points, list) or not 3 <= len(raw_points) <= MAX_POINTS: raise Invalid(f"expected 3..{MAX_POINTS} points") points = [] for entry in raw_points: if not isinstance(entry, list) or len(entry) != 2: raise Invalid("each point must be [x, y]") points.append((coordinate(entry[0]), coordinate(entry[1]))) if len(set(points)) != len(points): raise Invalid("points must be distinct after reduction") return points def centres(points): found = set() for (ax, ay), (bx, by) in combinations(points, 2): dx, dy = bx - ax, by - ay d2 = dx * dx + dy * dy if d2 == 0 or d2 > 4: continue mx, my = (ax + bx) / 2, (ay + by) / 2 if d2 == 4: found.add((mx, my)) continue step = perfect_square((4 - d2) / (4 * d2)) if step is None: continue offset_x, offset_y = step * -dy, step * dx found.add((mx + offset_x, my + offset_y)) found.add((mx - offset_x, my - offset_y)) return sorted(c for c in found if sum(1 for p in points if (p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2 == 1) >= 3) def render(value): value = Fraction(value) return str(value.numerator) if value.denominator == 1 else f"{value.numerator}/{value.denominator}" def main(argv): if len(argv) != 2: print("usage: repro.py ", file=sys.stderr) return 1 try: points = read(argv[1]) except (Invalid, ValueError, OSError, json.JSONDecodeError) as exc: print(f"invalid configuration: {exc}", file=sys.stderr) return 1 circles = centres(points) print(json.dumps({"n": len(points), "unit_circles": len(circles), "centers": [[render(x), render(y)] for x, y in circles]})) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))