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}.

Comparing changes
Choose two branches to see what changed, then open a pull request to bring the work across.
Able to merge. These branches can be merged automatically.
A pull request is already open: #8 Independent reproduction of the PR #4 verifier: six exact counters, 151 cases, 39 probes
10 commits
+3 −0 routes/rusirui-repro-verifier/.gitignore added View file
| @@ -0,0 +1,3 @@ | ||
| 1 | +corpus/ | |
| 2 | +__pycache__/ | |
| 3 | +verification.json | |
+180 −0 routes/rusirui-repro-verifier/README.md added View file
| @@ -0,0 +1,180 @@ | ||
| 1 | +--- | |
| 2 | +issue: 5 | |
| 3 | +status: done | |
| 4 | +--- | |
| 5 | + | |
| 6 | +# Independent reproduction of the PR #4 verifier | |
| 7 | + | |
| 8 | +Issue #5 asks for one thing: reproduce the result of pull request #4 with code of | |
| 9 | +my own, then report in a review there. This route does that. The artifact is | |
| 10 | +branch `origin/rusirui-rational-verifier` at `73e7e69`, folder | |
| 11 | +`routes/rusirui-rational-verifier/`; I checked it out in a separate worktree and | |
| 12 | +never modified it. | |
| 13 | + | |
| 14 | +**Verdict: every claim the artifact makes about itself held on this machine.** Its | |
| 15 | +five test methods pass; the CLI gives the documented exit codes and the | |
| 16 | +documented output; the output is byte-identical to `example-verification.json`; | |
| 17 | +the six reject fixtures fail and leave no file; the 80-point grid counts 76 in | |
| 18 | +about a second. Independently written counters agree with it on 138 | |
| 19 | +configurations. Nothing I found blocks merging #4. | |
| 20 | + | |
| 21 | +This is a reproduction of a verifier, not of the problem: it says nothing about | |
| 22 | +whether u(A) = o(n²), and no Shoal check exists to judge either (the root | |
| 23 | +`scienceslack.json` has no `checks`, and `GET .../branches/rusirui-repro-verifier` | |
| 24 | +reports none), so this route's finding is a peer reproduction, not a verdict. | |
| 25 | + | |
| 26 | +## What I ran on the artifact, and what it said | |
| 27 | + | |
| 28 | +Windows 11, Python 3.13.13, Git's POSIX shell, 2026-11-28. Every number below is | |
| 29 | +from a run in this session, not from the artifact's notes. | |
| 30 | + | |
| 31 | +| claim in the artifact's README | what I observed | | |
| 32 | +| --- | --- | | |
| 33 | +| `test_verify.py` passes five methods incl. 60 oracle comparisons | `Ran 5 tests in 0.478s`, `OK`; the five are `test_samples`, `test_independent_oracle`, `test_symmetries_and_witnesses`, `test_cli`, `test_limits`; the oracle loop really is `range(60)` and does not reuse the circumcentre code (side-length/area radius identity + a concyclicity determinant) | | |
| 34 | +| `verify.py` on the route folder → PASS n=9, 5 circles, output identical to `example-verification.json` | exit 0; `PASS: configuration.json: n=9, exact unit circles=5`; output identical **as bytes**, not only as parsed JSON | | |
| 35 | +| each of the six `samples/reject` fixtures → exit 1, no `verification.json` left | all six exit 1 and leave no output, including when a stale output file was planted first; the four with a wrong count are refused with `collinear` 1→0, `nearly-unit` 1→0, `overcount` 4→1, `undercount` 0→1; `duplicate` and `float` are refused as invalid input | | |
| 36 | +| the six `samples/accept` fixtures pass | exit 0 with counts 0, 1, 5, 0, 1, 1 as claimed | | |
| 37 | +| 80-point grid → 76 circles, promptly | 76 circles, 0.94 s; by hand, lattice centres give 8·6 interior + 6+6 on the vertical edges + 8+8 on the horizontal ones = 76, and the exact enumeration finds no non-lattice centre | | |
| 38 | + | |
| 39 | +`ops_probe.py` in this route is the harness: **38 checks matched, 1 skipped**, 0 | |
| 40 | +mismatched ([ops-probe.log](ops-probe.log)). Besides the | |
| 41 | +table above it covers exit 2 for a nonexistent route folder and for | |
| 42 | +`--output` equal to the input (leaving the input intact), `SKIP` on a missing | |
| 43 | +`configuration.json` with no file emitted, duplicate JSON keys, invalid UTF-8, | |
| 44 | +`configuration.json` as a directory, 81 points, a 33-digit coordinate, a file | |
| 45 | +over 128 KiB, a count above the pair bound, and `check.sbatch` itself under | |
| 46 | +Git's POSIX shell (it resolves `verify.py` beside itself, writes | |
| 47 | +`verification.json` in the job's cwd, and passes a wrong-count rejection | |
| 48 | +through). One probe is **not** exercised: the symlinked-`configuration.json` | |
| 49 | +guard, because this Windows account cannot create symlinks. A route directory | |
| 50 | +that is itself a symlink or junction is not guarded at all. | |
| 51 | + | |
| 52 | +### Worst-case cost at the input caps | |
| 53 | + | |
| 54 | +The proposed runner allows `--time=00:02:00` and `--mem=256M`. At n = 80: | |
| 55 | + | |
| 56 | +| input | count | wall time | peak RSS | | |
| 57 | +| --- | --- | --- | --- | | |
| 58 | +| 10×8 grid | 76 | 0.94 s | 17.6 MB | | |
| 59 | +| 80 points on one unit circle | 1 | 1.27 s | 17.7 MB | | |
| 60 | +| 80 random small integers | 0 | 1.00 s | 17.4 MB | | |
| 61 | +| 80 random 32-digit integers | 0 | 1.69 s | 17.5 MB | | |
| 62 | +| 80 random 32-digit fractions | 0 | 9.24 s | 17.4 MB | | |
| 63 | + | |
| 64 | +The last case is ten times the README's 0.9 s figure and is the one a hostile | |
| 65 | +submitter would send, but it is still an order of magnitude inside both limits. | |
| 66 | + | |
| 67 | +## Code of my own, and how it was checked | |
| 68 | + | |
| 69 | +Six counters, each written from the problem statement with the artifact's | |
| 70 | +source off limits, with different algorithms: | |
| 71 | + | |
| 72 | +- `repro.py` — chord construction, O(n²) pairs. A centre on the perpendicular | |
| 73 | + bisector is `m + s·v'`; the radius condition forces | |
| 74 | + `s² = (4 − d2)/(4·d2)`, so a pair yields rational centres exactly when that | |
| 75 | + ratio is a rational square (or `d2 = 4`, giving the midpoint). | |
| 76 | +- `panel/impl-triples/count.py` — triple enumeration with `fractions.Fraction`, | |
| 77 | + Cramer's rule on `2u·d = |u|²`, `2v·d = |v|²`, dedup by exact centre. | |
| 78 | +- `panel/impl-integer/count.py` — integer arithmetic only, no `Fraction`: all | |
| 79 | + points over one denominator `L`, centre as a canonical reduced triple, | |
| 80 | + radius test `P² + Q² = 4D²L²`, incidences recounted with integers. | |
| 81 | +- `panel/impl-integer/altcount.py` — the same author's pair-based integer | |
| 82 | + method, a second code path with different parsing. | |
| 83 | +- `panel/impl-pairs/count.py` — a third pair/chord method, written without | |
| 84 | + seeing `repro.py`. | |
| 85 | +- `panel/impl-circle-equation/count.py` — the circle equation | |
| 86 | + `x²+y²+Dx+Ey+F=0`, radius test `D²+E²−4F=4`, no circumcentre formed. | |
| 87 | + | |
| 88 | +`compare.py` requires every counter to report the same n, the same number of | |
| 89 | +circles and the same set of exact centres (compared as `Fraction`s, not | |
| 90 | +strings), and to reject every invalid input with exit 1 and empty stdout. The | |
| 91 | +corpus is `make_corpus.py`: 138 valid cases — 18 structured, 120 fixed-seed | |
| 92 | +random over small rationals — and 12 invalid inputs, plus one claim-contract | |
| 93 | +case the artifact alone must reject (a counter ignores the claimed count, by | |
| 94 | +design). | |
| 95 | + | |
| 96 | +Result (**[compare.log](compare.log)**): **138/138 valid cases agree** across all | |
| 97 | +six counters and the artifact's own `unit_centers` (imported and used as a | |
| 98 | +seventh opinion), with every centre compared exactly; all 12 invalid inputs are | |
| 99 | +rejected by all six counters; the claim-contract case is rejected by the | |
| 100 | +artifact. Counts for the structured cases were derived by hand, not by code: three, five, eight and ten | |
| 101 | +points on a unit circle → 1; five points on a circle of radius 2 or 3 → 0; a | |
| 102 | +collinear set → 0; the 3×3 grid → 5; the 4×4 grid → 12 and the 5×5 grid → 21 | |
| 103 | +(`(k−2)²` interior centres with four incident points plus `4(k−2)` edge centres | |
| 104 | +with three, none off the lattice); the 10×8 grid → 76; four concyclic points | |
| 105 | +plus one off the circle → 1; three points on a unit circle with centre | |
| 106 | +(1/3, 2/7) → 1; a triangle with circumradius √5/2 → 0; and two unit circles at | |
| 107 | +centres (0,0) and (6/5,0) meeting at (3/5, ±4/5), plus (1,0) and (11/5,0) → 4, | |
| 108 | +not 2: the mixed triples also lie on the unit circles centred (8/5, ±4/5). | |
| 109 | + | |
| 110 | +That last case and one other were errors **in my own work**, caught by the | |
| 111 | +harness: I first expected 2 there, and my first `repro.py` required the chord | |
| 112 | +and the perpendicular height each to be rational, which rejects `(1,0)` and | |
| 113 | +`(0,1)` although their centres are `(0,0)` and `(1,1)`. Only the ratio is | |
| 114 | +rational; `three-on-unit-circle` fails immediately under the wrong test. Both | |
| 115 | +are recorded because a reproduction that never found a mistake in itself is | |
| 116 | +usually not looking hard enough. | |
| 117 | + | |
| 118 | +## The mathematics I re-derived | |
| 119 | + | |
| 120 | +- **Completeness for rational input.** The circumcentre of three non-collinear | |
| 121 | + rational points is rational by Cramer's rule, and a line meets a circle in at | |
| 122 | + most two points, so three points on a unit circle are never collinear and are | |
| 123 | + the circumcentre's own triple. No unit circle through three rational points is | |
| 124 | + lost by working with rational centres only. | |
| 125 | +- **Soundness.** A retained centre satisfies `2u·d = |u|²` and `2v·d = |v|²`, so | |
| 126 | + it is equidistant from all three points; testing the radius against one of | |
| 127 | + them tests all three. | |
| 128 | +- **Dedup.** A unit circle has exactly one centre, and reduced `Fraction` pairs | |
| 129 | + compare exactly, so a set of centres counts each circle once however many of | |
| 130 | + its points are incident — verified on a case with six concyclic points. | |
| 131 | +- **Pair bound.** Each counted circle carries `C(k,2) ≥ 3` pairs for `k ≥ 3` | |
| 132 | + incident points, each pair lies on at most two unit circles, so | |
| 133 | + `3u ≤ 2·C(n,2) = n(n−1)` and `u ≤ n(n−1)/3`; the artifact's use of `n(n−1)//3` | |
| 134 | + as an input guard is sound. | |
| 135 | +- **Cited values.** OEIS A003829 read at oeis.org/A003829 on 2026-11-28 gives | |
| 136 | + `1, 4, 4, 8, 12, 16`, offset 3, "Maximal number of unit circles through n | |
| 137 | + points in plane, each circle containing 3 of the points" — the artifact's | |
| 138 | + citation is right. I did not re-derive Elekes' construction or the | |
| 139 | + Harborth–Mengersen configurations. | |
| 140 | + | |
| 141 | +## Limitations | |
| 142 | + | |
| 143 | +- No Shoal check exists for this project, so nothing here carries a check's | |
| 144 | + verdict; the reproduction is another agent's independent run, which the guide | |
| 145 | + counts as verification, no more. | |
| 146 | +- Windows only: the Linux image, the symlink guard and the route-directory | |
| 147 | + symlink case are untested, and the timing figures are this machine's. | |
| 148 | +- Rational coordinates only, like the artifact; the problem is stated over the | |
| 149 | + reals. | |
| 150 | +- I did not test the input caps' *interaction* (a 128 KiB file full of 32-digit | |
| 151 | + fractions at n=80), only each cap separately. | |
| 152 | + | |
| 153 | +## Reproduce | |
| 154 | + | |
| 155 | +``` | |
| 156 | +git worktree add ../pr4-artifact origin/rusirui-rational-verifier | |
| 157 | +python3 routes/rusirui-repro-verifier/ops_probe.py ../pr4-artifact/routes/rusirui-rational-verifier | |
| 158 | +python3 routes/rusirui-repro-verifier/make_corpus.py /tmp/corpus | |
| 159 | +python3 routes/rusirui-repro-verifier/compare.py --corpus /tmp/corpus \ | |
| 160 | + --artifact ../pr4-artifact/routes/rusirui-rational-verifier \ | |
| 161 | + routes/rusirui-repro-verifier/repro.py \ | |
| 162 | + routes/rusirui-repro-verifier/panel/*/count.py | |
| 163 | +python3 ../pr4-artifact/routes/rusirui-rational-verifier/test_verify.py | |
| 164 | +``` | |
| 165 | + | |
| 166 | +## Sources | |
| 167 | + | |
| 168 | +- T. F. Bloom, [Erdős Problem 104](https://www.erdosproblems.com/104), accessed | |
| 169 | + 2026-11-28. Credit to Erdős Problems for the problem statement. | |
| 170 | +- [OEIS A003829](https://oeis.org/A003829), read 2026-11-28. | |
| 171 | +- Pull request #4, branch `origin/rusirui-rational-verifier` at `73e7e69`. | |
| 172 | + | |
| 173 | +## Next | |
| 174 | + | |
| 175 | +For #4: nothing found that blocks the merge, and the review on the pull request | |
| 176 | +says so. For the maintainer's activation step, the two things this reproduction | |
| 177 | +could not check are the run inside `python:3.12-slim` and the symlink guard; both | |
| 178 | +are one command on a Linux runner. A hostile-submitter probe worth adding is a | |
| 179 | +route directory that is itself a symlink or junction, which `verify.py` does not | |
| 180 | +test for. | |
+5 −0 routes/rusirui-repro-verifier/compare.log added View file
| @@ -0,0 +1,5 @@ | ||
| 1 | + | |
| 2 | +138/138 valid cases agreed across: rusirui-repro-verifier/repro, impl-circle-equation/count, impl-integer/count, impl-pairs/count, impl-triples/count, impl-integer/altcount, pr4 verify.unit_centers | |
| 3 | +12 invalid cases checked for exit 1 and empty stdout | |
| 4 | +1 claim-contract cases checked against the artifact only | |
| 5 | +0 failure(s) | |
+148 −0 routes/rusirui-repro-verifier/compare.py added View file
| @@ -0,0 +1,148 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Differential comparison of several independent exact counters. | |
| 3 | + | |
| 4 | +Usage: | |
| 5 | + python3 compare.py --corpus <dir> [--artifact <route-dir>] <count.py> [<count.py> ...] | |
| 6 | + | |
| 7 | +Every count.py must accept one path to a configuration.json and print | |
| 8 | +{"n": ..., "unit_circles": ..., "centers": [["x","y"], ...]} on one line. | |
| 9 | + | |
| 10 | +For each valid case the script requires: every counter exits 0, reports the | |
| 11 | +same n, the same number of circles and the same set of exact centres; where | |
| 12 | +the corpus carries an independently derived count, the counters must match it. | |
| 13 | +For each invalid case it requires every counter to exit 1 with empty stdout. | |
| 14 | +Exit status 0 only when every requirement held. | |
| 15 | +""" | |
| 16 | +import argparse | |
| 17 | +import importlib.util | |
| 18 | +import json | |
| 19 | +import subprocess | |
| 20 | +import sys | |
| 21 | +from fractions import Fraction | |
| 22 | +from pathlib import Path | |
| 23 | + | |
| 24 | +TIMEOUT = 300 | |
| 25 | +failures = [] | |
| 26 | + | |
| 27 | + | |
| 28 | +def fail(message): | |
| 29 | + failures.append(message) | |
| 30 | + print("FAIL " + message) | |
| 31 | + | |
| 32 | + | |
| 33 | +def exact(value): | |
| 34 | + return Fraction(str(value)) | |
| 35 | + | |
| 36 | + | |
| 37 | +def parse_centres(raw): | |
| 38 | + return sorted((exact(x), exact(y)) for x, y in raw) | |
| 39 | + | |
| 40 | + | |
| 41 | +def run_counter(path, config): | |
| 42 | + proc = subprocess.run([sys.executable, str(path), str(config)], | |
| 43 | + capture_output=True, text=True, timeout=TIMEOUT) | |
| 44 | + return proc.returncode, proc.stdout.strip(), proc.stderr.strip() | |
| 45 | + | |
| 46 | + | |
| 47 | +def load_artifact(route_dir): | |
| 48 | + """Import the artifact's verify.py as a module under a private name.""" | |
| 49 | + spec = importlib.util.spec_from_file_location("pr4_verify", Path(route_dir) / "verify.py") | |
| 50 | + module = importlib.util.module_from_spec(spec) | |
| 51 | + sys.modules["pr4_verify"] = module | |
| 52 | + spec.loader.exec_module(module) | |
| 53 | + return module | |
| 54 | + | |
| 55 | + | |
| 56 | +def main(): | |
| 57 | + parser = argparse.ArgumentParser() | |
| 58 | + parser.add_argument("--corpus", required=True, type=Path) | |
| 59 | + parser.add_argument("--artifact", type=Path, default=None) | |
| 60 | + parser.add_argument("counters", nargs="+", type=Path) | |
| 61 | + args = parser.parse_args() | |
| 62 | + | |
| 63 | + expect = json.loads((args.corpus / "expect.json").read_text()) if (args.corpus / "expect.json").exists() else {} | |
| 64 | + cases = sorted((args.corpus / "cases").iterdir()) | |
| 65 | + invalid = sorted((args.corpus / "invalid").iterdir()) if (args.corpus / "invalid").exists() else [] | |
| 66 | + artifact = load_artifact(args.artifact) if args.artifact else None | |
| 67 | + | |
| 68 | + agreed = 0 | |
| 69 | + for case in cases: | |
| 70 | + config = case / "configuration.json" | |
| 71 | + claims = {} | |
| 72 | + for counter in args.counters: | |
| 73 | + try: | |
| 74 | + rc, out, err = run_counter(counter, config) | |
| 75 | + except subprocess.TimeoutExpired: | |
| 76 | + fail(f"{case.name}: {counter.parent.name + "/" + counter.stem} timed out") | |
| 77 | + continue | |
| 78 | + if rc != 0: | |
| 79 | + fail(f"{case.name}: {counter.parent.name + "/" + counter.stem} exited {rc}: {err.splitlines()[:1]}") | |
| 80 | + continue | |
| 81 | + try: | |
| 82 | + data = json.loads(out) | |
| 83 | + claims[counter.parent.name + "/" + counter.stem] = (data["n"], data["unit_circles"], parse_centres(data["centers"])) | |
| 84 | + except (json.JSONDecodeError, KeyError, ValueError) as exc: | |
| 85 | + fail(f"{case.name}: {counter.parent.name + "/" + counter.stem} printed unusable output ({exc})") | |
| 86 | + | |
| 87 | + if artifact is not None: | |
| 88 | + try: | |
| 89 | + data = json.loads(config.read_text()) | |
| 90 | + points, _ = artifact.parse(data) | |
| 91 | + centres = artifact.unit_centers(points) | |
| 92 | + claims["pr4-verify.unit_centers"] = (len(points), len(centres), parse_centres([[str(x), str(y)] for x, y in centres])) | |
| 93 | + except Exception as exc: # noqa: BLE001 - report anything the artifact raises | |
| 94 | + fail(f"{case.name}: pr4 verify.unit_centers raised {exc!r}") | |
| 95 | + | |
| 96 | + if not claims: | |
| 97 | + continue | |
| 98 | + values = list(claims.values()) | |
| 99 | + if any(v != values[0] for v in values[1:]): | |
| 100 | + detail = "; ".join(f"{name}={v[1]}" for name, v in claims.items()) | |
| 101 | + fail(f"{case.name}: counters disagree ({detail})") | |
| 102 | + continue | |
| 103 | + n, count, _ = values[0] | |
| 104 | + if n != len(json.loads(config.read_text())["points"]): | |
| 105 | + fail(f"{case.name}: reported n={n} does not match the input") | |
| 106 | + continue | |
| 107 | + if expect.get(case.name) is not None and count != expect[case.name]: | |
| 108 | + fail(f"{case.name}: count {count} but hand-derived expectation is {expect[case.name]}") | |
| 109 | + continue | |
| 110 | + agreed += 1 | |
| 111 | + | |
| 112 | + # Claim-contract cases: the artifact validates the claimed count as part of its input | |
| 113 | + # contract; an independent counter ignores that field, so only the artifact is judged. | |
| 114 | + contract = sorted((args.corpus / "contract").iterdir()) if (args.corpus / "contract").exists() else [] | |
| 115 | + for case in contract: | |
| 116 | + if artifact is None: | |
| 117 | + continue | |
| 118 | + proc = subprocess.run([sys.executable, str(Path(args.artifact) / "verify.py"), str(case), | |
| 119 | + "--output", str(args.corpus / "contract-out.json")], | |
| 120 | + capture_output=True, text=True, timeout=TIMEOUT) | |
| 121 | + if proc.returncode != 1: | |
| 122 | + fail(f"contract/{case.name}: artifact exited {proc.returncode}, expected 1") | |
| 123 | + | |
| 124 | + for case in invalid: | |
| 125 | + config = case / "configuration.json" | |
| 126 | + for counter in args.counters: | |
| 127 | + try: | |
| 128 | + rc, out, err = run_counter(counter, config) | |
| 129 | + except subprocess.TimeoutExpired: | |
| 130 | + fail(f"invalid/{case.name}: {counter.parent.name + "/" + counter.stem} timed out") | |
| 131 | + continue | |
| 132 | + name = counter.parent.name + "/" + counter.stem | |
| 133 | + if rc != 1: | |
| 134 | + fail(f"invalid/{case.name}: {name} exited {rc}, expected 1") | |
| 135 | + elif out: | |
| 136 | + fail(f"invalid/{case.name}: {name} printed to stdout on rejection") | |
| 137 | + | |
| 138 | + names = ", ".join(c.parent.name + "/" + c.stem for c in args.counters) + (", pr4 verify.unit_centers" if artifact else "") | |
| 139 | + print(f"\n{agreed}/{len(cases)} valid cases agreed across: {names}") | |
| 140 | + print(f"{len(invalid)} invalid cases checked for exit 1 and empty stdout") | |
| 141 | + if contract: | |
| 142 | + print(f"{len(contract)} claim-contract cases checked against the artifact only") | |
| 143 | + print(f"{len(failures)} failure(s)") | |
| 144 | + return 0 if not failures else 1 | |
| 145 | + | |
| 146 | + | |
| 147 | +if __name__ == "__main__": | |
| 148 | + sys.exit(main()) | |
+326 −0 routes/rusirui-repro-verifier/fixtures/grid80/configuration.json added View file
| @@ -0,0 +1,326 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 0, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + 1, | |
| 10 | + 0 | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + 2, | |
| 14 | + 0 | |
| 15 | + ], | |
| 16 | + [ | |
| 17 | + 3, | |
| 18 | + 0 | |
| 19 | + ], | |
| 20 | + [ | |
| 21 | + 4, | |
| 22 | + 0 | |
| 23 | + ], | |
| 24 | + [ | |
| 25 | + 5, | |
| 26 | + 0 | |
| 27 | + ], | |
| 28 | + [ | |
| 29 | + 6, | |
| 30 | + 0 | |
| 31 | + ], | |
| 32 | + [ | |
| 33 | + 7, | |
| 34 | + 0 | |
| 35 | + ], | |
| 36 | + [ | |
| 37 | + 8, | |
| 38 | + 0 | |
| 39 | + ], | |
| 40 | + [ | |
| 41 | + 9, | |
| 42 | + 0 | |
| 43 | + ], | |
| 44 | + [ | |
| 45 | + 0, | |
| 46 | + 1 | |
| 47 | + ], | |
| 48 | + [ | |
| 49 | + 1, | |
| 50 | + 1 | |
| 51 | + ], | |
| 52 | + [ | |
| 53 | + 2, | |
| 54 | + 1 | |
| 55 | + ], | |
| 56 | + [ | |
| 57 | + 3, | |
| 58 | + 1 | |
| 59 | + ], | |
| 60 | + [ | |
| 61 | + 4, | |
| 62 | + 1 | |
| 63 | + ], | |
| 64 | + [ | |
| 65 | + 5, | |
| 66 | + 1 | |
| 67 | + ], | |
| 68 | + [ | |
| 69 | + 6, | |
| 70 | + 1 | |
| 71 | + ], | |
| 72 | + [ | |
| 73 | + 7, | |
| 74 | + 1 | |
| 75 | + ], | |
| 76 | + [ | |
| 77 | + 8, | |
| 78 | + 1 | |
| 79 | + ], | |
| 80 | + [ | |
| 81 | + 9, | |
| 82 | + 1 | |
| 83 | + ], | |
| 84 | + [ | |
| 85 | + 0, | |
| 86 | + 2 | |
| 87 | + ], | |
| 88 | + [ | |
| 89 | + 1, | |
| 90 | + 2 | |
| 91 | + ], | |
| 92 | + [ | |
| 93 | + 2, | |
| 94 | + 2 | |
| 95 | + ], | |
| 96 | + [ | |
| 97 | + 3, | |
| 98 | + 2 | |
| 99 | + ], | |
| 100 | + [ | |
| 101 | + 4, | |
| 102 | + 2 | |
| 103 | + ], | |
| 104 | + [ | |
| 105 | + 5, | |
| 106 | + 2 | |
| 107 | + ], | |
| 108 | + [ | |
| 109 | + 6, | |
| 110 | + 2 | |
| 111 | + ], | |
| 112 | + [ | |
| 113 | + 7, | |
| 114 | + 2 | |
| 115 | + ], | |
| 116 | + [ | |
| 117 | + 8, | |
| 118 | + 2 | |
| 119 | + ], | |
| 120 | + [ | |
| 121 | + 9, | |
| 122 | + 2 | |
| 123 | + ], | |
| 124 | + [ | |
| 125 | + 0, | |
| 126 | + 3 | |
| 127 | + ], | |
| 128 | + [ | |
| 129 | + 1, | |
| 130 | + 3 | |
| 131 | + ], | |
| 132 | + [ | |
| 133 | + 2, | |
| 134 | + 3 | |
| 135 | + ], | |
| 136 | + [ | |
| 137 | + 3, | |
| 138 | + 3 | |
| 139 | + ], | |
| 140 | + [ | |
| 141 | + 4, | |
| 142 | + 3 | |
| 143 | + ], | |
| 144 | + [ | |
| 145 | + 5, | |
| 146 | + 3 | |
| 147 | + ], | |
| 148 | + [ | |
| 149 | + 6, | |
| 150 | + 3 | |
| 151 | + ], | |
| 152 | + [ | |
| 153 | + 7, | |
| 154 | + 3 | |
| 155 | + ], | |
| 156 | + [ | |
| 157 | + 8, | |
| 158 | + 3 | |
| 159 | + ], | |
| 160 | + [ | |
| 161 | + 9, | |
| 162 | + 3 | |
| 163 | + ], | |
| 164 | + [ | |
| 165 | + 0, | |
| 166 | + 4 | |
| 167 | + ], | |
| 168 | + [ | |
| 169 | + 1, | |
| 170 | + 4 | |
| 171 | + ], | |
| 172 | + [ | |
| 173 | + 2, | |
| 174 | + 4 | |
| 175 | + ], | |
| 176 | + [ | |
| 177 | + 3, | |
| 178 | + 4 | |
| 179 | + ], | |
| 180 | + [ | |
| 181 | + 4, | |
| 182 | + 4 | |
| 183 | + ], | |
| 184 | + [ | |
| 185 | + 5, | |
| 186 | + 4 | |
| 187 | + ], | |
| 188 | + [ | |
| 189 | + 6, | |
| 190 | + 4 | |
| 191 | + ], | |
| 192 | + [ | |
| 193 | + 7, | |
| 194 | + 4 | |
| 195 | + ], | |
| 196 | + [ | |
| 197 | + 8, | |
| 198 | + 4 | |
| 199 | + ], | |
| 200 | + [ | |
| 201 | + 9, | |
| 202 | + 4 | |
| 203 | + ], | |
| 204 | + [ | |
| 205 | + 0, | |
| 206 | + 5 | |
| 207 | + ], | |
| 208 | + [ | |
| 209 | + 1, | |
| 210 | + 5 | |
| 211 | + ], | |
| 212 | + [ | |
| 213 | + 2, | |
| 214 | + 5 | |
| 215 | + ], | |
| 216 | + [ | |
| 217 | + 3, | |
| 218 | + 5 | |
| 219 | + ], | |
| 220 | + [ | |
| 221 | + 4, | |
| 222 | + 5 | |
| 223 | + ], | |
| 224 | + [ | |
| 225 | + 5, | |
| 226 | + 5 | |
| 227 | + ], | |
| 228 | + [ | |
| 229 | + 6, | |
| 230 | + 5 | |
| 231 | + ], | |
| 232 | + [ | |
| 233 | + 7, | |
| 234 | + 5 | |
| 235 | + ], | |
| 236 | + [ | |
| 237 | + 8, | |
| 238 | + 5 | |
| 239 | + ], | |
| 240 | + [ | |
| 241 | + 9, | |
| 242 | + 5 | |
| 243 | + ], | |
| 244 | + [ | |
| 245 | + 0, | |
| 246 | + 6 | |
| 247 | + ], | |
| 248 | + [ | |
| 249 | + 1, | |
| 250 | + 6 | |
| 251 | + ], | |
| 252 | + [ | |
| 253 | + 2, | |
| 254 | + 6 | |
| 255 | + ], | |
| 256 | + [ | |
| 257 | + 3, | |
| 258 | + 6 | |
| 259 | + ], | |
| 260 | + [ | |
| 261 | + 4, | |
| 262 | + 6 | |
| 263 | + ], | |
| 264 | + [ | |
| 265 | + 5, | |
| 266 | + 6 | |
| 267 | + ], | |
| 268 | + [ | |
| 269 | + 6, | |
| 270 | + 6 | |
| 271 | + ], | |
| 272 | + [ | |
| 273 | + 7, | |
| 274 | + 6 | |
| 275 | + ], | |
| 276 | + [ | |
| 277 | + 8, | |
| 278 | + 6 | |
| 279 | + ], | |
| 280 | + [ | |
| 281 | + 9, | |
| 282 | + 6 | |
| 283 | + ], | |
| 284 | + [ | |
| 285 | + 0, | |
| 286 | + 7 | |
| 287 | + ], | |
| 288 | + [ | |
| 289 | + 1, | |
| 290 | + 7 | |
| 291 | + ], | |
| 292 | + [ | |
| 293 | + 2, | |
| 294 | + 7 | |
| 295 | + ], | |
| 296 | + [ | |
| 297 | + 3, | |
| 298 | + 7 | |
| 299 | + ], | |
| 300 | + [ | |
| 301 | + 4, | |
| 302 | + 7 | |
| 303 | + ], | |
| 304 | + [ | |
| 305 | + 5, | |
| 306 | + 7 | |
| 307 | + ], | |
| 308 | + [ | |
| 309 | + 6, | |
| 310 | + 7 | |
| 311 | + ], | |
| 312 | + [ | |
| 313 | + 7, | |
| 314 | + 7 | |
| 315 | + ], | |
| 316 | + [ | |
| 317 | + 8, | |
| 318 | + 7 | |
| 319 | + ], | |
| 320 | + [ | |
| 321 | + 9, | |
| 322 | + 7 | |
| 323 | + ] | |
| 324 | + ], | |
| 325 | + "unit_circles": 76 | |
| 326 | +} | |
+18 −0 routes/rusirui-repro-verifier/fixtures/samples/accept/collinear/configuration.json added View file
| @@ -0,0 +1,18 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 0, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + 1, | |
| 10 | + 0 | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + 2, | |
| 14 | + 0 | |
| 15 | + ] | |
| 16 | + ], | |
| 17 | + "unit_circles": 0 | |
| 18 | +} | |
+26 −0 routes/rusirui-repro-verifier/fixtures/samples/accept/dedup/configuration.json added View file
| @@ -0,0 +1,26 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 1, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + 0, | |
| 10 | + 1 | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + -1, | |
| 14 | + 0 | |
| 15 | + ], | |
| 16 | + [ | |
| 17 | + 0, | |
| 18 | + -1 | |
| 19 | + ], | |
| 20 | + [ | |
| 21 | + "3/5", | |
| 22 | + "4/5" | |
| 23 | + ] | |
| 24 | + ], | |
| 25 | + "unit_circles": 1 | |
| 26 | +} | |
+42 −0 routes/rusirui-repro-verifier/fixtures/samples/accept/grid/configuration.json added View file
| @@ -0,0 +1,42 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 0, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + 0, | |
| 10 | + 1 | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + 0, | |
| 14 | + 2 | |
| 15 | + ], | |
| 16 | + [ | |
| 17 | + 1, | |
| 18 | + 0 | |
| 19 | + ], | |
| 20 | + [ | |
| 21 | + 1, | |
| 22 | + 1 | |
| 23 | + ], | |
| 24 | + [ | |
| 25 | + 1, | |
| 26 | + 2 | |
| 27 | + ], | |
| 28 | + [ | |
| 29 | + 2, | |
| 30 | + 0 | |
| 31 | + ], | |
| 32 | + [ | |
| 33 | + 2, | |
| 34 | + 1 | |
| 35 | + ], | |
| 36 | + [ | |
| 37 | + 2, | |
| 38 | + 2 | |
| 39 | + ] | |
| 40 | + ], | |
| 41 | + "unit_circles": 5 | |
| 42 | +} | |
+18 −0 routes/rusirui-repro-verifier/fixtures/samples/accept/nonunit/configuration.json added View file
| @@ -0,0 +1,18 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 0, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + 1, | |
| 10 | + 0 | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + 0, | |
| 14 | + 1 | |
| 15 | + ] | |
| 16 | + ], | |
| 17 | + "unit_circles": 0 | |
| 18 | +} | |
+18 −0 routes/rusirui-repro-verifier/fixtures/samples/accept/rational-center/configuration.json added View file
| @@ -0,0 +1,18 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + "4/3", | |
| 6 | + "2/7" | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + "1/3", | |
| 10 | + "9/7" | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + "-2/3", | |
| 14 | + "2/7" | |
| 15 | + ] | |
| 16 | + ], | |
| 17 | + "unit_circles": 1 | |
| 18 | +} | |
+18 −0 routes/rusirui-repro-verifier/fixtures/samples/accept/three/configuration.json added View file
| @@ -0,0 +1,18 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 1, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + 0, | |
| 10 | + 1 | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + -1, | |
| 14 | + 0 | |
| 15 | + ] | |
| 16 | + ], | |
| 17 | + "unit_circles": 1 | |
| 18 | +} | |
+18 −0 routes/rusirui-repro-verifier/fixtures/samples/reject/collinear/configuration.json added View file
| @@ -0,0 +1,18 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 0, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + 1, | |
| 10 | + 0 | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + 2, | |
| 14 | + 0 | |
| 15 | + ] | |
| 16 | + ], | |
| 17 | + "unit_circles": 1 | |
| 18 | +} | |
+18 −0 routes/rusirui-repro-verifier/fixtures/samples/reject/duplicate/configuration.json added View file
| @@ -0,0 +1,18 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 1, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + "2/2", | |
| 10 | + 0 | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + 0, | |
| 14 | + 1 | |
| 15 | + ] | |
| 16 | + ], | |
| 17 | + "unit_circles": 1 | |
| 18 | +} | |
+18 −0 routes/rusirui-repro-verifier/fixtures/samples/reject/float/configuration.json added View file
| @@ -0,0 +1,18 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 1.0, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + 0, | |
| 10 | + 1 | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + -1, | |
| 14 | + 0 | |
| 15 | + ] | |
| 16 | + ], | |
| 17 | + "unit_circles": 1 | |
| 18 | +} | |
+18 −0 routes/rusirui-repro-verifier/fixtures/samples/reject/nearly-unit/configuration.json added View file
| @@ -0,0 +1,18 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 1, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + 0, | |
| 10 | + "10000000000000001/10000000000000000" | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + -1, | |
| 14 | + 0 | |
| 15 | + ] | |
| 16 | + ], | |
| 17 | + "unit_circles": 1 | |
| 18 | +} | |
+22 −0 routes/rusirui-repro-verifier/fixtures/samples/reject/overcount/configuration.json added View file
| @@ -0,0 +1,22 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 1, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + 0, | |
| 10 | + 1 | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + -1, | |
| 14 | + 0 | |
| 15 | + ], | |
| 16 | + [ | |
| 17 | + 0, | |
| 18 | + -1 | |
| 19 | + ] | |
| 20 | + ], | |
| 21 | + "unit_circles": 4 | |
| 22 | +} | |
+18 −0 routes/rusirui-repro-verifier/fixtures/samples/reject/undercount/configuration.json added View file
| @@ -0,0 +1,18 @@ | ||
| 1 | +{ | |
| 2 | + "schema": 1, | |
| 3 | + "points": [ | |
| 4 | + [ | |
| 5 | + 1, | |
| 6 | + 0 | |
| 7 | + ], | |
| 8 | + [ | |
| 9 | + 0, | |
| 10 | + 1 | |
| 11 | + ], | |
| 12 | + [ | |
| 13 | + -1, | |
| 14 | + 0 | |
| 15 | + ] | |
| 16 | + ], | |
| 17 | + "unit_circles": 0 | |
| 18 | +} | |
+145 −0 routes/rusirui-repro-verifier/make_corpus.py added View file
| @@ -0,0 +1,145 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Write a deterministic corpus of configurations for differential testing. | |
| 3 | + | |
| 4 | +Usage: python3 make_corpus.py <target-dir> | |
| 5 | + | |
| 6 | +Layout produced: | |
| 7 | + <target>/cases/<name>/configuration.json valid input for a counter | |
| 8 | + <target>/invalid/<name>/configuration.json input a strict counter must reject | |
| 9 | + <target>/expect.json hand-derived counts for the structured cases | |
| 10 | + ("null" means: only agreement between counters is | |
| 11 | + required, no independent expected value) | |
| 12 | +The random cases use a fixed seed, so two runs produce identical files. | |
| 13 | +""" | |
| 14 | +import json | |
| 15 | +import random | |
| 16 | +import sys | |
| 17 | +from fractions import Fraction | |
| 18 | +from pathlib import Path | |
| 19 | + | |
| 20 | + | |
| 21 | +def num(value): | |
| 22 | + """Render an exact Fraction as JSON int (integral) or "p/q" string.""" | |
| 23 | + value = Fraction(value) | |
| 24 | + if value.denominator == 1: | |
| 25 | + return int(value) | |
| 26 | + return f"{value.numerator}/{value.denominator}" | |
| 27 | + | |
| 28 | + | |
| 29 | +def put(folder, points, claimed=0, schema=1): | |
| 30 | + folder.mkdir(parents=True, exist_ok=True) | |
| 31 | + data = {"schema": schema, "points": [[num(x), num(y)] for x, y in points], "unit_circles": claimed} | |
| 32 | + (folder / "configuration.json").write_text(json.dumps(data) + "\n") | |
| 33 | + return data | |
| 34 | + | |
| 35 | + | |
| 36 | +def on_unit_circle(k, offset=(0, 0)): | |
| 37 | + """k rational points on the unit circle centred at offset (Pythagorean parametrisation).""" | |
| 38 | + ts = [Fraction(0), Fraction(1, 2), Fraction(1), Fraction(2), Fraction(3), Fraction(-1, 2), | |
| 39 | + Fraction(-1), Fraction(5, 2), Fraction(1, 3), Fraction(3, 5), Fraction(-2, 3)] | |
| 40 | + ts = ts[:k] | |
| 41 | + ox, oy = Fraction(offset[0]), Fraction(offset[1]) | |
| 42 | + return [((1 - t * t) / (1 + t * t) + ox, 2 * t / (1 + t * t) + oy) for t in ts] | |
| 43 | + | |
| 44 | + | |
| 45 | +def on_radius_circle(k, radius, offset=(0, 0)): | |
| 46 | + ox, oy = Fraction(offset[0]), Fraction(offset[1]) | |
| 47 | + return [(radius * x + ox, radius * y + oy) for x, y in on_unit_circle(k)] | |
| 48 | + | |
| 49 | + | |
| 50 | +def main(): | |
| 51 | + if len(sys.argv) != 2: | |
| 52 | + print(__doc__.strip().splitlines()[2], file=sys.stderr) | |
| 53 | + return 2 | |
| 54 | + root = Path(sys.argv[1]) | |
| 55 | + cases = root / "cases" | |
| 56 | + invalid = root / "invalid" | |
| 57 | + expect = {} | |
| 58 | + | |
| 59 | + def case(name, points, claimed, independent): | |
| 60 | + put(cases / name, points, claimed) | |
| 61 | + expect[name] = independent | |
| 62 | + | |
| 63 | + # --- structured cases, expectations derived by hand ------------------------- | |
| 64 | + case("three-on-unit-circle", on_unit_circle(3), 1, 1) | |
| 65 | + case("five-on-unit-circle", on_unit_circle(5), 1, 1) | |
| 66 | + case("eight-on-unit-circle", on_unit_circle(8), 1, 1) | |
| 67 | + case("ten-on-unit-circle", on_unit_circle(10), 1, 1) | |
| 68 | + case("five-on-radius-2", on_radius_circle(5, 2), 0, 0) | |
| 69 | + case("five-on-radius-3-shifted", on_radius_circle(5, 3, (1, -2)), 0, 0) | |
| 70 | + case("three-collinear", [(0, 0), (1, 0), (2, 0)], 0, 0) | |
| 71 | + case("five-collinear", [(i, 3) for i in range(5)], 0, 0) | |
| 72 | + case("grid-2x2", [(x, y) for y in range(2) for x in range(2)], 0, 0) | |
| 73 | + case("grid-3x3", [(x, y) for y in range(3) for x in range(3)], 5, 5) | |
| 74 | + # A k-by-k lattice has (k-2)^2 interior centres with four incident points and | |
| 75 | + # 4(k-2) edge centres with three; corner centres have only two and are not counted. | |
| 76 | + # The exact enumeration finds no centre off the lattice, so these counts are exact: | |
| 77 | + # k=4 gives 4 + 8 = 12 and k=5 gives 9 + 12 = 21. | |
| 78 | + case("grid-4x4", [(x, y) for y in range(4) for x in range(4)], 12, 12) | |
| 79 | + case("grid-5x5", [(x, y) for y in range(5) for x in range(5)], 21, 21) | |
| 80 | + case("grid-10x8", [(x, y) for y in range(8) for x in range(10)], 76, 76) | |
| 81 | + # Two unit circles at centres 0 and 6/5 meet at (3/5, +/-4/5). Adding (1,0) and (11/5,0) | |
| 82 | + # gives four unit circles, one per triple: centres (0,0) and (6/5,0) each carry three of | |
| 83 | + # them, and the mixed triples {(3/5,4/5),(1,0),(11/5,0)} and {(3/5,-4/5),(1,0),(11/5,0)} | |
| 84 | + # lie on the unit circles centred (8/5,4/5) and (8/5,-4/5). Derived by hand, not by code. | |
| 85 | + case("two-crossing-unit-circles", | |
| 86 | + [(Fraction(3, 5), Fraction(4, 5)), (Fraction(3, 5), Fraction(-4, 5)), (1, 0), (Fraction(11, 5), 0)], | |
| 87 | + 4, 4) | |
| 88 | + # Four concyclic plus one off the circle: still one circle, counted once. | |
| 89 | + case("four-concyclic-plus-one", on_unit_circle(4) + [(3, 3)], 1, 1) | |
| 90 | + # A pair exactly distance 2 apart (centres coincide) plus a third point elsewhere. | |
| 91 | + case("tangent-pair-distance-2", [(0, 0), (2, 0), (5, 5)], 0, 0) | |
| 92 | + # Three points on a circle of radius 1 but with rational centre not at the origin. | |
| 93 | + case("shifted-unit-circle", on_unit_circle(4, (Fraction(1, 3), Fraction(2, 7))), 1, 1) | |
| 94 | + # Circumcircle has centre (1/2, 1) and radius sqrt(5)/2, not 1, so no unit circle exists. | |
| 95 | + case("half-centre-nonunit", [(0, 0), (1, 0), (0, 2)], 0, 0) | |
| 96 | + | |
| 97 | + # --- fixed-seed random cases ------------------------------------------------ | |
| 98 | + rng = random.Random(20261128) | |
| 99 | + values = [Fraction(i) for i in range(-3, 4)] + [Fraction(p, q) for q in (2, 3, 5, 7) for p in range(-4, 5)] | |
| 100 | + for trial in range(120): | |
| 101 | + n = rng.randint(3, 12) | |
| 102 | + points = [] | |
| 103 | + seen = set() | |
| 104 | + while len(points) < n: | |
| 105 | + x = rng.choice(values) | |
| 106 | + y = rng.choice(values) | |
| 107 | + if (x, y) in seen: | |
| 108 | + continue | |
| 109 | + seen.add((x, y)) | |
| 110 | + points.append((x, y)) | |
| 111 | + case(f"random-{trial:03d}", points, 0, None) | |
| 112 | + | |
| 113 | + # --- inputs a strict counter must reject ------------------------------------- | |
| 114 | + contract = root / "contract" | |
| 115 | + | |
| 116 | + def bad(name, data, bucket=None): | |
| 117 | + bucket = bucket or invalid | |
| 118 | + bucket.mkdir(parents=True, exist_ok=True) | |
| 119 | + (bucket / name).mkdir(exist_ok=True) | |
| 120 | + (bucket / name / "configuration.json").write_text(json.dumps(data) + "\n") | |
| 121 | + | |
| 122 | + good = {"schema": 1, "points": [[1, 0], [0, 1], [-1, 0]], "unit_circles": 1} | |
| 123 | + bad("float-coordinate", {**good, "points": [[1.0, 0], [0, 1], [-1, 0]]}) | |
| 124 | + bad("boolean-coordinate", {**good, "points": [[True, 0], [0, 1], [-1, 0]]}) | |
| 125 | + bad("decimal-string", {**good, "points": [["1.0", 0], [0, 1], [-1, 0]]}) | |
| 126 | + bad("exponent-string", {**good, "points": [["1e0", 0], [0, 1], [-1, 0]]}) | |
| 127 | + bad("zero-denominator", {**good, "points": [["1/0", 0], [0, 1], [-1, 0]]}) | |
| 128 | + bad("negative-denominator", {**good, "points": [["1/-2", 0], [0, 1], ([-1, 0])]}) | |
| 129 | + bad("33-digit-numerator", {**good, "points": [["1" + "0" * 32, 0], [0, 1], [-1, 0]]}) | |
| 130 | + bad("duplicate-points", {**good, "points": [[1, 0], ["2/2", 0], [0, 1]]}) | |
| 131 | + bad("two-points", {**good, "points": [[1, 0], [0, 1]]}) | |
| 132 | + bad("eighty-one-points", {**good, "points": [[i, 0] for i in range(81)]}) | |
| 133 | + bad("schema-2", {**good, "schema": 2}) | |
| 134 | + # A counter ignores the claimed count, so only the artifact's input contract rejects this. | |
| 135 | + bad("missing-unit-circles", {"schema": 1, "points": [[1, 0], [0, 1], [-1, 0]]}, bucket=contract) | |
| 136 | + bad("point-not-a-pair", {**good, "points": [[1, 0, 0], [0, 1], [-1, 0]]}) | |
| 137 | + | |
| 138 | + (root / "expect.json").write_text(json.dumps(expect, indent=2, sort_keys=True) + "\n") | |
| 139 | + print(f"wrote {len(expect)} valid, {len(list(invalid.iterdir()))} invalid and " | |
| 140 | + f"{len(list(contract.iterdir()))} claim-contract cases to {root}") | |
| 141 | + return 0 | |
| 142 | + | |
| 143 | + | |
| 144 | +if __name__ == "__main__": | |
| 145 | + sys.exit(main()) | |
+43 −0 routes/rusirui-repro-verifier/ops-probe.log added View file
| @@ -0,0 +1,43 @@ | ||
| 1 | +OK route folder exits 0 | |
| 2 | +OK route folder prints PASS n=9 / 5 | |
| 3 | +OK output equals example-verification.json (parsed) | |
| 4 | +OK output equals example-verification.json (bytes) | |
| 5 | +OK accept/collinear exits 0 with 0 | |
| 6 | +OK accept/dedup exits 0 with 1 | |
| 7 | +OK accept/grid exits 0 with 5 | |
| 8 | +OK accept/nonunit exits 0 with 0 | |
| 9 | +OK accept/rational-center exits 0 with 1 | |
| 10 | +OK accept/three exits 0 with 1 | |
| 11 | +OK reject/collinear exits 1 and leaves no output | |
| 12 | +OK reject/collinear printed no PASS | |
| 13 | +OK reject/duplicate exits 1 and leaves no output | |
| 14 | +OK reject/duplicate printed no PASS | |
| 15 | +OK reject/float exits 1 and leaves no output | |
| 16 | +OK reject/float printed no PASS | |
| 17 | +OK reject/nearly-unit exits 1 and leaves no output | |
| 18 | +OK reject/nearly-unit printed no PASS | |
| 19 | +OK reject/overcount exits 1 and leaves no output | |
| 20 | +OK reject/overcount printed no PASS | |
| 21 | +OK reject/undercount exits 1 and leaves no output | |
| 22 | +OK reject/undercount printed no PASS | |
| 23 | +OK missing configuration.json exits 0 with SKIP | |
| 24 | +OK nonexistent route folder exits 2 | |
| 25 | +OK output == input exits 2 | |
| 26 | +OK output == input left configuration.json intact | |
| 27 | +OK duplicate JSON key exits 1 | |
| 28 | +OK invalid UTF-8 exits 1 | |
| 29 | +OK configuration.json as directory exits 1 | |
| 30 | +OK 81 points exits 1 | |
| 31 | +OK 33-digit coordinate exits 1 | |
| 32 | +OK file over 128 KiB exits 1 | |
| 33 | +OK count over the pair bound exits 1 | |
| 34 | +OK grid80 exits 0 | |
| 35 | +OK grid80 counts 76 | |
| 36 | + grid80 wall time: 0.961s | |
| 37 | +OK check.sbatch accepts a valid route (exit 0) | |
| 38 | +OK check.sbatch wrote verification.json in its cwd | |
| 39 | +OK check.sbatch rejects a wrong count (exit 1) | |
| 40 | + check.sbatch shebang: #!/bin/sh | |
| 41 | +SKIP symlinked configuration.json: cannot create symlink (OSError) | |
| 42 | + | |
| 43 | +38 matched, 1 skipped, 0 did not match the artifact's documented claim | |
+194 −0 routes/rusirui-repro-verifier/ops_probe.py added View file
| @@ -0,0 +1,194 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Operational probes for the verifier proposed in pull request #4. | |
| 3 | + | |
| 4 | +Usage: python3 ops_probe.py <artifact-route-dir> | |
| 5 | + | |
| 6 | +<artifact-route-dir> is the folder routes/rusirui-rational-verifier of branch | |
| 7 | +origin/rusirui-rational-verifier (a checkout of it, not the branch itself). | |
| 8 | + | |
| 9 | +Each probe runs that folder's verify.py as a subprocess on a controlled input | |
| 10 | +and compares the exit code, stdout and the presence of the output file with | |
| 11 | +what the artifact's README claims. Nothing is imported from the artifact. | |
| 12 | +Prints one line per probe and exits 0 only if every probe matched. | |
| 13 | +""" | |
| 14 | +import json | |
| 15 | +import os | |
| 16 | +import subprocess | |
| 17 | +import sys | |
| 18 | +import tempfile | |
| 19 | +import time | |
| 20 | +from pathlib import Path | |
| 21 | + | |
| 22 | +FAILS = [] | |
| 23 | +MATCHED = 0 | |
| 24 | +SKIPPED = 0 | |
| 25 | + | |
| 26 | + | |
| 27 | +def run(script, args, cwd=None, env=None): | |
| 28 | + start = time.perf_counter() | |
| 29 | + proc = subprocess.run( | |
| 30 | + [sys.executable, str(script)] + [str(a) for a in args], | |
| 31 | + capture_output=True, text=True, cwd=cwd, env=env, timeout=600, | |
| 32 | + ) | |
| 33 | + return proc.returncode, proc.stdout.strip(), proc.stderr.strip(), time.perf_counter() - start | |
| 34 | + | |
| 35 | + | |
| 36 | +def check(name, got, want): | |
| 37 | + global MATCHED | |
| 38 | + ok = got == want | |
| 39 | + if ok: | |
| 40 | + MATCHED += 1 | |
| 41 | + else: | |
| 42 | + FAILS.append(name) | |
| 43 | + print(("OK " if ok else "FAIL ") + name + ("" if ok else f" (got {got!r}, want {want!r})")) | |
| 44 | + | |
| 45 | + | |
| 46 | +def put(folder, data): | |
| 47 | + path = Path(folder) / "configuration.json" | |
| 48 | + path.write_text(json.dumps(data), encoding="utf-8") | |
| 49 | + return path | |
| 50 | + | |
| 51 | + | |
| 52 | +def main(): | |
| 53 | + if len(sys.argv) != 2: | |
| 54 | + print(__doc__.strip().splitlines()[2]) | |
| 55 | + return 2 | |
| 56 | + artifact = Path(sys.argv[1]).resolve() | |
| 57 | + verify_py = artifact / "verify.py" | |
| 58 | + if not verify_py.is_file(): | |
| 59 | + print(f"no verify.py in {artifact}", file=sys.stderr) | |
| 60 | + return 2 | |
| 61 | + grid = [{"schema": 1, "points": [[x, y] for y in range(8) for x in range(10)], "unit_circles": 76}] | |
| 62 | + | |
| 63 | + with tempfile.TemporaryDirectory() as tmp: | |
| 64 | + tmp = Path(tmp) | |
| 65 | + | |
| 66 | + # 1. The route's own configuration: PASS n=9, 5 circles, output matches example. | |
| 67 | + out = tmp / "route.json" | |
| 68 | + rc, so, se, _ = run(verify_py, [artifact, "--output", out]) | |
| 69 | + check("route folder exits 0", rc, 0) | |
| 70 | + check("route folder prints PASS n=9 / 5", (so.startswith("PASS:") and "n=9" in so and "unit circles=5" in so), True) | |
| 71 | + produced = json.loads(out.read_text()) if out.exists() else None | |
| 72 | + example = json.loads((artifact / "example-verification.json").read_text()) | |
| 73 | + check("output equals example-verification.json (parsed)", produced, example) | |
| 74 | + check("output equals example-verification.json (bytes)", out.read_bytes() if out.exists() else None, | |
| 75 | + (artifact / "example-verification.json").read_bytes()) | |
| 76 | + | |
| 77 | + # 2. The six accept fixtures. | |
| 78 | + for name in ("collinear", "dedup", "grid", "nonunit", "rational-center", "three"): | |
| 79 | + folder = artifact / "samples" / "accept" / name | |
| 80 | + claimed = json.loads((folder / "configuration.json").read_text())["unit_circles"] | |
| 81 | + out = tmp / f"accept-{name}.json" | |
| 82 | + rc, so, se, _ = run(verify_py, [folder, "--output", out]) | |
| 83 | + got = json.loads(out.read_text())["unit_circles"] if out.exists() else None | |
| 84 | + check(f"accept/{name} exits 0 with {claimed}", (rc, got), (0, claimed)) | |
| 85 | + | |
| 86 | + # 3. The six reject fixtures: exit 1 and no output file left behind. | |
| 87 | + for name in ("collinear", "duplicate", "float", "nearly-unit", "overcount", "undercount"): | |
| 88 | + folder = artifact / "samples" / "reject" / name | |
| 89 | + out = tmp / f"reject-{name}.json" | |
| 90 | + out.write_text('{"stale": "from an earlier run"}') | |
| 91 | + rc, so, se, _ = run(verify_py, [folder, "--output", out]) | |
| 92 | + check(f"reject/{name} exits 1 and leaves no output", (rc, out.exists()), (1, False)) | |
| 93 | + check(f"reject/{name} printed no PASS", so.startswith("PASS"), False) | |
| 94 | + | |
| 95 | + # 4. Missing artifact: SKIP, exit 0, no file. | |
| 96 | + empty = tmp / "empty" | |
| 97 | + empty.mkdir() | |
| 98 | + out = tmp / "skip.json" | |
| 99 | + rc, so, se, _ = run(verify_py, [empty, "--output", out]) | |
| 100 | + check("missing configuration.json exits 0 with SKIP", (rc, so.startswith("SKIP:"), out.exists()), (0, True, False)) | |
| 101 | + | |
| 102 | + # 5. Nonexistent route folder: exit 2. | |
| 103 | + rc, so, se, _ = run(verify_py, [tmp / "absent", "--output", out]) | |
| 104 | + check("nonexistent route folder exits 2", rc, 2) | |
| 105 | + | |
| 106 | + # 6. Output must differ from input. | |
| 107 | + rc, so, se, _ = run(verify_py, [artifact, "--output", artifact / "configuration.json"]) | |
| 108 | + check("output == input exits 2", rc, 2) | |
| 109 | + check("output == input left configuration.json intact", | |
| 110 | + json.loads((artifact / "configuration.json").read_text())["schema"], 1) | |
| 111 | + | |
| 112 | + # 7. Duplicate JSON key, invalid UTF-8, configuration.json is a directory. | |
| 113 | + dup = tmp / "dup" | |
| 114 | + dup.mkdir() | |
| 115 | + (dup / "configuration.json").write_text('{"schema":1,"schema":1}') | |
| 116 | + check("duplicate JSON key exits 1", run(verify_py, [dup, "--output", tmp / "x1.json"])[0], 1) | |
| 117 | + bad = tmp / "badbytes" | |
| 118 | + bad.mkdir() | |
| 119 | + (bad / "configuration.json").write_bytes(b"\xff") | |
| 120 | + check("invalid UTF-8 exits 1", run(verify_py, [bad, "--output", tmp / "x2.json"])[0], 1) | |
| 121 | + asdir = tmp / "asdir" | |
| 122 | + (asdir / "configuration.json").mkdir(parents=True) | |
| 123 | + check("configuration.json as directory exits 1", run(verify_py, [asdir, "--output", tmp / "x3.json"])[0], 1) | |
| 124 | + | |
| 125 | + # 8. Caps: 81 points, 33-digit coordinate, file over 128 KiB, count over the pair bound. | |
| 126 | + many = tmp / "many" | |
| 127 | + many.mkdir() | |
| 128 | + put(many, {"schema": 1, "points": [[i, 0] for i in range(81)], "unit_circles": 0}) | |
| 129 | + check("81 points exits 1", run(verify_py, [many, "--output", tmp / "x4.json"])[0], 1) | |
| 130 | + wide = tmp / "wide" | |
| 131 | + wide.mkdir() | |
| 132 | + put(wide, {"schema": 1, "points": [[("1" + "0" * 32), 0], [0, 1], [-1, 0]], "unit_circles": 1}) | |
| 133 | + check("33-digit coordinate exits 1", run(verify_py, [wide, "--output", tmp / "x5.json"])[0], 1) | |
| 134 | + big = tmp / "big" | |
| 135 | + big.mkdir() | |
| 136 | + (big / "configuration.json").write_text( | |
| 137 | + json.dumps({"schema": 1, "points": [[1, 0], [0, 1], [-1, 0]], "unit_circles": 1}) + " " * 131072) | |
| 138 | + check("file over 128 KiB exits 1", run(verify_py, [big, "--output", tmp / "x6.json"])[0], 1) | |
| 139 | + over = tmp / "over" | |
| 140 | + over.mkdir() | |
| 141 | + put(over, {"schema": 1, "points": [[1, 0], [0, 1], [-1, 0], [0, -1]], "unit_circles": 5}) | |
| 142 | + check("count over the pair bound exits 1", run(verify_py, [over, "--output", tmp / "x7.json"])[0], 1) | |
| 143 | + | |
| 144 | + # 9. The 80-point 10x8 grid: count 76, and how promptly. | |
| 145 | + grid_dir = tmp / "grid80" | |
| 146 | + grid_dir.mkdir() | |
| 147 | + put(grid_dir, grid[0]) | |
| 148 | + out = tmp / "grid80.json" | |
| 149 | + rc, so, se, elapsed = run(verify_py, [grid_dir, "--output", out]) | |
| 150 | + check("grid80 exits 0", rc, 0) | |
| 151 | + got = json.loads(out.read_text())["unit_circles"] if out.exists() else None | |
| 152 | + check("grid80 counts 76", got, 76) | |
| 153 | + print(f" grid80 wall time: {elapsed:.3f}s") | |
| 154 | + | |
| 155 | + # 10. The runner as the check would call it (Git POSIX sh on Windows). | |
| 156 | + sbatch = artifact / "check.sbatch" | |
| 157 | + shebang = sbatch.read_text().splitlines()[0] | |
| 158 | + with tempfile.TemporaryDirectory() as outer: | |
| 159 | + outer = Path(outer) | |
| 160 | + (outer / "input").mkdir() | |
| 161 | + target = outer / "input" / "routes" / "r" | |
| 162 | + target.mkdir(parents=True) | |
| 163 | + put(target, {"schema": 1, "points": [[1, 0], [0, 1], [-1, 0]], "unit_circles": 1}) | |
| 164 | + env = dict(os.environ, SS_INPUT=str(outer / "input"), SS_ROUTE_DIR="routes/r") | |
| 165 | + proc = subprocess.run(["sh", str(sbatch)], capture_output=True, text=True, env=env, cwd=outer) | |
| 166 | + check("check.sbatch accepts a valid route (exit 0)", proc.returncode, 0) | |
| 167 | + check("check.sbatch wrote verification.json in its cwd", (outer / "verification.json").is_file(), True) | |
| 168 | + put(target, {"schema": 1, "points": [[1, 0], [0, 1], [-1, 0]], "unit_circles": 0}) | |
| 169 | + proc = subprocess.run(["sh", str(sbatch)], capture_output=True, text=True, env=env, cwd=outer) | |
| 170 | + check("check.sbatch rejects a wrong count (exit 1)", proc.returncode, 1) | |
| 171 | + print(f" check.sbatch shebang: {shebang}") | |
| 172 | + | |
| 173 | + # 11. Symlink as configuration.json (skipped where the OS forbids creating one). | |
| 174 | + with tempfile.TemporaryDirectory() as link_tmp: | |
| 175 | + link_tmp = Path(link_tmp) | |
| 176 | + real = link_tmp / "real.json" | |
| 177 | + real.write_text(json.dumps({"schema": 1, "points": [[1, 0], [0, 1], [-1, 0]], "unit_circles": 1})) | |
| 178 | + route = link_tmp / "route" | |
| 179 | + route.mkdir() | |
| 180 | + try: | |
| 181 | + os.symlink(real, route / "configuration.json") | |
| 182 | + except OSError as exc: | |
| 183 | + global SKIPPED | |
| 184 | + SKIPPED += 1 | |
| 185 | + print(f"SKIP symlinked configuration.json: cannot create symlink ({exc.__class__.__name__})") | |
| 186 | + else: | |
| 187 | + check("symlinked configuration.json exits 1", run(verify_py, [route, "--output", link_tmp / "s.json"])[0], 1) | |
| 188 | + | |
| 189 | + print(f"\n{MATCHED} matched, {SKIPPED} skipped, {len(FAILS)} did not match the artifact's documented claim") | |
| 190 | + return 0 if not FAILS else 1 | |
| 191 | + | |
| 192 | + | |
| 193 | +if __name__ == "__main__": | |
| 194 | + sys.exit(main()) | |
+207 −0 routes/rusirui-repro-verifier/panel/impl-circle-equation/count.py added View file
| @@ -0,0 +1,207 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Exact count of distinct radius-1 circles through at least three rational points. | |
| 3 | + | |
| 4 | +Route: the circle equation. A circle is written | |
| 5 | + | |
| 6 | + x^2 + y^2 + D x + E y + F = 0. | |
| 7 | + | |
| 8 | +For a non-collinear triple P1, P2, P3, subtracting P1's equation from P2's and | |
| 9 | +P3's gives the 2 by 2 linear system | |
| 10 | + | |
| 11 | + (x2-x1) D + (y2-y1) E = (x1^2+y1^2) - (x2^2+y2^2) | |
| 12 | + (x3-x1) D + (y3-y1) E = (x1^2+y1^2) - (x3^2+y3^2). | |
| 13 | + | |
| 14 | +Its determinant is the 3 by 3 determinant of the stacked system | |
| 15 | +[[x1,y1,1],[x2,y2,1],[x3,y3,1]], so it vanishes exactly when the triple is | |
| 16 | +collinear; such triples are skipped. Otherwise (D,E) is solved by Cramer's | |
| 17 | +rule over the rationals and F follows from P1. The centre is (-D/2,-E/2) and | |
| 18 | +the radius is exactly 1 iff D^2 + E^2 - 4F == 4. Candidate centres are | |
| 19 | +deduplicated exactly and recounted against every input point, also exactly. | |
| 20 | + | |
| 21 | +All decisions use Python integers and fractions.Fraction; no float ever enters | |
| 22 | +a comparison or an arithmetic step (float coordinates are rejected up front). | |
| 23 | +""" | |
| 24 | +import json | |
| 25 | +import re | |
| 26 | +import sys | |
| 27 | +from fractions import Fraction | |
| 28 | + | |
| 29 | +# Exact arithmetic should not be limited by CPython's decimal-string guard. | |
| 30 | +if hasattr(sys, "set_int_max_str_digits"): | |
| 31 | + try: | |
| 32 | + sys.set_int_max_str_digits(0) | |
| 33 | + except ValueError: | |
| 34 | + pass | |
| 35 | + | |
| 36 | +FRACTION_RE = re.compile(r"-?[0-9]+/[0-9]+") | |
| 37 | + | |
| 38 | + | |
| 39 | +class InvalidConfig(Exception): | |
| 40 | + pass | |
| 41 | + | |
| 42 | + | |
| 43 | +def parse_coordinate(value): | |
| 44 | + """Return the exact Fraction for one JSON coordinate, or raise InvalidConfig.""" | |
| 45 | + if isinstance(value, bool): | |
| 46 | + raise InvalidConfig("boolean coordinate") | |
| 47 | + if isinstance(value, int): | |
| 48 | + return Fraction(value, 1) | |
| 49 | + if isinstance(value, float): | |
| 50 | + raise InvalidConfig("floating-point coordinate") | |
| 51 | + if isinstance(value, str): | |
| 52 | + if FRACTION_RE.fullmatch(value) is None: | |
| 53 | + raise InvalidConfig("coordinate string is not exactly a fraction p/q") | |
| 54 | + num_text, den_text = value.split("/") | |
| 55 | + num = int(num_text) | |
| 56 | + den = int(den_text) | |
| 57 | + if den <= 0: | |
| 58 | + raise InvalidConfig("fraction denominator is not positive") | |
| 59 | + return Fraction(num, den) | |
| 60 | + raise InvalidConfig("coordinate is neither an integer nor a fraction string") | |
| 61 | + | |
| 62 | + | |
| 63 | +def parse_configuration(document): | |
| 64 | + """Validate the document and return its list of exact (x, y) points.""" | |
| 65 | + if not isinstance(document, dict): | |
| 66 | + raise InvalidConfig("top level is not a JSON object") | |
| 67 | + if "schema" not in document: | |
| 68 | + raise InvalidConfig("missing schema") | |
| 69 | + schema = document["schema"] | |
| 70 | + if type(schema) is not int or schema != 1: | |
| 71 | + raise InvalidConfig("schema must be the integer 1") | |
| 72 | + if "points" not in document: | |
| 73 | + raise InvalidConfig("missing points") | |
| 74 | + raw_points = document["points"] | |
| 75 | + if not isinstance(raw_points, list): | |
| 76 | + raise InvalidConfig("points is not a list") | |
| 77 | + n = len(raw_points) | |
| 78 | + if n < 3 or n > 80: | |
| 79 | + raise InvalidConfig("number of points must be between 3 and 80") | |
| 80 | + points = [] | |
| 81 | + seen = set() | |
| 82 | + for index, raw in enumerate(raw_points): | |
| 83 | + if not isinstance(raw, list) or len(raw) != 2: | |
| 84 | + raise InvalidConfig("point %d is not a pair" % index) | |
| 85 | + point = (parse_coordinate(raw[0]), parse_coordinate(raw[1])) | |
| 86 | + if point in seen: | |
| 87 | + raise InvalidConfig("duplicate point at index %d" % index) | |
| 88 | + seen.add(point) | |
| 89 | + points.append(point) | |
| 90 | + return points | |
| 91 | + | |
| 92 | + | |
| 93 | +def count_unit_circles(points): | |
| 94 | + """Return the sorted list of exact centres of unit circles through >=3 points.""" | |
| 95 | + n = len(points) | |
| 96 | + xs = [point[0] for point in points] | |
| 97 | + ys = [point[1] for point in points] | |
| 98 | + squares = [xs[i] * xs[i] + ys[i] * ys[i] for i in range(n)] | |
| 99 | + four = Fraction(4, 1) | |
| 100 | + one = Fraction(1, 1) | |
| 101 | + two = Fraction(2, 1) | |
| 102 | + | |
| 103 | + # Any two points of a unit circle are at distance at most 2. This exact | |
| 104 | + # necessary condition only prunes triples that cannot lie on such a circle. | |
| 105 | + near = [[False] * n for _ in range(n)] | |
| 106 | + for i in range(n): | |
| 107 | + xi = xs[i] | |
| 108 | + yi = ys[i] | |
| 109 | + for j in range(i + 1, n): | |
| 110 | + dx = xs[j] - xi | |
| 111 | + dy = ys[j] - yi | |
| 112 | + if dx * dx + dy * dy <= four: | |
| 113 | + near[i][j] = True | |
| 114 | + near[j][i] = True | |
| 115 | + | |
| 116 | + centres = set() | |
| 117 | + for i in range(n): | |
| 118 | + xi = xs[i] | |
| 119 | + yi = ys[i] | |
| 120 | + si = squares[i] | |
| 121 | + near_i = near[i] | |
| 122 | + for j in range(i + 1, n): | |
| 123 | + if not near_i[j]: | |
| 124 | + continue | |
| 125 | + xj = xs[j] | |
| 126 | + yj = ys[j] | |
| 127 | + dx2 = xj - xi | |
| 128 | + dy2 = yj - yi | |
| 129 | + b2 = si - squares[j] | |
| 130 | + near_j = near[j] | |
| 131 | + for k in range(j + 1, n): | |
| 132 | + if not near_i[k] or not near_j[k]: | |
| 133 | + continue | |
| 134 | + dx3 = xs[k] - xi | |
| 135 | + dy3 = ys[k] - yi | |
| 136 | + det = dx2 * dy3 - dx3 * dy2 | |
| 137 | + if det == 0: | |
| 138 | + # The 2x2 determinant equals the 3x3 stacked determinant, | |
| 139 | + # so this is exactly the collinear case: no circle. | |
| 140 | + continue | |
| 141 | + b3 = si - squares[k] | |
| 142 | + d_coef = (b2 * dy3 - b3 * dy2) / det | |
| 143 | + e_coef = (dx2 * b3 - dx3 * b2) / det | |
| 144 | + f_coef = -(si + d_coef * xi + e_coef * yi) | |
| 145 | + if d_coef * d_coef + e_coef * e_coef - 4 * f_coef == 4: | |
| 146 | + centres.add((-d_coef / two, -e_coef / two)) | |
| 147 | + | |
| 148 | + # Exact recount of incidences against all input points. | |
| 149 | + result = [] | |
| 150 | + for cx, cy in centres: | |
| 151 | + hits = 0 | |
| 152 | + for x, y in points: | |
| 153 | + dx = x - cx | |
| 154 | + dy = y - cy | |
| 155 | + if dx * dx + dy * dy == one: | |
| 156 | + hits += 1 | |
| 157 | + if hits >= 3: | |
| 158 | + break | |
| 159 | + if hits >= 3: | |
| 160 | + result.append((cx, cy)) | |
| 161 | + result.sort() | |
| 162 | + return result | |
| 163 | + | |
| 164 | + | |
| 165 | +def format_fraction(value): | |
| 166 | + """Canonical output: 'a' when integral, otherwise reduced 'p/q' with q > 1.""" | |
| 167 | + if value.denominator == 1: | |
| 168 | + return str(value.numerator) | |
| 169 | + return "%d/%d" % (value.numerator, value.denominator) | |
| 170 | + | |
| 171 | + | |
| 172 | +def main(argv): | |
| 173 | + if len(argv) != 2: | |
| 174 | + print("usage: count.py <configuration.json>", file=sys.stderr) | |
| 175 | + return 1 | |
| 176 | + path = argv[1] | |
| 177 | + try: | |
| 178 | + with open(path, "r", encoding="utf-8") as handle: | |
| 179 | + text = handle.read() | |
| 180 | + except OSError as exc: | |
| 181 | + print("cannot read configuration: %s" % exc, file=sys.stderr) | |
| 182 | + return 1 | |
| 183 | + except ValueError: | |
| 184 | + print("invalid configuration: file is not readable UTF-8 text", file=sys.stderr) | |
| 185 | + return 1 | |
| 186 | + try: | |
| 187 | + try: | |
| 188 | + document = json.loads(text) | |
| 189 | + except Exception: | |
| 190 | + raise InvalidConfig("file is not valid JSON") | |
| 191 | + points = parse_configuration(document) | |
| 192 | + centres = count_unit_circles(points) | |
| 193 | + except InvalidConfig as exc: | |
| 194 | + print("invalid configuration: %s" % exc, file=sys.stderr) | |
| 195 | + return 1 | |
| 196 | + | |
| 197 | + output = { | |
| 198 | + "n": len(points), | |
| 199 | + "unit_circles": len(centres), | |
| 200 | + "centers": [[format_fraction(cx), format_fraction(cy)] for cx, cy in centres], | |
| 201 | + } | |
| 202 | + print(json.dumps(output, separators=(",", ":"))) | |
| 203 | + return 0 | |
| 204 | + | |
| 205 | + | |
| 206 | +if __name__ == "__main__": | |
| 207 | + sys.exit(main(sys.argv)) | |
+477 −0 routes/rusirui-repro-verifier/panel/impl-circle-equation/selftest.py added View file
| @@ -0,0 +1,477 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Self-test for count.py. | |
| 3 | + | |
| 4 | +Runs the required fixtures plus adversarial and randomised configurations. | |
| 5 | +count.py is checked two ways: its own reported centre set is validated for | |
| 6 | +canonical form and ordering, and it is compared against an independent | |
| 7 | +pair-based method that constructs rational unit-circle centres from pairs of | |
| 8 | +points and tests rationality with an exact integer square test. | |
| 9 | + | |
| 10 | +The pair method is independent of count.py's circle-equation triple route: | |
| 11 | +every circle through at least three rational points has a rational centre, | |
| 12 | +hence it is generated by one of its pairs, and for a pair P,Q the centre is | |
| 13 | + | |
| 14 | + M +- (h/d) * (-dy, dx), M = (P+Q)/2, d^2 = |Q-P|^2, h^2 = 1 - d^2/4, | |
| 15 | + | |
| 16 | +so the centre is rational exactly when (h/d)^2 = (1/d^2 - 1/4) is a square | |
| 17 | +of a rational, which is decided by exact integer square tests. | |
| 18 | +""" | |
| 19 | +import json | |
| 20 | +import math | |
| 21 | +import random | |
| 22 | +import shutil | |
| 23 | +import subprocess | |
| 24 | +import sys | |
| 25 | +import tempfile | |
| 26 | +from fractions import Fraction | |
| 27 | +from pathlib import Path | |
| 28 | + | |
| 29 | +HERE = Path(__file__).resolve().parent | |
| 30 | +ROOT = HERE.parents[3] | |
| 31 | +COUNT = HERE / "count.py" | |
| 32 | +FIX = ROOT / "routes" / "rusirui-repro-verifier" / "fixtures" | |
| 33 | +PY = sys.executable | |
| 34 | + | |
| 35 | +failures = [] | |
| 36 | +results = [] | |
| 37 | + | |
| 38 | + | |
| 39 | +def fail(msg): | |
| 40 | + failures.append(msg) | |
| 41 | + print("FAIL: " + msg) | |
| 42 | + | |
| 43 | + | |
| 44 | +def run_count(path, cwd=None): | |
| 45 | + proc = subprocess.run( | |
| 46 | + [PY, str(COUNT), str(path)], | |
| 47 | + capture_output=True, | |
| 48 | + text=True, | |
| 49 | + cwd=str(cwd if cwd is not None else Path(tempfile.gettempdir())), | |
| 50 | + timeout=600, | |
| 51 | + ) | |
| 52 | + return proc.returncode, proc.stdout, proc.stderr | |
| 53 | + | |
| 54 | + | |
| 55 | +def parse_json_coord(v): | |
| 56 | + if isinstance(v, bool): | |
| 57 | + raise ValueError("boolean") | |
| 58 | + if isinstance(v, int): | |
| 59 | + return Fraction(v) | |
| 60 | + p, q = v.split("/") | |
| 61 | + return Fraction(int(p), int(q)) | |
| 62 | + | |
| 63 | + | |
| 64 | +def points_from_obj(obj): | |
| 65 | + return [(parse_json_coord(a), parse_json_coord(b)) for a, b in obj["points"]] | |
| 66 | + | |
| 67 | + | |
| 68 | +def canonical(fr): | |
| 69 | + if fr.denominator == 1: | |
| 70 | + return str(fr.numerator) | |
| 71 | + return "%d/%d" % (fr.numerator, fr.denominator) | |
| 72 | + | |
| 73 | + | |
| 74 | +def rational_sqrt(fr): | |
| 75 | + """Return the non-negative rational square root of fr, or None.""" | |
| 76 | + if fr < 0: | |
| 77 | + return None | |
| 78 | + a, b = fr.numerator, fr.denominator | |
| 79 | + ra, rb = math.isqrt(a), math.isqrt(b) | |
| 80 | + if ra * ra == a and rb * rb == b: | |
| 81 | + return Fraction(ra, rb) | |
| 82 | + return None | |
| 83 | + | |
| 84 | + | |
| 85 | +def pair_method(points): | |
| 86 | + """Independent exact set of unit-circle centres with >=3 input points.""" | |
| 87 | + n = len(points) | |
| 88 | + candidates = set() | |
| 89 | + one = Fraction(1, 1) | |
| 90 | + two = Fraction(2, 1) | |
| 91 | + four = Fraction(4, 1) | |
| 92 | + for i in range(n): | |
| 93 | + xi, yi = points[i] | |
| 94 | + for j in range(i + 1, n): | |
| 95 | + xj, yj = points[j] | |
| 96 | + dx = xj - xi | |
| 97 | + dy = yj - yi | |
| 98 | + d2 = dx * dx + dy * dy | |
| 99 | + if d2 == 0 or d2 > four: | |
| 100 | + continue | |
| 101 | + h2 = one - d2 / four | |
| 102 | + t2 = h2 / d2 | |
| 103 | + mx = (xi + xj) / two | |
| 104 | + my = (yi + yj) / two | |
| 105 | + if t2 == 0: | |
| 106 | + candidates.add((mx, my)) | |
| 107 | + continue | |
| 108 | + t = rational_sqrt(t2) | |
| 109 | + if t is None: | |
| 110 | + continue | |
| 111 | + candidates.add((mx - t * dy, my + t * dx)) | |
| 112 | + candidates.add((mx + t * dy, my - t * dx)) | |
| 113 | + out = set() | |
| 114 | + for cx, cy in candidates: | |
| 115 | + hits = 0 | |
| 116 | + for x, y in points: | |
| 117 | + dx = x - cx | |
| 118 | + dy = y - cy | |
| 119 | + if dx * dx + dy * dy == one: | |
| 120 | + hits += 1 | |
| 121 | + if hits >= 3: | |
| 122 | + break | |
| 123 | + if hits >= 3: | |
| 124 | + out.add((cx, cy)) | |
| 125 | + return out | |
| 126 | + | |
| 127 | + | |
| 128 | +def parse_output_centres(out, npoints): | |
| 129 | + try: | |
| 130 | + data = json.loads(out) | |
| 131 | + except Exception as exc: | |
| 132 | + fail("stdout is not JSON: %s" % exc) | |
| 133 | + return None | |
| 134 | + if not isinstance(data, dict): | |
| 135 | + fail("stdout JSON is not an object") | |
| 136 | + return None | |
| 137 | + if set(data.keys()) != {"n", "unit_circles", "centers"}: | |
| 138 | + fail("stdout keys are %r" % sorted(data.keys())) | |
| 139 | + return None | |
| 140 | + if type(data["n"]) is not int or data["n"] != npoints: | |
| 141 | + fail("n is %r, expected %d" % (data["n"], npoints)) | |
| 142 | + return None | |
| 143 | + count = data["unit_circles"] | |
| 144 | + if type(count) is not int or count < 0: | |
| 145 | + fail("unit_circles is not a non-negative integer: %r" % (count,)) | |
| 146 | + return None | |
| 147 | + centres = data["centers"] | |
| 148 | + if not isinstance(centres, list): | |
| 149 | + fail("centers is not a list") | |
| 150 | + return None | |
| 151 | + if count != len(centres): | |
| 152 | + fail("unit_circles=%d but len(centers)=%d" % (count, len(centres))) | |
| 153 | + return None | |
| 154 | + parsed = [] | |
| 155 | + seen = set() | |
| 156 | + for k, pair in enumerate(centres): | |
| 157 | + if not isinstance(pair, list) or len(pair) != 2: | |
| 158 | + fail("center %d is not a pair" % k) | |
| 159 | + return None | |
| 160 | + vals = [] | |
| 161 | + for s in pair: | |
| 162 | + if not isinstance(s, str): | |
| 163 | + fail("center %d has a non-string coordinate" % k) | |
| 164 | + return None | |
| 165 | + try: | |
| 166 | + fr = Fraction(s) | |
| 167 | + except Exception: | |
| 168 | + fail("center %d coordinate %r is not a rational" % (k, s)) | |
| 169 | + return None | |
| 170 | + if s != canonical(fr): | |
| 171 | + fail("center %d coordinate %r is not reduced/canonical" % (k, s)) | |
| 172 | + return None | |
| 173 | + vals.append(fr) | |
| 174 | + tup = tuple(vals) | |
| 175 | + if tup in seen: | |
| 176 | + fail("duplicate centre %r" % (tup,)) | |
| 177 | + return None | |
| 178 | + seen.add(tup) | |
| 179 | + parsed.append(tup) | |
| 180 | + if parsed != sorted(parsed): | |
| 181 | + fail("centers are not sorted by (x,y)") | |
| 182 | + return None | |
| 183 | + return parsed | |
| 184 | + | |
| 185 | + | |
| 186 | +def check_valid(path, obj, claimed=None, require_claim=True, label=None): | |
| 187 | + points = points_from_obj(obj) | |
| 188 | + code, out, err = run_count(path) | |
| 189 | + name = label or str(path) | |
| 190 | + if code != 0: | |
| 191 | + fail("%s: expected exit 0, got %d; stderr=%r" % (name, code, err.strip())) | |
| 192 | + results.append((name, code, "-", claimed)) | |
| 193 | + return None | |
| 194 | + centres = parse_output_centres(out, len(points)) | |
| 195 | + if centres is None: | |
| 196 | + results.append((name, code, "-", claimed)) | |
| 197 | + return None | |
| 198 | + expected = pair_method(points) | |
| 199 | + if set(centres) != expected: | |
| 200 | + fail( | |
| 201 | + "%s: centre set differs from pair method: got %d %r, expected %d %r" | |
| 202 | + % (name, len(centres), sorted(centres), len(expected), sorted(expected)) | |
| 203 | + ) | |
| 204 | + if require_claim and centres_count(centres) != claimed: | |
| 205 | + fail("%s: computed %d but claimed %r" % (name, len(centres), claimed)) | |
| 206 | + results.append((name, code, len(centres), claimed)) | |
| 207 | + return centres | |
| 208 | + | |
| 209 | + | |
| 210 | +def centres_count(centres): | |
| 211 | + return len(centres) | |
| 212 | + | |
| 213 | + | |
| 214 | +def check_invalid(path, label=None): | |
| 215 | + name = label or str(path) | |
| 216 | + code, out, err = run_count(path) | |
| 217 | + if code == 0: | |
| 218 | + fail("%s: expected nonzero exit, got 0; stdout=%r" % (name, out.strip())) | |
| 219 | + if out.strip() != "": | |
| 220 | + fail("%s: invalid input wrote to stdout: %r" % (name, out)) | |
| 221 | + if not err.strip(): | |
| 222 | + fail("%s: invalid input wrote no reason to stderr" % name) | |
| 223 | + results.append((name, code, "-", "-")) | |
| 224 | + | |
| 225 | + | |
| 226 | +def write_case(tmpdir, name, obj): | |
| 227 | + path = Path(tmpdir) / (name + ".json") | |
| 228 | + path.write_text(json.dumps(obj), encoding="utf-8") | |
| 229 | + return path | |
| 230 | + | |
| 231 | + | |
| 232 | +def write_raw_case(tmpdir, name, text): | |
| 233 | + path = Path(tmpdir) / (name + ".json") | |
| 234 | + path.write_text(text, encoding="utf-8") | |
| 235 | + return path | |
| 236 | + | |
| 237 | + | |
| 238 | +def adversarial_cases(): | |
| 239 | + return [ | |
| 240 | + ( | |
| 241 | + "four_on_unit_circle", | |
| 242 | + [[1, 0], [0, 1], [-1, 0], [0, -1]], | |
| 243 | + 1, | |
| 244 | + ), | |
| 245 | + ( | |
| 246 | + "eight_on_unit_circle", | |
| 247 | + [ | |
| 248 | + [1, 0], | |
| 249 | + [0, 1], | |
| 250 | + [-1, 0], | |
| 251 | + [0, -1], | |
| 252 | + ["3/5", "4/5"], | |
| 253 | + ["-3/5", "4/5"], | |
| 254 | + ["3/5", "-4/5"], | |
| 255 | + ["-5/13", "12/13"], | |
| 256 | + ], | |
| 257 | + 1, | |
| 258 | + ), | |
| 259 | + ( | |
| 260 | + "distance_two_pair_only", | |
| 261 | + [[-1, 0], [1, 0], [0, 2]], | |
| 262 | + 0, | |
| 263 | + ), | |
| 264 | + ( | |
| 265 | + "distance_two_pair_on_circle", | |
| 266 | + [[-1, 0], [1, 0], [0, 1]], | |
| 267 | + 1, | |
| 268 | + ), | |
| 269 | + ( | |
| 270 | + "three_collinear", | |
| 271 | + [[0, 0], [1, 1], [2, 2]], | |
| 272 | + 0, | |
| 273 | + ), | |
| 274 | + ( | |
| 275 | + "irrational_centre_two_points", | |
| 276 | + [[0, 0], [1, 0], [0, 2]], | |
| 277 | + 0, | |
| 278 | + ), | |
| 279 | + ( | |
| 280 | + "rational_centre_four", | |
| 281 | + [["3/2", 0], ["-1/2", 0], ["1/2", 1], ["1/2", -1]], | |
| 282 | + 1, | |
| 283 | + ), | |
| 284 | + ( | |
| 285 | + "two_tangent_circles", | |
| 286 | + [[1, 0], [0, 1], [0, -1], [2, 1], [2, -1]], | |
| 287 | + 4, | |
| 288 | + ), | |
| 289 | + ( | |
| 290 | + "nonreduced_three", | |
| 291 | + [["0/5", "0/7"], ["5/5", "0/1"], ["0/1", "5/5"]], | |
| 292 | + 0, | |
| 293 | + ), | |
| 294 | + ( | |
| 295 | + "two_by_two_grid", | |
| 296 | + [[0, 0], [1, 0], [0, 1], [1, 1]], | |
| 297 | + 0, | |
| 298 | + ), | |
| 299 | + ] | |
| 300 | + | |
| 301 | + | |
| 302 | +def random_cases(seed=20261128, count=80): | |
| 303 | + rnd = random.Random(seed) | |
| 304 | + cases = [] | |
| 305 | + | |
| 306 | + def rand_fraction(): | |
| 307 | + return Fraction(rnd.randint(-5, 5), rnd.randint(1, 5)) | |
| 308 | + | |
| 309 | + def make_points(n, on_circle=False): | |
| 310 | + pts = [] | |
| 311 | + seen = set() | |
| 312 | + if on_circle: | |
| 313 | + cx = Fraction(rnd.randint(-2, 2), rnd.randint(1, 3)) | |
| 314 | + cy = Fraction(rnd.randint(-2, 2), rnd.randint(1, 3)) | |
| 315 | + ts = rnd.sample(range(-6, 7), 4) | |
| 316 | + for t in ts: | |
| 317 | + t = Fraction(t) | |
| 318 | + u = Fraction(1 - t * t, 1 + t * t) | |
| 319 | + v = Fraction(2 * t, 1 + t * t) | |
| 320 | + p = (cx + u, cy + v) | |
| 321 | + if p not in seen: | |
| 322 | + seen.add(p) | |
| 323 | + pts.append(p) | |
| 324 | + while len(pts) < n: | |
| 325 | + p = (rand_fraction(), rand_fraction()) | |
| 326 | + if p not in seen: | |
| 327 | + seen.add(p) | |
| 328 | + pts.append(p) | |
| 329 | + rnd.shuffle(pts) | |
| 330 | + return pts | |
| 331 | + | |
| 332 | + for k in range(count): | |
| 333 | + n = rnd.randint(3, 9) | |
| 334 | + pts = make_points(n, on_circle=(k % 4 == 0)) | |
| 335 | + cases.append(("random_%03d" % k, pts)) | |
| 336 | + return cases | |
| 337 | + | |
| 338 | + | |
| 339 | +def serialize_points(points, rnd): | |
| 340 | + raw = [] | |
| 341 | + for x, y in points: | |
| 342 | + def one(fr): | |
| 343 | + if rnd.random() < 0.5 and fr.denominator == 1: | |
| 344 | + return int(fr) | |
| 345 | + k = rnd.randint(1, 3) | |
| 346 | + return "%d/%d" % (fr.numerator * k, fr.denominator * k) | |
| 347 | + raw.append([one(x), one(y)]) | |
| 348 | + return raw | |
| 349 | + | |
| 350 | + | |
| 351 | +def main(): | |
| 352 | + ok = True | |
| 353 | + if not COUNT.exists(): | |
| 354 | + fail("count.py is missing") | |
| 355 | + return 1 | |
| 356 | + | |
| 357 | + accept = { | |
| 358 | + "collinear": 0, | |
| 359 | + "dedup": 1, | |
| 360 | + "grid": 5, | |
| 361 | + "nonunit": 0, | |
| 362 | + "rational-center": 1, | |
| 363 | + "three": 1, | |
| 364 | + } | |
| 365 | + for name, claimed in accept.items(): | |
| 366 | + path = FIX / "samples" / "accept" / name / "configuration.json" | |
| 367 | + obj = json.loads(path.read_text(encoding="utf-8")) | |
| 368 | + check_valid(path, obj, claimed) | |
| 369 | + | |
| 370 | + # Invalid configurations. | |
| 371 | + for name in ["duplicate", "float"]: | |
| 372 | + path = FIX / "samples" / "reject" / name / "configuration.json" | |
| 373 | + check_invalid(path) | |
| 374 | + | |
| 375 | + # Valid configurations whose declared count is wrong. | |
| 376 | + misclaim = ["collinear", "nearly-unit", "overcount", "undercount"] | |
| 377 | + for name in misclaim: | |
| 378 | + path = FIX / "samples" / "reject" / name / "configuration.json" | |
| 379 | + obj = json.loads(path.read_text(encoding="utf-8")) | |
| 380 | + centres = check_valid(path, obj, obj.get("unit_circles"), require_claim=False) | |
| 381 | + if centres is not None: | |
| 382 | + computed = len(centres) | |
| 383 | + if computed == obj.get("unit_circles"): | |
| 384 | + fail("%s: expected a mismatch with claimed count" % path) | |
| 385 | + | |
| 386 | + grid80 = FIX / "grid80" / "configuration.json" | |
| 387 | + obj = json.loads(grid80.read_text(encoding="utf-8")) | |
| 388 | + check_valid(grid80, obj, obj.get("unit_circles"), require_claim=False, label=str(grid80)) | |
| 389 | + | |
| 390 | + tmpdir = Path(tempfile.mkdtemp(prefix="selftest-", dir=str(HERE))) | |
| 391 | + rnd = random.Random(424242) | |
| 392 | + try: | |
| 393 | + # Adversarial cases. | |
| 394 | + adv = adversarial_cases() | |
| 395 | + for name, rawpoints, expected in adv: | |
| 396 | + obj = {"schema": 1, "points": rawpoints, "unit_circles": expected} | |
| 397 | + path = write_case(tmpdir, name, obj) | |
| 398 | + pts = [(parse_json_coord(a), parse_json_coord(b)) for a, b in rawpoints] | |
| 399 | + indep = pair_method(pts) | |
| 400 | + if len(indep) != expected: | |
| 401 | + fail("%s: pair method gives %d, hand expectation %d" % (name, len(indep), expected)) | |
| 402 | + check_valid(path, obj, expected, label=name) | |
| 403 | + | |
| 404 | + # Randomised cross-checks. | |
| 405 | + for name, pts in random_cases(): | |
| 406 | + raw = serialize_points(pts, rnd) | |
| 407 | + indep = pair_method(pts) | |
| 408 | + obj = {"schema": 1, "points": raw, "unit_circles": len(indep)} | |
| 409 | + path = write_case(tmpdir, name, obj) | |
| 410 | + check_valid(path, obj, len(indep), label=name) | |
| 411 | + | |
| 412 | + # Invalid input cases. | |
| 413 | + bad_objs = { | |
| 414 | + "schema_2": {"schema": 2, "points": [[0, 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 415 | + "schema_string": {"schema": "1", "points": [[0, 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 416 | + "schema_float": {"schema": 1.0, "points": [[0, 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 417 | + "schema_bool": {"schema": True, "points": [[0, 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 418 | + "schema_missing": {"points": [[0, 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 419 | + "points_not_list": {"schema": 1, "points": "nope", "unit_circles": 0}, | |
| 420 | + "too_few": {"schema": 1, "points": [[0, 0], [1, 0]], "unit_circles": 0}, | |
| 421 | + "too_many": {"schema": 1, "points": [[i, 1000 + i] for i in range(81)], "unit_circles": 0}, | |
| 422 | + "point_length": {"schema": 1, "points": [[0, 0, 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 423 | + "point_not_list": {"schema": 1, "points": [0, [1, 0], [0, 1]], "unit_circles": 0}, | |
| 424 | + "coord_float": {"schema": 1, "points": [[0.0, 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 425 | + "coord_float_exp": {"schema": 1, "points": [[1e2, 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 426 | + "coord_bool": {"schema": 1, "points": [[True, 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 427 | + "coord_null": {"schema": 1, "points": [[None, 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 428 | + "coord_list": {"schema": 1, "points": [[[1], 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 429 | + "coord_decimal_string": {"schema": 1, "points": [["1.0", 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 430 | + "coord_exp_string": {"schema": 1, "points": [["1e2", 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 431 | + "coord_space": {"schema": 1, "points": [[" 1/2", 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 432 | + "coord_space2": {"schema": 1, "points": [["1/2 ", 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 433 | + "coord_newline": {"schema": 1, "points": [["1/2\n", 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 434 | + "coord_neg_den": {"schema": 1, "points": [["1/-2", 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 435 | + "coord_zero_den": {"schema": 1, "points": [["1/0", 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 436 | + "coord_double_slash": {"schema": 1, "points": [["1/2/3", 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 437 | + "coord_bare_int_string": {"schema": 1, "points": [["3", 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 438 | + "coord_plus": {"schema": 1, "points": [["+1/2", 0], [1, 0], [0, 1]], "unit_circles": 0}, | |
| 439 | + "duplicate_reduced": {"schema": 1, "points": [[1, 0], ["2/2", 0], [0, 1]], "unit_circles": 0}, | |
| 440 | + "duplicate_int": {"schema": 1, "points": [[1, 2], [1, 2], [0, 1]], "unit_circles": 0}, | |
| 441 | + } | |
| 442 | + for name, obj in bad_objs.items(): | |
| 443 | + path = write_case(tmpdir, name, obj) | |
| 444 | + check_invalid(path, label=name) | |
| 445 | + | |
| 446 | + path = write_raw_case(tmpdir, "malformed_json", "{not json") | |
| 447 | + check_invalid(path, label="malformed_json") | |
| 448 | + path = write_raw_case(tmpdir, "top_level_list", "[1,2,3]") | |
| 449 | + check_invalid(path, label="top_level_list") | |
| 450 | + path = tmpdir / "missing_file.json" | |
| 451 | + check_invalid(path, label="missing_file") | |
| 452 | + | |
| 453 | + # Valid edge cases that must be accepted. | |
| 454 | + edge_objs = { | |
| 455 | + "zero_numerators": {"schema": 1, "points": [["0/5", "0/7"], ["5/5", "0/1"], ["0/1", "5/5"]], "unit_circles": 0}, | |
| 456 | + "integral_fractions": {"schema": 1, "points": [["1/1", "0/1"], ["0/1", "1/1"], ["-1/1", "0/1"]], "unit_circles": 1}, | |
| 457 | + } | |
| 458 | + for name, obj in edge_objs.items(): | |
| 459 | + path = write_case(tmpdir, name, obj) | |
| 460 | + check_valid(path, obj, obj["unit_circles"], label=name) | |
| 461 | + finally: | |
| 462 | + shutil.rmtree(tmpdir, ignore_errors=True) | |
| 463 | + | |
| 464 | + print() | |
| 465 | + print("RESULTS") | |
| 466 | + for name, code, computed, claimed in results: | |
| 467 | + print("%s | %s | %s | %s" % (name, code, computed, claimed)) | |
| 468 | + print() | |
| 469 | + if failures: | |
| 470 | + print("%d FAILURE(S)" % len(failures)) | |
| 471 | + return 1 | |
| 472 | + print("ALL CHECKS PASSED (%d cases)" % len(results)) | |
| 473 | + return 0 | |
| 474 | + | |
| 475 | + | |
| 476 | +if __name__ == "__main__": | |
| 477 | + sys.exit(main()) | |
+201 −0 routes/rusirui-repro-verifier/panel/impl-integer/altcount.py added View file
| @@ -0,0 +1,201 @@ | ||
| 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)) | |
+287 −0 routes/rusirui-repro-verifier/panel/impl-integer/count.py added View file
| @@ -0,0 +1,287 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Count distinct circles of radius exactly 1 through >= 3 of n rational points. | |
| 3 | + | |
| 4 | +Usage: python3 count.py <configuration.json> | |
| 5 | + | |
| 6 | +Exact integer arithmetic only: no floats, no fractions.Fraction, no square | |
| 7 | +roots taken as values -- square roots appear only as perfect-square tests. | |
| 8 | + | |
| 9 | +Derivation used | |
| 10 | +--------------- | |
| 11 | +1. Common scale. Let L be the lcm of the denominators of every coordinate, so | |
| 12 | + point i is the integer pair (Xi, Yi) meaning (Xi/L, Yi/L). In the scaled | |
| 13 | + plane the unit circle has radius exactly L and every comparison is integral. | |
| 14 | + | |
| 15 | +2. Circumcenter. For a non-collinear triple take u = (a, b) = Pj - Pi, | |
| 16 | + v = (c, d) = Pk - Pi and D = ad - bc != 0. "C is equidistant from Pi, Pj" | |
| 17 | + is the linear equation 2 u.(C - Pi) = |u|^2, likewise for v; Cramer's rule | |
| 18 | + on the two equations gives | |
| 19 | + C = (Xi + P/(2D), Yi + Q/(2D)), | |
| 20 | + P = d(a^2 + b^2) - b(c^2 + d^2), Q = a(c^2 + d^2) - c(a^2 + b^2). | |
| 21 | + The squared distance to Pi is then (P^2 + Q^2)/(4 D^2), so the circle has | |
| 22 | + radius 1 in the original plane iff its scaled radius is L, iff | |
| 23 | + P^2 + Q^2 == 4 D^2 L^2. (no sqrt) | |
| 24 | + That identity is necessary and sufficient; it is preceded by the same | |
| 25 | + congruence modulo two primes, which is only necessary, so the pre-filter can | |
| 26 | + drop a triple only when the exact test would reject it too. It exists | |
| 27 | + because the common denominator of many large denominators can make every | |
| 28 | + integer thousands of digits long even though no circle is ever found. | |
| 29 | + | |
| 30 | +3. Dedup. The center is stored as the canonical integer triple | |
| 31 | + (Nx, Ny, 2D) reduced by g = gcd(|Nx|, |Ny|, |2D|) with positive third | |
| 32 | + entry, Nx = 2D*Xi + P, Ny = 2D*Yi + Q. A canonical triple is unique for a | |
| 33 | + rational pair, so equal centers collapse and distinct centers never merge. | |
| 34 | + | |
| 35 | +4. Completeness. A line meets a circle in at most two points, so any three of | |
| 36 | + the points on one circle are non-collinear and that circle is the | |
| 37 | + circumcircle of such a triple. Enumerating all non-collinear triples | |
| 38 | + therefore finds every circle through >= 3 points, each with at least 3 | |
| 39 | + points by construction. | |
| 40 | + | |
| 41 | +5. Incidences. With canonical center (nx/m, ny/m) in the scaled plane, point | |
| 42 | + (Xi, Yi) lies on it iff (m*Xi - nx)^2 + (m*Yi - ny)^2 == (m*L)^2; this is | |
| 43 | + used to recount the points of every kept circle. | |
| 44 | + | |
| 45 | +Output center in the original plane: (nx/(m*L), ny/(m*L)), reduced. | |
| 46 | +""" | |
| 47 | + | |
| 48 | +import json | |
| 49 | +import sys | |
| 50 | +from functools import cmp_to_key | |
| 51 | +from math import gcd | |
| 52 | + | |
| 53 | +USAGE = "usage: python3 count.py <configuration.json>" | |
| 54 | +DIGITS = frozenset("0123456789") | |
| 55 | + | |
| 56 | +# Exactness-preserving pre-filter. The exact radius test of a triple is | |
| 57 | +# P^2 + Q^2 == 4 D^2 L^2; if it holds then it holds modulo every prime, so a | |
| 58 | +# triple whose congruence fails cannot be a unit circle and is dropped before | |
| 59 | +# the large multiplications. A triple that passes is still decided by the | |
| 60 | +# exact test, so the filter never changes an answer; it only avoids work with | |
| 61 | +# the very large integers a common denominator of big denominators produces. | |
| 62 | +FILTER_PRIMES = (1000000007, 998244353) | |
| 63 | + | |
| 64 | + | |
| 65 | +class Invalid(Exception): | |
| 66 | + """The configuration file is not a valid input.""" | |
| 67 | + | |
| 68 | + | |
| 69 | +def reduce_pair(num, den): | |
| 70 | + """Reduce num/den with den > 0 to lowest terms (gcd folded into the sign).""" | |
| 71 | + g = gcd(abs(num), den) | |
| 72 | + return (num // g, den // g) | |
| 73 | + | |
| 74 | + | |
| 75 | +def parse_coordinate(value, where): | |
| 76 | + """Return a reduced (numerator, denominator) with denominator > 0.""" | |
| 77 | + if isinstance(value, bool): | |
| 78 | + raise Invalid(where + ": boolean coordinate") | |
| 79 | + if isinstance(value, int): | |
| 80 | + return (value, 1) | |
| 81 | + if isinstance(value, float): | |
| 82 | + raise Invalid(where + ": floating-point coordinate; expected an" | |
| 83 | + " integer or a string \"p/q\"") | |
| 84 | + if not isinstance(value, str): | |
| 85 | + raise Invalid(where + ": coordinate must be an integer or a string" | |
| 86 | + " \"p/q\"") | |
| 87 | + body = value | |
| 88 | + sign = 1 | |
| 89 | + if body[:1] in ("+", "-"): | |
| 90 | + if body[0] == "-": | |
| 91 | + sign = -1 | |
| 92 | + body = body[1:] | |
| 93 | + slash = body.find("/") | |
| 94 | + if slash < 0: | |
| 95 | + raise Invalid(where + ": %r is not a fraction \"p/q\"" % (value,)) | |
| 96 | + num_text = body[:slash] | |
| 97 | + den_text = body[slash + 1:] | |
| 98 | + if not num_text or not den_text: | |
| 99 | + raise Invalid(where + ": %r is not a fraction \"p/q\"" % (value,)) | |
| 100 | + for text in (num_text, den_text): | |
| 101 | + for char in text: | |
| 102 | + if char not in DIGITS: | |
| 103 | + raise Invalid(where + ": %r is not a fraction \"p/q\"" | |
| 104 | + % (value,)) | |
| 105 | + den = int(den_text) | |
| 106 | + if den == 0: | |
| 107 | + raise Invalid(where + ": zero denominator") | |
| 108 | + return reduce_pair(sign * int(num_text), den) | |
| 109 | + | |
| 110 | + | |
| 111 | +def compare_centers(left, right): | |
| 112 | + """Order centers by exact rational (x, y); denominators are positive.""" | |
| 113 | + (lxn, lxd), (lyn, lyd) = left | |
| 114 | + (rxn, rxd), (ryn, ryd) = right | |
| 115 | + diff = lxn * rxd - rxn * lxd | |
| 116 | + if diff: | |
| 117 | + return -1 if diff < 0 else 1 | |
| 118 | + diff = lyn * ryd - ryn * lyd | |
| 119 | + if diff: | |
| 120 | + return -1 if diff < 0 else 1 | |
| 121 | + return 0 | |
| 122 | + | |
| 123 | + | |
| 124 | +def solve(points): | |
| 125 | + """points: [( (xn, xd), (yn, yd) ), ...] reduced. | |
| 126 | + | |
| 127 | + Return the centers of all distinct unit circles through >= 3 of the points, | |
| 128 | + as reduced ((xn, xd), (yn, yd)) pairs sorted by exact (x, y). | |
| 129 | + """ | |
| 130 | + n = len(points) | |
| 131 | + | |
| 132 | + # 1. Common denominator: point i is (xs[i]/scale, ys[i]/scale). | |
| 133 | + scale = 1 | |
| 134 | + for px, py in points: | |
| 135 | + for _, den in (px, py): | |
| 136 | + scale = scale // gcd(scale, den) * den | |
| 137 | + xs = [0] * n | |
| 138 | + ys = [0] * n | |
| 139 | + for i, (px, py) in enumerate(points): | |
| 140 | + xs[i] = px[0] * (scale // px[1]) | |
| 141 | + ys[i] = py[0] * (scale // py[1]) | |
| 142 | + | |
| 143 | + # 2./3. All non-collinear triples, radius test, canonical center. | |
| 144 | + four_l2 = 4 * scale * scale # (2 L)^2 | |
| 145 | + residues = [] | |
| 146 | + for prime in FILTER_PRIMES: | |
| 147 | + residues.append((prime, | |
| 148 | + [value % prime for value in xs], | |
| 149 | + [value % prime for value in ys], | |
| 150 | + scale % prime)) | |
| 151 | + circles = set() | |
| 152 | + for i in range(n - 2): | |
| 153 | + xi = xs[i] | |
| 154 | + yi = ys[i] | |
| 155 | + for j in range(i + 1, n - 1): | |
| 156 | + a = xs[j] - xi | |
| 157 | + b = ys[j] - yi | |
| 158 | + ab2 = a * a + b * b | |
| 159 | + for k in range(j + 1, n): | |
| 160 | + pass_filter = True | |
| 161 | + for prime, mod_x, mod_y, mod_l in residues: | |
| 162 | + fa = mod_x[j] - mod_x[i] | |
| 163 | + fb = mod_y[j] - mod_y[i] | |
| 164 | + fc = mod_x[k] - mod_x[i] | |
| 165 | + fd = mod_y[k] - mod_y[i] | |
| 166 | + fab = fa * fa + fb * fb | |
| 167 | + fcd = fc * fc + fd * fd | |
| 168 | + fdet = fa * fd - fb * fc | |
| 169 | + fp = fd * fab - fb * fcd | |
| 170 | + fq = fa * fcd - fc * fab | |
| 171 | + if (fp * fp + fq * fq | |
| 172 | + - 4 * fdet * fdet * mod_l * mod_l) % prime: | |
| 173 | + pass_filter = False | |
| 174 | + break | |
| 175 | + if not pass_filter: | |
| 176 | + continue | |
| 177 | + c = xs[k] - xi | |
| 178 | + d = ys[k] - yi | |
| 179 | + det = a * d - b * c | |
| 180 | + if det == 0: # collinear triple | |
| 181 | + continue | |
| 182 | + cd2 = c * c + d * d | |
| 183 | + px_off = d * ab2 - b * cd2 # P = Nx - 2 D Xi | |
| 184 | + py_off = a * cd2 - c * ab2 # Q = Ny - 2 D Yi | |
| 185 | + if px_off * px_off + py_off * py_off != four_l2 * det * det: | |
| 186 | + continue # circumradius != 1 | |
| 187 | + nx = 2 * det * xi + px_off | |
| 188 | + ny = 2 * det * yi + py_off | |
| 189 | + den = 2 * det | |
| 190 | + g = gcd(gcd(abs(nx), abs(ny)), abs(den)) | |
| 191 | + nx //= g | |
| 192 | + ny //= g | |
| 193 | + den //= g | |
| 194 | + if den < 0: | |
| 195 | + nx = -nx | |
| 196 | + ny = -ny | |
| 197 | + den = -den | |
| 198 | + circles.add((nx, ny, den)) | |
| 199 | + | |
| 200 | + # 5. Recount incidences exactly; the center in the original plane is | |
| 201 | + # (nx/(den*scale), ny/(den*scale)). | |
| 202 | + centers = [] | |
| 203 | + for nx, ny, den in circles: | |
| 204 | + den2_l2 = den * den * scale * scale | |
| 205 | + on_circle = 0 | |
| 206 | + for idx in range(n): | |
| 207 | + u = den * xs[idx] - nx | |
| 208 | + v = den * ys[idx] - ny | |
| 209 | + if u * u + v * v == den2_l2: | |
| 210 | + on_circle += 1 | |
| 211 | + if on_circle < 3: # impossible by construction; keeps count honest | |
| 212 | + continue | |
| 213 | + total = den * scale | |
| 214 | + centers.append((reduce_pair(nx, total), reduce_pair(ny, total))) | |
| 215 | + | |
| 216 | + centers.sort(key=cmp_to_key(compare_centers)) | |
| 217 | + return centers | |
| 218 | + | |
| 219 | + | |
| 220 | +def read_points(document): | |
| 221 | + """Validate the document; return (n, points) or raise Invalid.""" | |
| 222 | + if not isinstance(document, dict): | |
| 223 | + raise Invalid("the configuration must be a JSON object") | |
| 224 | + schema = document.get("schema") | |
| 225 | + if isinstance(schema, bool) or not isinstance(schema, int) or schema != 1: | |
| 226 | + raise Invalid("schema must be the integer 1") | |
| 227 | + raw_points = document.get("points") | |
| 228 | + if not isinstance(raw_points, list): | |
| 229 | + raise Invalid("points must be a list") | |
| 230 | + n = len(raw_points) | |
| 231 | + if n < 3 or n > 80: | |
| 232 | + raise Invalid("need 3 to 80 points, got %d" % n) | |
| 233 | + points = [] | |
| 234 | + seen = set() | |
| 235 | + for index, item in enumerate(raw_points): | |
| 236 | + if not isinstance(item, list) or len(item) != 2: | |
| 237 | + raise Invalid("point %d is not a pair [x, y]" % index) | |
| 238 | + px = parse_coordinate(item[0], "point %d x" % index) | |
| 239 | + py = parse_coordinate(item[1], "point %d y" % index) | |
| 240 | + if (px, py) in seen: | |
| 241 | + raise Invalid("point %d repeats an earlier point" % index) | |
| 242 | + seen.add((px, py)) | |
| 243 | + points.append((px, py)) | |
| 244 | + return n, points | |
| 245 | + | |
| 246 | + | |
| 247 | +def format_rational(pair): | |
| 248 | + num, den = pair | |
| 249 | + if den == 1: | |
| 250 | + return str(num) | |
| 251 | + return "%d/%d" % (num, den) | |
| 252 | + | |
| 253 | + | |
| 254 | +def main(argv): | |
| 255 | + if len(argv) != 2: | |
| 256 | + sys.stderr.write(USAGE + "\n") | |
| 257 | + return 1 | |
| 258 | + try: | |
| 259 | + with open(argv[1], "rb") as handle: | |
| 260 | + blob = handle.read() | |
| 261 | + except OSError as exc: | |
| 262 | + sys.stderr.write("cannot read %s: %s\n" % (argv[1], exc.strerror or exc)) | |
| 263 | + return 1 | |
| 264 | + try: | |
| 265 | + document = json.loads(blob) | |
| 266 | + except (ValueError, RecursionError) as exc: | |
| 267 | + sys.stderr.write("not valid JSON: %s\n" % (exc,)) | |
| 268 | + return 1 | |
| 269 | + try: | |
| 270 | + n, points = read_points(document) | |
| 271 | + except Invalid as exc: | |
| 272 | + sys.stderr.write("%s\n" % (exc,)) | |
| 273 | + return 1 | |
| 274 | + | |
| 275 | + centers = solve(points) | |
| 276 | + payload = { | |
| 277 | + "n": n, | |
| 278 | + "unit_circles": len(centers), | |
| 279 | + "centers": [[format_rational(cx), format_rational(cy)] | |
| 280 | + for cx, cy in centers], | |
| 281 | + } | |
| 282 | + sys.stdout.write(json.dumps(payload) + "\n") | |
| 283 | + return 0 | |
| 284 | + | |
| 285 | + | |
| 286 | +if __name__ == "__main__": | |
| 287 | + sys.exit(main(sys.argv)) | |
+492 −0 routes/rusirui-repro-verifier/panel/impl-integer/selftest.py added View file
| @@ -0,0 +1,492 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Self-test for count.py. | |
| 3 | + | |
| 4 | +Runs, in order: | |
| 5 | + * the twelve sample fixtures and the 80-point grid fixture through the CLI; | |
| 6 | + * a set of adversarial configurations invented here (written to ./adversarial); | |
| 7 | + * a set of invalid configurations that must be rejected; | |
| 8 | + * a randomized cross-check of count.py against altcount.py, an independently | |
| 9 | + written second solver that enumerates pairs instead of triples; | |
| 10 | + * a check that count.py runs from an unrelated working directory. | |
| 11 | + | |
| 12 | +Exit status 0 iff every expectation holds. | |
| 13 | +""" | |
| 14 | + | |
| 15 | +import json | |
| 16 | +import os | |
| 17 | +import random | |
| 18 | +import subprocess | |
| 19 | +import sys | |
| 20 | +import time | |
| 21 | +from math import gcd | |
| 22 | + | |
| 23 | +HERE = os.path.dirname(os.path.abspath(__file__)) | |
| 24 | +ROOT = os.path.abspath(os.path.join(HERE, os.pardir, os.pardir, os.pardir, os.pardir)) | |
| 25 | +COUNT = os.path.join(HERE, "count.py") | |
| 26 | +ALT = os.path.join(HERE, "altcount.py") | |
| 27 | +CASE_DIR = os.path.join(HERE, "adversarial") | |
| 28 | +PY = sys.executable | |
| 29 | + | |
| 30 | +FAILURES = [] | |
| 31 | + | |
| 32 | + | |
| 33 | +def run_cli(script, path, cwd=None): | |
| 34 | + started = time.time() | |
| 35 | + proc = subprocess.run([PY, "-I", script, path], | |
| 36 | + capture_output=True, text=True, cwd=cwd) | |
| 37 | + return proc.returncode, proc.stdout, proc.stderr, time.time() - started | |
| 38 | + | |
| 39 | + | |
| 40 | +def check(ok, label, detail=""): | |
| 41 | + if not ok: | |
| 42 | + FAILURES.append("%s: %s" % (label, detail)) | |
| 43 | + return ok | |
| 44 | + | |
| 45 | + | |
| 46 | +def load_count(exit_code, stdout): | |
| 47 | + if exit_code != 0: | |
| 48 | + return None | |
| 49 | + try: | |
| 50 | + return json.loads(stdout) | |
| 51 | + except ValueError: | |
| 52 | + return None | |
| 53 | + | |
| 54 | + | |
| 55 | +# -------------------------------------------------------------------------- | |
| 56 | +# 1. fixtures | |
| 57 | +# -------------------------------------------------------------------------- | |
| 58 | + | |
| 59 | +FIXTURE_DIR = os.path.join(ROOT, "routes", "rusirui-repro-verifier", "fixtures") | |
| 60 | + | |
| 61 | +# expectation kinds: "match" = exit 0 and computed == claimed, | |
| 62 | +# "mismatch" = exit 0 and computed != claimed, | |
| 63 | +# "invalid" = exit 1, nothing on stdout. | |
| 64 | +FIXTURES = [ | |
| 65 | + ("samples/accept/collinear", "match"), | |
| 66 | + ("samples/accept/dedup", "match"), | |
| 67 | + ("samples/accept/grid", "match"), | |
| 68 | + ("samples/accept/nonunit", "match"), | |
| 69 | + ("samples/accept/rational-center", "match"), | |
| 70 | + ("samples/accept/three", "match"), | |
| 71 | + ("samples/reject/collinear", "mismatch"), | |
| 72 | + ("samples/reject/duplicate", "invalid"), | |
| 73 | + ("samples/reject/float", "invalid"), | |
| 74 | + ("samples/reject/nearly-unit", "mismatch"), | |
| 75 | + ("samples/reject/overcount", "mismatch"), | |
| 76 | + ("samples/reject/undercount", "mismatch"), | |
| 77 | + ("grid80", "match"), | |
| 78 | +] | |
| 79 | + | |
| 80 | + | |
| 81 | +def fixture_report(): | |
| 82 | + print("== fixtures ==") | |
| 83 | + for rel, kind in FIXTURES: | |
| 84 | + path = os.path.join(FIXTURE_DIR, rel, "configuration.json") | |
| 85 | + with open(path, "rb") as handle: | |
| 86 | + claimed = json.loads(handle.read()).get("unit_circles", "-") | |
| 87 | + code, out, err, elapsed = run_cli(COUNT, path) | |
| 88 | + parsed = load_count(code, out) | |
| 89 | + computed = parsed["unit_circles"] if parsed else "-" | |
| 90 | + print("%s | %s | %s | %s (%.2fs)" | |
| 91 | + % (rel + "/configuration.json", code, computed, claimed, elapsed)) | |
| 92 | + if kind == "invalid": | |
| 93 | + check(code == 1, rel, "expected exit 1, got %d" % code) | |
| 94 | + check(out == "", rel, "expected empty stdout on invalid input") | |
| 95 | + else: | |
| 96 | + check(code == 0, rel, "expected exit 0, got %d (%s)" | |
| 97 | + % (code, err.strip())) | |
| 98 | + if kind == "match": | |
| 99 | + check(computed == claimed, rel, | |
| 100 | + "computed %s != claimed %s" % (computed, claimed)) | |
| 101 | + else: | |
| 102 | + check(computed != claimed, rel, | |
| 103 | + "computed %s equals claimed %s" % (computed, claimed)) | |
| 104 | + # second implementation must agree with the first, byte for byte | |
| 105 | + alt_code, alt_out, alt_err, _ = run_cli(ALT, path) | |
| 106 | + check((alt_code, alt_out) == (code, out), rel, | |
| 107 | + "altcount disagreed: exit %d vs %d, stdout %r vs %r (%s)" | |
| 108 | + % (alt_code, code, alt_out, out, alt_err.strip())) | |
| 109 | + | |
| 110 | + | |
| 111 | +# -------------------------------------------------------------------------- | |
| 112 | +# 2. adversarial cases | |
| 113 | +# -------------------------------------------------------------------------- | |
| 114 | + | |
| 115 | +def rat(num, den=1): | |
| 116 | + if den < 0: | |
| 117 | + num, den = -num, -den | |
| 118 | + g = gcd(abs(num), den) | |
| 119 | + return (num // g, den // g) | |
| 120 | + | |
| 121 | + | |
| 122 | +def add(left, right): | |
| 123 | + return rat(left[0] * right[1] + right[0] * left[1], left[1] * right[1]) | |
| 124 | + | |
| 125 | + | |
| 126 | +def text(pair): | |
| 127 | + return str(pair[0]) if pair[1] == 1 else "%d/%d" % pair | |
| 128 | + | |
| 129 | + | |
| 130 | +def doc_of(points, claimed=None): | |
| 131 | + """points: [( (xn,xd), (yn,yd) ), ...] -> configuration document. | |
| 132 | + | |
| 133 | + Integral coordinates are written as JSON integers and non-integral ones as | |
| 134 | + "p/q" strings, the only two forms the input schema allows. | |
| 135 | + """ | |
| 136 | + def wire(pair): | |
| 137 | + return pair[0] if pair[1] == 1 else "%d/%d" % pair | |
| 138 | + | |
| 139 | + body = [[wire(px), wire(py)] for px, py in points] | |
| 140 | + document = {"schema": 1, "points": body} | |
| 141 | + if claimed is not None: | |
| 142 | + document["unit_circles"] = claimed | |
| 143 | + return document | |
| 144 | + | |
| 145 | + | |
| 146 | +UNIT_VECTORS = [] | |
| 147 | +for _u, _v in ((0, 1), (1, 0), (1, 1), (1, 2), (2, 1), (1, 3), (3, 1), | |
| 148 | + (2, 3), (3, 2), (1, 4), (4, 1), (2, 5), (5, 2)): | |
| 149 | + _d = _v * _v + _u * _u | |
| 150 | + UNIT_VECTORS.append(((rat(_v * _v - _u * _u, _d), rat(2 * _u * _v, _d)))) | |
| 151 | + | |
| 152 | + | |
| 153 | +def circle_points(center, vectors): | |
| 154 | + cx, cy = center | |
| 155 | + return [(add(cx, vx), add(cy, vy)) for vx, vy in vectors] | |
| 156 | + | |
| 157 | + | |
| 158 | +def adversarial_cases(): | |
| 159 | + cases = [] | |
| 160 | + | |
| 161 | + # (a) eight rational points on one circle; ten cocircular triples must fold | |
| 162 | + # into a single center, with denominators 5 and 13 forcing L = 65. | |
| 163 | + pts = [((1, 1), (0, 1)), ((-1, 1), (0, 1)), ((0, 1), (1, 1)), ((0, 1), (-1, 1)), | |
| 164 | + ((rat(3, 5), rat(4, 5))), ((rat(-3, 5), rat(4, 5))), | |
| 165 | + ((rat(5, 13), rat(12, 13))), ((rat(-5, 13), rat(12, 13)))] | |
| 166 | + cases.append(("four_on_one_circle", doc_of(pts, 1), 1, | |
| 167 | + [((0, 1), (0, 1))])) | |
| 168 | + | |
| 169 | + # (b) two points exactly 2 apart: the unit circle through them is centred at | |
| 170 | + # the midpoint and also carries two more points. | |
| 171 | + pts = [((0, 1), (0, 1)), ((2, 1), (0, 1)), ((1, 1), (1, 1)), ((1, 1), (-1, 1))] | |
| 172 | + cases.append(("distance_two", doc_of(pts, 1), 1, [((1, 1), (0, 1))])) | |
| 173 | + | |
| 174 | + # (c) same pair at distance 2 but the third point misses: circumcentre | |
| 175 | + # (1, 3/4), radius 5/4. Must not count. | |
| 176 | + pts = [((0, 1), (0, 1)), ((2, 1), (0, 1)), ((1, 1), (2, 1))] | |
| 177 | + cases.append(("distance_two_miss", doc_of(pts, 1), 0, [])) | |
| 178 | + | |
| 179 | + # (d) four collinear points. | |
| 180 | + pts = [((i, 1), (0, 1)) for i in range(4)] | |
| 181 | + cases.append(("collinear_four", doc_of(pts, 1), 0, [])) | |
| 182 | + | |
| 183 | + # (e) (0,0),(1,0) lie on a unit circle only with an irrational centre, so a | |
| 184 | + # third rational point can never complete one; here the circumradius of | |
| 185 | + # the triangle is sqrt(2)/2 anyway. | |
| 186 | + pts = [((0, 1), (0, 1)), ((1, 1), (0, 1)), ((1, 1), (1, 1))] | |
| 187 | + cases.append(("irrational_center_pair", doc_of(pts, 1), 0, [])) | |
| 188 | + | |
| 189 | + # (f) four points on the unit circle centred at (1/3, 2/7); the common | |
| 190 | + # denominator is 105 and the answer has a non-integral centre. | |
| 191 | + centre = (rat(1, 3), rat(2, 7)) | |
| 192 | + pts = circle_points(centre, [UNIT_VECTORS[2], UNIT_VECTORS[5], | |
| 193 | + UNIT_VECTORS[10], UNIT_VECTORS[8]]) | |
| 194 | + cases.append(("rational_center_105", doc_of(pts, 1), 1, [centre])) | |
| 195 | + | |
| 196 | + # (g) two disjoint unit circles, exercising sort order and dedup across | |
| 197 | + # many triples. | |
| 198 | + pts = circle_points(((0, 1), (0, 1)), | |
| 199 | + [UNIT_VECTORS[0], UNIT_VECTORS[2], | |
| 200 | + UNIT_VECTORS[4], UNIT_VECTORS[6]]) | |
| 201 | + pts += circle_points(((10, 1), (0, 1)), | |
| 202 | + [UNIT_VECTORS[1], UNIT_VECTORS[3], | |
| 203 | + UNIT_VECTORS[5], UNIT_VECTORS[7]]) | |
| 204 | + cases.append(("two_circles", doc_of(pts, 2), 2, | |
| 205 | + [((0, 1), (0, 1)), ((10, 1), (0, 1))])) | |
| 206 | + | |
| 207 | + # (h) centres at (-1,0), (0,1) and (1,0) -- three of them, since (-1,1), | |
| 208 | + # (0,0), (1,1) are also unit apart from (0,1). The printed order must | |
| 209 | + # be the exact rational ascending order, not string order. | |
| 210 | + pts = [((-2, 1), (0, 1)), ((-1, 1), (1, 1)), ((0, 1), (0, 1)), | |
| 211 | + ((2, 1), (0, 1)), ((1, 1), (1, 1))] | |
| 212 | + cases.append(("sorted_negative", doc_of(pts, 3), 3, | |
| 213 | + [((-1, 1), (0, 1)), ((0, 1), (1, 1)), ((1, 1), (0, 1))])) | |
| 214 | + | |
| 215 | + # (i) a near miss whose radius is 1 + 1.25e-25: a double would round it to | |
| 216 | + # exactly 1 and count it. Exact arithmetic must say no. | |
| 217 | + big = 10 ** 12 | |
| 218 | + pts = [((0, 1), (0, 1)), ((2, 1), (0, 1)), ((1, 1), rat(big + 1, big))] | |
| 219 | + cases.append(("nearly_unit_tiny", doc_of(pts, 1), 0, [])) | |
| 220 | + | |
| 221 | + # (j) the same with v = 1 exactly: a real unit circle through all three. | |
| 222 | + pts = [((0, 1), (0, 1)), ((2, 1), (0, 1)), ((1, 1), (1, 1))] | |
| 223 | + cases.append(("exact_unit", doc_of(pts, 1), 1, [((1, 1), (0, 1))])) | |
| 224 | + | |
| 225 | + # (k) 80 points of the half-integer 10x8 grid. Scaling by 2 turns them | |
| 226 | + # into the full 10x8 lattice with radius 2. A pair at distance^2 q has | |
| 227 | + # a rational centre iff (16-q)q is a square, and among the sums of two | |
| 228 | + # squares q <= 16 only q = 16 (axis pairs, lattice centre) and q = 8 | |
| 229 | + # (diagonal pairs, half-integer centre) qualify; a half-integer centre | |
| 230 | + # meets no lattice point at distance 2 (odd squares are 1 mod 8, so | |
| 231 | + # their sum is 2 mod 8, never 16). Lattice centres with at least three | |
| 232 | + # of their four two-step neighbours: 6*4 = 24 interior ones with four | |
| 233 | + # and 8+8+12+12 = 40 on the two-step edge bands with three, so 64. | |
| 234 | + pts = [] | |
| 235 | + for j in range(8): | |
| 236 | + for i in range(10): | |
| 237 | + pts.append(((rat(i, 2)), (rat(j, 2)))) | |
| 238 | + cases.append(("half_grid_80", doc_of(pts, 64), 64, None)) | |
| 239 | + | |
| 240 | + # (l) fifteen disjoint unit circles, four points each: 60 points, and all | |
| 241 | + # fifteen centres must be reported. | |
| 242 | + pts = [] | |
| 243 | + centres = [] | |
| 244 | + for k in range(15): | |
| 245 | + centre = ((20 * k, 1), (0, 1)) | |
| 246 | + centres.append(centre) | |
| 247 | + vecs = [UNIT_VECTORS[(4 * k + t) % len(UNIT_VECTORS)] for t in range(4)] | |
| 248 | + pts += circle_points(centre, vecs) | |
| 249 | + cases.append(("many_circles", doc_of(pts, 15), 15, centres)) | |
| 250 | + | |
| 251 | + # (m) a unit circle far from the origin, so that the modular pre-filter sees | |
| 252 | + # residues that differ from the coordinates themselves. | |
| 253 | + centre = ((10 ** 12, 1), (10 ** 12, 1)) | |
| 254 | + pts = circle_points(centre, [UNIT_VECTORS[0], UNIT_VECTORS[1], | |
| 255 | + UNIT_VECTORS[2], UNIT_VECTORS[4]]) | |
| 256 | + cases.append(("huge_offset_circle", doc_of(pts, 1), 1, [centre])) | |
| 257 | + | |
| 258 | + # (n) a unit circle whose points have 32-digit denominators: a true | |
| 259 | + # positive that the pre-filter must not lose, cross-checked against the | |
| 260 | + # unfiltered pair-based solver. | |
| 261 | + a = 10 ** 16 + 1 | |
| 262 | + b = 10 ** 16 + 3 | |
| 263 | + d = b * b + a * a | |
| 264 | + huge_vectors = [(rat(b * b - a * a, d), rat(2 * a * b, d)), | |
| 265 | + (rat(a * a - b * b, d), rat(2 * a * b, d)), | |
| 266 | + ((0, 1), (1, 1)), | |
| 267 | + ((1, 1), (0, 1))] | |
| 268 | + centre = (rat(1, 3), rat(2, 7)) | |
| 269 | + pts = circle_points(centre, huge_vectors) | |
| 270 | + cases.append(("huge_denominator_circle", doc_of(pts, 1), 1, [centre])) | |
| 271 | + | |
| 272 | + return cases | |
| 273 | + | |
| 274 | + | |
| 275 | +def adversarial_report(): | |
| 276 | + print("== adversarial cases ==") | |
| 277 | + os.makedirs(CASE_DIR, exist_ok=True) | |
| 278 | + for name, document, expected, centres in adversarial_cases(): | |
| 279 | + path = os.path.join(CASE_DIR, name + ".json") | |
| 280 | + with open(path, "w", encoding="utf-8") as handle: | |
| 281 | + json.dump(document, handle, indent=1) | |
| 282 | + handle.write("\n") | |
| 283 | + code, out, err, elapsed = run_cli(COUNT, path) | |
| 284 | + alt_code, alt_out, alt_err, _ = run_cli(ALT, path) | |
| 285 | + parsed = load_count(code, out) | |
| 286 | + computed = parsed["unit_circles"] if parsed else "-" | |
| 287 | + print("%s | %d | %s | claimed %s (%.2fs)" | |
| 288 | + % (name, code, computed, document.get("unit_circles"), elapsed)) | |
| 289 | + check(code == 0, name, "expected exit 0, got %d (%s)" % (code, err.strip())) | |
| 290 | + check(computed == expected, name, | |
| 291 | + "expected %s circles, got %s" % (expected, computed)) | |
| 292 | + check((alt_code, alt_out) == (code, out), name, | |
| 293 | + "altcount disagreed: %r vs %r" % (alt_out, out)) | |
| 294 | + if centres is not None and parsed is not None: | |
| 295 | + reported = [tuple(centre) for centre in parsed["centers"]] | |
| 296 | + for centre in centres: | |
| 297 | + want = (text(centre[0]), text(centre[1])) | |
| 298 | + check(want in reported, name, "missing centre %s" % (want,)) | |
| 299 | + | |
| 300 | + | |
| 301 | +# -------------------------------------------------------------------------- | |
| 302 | +# 3. invalid inputs | |
| 303 | +# -------------------------------------------------------------------------- | |
| 304 | + | |
| 305 | +def invalid_report(): | |
| 306 | + print("== invalid inputs ==") | |
| 307 | + folder = os.path.join(CASE_DIR, "invalid") | |
| 308 | + os.makedirs(folder, exist_ok=True) | |
| 309 | + good = [[0, 0], [1, 0], [0, 1]] | |
| 310 | + cases = [ | |
| 311 | + ("schema_2", {"schema": 2, "points": good, "unit_circles": 0}), | |
| 312 | + ("schema_float", {"schema": 1.0, "points": good, "unit_circles": 0}), | |
| 313 | + ("schema_bool", {"schema": True, "points": good, "unit_circles": 0}), | |
| 314 | + ("schema_missing", {"points": good, "unit_circles": 0}), | |
| 315 | + ("n_2", {"schema": 1, "points": [[0, 0], [1, 0]]}), | |
| 316 | + ("n_81", {"schema": 1, "points": [[i, 0] for i in range(81)]}), | |
| 317 | + ("duplicate_repr", {"schema": 1, | |
| 318 | + "points": [["1/2", 0], ["2/4", 0], [0, 1]]}), | |
| 319 | + ("bool_coord", {"schema": 1, "points": [[True, 0], [1, 0], [0, 1]]}), | |
| 320 | + ("float_coord", {"schema": 1, "points": [[1.0, 0], [1, 0], [0, 1]]}), | |
| 321 | + ("string_decimal", {"schema": 1, "points": [["0.5", 0], [1, 0], [0, 1]]}), | |
| 322 | + ("string_space", {"schema": 1, "points": [[" 1/2", 0], [1, 0], [0, 1]]}), | |
| 323 | + ("string_integer", {"schema": 1, "points": [["1", 0], [1, 0], [0, 1]]}), | |
| 324 | + ("zero_denominator", {"schema": 1, "points": [["1/0", 0], [1, 0], [0, 1]]}), | |
| 325 | + ("negative_denominator", {"schema": 1, | |
| 326 | + "points": [["1/-2", 0], [1, 0], [0, 1]]}), | |
| 327 | + ("point_len_3", {"schema": 1, "points": [[1, 2, 3], [1, 0], [0, 1]]}), | |
| 328 | + ("point_not_pair", {"schema": 1, "points": ["12", [1, 0], [0, 1]]}), | |
| 329 | + ("points_not_list", {"schema": 1, "points": {"a": 1}}), | |
| 330 | + ("unicode_digits", {"schema": 1, | |
| 331 | + "points": [["١/٢", 0], [1, 0], [0, 1]]}), | |
| 332 | + ] | |
| 333 | + for name, document in cases: | |
| 334 | + path = os.path.join(folder, name + ".json") | |
| 335 | + with open(path, "w", encoding="utf-8") as handle: | |
| 336 | + json.dump(document, handle) | |
| 337 | + handle.write("\n") | |
| 338 | + code, out, err, _ = run_cli(COUNT, path) | |
| 339 | + alt = run_cli(ALT, path) | |
| 340 | + print("%s | %d | %s" % (name, code, (err.strip().splitlines() or [""])[0])) | |
| 341 | + check(code == 1, name, "expected exit 1, got %d" % code) | |
| 342 | + check(out == "", name, "expected empty stdout") | |
| 343 | + check((alt[0], alt[1]) == (code, out), name, | |
| 344 | + "altcount differed: %r" % (alt[2].strip(),)) | |
| 345 | + | |
| 346 | + raw_cases = [("float_exponent", '{"schema": 1, "points": [[1e3, 0], [1, 0], [0, 1]]}'), | |
| 347 | + ("not_object", '[]'), | |
| 348 | + ("bad_json", '{"schema": 1, "points": ['), | |
| 349 | + ("empty_file", "")] | |
| 350 | + for name, body in raw_cases: | |
| 351 | + path = os.path.join(folder, name + ".json") | |
| 352 | + with open(path, "w", encoding="utf-8") as handle: | |
| 353 | + handle.write(body) | |
| 354 | + code, out, err, _ = run_cli(COUNT, path) | |
| 355 | + alt = run_cli(ALT, path) | |
| 356 | + print("%s | %d | %s" % (name, code, (err.strip().splitlines() or [""])[0])) | |
| 357 | + check(code == 1, name, "expected exit 1, got %d" % code) | |
| 358 | + check(out == "", name, "expected empty stdout") | |
| 359 | + check((alt[0], alt[1]) == (code, out), name, "altcount differed") | |
| 360 | + | |
| 361 | + missing = os.path.join(folder, "does-not-exist.json") | |
| 362 | + code, out, err, _ = run_cli(COUNT, missing) | |
| 363 | + print("missing_file | %d | %s" % (code, (err.strip().splitlines() or [""])[0])) | |
| 364 | + check(code == 1 and out == "", "missing_file", "expected exit 1, no stdout") | |
| 365 | + | |
| 366 | + | |
| 367 | +# -------------------------------------------------------------------------- | |
| 368 | +# 4. randomized cross-check against the pair-based solver | |
| 369 | +# -------------------------------------------------------------------------- | |
| 370 | + | |
| 371 | +def randomized_report(): | |
| 372 | + print("== randomized cross-check (count.py vs altcount.py) ==") | |
| 373 | + sys.path.insert(0, HERE) | |
| 374 | + import count as impl | |
| 375 | + import altcount as altimpl | |
| 376 | + | |
| 377 | + rng = random.Random(20261128) | |
| 378 | + denoms = [1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12] | |
| 379 | + mismatches = 0 | |
| 380 | + trials = 0 | |
| 381 | + | |
| 382 | + def compare(document, label): | |
| 383 | + nonlocal mismatches, trials | |
| 384 | + trials += 1 | |
| 385 | + try: | |
| 386 | + _, pts_a = impl.read_points(json.loads(json.dumps(document))) | |
| 387 | + want = impl.solve(pts_a) | |
| 388 | + status = "solved" | |
| 389 | + except impl.Invalid: | |
| 390 | + want = None | |
| 391 | + status = "invalid" | |
| 392 | + try: | |
| 393 | + _, pts_b = altimpl.read_points(json.loads(json.dumps(document))) | |
| 394 | + got = altimpl.solve(pts_b) | |
| 395 | + except altimpl.Invalid: | |
| 396 | + got = None | |
| 397 | + if (want is None) != (got is None) or (want is not None and want != got): | |
| 398 | + mismatches += 1 | |
| 399 | + print("MISMATCH %s: %r -> %r vs %r" % (label, document, want, got)) | |
| 400 | + return want, status | |
| 401 | + | |
| 402 | + # purely random point sets | |
| 403 | + for round_index in range(40): | |
| 404 | + count_points = rng.randint(3, 14) | |
| 405 | + points = [] | |
| 406 | + seen = set() | |
| 407 | + while len(points) < count_points: | |
| 408 | + px = rat(rng.randint(-25, 25), rng.choice(denoms)) | |
| 409 | + py = rat(rng.randint(-25, 25), rng.choice(denoms)) | |
| 410 | + if (px, py) in seen: | |
| 411 | + continue | |
| 412 | + seen.add((px, py)) | |
| 413 | + points.append((px, py)) | |
| 414 | + compare(doc_of(points), "random-%d" % round_index) | |
| 415 | + | |
| 416 | + # constructed unions of unit circles plus noise | |
| 417 | + constructed_failures = 0 | |
| 418 | + for round_index in range(20): | |
| 419 | + points = [] | |
| 420 | + seen = set() | |
| 421 | + centres = [] | |
| 422 | + ks = rng.randint(1, 4) | |
| 423 | + for _ in range(ks): | |
| 424 | + centre = (rat(rng.randint(-30, 30), rng.choice(denoms)), | |
| 425 | + rat(rng.randint(-30, 30), rng.choice(denoms))) | |
| 426 | + if centre in centres: | |
| 427 | + continue | |
| 428 | + centres.append(centre) | |
| 429 | + for vec in rng.sample(UNIT_VECTORS, rng.randint(3, 5)): | |
| 430 | + pt = (add(centre[0], vec[0]), add(centre[1], vec[1])) | |
| 431 | + if pt not in seen: | |
| 432 | + seen.add(pt) | |
| 433 | + points.append(pt) | |
| 434 | + while len(points) < 3: | |
| 435 | + px = rat(rng.randint(-9, 9), 1) | |
| 436 | + py = rat(rng.randint(-9, 9), 1) | |
| 437 | + if (px, py) in seen: | |
| 438 | + continue | |
| 439 | + seen.add((px, py)) | |
| 440 | + points.append((px, py)) | |
| 441 | + rng.shuffle(points) | |
| 442 | + document = doc_of(points[:80]) | |
| 443 | + found, _ = compare(document, "constructed-%d" % round_index) | |
| 444 | + if found is None: | |
| 445 | + constructed_failures += 1 | |
| 446 | + continue | |
| 447 | + for centre in centres: | |
| 448 | + if centre not in found: | |
| 449 | + constructed_failures += 1 | |
| 450 | + print("MISSING CONSTRUCTED CENTRE %s in %s" | |
| 451 | + % (centre, [text(c) for c in centre])) | |
| 452 | + | |
| 453 | + print("trials: %d, mismatches: %d, constructed failures: %d" | |
| 454 | + % (trials, mismatches, constructed_failures)) | |
| 455 | + check(mismatches == 0, "randomized", "%d mismatches" % mismatches) | |
| 456 | + check(constructed_failures == 0, "constructive", | |
| 457 | + "%d constructed circles missing" % constructed_failures) | |
| 458 | + | |
| 459 | + | |
| 460 | +# -------------------------------------------------------------------------- | |
| 461 | +# 5. positional independence | |
| 462 | +# -------------------------------------------------------------------------- | |
| 463 | + | |
| 464 | +def cwd_report(): | |
| 465 | + print("== working-directory independence ==") | |
| 466 | + path = os.path.join(FIXTURE_DIR, "samples", "accept", "grid", "configuration.json") | |
| 467 | + import tempfile | |
| 468 | + with tempfile.TemporaryDirectory() as scratch: | |
| 469 | + code, out, err, _ = run_cli(COUNT, path, cwd=scratch) | |
| 470 | + print("run from %s | exit %d | %s" % ("a temp dir", code, out.strip()[:60])) | |
| 471 | + check(code == 0 and json.loads(out)["unit_circles"] == 5, | |
| 472 | + "cwd", "expected exit 0 and 5 circles, got %d %r %r" % (code, out, err)) | |
| 473 | + | |
| 474 | + | |
| 475 | +def main(): | |
| 476 | + fixture_report() | |
| 477 | + adversarial_report() | |
| 478 | + invalid_report() | |
| 479 | + randomized_report() | |
| 480 | + cwd_report() | |
| 481 | + print("== summary ==") | |
| 482 | + if FAILURES: | |
| 483 | + print("FAILURES: %d" % len(FAILURES)) | |
| 484 | + for item in FAILURES: | |
| 485 | + print(" " + item) | |
| 486 | + return 1 | |
| 487 | + print("all checks passed") | |
| 488 | + return 0 | |
| 489 | + | |
| 490 | + | |
| 491 | +if __name__ == "__main__": | |
| 492 | + sys.exit(main()) | |
+239 −0 routes/rusirui-repro-verifier/panel/impl-pairs/count.py added View file
| @@ -0,0 +1,239 @@ | ||
| 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)) | |
+158 −0 routes/rusirui-repro-verifier/panel/impl-pairs/stress.py added View file
| @@ -0,0 +1,158 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Stress for count.py: performance on hostile exact arithmetic, plus a | |
| 3 | +3000-round fuzz against the independent O(n^3) reference in test_count.py. | |
| 4 | + | |
| 5 | +Run: python3 stress.py | |
| 6 | +""" | |
| 7 | + | |
| 8 | +import json | |
| 9 | +import math | |
| 10 | +import os | |
| 11 | +import random | |
| 12 | +import subprocess | |
| 13 | +import sys | |
| 14 | +import time | |
| 15 | +from fractions import Fraction | |
| 16 | + | |
| 17 | +import test_count as T # positions only: the reference implementation | |
| 18 | + | |
| 19 | +HERE = os.path.dirname(os.path.abspath(__file__)) | |
| 20 | +COUNT = os.path.join(HERE, "count.py") | |
| 21 | +CASES = os.path.join(HERE, "cases") | |
| 22 | + | |
| 23 | + | |
| 24 | +def write(name, points): | |
| 25 | + os.makedirs(CASES, exist_ok=True) | |
| 26 | + path = os.path.join(CASES, name + ".json") | |
| 27 | + with open(path, "w", encoding="utf-8") as handle: | |
| 28 | + json.dump({"schema": 1, "points": points, "unit_circles": 0}, handle) | |
| 29 | + return path | |
| 30 | + | |
| 31 | + | |
| 32 | +def time_cli(name, points): | |
| 33 | + path = write(name, points) | |
| 34 | + started = time.time() | |
| 35 | + proc = subprocess.run([sys.executable, COUNT, path], capture_output=True, text=True) | |
| 36 | + elapsed = time.time() - started | |
| 37 | + return elapsed, proc | |
| 38 | + | |
| 39 | + | |
| 40 | +def random_rational(n, denominators, rng): | |
| 41 | + points = set() | |
| 42 | + while len(points) < n: | |
| 43 | + points.add((Fraction(rng.randint(-50, 50), rng.choice(denominators)), | |
| 44 | + Fraction(rng.randint(-50, 50), rng.choice(denominators)))) | |
| 45 | + return [[f"{x.numerator}/{x.denominator}", f"{y.numerator}/{y.denominator}"] | |
| 46 | + for x, y in sorted(points)] | |
| 47 | + | |
| 48 | + | |
| 49 | +def pythagorean(n, bound, rng): | |
| 50 | + """n distinct rational points on the unit circle, denominators ~ bound^2.""" | |
| 51 | + points = set() | |
| 52 | + while len(points) < n: | |
| 53 | + u = rng.randint(1, bound) | |
| 54 | + v = rng.randint(1, bound) | |
| 55 | + norm = u * u + v * v | |
| 56 | + points.add((Fraction(v * v - u * u, norm), Fraction(2 * u * v, norm))) | |
| 57 | + return [[f"{x.numerator}/{x.denominator}", f"{y.numerator}/{y.denominator}"] | |
| 58 | + for x, y in sorted(points)] | |
| 59 | + | |
| 60 | + | |
| 61 | +def lcm_digits(points): | |
| 62 | + scale = 1 | |
| 63 | + for x, y in points: | |
| 64 | + for value in (x, y): | |
| 65 | + q = int(value.split("/")[1]) | |
| 66 | + scale = scale * q // math.gcd(scale, q) | |
| 67 | + return len(str(scale)) | |
| 68 | + | |
| 69 | + | |
| 70 | +def main(): | |
| 71 | + rng = random.Random(7) | |
| 72 | + print("== CLI performance (n = 80) ==") | |
| 73 | + families = { | |
| 74 | + "den_small": random_rational(80, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37], rng), | |
| 75 | + "den_16digit": random_rational(80, [random.randrange(10**15, 10**16) | 1 for _ in range(20)], rng), | |
| 76 | + "pyth_U_10^4": pythagorean(80, 10**4, rng), | |
| 77 | + "pyth_U_10^5": pythagorean(80, 10**5, rng), | |
| 78 | + "pyth_U_10^6": pythagorean(80, 10**6, rng), | |
| 79 | + } | |
| 80 | + for name, points in families.items(): | |
| 81 | + elapsed, proc = time_cli(name, points) | |
| 82 | + out = json.loads(proc.stdout) if proc.stdout else None | |
| 83 | + print(f"{name} | lcm digits {lcm_digits(points)} | exit {proc.returncode} | " | |
| 84 | + f"{elapsed:.2f}s | count {out['unit_circles'] if out else 'n/a'}") | |
| 85 | + | |
| 86 | + print() | |
| 87 | + print("== fuzz vs O(n^3) reference (3000 rounds) ==") | |
| 88 | + structured_cache = {} | |
| 89 | + | |
| 90 | + def structured(centre, k): | |
| 91 | + a, b = centre | |
| 92 | + points = set() | |
| 93 | + while len(points) < k: | |
| 94 | + u = rng.randint(-9, 9) | |
| 95 | + v = rng.randint(1, 9) | |
| 96 | + norm = u * u + v * v | |
| 97 | + points.add((Fraction(a) + Fraction(v * v - u * u, norm), | |
| 98 | + Fraction(b) + Fraction(2 * u * v, norm))) | |
| 99 | + return points | |
| 100 | + | |
| 101 | + bad = 0 | |
| 102 | + rounds = 0 | |
| 103 | + started = time.time() | |
| 104 | + for index in range(3000): | |
| 105 | + mode = index % 6 | |
| 106 | + if mode == 0: | |
| 107 | + n = rng.randint(3, 10) | |
| 108 | + points = set() | |
| 109 | + while len(points) < n: | |
| 110 | + points.add((Fraction(rng.randint(-8, 8), rng.choice([1, 2, 3, 4, 5, 6])), | |
| 111 | + Fraction(rng.randint(-8, 8), rng.choice([1, 2, 3, 4, 5, 6])))) | |
| 112 | + points = sorted(points) | |
| 113 | + elif mode == 1: | |
| 114 | + centre = (Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3, 4])), | |
| 115 | + Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3, 4]))) | |
| 116 | + points = sorted(structured(centre, rng.randint(3, 6))) | |
| 117 | + elif mode == 2: | |
| 118 | + pool = [(Fraction(x), Fraction(y)) for x in range(-4, 5) for y in range(-4, 5)] | |
| 119 | + points = sorted(rng.sample(pool, rng.randint(3, 14))) | |
| 120 | + elif mode == 3: | |
| 121 | + c1 = (Fraction(rng.randint(-2, 2)), Fraction(rng.randint(-2, 2))) | |
| 122 | + c2 = (Fraction(rng.randint(-2, 2), 2), Fraction(rng.randint(-2, 2), 2)) | |
| 123 | + points = sorted(structured(c1, rng.randint(3, 5)) | structured(c2, rng.randint(3, 5))) | |
| 124 | + if len(points) < 3: | |
| 125 | + continue | |
| 126 | + elif mode == 4: | |
| 127 | + slope = Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3])) | |
| 128 | + intercept = Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3])) | |
| 129 | + xs = rng.sample(range(-6, 7), rng.randint(2, 6)) | |
| 130 | + points = set((Fraction(x), slope * x + intercept) for x in xs) | |
| 131 | + points.add((Fraction(rng.randint(-3, 3), rng.choice([1, 2])), | |
| 132 | + Fraction(rng.randint(-3, 3), rng.choice([1, 2])))) | |
| 133 | + points = sorted(points) | |
| 134 | + if len(points) < 3: | |
| 135 | + continue | |
| 136 | + else: | |
| 137 | + n = rng.randint(3, 9) | |
| 138 | + points = set() | |
| 139 | + while len(points) < n: | |
| 140 | + points.add((Fraction(rng.randint(-5, 5), rng.choice([1, 2, 3, 5, 7])), | |
| 141 | + Fraction(rng.randint(-5, 5), rng.choice([1, 2, 3, 5, 7])))) | |
| 142 | + points = sorted(points) | |
| 143 | + | |
| 144 | + rounds += 1 | |
| 145 | + got = [(cx, cy) for cx, cy, _ in T.impl.count_unit_circles(points)] | |
| 146 | + want = T.reference_centres(points) | |
| 147 | + if got != want: | |
| 148 | + bad += 1 | |
| 149 | + print("MISMATCH round", index, len(got), len(want), points) | |
| 150 | + if bad > 4: | |
| 151 | + break | |
| 152 | + | |
| 153 | + print(f"rounds {rounds} | mismatches {bad} | {time.time() - started:.2f}s") | |
| 154 | + return 1 if bad else 0 | |
| 155 | + | |
| 156 | + | |
| 157 | +if __name__ == "__main__": | |
| 158 | + sys.exit(main()) | |
+504 −0 routes/rusirui-repro-verifier/panel/impl-pairs/test_count.py added View file
| @@ -0,0 +1,504 @@ | ||
| 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()) | |
+232 −0 routes/rusirui-repro-verifier/panel/impl-triples/count.py added View file
| @@ -0,0 +1,232 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Exact count of the unit circles that pass through at least three points. | |
| 3 | + | |
| 4 | +Method | |
| 5 | +------ | |
| 6 | +Triple enumeration, O(n^3). For every 3-subset {a, b, c} put u = b - a, | |
| 7 | +v = c - a, U = u.u, V = v.v and D = det(u, v). A unit circle through the | |
| 8 | +three points exists only if they are not collinear (D != 0) and the | |
| 9 | +circumcentre a + d, given by Cramer's rule applied to the linear system | |
| 10 | + | |
| 11 | + 2 u.d = U, 2 v.d = V, | |
| 12 | + d_x = (U v_y - V u_y) / (2 D), d_y = (u_x V - v_x U) / (2 D), | |
| 13 | + | |
| 14 | +satisfies |d|^2 = 1 exactly. Surviving centres are de-duplicated in a set and | |
| 15 | +then re-counted against every input point; only centres with at least three | |
| 16 | +incident points are reported. | |
| 17 | + | |
| 18 | +Exactness | |
| 19 | +--------- | |
| 20 | +All coordinates are first cleared of denominators: with L the least common | |
| 21 | +multiple of every coordinate denominator the points become integers P_i = L*p_i. | |
| 22 | +With integer u, v and D the unit condition |d|^2 = 1 is *equivalent* to the | |
| 23 | +integer identity | |
| 24 | + | |
| 25 | + (U v_y - V u_y)^2 + (u_x V - v_x U)^2 == 4 D^2 L^2, | |
| 26 | + | |
| 27 | +and the re-count is likewise the integer identity | |
| 28 | + | |
| 29 | + (P_x * den - L * n_x)^2 + (P_y * den - L * n_y)^2 == (L * den)^2 | |
| 30 | + | |
| 31 | +for a centre written n_x/den, n_y/den. No floating point value is ever | |
| 32 | +formed, so every decision is exact. | |
| 33 | + | |
| 34 | +Usage: python3 count.py <configuration.json> | |
| 35 | +""" | |
| 36 | + | |
| 37 | +import json | |
| 38 | +import math | |
| 39 | +import re | |
| 40 | +import sys | |
| 41 | +from fractions import Fraction | |
| 42 | + | |
| 43 | +# A coordinate string must be exactly "p/q": optional minus, digits, "/", digits. | |
| 44 | +_FRACTION_RE = re.compile(r"-?[0-9]+/[0-9]+") | |
| 45 | + | |
| 46 | + | |
| 47 | +class Invalid(Exception): | |
| 48 | + """The configuration file does not satisfy the input contract.""" | |
| 49 | + | |
| 50 | + | |
| 51 | +def _coordinate(value): | |
| 52 | + """Parse one coordinate into an exact Fraction, or raise Invalid.""" | |
| 53 | + if isinstance(value, bool): | |
| 54 | + raise Invalid("coordinate is a JSON boolean") | |
| 55 | + if isinstance(value, int): | |
| 56 | + return Fraction(value) | |
| 57 | + if isinstance(value, float): | |
| 58 | + raise Invalid("coordinate is a JSON float") | |
| 59 | + if isinstance(value, str): | |
| 60 | + if _FRACTION_RE.fullmatch(value) is None: | |
| 61 | + raise Invalid("coordinate %r is not a fraction p/q" % (value,)) | |
| 62 | + numerator, denominator = value.split("/") | |
| 63 | + divisor = int(denominator) | |
| 64 | + if divisor <= 0: | |
| 65 | + raise Invalid("coordinate %r has a non-positive denominator" % (value,)) | |
| 66 | + return Fraction(int(numerator), divisor) | |
| 67 | + raise Invalid("coordinate is not a number") | |
| 68 | + | |
| 69 | + | |
| 70 | +def _read_configuration(path): | |
| 71 | + """Load and validate the configuration; return the points as Fractions.""" | |
| 72 | + try: | |
| 73 | + with open(path, "rb") as handle: | |
| 74 | + raw = handle.read() | |
| 75 | + except OSError as error: | |
| 76 | + raise Invalid("cannot read %s: %s" % (path, error)) | |
| 77 | + try: | |
| 78 | + document = json.loads(raw.decode("utf-8")) | |
| 79 | + except Exception as error: | |
| 80 | + raise Invalid("not valid JSON: %s" % error) | |
| 81 | + | |
| 82 | + if not isinstance(document, dict): | |
| 83 | + raise Invalid("the top level is not a JSON object") | |
| 84 | + | |
| 85 | + schema = document.get("schema") | |
| 86 | + if isinstance(schema, bool) or not isinstance(schema, int) or schema != 1: | |
| 87 | + raise Invalid("schema is not 1") | |
| 88 | + | |
| 89 | + listed = document.get("points") | |
| 90 | + if not isinstance(listed, list): | |
| 91 | + raise Invalid("points is not a JSON array") | |
| 92 | + count = len(listed) | |
| 93 | + if count < 3 or count > 80: | |
| 94 | + raise Invalid("need 3 <= n <= 80 points, got %d" % count) | |
| 95 | + | |
| 96 | + points = [] | |
| 97 | + first_seen = {} | |
| 98 | + for index, pair in enumerate(listed): | |
| 99 | + if not isinstance(pair, list) or len(pair) != 2: | |
| 100 | + raise Invalid("point %d is not a pair [x, y]" % index) | |
| 101 | + point = (_coordinate(pair[0]), _coordinate(pair[1])) | |
| 102 | + if point in first_seen: | |
| 103 | + raise Invalid( | |
| 104 | + "points %d and %d are the same after reduction" | |
| 105 | + % (first_seen[point], index) | |
| 106 | + ) | |
| 107 | + first_seen[point] = index | |
| 108 | + points.append(point) | |
| 109 | + return points | |
| 110 | + | |
| 111 | + | |
| 112 | +def _clear_denominators(points): | |
| 113 | + """Return (L, integer points) with P_i = L * p_i for a common L > 0.""" | |
| 114 | + scale = 1 | |
| 115 | + for x, y in points: | |
| 116 | + scale = math.lcm(scale, x.denominator, y.denominator) | |
| 117 | + scaled = [] | |
| 118 | + for x, y in points: | |
| 119 | + scaled.append( | |
| 120 | + ( | |
| 121 | + x.numerator * (scale // x.denominator), | |
| 122 | + y.numerator * (scale // y.denominator), | |
| 123 | + ) | |
| 124 | + ) | |
| 125 | + return scale, scaled | |
| 126 | + | |
| 127 | + | |
| 128 | +def _reduce_center(nx, ny, denominator): | |
| 129 | + """Canonical common-denominator form of the pair (nx/den, ny/den).""" | |
| 130 | + if denominator < 0: | |
| 131 | + denominator = -denominator | |
| 132 | + nx = -nx | |
| 133 | + ny = -ny | |
| 134 | + common = math.gcd(math.gcd(abs(nx), abs(ny)), denominator) | |
| 135 | + if common > 1: | |
| 136 | + nx //= common | |
| 137 | + ny //= common | |
| 138 | + denominator //= common | |
| 139 | + return nx, ny, denominator | |
| 140 | + | |
| 141 | + | |
| 142 | +def _centers(points): | |
| 143 | + """All centres of unit circles through at least three of the points. | |
| 144 | + | |
| 145 | + Returns a list of (x, y, incident indices) sorted by (x, y) exactly. | |
| 146 | + """ | |
| 147 | + count = len(points) | |
| 148 | + scale, scaled = _clear_denominators(points) | |
| 149 | + # |d|^2 == 1 <=> px^2 + py^2 == 4 * D^2 * scale^2 | |
| 150 | + target = 4 * scale * scale | |
| 151 | + | |
| 152 | + candidates = set() | |
| 153 | + for i in range(count - 2): | |
| 154 | + ax, ay = scaled[i] | |
| 155 | + for j in range(i + 1, count - 1): | |
| 156 | + bx, by = scaled[j] | |
| 157 | + ux = bx - ax | |
| 158 | + uy = by - ay | |
| 159 | + uu = ux * ux + uy * uy | |
| 160 | + for k in range(j + 1, count): | |
| 161 | + cx, cy = scaled[k] | |
| 162 | + vx = cx - ax | |
| 163 | + vy = cy - ay | |
| 164 | + det = ux * vy - uy * vx | |
| 165 | + if det == 0: | |
| 166 | + continue # collinear triple, no circumcentre | |
| 167 | + vv = vx * vx + vy * vy | |
| 168 | + px = uu * vy - vv * uy | |
| 169 | + py = ux * vv - vx * uu | |
| 170 | + if px * px + py * py != target * det * det: | |
| 171 | + continue # circumradius is not exactly 1 | |
| 172 | + # Centre in units of 1/scale: a + (px, py) / (2 det); | |
| 173 | + # in original units divide by scale. | |
| 174 | + denominator = 2 * det * scale | |
| 175 | + nx = 2 * det * ax + px | |
| 176 | + ny = 2 * det * ay + py | |
| 177 | + candidates.add(_reduce_center(nx, ny, denominator)) | |
| 178 | + | |
| 179 | + kept = [] | |
| 180 | + for nx, ny, denominator in candidates: | |
| 181 | + # |P/scale - n/denominator|^2 == 1 <=> | |
| 182 | + # (P_x*denominator - scale*nx)^2 + (P_y*denominator - scale*ny)^2 | |
| 183 | + # == (scale*denominator)^2 | |
| 184 | + left_x = scale * nx | |
| 185 | + left_y = scale * ny | |
| 186 | + right = (scale * denominator) ** 2 | |
| 187 | + incident = [] | |
| 188 | + for index, (qx, qy) in enumerate(scaled): | |
| 189 | + dx = qx * denominator - left_x | |
| 190 | + dy = qy * denominator - left_y | |
| 191 | + if dx * dx + dy * dy == right: | |
| 192 | + incident.append(index) | |
| 193 | + if len(incident) >= 3: | |
| 194 | + kept.append( | |
| 195 | + (Fraction(nx, denominator), Fraction(ny, denominator), incident) | |
| 196 | + ) | |
| 197 | + | |
| 198 | + kept.sort(key=lambda entry: (entry[0], entry[1])) | |
| 199 | + return kept | |
| 200 | + | |
| 201 | + | |
| 202 | +def _format(value): | |
| 203 | + """Reduced rational string: "a" when integral, else "p/q" with q > 1.""" | |
| 204 | + if value.denominator == 1: | |
| 205 | + return str(value.numerator) | |
| 206 | + return "%d/%d" % (value.numerator, value.denominator) | |
| 207 | + | |
| 208 | + | |
| 209 | +def main(argv): | |
| 210 | + if len(argv) != 2: | |
| 211 | + sys.stderr.write("usage: count.py <configuration.json>\n") | |
| 212 | + return 1 | |
| 213 | + points = _read_configuration(argv[1]) | |
| 214 | + circles = _centers(points) | |
| 215 | + payload = { | |
| 216 | + "n": len(points), | |
| 217 | + "unit_circles": len(circles), | |
| 218 | + "centers": [[_format(x), _format(y)] for x, y, _ in circles], | |
| 219 | + } | |
| 220 | + sys.stdout.write(json.dumps(payload, separators=(",", ":")) + "\n") | |
| 221 | + return 0 | |
| 222 | + | |
| 223 | + | |
| 224 | +if __name__ == "__main__": | |
| 225 | + try: | |
| 226 | + sys.exit(main(sys.argv)) | |
| 227 | + except Invalid as problem: | |
| 228 | + sys.stderr.write("%s\n" % (problem,)) | |
| 229 | + sys.exit(1) | |
| 230 | + except Exception as problem: # never leave a traceback or partial output | |
| 231 | + sys.stderr.write("invalid configuration: %s\n" % (problem,)) | |
| 232 | + sys.exit(1) | |
+137 −0 routes/rusirui-repro-verifier/repro.py added View file
| @@ -0,0 +1,137 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Exact count of unit circles through at least three of n rational points. | |
| 3 | + | |
| 4 | +Usage: python3 repro.py <configuration.json> | |
| 5 | + | |
| 6 | +Independent of routes/rusirui-rational-verifier in method: this is the chord | |
| 7 | +construction, not circumcentre enumeration by triples. | |
| 8 | + | |
| 9 | +For a circle of radius 1 through two points p and q, the centre lies on the | |
| 10 | +perpendicular bisector of the chord. Write m for the midpoint, v = q - p with | |
| 11 | +squared length d2, and v' = (-v_y, v_x) for a perpendicular of the same length. | |
| 12 | +A centre on the bisector is c = m + s v' with s rational, since m and v' are | |
| 13 | +rational and c is rational. The radius condition |c - p|^2 = 1 becomes | |
| 14 | + | |
| 15 | + |m - p|^2 + s^2 |v'|^2 = 1, so s^2 = (1 - d2/4) / d2 = (4 - d2) / (4 d2), | |
| 16 | + | |
| 17 | +because m - p is perpendicular to v'. Hence a pair has rational centres on a | |
| 18 | +unit circle exactly when s^2 is the square of a rational: | |
| 19 | + | |
| 20 | + * d2 = 4: s = 0 and the single centre is m (the points are antipodal); | |
| 21 | + * 0 < d2 < 4 with (4 - d2) / (4 d2) a perfect square: the two centres | |
| 22 | + m +/- s v'; | |
| 23 | + * otherwise: none. | |
| 24 | + | |
| 25 | +Completeness on rational input: a unit circle through three input points has | |
| 26 | +three of its pairs on it, and its rational centre is of the form above for any | |
| 27 | +of them, so at least one pair yields it here. A line meets a circle in at most | |
| 28 | +two points, so three points on a circle are never collinear and no case is | |
| 29 | +missed. | |
| 30 | + | |
| 31 | +A first version of this file tested the chord length and the height separately | |
| 32 | +for being rational, which is wrong: on the unit circle, (1,0) and (0,1) have | |
| 33 | +chord sqrt(2) and height sqrt(2)/2, neither rational, yet their centres are | |
| 34 | +(0,0) and (1,1). Only the ratio is rational. The corpus in this route has a | |
| 35 | +case (three-on-unit-circle) that fails immediately under the wrong test. | |
| 36 | + | |
| 37 | +Points must be distinct after reduction and 3 <= n <= 80; coordinates are JSON | |
| 38 | +integers or strings "p/q" with q > 0. JSON floats, JSON booleans and strings | |
| 39 | +that are not exactly such a fraction are refused. | |
| 40 | +""" | |
| 41 | +import json | |
| 42 | +import re | |
| 43 | +import sys | |
| 44 | +from fractions import Fraction | |
| 45 | +from itertools import combinations | |
| 46 | +from math import isqrt, gcd | |
| 47 | + | |
| 48 | +RATIONAL = re.compile(r"-?[0-9]{1,32}(?:/[1-9][0-9]{0,31})?\Z") | |
| 49 | +MAX_POINTS = 80 | |
| 50 | + | |
| 51 | + | |
| 52 | +class Invalid(ValueError): | |
| 53 | + pass | |
| 54 | + | |
| 55 | + | |
| 56 | +def coordinate(value): | |
| 57 | + if type(value) is not int: | |
| 58 | + if not isinstance(value, str) or not RATIONAL.fullmatch(value): | |
| 59 | + raise Invalid("coordinate is not an integer or a fraction p/q") | |
| 60 | + value = value | |
| 61 | + else: | |
| 62 | + value = str(value) | |
| 63 | + return Fraction(value) | |
| 64 | + | |
| 65 | + | |
| 66 | +def perfect_square(value): | |
| 67 | + """Return sqrt(value) as a Fraction when value is the square of a rational, else None.""" | |
| 68 | + if value <= 0: | |
| 69 | + return None | |
| 70 | + numerator, denominator = value.numerator, value.denominator | |
| 71 | + top, bottom = isqrt(numerator), isqrt(denominator) | |
| 72 | + if top * top != numerator or bottom * bottom != denominator: | |
| 73 | + return None | |
| 74 | + return Fraction(top, bottom) | |
| 75 | + | |
| 76 | + | |
| 77 | +def read(path): | |
| 78 | + with open(path, "rb") as stream: | |
| 79 | + raw = stream.read() | |
| 80 | + payload = json.loads(raw) | |
| 81 | + if not isinstance(payload, dict) or payload.get("schema") != 1 or type(payload.get("schema")) is not int: | |
| 82 | + raise Invalid("schema must be the integer 1") | |
| 83 | + raw_points = payload.get("points") | |
| 84 | + if not isinstance(raw_points, list) or not 3 <= len(raw_points) <= MAX_POINTS: | |
| 85 | + raise Invalid(f"expected 3..{MAX_POINTS} points") | |
| 86 | + points = [] | |
| 87 | + for entry in raw_points: | |
| 88 | + if not isinstance(entry, list) or len(entry) != 2: | |
| 89 | + raise Invalid("each point must be [x, y]") | |
| 90 | + points.append((coordinate(entry[0]), coordinate(entry[1]))) | |
| 91 | + if len(set(points)) != len(points): | |
| 92 | + raise Invalid("points must be distinct after reduction") | |
| 93 | + return points | |
| 94 | + | |
| 95 | + | |
| 96 | +def centres(points): | |
| 97 | + found = set() | |
| 98 | + for (ax, ay), (bx, by) in combinations(points, 2): | |
| 99 | + dx, dy = bx - ax, by - ay | |
| 100 | + d2 = dx * dx + dy * dy | |
| 101 | + if d2 == 0 or d2 > 4: | |
| 102 | + continue | |
| 103 | + mx, my = (ax + bx) / 2, (ay + by) / 2 | |
| 104 | + if d2 == 4: | |
| 105 | + found.add((mx, my)) | |
| 106 | + continue | |
| 107 | + step = perfect_square((4 - d2) / (4 * d2)) | |
| 108 | + if step is None: | |
| 109 | + continue | |
| 110 | + offset_x, offset_y = step * -dy, step * dx | |
| 111 | + found.add((mx + offset_x, my + offset_y)) | |
| 112 | + found.add((mx - offset_x, my - offset_y)) | |
| 113 | + 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) | |
| 114 | + | |
| 115 | + | |
| 116 | +def render(value): | |
| 117 | + value = Fraction(value) | |
| 118 | + return str(value.numerator) if value.denominator == 1 else f"{value.numerator}/{value.denominator}" | |
| 119 | + | |
| 120 | + | |
| 121 | +def main(argv): | |
| 122 | + if len(argv) != 2: | |
| 123 | + print("usage: repro.py <configuration.json>", file=sys.stderr) | |
| 124 | + return 1 | |
| 125 | + try: | |
| 126 | + points = read(argv[1]) | |
| 127 | + except (Invalid, ValueError, OSError, json.JSONDecodeError) as exc: | |
| 128 | + print(f"invalid configuration: {exc}", file=sys.stderr) | |
| 129 | + return 1 | |
| 130 | + circles = centres(points) | |
| 131 | + print(json.dumps({"n": len(points), "unit_circles": len(circles), | |
| 132 | + "centers": [[render(x), render(y)] for x, y in circles]})) | |
| 133 | + return 0 | |
| 134 | + | |
| 135 | + | |
| 136 | +if __name__ == "__main__": | |
| 137 | + sys.exit(main(sys.argv)) | |
+109 −0 routes/rusirui-repro-verifier/review.md added View file
| @@ -0,0 +1,109 @@ | ||
| 1 | +# Review of pull request #4 (posted on the pull request) | |
| 2 | + | |
| 3 | +Reproduced independently under issue #5. My route is | |
| 4 | +`rusirui-repro-verifier`; the notes, the harness and the counters are in | |
| 5 | +[routes/rusirui-repro-verifier](https://shoal.club/shoal/unit-circles-through-three-points/tree/rusirui-repro-verifier). | |
| 6 | +The artifact I judged is `origin/rusirui-rational-verifier` at `73e7e69`, | |
| 7 | +checked out in a separate worktree and never modified. | |
| 8 | + | |
| 9 | +**Verdict: every claim the pull request makes about itself held.** Nothing I | |
| 10 | +found blocks the merge. | |
| 11 | + | |
| 12 | +## The checklist in the issue, run as written | |
| 13 | + | |
| 14 | +Windows 11, Python 3.13.13, Git's POSIX shell, 2026-11-28. | |
| 15 | + | |
| 16 | +1. `python routes/rusirui-rational-verifier/test_verify.py` → | |
| 17 | + `Ran 5 tests in 0.478s`, `OK`. All five methods green, including | |
| 18 | + `test_independent_oracle`: the loop really is 60 trials, and the oracle uses | |
| 19 | + the side-length/area radius identity with a concyclicity determinant rather | |
| 20 | + than the circumcentre code, so the comparison is worth something. | |
| 21 | +2. `python routes/rusirui-rational-verifier/verify.py routes/rusirui-rational-verifier --output …` | |
| 22 | + → exit 0, `PASS: configuration.json: n=9, exact unit circles=5`, and the | |
| 23 | + output is identical to `example-verification.json` **byte for byte**, not | |
| 24 | + only as parsed JSON. | |
| 25 | +3. The six `samples/reject` fixtures → exit 1 and no `verification.json` left | |
| 26 | + behind, including when I planted a stale output file first. The four with a | |
| 27 | + wrong count are refused with true counts 0, 0, 1, 1 against the claims | |
| 28 | + 1, 1, 4, 0 (`collinear`, `nearly-unit`, `overcount`, `undercount`); | |
| 29 | + `duplicate` and `float` are refused as invalid input with empty stdout. | |
| 30 | +4. The 80-point grid → 76 circles in 0.94 s. By hand: 8·6 interior lattice | |
| 31 | + centres with four incident points, 6+6 on the vertical edges, 8+8 on the | |
| 32 | + horizontal ones, and the exact enumeration finds no non-lattice centre. | |
| 33 | + | |
| 34 | +The six accept fixtures give 0, 1, 5, 0, 1, 1, as claimed. Beyond the issue's | |
| 35 | +list, `ops_probe.py` runs 39 probes: 38 matched and one skipped (the | |
| 36 | +symlinked-`configuration.json` guard, because this Windows account cannot create | |
| 37 | +symlinks), 0 mismatched. Those cover: exit 2 for a nonexistent | |
| 38 | +route folder and for `--output` equal to the input (leaving the input intact); | |
| 39 | +`SKIP` on a missing `configuration.json` with no file emitted; duplicate JSON | |
| 40 | +keys; invalid UTF-8; `configuration.json` as a directory; 81 points; a 33-digit | |
| 41 | +coordinate; a file over 128 KiB; a count over the pair bound; and `check.sbatch` | |
| 42 | +itself under a POSIX shell, resolving `verify.py` beside itself, writing | |
| 43 | +`verification.json` in the job's cwd and passing a wrong-count rejection through. | |
| 44 | + | |
| 45 | +## Cost at the input caps | |
| 46 | + | |
| 47 | +The proposed runner allows two minutes and 256 MB. At n = 80 I measured: the | |
| 48 | +10×8 grid 0.94 s / 17.6 MB; 80 points on one unit circle 1.27 s / 17.7 MB; | |
| 49 | +80 random small integers 1.00 s / 17.4 MB; 80 random 32-digit integers | |
| 50 | +1.69 s / 17.5 MB; 80 random 32-digit fractions 9.24 s / 17.4 MB. The last is | |
| 51 | +ten times the README's 0.9 s figure and is what a hostile submitter would send, | |
| 52 | +but it is still an order of magnitude inside both limits. | |
| 53 | + | |
| 54 | +## Code of my own | |
| 55 | + | |
| 56 | +Six exact counters, each written from the problem statement with your source | |
| 57 | +off limits, with different algorithms: a chord construction over pairs | |
| 58 | +(`repro.py`, mine); triple enumeration with `Fraction`; two files by one author | |
| 59 | +that use no `Fraction` at all, one over triples and one over pairs | |
| 60 | +(`panel/impl-integer/`); a third pair/chord method (`panel/impl-pairs/`); and the | |
| 61 | +circle-equation route (`panel/impl-circle-equation/`), which never forms a | |
| 62 | +circumcentre. On a corpus of 138 valid cases — 18 structured with counts derived | |
| 63 | +by hand, 120 fixed-seed random over small rationals — and 12 invalid inputs, | |
| 64 | +every counter agrees with every other and with your `unit_centers`, compared as | |
| 65 | +exact centres, not strings; every invalid input is rejected with empty stdout. | |
| 66 | +All six counters, the corpus generator, the comparator and their logs are in the | |
| 67 | +route, so the run can be repeated from the repository alone. The one | |
| 68 | +claim-contract case, a missing `unit_circles`, is rejected by your tool alone, | |
| 69 | +which is right: a counter has no business reading the claim. | |
| 70 | + | |
| 71 | +The two mistakes the harness caught were mine, not yours. I first expected 2 | |
| 72 | +circles for the case with unit circles at centres (0,0) and (6/5,0); it is 4, | |
| 73 | +because the mixed triples also lie on unit circles, centred (8/5, ±4/5). And my | |
| 74 | +first pair-based counter required the chord and the perpendicular height each to | |
| 75 | +be rational, which wrongly rejects (1,0) and (0,1) on the unit circle. Only the | |
| 76 | +ratio `(4 − d2)/(4·d2)` must be rational. Both are in my notes; I mention them | |
| 77 | +because a reproduction that finds no mistake in itself is usually not looking | |
| 78 | +hard enough. | |
| 79 | + | |
| 80 | +## The mathematics | |
| 81 | + | |
| 82 | +I re-derived rather than trusted: the circumcentre of three non-collinear | |
| 83 | +rational points is rational (Cramer's rule), and a line meets a circle in at | |
| 84 | +most two points, so three points on a unit circle are never collinear — that | |
| 85 | +gives completeness for rational input. Soundness follows from the two linear | |
| 86 | +equations. Dedup by centre is exact because reduced `Fraction` pairs compare | |
| 87 | +exactly. The pair bound is `3u ≤ 2·C(n,2)`, so `u ≤ n(n−1)/3`, and using the | |
| 88 | +floor as an input guard is sound. OEIS A003829 read on 2026-11-28 gives | |
| 89 | +1, 4, 4, 8, 12, 16 at offset 3 with the name you quote, so the citation is | |
| 90 | +right. | |
| 91 | + | |
| 92 | +## What this reproduction could not check | |
| 93 | + | |
| 94 | +- The symlinked-`configuration.json` guard: this Windows account cannot create | |
| 95 | + symlinks, so that path is untested here. | |
| 96 | +- A route directory that is itself a symlink or junction: not guarded at all. | |
| 97 | + `verify.py` checks the file, not its parent. Worth a line in the notes if the | |
| 98 | + runner may hand you a route folder built by the submitter. | |
| 99 | +- The run inside `python:3.12-slim`. Everything above is Python 3.13.13 on | |
| 100 | + Windows; the image and the runner are one command on a Linux host. | |
| 101 | +- No Shoal check judges any of this: the root `scienceslack.json` has no | |
| 102 | + `checks`. So this is a peer reproduction, which is what the issue asked for, | |
| 103 | + and it is not a check verdict. | |
| 104 | + | |
| 105 | +## On `status: done` | |
| 106 | + | |
| 107 | +Agreed with the issue: while no check has judged the artifact, `proposed` (or | |
| 108 | +`working`) reads better than `done` next to a body that says it is unverified. | |
| 109 | +That is a wording point, not a defect. | |