"""Exact finite counts for rational coordinates; Python 3.12+, no dependencies.""" import argparse from fractions import Fraction from itertools import combinations import json from pathlib import Path import re import sys MAX_BYTES = 131072 MAX_POINTS = 80 RATIONAL = re.compile(r"-?[0-9]{1,32}(?:/[1-9][0-9]{0,31})?\Z") class Invalid(ValueError): pass def rational(value): if type(value) is int: value = str(value) if not isinstance(value, str) or not RATIONAL.fullmatch(value): raise Invalid('coordinates must be integers or rational strings with <=32 digits per part') return Fraction(value) def unique_keys(pairs): result = {} for key, value in pairs: if key in result: raise Invalid('duplicate JSON key: ' + key) result[key] = value return result def parse(data): if not isinstance(data, dict) or set(data) != {'schema', 'points', 'unit_circles'}: raise Invalid('expected exactly schema, points, unit_circles') if type(data['schema']) is not int or data['schema'] != 1: raise Invalid('schema must be integer 1') raw = data['points'] if not isinstance(raw, list) or not 3 <= len(raw) <= MAX_POINTS: raise Invalid(f'expected 3..{MAX_POINTS} points') points = [] for point in raw: if not isinstance(point, list) or len(point) != 2: raise Invalid('each point must be [x,y]') points.append(tuple(map(rational, point))) if len(set(points)) != len(points): raise Invalid('points must be distinct after rational reduction') expected = data['unit_circles'] if type(expected) is not int or not 0 <= expected <= len(points)*(len(points)-1)//3: raise Invalid('unit_circles must be a nonnegative integer within the pair bound') return points, expected def unit_centers(points): centers = set() for a, b, c in combinations(points, 3): ux, uy = b[0]-a[0], b[1]-a[1] vx, vy = c[0]-a[0], c[1]-a[1] det = ux*vy-uy*vx if det == 0: continue u2, v2 = ux*ux+uy*uy, vx*vx+vy*vy dx = (u2*vy-v2*uy)/(2*det) dy = (ux*v2-vx*u2)/(2*det) if dx*dx+dy*dy == 1: centers.add((a[0]+dx, a[1]+dy)) return centers def verify(data): points, expected = parse(data) centers = unit_centers(points) if len(centers) != expected: raise Invalid(f'claimed {expected} unit circles; exact count is {len(centers)}') circles = [] for x, y in sorted(centers): incident = [i for i, (px, py) in enumerate(points) if (px-x)**2+(py-y)**2 == 1] circles.append({'center': [str(x), str(y)], 'point_indices': incident}) return {'n': len(points), 'unit_circles': len(centers), 'circles': circles} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('route', type=Path, help='folder containing configuration.json') parser.add_argument('--output', type=Path, default=Path('verification.json')) args = parser.parse_args() path = args.route / 'configuration.json' try: if args.output.resolve() == path.resolve(): print('ERROR: output must differ from input', file=sys.stderr) return 2 # Prevent a prior successful run from masquerading as this run. args.output.unlink(missing_ok=True) if not args.route.is_dir(): print('ERROR: route folder does not exist', file=sys.stderr) return 2 if path.is_symlink(): raise Invalid('configuration.json must not be a symlink') if not path.exists(): print('SKIP: no configuration.json; no mathematical artifact judged') return 0 if not path.is_file(): raise Invalid('configuration.json must be a plain file') with path.open('rb') as stream: raw = stream.read(MAX_BYTES+1) if len(raw) > MAX_BYTES: raise Invalid('configuration.json exceeds 128 KiB') data = json.loads(raw, object_pairs_hook=unique_keys) result = verify(data) args.output.write_text(json.dumps(result, indent=2)+'\n', encoding='utf-8') print(f"PASS: configuration.json: n={result['n']}, exact unit circles={result['unit_circles']}") return 0 except (Invalid, ValueError, UnicodeError, RecursionError) as exc: print('FAIL: '+str(exc), file=sys.stderr) return 1 except OSError as exc: print('ERROR: '+str(exc), file=sys.stderr) return 2 if __name__ == '__main__': sys.exit(main())