"""Check the manuscript tables and fixed rational planes using interval arithmetic.""" import json from fractions import Fraction from pathlib import Path import numpy as np from calibrated_kernel import improvement from check_rank import ( SCALE, TAU, L, M, Q, ceil_upper, diagonal_input, entropy_range, exact, floor_lower, ) from diagonal_tail import diagonal_residual, verify_clipped_tail from flint import arb from interpolated_kernel import InterpolatedKernel from mixed_gap import HIGH, LOW, band_gain from mixed_gap import verify as verify_arc def cut_interval(a, b, predicate): stack = [(a, b)] leaves = 0 while stack: a, b = stack.pop() if predicate(a, b, a.union(b)): leaves += 1 else: mid = (a + b) / 2 stack.extend([(a, mid), (mid, b)]) return leaves def scalar_checks(): def root_fn(x): return (1 - x) * (1 - x).log() + x * (1 + x).log() assert ( root_fn(exact("0.69090773872540775")) < 0 < root_fn(exact("0.69090773872540776")) ) def second(a, b, x): u = diagonal_input(a).union(diagonal_input(b)) du = 2 * x * (1 + TAU * (1 - x) * (1 - 2 * x)) ddu = 2 + TAU * (2 - 12 * x + 12 * x * x) curvature = Q * ((1 / u - 1).log() * ddu - du**2 / (u * (1 - u))) return curvature + 2 * ((1 + x).log() - (1 - x).log() - 1 + x / (1 + x)) > 0 def positive(a, b, x): phi = (entropy_range(diagonal_input(a), diagonal_input(b)) / L).sqrt() return diagonal_residual(a, b, x, phi) > 0 edge = arb(1) / 65536 l, u = exact(".68"), exact(".70") n = cut_interval(edge, l, positive) + cut_interval(l, u, second) n += cut_interval(u, 1 - edge, positive) def moment(a, b, x): phi = ( (entropy_range(diagonal_input(a), diagonal_input(b)) / L) .nonnegative_part() .sqrt() ) return entropy_range(a, b) <= 4 * phi / 5 + arb(27) / 400 return n, cut_interval(arb(0), arb(1), moment) def calibrated_rectangles(): from functools import lru_cache @lru_cache(None) def point(a, b, kind): a, b = exact(a), exact(b) x = a.union(b) phi = ( (entropy_range(diagonal_input(a), diagonal_input(b)) / L) .nonnegative_part() .sqrt() ) gain = improvement(a, b, phi, kind) if kind == "off": f = TAU.sqrt() * x * (1 - x) elif kind == "linear": f = x else: f = (arb(1) / 2 - x * x).sqrt() return x, f, phi, gain def visit(a, b, k, c, d, j): x, f, px, gx = point(a, b, k) y, g, py, gy = point(c, d, j) i = x * y + f * g if entropy_range(i.lower(), i.upper()) >= L * (px * py + px * gy + py * gx): return 1 if b - a > d - c: m = (a + b) / 2 return visit(a, m, k, c, d, j) + visit(m, b, k, c, d, j) m = (c + d) / 2 return visit(a, b, k, c, m, j) + visit(a, b, k, m, d, j) cuts = list(map(Fraction, ["0.0009765625", ".4", ".5", ".67", "1"])) pieces = list(zip(cuts, cuts[1:], ["off", "linear", "circle", "off"])) return sum(visit(*left, *right) for left in pieces[1:3] for right in pieces) def features(anchors, profile): # Each original span has 768 subintervals graded towards both ends. knots = [arb(i) / 200 for i, _, _ in anchors] fs = [arb(f) / SCALE for _, f, _ in anchors] ks = [arb(k) / SCALE for _, _, k in anchors] def boundary(i): span, j = divmod(i, 768) y = arb(j) / 768 return (span + y * y * (3 - 2 * y)) / 200 low, high = [], [] j = 0 for i in range(200 * 768): if i == anchors[j + 1][0] * 768: j += 1 a, b = boundary(i), boundary(i + 1) x = a.union(b) h = entropy_range(a, b) phi = ( (entropy_range(diagonal_input(a), diagonal_input(b)) / L) .nonnegative_part() .sqrt() ) d = arb(0).union(Q * L * phi) if phi > 0: d = d.intersection( (entropy_range(a * a, b * b) + Q * L * phi**2 - 2 * x * h) / phi ) if 0 < a and b < 1: d = d.intersection(diagonal_residual(a, b, x, phi)) d = d.nonnegative_part() width = knots[j + 1] - knots[j] t = (x - knots[j]) / width early = ( fs[j] + t * (fs[j + 1] - fs[j]) + t * (1 - t) * width * (ks[j] - ks[j + 1]) ) late = (knots[0] - M) * h - fs[0] - ks[0] * (x - knots[0]) for p, f, k in zip(knots[1:], fs[1:], ks[1:]): late = late.min((p - M) * h - f - k * (x - p)) span = i // 768 kind = ( "linear" if 80 <= span < 100 else "circle" if 100 <= span < 134 else "off" ) bump = improvement(a, b, phi, kind) gain = ( band_gain(a, b, x) if LOW * 200 <= span < HIGH * 200 else (phi * (d + 2 * Q * L * bump)).nonnegative_part().sqrt() ) values = [ arb(1), x, h, phi, d, early + 8, late + 8, bump, bump**2, profile.feature(span, x), gain, ] assert early + 8 >= 0 and late + 8 >= 0 low.append([max(0, floor_lower(y * SCALE)) for y in values]) high.append([ceil_upper(y * SCALE) for y in values]) return np.array(low, dtype=np.int64), np.array(high, dtype=np.int64) def coefficients(w, a, b, v, constants): z, mu, lam, s, m, ql = constants mean, k, left, right, table, arc, v1, v2, b1, b2 = v cal = mu - table - arc return [ -8 - mean * s + (lam + table) * ql * a * b + k * z + left * a - right * b - ql * v2 - b2, mean, lam * (2 * s - 1) - 2 * mu * (m - s) - k, -(lam + table) * ql * (a + b) - left + right, (mu + lam - arc) * a, w, 1 - w, 2 * cal * ql * a, -cal * ql, 2 * ql * v1, 2 * b1, ] def check_planes(low, high, edges, constants, records, targets, *, two_responses=False): """Check every fixed plane against all 153600 feature intervals.""" divisions = len(targets) - 1 assert set(targets) == set(range(divisions + 1)) assert len(records) == (divisions + 1) * 173 block_size = 48 block_low = low.reshape(-1, block_size, 11).min(axis=1) block_high = high.reshape(-1, block_size, 11).max(axis=1) magnitudes = high.max(axis=0).tolist() levels = [10**18] * (divisions + 1) for index, record in enumerate(records): rank, cell = divmod(index, 173) assert (record["rank"], record["cell"]) == (rank, cell) multipliers = record["multipliers"] assert len(multipliers) == 6 # Lean uses M1 <= 2*z*(lambda + mu) for its mean correction; the upper limit is rounded down at scale 10^6. assert -120000000 <= multipliers[0] <= 2260333 assert min(multipliers[1:]) >= 0 assert multipliers[4] + multipliers[5] <= 3917801 assert 0 <= record["u"] <= 10**6 and 0 <= record["v"] <= 10**6 values = [arb(value) / 10**6 for value in multipliers] u, v = (arb(record[key]) / 10**6 for key in ("u", "v")) if two_responses: assert sum(multipliers[4:6]) == 3917801 w = arb(rank) / divisions weight = (1 - w) / 2 + values[5] values += [values[4] * u, values[4] * u * u, weight * v, weight * v * v] coefficients_real = coefficients( w, edges[cell], edges[cell + 1], values, constants ) coefficients_int = [floor_lower(value * 10**8) for value in coefficients_real] assert coefficients_int == record["coefficients"] assert sum(abs(c) * m for c, m in zip(coefficients_int, magnitudes)) < 2**63 plane = np.array(coefficients_int, dtype=np.int64) positive, negative = plane.clip(0), plane.clip(max=0) # Block hulls give lower bounds. Refine every block that can beat # a known upper bound on the minimum. All operations here are integers. rough = block_low @ positive + block_high @ negative start = int(rough.argmin()) * block_size upper = int( ( low[start : start + block_size] @ positive + high[start : start + block_size] @ negative ).min() ) candidates = ( block_size * np.flatnonzero(rough <= upper)[:, None] + np.arange(block_size) ).ravel() minimum = int((low[candidates] @ positive + high[candidates] @ negative).min()) assert minimum == record["bound"] levels[rank] = min(levels[rank], minimum) if cell == 172: assert levels[rank] >= targets[rank] * 10**8 print(f"Rank {rank:02d}: {levels[rank]} / 10^15", flush=True) return levels def main(): directory = Path(__file__).resolve().parent data = json.loads((directory / "inputs.json").read_text()) anchors, response = data["anchors"], data["response"] targets = dict(data["ranks"]) assert len(anchors) == 39 and len(response) == 59 assert set(targets) == set(range(25)) print( "Local interval checks:", scalar_checks(), calibrated_rectangles(), verify_arc(), verify_clipped_tail(), flush=True, ) profile = InterpolatedKernel( [(j, t) for j, _, t in response], [f for _, f, _ in response] ) low, high = features(anchors, profile) print(f"Feature intervals: {len(low)}", flush=True) edges = [Fraction(41, 320)] for first, last, count in [ (edges[0], Fraction(83, 100), 28), (Fraction(83, 100), Fraction(997, 1000), 144), (Fraction(997, 1000), Fraction(1), 1), ]: for j in range(1, count + 1): point = (first * (count - j) + last * j) / count edges.append(Fraction(round(point * SCALE), SCALE)) z, mu, lam, eps = map(exact, [".17", "3.917801", "2.73024", ".001636"]) s = M - eps tail = lam * (2 * s - 1) - M - 2 * mu * eps assert tail > exact(".00063556") certificates = json.loads((directory / "planes.json").read_text()) coarse = ( certificates if isinstance(certificates, list) else certificates["three_response"] ) runs = [("25-node certificate", coarse, targets, False)] if isinstance(certificates, dict): ranks = dict(data["two_response_ranks"]) assert len(ranks) == 49 runs.append(("49-node certificate", certificates["two_response"], ranks, True)) for name, rows, rank_targets, two in runs: levels = check_planes( low, high, list(map(exact, edges)), [z, mu, lam, s, M, Q * L], rows, rank_targets, two_responses=two, ) divisions = len(levels) - 1 average = Fraction( 2 * sum(levels) - levels[0] - levels[-1], 2 * divisions * 10**15 ) floor = Fraction( 2 * sum(rank_targets.values()) - rank_targets[0] - rank_targets[divisions], 2 * divisions * SCALE, ) assert average >= floor > Fraction(4, 10**7) if not two: assert floor == Fraction(41, 80000000) print(f"{name}: {len(rows)} planes, average {average}, rounded bound {floor}") print(f"Tail margin: {tail}") print("Verified all fixed planes and local interval comparisons.") if __name__ == "__main__": main()