Heilbronn's triangle problem: record configurations
Place n points in a square or triangle so the smallest triangle they form is as large as possible; beat a record or prove one optimal.
| 1 | #!/usr/bin/env python3 |
| 2 | """Exact check of Heilbronn configurations, scored as Tej Stead's record tables (math.tejstead.com/heilbronn) score |
| 3 | them, for n = 20..36 points in two containers: the unit square 0 <= x, y <= 1, and the right triangle x, y >= 0, |
| 4 | x + y <= 1. |
| 5 | |
| 6 | A candidate is a JSON object {"container": "square" or "triangle", "n": n, "points": [[x, y], ...]} with n points; |
| 7 | every coordinate is a string holding a plain decimal ("0", "0.125", at most 6 digits before the point and 200 after), |
| 8 | as the tables accept them, read as an exact rational. Its value is the smallest area of a triangle formed by three of |
| 9 | its points (0 if three are collinear), normalized to a container of area 1 as the tables do: the square's value is that |
| 10 | area, the triangle's is twice it. Integer arithmetic over the coordinates' common denominator; no floating-point number |
| 11 | enters. Python >= 3.9, standard library only. |
| 12 | """ |
| 13 | import json |
| 14 | import re |
| 15 | from fractions import Fraction |
| 16 | from itertools import combinations |
| 17 | from math import lcm |
| 18 | from pathlib import Path |
| 19 | |
| 20 | CONTAINERS = ("square", "triangle") |
| 21 | SIZES = tuple(range(20, 37)) |
| 22 | INSTANCES = tuple(f"{c}-n{n}" for c in CONTAINERS for n in SIZES) |
| 23 | DECIMAL = re.compile(r"-?\d{1,6}(\.\d{1,200})?") |
| 24 | # A value is a new record when it exceeds the record by more than this fraction of it: the tables' own tie window, so |
| 25 | # that re-rounding a record's coordinates does not count. (The tables take any strictly larger exact value.) |
| 26 | MIN_GAIN = Fraction(1, 10 ** 9) |
| 27 | # instance -> the public record: its exact value ("p/q"), who found it, when the tables took it, and where it is listed |
| 28 | RECORDS = json.loads(Path(__file__).with_name("records.json").read_text()) |
| 29 | RECORD = {k: Fraction(v["value"]) for k, v in RECORDS.items()} |
| 30 | |
| 31 | |
| 32 | class CandidateError(ValueError): |
| 33 | pass |
| 34 | |
| 35 | |
| 36 | def coordinate(value) -> Fraction: |
| 37 | if not isinstance(value, str): |
| 38 | raise CandidateError(f'a coordinate must be a string such as "0.125", not {type(value).__name__}') |
| 39 | if not DECIMAL.fullmatch(value): |
| 40 | raise CandidateError(f"{value[:40]!r} is not a plain decimal (at most 6 digits before the point, 200 after, no exponent)") |
| 41 | return Fraction(value) |
| 42 | |
| 43 | |
| 44 | def points(candidate: dict) -> tuple[str, list[tuple[Fraction, Fraction]]]: |
| 45 | """The candidate's instance ("square-n27") and its points; raises CandidateError when it is malformed.""" |
| 46 | container, n = candidate.get("container"), candidate.get("n") |
| 47 | if container not in CONTAINERS: |
| 48 | raise CandidateError('"container" must be "square" or "triangle"') |
| 49 | if type(n) is not int or n not in SIZES: |
| 50 | raise CandidateError(f'"n" must be one of the integers {SIZES[0]} to {SIZES[-1]}') |
| 51 | pts = candidate.get("points") |
| 52 | if not isinstance(pts, list) or len(pts) != n: |
| 53 | raise CandidateError(f'"points" must be a list of {n} points') |
| 54 | if not all(isinstance(p, list) and len(p) == 2 for p in pts): |
| 55 | raise CandidateError("each point must be a list [x, y]") |
| 56 | out = [(coordinate(x), coordinate(y)) for x, y in pts] |
| 57 | for i, (x, y) in enumerate(out): |
| 58 | inside = 0 <= x <= 1 and 0 <= y <= 1 if container == "square" else x >= 0 and y >= 0 and x + y <= 1 |
| 59 | if not inside: |
| 60 | raise CandidateError(f"point {i} ({pts[i][0]}, {pts[i][1]}) is outside the {container}") |
| 61 | return f"{container}-n{n}", out |
| 62 | |
| 63 | |
| 64 | def value(instance: str, pts: list[tuple[Fraction, Fraction]]) -> Fraction: |
| 65 | q = lcm(*(c.denominator for p in pts for c in p)) |
| 66 | P = [(int(x * q), int(y * q)) for x, y in pts] |
| 67 | twice = min(abs((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)) for (ax, ay), (bx, by), (cx, cy) in combinations(P, 3)) |
| 68 | # the smallest area is twice / (2 q^2); the triangle (area 1/2) reports it doubled |
| 69 | return Fraction(twice, 2 * q * q) if instance.startswith("square") else Fraction(twice, q * q) |
| 70 | |
| 71 | |
| 72 | def is_record(instance: str, v: Fraction) -> bool: |
| 73 | return v > RECORD[instance] * (1 + MIN_GAIN) |
| 74 | |
| 75 | |
| 76 | def score(best: dict[str, Fraction]) -> Fraction: |
| 77 | """The mean over all instances of best / record, where an instance counts as its record when the route has nothing |
| 78 | better (main starts from the records, so it scores exactly 1, and any value above a record raises the score).""" |
| 79 | return Fraction(sum(max(best.get(k, 0) / RECORD[k], 1) for k in INSTANCES), len(INSTANCES)) |
| 80 | |
| 81 | |
| 82 | def scan(roots): |
| 83 | """(file, instance, value) for each candidate (*.json with "points") under these folders, in order. For a file that |
| 84 | is unreadable or malformed, instance is None and value says why; other JSON files are not candidates.""" |
| 85 | for root in roots: |
| 86 | for path in sorted(root.rglob("*.json")) if root.exists() else []: |
| 87 | name = str(path.relative_to(root.parent)) |
| 88 | try: |
| 89 | candidate = json.loads(path.read_text()) |
| 90 | except Exception as exc: |
| 91 | yield name, None, f"unreadable ({exc})" |
| 92 | continue |
| 93 | if not isinstance(candidate, dict) or "points" not in candidate: |
| 94 | continue |
| 95 | try: |
| 96 | instance, pts = points(candidate) |
| 97 | except CandidateError as exc: |
| 98 | yield name, None, f"malformed: {exc}" |
| 99 | continue |
| 100 | yield name, instance, value(instance, pts) |
| 101 | |
| 102 | |
| 103 | def best_of(found) -> dict[str, tuple[Fraction, str]]: |
| 104 | """Each instance's best value among scanned candidates, with the file that holds it.""" |
| 105 | best = {} |
| 106 | for name, instance, v in found: |
| 107 | if instance and (instance not in best or v > best[instance][0]): |
| 108 | best[instance] = (v, name) |
| 109 | return best |
| 110 | |
| 111 | |
| 112 | def decimal(v: Fraction, digits: int = 16) -> str: |
| 113 | """v >= 0 in decimal, rounded down.""" |
| 114 | text = str(v.numerator * 10 ** digits // v.denominator).rjust(digits + 1, "0") |
| 115 | return f"{text[:-digits]}.{text[-digits:]}" |
| 116 | |
| 117 | |
| 118 | def gain(v: Fraction, over: Fraction) -> str: |
| 119 | """v's relative gain over another value.""" |
| 120 | return f"{float(v / over - 1):+.3e}" if over else "+inf" |
| 121 | |
| 122 | |
| 123 | def card(instance: str) -> str: |
| 124 | r = RECORDS[instance] |
| 125 | return f"{decimal(RECORD[instance])} ({r['by']}, {r['date']})" |
