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.
Derive and certify the exact area and strict local maximum of the recovered layout
Browse files+199 −0 routes/irisbud-codex/square20-search/certificate.py added View file
| @@ -0,0 +1,199 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Certify the recovered layout's exact area and strict local optimality.""" | |
| 3 | + | |
| 4 | +import argparse | |
| 5 | +from dataclasses import dataclass | |
| 6 | +from fractions import Fraction | |
| 7 | +import json | |
| 8 | +from pathlib import Path | |
| 9 | + | |
| 10 | +import sympy as s | |
| 11 | + | |
| 12 | +from local_optimum import certify_local, require | |
| 13 | +from refine import TRIPLES, axis_points, determinant | |
| 14 | +from run_seeds import write_json | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | +class Interval: | |
| 19 | + lo: Fraction | |
| 20 | + hi: Fraction | |
| 21 | + | |
| 22 | + | |
| 23 | + def point(value): | |
| 24 | + return Interval(Fraction(value), Fraction(value)) | |
| 25 | + | |
| 26 | + def __add__(self, other): | |
| 27 | + if not isinstance(other, Interval): | |
| 28 | + other = Interval.point(other) | |
| 29 | + return Interval(self.lo + other.lo, self.hi + other.hi) | |
| 30 | + | |
| 31 | + __radd__ = __add__ | |
| 32 | + | |
| 33 | + def __neg__(self): | |
| 34 | + return Interval(-self.hi, -self.lo) | |
| 35 | + | |
| 36 | + def __sub__(self, other): | |
| 37 | + return self + (-other) | |
| 38 | + | |
| 39 | + def __rsub__(self, other): | |
| 40 | + return other + (-self) | |
| 41 | + | |
| 42 | + def __mul__(self, other): | |
| 43 | + if not isinstance(other, Interval): | |
| 44 | + other = Interval.point(other) | |
| 45 | + endpoints = [a * b for a in (self.lo, self.hi) for b in (other.lo, other.hi)] | |
| 46 | + return Interval(min(endpoints), max(endpoints)) | |
| 47 | + | |
| 48 | + __rmul__ = __mul__ | |
| 49 | + | |
| 50 | + def __truediv__(self, other): | |
| 51 | + if not isinstance(other, Interval): | |
| 52 | + other = Interval.point(other) | |
| 53 | + if other.lo <= 0 <= other.hi: | |
| 54 | + raise ValueError("an interval denominator may vanish") | |
| 55 | + return self * Interval(1 / other.hi, 1 / other.lo) | |
| 56 | + | |
| 57 | + def __pow__(self, exponent): | |
| 58 | + if exponent < 0: | |
| 59 | + return Interval.point(1) / (self ** (-exponent)) | |
| 60 | + result = Interval.point(1) | |
| 61 | + for _ in range(exponent): | |
| 62 | + result *= self | |
| 63 | + return result | |
| 64 | + | |
| 65 | + | |
| 66 | +def enclose(expression, environment): | |
| 67 | + if expression.is_Rational: | |
| 68 | + return Interval.point(Fraction(int(expression.p), int(expression.q))) | |
| 69 | + if expression.is_Symbol: | |
| 70 | + return environment[expression] | |
| 71 | + if expression.is_Add: | |
| 72 | + return sum(enclose(term, environment) for term in expression.args) | |
| 73 | + if expression.is_Mul: | |
| 74 | + value = Interval.point(1) | |
| 75 | + for factor in expression.args: | |
| 76 | + value *= enclose(factor, environment) | |
| 77 | + return value | |
| 78 | + if expression.is_Pow and expression.exp.is_Integer: | |
| 79 | + return enclose(expression.base, environment) ** int(expression.exp) | |
| 80 | + raise ValueError(f"unsupported expression: {expression}") | |
| 81 | + | |
| 82 | + | |
| 83 | +def certify(approximation, report): | |
| 84 | + a, b, c, d, e, f, g, h, t = s.symbols("a b c d e f g h t") | |
| 85 | + symbolic = axis_points([a, b, c, d, e, f, 1, 0, g, h], s.Integer(1)) | |
| 86 | + observed = [(Fraction(x), Fraction(y)) for x, y in approximation["points"]] | |
| 87 | + active = {tuple(row) for row in report["active_triangles"]} | |
| 88 | + require(len(active) == 42 and active <= set(TRIPLES), "expected 42 distinct active triangles") | |
| 89 | + require(report["fixed_base_coordinates"] == {"6": 1, "7": 0}, "unexpected corner representative") | |
| 90 | + | |
| 91 | + unique = {} | |
| 92 | + signs = {} | |
| 93 | + for triple in sorted(active): | |
| 94 | + orientation = 1 if determinant(observed, triple) > 0 else -1 | |
| 95 | + signs[triple] = orientation | |
| 96 | + equation = s.expand(orientation * determinant(symbolic, triple) - t) | |
| 97 | + unique.setdefault(equation, triple) | |
| 98 | + equations = {triple: equation for equation, triple in unique.items()} | |
| 99 | + require(len(equations) == 9, "the active triples must give nine distinct equations") | |
| 100 | + | |
| 101 | + # Back-substitution reconstructs seven coordinates from t and g. Keep every denominator to check it later. | |
| 102 | + order = [(h, (3, 15, 19)), (b, (0, 3, 8)), (a, (0, 15, 18)), (d, (1, 15, 16)), | |
| 103 | + (f, (2, 15, 17)), (c, (0, 1, 8)), (e, (0, 6, 19))] | |
| 104 | + back_substitutions = [] | |
| 105 | + denominators = [] | |
| 106 | + for variable, triple in order: | |
| 107 | + numerator, denominator = s.fraction(equations.pop(triple)) | |
| 108 | + line = s.Poly(numerator, variable) | |
| 109 | + require(line.degree() == 1, f"the equation is not linear in {variable}") | |
| 110 | + leading, constant = line.all_coeffs() | |
| 111 | + expression = s.cancel(-constant / leading) | |
| 112 | + denominators.extend((denominator, leading)) | |
| 113 | + back_substitutions.append((variable, expression)) | |
| 114 | + equations = {key: s.cancel(poly.subs(variable, expression)) for key, poly in equations.items()} | |
| 115 | + denominators.extend(s.fraction(poly)[1] for poly in equations.values()) | |
| 116 | + | |
| 117 | + lhs, rhs = (s.fraction(poly)[0] for poly in equations.values()) | |
| 118 | + approximate_t = 2 * Fraction(report["area_approx"]) | |
| 119 | + scale = 10**55 | |
| 120 | + center = approximate_t * scale // 1 | |
| 121 | + interval = Interval(Fraction(center - 1, scale), Fraction(center + 2, scale)) | |
| 122 | + lo, hi = s.Rational(interval.lo), s.Rational(interval.hi) | |
| 123 | + resultant = s.resultant(lhs, rhs, g) | |
| 124 | + factors = [s.Poly(factor, t, domain=s.QQ) for factor, _ in s.factor_list(resultant)[1]] | |
| 125 | + isolated = [(factor, factor.count_roots(lo, hi)) for factor in factors] | |
| 126 | + matches = [factor for factor, count in isolated if count == 1] | |
| 127 | + require(len(matches) == 1 and sum(count for _, count in isolated) == 1, "resultant root is not isolated") | |
| 128 | + field_polynomial = matches[0] | |
| 129 | + require(field_polynomial.degree() == 19 and field_polynomial.eval(lo) * field_polynomial.eval(hi) < 0, | |
| 130 | + "the isolated root must lie strictly inside the interval and have degree 19") | |
| 131 | + | |
| 132 | + linear = [s.Poly(poly, g) for poly in s.subresultants(lhs, rhs, g) if s.degree(poly, g) == 1] | |
| 133 | + require(len(linear) == 1, "could not recover g from a linear subresultant") | |
| 134 | + leading, constant = linear[0].all_coeffs() | |
| 135 | + denominators.append(leading) | |
| 136 | + recover_g = s.cancel(-constant / leading) | |
| 137 | + for equation in (lhs, rhs): | |
| 138 | + numerator, denominator = s.fraction(s.cancel(equation.subs(g, recover_g))) | |
| 139 | + denominators.append(denominator) | |
| 140 | + remainder = s.Poly(numerator, t, domain=s.QQ).rem(field_polynomial) | |
| 141 | + require(remainder.is_zero, "the recovered g does not solve a remaining equation exactly") | |
| 142 | + | |
| 143 | + environment = {t: interval} | |
| 144 | + environment[g] = enclose(recover_g, environment) | |
| 145 | + for variable, formula in reversed(back_substitutions): | |
| 146 | + environment[variable] = enclose(formula, environment) | |
| 147 | + for denominator in set(denominators): | |
| 148 | + bound = enclose(denominator, environment) | |
| 149 | + require(not bound.lo <= 0 <= bound.hi, "an elimination denominator might vanish") | |
| 150 | + | |
| 151 | + base = [environment[key] for key in (a, b, c, d, e, f)] + [Interval.point(1), Interval.point(0)] | |
| 152 | + base += [environment[g], environment[h]] | |
| 153 | + exact_enclosures = axis_points(base, Interval.point(1)) | |
| 154 | + for point in exact_enclosures: | |
| 155 | + require(all(0 <= coordinate.lo <= coordinate.hi <= 1 for coordinate in point), "point outside square") | |
| 156 | + | |
| 157 | + gaps = [] | |
| 158 | + for triple in TRIPLES: | |
| 159 | + if triple in active: | |
| 160 | + continue | |
| 161 | + bound = determinant(exact_enclosures, triple) | |
| 162 | + absolute_lower = max(bound.lo, -bound.hi, 0) | |
| 163 | + gaps.append((absolute_lower - interval.hi) / 2) | |
| 164 | + gap = min(gaps) | |
| 165 | + require(gap > 0, "an inactive triangle is not certified to be larger") | |
| 166 | + | |
| 167 | + area = s.symbols("A") | |
| 168 | + area_polynomial = s.Poly(field_polynomial.as_expr().subs(t, 2 * area), area).primitive()[1] | |
| 169 | + # The largest lower bound at this precision gives a short exact number for the report. | |
| 170 | + gap_lower = Fraction(gap * 10**12 // 1, 10**12) | |
| 171 | + return { | |
| 172 | + "degree": area_polynomial.degree(), | |
| 173 | + "area_polynomial_coefficients_descending": [int(coefficient) for coefficient in area_polynomial.all_coeffs()], | |
| 174 | + "isolating_interval_for_area": [str(interval.lo / 2), str(interval.hi / 2)], | |
| 175 | + "active_triangles_with_exact_area": len(active), | |
| 176 | + "inactive_triangles_with_larger_area": len(gaps), | |
| 177 | + "inactive_area_gap_lower_bound": str(gap_lower), | |
| 178 | + "local_maximum_certificate": certify_local(exact_enclosures, observed, active, signs), | |
| 179 | + "seed": report["seed"], | |
| 180 | + } | |
| 181 | + | |
| 182 | + | |
| 183 | +def main(): | |
| 184 | + parser = argparse.ArgumentParser(description=__doc__) | |
| 185 | + parser.add_argument("configuration", type=Path) | |
| 186 | + parser.add_argument("tie_report", type=Path) | |
| 187 | + parser.add_argument("--output", type=Path, default=Path("algebraic-certificate.json")) | |
| 188 | + args = parser.parse_args() | |
| 189 | + comparison = json.loads(args.configuration.read_text(encoding="ascii")) | |
| 190 | + report = json.loads(args.tie_report.read_text(encoding="ascii")) | |
| 191 | + result = certify(comparison, report) | |
| 192 | + write_json(args.output, result) | |
| 193 | + print(f"certified: degree {result['degree']}, {result['active_triangles_with_exact_area']} exact ties, " | |
| 194 | + f"{result['inactive_triangles_with_larger_area']} strictly larger triangles", flush=True) | |
| 195 | + print("certified: strict local maximum in all 40 coordinate directions", flush=True) | |
| 196 | + | |
| 197 | + | |
| 198 | +if __name__ == "__main__": | |
| 199 | + main() | |
+14 −0 routes/irisbud-codex/square20-search/certify.sbatch added View file
| @@ -0,0 +1,14 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +#SBATCH --job-name=square20-certify | |
| 3 | +#SBATCH --cpus-per-task=1 | |
| 4 | +#SBATCH --time=00:15:00 | |
| 5 | +#SBATCH --mem=2048M | |
| 6 | +set -euo pipefail | |
| 7 | + | |
| 8 | +export OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 | |
| 9 | +repo=${SS_INPUT:-$(git rev-parse --show-toplevel)} | |
| 10 | +python=${PYTHON:-python3} | |
| 11 | +"$python" -B polish.py annealed-candidates.json reflection-candidates.json --limit 160 --output polished-best.data | |
| 12 | +"$python" -B refine.py polish-results.json --seed 2607 | |
| 13 | +"$python" -B certificate.py square-n20.json tie-report.json | |
| 14 | +"$python" -B compare.py square-n20.json "$repo/constructions/square-n20.json" --polish-report polish-results.json | |
+75 −0 routes/irisbud-codex/square20-search/compare.py added View file
| @@ -0,0 +1,75 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Compare the completed search to the repository reference after generating points.""" | |
| 3 | + | |
| 4 | +import argparse | |
| 5 | +from decimal import Decimal, localcontext | |
| 6 | +from fractions import Fraction | |
| 7 | +import json | |
| 8 | +from pathlib import Path | |
| 9 | + | |
| 10 | +from run_seeds import area, write_json | |
| 11 | + | |
| 12 | + | |
| 13 | +def read(path): | |
| 14 | + return json.loads(path.read_text(encoding="ascii")) | |
| 15 | + | |
| 16 | + | |
| 17 | +def coordinates(candidate): | |
| 18 | + return [(Fraction(x), Fraction(y)) for x, y in candidate["points"]] | |
| 19 | + | |
| 20 | + | |
| 21 | +def matching_error(candidate, reference): | |
| 22 | + source, target = coordinates(candidate), coordinates(reference) | |
| 23 | + errors = [] | |
| 24 | + for swap in (False, True): | |
| 25 | + for flip_x in (False, True): | |
| 26 | + for flip_y in (False, True): | |
| 27 | + matches = [] | |
| 28 | + for pair in source: | |
| 29 | + x, y = pair[::-1] if swap else pair | |
| 30 | + transformed = (1 - x if flip_x else x, 1 - y if flip_y else y) | |
| 31 | + distances = [max(abs(a - b) for a, b in zip(transformed, other)) for other in target] | |
| 32 | + index = min(range(len(target)), key=distances.__getitem__) | |
| 33 | + matches.append((index, distances[index])) | |
| 34 | + if len({index for index, _ in matches}) == len(target): | |
| 35 | + errors.append(max(distance for _, distance in matches)) | |
| 36 | + return min(errors) if errors else None | |
| 37 | + | |
| 38 | + | |
| 39 | +def decimal(value): | |
| 40 | + with localcontext() as ctx: | |
| 41 | + ctx.prec = 75 | |
| 42 | + return str(Decimal(value.numerator) / value.denominator) | |
| 43 | + | |
| 44 | + | |
| 45 | +def main(): | |
| 46 | + parser = argparse.ArgumentParser(description=__doc__) | |
| 47 | + parser.add_argument("configuration", type=Path) | |
| 48 | + parser.add_argument("reference", type=Path) | |
| 49 | + parser.add_argument("--polish-report", type=Path) | |
| 50 | + parser.add_argument("--output", type=Path, default=Path("comparison.json")) | |
| 51 | + args = parser.parse_args() | |
| 52 | + candidate, reference = read(args.configuration), read(args.reference) | |
| 53 | + measured, reference_area = area(candidate), area(reference) | |
| 54 | + ratio = measured / reference_area | |
| 55 | + error = matching_error(candidate, reference) | |
| 56 | + comparison = { | |
| 57 | + "candidate_area_exact": str(measured), | |
| 58 | + "reference_area_exact": str(reference_area), | |
| 59 | + "reference_ratio_exact": str(ratio), | |
| 60 | + "reference_ratio_decimal": decimal(ratio), | |
| 61 | + "relative_difference_decimal": decimal(ratio - 1), | |
| 62 | + "matched_coordinate_error_max_decimal": None if error is None else decimal(error), | |
| 63 | + } | |
| 64 | + if args.polish_report: | |
| 65 | + rows = read(args.polish_report) | |
| 66 | + if any(measured < Fraction(row["after"]) for row in rows): | |
| 67 | + raise ValueError("the polished archive contains a better configuration than the export") | |
| 68 | + comparison["polished_configurations_compared"] = len(rows) | |
| 69 | + write_json(args.output, comparison) | |
| 70 | + print(f"exact reference ratio: {comparison['reference_ratio_decimal']}", flush=True) | |
| 71 | + print(f"matched coordinate error: {comparison['matched_coordinate_error_max_decimal']}", flush=True) | |
| 72 | + | |
| 73 | + | |
| 74 | +if __name__ == "__main__": | |
| 75 | + main() | |
+108 −0 routes/irisbud-codex/square20-search/local_optimum.py added View file
| @@ -0,0 +1,108 @@ | ||
| 1 | +"""Certify a positive equilibrium spanning all coordinate directions.""" | |
| 2 | + | |
| 3 | +from fractions import Fraction | |
| 4 | +from math import ceil | |
| 5 | + | |
| 6 | +import numpy as np | |
| 7 | +from ortools.linear_solver import pywraplp | |
| 8 | + | |
| 9 | + | |
| 10 | +def require(condition, explanation): | |
| 11 | + if not condition: | |
| 12 | + raise ValueError(explanation) | |
| 13 | + | |
| 14 | + | |
| 15 | +def gradient_columns(points, active, signs, boundary): | |
| 16 | + for i, j, k in sorted(active): | |
| 17 | + a, b, c = (points[index] for index in (i, j, k)) | |
| 18 | + sign = signs[i, j, k] | |
| 19 | + column = [0] * 40 | |
| 20 | + column[2 * i:2 * i + 2] = [sign * (b[1] - c[1]), sign * (c[0] - b[0])] | |
| 21 | + column[2 * j:2 * j + 2] = [sign * (c[1] - a[1]), sign * (a[0] - c[0])] | |
| 22 | + column[2 * k:2 * k + 2] = [sign * (a[1] - b[1]), sign * (b[0] - a[0])] | |
| 23 | + yield column | |
| 24 | + for coordinate, inward in boundary: | |
| 25 | + column = [0] * 40 | |
| 26 | + column[coordinate] = inward | |
| 27 | + yield column | |
| 28 | + | |
| 29 | + | |
| 30 | +def choose_basis(matrix): | |
| 31 | + residuals = matrix.copy() | |
| 32 | + basis = [] | |
| 33 | + for _ in range(matrix.shape[0]): | |
| 34 | + lengths = np.linalg.norm(residuals, axis=0) | |
| 35 | + lengths[basis] = 0 | |
| 36 | + index = int(np.argmax(lengths)) | |
| 37 | + require(lengths[index] > 1e-8, "the numerical gradient matrix lacks full rank") | |
| 38 | + unit = residuals[:, index] / lengths[index] | |
| 39 | + residuals -= np.outer(unit, unit @ residuals) | |
| 40 | + basis.append(index) | |
| 41 | + return basis | |
| 42 | + | |
| 43 | + | |
| 44 | +def candidate_weights(matrix): | |
| 45 | + solver = pywraplp.Solver.CreateSolver("GLOP") | |
| 46 | + require(solver is not None, "OR-Tools is missing GLOP") | |
| 47 | + weights = [solver.NumVar(0, 1, "") for _ in range(matrix.shape[1])] | |
| 48 | + floor = solver.NumVar(0, 1, "") | |
| 49 | + for row in matrix: | |
| 50 | + solver.Add(sum(float(value) * weight for value, weight in zip(row, weights) if value != 0) == 0) | |
| 51 | + solver.Add(sum(weights) == 1) | |
| 52 | + for weight in weights: | |
| 53 | + solver.Add(weight >= floor) | |
| 54 | + solver.Maximize(floor) | |
| 55 | + require(solver.Solve() == pywraplp.Solver.OPTIMAL and floor.solution_value() > 0, | |
| 56 | + "could not find approximate positive equilibrium weights") | |
| 57 | + return [weight.solution_value() for weight in weights] | |
| 58 | + | |
| 59 | + | |
| 60 | +def certify_local(enclosed_points, observed, active, signs): | |
| 61 | + boundary = [] | |
| 62 | + for index, coordinate in enumerate(value for point in enclosed_points for value in point): | |
| 63 | + if coordinate.lo == coordinate.hi and coordinate.lo in (0, 1): | |
| 64 | + boundary.append((index, int(1 - 2 * coordinate.lo))) | |
| 65 | + | |
| 66 | + rational_scale = 10**12 | |
| 67 | + | |
| 68 | + def rational(value): | |
| 69 | + return Fraction(int(round(value * rational_scale)), rational_scale) | |
| 70 | + | |
| 71 | + centers = [[rational(value) for value in column] for column in gradient_columns(observed, active, signs, boundary)] | |
| 72 | + bounds = gradient_columns(enclosed_points, active, signs, boundary) | |
| 73 | + error = Fraction(0) | |
| 74 | + for column, enclosure in zip(centers, bounds, strict=True): | |
| 75 | + for center, bound in zip(column, enclosure, strict=True): | |
| 76 | + lo, hi = (bound, bound) if isinstance(bound, int) else (bound.lo, bound.hi) | |
| 77 | + error = max(error, abs(center - lo), abs(center - hi)) | |
| 78 | + | |
| 79 | + # Floating-point calculations propose a basis, approximate inverse and positive weights. | |
| 80 | + # The rational bounds below independently check them at the exact algebraic points. | |
| 81 | + matrix = np.array(centers, dtype=float).T | |
| 82 | + basis = choose_basis(matrix) | |
| 83 | + approximate_inverse = np.linalg.inv(matrix[:, basis]) | |
| 84 | + inverse = [[rational(value) for value in row] for row in approximate_inverse] | |
| 85 | + weights = [rational(value) for value in candidate_weights(matrix)] | |
| 86 | + dimension = matrix.shape[0] | |
| 87 | + inverse_norm = max(sum(map(abs, row)) for row in inverse) | |
| 88 | + basis_columns = [centers[index] for index in basis] | |
| 89 | + inverse_defect = max( | |
| 90 | + sum(abs(int(i == j) - sum(x * y for x, y in zip(row, column))) for j, column in enumerate(basis_columns)) | |
| 91 | + for i, row in enumerate(inverse) | |
| 92 | + ) + inverse_norm * dimension * error | |
| 93 | + require(inverse_defect < 1, "the exact gradient basis was not certified invertible") | |
| 94 | + | |
| 95 | + imbalance = [sum(weight * value for weight, value in zip(weights, row)) for row in zip(*centers)] | |
| 96 | + residual = max(abs(sum(x * y for x, y in zip(row, imbalance))) for row in inverse) | |
| 97 | + residual += inverse_norm * error * sum(map(abs, weights)) | |
| 98 | + correction = residual / (1 - inverse_defect) | |
| 99 | + positive_margin = min(weights) - correction | |
| 100 | + require(positive_margin > 0, "the exact equilibrium might have a nonpositive weight") | |
| 101 | + return { | |
| 102 | + "dimension": dimension, | |
| 103 | + "active_box_bounds": len(boundary), | |
| 104 | + "basis_column_indices": basis, | |
| 105 | + "inverse_defect_upper_bound": str(Fraction(ceil(inverse_defect * rational_scale), rational_scale)), | |
| 106 | + "positive_weight_lower_bound": str(Fraction(positive_margin * rational_scale // 1, rational_scale)), | |
| 107 | + "strict_local_maximum": True, | |
| 108 | + } | |
+123 −0 routes/irisbud-codex/square20-search/refine.py added View file
| @@ -0,0 +1,123 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Refine the independently found axis-reflection layout by solving its area ties.""" | |
| 3 | + | |
| 4 | +import argparse | |
| 5 | +from decimal import Decimal, ROUND_DOWN, localcontext | |
| 6 | +from fractions import Fraction | |
| 7 | +from itertools import combinations | |
| 8 | +import json | |
| 9 | +from pathlib import Path | |
| 10 | + | |
| 11 | +import mpmath as mp | |
| 12 | + | |
| 13 | +from run_seeds import area, write_json | |
| 14 | + | |
| 15 | + | |
| 16 | +TRIPLES = list(combinations(range(20), 3)) | |
| 17 | +OUTPUT_DIGITS = 70 | |
| 18 | +TIE_TOLERANCE = Fraction(1, 10**9) | |
| 19 | +BOUNDARY_TOLERANCE = Fraction(1, 10**10) | |
| 20 | + | |
| 21 | + | |
| 22 | +def axis_points(base, one): | |
| 23 | + """Input is four general orbit representatives and the two axis offsets.""" | |
| 24 | + general = [(base[i], base[i + 1]) for i in range(0, 8, 2)] | |
| 25 | + first_axis, second_axis = base[8:] | |
| 26 | + half = one / 2 | |
| 27 | + return (general + [(one - x, y) for x, y in general] | |
| 28 | + + [(one - x, one - y) for x, y in general] + [(x, one - y) for x, y in general] | |
| 29 | + + [(half, first_axis), (half, one - first_axis), (second_axis, half), (one - second_axis, half)]) | |
| 30 | + | |
| 31 | + | |
| 32 | +def determinant(points, triple): | |
| 33 | + (ax, ay), (bx, by), (cx, cy) = [points[i] for i in triple] | |
| 34 | + return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) | |
| 35 | + | |
| 36 | + | |
| 37 | +def as_mpf(value): | |
| 38 | + return mp.mpf(value.numerator) / value.denominator | |
| 39 | + | |
| 40 | + | |
| 41 | +def decimal_string(value): | |
| 42 | + with localcontext() as ctx: | |
| 43 | + ctx.prec = OUTPUT_DIGITS + 40 | |
| 44 | + approximate = Decimal(mp.nstr(value, OUTPUT_DIGITS + 35)) | |
| 45 | + return format(approximate.quantize(Decimal(1).scaleb(-OUTPUT_DIGITS), rounding=ROUND_DOWN), "f") | |
| 46 | + | |
| 47 | + | |
| 48 | +def refine(source): | |
| 49 | + points = [(Fraction(x), Fraction(y)) for x, y in source["points"]] | |
| 50 | + base = [coordinate for point in points[:4] for coordinate in point] + [points[16][1], points[18][0]] | |
| 51 | + fixed = {i: round(value) for i, value in enumerate(base) if abs(value - round(value)) <= BOUNDARY_TOLERANCE} | |
| 52 | + free = [i for i in range(len(base)) if i not in fixed] | |
| 53 | + signed = {triple: determinant(points, triple) for triple in TRIPLES} | |
| 54 | + minimum = min(map(abs, signed.values())) | |
| 55 | + active = [(triple, 1 if value > 0 else -1) for triple, value in signed.items() | |
| 56 | + if abs(value) <= minimum + TIE_TOLERANCE] | |
| 57 | + if minimum <= 0 or len(active) <= len(free): | |
| 58 | + raise ValueError("the layout has too few positive near-minimum triangles for the tie system") | |
| 59 | + | |
| 60 | + with mp.workdps(125): | |
| 61 | + def expanded(solution): | |
| 62 | + parameters = dict(zip(free, solution[:-1])) | fixed | |
| 63 | + return axis_points([parameters[i] for i in range(len(base))], mp.mpf(1)) | |
| 64 | + | |
| 65 | + def equations(*solution): | |
| 66 | + layout = expanded(solution) | |
| 67 | + return [orientation * determinant(layout, triple) - solution[-1] for triple, orientation in active] | |
| 68 | + | |
| 69 | + start = [as_mpf(base[i]) for i in free] + [as_mpf(minimum)] | |
| 70 | + solution = tuple(mp.findroot(equations, tuple(start), tol=mp.mpf("1e-110"), maxsteps=50)) | |
| 71 | + residual = max(map(abs, equations(*solution))) | |
| 72 | + if residual > mp.mpf("1e-100"): | |
| 73 | + raise ValueError(f"tie system did not converge: residual {residual}") | |
| 74 | + layout = expanded(solution) | |
| 75 | + if any(not 0 <= coordinate <= 1 for point in layout for coordinate in point): | |
| 76 | + raise ValueError("the refined points leave the square") | |
| 77 | + refined = {"container": "square", "n": 20, | |
| 78 | + "points": [[decimal_string(x), decimal_string(y)] for x, y in layout]} | |
| 79 | + refined_points = [(Fraction(x), Fraction(y)) for x, y in refined["points"]] | |
| 80 | + refined_areas = {triple: abs(determinant(refined_points, triple)) / 2 for triple in TRIPLES} | |
| 81 | + known_active = {triple for triple, _ in active} | |
| 82 | + exact_min = min(refined_areas.values()) | |
| 83 | + active_spread = max(refined_areas[triple] for triple in known_active) - exact_min | |
| 84 | + inactive_gap = min(value for triple, value in refined_areas.items() if triple not in known_active) - exact_min | |
| 85 | + if inactive_gap <= TIE_TOLERANCE or active_spread > Fraction(1, 10**(OUTPUT_DIGITS - 2)): | |
| 86 | + raise ValueError("the exact decimal configuration does not preserve the tie pattern") | |
| 87 | + if exact_min <= area(source): | |
| 88 | + raise ValueError("the high-precision configuration did not improve its input") | |
| 89 | + report = { | |
| 90 | + "decimal_digits": OUTPUT_DIGITS, | |
| 91 | + "fixed_base_coordinates": fixed, | |
| 92 | + "unknowns_including_twice_area": len(free) + 1, | |
| 93 | + "active_triangles": [list(triple) for triple, _ in active], | |
| 94 | + "active_spread_exact": str(active_spread), | |
| 95 | + "inactive_gap_exact": str(inactive_gap), | |
| 96 | + "newton_residual": mp.nstr(residual, 10), | |
| 97 | + "area_approx": mp.nstr(solution[-1] / 2, 72), | |
| 98 | + "area_exact": str(exact_min), | |
| 99 | + } | |
| 100 | + return refined, report | |
| 101 | + | |
| 102 | + | |
| 103 | +def main(): | |
| 104 | + parser = argparse.ArgumentParser(description=__doc__) | |
| 105 | + parser.add_argument("polish_report", type=Path) | |
| 106 | + parser.add_argument("--seed", required=True, type=int) | |
| 107 | + parser.add_argument("--output", type=Path, default=Path("square-n20.json")) | |
| 108 | + parser.add_argument("--report", type=Path, default=Path("tie-report.json")) | |
| 109 | + args = parser.parse_args() | |
| 110 | + rows = json.loads(args.polish_report.read_text(encoding="ascii")) | |
| 111 | + matches = [row for row in rows if row["seed"] == args.seed and row["end_mode"] == "axis-mid"] | |
| 112 | + if len(matches) != 1: | |
| 113 | + parser.error("specify a seed with a polished axis-mid layout") | |
| 114 | + refined, report = refine(matches[0]["candidate"]) | |
| 115 | + report["seed"] = args.seed | |
| 116 | + write_json(args.output, refined) | |
| 117 | + write_json(args.report, report) | |
| 118 | + print(f"seed {args.seed}: {len(report['active_triangles'])} near-minimum triangles, residual {report['newton_residual']}", flush=True) | |
| 119 | + print(f"metric: best_area {report['area_approx']}", flush=True) | |
| 120 | + | |
| 121 | + | |
| 122 | +if __name__ == "__main__": | |
| 123 | + main() | |
+4 −0 routes/irisbud-codex/square20-search/requirements.txt added View file
| @@ -0,0 +1,4 @@ | ||
| 1 | +numpy==2.5.5 | |
| 2 | +ortools==9.15.6755 | |
| 3 | +mpmath==1.3.0 | |
| 4 | +sympy==1.14.0 | |
