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 | """Self-test for count.py. |
| 3 | |
| 4 | Three layers, all exact: |
| 5 | * the fixture files, through the CLI (exit code, stdout shape, count); |
| 6 | * hand-built adversarial configurations with hand-checked answers; |
| 7 | * a fuzz comparison against an independent O(n^3) reference that computes |
| 8 | the exact circumcentre of every triple and keeps those of radius exactly 1. |
| 9 | |
| 10 | Run: python3 test_count.py |
| 11 | """ |
| 12 | |
| 13 | import importlib.util |
| 14 | import json |
| 15 | import math |
| 16 | import os |
| 17 | import random |
| 18 | import subprocess |
| 19 | import sys |
| 20 | from fractions import Fraction |
| 21 | |
| 22 | if hasattr(sys, "set_int_max_str_digits"): |
| 23 | sys.set_int_max_str_digits(0) |
| 24 | |
| 25 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 26 | COUNT = os.path.join(HERE, "count.py") |
| 27 | # The fixtures live in the route (../..); this checkout is shared with other |
| 28 | # agents and has been switched to another branch mid-run, which removes them |
| 29 | # from the working tree. A byte-identical copy taken from |
| 30 | # origin/rusirui-repro-verifier is kept in ./fixtures and used only as fallback. |
| 31 | REPO_FIXTURES = os.path.abspath(os.path.join(HERE, "..", "..", "fixtures")) |
| 32 | LOCAL_FIXTURES = os.path.join(HERE, "fixtures") |
| 33 | FIXTURES = REPO_FIXTURES if os.path.isdir(REPO_FIXTURES) else LOCAL_FIXTURES |
| 34 | CASES = os.path.join(HERE, "cases") |
| 35 | |
| 36 | failures = [] |
| 37 | |
| 38 | |
| 39 | def check(condition, label, detail=""): |
| 40 | if condition: |
| 41 | return True |
| 42 | failures.append(f"{label}: {detail}" if detail else label) |
| 43 | return False |
| 44 | |
| 45 | |
| 46 | def load_impl(): |
| 47 | spec = importlib.util.spec_from_file_location("count_impl_pairs", COUNT) |
| 48 | module = importlib.util.module_from_spec(spec) |
| 49 | spec.loader.exec_module(module) |
| 50 | return module |
| 51 | |
| 52 | |
| 53 | impl = load_impl() |
| 54 | |
| 55 | |
| 56 | # ---------------------------------------------------------------- reference |
| 57 | |
| 58 | def reference_centres(points): |
| 59 | """Exact centres of all radius-1 circles through >= 3 points, O(n^3). |
| 60 | |
| 61 | Independent of count.py: for every triple it computes the circumcentre by |
| 62 | Cramer's rule on the perpendicular-bisector system (integer arithmetic on |
| 63 | the scaled points) and keeps it when the squared radius is exactly 1. |
| 64 | """ |
| 65 | n = len(points) |
| 66 | scale = 1 |
| 67 | for x, y in points: |
| 68 | scale = scale * x.denominator // math.gcd(scale, x.denominator) |
| 69 | scale = scale * y.denominator // math.gcd(scale, y.denominator) |
| 70 | xs = [int(x * scale) for x, _ in points] |
| 71 | ys = [int(y * scale) for _, y in points] |
| 72 | target = scale * scale |
| 73 | found = set() |
| 74 | for i in range(n): |
| 75 | ax, ay = xs[i], ys[i] |
| 76 | a2 = ax * ax + ay * ay |
| 77 | for j in range(i + 1, n): |
| 78 | bx, by = xs[j], ys[j] |
| 79 | b2 = bx * bx + by * by |
| 80 | for k in range(j + 1, n): |
| 81 | cx, cy = xs[k], ys[k] |
| 82 | d = 2 * ((bx - ax) * (cy - ay) - (by - ay) * (cx - ax)) |
| 83 | if d == 0: |
| 84 | continue |
| 85 | c2 = cx * cx + cy * cy |
| 86 | nx = a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by) |
| 87 | ny = a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax) |
| 88 | # centre = (nx/d, ny/d) in scaled coordinates, i.e. /scale in real ones |
| 89 | if (ax * d - nx) ** 2 + (ay * d - ny) ** 2 == target * d * d: |
| 90 | found.add((Fraction(nx, d * scale), Fraction(ny, d * scale))) |
| 91 | return sorted(found) |
| 92 | |
| 93 | |
| 94 | # ---------------------------------------------------------------------- cli |
| 95 | |
| 96 | def run_cli(path, cwd=None): |
| 97 | return subprocess.run( |
| 98 | [sys.executable, COUNT, path], |
| 99 | capture_output=True, text=True, encoding="utf-8", cwd=cwd, |
| 100 | ) |
| 101 | |
| 102 | |
| 103 | def run_valid(path, cwd=None): |
| 104 | proc = run_cli(path, cwd) |
| 105 | if proc.returncode != 0: |
| 106 | raise AssertionError(f"{path}: expected exit 0, got {proc.returncode}: {proc.stderr!r}") |
| 107 | raw = proc.stdout.strip() |
| 108 | if not raw or "\n" in raw: |
| 109 | raise AssertionError(f"{path}: stdout must be one JSON line, got {proc.stdout!r}") |
| 110 | document = json.loads(raw) |
| 111 | if set(document) != {"n", "unit_circles", "centers"}: |
| 112 | raise AssertionError(f"{path}: unexpected keys {sorted(document)}") |
| 113 | if not isinstance(document["n"], int) or not isinstance(document["unit_circles"], int): |
| 114 | raise AssertionError(f"{path}: n / unit_circles must be JSON integers") |
| 115 | if document["unit_circles"] != len(document["centers"]): |
| 116 | raise AssertionError(f"{path}: unit_circles != len(centers)") |
| 117 | return document |
| 118 | |
| 119 | |
| 120 | def run_invalid(path): |
| 121 | proc = run_cli(path) |
| 122 | if proc.returncode != 1: |
| 123 | return False, f"expected exit 1, got {proc.returncode}" |
| 124 | if proc.stdout != "": |
| 125 | return False, f"expected empty stdout, got {proc.stdout!r}" |
| 126 | if not proc.stderr.strip(): |
| 127 | return False, "expected a reason on stderr" |
| 128 | return True, proc.stderr.strip() |
| 129 | |
| 130 | |
| 131 | def write_case(name, document): |
| 132 | os.makedirs(CASES, exist_ok=True) |
| 133 | path = os.path.join(CASES, name + ".json") |
| 134 | with open(path, "w", encoding="utf-8") as handle: |
| 135 | json.dump(document, handle, indent=2) |
| 136 | handle.write("\n") |
| 137 | return path |
| 138 | |
| 139 | |
| 140 | def config(points, claimed=0, schema=1): |
| 141 | return {"schema": schema, "points": points, "unit_circles": claimed} |
| 142 | |
| 143 | |
| 144 | # ---------------------------------------------------------------- fixtures |
| 145 | |
| 146 | SAMPLE_ACCEPT = ["collinear", "dedup", "grid", "nonunit", "rational-center", "three"] |
| 147 | SAMPLE_REJECT = ["collinear", "duplicate", "float", "nearly-unit", "overcount", "undercount"] |
| 148 | |
| 149 | |
| 150 | def fixture_rows(): |
| 151 | rows = [] |
| 152 | for name in SAMPLE_ACCEPT: |
| 153 | path = os.path.join(FIXTURES, "samples", "accept", name, "configuration.json") |
| 154 | claimed = json.load(open(path, encoding="utf-8"))["unit_circles"] |
| 155 | doc = run_valid(path) |
| 156 | ok = check(doc["unit_circles"] == claimed, f"accept/{name} count", f"{doc['unit_circles']} != {claimed}") |
| 157 | rows.append((os.path.relpath(path, FIXTURES), 0, doc["unit_circles"], claimed, ok)) |
| 158 | for name in SAMPLE_REJECT: |
| 159 | path = os.path.join(FIXTURES, "samples", "reject", name, "configuration.json") |
| 160 | claimed = json.load(open(path, encoding="utf-8"))["unit_circles"] |
| 161 | if name in ("duplicate", "float"): |
| 162 | ok, detail = run_invalid(path) |
| 163 | check(ok, f"reject/{name} invalid", detail) |
| 164 | rows.append((os.path.relpath(path, FIXTURES), 1, "n/a", claimed, ok)) |
| 165 | else: |
| 166 | doc = run_valid(path) |
| 167 | ok = check(doc["unit_circles"] != claimed, f"reject/{name} mismatch", f"{doc['unit_circles']} == {claimed}") |
| 168 | rows.append((os.path.relpath(path, FIXTURES), 0, doc["unit_circles"], claimed, ok)) |
| 169 | path = os.path.join(FIXTURES, "grid80", "configuration.json") |
| 170 | claimed = json.load(open(path, encoding="utf-8"))["unit_circles"] |
| 171 | doc = run_valid(path) |
| 172 | check(doc["n"] == 80, "grid80 n", str(doc["n"])) |
| 173 | rows.append((os.path.relpath(path, FIXTURES), 0, doc["unit_circles"], claimed, True)) |
| 174 | return rows, doc |
| 175 | |
| 176 | |
| 177 | def fixture_crosscheck(grid80_doc): |
| 178 | """Every valid fixture, plus grid80, must match the O(n^3) reference exactly.""" |
| 179 | paths = [] |
| 180 | for name in SAMPLE_ACCEPT: |
| 181 | paths.append(os.path.join(FIXTURES, "samples", "accept", name, "configuration.json")) |
| 182 | for name in ("collinear", "nearly-unit", "overcount", "undercount"): |
| 183 | paths.append(os.path.join(FIXTURES, "samples", "reject", name, "configuration.json")) |
| 184 | paths.append(os.path.join(FIXTURES, "grid80", "configuration.json")) |
| 185 | for path in paths: |
| 186 | document = json.load(open(path, encoding="utf-8")) |
| 187 | points = [(impl._coordinate(p[0], "x"), impl._coordinate(p[1], "y")) for p in document["points"]] |
| 188 | got = [(cx, cy) for cx, cy, _ in impl.count_unit_circles(points)] |
| 189 | want = reference_centres(points) |
| 190 | check(got == want, f"reference mismatch {os.path.basename(os.path.dirname(path))}", |
| 191 | f"{len(got)} vs {len(want)}") |
| 192 | # grid80 through the reference too (82k triples, integer arithmetic) |
| 193 | document = json.load(open(os.path.join(FIXTURES, "grid80", "configuration.json"), encoding="utf-8")) |
| 194 | points = [(Fraction(p[0]), Fraction(p[1])) for p in document["points"]] |
| 195 | want = reference_centres(points) |
| 196 | check(len(want) == grid80_doc["unit_circles"], "grid80 reference", f"{len(want)} != {grid80_doc['unit_circles']}") |
| 197 | |
| 198 | |
| 199 | # ------------------------------------------------------------- adversarial |
| 200 | |
| 201 | def adversarial_cases(): |
| 202 | rows = [] |
| 203 | |
| 204 | def case(name, points, expected_count, expected_centres=None, note=""): |
| 205 | path = write_case(name, config(points, claimed=999)) |
| 206 | doc = run_valid(path) |
| 207 | ok = check(doc["unit_circles"] == expected_count, f"adversarial {name} count", |
| 208 | f"{doc['unit_circles']} != {expected_count}") |
| 209 | if expected_centres is not None: |
| 210 | ok = check(doc["centers"] == expected_centres, f"adversarial {name} centres", |
| 211 | f"{doc['centers']} != {expected_centres}") and ok |
| 212 | # independent reference on the same set |
| 213 | pts = [(impl._coordinate(p[0], "x"), impl._coordinate(p[1], "y")) for p in points] |
| 214 | ref = reference_centres(pts) |
| 215 | ok = check([(cx, cy) for cx, cy, _ in impl.count_unit_circles(pts)] == ref, |
| 216 | f"adversarial {name} reference", f"{len(ref)} circles") and ok |
| 217 | rows.append((name, expected_count, doc["unit_circles"], note, ok)) |
| 218 | return doc |
| 219 | |
| 220 | # A1: eight rational points on one unit circle; two distinct unit circles |
| 221 | # meet in at most two points, so exactly one circle is counted. |
| 222 | case("many-on-one-circle", [ |
| 223 | [1, 0], [0, 1], [-1, 0], [0, -1], |
| 224 | ["3/5", "4/5"], ["-3/5", "4/5"], ["4/5", "3/5"], ["3/5", "-4/5"], |
| 225 | ], 1, [["0", "0"]], "8 cocircular rational points -> 1") |
| 226 | |
| 227 | # A2: a chord of length exactly 2 forces the centre to be the midpoint; |
| 228 | # the two points plus each apex give one circle each way, same centre. |
| 229 | case("diameter-chord", [[0, 0], [2, 0], [1, 1], [1, -1]], 1, [["1", "0"]], |
| 230 | "d2 = 4 branch, centre is the midpoint") |
| 231 | |
| 232 | # A3: three collinear points lie on no circle. |
| 233 | case("three-collinear", [[0, 0], [1, 0], [2, 0]], 0, [], "no circle") |
| 234 | |
| 235 | # A4: unit square. Every triple has circumcentre (1/2,1/2) and radius |
| 236 | # sqrt(2)/2, not 1; the unit circles through (0,0),(1,0) have irrational |
| 237 | # centres and contain no third rational point. |
| 238 | case("unit-square", [[0, 0], [1, 0], [0, 1], [1, 1]], 0, [], |
| 239 | "irrational centres cannot carry three rational points") |
| 240 | |
| 241 | # A5: d2 = 4/5 is not a rational square and 4-d2 = 16/5 is not either, yet |
| 242 | # (4-d2)/d2 = 4 is a square, so the centre is rational. A test that asks |
| 243 | # only whether 4-d2 is a square misses this circle. |
| 244 | case("non-square-chord-rational-centre", |
| 245 | [[0, 0], ["2/5", "4/5"], ["-3/5", "-1/5"]], 1, [["-3/5", "4/5"]], |
| 246 | "centre rational although d2 and 4-d2 are not squares") |
| 247 | |
| 248 | # A6: four points on which each 3-subset has its own unit circle: the two |
| 249 | # unit circles sharing the chord (4/5, +-3/5) and two more through the |
| 250 | # apexes (1,0) and (13/5,0). |
| 251 | case("two-circles-shared-chord", |
| 252 | [["4/5", "3/5"], ["4/5", "-3/5"], [1, 0], ["13/5", 0]], 4, |
| 253 | [["0", "0"], ["8/5", "0"], ["9/5", "-3/5"], ["9/5", "3/5"]], |
| 254 | "four 3-subsets, four centres") |
| 255 | |
| 256 | # A7: the same circle described by non-reduced coordinates everywhere. |
| 257 | case("non-reduced-input", |
| 258 | [["2/2", "0/1"], ["0/1", "3/3"], ["-4/4", "0/1"]], 1, [["0", "0"]], |
| 259 | "coordinates reduced on input") |
| 260 | |
| 261 | # A8: four Pythagorean points on the unit circle centred at (1/5, 1/5). |
| 262 | case("scaled-pythagorean", |
| 263 | [["4/5", 1], [1, "4/5"], ["-2/5", 1], ["4/5", "-3/5"]], 1, |
| 264 | [["1/5", "1/5"]], "circle centre (1/5,1/5)") |
| 265 | |
| 266 | # A9: negative centres print as "-2" and "-7/5" (reduced, sign on top). |
| 267 | case("negative-integral-centre", |
| 268 | [[-1, 3], [-3, 3], [-2, 4], [-2, 2]], 1, [["-2", "3"]], |
| 269 | "integral negative centre") |
| 270 | case("negative-fraction-centre", |
| 271 | [["-4/5", "7/5"], ["-3/5", "6/5"], ["-2/1", "7/5"]], 1, [["-7/5", "3/5"]], |
| 272 | "fractional negative centre") |
| 273 | |
| 274 | return rows |
| 275 | |
| 276 | |
| 277 | # ------------------------------------------------------------------- fuzz |
| 278 | |
| 279 | def lcm(a, b): |
| 280 | return a * b // math.gcd(a, b) |
| 281 | |
| 282 | |
| 283 | def structured_points(rng, centre, how_many, noise): |
| 284 | """Points on the unit circle centred at `centre`, plus random noise.""" |
| 285 | a, b = centre |
| 286 | points = set() |
| 287 | tries = 0 |
| 288 | while len(points) < how_many and tries < 400: |
| 289 | tries += 1 |
| 290 | u = rng.randint(-7, 7) |
| 291 | v = rng.randint(1, 7) |
| 292 | norm = u * u + v * v |
| 293 | px = Fraction(a) + Fraction(v * v - u * u, norm) |
| 294 | py = Fraction(b) + Fraction(2 * u * v, norm) |
| 295 | points.add((px, py)) |
| 296 | while len(points) < how_many + noise: |
| 297 | points.add((Fraction(rng.randint(-6, 6), rng.choice([1, 2, 3, 4])), |
| 298 | Fraction(rng.randint(-6, 6), rng.choice([1, 2, 3, 4])))) |
| 299 | return sorted(points) |
| 300 | |
| 301 | |
| 302 | def fuzz(rounds=200, seed=20261128): |
| 303 | rng = random.Random(seed) |
| 304 | bad = 0 |
| 305 | for round_index in range(rounds): |
| 306 | mode = round_index % 5 |
| 307 | if mode == 0: |
| 308 | n = rng.randint(3, 9) |
| 309 | points = set() |
| 310 | while len(points) < n: |
| 311 | points.add((Fraction(rng.randint(-10, 10), rng.choice([1, 2, 3, 4, 5, 6])), |
| 312 | Fraction(rng.randint(-10, 10), rng.choice([1, 2, 3, 4, 5, 6])))) |
| 313 | points = sorted(points) |
| 314 | elif mode == 1: |
| 315 | centre = (Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3])), |
| 316 | Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3]))) |
| 317 | points = structured_points(rng, centre, rng.randint(3, 6), rng.randint(0, 3)) |
| 318 | elif mode == 2: |
| 319 | # collinear on a rational line: no circles at all |
| 320 | slope = Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3])) |
| 321 | intercept = Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3])) |
| 322 | n = rng.randint(3, 8) |
| 323 | xs = rng.sample(range(-9, 10), n) |
| 324 | points = sorted((Fraction(x), slope * x + intercept) for x in xs) |
| 325 | elif mode == 3: |
| 326 | # lattice points, where many unit circles occur |
| 327 | n = rng.randint(3, 12) |
| 328 | pool = [(Fraction(x), Fraction(y)) for x in range(-4, 5) for y in range(-4, 5)] |
| 329 | points = sorted(rng.sample(pool, n)) |
| 330 | else: |
| 331 | # two structured circles plus noise |
| 332 | c1 = (Fraction(rng.randint(-2, 2)), Fraction(rng.randint(-2, 2))) |
| 333 | c2 = (Fraction(rng.randint(-2, 2), 2), Fraction(rng.randint(-2, 2), 2)) |
| 334 | points = sorted(set(structured_points(rng, c1, rng.randint(3, 5), 1) |
| 335 | + structured_points(rng, c2, rng.randint(3, 5), 1))) |
| 336 | if len(points) < 3: |
| 337 | continue |
| 338 | got = [(cx, cy) for cx, cy, _ in impl.count_unit_circles(points)] |
| 339 | want = reference_centres(points) |
| 340 | if got != want: |
| 341 | bad += 1 |
| 342 | check(False, f"fuzz round {round_index}", f"{len(got)} != {len(want)} on {points}") |
| 343 | if bad > 3: |
| 344 | break |
| 345 | check(bad == 0, "fuzz all rounds", f"{bad} mismatches") |
| 346 | return rounds |
| 347 | |
| 348 | |
| 349 | # --------------------------------------------------------------- validity |
| 350 | |
| 351 | def validity_cases(): |
| 352 | rows = [] |
| 353 | |
| 354 | def invalid(name, document, note=""): |
| 355 | path = write_case(name, document) |
| 356 | ok, detail = run_invalid(path) |
| 357 | check(ok, f"invalid {name}", detail) |
| 358 | rows.append((name, ok, note)) |
| 359 | return ok |
| 360 | |
| 361 | def valid(name, document, expected=None, note=""): |
| 362 | path = write_case(name, document) |
| 363 | try: |
| 364 | doc = run_valid(path) |
| 365 | except AssertionError as exc: |
| 366 | check(False, f"valid {name}", str(exc)) |
| 367 | rows.append((name, False, note)) |
| 368 | return |
| 369 | if expected is not None: |
| 370 | check(doc["unit_circles"] == expected, f"valid {name} count", f"{doc['unit_circles']} != {expected}") |
| 371 | rows.append((name, True, note)) |
| 372 | |
| 373 | valid("minimum-three", config([[0, 0], [1, 0], ["1/2", "0/1"]], 0), 0, "n = 3, distinct and collinear") |
| 374 | invalid("two-points", config([[0, 0], [1, 0]]), "n < 3") |
| 375 | invalid("eighty-one-points", config([[x, 0] for x in range(81)]), "n > 80") |
| 376 | invalid("schema-two", config([[0, 0], [1, 0], [2, 2]], schema=2), "schema != 1") |
| 377 | invalid("schema-float", config([[0, 0], [1, 0], [2, 2]], schema=1.0), "schema 1.0") |
| 378 | invalid("schema-string", config([[0, 0], [1, 0], [2, 2]], schema="1"), "schema '1'") |
| 379 | invalid("schema-bool", config([[0, 0], [1, 0], [2, 2]], schema=True), "schema true") |
| 380 | invalid("top-level-array", [[0, 0], [1, 0], [2, 2]], "not an object") |
| 381 | invalid("float-x", config([[1.0, 0], [0, 1], [-1, 0]]), "JSON float") |
| 382 | invalid("float-y", config([[0, 0], [1, 0], [0, 1.5]]), "JSON float") |
| 383 | invalid("bool-coordinate", config([[0, 0], [1, 0], [True, 2]]), "JSON boolean") |
| 384 | invalid("null-coordinate", config([[0, 0], [1, 0], [None, 2]]), "null") |
| 385 | invalid("decimal-string", config([[0, 0], [1, 0], ["1.5/2", 0]]), "decimal in string") |
| 386 | invalid("exponent-string", config([[0, 0], [1, 0], ["1e3/2", 0]]), "exponent in string") |
| 387 | invalid("whitespace-string", config([[0, 0], [1, 0], [" 1/2", 0]]), "leading space") |
| 388 | invalid("trailing-string", config([[0, 0], [1, 0], ["1/2 ", 0]]), "trailing space") |
| 389 | invalid("zero-denominator", config([[0, 0], [1, 0], ["1/0", 0]]), "q = 0") |
| 390 | invalid("negative-denominator", config([[0, 0], [1, 0], ["1/-2", 0]]), "q < 0") |
| 391 | invalid("plain-integer-string", config([[0, 0], [1, 0], ["2", 0]]), "string not p/q") |
| 392 | invalid("plus-sign", config([[0, 0], [1, 0], ["+1/2", 0]]), "plus sign (rejected)") |
| 393 | invalid("double-slash", config([[0, 0], [1, 0], ["1//2", 0]]), "1//2") |
| 394 | invalid("duplicate-reduced", config([[1, 0], ["2/2", 0], [0, 1]]), "duplicate after reduction") |
| 395 | invalid("duplicate-fraction", config([["1/3", 0], [2, 0], ["2/6", 0], [0, 1]]), "duplicate after reduction") |
| 396 | invalid("point-length-1", config([[0, 0], [1, 0], [2]]), "point with one coordinate") |
| 397 | invalid("point-length-3", config([[0, 0], [1, 0], [2, 2, 2]]), "point with three coordinates") |
| 398 | invalid("point-not-array", config([[0, 0], [1, 0], 7]), "point not an array") |
| 399 | invalid("points-not-array", {"schema": 1, "points": "nope", "unit_circles": 0}, "points not an array") |
| 400 | invalid("missing-points", {"schema": 1, "unit_circles": 0}, "points missing") |
| 401 | |
| 402 | # coordinates beyond CPython's default 4300-digit int-string limit stay exact |
| 403 | huge = int("9" * 5000) |
| 404 | valid("huge-json-integer", config([[0, 0], [1, 0], [huge, 0]], 0), 0, |
| 405 | "5000-digit JSON integer coordinate") |
| 406 | valid("huge-string-fraction", |
| 407 | config([[0, 0], [1, 0], ["1" + "0" * 5000 + "/" + "3" + "0" * 5000, 0]], 0), 0, |
| 408 | "5000-digit fraction string, reduces to 1/3") |
| 409 | |
| 410 | # deeply nested JSON is not a configuration, not a crash |
| 411 | deep = os.path.join(CASES, "deeply-nested.json") |
| 412 | with open(deep, "w", encoding="utf-8") as handle: |
| 413 | handle.write("[" * 5000 + "]" * 5000) |
| 414 | ok, detail = run_invalid(deep) |
| 415 | check(ok, "invalid deeply-nested", detail) |
| 416 | rows.append(("deeply-nested", ok, "recursion guard")) |
| 417 | |
| 418 | # not JSON at all |
| 419 | os.makedirs(CASES, exist_ok=True) |
| 420 | broken = os.path.join(CASES, "broken.json") |
| 421 | with open(broken, "w", encoding="utf-8") as handle: |
| 422 | handle.write("{not json") |
| 423 | ok, detail = run_invalid(broken) |
| 424 | check(ok, "invalid broken-json", detail) |
| 425 | rows.append(("broken-json", ok, "not JSON")) |
| 426 | |
| 427 | missing = os.path.join(CASES, "does-not-exist.json") |
| 428 | if os.path.exists(missing): |
| 429 | os.remove(missing) |
| 430 | ok, detail = run_invalid(missing) |
| 431 | check(ok, "invalid missing-file", detail) |
| 432 | rows.append(("missing-file", ok, "unreadable")) |
| 433 | |
| 434 | # a valid n = 80 configuration and a very large coordinate |
| 435 | points = [[x, y] for x in range(10) for y in range(8)] |
| 436 | valid("eighty-points", config(points, 76), 76, "n = 80 upper bound (same 10x8 grid as grid80)") |
| 437 | valid("huge-coordinates", |
| 438 | config([[0, 0], ["10000000000000000000000000000000001/10000000000000000000000000000000000", 0], [1, 0]], 0), |
| 439 | 0, "big integers stay exact") |
| 440 | |
| 441 | # non-reduced input accepted and reduced on the way out |
| 442 | path = write_case("non-reduced-valid", |
| 443 | config([["10/10", "0/7"], ["0/9", "6/6"], ["-2/2", "0/5"]], 999)) |
| 444 | doc = run_valid(path) |
| 445 | check(doc["centers"] == [["0", "0"]], "non-reduced centres", str(doc["centers"])) |
| 446 | check(doc["unit_circles"] == 1, "non-reduced count", str(doc["unit_circles"])) |
| 447 | rows.append(("non-reduced-valid", True, "(1,0),(0,1),(-1,0) from non-reduced strings")) |
| 448 | |
| 449 | return rows |
| 450 | |
| 451 | |
| 452 | def cwd_cases(): |
| 453 | """count.py must work from any working directory.""" |
| 454 | path = os.path.join(FIXTURES, "samples", "accept", "three", "configuration.json") |
| 455 | ok = True |
| 456 | for cwd in (os.path.abspath(os.path.join(HERE, "..", "..", "..", "..")), os.path.abspath(os.sep)): |
| 457 | try: |
| 458 | doc = run_valid(path, cwd=cwd) |
| 459 | ok = check(doc["unit_circles"] == 1, f"cwd {cwd}", str(doc)) and ok |
| 460 | except AssertionError as exc: |
| 461 | ok = check(False, f"cwd {cwd}", str(exc)) and ok |
| 462 | return ok |
| 463 | |
| 464 | |
| 465 | # ------------------------------------------------------------------- main |
| 466 | |
| 467 | def main(): |
| 468 | print("== fixtures ==") |
| 469 | rows, grid80 = fixture_rows() |
| 470 | for path, code, computed, claimed, ok in rows: |
| 471 | print(f"{path} | {code} | {computed} | {claimed} | {'ok' if ok else 'FAIL'}") |
| 472 | print() |
| 473 | print("== fixture cross-check against O(n^3) circumcentre reference ==") |
| 474 | fixture_crosscheck(grid80) |
| 475 | print("done" if not failures else "FAILED") |
| 476 | print() |
| 477 | print("== adversarial cases ==") |
| 478 | for name, expected, computed, note, ok in adversarial_cases(): |
| 479 | print(f"{name} | expected {expected} | computed {computed} | {'ok' if ok else 'FAIL'} | {note}") |
| 480 | print() |
| 481 | print("== validity cases ==") |
| 482 | for name, ok, note in validity_cases(): |
| 483 | print(f"{name} | {'ok' if ok else 'FAIL'} | {note}") |
| 484 | print() |
| 485 | print("== working directory ==") |
| 486 | cwd_cases() |
| 487 | print("done") |
| 488 | print() |
| 489 | print("== fuzz vs reference ==") |
| 490 | rounds = fuzz() |
| 491 | print(f"{rounds} rounds done") |
| 492 | print() |
| 493 | |
| 494 | if failures: |
| 495 | print(f"FAILURES ({len(failures)}):") |
| 496 | for item in failures: |
| 497 | print(" -", item) |
| 498 | return 1 |
| 499 | print("ALL CHECKS PASSED") |
| 500 | return 0 |
| 501 | |
| 502 | |
| 503 | if __name__ == "__main__": |
| 504 | sys.exit(main()) |