"""Refine a 15-point basin and bound its nearby equal-area solution.""" import argparse import json from decimal import Decimal, localcontext from fractions import Fraction from itertools import combinations from pathlib import Path TRIPLES = tuple(combinations(range(15), 3)) ACTIVE_TOLERANCE = Decimal("1e-9") RADIUS = Fraction(1, 10**42) def signed_area(points, triple): (ax, ay), (bx, by), (cx, cy) = (points[index] for index in triple) return ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)) / 2 def derivatives(points, triple): (ax, ay), (bx, by), (cx, cy) = (points[index] for index in triple) return ((by - cy, cx - bx), (cy - ay, ax - cx), (ay - by, bx - ax)) def solve(matrix, rhs): rows = [list(a) + list(b) for a, b in zip(matrix, rhs)] size = len(rows) for col in range(size): pivot = max(range(col, size), key=lambda row: abs(rows[row][col])) rows[col], rows[pivot] = rows[pivot], rows[col] if not rows[col][col]: raise ValueError("singular system of critical triangles") row = [value / rows[col][col] for value in rows[col]] rows[col] = row for i, other in enumerate(rows): if i != col and other[col]: rows[i] = [a - other[col] * b for a, b in zip(other, row)] return [row[size:] for row in rows] def coordinates(template, free, state): points = [list(point) for point in template] for (point, axis), value in zip(free, state): points[point][axis] = value return points def evaluate(template, free, active, state): points = coordinates(template, free, state) by_coordinate = {key: i for i, key in enumerate(free)} values, jacobian = [], [] for triple, sign in active: row = [0] * len(state) row[-1] = -1 for index, (dx, dy) in zip(triple, derivatives(points, triple)): for axis, deriv in enumerate((dx, dy)): position = by_coordinate.get((index, axis)) if position is not None: row[position] = sign * deriv / 2 values.append(sign * signed_area(points, triple) - state[-1]) jacobian.append(row) return values, jacobian def stationarity_margins(points, free, active, norm_inv, contraction, inverse): # At the certified root the inverse differs from our approximate inverse # by at most this amount in the induced infinity norm (Neumann series). inverse_error = norm_inv * contraction / (1 - contraction) weights = [-value for value in inverse[-1]] weight_margin = min(weights) - inverse_error gradient = [[Fraction(0), Fraction(0)] for _ in points] for (triple, sign), weight in zip(active, weights): for index, (dx, dy) in zip(triple, derivatives(points, triple)): gradient[index][0] += weight * sign * dx / 2 gradient[index][1] += weight * sign * dy / 2 # Every area derivative has magnitude at most 1/2 and changes by at most # RADIUS. The exact positive weights sum to one by the last column of J. error = inverse_error / 2 + RADIUS free = set(free) margins = [] for index, point in enumerate(points): for axis, value in enumerate(point): if (index, axis) not in free: coefficient = gradient[index][axis] margins.append((coefficient if value == 1 else -coefficient) - error) return weight_margin, min(margins, default=Fraction(1)), norm_inv + inverse_error def certify(template, free, active, state, inverse): """Use exact rational arithmetic for the residual and contraction bounds.""" template = [[Fraction(value) for value in point] for point in template] state = list(map(Fraction, state)) values, jacobian = evaluate(template, free, active, state) columns = list(zip(*jacobian)) inverse = [[Fraction(value) for value in row] for row in inverse] norm_inv = max(sum(map(abs, row)) for row in inverse) residual = max( sum(abs(int(i == j) - sum(a * b for a, b in zip(row, column))) for j, column in enumerate(columns)) for i, row in enumerate(inverse) ) correction = max(abs(sum(a * b for a, b in zip(row, values))) for row in inverse) contraction = residual + 6 * RADIUS * norm_inv if contraction >= 1 or correction + contraction * RADIUS > RADIUS: raise ValueError("could not certify the contraction") if any(not RADIUS < value < 1 - RADIUS for value in state[:-1]): raise ValueError("certificate box would extend outside the square") points = coordinates(template, free, state) critical = {triple for triple, _ in active} inactive_min = min(abs(signed_area(points, triple)) for triple in TRIPLES if triple not in critical) if inactive_min - 6 * RADIUS <= state[-1] + RADIUS or state[-1] <= RADIUS: raise ValueError("could not separate inactive triangles from the common minimum") weight_margin, boundary_margin, inverse_bound = stationarity_margins( points, free, active, norm_inv, contraction, inverse ) local_radius = Fraction(0) if weight_margin > 0 and boundary_margin > 0: direction_bound = max(1 / boundary_margin, inverse_bound * (1 / weight_margin + 1 / (2 * boundary_margin))) local_radius = min(1 / (6 * direction_bound), (state[-1] - RADIUS) / 6) return { "free_coordinates": len(free), "active_triangles": len(active), "radius": "1e-42", "contraction_factor_bound_approx": str(float(contraction)), "center_correction_approx": str(float(correction)), "minimum_active_weight_bound_approx": str(float(weight_margin)), "minimum_boundary_sign_margin_approx": str(float(boundary_margin)), "strict_local_maximum": local_radius > 0, "local_maximum_radius_approx": str(float(local_radius)), "area_center": str(Decimal(state[-1].numerator) / Decimal(state[-1].denominator)), "area_interval": [str(state[-1] - RADIUS), str(state[-1] + RADIUS)], "exact_minimum_of_decimal_export": str(min(abs(signed_area(points, triangle)) for triangle in TRIPLES)), } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("input", type=Path) parser.add_argument("output", type=Path) args = parser.parse_args() with localcontext() as ctx: ctx.prec = 90 template = [list(map(Decimal, line.split())) for line in args.input.read_text().splitlines() if line.strip() and not line.lstrip().startswith("#")] if len(template) != 15: raise ValueError("expected 15 points") free = [] for i, point in enumerate(template): for axis, value in enumerate(point): if abs(value) < ACTIVE_TOLERANCE: point[axis] = Decimal(0) elif abs(value - 1) < ACTIVE_TOLERANCE: point[axis] = Decimal(1) else: free.append((i, axis)) areas = [signed_area(template, triple) for triple in TRIPLES] lowest = min(map(abs, areas)) active = [(triple, 1 if area > 0 else -1) for triple, area in zip(TRIPLES, areas) if abs(area) <= lowest + ACTIVE_TOLERANCE] state = [template[i][axis] for i, axis in free] + [lowest] if len(active) != len(state): raise ValueError(f"{len(active)} active triangles for {len(state)} unknowns") for _ in range(7): values, jacobian = evaluate(template, free, active, state) step = solve(jacobian, [[value] for value in values]) state = [value - delta[0] for value, delta in zip(state, step)] state = [Decimal(f"{value:.60f}") for value in state] _, jacobian = evaluate(template, free, active, state) identity = [[Decimal(i == j) for j in range(len(state))] for i in range(len(state))] approximate_inverse = [[f"{value:.45f}" for value in row] for row in solve(jacobian, identity)] report = certify(template, free, active, state, approximate_inverse) points = coordinates(template, free, state) args.output.write_text("".join(f"{x} {y}\n" for x, y in points)) print(json.dumps(report, indent=2)) if __name__ == "__main__": main()