#!/usr/bin/env python3 """0029_assembly.py — an independent assembly of the pg186 cap scalar `trialIH`. Programme 0029. Builds denominator = sum_shells sum_sigs sum_{j in mask} radial_sig(j) * moment_sig(cap_shell)_j from `Challenge.lean`'s own definitions plus the proved mass law, using * fixed point at 2**224 with exact integer products (module `0029_ntt.py`: NTT+CRT over 16 primes, no FLINT); * a self-contained implementation of the Dickman enclosure recurrence and of the moment/block combinatorics; * exact rational scoring: each signature sum is reconstructed as an exact integer by CRT over the NTT primes plus 24 extra primes, then divided by the exact denominator 10^20 * (10*258046918656)^12 * 2^224. Cell laws (`--law`): trapz the certificate's own `survival`: A_j/h = (d_j+d_{j+1})/2 - h^2/(12c^2) (CONTROL) mean the density at the grid point, s_j = d_j (what the inherited finding attributed to the certificate, and what the task spec calls its "own" law) double (trapz_j + trapz_{j+1})/2 (the substitution of the round-9 experiment) exact the true cell mass M * int_{j/M}^{(j+1)/M} rho(u) du (the paper's (2.2)) Usage: python 0029_assembly.py --law trapz [--cap 68225] [--sigs N] [--out FILE] """ from __future__ import annotations import argparse import gc import importlib.util import json import sys import time from fractions import Fraction as F from itertools import islice from pathlib import Path import numpy as np from mpmath import mp, mpf, log, floor as mpfloor HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) _spec = importlib.util.spec_from_file_location("ntt0029", HERE / "0029_ntt.py") NTT = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(NTT) mp.dps = 90 # ---------------------------------------------------------------- Challenge.lean data N_CELLS = 98264 SHIFT = 224 SCALE = 1 << SHIFT A_NUM, B_DEN = 2742997, 258046918656 # trialMesh = A_NUM / B_DEN H_MPF = mpf(A_NUM) / B_DEN SIGNATURES = [(), (2,), (3,), (4,), (5,), (6,), (2, 2), (2, 3), (2, 4), (3, 3), (2, 2, 2)] COEFFICIENTS = [ [10000000000, -264598476112, 834262268474, -3540575351215, 5377491111325, 116705356572254, 121730820431102], [71070047507, 7222861788586, -48747932657986, 290976672545723, -1136422724027134, -2058910631434711, 1375878942948547], [6457252424873, -61201446212885, 28811649792090, -2058803084231281, 9970156747759406, 38278849934023144, 34806920812932737], [-16779263512274, 128033707910825, 169290603857215, 7359669931312727, -35090795379920588, -120997133235510923, -141527585901304670], [28114161526671, -276375633435566, -690482702304933, -15120456749385986, 47650276584638031, 372137534144492224, 2191913505882230103], [-21150553032771, 379875924448266, -929062247569514, -13967219843969236, 168416050564605519, -248058724714138769, -4161797957833172083], [-19004216224617, 136674974139652, -183344485344333, 1114879023072977, 1119583327002910, -47568062965320963, 2537631525616777], [31171802814567, -97428388152051, 526635309233054, 1222047580792220, 15846796161434448, -165623953461271580, -2358019996221938729], [-53602626608739, 329397902441121, 1613505134333316, 13893066541430270, -126262434123562668, 239934302929501943, -1506861482386002243], [27653330903418, -290549334488305, -1847330641348475, 28351866831729468, -61505472221886320, -424266003419714347, 2585236507449911535], [12374547113901, -244168600145684, 1603694896120437, -21603130476787649, -30285492734943698, 381987976419637874, 3605516061450295448], ] # outer shells: (upper index of (r+40), per-coordinate cap index) OUTER_SHELLS = ((89236, 68225), (95638, 49152), (98304, 46580)) SHELL_LOWER = {89236: 0, 95638: 89236, 98304: 95638} DEADLINE_DEN = 10 ** 20 * (10 * B_DEN) ** 12 * SCALE def _is_prime(n): if n < 2: return False for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37): if n % p == 0: return n == p d, s = n - 1, 0 while d % 2 == 0: d //= 2 s += 1 for a in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37): x = pow(a, d, n) if x in (1, n - 1): continue for _ in range(s - 1): x = x * x % n if x == n - 1: break else: return False return True SCORE_PRIMES = tuple(islice((p for p in range((1 << 30) + 1, (1 << 31), 2) if _is_prime(p)), 24)) ALL_PRIMES = NTT.PRIMES + SCORE_PRIMES ALL_Q = 1 for _p in ALL_PRIMES: ALL_Q *= _p _PRIME_ROW = np.array(ALL_PRIMES, dtype=np.int64) # ---------------------------------------------------------------- combinatorics def block_partitions(signature): """Set partitions of the multiset `signature`; blocks are exponent SUMS.""" from collections import Counter, defaultdict if not signature: return (((), 1),) q, answer = signature[-1], defaultdict(int) for blocks, multiplicity in block_partitions(signature[:-1]): answer[tuple(sorted((*blocks, q)))] += multiplicity for value, copies in Counter(blocks).items(): joined = list(blocks) joined.remove(value) answer[tuple(sorted(joined + [value + q]))] += multiplicity * copies return tuple(sorted(answer.items(), key=lambda item: (len(item[0]), item[0]))) def moment_terms(count, signature): from math import prod return tuple( (blocks, m * prod(range(count - len(blocks) + 1, count + 1))) for blocks, m in block_partitions(tuple(sorted(signature))) if len(blocks) <= count ) def square_polynomials(): from collections import defaultdict groups = defaultdict(lambda: [F(0)] * 13) descriptors = [(s, d) for s in SIGNATURES for d in range(7)] coeffs = [F(v, 10 ** 10) for row in COEFFICIENTS for v in row] for i, (si, di) in enumerate(descriptors): for j in range(i, len(descriptors)): sj, dj = descriptors[j] groups[tuple(sorted(si + sj))][di + dj] += coeffs[i] * coeffs[j] * (1 if i == j else 2) return {s: tuple(p) for s, p in groups.items()} # ---------------------------------------------------------------- grid and cell laws def build_grid(cap_index): """The `dickmanDirectedGrid` recurrence: lo_j <= rho(j/M) <= hi_j.""" M = cap_index c = H_MPF * M err = H_MPF ** 3 / (2 * c ** 3) lo = [mpf(1)] * (M + 1) hi = [mpf(1)] * (M + 1) for j in range(M, N_CELLS): hi_i = hi[j - M] / (2 * j) + hi[j + 1 - M] / (2 * (j + 1)) lo_i = lo[j - M] / (2 * j) + lo[j + 1 - M] / (2 * (j + 1)) lo.append(max(mpf(0), lo[j] - hi_i)) hi.append(min(mpf(1), hi[j] - lo_i + err)) return lo, hi def _G(u): """Antiderivative of 1 - log u (the Dickman density on 1 <= u <= 2).""" return 2 * u - u * log(u) _GL_NODES, _GL_WEIGHTS = np.polynomial.legendre.leggauss(28) _GL_NODES = [mpf(float(x)) for x in _GL_NODES] _GL_WEIGHTS = [mpf(float(w)) for w in _GL_WEIGHTS] def _phi_beyond_two(cap_index): """Phi(j) = int_2^{j/M} rho(u) du for every grid point j/M >= 2.""" M = cap_index if 2 * M > N_CELLS: return {} ln2 = log(mpf(2)) out = {} for j in range(2 * M, N_CELLS + 1): u = mpf(j) / M w = u - 1 half, mid = (w - 1) / 2, (w + 1) / 2 acc = mpf(0) for x, wt in zip(_GL_NODES, _GL_WEIGHTS): v = mid + half * x acc += wt * (1 - log(v)) / (v + 1) * (u - 1 - v) out[j] = (1 - ln2) * (u - 2) - acc * half return out def cell_law(law, cap_index, lo, hi): """A_j(c)/h for every cell; `lo`,`hi` are the density enclosures.""" M = cap_index err = H_MPF ** 2 / (12 * (H_MPF * M) ** 2) trapz = [mpf(1)] * M + [ max(mpf(0), min(mpf(1), (lo[j] + lo[j + 1]) / 2 - err)) for j in range(M, N_CELLS) ] if law == "trapz": return trapz if law == "mean": return [mpf(1)] * M + [lo[j] for j in range(M, N_CELLS)] if law == "double": return [(trapz[j] + (trapz[j + 1] if j + 1 < N_CELLS else trapz[j])) / 2 for j in range(N_CELLS)] if law == "exact": phi = _phi_beyond_two(cap_index) out = [mpf(1)] * M for j in range(M, N_CELLS): a, b = mpf(j) / M, mpf(j + 1) / M if b <= 2: val = (_G(b) - _G(a)) * M elif a >= 2: val = (phi[j + 1] - phi[j]) * M else: val = ((_G(mpf(2)) - _G(a)) + phi[j + 1]) * M out.append(max(mpf(0), min(mpf(1), val))) return out raise ValueError(law) def coordinate_weights(): w1, w2 = mpf(21) / 200, mpf(179) / 200 g = [w1 / (1 + (mpf(j) + mpf("0.5")) * H_MPF / 100) + w2 / (1 + (mpf(907) / 5) * (mpf(j) + mpf("0.5")) * H_MPF) for j in range(N_CELLS)] Z = sum(x * x for x in g) u = [x * x / Z for x in g] t = [(mpf(j) + mpf("0.5")) * H_MPF for j in range(N_CELLS)] return u, t, Z def fixed_array(values): return [int(mpfloor(v * SCALE)) for v in values] # ---------------------------------------------------------------- exact scoring def pack_signed(values): """Pack signed Python ints into 4-byte limbs plus a sign mask (for modular work).""" n = len(values) width = 40 buf = np.zeros((n, width), dtype=np.uint8) neg = np.zeros(n, dtype=bool) for j, v in enumerate(values): if v < 0: neg[j] = True v = -v buf[j] = np.frombuffer(int(v).to_bytes(width, "little"), dtype=np.uint8) nlimb = width // 4 limbs = np.empty((nlimb, n), dtype=np.int64) for i in range(nlimb): c = buf[:, 4 * i:4 * i + 4].astype(np.int64) limbs[i] = c[:, 0] | (c[:, 1] << 8) | (c[:, 2] << 16) | (c[:, 3] << 24) return limbs, neg def limbs_mod(limbs, neg, prime): acc = np.zeros(limbs.shape[1], dtype=np.int64) pw = 1 base = (1 << 32) % prime for i in range(limbs.shape[0]): acc = (acc + limbs[i] % prime * pw) % prime pw = pw * base % prime return np.where(neg, (-acc) % prime, acc) def crt_signed(residues, modulus): x, P = 0, 1 for r, p in zip(residues, ALL_PRIMES): t = ((r - x) % p) * pow(P % p, p - 2, p) % p x += P * t P *= p x %= modulus return x - modulus if x > modulus // 2 else x def one_poly(): v = np.zeros((NTT.K, N_CELLS), dtype=np.int32) for t, p in enumerate(NTT.PRIMES): v[t, 0] = SCALE % p return v # ---------------------------------------------------------------- main def main(): ap = argparse.ArgumentParser() ap.add_argument("--law", default="trapz", choices=("trapz", "mean", "double", "exact")) ap.add_argument("--cap", type=int, default=None) ap.add_argument("--sigs", type=int, default=None) ap.add_argument("--out", default=None) args = ap.parse_args() t0 = time.time() def stamp(msg): print("[%7.1fs] %s" % (time.time() - t0, msg), flush=True) stamp("law = %s" % args.law) u, t, Z = coordinate_weights() stamp("weights ready, Z = %.15g" % float(Z)) squares = square_polynomials() groups = sorted(squares.items(), key=lambda kv: (sum(kv[0]), kv[0])) print("total signatures available:", len(groups)) if args.sigs: groups = groups[: args.sigs] stamp("%d square groups in this run" % len(groups)) shells = OUTER_SHELLS if args.cap is None else tuple(s for s in OUTER_SHELLS if s[1] == args.cap) if not shells: raise SystemExit("no outer shell with cap %d" % args.cap) # radial polynomial data D_ = 10 * B_DEN Dp = [D_ ** (12 - d) for d in range(13)] radial_p = {} for sig, poly in groups: p = [] for c in poly: q = c * 10 ** 20 assert q.denominator == 1 p.append(int(q)) radial_p[sig] = p N_j = np.array([10 * (j + 20) * A_NUM - 9 * B_DEN for j in range(N_CELLS)], dtype=np.int64) stamp("radial polynomial data ready") results = [] total = F(0) for upper_idx, cap in shells: lo, hi = build_grid(cap) stamp("cap %d: grid built" % cap) law = cell_law(args.law, cap, lo, hi) mx = max(law) wres = [] for e in range(13): arr = fixed_array([u[j] * law[j] * t[j] ** e for j in range(N_CELLS)]) wres.append(NTT.encode_ints_fast(arr, N_CELLS).astype(np.int32)) del law stamp("cap %d: 13 weighted arrays ready (max %.6g)" % (cap, float(mx))) eng = NTT.ConvolutionEngine(N_CELLS, SHIFT) pp, bp = {}, {} def prob_power(m): if m not in pp: if m == 0: v = one_poly() elif m == 1: v = wres[0] else: half = prob_power(m // 2) v = eng.mul_low(half, half).astype(np.int32) if m & 1: v = eng.mul_low(v, wres[0]).astype(np.int32) pp[m] = v return pp[m] def block_product(blocks): if blocks not in bp: if not blocks: v = one_poly() elif len(blocks) == 1: v = wres[blocks[0]] else: v = eng.mul_low(block_product(blocks[:-1]), wres[blocks[-1]]).astype(np.int32) bp[blocks] = v return bp[blocks] need_m = sorted({40 - len(b) for sig, _ in groups for b, _ in moment_terms(40, sig)}) for m in need_m: prob_power(m) blocks_all = sorted({b for sig, _ in groups for b, _ in moment_terms(40, sig)}, key=len) for b in blocks_all: block_product(b) stamp("cap %d: %d probability powers, %d block products, %d products total" % (cap, len(pp), len(bp), eng.n_mul)) # mask on (r + 40) idx = np.arange(N_CELLS) + 40 mask = ((idx > SHELL_LOWER[upper_idx]) & (idx <= upper_idx)).astype(np.int64) stamp("cap %d: mask covers %d cells" % (cap, int(mask.sum()))) # power tables of N_j mod each prime nres = {p: N_j % p for p in ALL_PRIMES} pw = {} for p in ALL_PRIMES: seq = [np.ones(N_CELLS, dtype=np.int64)] for d in range(12): seq.append(seq[-1] * nres[p] % p) pw[p] = seq stamp("cap %d: power tables ready" % cap) shell_total = F(0) for si, (sig, poly) in enumerate(groups): terms = moment_terms(40, sig) mom = None for blocks, coef in terms: term = eng.mul_low(prob_power(40 - len(blocks)), block_product(blocks)) scaled = term * (coef % NTT._PRIME_ARR[:, None]) % NTT._PRIME_ARR[:, None] mom = scaled if mom is None else (mom + scaled) % NTT._PRIME_ARR[:, None] vals = NTT.decode_ints(mom) half = NTT.CRT_MODULUS // 2 vals = [v - NTT.CRT_MODULUS if v > half else v for v in vals] limbs, neg = pack_signed(vals) residues = [] for p in ALL_PRIMES: mv = limbs_mod(limbs, neg, p) * mask % p acc = np.zeros(N_CELLS, dtype=np.int64) for d in range(13): acc = (acc + (radial_p[sig][d] * Dp[d]) % p * pw[p][d]) % p residues.append(int((mv * acc % p).sum()) % p) S = crt_signed(residues, ALL_Q) val = F(S, DEADLINE_DEN) shell_total += val print(" [%7.1fs] sig %-14s = %.12g" % (time.time() - t0, str(sig), float(val)), flush=True) total += shell_total stamp("cap %d shell contribution = %.15g" % (cap, float(shell_total))) results.append(dict(cap=cap, cells=int(mask.sum()), value=float(shell_total), exact=str(shell_total), products=eng.n_mul)) del wres, pp, bp, eng, pw, nres, mom, vals, limbs gc.collect() lo_f, hi_f = float(F(23685317816, 10 ** 24)), float(F(23685317890, 10 ** 24)) inside = F(23685317816, 10 ** 24) <= total <= F(23685317890, 10 ** 24) print() print("I_H (%s) = %.15g" % (args.law, float(total))) print("axiom interval = [%.15g, %.15g] inside: %s" % (lo_f, hi_f, inside)) print("exact fraction = %s" % total) if args.out: Path(args.out).write_text(json.dumps(dict( law=args.law, value=float(total), exact=str(total), inside=inside, shells=results, seconds=time.time() - t0), indent=2), encoding="utf-8") if __name__ == "__main__": main()