#!/usr/bin/env python3 """Exact count of the unit circles that pass through at least three points. Method ------ Triple enumeration, O(n^3). For every 3-subset {a, b, c} put u = b - a, v = c - a, U = u.u, V = v.v and D = det(u, v). A unit circle through the three points exists only if they are not collinear (D != 0) and the circumcentre a + d, given by Cramer's rule applied to the linear system 2 u.d = U, 2 v.d = V, d_x = (U v_y - V u_y) / (2 D), d_y = (u_x V - v_x U) / (2 D), satisfies |d|^2 = 1 exactly. Surviving centres are de-duplicated in a set and then re-counted against every input point; only centres with at least three incident points are reported. Exactness --------- All coordinates are first cleared of denominators: with L the least common multiple of every coordinate denominator the points become integers P_i = L*p_i. With integer u, v and D the unit condition |d|^2 = 1 is *equivalent* to the integer identity (U v_y - V u_y)^2 + (u_x V - v_x U)^2 == 4 D^2 L^2, and the re-count is likewise the integer identity (P_x * den - L * n_x)^2 + (P_y * den - L * n_y)^2 == (L * den)^2 for a centre written n_x/den, n_y/den. No floating point value is ever formed, so every decision is exact. Usage: python3 count.py """ import json import math import re import sys from fractions import Fraction # A coordinate string must be exactly "p/q": optional minus, digits, "/", digits. _FRACTION_RE = re.compile(r"-?[0-9]+/[0-9]+") class Invalid(Exception): """The configuration file does not satisfy the input contract.""" def _coordinate(value): """Parse one coordinate into an exact Fraction, or raise Invalid.""" if isinstance(value, bool): raise Invalid("coordinate is a JSON boolean") if isinstance(value, int): return Fraction(value) if isinstance(value, float): raise Invalid("coordinate is a JSON float") if isinstance(value, str): if _FRACTION_RE.fullmatch(value) is None: raise Invalid("coordinate %r is not a fraction p/q" % (value,)) numerator, denominator = value.split("/") divisor = int(denominator) if divisor <= 0: raise Invalid("coordinate %r has a non-positive denominator" % (value,)) return Fraction(int(numerator), divisor) raise Invalid("coordinate is not a number") def _read_configuration(path): """Load and validate the configuration; return the points as Fractions.""" try: with open(path, "rb") as handle: raw = handle.read() except OSError as error: raise Invalid("cannot read %s: %s" % (path, error)) try: document = json.loads(raw.decode("utf-8")) except Exception as error: raise Invalid("not valid JSON: %s" % error) if not isinstance(document, dict): raise Invalid("the top level is not a JSON object") schema = document.get("schema") if isinstance(schema, bool) or not isinstance(schema, int) or schema != 1: raise Invalid("schema is not 1") listed = document.get("points") if not isinstance(listed, list): raise Invalid("points is not a JSON array") count = len(listed) if count < 3 or count > 80: raise Invalid("need 3 <= n <= 80 points, got %d" % count) points = [] first_seen = {} for index, pair in enumerate(listed): if not isinstance(pair, list) or len(pair) != 2: raise Invalid("point %d is not a pair [x, y]" % index) point = (_coordinate(pair[0]), _coordinate(pair[1])) if point in first_seen: raise Invalid( "points %d and %d are the same after reduction" % (first_seen[point], index) ) first_seen[point] = index points.append(point) return points def _clear_denominators(points): """Return (L, integer points) with P_i = L * p_i for a common L > 0.""" scale = 1 for x, y in points: scale = math.lcm(scale, x.denominator, y.denominator) scaled = [] for x, y in points: scaled.append( ( x.numerator * (scale // x.denominator), y.numerator * (scale // y.denominator), ) ) return scale, scaled def _reduce_center(nx, ny, denominator): """Canonical common-denominator form of the pair (nx/den, ny/den).""" if denominator < 0: denominator = -denominator nx = -nx ny = -ny common = math.gcd(math.gcd(abs(nx), abs(ny)), denominator) if common > 1: nx //= common ny //= common denominator //= common return nx, ny, denominator def _centers(points): """All centres of unit circles through at least three of the points. Returns a list of (x, y, incident indices) sorted by (x, y) exactly. """ count = len(points) scale, scaled = _clear_denominators(points) # |d|^2 == 1 <=> px^2 + py^2 == 4 * D^2 * scale^2 target = 4 * scale * scale candidates = set() for i in range(count - 2): ax, ay = scaled[i] for j in range(i + 1, count - 1): bx, by = scaled[j] ux = bx - ax uy = by - ay uu = ux * ux + uy * uy for k in range(j + 1, count): cx, cy = scaled[k] vx = cx - ax vy = cy - ay det = ux * vy - uy * vx if det == 0: continue # collinear triple, no circumcentre vv = vx * vx + vy * vy px = uu * vy - vv * uy py = ux * vv - vx * uu if px * px + py * py != target * det * det: continue # circumradius is not exactly 1 # Centre in units of 1/scale: a + (px, py) / (2 det); # in original units divide by scale. denominator = 2 * det * scale nx = 2 * det * ax + px ny = 2 * det * ay + py candidates.add(_reduce_center(nx, ny, denominator)) kept = [] for nx, ny, denominator in candidates: # |P/scale - n/denominator|^2 == 1 <=> # (P_x*denominator - scale*nx)^2 + (P_y*denominator - scale*ny)^2 # == (scale*denominator)^2 left_x = scale * nx left_y = scale * ny right = (scale * denominator) ** 2 incident = [] for index, (qx, qy) in enumerate(scaled): dx = qx * denominator - left_x dy = qy * denominator - left_y if dx * dx + dy * dy == right: incident.append(index) if len(incident) >= 3: kept.append( (Fraction(nx, denominator), Fraction(ny, denominator), incident) ) kept.sort(key=lambda entry: (entry[0], entry[1])) return kept def _format(value): """Reduced rational string: "a" when integral, else "p/q" with q > 1.""" if value.denominator == 1: return str(value.numerator) return "%d/%d" % (value.numerator, value.denominator) def main(argv): if len(argv) != 2: sys.stderr.write("usage: count.py \n") return 1 points = _read_configuration(argv[1]) circles = _centers(points) payload = { "n": len(points), "unit_circles": len(circles), "centers": [[_format(x), _format(y)] for x, y, _ in circles], } sys.stdout.write(json.dumps(payload, separators=(",", ":")) + "\n") return 0 if __name__ == "__main__": try: sys.exit(main(sys.argv)) except Invalid as problem: sys.stderr.write("%s\n" % (problem,)) sys.exit(1) except Exception as problem: # never leave a traceback or partial output sys.stderr.write("invalid configuration: %s\n" % (problem,)) sys.exit(1)