Unit circles through three of n points
Show that n points in the plane have only o(n²) unit circles passing through three of them; the best construction gives n^{3/2}.

| 1 | #!/usr/bin/env python3 |
| 2 | """Exact counter for unit circles through at least three of n rational points. |
| 3 | |
| 4 | Usage: python3 count.py <configuration.json> |
| 5 | |
| 6 | Method (pair-based chord construction, O(n^2) candidate pairs). |
| 7 | |
| 8 | For an unordered pair of points p1, p2 with squared distance d2 (0 < d2 <= 4), |
| 9 | the centres of the two unit circles through the pair are |
| 10 | |
| 11 | c = m +/- (k/2) * perp(p2 - p1), perp(dx, dy) = (-dy, dx), |
| 12 | m = (p1 + p2)/2, k = sqrt((4 - d2) / d2). |
| 13 | |
| 14 | Only pairs whose k is rational can yield a rational centre, and every centre |
| 15 | of a unit circle through three rational points is rational: three non-collinear |
| 16 | rational points have a rational circumcentre (a nonsingular linear system with |
| 17 | rational coefficients), and three distinct collinear points lie on no circle. |
| 18 | So enumerating rational candidates over all pairs loses no circle. |
| 19 | |
| 20 | All arithmetic is exact. Coordinates are fractions.Fraction throughout; |
| 21 | the input coordinates are scaled once by a common integer to make every point |
| 22 | integral, so candidate generation and the final "exactly three points at |
| 23 | distance 1" test are pure integer arithmetic. No floating point value is ever |
| 24 | created: k rational is decided by reducing (4-d2)/d2 and testing that numerator |
| 25 | and denominator are perfect squares (math.isqrt), never by a float square root. |
| 26 | """ |
| 27 | |
| 28 | import json |
| 29 | import math |
| 30 | import re |
| 31 | import sys |
| 32 | from fractions import Fraction |
| 33 | |
| 34 | # Python 3.11+ refuses int() on strings longer than 4300 digits by default. |
| 35 | # A coordinate may legitimately be a huge exact integer or fraction; the |
| 36 | # exactness of the count must not depend on that interpreter guard. |
| 37 | if hasattr(sys, "set_int_max_str_digits"): |
| 38 | sys.set_int_max_str_digits(0) |
| 39 | |
| 40 | |
| 41 | class Invalid(Exception): |
| 42 | """The configuration does not satisfy the input contract.""" |
| 43 | |
| 44 | |
| 45 | # "p/q" exactly: an optionally negative integer over a non-negative integer. |
| 46 | # No sign on the denominator (q must be positive), no whitespace, no decimal |
| 47 | # point, no exponent, no other characters. |
| 48 | _FRACTION_RE = re.compile(r"\A(-?[0-9]+)/([0-9]+)\Z") |
| 49 | |
| 50 | |
| 51 | def _coordinate(value, where): |
| 52 | """Parse one coordinate; raise Invalid unless it is an integer or 'p/q'.""" |
| 53 | if isinstance(value, bool): |
| 54 | raise Invalid(f"{where} is a JSON boolean, not a number") |
| 55 | if isinstance(value, float): |
| 56 | raise Invalid(f"{where} is a JSON float, not an integer or fraction") |
| 57 | if isinstance(value, int): |
| 58 | return Fraction(value) |
| 59 | if isinstance(value, str): |
| 60 | match = _FRACTION_RE.match(value) |
| 61 | if match is None: |
| 62 | raise Invalid(f"{where} {value!r} is not exactly a fraction p/q") |
| 63 | numerator = int(match.group(1)) |
| 64 | denominator = int(match.group(2)) |
| 65 | if denominator == 0: |
| 66 | raise Invalid(f"{where} {value!r} has a zero denominator") |
| 67 | return Fraction(numerator, denominator) |
| 68 | raise Invalid(f"{where} is not an integer or a 'p/q' string") |
| 69 | |
| 70 | |
| 71 | def load_configuration(path): |
| 72 | """Read and validate the configuration file; return the points.""" |
| 73 | try: |
| 74 | with open(path, "r", encoding="utf-8-sig") as handle: |
| 75 | document = json.load(handle) |
| 76 | except OSError as exc: |
| 77 | raise Invalid(f"cannot read {path}: {exc.strerror or exc}") |
| 78 | except UnicodeDecodeError: |
| 79 | raise Invalid(f"{path} is not valid UTF-8") |
| 80 | except RecursionError: |
| 81 | raise Invalid(f"{path} is nested too deeply to be a configuration") |
| 82 | except json.JSONDecodeError as exc: |
| 83 | raise Invalid(f"{path} is not valid JSON: {exc.msg} at line {exc.lineno}") |
| 84 | |
| 85 | if not isinstance(document, dict): |
| 86 | raise Invalid("the top-level JSON value must be an object") |
| 87 | |
| 88 | schema = document.get("schema") |
| 89 | if isinstance(schema, bool) or not isinstance(schema, int) or schema != 1: |
| 90 | raise Invalid('"schema" must be the integer 1') |
| 91 | |
| 92 | raw_points = document.get("points") |
| 93 | if not isinstance(raw_points, list): |
| 94 | raise Invalid('"points" must be an array') |
| 95 | |
| 96 | count = len(raw_points) |
| 97 | if not 3 <= count <= 80: |
| 98 | raise Invalid(f"need 3 <= n <= 80 points, got {count}") |
| 99 | |
| 100 | points = [] |
| 101 | for index, raw_point in enumerate(raw_points): |
| 102 | if not isinstance(raw_point, list) or len(raw_point) != 2: |
| 103 | raise Invalid(f"point {index} must be an array of exactly two coordinates") |
| 104 | x = _coordinate(raw_point[0], f"point {index} x") |
| 105 | y = _coordinate(raw_point[1], f"point {index} y") |
| 106 | points.append((x, y)) |
| 107 | |
| 108 | seen = set() |
| 109 | for index, point in enumerate(points): |
| 110 | if point in seen: |
| 111 | raise Invalid(f"point {index} duplicates an earlier point after reduction") |
| 112 | seen.add(point) |
| 113 | |
| 114 | return points |
| 115 | |
| 116 | |
| 117 | def _rational_sqrt_ratio(numerator, denominator): |
| 118 | """Return (a, b) with a/b == sqrt(numerator/denominator), or None. |
| 119 | |
| 120 | numerator and denominator are positive integers, not necessarily coprime. |
| 121 | The ratio is the square of a rational exactly when, after reduction, both |
| 122 | parts are perfect squares of integers; that is decided with math.isqrt. |
| 123 | """ |
| 124 | common = math.gcd(numerator, denominator) |
| 125 | numerator //= common |
| 126 | denominator //= common |
| 127 | root_num = math.isqrt(numerator) |
| 128 | root_den = math.isqrt(denominator) |
| 129 | if root_num * root_num != numerator or root_den * root_den != denominator: |
| 130 | return None |
| 131 | return root_num, root_den |
| 132 | |
| 133 | |
| 134 | def count_unit_circles(points): |
| 135 | """Return [(cx, cy, [point indices on the circle]), ...] sorted by (cx, cy). |
| 136 | |
| 137 | Every returned circle has radius exactly 1 and at least three input points |
| 138 | at distance exactly 1 from its centre. |
| 139 | """ |
| 140 | n = len(points) |
| 141 | |
| 142 | # One common denominator: with scale = lcm of all coordinate denominators, |
| 143 | # every point is (xs[i]/scale, ys[i]/scale) with xs[i], ys[i] integers. |
| 144 | scale = 1 |
| 145 | for x, y in points: |
| 146 | scale = scale * x.denominator // math.gcd(scale, x.denominator) |
| 147 | scale = scale * y.denominator // math.gcd(scale, y.denominator) |
| 148 | xs = [int(x * scale) for x, _ in points] |
| 149 | ys = [int(y * scale) for _, y in points] |
| 150 | four_scale_sq = 4 * scale * scale |
| 151 | |
| 152 | # Candidate centres from every pair at distance at most 2. |
| 153 | candidates = set() |
| 154 | for i in range(n): |
| 155 | x1, y1 = xs[i], ys[i] |
| 156 | for j in range(i + 1, n): |
| 157 | x2, y2 = xs[j], ys[j] |
| 158 | dx = x2 - x1 |
| 159 | dy = y2 - y1 |
| 160 | d2 = dx * dx + dy * dy # (distance * scale)^2 |
| 161 | if d2 == 0 or d2 > four_scale_sq: |
| 162 | # d2 = 0 only for a repeated point, which validation rejects; |
| 163 | # d2 > 4 puts the pair outside every unit circle. |
| 164 | continue |
| 165 | sum_x = x1 + x2 |
| 166 | sum_y = y1 + y2 |
| 167 | if d2 == four_scale_sq: |
| 168 | # Chord of length exactly 2: the centre is the midpoint. |
| 169 | candidates.add((Fraction(sum_x, 2 * scale), Fraction(sum_y, 2 * scale))) |
| 170 | continue |
| 171 | root = _rational_sqrt_ratio(four_scale_sq - d2, d2) |
| 172 | if root is None: |
| 173 | # k is irrational, so this pair lies on no unit circle with a |
| 174 | # rational centre, and every circle we must count has one. |
| 175 | continue |
| 176 | a, b = root # k = sqrt((4-d2)/d2) = a/b |
| 177 | denominator = 2 * scale * b |
| 178 | # centre = ((x1+x2) -/+ k*dy, (y1+y2) +/- k*dx) / (2*scale) |
| 179 | candidates.add( |
| 180 | ( |
| 181 | Fraction(sum_x * b - a * dy, denominator), |
| 182 | Fraction(sum_y * b + a * dx, denominator), |
| 183 | ) |
| 184 | ) |
| 185 | candidates.add( |
| 186 | ( |
| 187 | Fraction(sum_x * b + a * dy, denominator), |
| 188 | Fraction(sum_y * b - a * dx, denominator), |
| 189 | ) |
| 190 | ) |
| 191 | |
| 192 | # Keep the candidates with at least three points at distance exactly 1. |
| 193 | centres = [] |
| 194 | for cx, cy in candidates: |
| 195 | centre_den = cx.denominator * cy.denominator // math.gcd(cx.denominator, cy.denominator) |
| 196 | ax = int(cx * centre_den) # centre = (ax/centre_den, ay/centre_den) |
| 197 | ay = int(cy * centre_den) |
| 198 | target = (scale * centre_den) ** 2 |
| 199 | on_circle = [] |
| 200 | for i in range(n): |
| 201 | ux = xs[i] * centre_den - ax * scale |
| 202 | uy = ys[i] * centre_den - ay * scale |
| 203 | if ux * ux + uy * uy == target: |
| 204 | on_circle.append(i) |
| 205 | if len(on_circle) >= 3: |
| 206 | centres.append((cx, cy, on_circle)) |
| 207 | |
| 208 | centres.sort(key=lambda item: (item[0], item[1])) |
| 209 | return centres |
| 210 | |
| 211 | |
| 212 | def format_rational(value): |
| 213 | """Reduced string: 'a' when integral, else 'p/q' with q > 1 and gcd = 1.""" |
| 214 | # Fraction is always normalised: gcd(|p|, q) = 1 and q > 0. |
| 215 | return str(value) |
| 216 | |
| 217 | |
| 218 | def main(argv): |
| 219 | if len(argv) != 2: |
| 220 | print("usage: python3 count.py <configuration.json>", file=sys.stderr) |
| 221 | return 1 |
| 222 | try: |
| 223 | points = load_configuration(argv[1]) |
| 224 | except Invalid as exc: |
| 225 | print(f"invalid configuration: {exc}", file=sys.stderr) |
| 226 | return 1 |
| 227 | |
| 228 | centres = count_unit_circles(points) |
| 229 | payload = { |
| 230 | "n": len(points), |
| 231 | "unit_circles": len(centres), |
| 232 | "centers": [[format_rational(cx), format_rational(cy)] for cx, cy, _ in centres], |
| 233 | } |
| 234 | sys.stdout.write(json.dumps(payload, separators=(",", ":")) + "\n") |
| 235 | return 0 |
| 236 | |
| 237 | |
| 238 | if __name__ == "__main__": |
| 239 | sys.exit(main(sys.argv)) |