#!/usr/bin/env python3 # -*- coding: utf-8 -*- """The refined transport sum's truncation length, at every fold #159 actually ran. Question (registered as the next step of return #669): the alternation-refined sum Q_L^alt(theta) = #{i : G_{L+1}(i) >= theta and the L-1 interior slots of the window lie in a common translate of K = {0, q-2} mod q} is truncated: what is the largest L with a non-zero term, and is it #161's ANCHORED ladder L_anch(T_x, q) or L_anch + 1? Objects, each computed exactly on the old word of the fold: L_anch longest cyclic run of consecutive slots with residue in K = {0, q-2} (this is #161's "brief says" column, per the diagonal check in #669); L_free longest cyclic run of consecutive slots with residue in a translate {a, a-2} mod q, maximised over a (the FREE translate); L_star the largest L with a non-zero Q_L^alt term, taken from the producer's own loop (#159 src/analyze.c, the histQa block) transcribed literally, with reach = 3 at entry and the loop breaking only on a non-qualifying interior gap class -- the EXISTENTIAL reading, which is the one that reproduces #159's published numbers (#669 section C); L_loose the same for the loose form (qualifying interior gaps only). Gates, all against #159's own printed figures: G1 D(T_x) for x = 5..23 against the census; G2 D(T_q) after the fold against #159's per-fold table; G3 G2(new) = max gap of the folded word against the same table; G4 the 19 -> 23 control: L_anch = 3, alt spectra at L = 2, 3, and max alt N_new/RHS reproducing #159's 0.9180. Folds are #159's own list (report section "Per fold"): 13->17, 17->19, 19->23, 23->29, 23->31, 23->37, 31->37, 37->41. The first six have enumerable old words (T_x with x <= 23); the last two do not (T_31 = 6.2e9 slots, T_37 = 2.2e11) and are handled by the streaming companion, not here. Usage: python truncation-ladder.py """ import json import sys import time import numpy as np P_ALL = [2, 3, 5, 7, 11, 13, 17, 19, 23] CENSUS = {5: 3, 7: 15, 11: 135, 13: 1485, 17: 22275, 19: 378675, 23: 7952175} # #159's per-fold table: fold -> (D(old), G2(new), certificate) T159 = { (13, 17): (22275, 108, 108), (17, 19): (378675, 150, 150), (19, 23): (7952175, 204, 204), (23, 29): (7952175, 258, 270), (23, 31): (7952175, 258, 270), (23, 37): (7952175, 240, 240), } MAXRUN = 24 # #159's src/tct.h hard cap on L def primorial(x): m = 1 for q in P_ALL: if q <= x: m *= q return m def tile(x): """T_x as a sorted slot array; W = x#.""" W = primorial(x) cp = np.ones(W + 2, dtype=bool) for p in [v for v in P_ALL if v <= x]: cp[0::p] = False return W, np.nonzero(cp[:W] & cp[2:W + 2])[0].astype(np.int64) def cyclic_gaps(A, W): g = np.empty(A.size, dtype=np.int64) g[:-1] = np.diff(A) g[-1] = A[0] + W - A[-1] return g def longest_cyclic_run(flag): """Longest cyclic run of True, and the run-length spectrum. Vectorised: roll so that index 0 is False, then the runs are the gaps between consecutive Falses.""" n = flag.size if not flag.any(): return 0, {} if flag.all(): return n, {n: n} z = int(np.nonzero(~flag)[0][0]) r = np.roll(flag, -z) brk = np.nonzero(~r)[0] lens = np.diff(brk) - 1 lens = lens[lens > 0] if lens.size == 0: return 0, {} vals, cts = np.unique(lens, return_counts=True) return int(lens.max()), {int(v): int(c) for v, c in zip(vals, cts)} def ladders(r, q): """Anchored (+spectrum) and free ladders of the residue word r mod q.""" K = (r == 0) | (r == q - 2) La, spec_a = longest_cyclic_run(K) best_a, Lf, spec_f = None, 0, {} for a in range(q): hit = (r == a) | (r == (a - 2) % q) L, spec = longest_cyclic_run(hit) if L > Lf: best_a, Lf, spec_f = a, L, spec return La, spec_a, Lf, best_a, spec_f def producer_terms(g, q, maxrun=MAXRUN): """#159 src/analyze.c, the histQl/histQa block, transcribed literally. b0 = G(0); s6 = b0 + G(1) is the L = 1 window (both loose and alt count it). Then L = 2, reach = 3, and each step reads mi = G(L-1) mod q; the loop BREAKS on a non-qualifying mi. The alt term is counted iff the new reach is non-zero. Returns per-level non-zero counts, and the loose/alt maxima. The old word is cyclic: G(m) reads g[(i+m) % D]. """ D = g.size ext = np.concatenate([g, g[:maxrun + 2]]) loose = np.ones(D, dtype=bool) # L = 1: the loop has not broken yet reach = np.full(D, 3, dtype=np.int64) # bit 1 = state 0 reachable, bit 2 = q-2 counts_loose = {1: int(D)} counts_alt = {1: int(D)} # L = 1 is counted by histQa as well max_loose, max_alt = 1, 1 for L in range(2, maxrun + 1): mi = ((ext[L - 1:L - 1 + D]) % q).astype(np.int64) ok = (mi == 0) | (mi == 2) | (mi == q - 2) # the producer's loop breaks on a non-qualifying interior gap, so a window # that has broken keeps no term at any higher level either. loose = loose & ok # NB the parens: `reach & 1 == 1` parses as `reach & (1 == 1)` -- the same # int-vs-bool narrowing defect that #669 caught in the numpy instrument. nxt = np.zeros(D, dtype=np.int64) nxt |= np.where(((reach & 1) == 1) & (mi == q - 2), 2, 0) nxt |= np.where(((reach & 2) == 2) & (mi == 2), 1, 0) nxt |= np.where(mi == 0, reach, 0) reach = nxt alt = loose & (reach != 0) counts_loose[L] = int(loose.sum()) counts_alt[L] = int(alt.sum()) if counts_loose[L]: max_loose = L if counts_alt[L]: max_alt = L return counts_loose, counts_alt, max_loose, max_alt def scalar_Lstar(g, q, maxrun=MAXRUN): """The producer's loop in scalar arithmetic, as a blocking gate on the vector one.""" D = g.size ext = np.concatenate([g, g[:maxrun + 2]]) maxL = 0 for i in range(D): reach, L = 3, 2 while True: mi = int(ext[i + L - 1]) % q if not (mi == 0 or mi == 2 or mi == q - 2): break if mi == 0: nr = reach elif mi == 2: nr = 1 if (reach & 2) else 0 else: nr = 2 if (reach & 1) else 0 if nr: maxL = max(maxL, L) reach = nr L += 1 if L > maxrun: break return maxL def main(out_path): res = {"tool": "trunc-capladder/truncation-ladder.py", "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} tiles = {} res["G1_census"] = {} for x in (5, 7, 11, 13, 17, 19, 23): W, A = tile(x) tiles[x] = (W, A) res["G1_census"][str(x)] = {"computed": int(A.size), "published": CENSUS[x], "agrees": bool(A.size == CENSUS[x])} rows = [] g2 = {} g3 = {} for (x, q) in sorted(T159): W, A = tiles[x] D_new = int(A.size) * (q - 2) r = (A % q).astype(np.int64) g = cyclic_gaps(A, W) La, spec_a, Lf, best_a, spec_f = ladders(r, q) cl, ca, max_loose, max_alt = producer_terms(g, q) Lscalar = scalar_Lstar(g, q) if A.size <= 400000 else None dold, gnew, cert = T159[(x, q)] res.setdefault("G2_Dold", {})["T%d_by_%d" % (x, q)] = { "computed": int(A.size), "published": dold, "agrees": bool(A.size == dold)} res.setdefault("G3_Dnew_and_G2new", {})["T%d_by_%d" % (x, q)] = { "D_new_computed": D_new, "G2_new_computed": int(g.max()), "G2_new_published": gnew, "agrees": bool(int(g.max()) == gnew)} rows.append({ "fold": "T%d by %d" % (x, q), "x": x, "q": q, "D_old": int(A.size), "D_new": D_new, "G2_new": int(g.max()), "L_anch": La, "L_free": Lf, "free_translate_a": best_a, "L_star_alt": max_alt, "L_star_alt_scalar": Lscalar, "L_star_loose": max_loose, "alt_counts_by_L": {str(k): v for k, v in ca.items() if v}, "loose_counts_by_L": {str(k): v for k, v in cl.items() if v}, "anchored_run_spectrum": {str(k): v for k, v in spec_a.items()}, "free_run_spectrum_best_a": {str(k): v for k, v in spec_f.items()}, "alt_equals_anch": bool(max_alt == La), "alt_equals_anch_plus_1": bool(max_alt == La + 1), "alt_equals_free": bool(max_alt == Lf), }) res["TABLE"] = rows res["G4_gate_vector_vs_scalar_Lstar"] = { row["fold"]: {"vector": row["L_star_alt"], "scalar": row["L_star_alt_scalar"], "agree": (None if row["L_star_alt_scalar"] is None else bool(row["L_star_alt"] == row["L_star_alt_scalar"]))} for row in rows} res["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) with open(out_path, "w", encoding="utf-8", newline="\n") as fh: json.dump(res, fh, indent=1, sort_keys=True, default=str) fh.write("\n") print(json.dumps(res, indent=1, sort_keys=True, default=str)) return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "truncation-ladder.json"))