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 | """Independent second implementation, used only to cross-check count.py. |
| 3 | |
| 4 | Usage: python3 altcount.py <configuration.json> |
| 5 | |
| 6 | It answers the same problem with a different algorithm and different parsing |
| 7 | code, so that agreement between the two is evidence about the mathematics and |
| 8 | not about one shared code path. |
| 9 | |
| 10 | Algorithm: enumerate PAIRS instead of triples. Scale the points to integers |
| 11 | (Xi, Yi) with common denominator L as usual, so a unit circle has radius L in |
| 12 | the scaled plane. For a pair with difference (dx, dy) and q = dx^2 + dy^2, |
| 13 | a circle of radius L through both points has its center on the perpendicular |
| 14 | bisector through the midpoint M, at distance sqrt(L^2 - q/4) from M, i.e. |
| 15 | |
| 16 | C = M +- (-dy, dx) * sqrt(4 L^2 - q) / (2 sqrt(q)). |
| 17 | |
| 18 | Writing m = 4 L^2 - q, the offset is rational exactly when m/q is the square |
| 19 | of a rational, that is when m*q is a perfect square, m*q = p^2; then |
| 20 | |
| 21 | C = ( (q*sx -+ dy*p) / (2 q), (q*sy +- dx*p) / (2 q) ), |
| 22 | |
| 23 | where (sx, sy) = 2M is the componentwise sum of the two points. Only these |
| 24 | rational centers can carry three rational points (three rational points have a |
| 25 | rational circumcenter), so this enumeration is complete for the problem; each |
| 26 | surviving center is kept iff at least three of the points satisfy the integer |
| 27 | incidence test (m'*Xi - nx)^2 + (m'*Yi - ny)^2 == (m'*L)^2 after reduction. |
| 28 | """ |
| 29 | |
| 30 | import json |
| 31 | import re |
| 32 | import sys |
| 33 | from functools import cmp_to_key |
| 34 | from math import gcd, isqrt |
| 35 | |
| 36 | USAGE = "usage: python3 altcount.py <configuration.json>" |
| 37 | FRACTION = re.compile(r"[+-]?[0-9]+/[0-9]+") |
| 38 | |
| 39 | |
| 40 | class Invalid(Exception): |
| 41 | pass |
| 42 | |
| 43 | |
| 44 | def parse_coord(value, where): |
| 45 | if type(value) is bool: |
| 46 | raise Invalid(where + ": boolean coordinate") |
| 47 | if type(value) is int: |
| 48 | return (value, 1) |
| 49 | if type(value) is float: |
| 50 | raise Invalid(where + ": floating-point coordinate") |
| 51 | if type(value) is not str: |
| 52 | raise Invalid(where + ": coordinate is not a rational") |
| 53 | if FRACTION.fullmatch(value) is None: |
| 54 | raise Invalid(where + ": %r is not of the form p/q" % (value,)) |
| 55 | p_text, q_text = value.split("/") |
| 56 | p = int(p_text) |
| 57 | q = int(q_text) |
| 58 | if q == 0: |
| 59 | raise Invalid(where + ": zero denominator") |
| 60 | g = gcd(abs(p), q) |
| 61 | return (p // g, q // g) |
| 62 | |
| 63 | |
| 64 | def scale_points(points): |
| 65 | n = len(points) |
| 66 | scale = 1 |
| 67 | for px, py in points: |
| 68 | scale = scale // gcd(scale, px[1]) * px[1] |
| 69 | scale = scale // gcd(scale, py[1]) * py[1] |
| 70 | xs = [px[0] * (scale // px[1]) for px, py in points] |
| 71 | ys = [py[0] * (scale // py[1]) for px, py in points] |
| 72 | return scale, xs, ys |
| 73 | |
| 74 | |
| 75 | def solve(points): |
| 76 | n = len(points) |
| 77 | scale, xs, ys = scale_points(points) |
| 78 | four_l2 = 4 * scale * scale |
| 79 | |
| 80 | candidates = set() |
| 81 | for i in range(n - 1): |
| 82 | xi = xs[i] |
| 83 | yi = ys[i] |
| 84 | for j in range(i + 1, n): |
| 85 | dx = xs[j] - xi |
| 86 | dy = ys[j] - yi |
| 87 | q = dx * dx + dy * dy |
| 88 | if q > four_l2: |
| 89 | continue # farther apart than the diameter |
| 90 | m = four_l2 - q |
| 91 | p = isqrt(m * q) |
| 92 | if p * p != m * q: |
| 93 | continue # both centers irrational |
| 94 | sx = xi + xs[j] |
| 95 | sy = yi + ys[j] |
| 96 | den = 2 * q |
| 97 | for sign in (1, -1): |
| 98 | nx = q * sx - sign * dy * p |
| 99 | ny = q * sy + sign * dx * p |
| 100 | g = gcd(gcd(abs(nx), abs(ny)), den) |
| 101 | nx //= g |
| 102 | ny //= g |
| 103 | den_g = den // g |
| 104 | if den_g < 0: |
| 105 | nx = -nx |
| 106 | ny = -ny |
| 107 | den_g = -den_g |
| 108 | candidates.add((nx, ny, den_g)) |
| 109 | |
| 110 | centers = [] |
| 111 | for nx, ny, den in candidates: |
| 112 | target = den * den * scale * scale |
| 113 | count = 0 |
| 114 | for idx in range(n): |
| 115 | u = den * xs[idx] - nx |
| 116 | v = den * ys[idx] - ny |
| 117 | if u * u + v * v == target: |
| 118 | count += 1 |
| 119 | if count < 3: |
| 120 | continue |
| 121 | total = den * scale |
| 122 | gx = gcd(abs(nx), total) |
| 123 | gy = gcd(abs(ny), total) |
| 124 | centers.append(((nx // gx, total // gx), (ny // gy, total // gy))) |
| 125 | |
| 126 | centers.sort(key=cmp_to_key(compare)) |
| 127 | return centers |
| 128 | |
| 129 | |
| 130 | def compare(left, right): |
| 131 | for axis in (0, 1): |
| 132 | (ln, ld) = left[axis] |
| 133 | (rn, rd) = right[axis] |
| 134 | diff = ln * rd - rn * ld |
| 135 | if diff: |
| 136 | return -1 if diff < 0 else 1 |
| 137 | return 0 |
| 138 | |
| 139 | |
| 140 | def render(pair): |
| 141 | num, den = pair |
| 142 | return str(num) if den == 1 else "%d/%d" % (num, den) |
| 143 | |
| 144 | |
| 145 | def read_points(document): |
| 146 | if not isinstance(document, dict): |
| 147 | raise Invalid("not a JSON object") |
| 148 | schema = document.get("schema") |
| 149 | if type(schema) is not int or schema != 1: |
| 150 | raise Invalid("schema must be 1") |
| 151 | raw = document.get("points") |
| 152 | if not isinstance(raw, list): |
| 153 | raise Invalid("points must be a list") |
| 154 | if not 3 <= len(raw) <= 80: |
| 155 | raise Invalid("need 3 to 80 points") |
| 156 | points = [] |
| 157 | seen = set() |
| 158 | for index, item in enumerate(raw): |
| 159 | if not isinstance(item, list) or len(item) != 2: |
| 160 | raise Invalid("point %d is not a pair" % index) |
| 161 | px = parse_coord(item[0], "point %d x" % index) |
| 162 | py = parse_coord(item[1], "point %d y" % index) |
| 163 | if (px, py) in seen: |
| 164 | raise Invalid("point %d duplicates an earlier point" % index) |
| 165 | seen.add((px, py)) |
| 166 | points.append((px, py)) |
| 167 | return len(points), points |
| 168 | |
| 169 | |
| 170 | def main(argv): |
| 171 | if len(argv) != 2: |
| 172 | sys.stderr.write(USAGE + "\n") |
| 173 | return 1 |
| 174 | try: |
| 175 | with open(argv[1], "rb") as handle: |
| 176 | blob = handle.read() |
| 177 | except OSError as exc: |
| 178 | sys.stderr.write("cannot read %s: %s\n" % (argv[1], exc.strerror or exc)) |
| 179 | return 1 |
| 180 | try: |
| 181 | document = json.loads(blob) |
| 182 | except (ValueError, RecursionError) as exc: |
| 183 | sys.stderr.write("not valid JSON: %s\n" % (exc,)) |
| 184 | return 1 |
| 185 | try: |
| 186 | _, points = read_points(document) |
| 187 | except Invalid as exc: |
| 188 | sys.stderr.write("%s\n" % (exc,)) |
| 189 | return 1 |
| 190 | |
| 191 | centers = solve(points) |
| 192 | sys.stdout.write(json.dumps({ |
| 193 | "n": len(points), |
| 194 | "unit_circles": len(centers), |
| 195 | "centers": [[render(cx), render(cy)] for cx, cy in centers], |
| 196 | }) + "\n") |
| 197 | return 0 |
| 198 | |
| 199 | |
| 200 | if __name__ == "__main__": |
| 201 | sys.exit(main(sys.argv)) |