#!/usr/bin/env python3 """Job 966 (route 5 pursuit): alignment controls for the N66 weighted certificate. Reference (frozen by #363): the first 66 slots of #357's exact-cover758-input.json (sha256 ea81d82b...), a = 9409, old primes <= 97, Q = 101..193. Block q has incidence A_q[s,b] = 1 iff (s+b) % q in {0, q-2}, i.e. slot s sits in phases (-s) % q and (-s-2) % q. Weights: #370's integer witness (witness-66.out, as uploaded with #374). Part A (route 5 revision-3 next step, as written): w fixed, R = 2000 seeded draws of one prime block q and one slot pair {i,j}; swap the two slots' phase pairs in block q only; Delta = (sum w - sum_q max_b W(q,b)) / sum w, exact integers. Also the full population of 19 * C(66,2) = 40755 single-block transpositions. Part B (#363's preregistered design): tau*(A) = min over w >= 0, sum w = 1 of sum_q max_b W(q,b), re-optimised per matrix (HiGHS LP), T = 1 - tau*. Identity vs 31 product permutations (one uniform row permutation per prime) read from perms966.json (made by mkperms966.py from os.urandom before any evaluation). Every LP value is bracketed by exact rationals: u from the rationalised primal w (exact capacities), l from the rationalised dual lambda (each block renormalised to sum 1, l = min_s coverage). Sanity: common reverse-row and reverse-phase permutations must reproduce the identity's certificate exactly. Part C (diagnostic, float only): Part A's 2000 draws with w re-optimised (LP). usage: .venv/bin/python align966.py input.json witness-66.out perms966.json [certs966.json] stdout is the artifact (deterministic); nothing timed is printed. """ import json, sys, hashlib, random from fractions import Fraction as F import numpy as np from scipy.optimize import linprog inp, wit, permf = sys.argv[1:4] print("inputs: input.json sha256 %s" % hashlib.sha256(open(inp, 'rb').read()).hexdigest()) print(" witness-66.out sha256 %s" % hashlib.sha256(open(wit, 'rb').read()).hexdigest()) print(" perms966.json sha256 %s" % hashlib.sha256(open(permf, 'rb').read()).hexdigest()) d = json.load(open(inp)) Q = d['Q'] slots = d['slots'][:66] old = [p for p in range(2, 98) if all(p % r for r in range(2, p))] lit = [s for s in range(9409, 13722) if all(s % p not in (0, p - 2) for p in old)] N = len(slots) print("reference: N=%d slots %d..%d; literal survivors of [9409,13722): %d, equal: %s" % (N, slots[0], slots[-1], len(lit), lit == slots)) wl = [l for l in open(wit) if 'w_s x 10^6' in l][0] w = [int(x) for x in wl.split(':', 1)[1].split()] assert len(w) == N W = sum(w) # phase pairs per block: ph[q][i] = ((-s)%q, (-s-2)%q) ph = {q: [((-s) % q, (-s - 2) % q) for s in slots] for q in Q} cnt = {q: {} for q in Q} for q in Q: for a, b in ph[q]: cnt[q][a] = cnt[q].get(a, 0) + 1 cnt[q][b] = cnt[q].get(b, 0) + 1 F1 = N - sum(max(c.values()) for c in cnt.values()) print("unweighted F1 = %d" % F1) def blockmax(pairs, wt): acc = {} for (a, b), x in zip(pairs, wt): acc[a] = acc.get(a, 0) + x acc[b] = acc.get(b, 0) + x return max(acc.values()) M0 = {q: blockmax(ph[q], w) for q in Q} S0 = sum(M0.values()) print("identity: sum w = %d, sum_q max_b W(q,b) = %d, deficit %d, Delta_0 = %s = %.6f" % (W, S0, W - S0, F(W - S0, W), (W - S0) / W)) print("per-prime maxima: " + " ".join("%d:%d" % (q, M0[q]) for q in Q)) # ---------------- Part A print("\n== Part A: fixed witness w, one two-slot transposition in one block") def swapped_delta(q, i, j): p = list(ph[q]) p[i], p[j] = p[j], p[i] return W - (S0 - M0[q] + blockmax(p, w)) # deficit numerator (integer) def summary(tag, nums): a = np.array(nums, dtype=np.int64) d0 = W - S0 lt, eq, gt = int((a < d0).sum()), int((a == d0).sum()), int((a > d0).sum()) mean, sd = a.mean() / W, a.std(ddof=1) / W q05 = np.quantile(a, 0.05) / W med = np.median(a) / W print("%s: n=%d below Delta_0: %d tied: %d above: %d" % (tag, len(a), lt, eq, gt)) print(" ensemble min %.6f 5%% %.6f median %.6f mean %.6f max %.6f sd %.6f" % (a.min() / W, q05, med, mean, a.max() / W, sd)) print(" Delta_0 = %.6f; mid-rank percentile %.4f; (Delta_0-mean)/sd = %s" % (d0 / W, (lt + 0.5 * eq) / len(a), "%.3f" % ((d0 / W - mean) / sd) if sd > 0 else "inf")) print(" preregistered success (Delta_0 < 5%% quantile and effect > 1 sd): %s;" " preregistered failure (Delta_0 >= median): %s" % (d0 / W < q05 and (mean - d0 / W) > sd, d0 / W >= med)) return a rng = random.Random(966) draws = [] for _ in range(2000): q = rng.choice(Q) i, j = rng.sample(range(N), 2) draws.append((q, min(i, j), max(i, j))) A2000 = summary("seeded R=2000 (random.Random(966))", [swapped_delta(*t) for t in draws]) full = [(q, i, j) for q in Q for i in range(N) for j in range(i + 1, N)] Afull = summary("exhaustive 19*C(66,2)", [swapped_delta(*t) for t in full]) up = int((Afull > W - S0).sum()) print(" exhaustive: transpositions that RAISE the deficit: %d of %d; blocks where any does: %s" % (up, len(full), sorted({full[k][0] for k in np.nonzero(Afull > W - S0)[0]}))) # why: phases tied at the block maximum under the optimised w ties = {} for q in Q: acc = {} for (a, b), x in zip(ph[q], w): acc[a] = acc.get(a, 0) + x acc[b] = acc.get(b, 0) + x ties[q] = sum(1 for v in acc.values() if v == M0[q]) print(" phases attaining the block maximum under w (per prime): " + " ".join("%d:%d" % (q, ties[q]) for q in Q)) # ---------------- Part B print("\n== Part B: #363 design, w re-optimised per matrix (LP), exact rational brackets") def lp(pairs_by_q): """pairs_by_q: list over Q of list over slots of (a,b). Returns (tau_float, w, lam).""" rows, keys = [], [] for k, q in enumerate(Q): cls = {} for i, (a, b) in enumerate(pairs_by_q[k]): cls.setdefault(a, set()).add(i) cls.setdefault(b, set()).add(i) for b, S in sorted(cls.items()): r = np.zeros(N + len(Q)) r[list(S)] = 1.0 r[N + k] = -1.0 rows.append(r) keys.append((k, b, S)) c = np.r_[np.zeros(N), np.ones(len(Q))] Aeq = np.r_[np.ones(N), np.zeros(len(Q))][None, :] res = linprog(c, A_ub=np.array(rows), b_ub=np.zeros(len(rows)), A_eq=Aeq, b_eq=[1.0], bounds=[(0, None)] * (N + len(Q)), method='highs') assert res.status == 0 return res.fun, res.x[:N], -res.ineqlin.marginals, keys def brackets(pairs_by_q, wf, lamf, keys, den=10 ** 9): wr = [max(F(x).limit_denominator(den), F(0)) for x in wf] sw = sum(wr) wr = [x / sw for x in wr] u = sum(blockmax(pairs_by_q[k], wr) for k in range(len(Q))) lam = [max(F(x).limit_denominator(den), F(0)) for x in lamf] tot = [F(0)] * len(Q) for (k, b, S), x in zip(keys, lam): tot[k] += x cov = [F(0)] * N for (k, b, S), x in zip(keys, lam): if tot[k] > 0: for i in S: cov[i] += x / tot[k] assert all(t > 0 for t in tot) l = min(cov) return l, u CERTS = [] def evaluate(pairs_by_q, tag=None): tf, wf, lamf, keys = lp(pairs_by_q) l, u = brackets(pairs_by_q, wf, lamf, keys) if tag is not None: den = 10 ** 9 CERTS.append({"matrix": tag, "w": [str(max(F(x).limit_denominator(den), F(0))) for x in wf], "lambda": [[Q[k], b, str(max(F(x).limit_denominator(den), F(0)))] for (k, b, S), x in zip(keys, lamf)], "l": str(l), "u": str(u)}) return tf, l, u ident = [ph[q] for q in Q] t0, l0, u0 = evaluate(ident, 'identity') print("identity: tau*_LP = %.9f exact bracket [%.12f, %.12f] width %.2e T in [%.9f, %.9f]" % (t0, l0, u0, float(u0 - l0), 1 - u0, 1 - l0)) print(" #370 witness value %.9f >= u: %s" % (S0 / W, F(S0, W) >= u0)) # sanity: common reverse-row permutation and reverse-phase relabeling transport witnesses rev = [list(reversed(ph[q])) for q in Q] tr, lr, ur = evaluate(rev) print("sanity common reverse-row: tau*_LP %.9f, |diff| %.1e" % (tr, abs(tr - t0))) revb = [[((q - 1 - a), (q - 1 - b)) for a, b in ph[q]] for q in Q] tb, lb, ub = evaluate(revb) print("sanity reverse-phase: tau*_LP %.9f, |diff| %.1e" % (tb, abs(tb - t0))) # exact transport check of the identity witness under both tfi, wfi, lamfi, keysi = lp(ident) wr = [max(F(x).limit_denominator(10 ** 9), F(0)) for x in wfi] sw = sum(wr) wr = [x / sw for x in wr] u_id = sum(blockmax(ident[k], wr) for k in range(len(Q))) u_rev = sum(blockmax(rev[k], list(reversed(wr))) for k in range(len(Q))) u_rb = sum(blockmax(revb[k], wr) for k in range(len(Q))) print("sanity exact transported u: identity %s, reverse-row %s, reverse-phase %s -> equal: %s" % (float(u_id), float(u_rev), float(u_rb), u_id == u_rev == u_rb)) P = json.load(open(permf)) assert P['Q'] == Q and len(P['controls']) == 31 res = [] for j, ctrl in enumerate(P['controls'], 1): pb = [] for k, q in enumerate(Q): pi = ctrl[str(q)] pb.append([ph[q][pi[i]] for i in range(N)]) # A'_q[s,b] = A_q[pi(s), b] tf, l, u = evaluate(pb, 'control %d' % j) beats = u0 < l # certified T_actual > T_j defeats = u <= l0 # certified T_j >= T_actual res.append((j, tf, l, u, beats, defeats)) print("control %2d: tau*_LP %.9f bracket [%.9f, %.9f] T_j %.6f identity certified better: %s control certified >=: %s" % (j, tf, l, u, 1 - tf, beats, defeats)) nb = sum(r[4] for r in res) nd = sum(r[5] for r in res) nge = sum(1 for r in res if r[1] <= t0) print("summary: identity T = %.6f; controls T_j min %.6f median %.6f max %.6f" % (1 - t0, 1 - max(r[1] for r in res), 1 - float(np.median([r[1] for r in res])), 1 - min(r[1] for r in res))) print(" certified identity > control: %d/31; certified control >= identity: %d/31; unresolved: %d" % (nb, nd, 31 - nb - nd)) print(" preregistered success (T_actual > every T_j, certified): %s; R = (1 + #{T_j >= T_actual})/32 = %d/32 (%s)" % (nb == 31, 1 + nd, "all resolved" if nb + nd == 31 else "UNRESOLVED comparisons present")) if len(sys.argv) > 4: with open(sys.argv[4], 'w', encoding='utf-8', newline='\n') as fh: json.dump({"note": "rational LP witnesses; checker renormalises w to sum 1 and each block's lambda to sum 1", "certificates": CERTS}, fh, separators=(",", ":")) fh.write("\n") # ---------------- Part C print("\n== Part C (diagnostic, float LP): Part A's 2000 draws with w re-optimised") tc = [] for (q, i, j) in draws: k = Q.index(q) pb = list(ident) p = list(ph[q]) p[i], p[j] = p[j], p[i] pb[k] = p tc.append(lp(pb)[0]) tc = np.array(tc) Tc = 1 - tc T0 = 1 - t0 eps = 1e-9 print("re-optimised T over 2000 draws: min %.6f 5%% %.6f median %.6f mean %.6f max %.6f sd %.6f" % (Tc.min(), np.quantile(Tc, .05), np.median(Tc), Tc.mean(), Tc.max(), Tc.std(ddof=1))) print(" identity T %.6f: draws below %d, within 1e-9 %d, above %d; (T0-mean)/sd = %.3f" % (T0, int((Tc < T0 - eps).sum()), int((abs(Tc - T0) <= eps).sum()), int((Tc > T0 + eps).sum()), (T0 - Tc.mean()) / Tc.std(ddof=1)))