#!/usr/bin/env python3 # ============================================================================ # job #1922 -- route 79, stage pursue. # # QUESTION (the route's own open item): which explicit-weight functional of the # T29 gap histogram reproduces each entry of return #161's fold-31 run-spectrum # column (413 380 422 / 7 999 018 / 12 992 / 4), given that 7 999 018 is neither # the weight-1 kill-class occurrence count (8 022 924) nor the producer's own # PAIRS count (8 025 014 = 2*hist(d=0 mod p) + hist(d=+-2 mod p))? # # READING TAKEN FROM THE SERVED PRODUCER research/a3-08-adjacent-pairs.js: # an adjacent-kill pair is a PAIR of consecutive slots of the folded tile that # are both deleted; PAIRS(T,p) = 2*sum_{d=0 (mod p)} hist(d) + sum_{d=+-2 (mod p)} hist(d) # (weight 2 on the p-divisible sizes, because a slot with g = 0 (mod p) is # killed by TWO of the p copies); # the KILL GRAPH has 2D nodes (i,sigma), sigma in {0,-2}, an edge # (i,sigma) -> (i+1,sigma') whenever sigma' - sigma = g_i (mod p), in- and # out-degree <= 1, so its components are PATHS (or cycles) and its EDGES are # exactly the adjacent-kill pairs; "L is the largest component". # So the run spectrum is a component census of the kill graph -- a function of # the ORDER of the gap word, not of its histogram. # # This ledger rebuilds the tiles exactly, verifies the producer's PAIRS formula # against the census edge count, and then (T23 in memory, T29 by a # constant-memory segmented sieve) computes the component census by size and # compares it with #161's published column and with #1018/#1021's numbers. # Integer arithmetic throughout; no sampling. # ============================================================================ import json, sys, time from collections import Counter import numpy as np T0 = time.time() CHECKS = [] PASS = FAIL = 0 def check(name, cond, detail=""): global PASS, FAIL ok = bool(cond) PASS += ok FAIL += (not ok) print(("PASS " if ok else "FAIL ") + name + ((" " + detail) if detail else ""), flush=True) CHECKS.append({"name": name, "pass": ok, "detail": detail}) def note(msg): print(" " + msg, flush=True) # --------------------------------------------------------------- tile build -- def build_tile(x): """Residues a mod P_x with gcd(a(a+2), P_x) = 1 (a odd, a != 0,-2 mod odd q<=x).""" P, res = 2, [1] for q in range(3, x + 1): if any(q % d == 0 for d in range(2, int(q ** 0.5) + 1)): continue new = [] for r in res: for k in range(q): v = r + k * P m = v % q if m != 0 and m != q - 2: new.append(v) P *= q res = new return P, np.array(sorted(res), dtype=np.int64) def gaps_of(res, P): return np.diff(np.concatenate([res, res[:1] + P])).astype(np.int64) # ------------------------------------------------------- kill graph census -- def kill_spec(gaps, p): """Kill-class positions i (g_i = 0, +-2 mod p) and their type: 0 -> g=0, +1 -> +2, -1 -> -2.""" t = gaps % p is_kill = (t == 0) | (t == 2) | (t == p - 2) idx = np.flatnonzero(is_kill).astype(np.int64) if idx.size: tt = t[idx] typ = np.where(tt == 0, 0, np.where(tt == 2, 1, -1)).astype(np.int8) else: typ = np.zeros(0, dtype=np.int8) return idx, typ def census_fast(idx, typ, D): """Component census of the kill graph by O(1)-memory streaming over the kill positions. State (a,b) = lengths of the chains ending at the current level, lanes 0 and -2. Rotate the walk to a level r that is not a kill position (guaranteed: the word repeats, kill density < 1), so no chain crosses the seam of the walk. """ K = idx.size if K == 0: return Counter({1: 2 * D}) d = np.diff(idx) jumps = np.flatnonzero(d > 1) if jumps.size == 0: raise RuntimeError("no non-kill level found; cannot rotate the walk") m = int(jumps[0]) rot_idx = np.concatenate([idx[m + 1:], idx[:m + 1]]) rot_typ = np.concatenate([typ[m + 1:], typ[:m + 1]]) cnt = Counter() def rec(v): cnt[v] += 1 a = b = 1 # state at level r+1 (no predecessor: level r is not a kill level) cur = int(idx[m]) + 1 for q in range(K): pos = int(rot_idx[q]) if pos != cur: # levels cur..pos-1 are non-kill: both chains end at cur rec(a) rec(b) a = b = 1 t = int(rot_typ[q]) if t == 0: # two edges: both lanes continue a, b = a + 1, b + 1 elif t == 1: # edge (-2) -> (0) : lane 0 ends, lane -2 continues into 0 rec(a) a, b = b + 1, 1 else: # edge (0) -> (-2) rec(b) a, b = 1, a + 1 cur = pos + 1 rec(a) # the levels cur..r are non-kill: both chains end rec(b) return cnt def census_bruteforce(gaps, p): """Independent control: union-find over the 2D nodes of the kill graph.""" D = gaps.size t = gaps % p par = np.arange(2 * D, dtype=np.int64) def find(x): while par[x] != x: par[x] = par[par[x]] x = par[x] return x def union(x, y): rx, ry = find(x), find(y) if rx != ry: par[rx] = ry for i in range(D): ti = int(t[i]) nxt = (i + 1) % D # the word is cyclic if ti == 0: union(2 * i + 0, 2 * nxt + 0) union(2 * i + 1, 2 * nxt + 1) elif ti == 2: union(2 * i + 1, 2 * nxt + 0) elif ti == p - 2: union(2 * i + 0, 2 * nxt + 1) roots = {} for v in range(2 * D): r = find(v) roots[r] = roots.get(r, 0) + 1 return Counter(roots.values()) def pairs_formula(gaps, p): """The served producer's PAIRS(T,p): weight 2 on the p-divisible sizes.""" t = gaps % p h0 = int(np.count_nonzero(t == 0)) hm = int(np.count_nonzero(t == 2)) hp = int(np.count_nonzero(t == p - 2)) return 2 * h0 + hm + hp, h0, hm + hp def census_summary(cnt, D, label): """`cnt` holds the chains recorded during the walk (lengths >= 2 all of them, plus the 1-chains that terminate at the walk's own jump points). The true number of size-1 components follows by counting nodes: 2D = n1 + sum_{L>=2} L*n_L.""" big = {L: n for L, n in cnt.items() if L > 1} n1 = 2 * D - sum(L * n for L, n in big.items()) edges = sum((L - 1) * n for L, n in big.items()) nodes = n1 + sum(L * n for L, n in big.items()) ch = sum(big.values()) + n1 # every size-1 component is one chain note(f"{label}: nodes={nodes} (=2D {2*D}) edges={edges} chains={ch} " f"n1={n1} " + " ".join(f"n{L}={big[L]}" for L in sorted(big))) return n1, edges, nodes, big # ==================================================================== main === def main(): out = {} # ---- 1. exact tiles ----------------------------------------------------- tiles = {} for x in (13, 17, 19, 23): P, res = build_tile(x) g = gaps_of(res, P) D = res.size tiles[x] = (P, res, g) note(f"T{x}: D={D} P={P} gaps sum={int(g.sum())} min={int(g.min())} max={int(g.max())} " f"distinct={len(np.unique(g))} all6={bool(np.all(g % 6 == 0))}") check("tiles rebuild: D(T_x) = prod(q-2) at x = 13/17/19/23", [int(tiles[x][2].size) for x in (13, 17, 19, 23)] == [1485, 22275, 378675, 7952175]) check("tiles: sum(gaps) = P_x and every gap is a positive multiple of 6", all(int(tiles[x][2].sum()) == tiles[x][0] and bool(np.all(tiles[x][2] % 6 == 0)) and int(tiles[x][2].min()) == 6 for x in (13, 17, 19, 23))) check("tiles: G2(T_x) = 66/108/150/204 (A144311 + 1)", [int(tiles[x][2].max()) for x in (13, 17, 19, 23)] == [66, 108, 150, 204]) # ---- 2. census validated against brute force on the small tiles -------- for (x, p) in ((17, 19), (19, 23)): P, res, g = tiles[x] idx, typ = kill_spec(g, p) cf = census_fast(idx, typ, g.size) cb = census_bruteforce(g, p) bigf = {L: n for L, n in cf.items() if L > 1} bigb = {L: n for L, n in cb.items() if L > 1} n1f = 2 * g.size - sum(L * n for L, n in bigf.items()) check(f"census method (streaming) == union-find control at T{x}/p={p}", bigf == bigb and n1f == cb.get(1, 0), f"fast n1={n1f} brute n1={cb.get(1,0)} Lmax={max(list(bigf)+[1])} " f"n2={bigf.get(2)} n3={bigf.get(3)}") # ---- 3. T23: producer PAIRS formula vs census edge count -------------- P23, res23, g23 = tiles[23] D23 = g23.size t23 = {} for p in (29, 31, 37): idx, typ = kill_spec(g23, p) cf = census_fast(idx, typ, D23) n1, edges, nodes, big = census_summary(cf, D23, f"T23/p={p}") pf, h0, hpm = pairs_formula(g23, p) # weight-1 count: the number of kill-class gap OCCURRENCES (the set of kill values has weight 1) t = g23 % p w1 = int(np.count_nonzero((t == 0) | (t == 2) | (t == p - 2))) vals = sorted(set(int(v) for v in g23[np.isin(t, [0, 2, p - 2])])) t23[p] = {"n1": n1, "edges": edges, "nodes": nodes, "pairs_formula": pf, "h0": h0, "h_pm2": hpm, "w1": w1, "values": vals, "census": {int(k): int(v) for k, v in big.items()}, "maxcomp": max(big)} note(f"T23/p={p}: PAIRS formula={pf} (2*{h0}+{hpm}) census edges={edges} " f"weight1={w1} kill values={vals}") check(f"T23/p={p}: producer PAIRS formula == kill-graph edge count", pf == edges and nodes == 2 * D23) check("T23/p=29: weight-1 kill-class occurrence count = 243 816 (return #1018's A)", t23[29]["w1"] == 243816, f"got {t23[29]['w1']}") check("T23/p=31: weight-1 kill-class occurrence count = 248 058 (return #1018's A)", t23[31]["w1"] == 248058, f"got {t23[31]['w1']}") check("T23/p=29: producer PAIRS = 243 822 = #1018 A + hist(174) (the g=0 weight-2 term)", t23[29]["pairs_formula"] == 243822 and t23[29]["h0"] == 6, f"PAIRS={t23[29]['pairs_formula']} hist(g=0 mod 29)={t23[29]['h0']}") check("T23/p=31: producer PAIRS = 248 078 = #1018 A + hist(186)", t23[31]["pairs_formula"] == 248078 and t23[31]["h0"] == 20, f"PAIRS={t23[31]['pairs_formula']} hist(g=0 mod 31)={t23[31]['h0']}") # ---- 4. the T19-by-23 'runs-of-3' figure ------------------------------ P19, res19, g19 = tiles[19] D19 = g19.size idx19, typ19 = kill_spec(g19, 23) c19 = census_fast(idx19, typ19, D19) c19b = census_bruteforce(g19, 23) n1, edges, nodes, big19 = census_summary(c19, D19, "T19/p=23") check("T19/p=23: census agrees with union-find and PAIRS formula", big19 == {L: n for L, n in c19b.items() if L > 1} and edges == pairs_formula(g19, 23)[0] and n1 == c19b.get(1, 0), f"edges={edges} PAIRS={pairs_formula(g19,23)[0]} n1={n1} brute_n1={c19b.get(1,0)}") # doubled word (the job1634 tile constructor's P = 4*primorial = two copies) g19d = np.concatenate([g19, g19]) idxd, typd = kill_spec(g19d, 23) cd = census_fast(idxd, typd, 2 * D19) bigd = {L: n for L, n in cd.items() if L > 1} note("T19/p=23 doubled word chains: " + str({int(k): int(v) for k, v in sorted(bigd.items())})) check("T19/p=23: n_3 = 62 components of size 3 (the published 'runs-of-3 = 62')", big19.get(3) == 62, f"got n_3={big19.get(3)} census={dict(sorted(big19.items()))} n1={n1}") check("T19/p=23: the DOUBLED word gives exactly 2x every component size >= 2 (124 for n_3)", all(int(bigd[k]) == 2 * int(v) for k, v in big19.items()), f"doubled n_2={bigd.get(2)} n_3={bigd.get(3)} (gotcha 62's 124-vs-62 trap)") # ---- 5. the T29 gap word by constant-memory segmented sieve ----------- PRIMES29 = (3, 5, 7, 11, 13, 17, 19, 23, 29) P29 = 1 for q in (2,) + PRIMES29: P29 *= q CHUNK = 1 << 24 hist = np.zeros(4096, dtype=np.int64) # gap values are <= G2 << 4096 idxs, typs = [], [] off = 0 prev = first = None total_gaps = 0 sum_gaps = 0 nres = 0 t_sieve = time.time() for start in range(0, P29, CHUNK): n = min(CHUNK, P29 - start) arr = np.ones(n, dtype=bool) for q in PRIMES29: arr[(-start) % q:: q] = False arr[(q - 2 - start) % q:: q] = False arr[(1 - (start & 1)) % 2::2] = False j = np.flatnonzero(arr) if j.size == 0: continue rr = (start + j).astype(np.int64) nres += rr.size if first is None: first = int(rr[0]) if prev is None: d = np.diff(rr) # the gap before rr[0] is the wrap gap, appended last else: d = np.empty(rr.size, dtype=np.int64) d[0] = rr[0] - prev d[1:] = np.diff(rr) total_gaps += d.size sum_gaps += int(d.sum()) hist += np.bincount(d, minlength=hist.size)[:hist.size] # kill positions at every fold of interest, in one pass idxs.append({}) typs.append({}) for p in (29, 31, 37): t = d % p m = (t == 0) | (t == 2) | (t == p - 2) ki = np.flatnonzero(m).astype(np.int64) + off idxs[-1][p] = ki tt = t[ki - off] typs[-1][p] = np.where(tt == 0, 0, np.where(tt == 2, 1, -1)).astype(np.int8) prev = int(rr[-1]) off += d.size wrap = P29 + first - prev # completes the cyclic gap word (a rotation) hist[wrap] += 1 sum_gaps += wrap total_gaps += 1 N_gaps = total_gaps # stdout is the artifact and must reproduce byte for byte; timings go to stderr only (server file # note on return #1023 cleared by this correction). note(f"T29 sieve: residues={nres} gaps={total_gaps} sum={sum_gaps} wrap={wrap}") print(f" (sieve wall {time.time()-t_sieve:.1f}s -> stderr)", file=sys.stderr, flush=True) check(" T29: D(T29) = 214 708 725 = 29*D(T23) - 2*D(T23)", nres == 214708725 == 29 * 7952175 - 2 * 7952175, f"got {nres}") check("T29: sum of all 214 708 725 gaps = P29 = 6 469 693 230", sum_gaps == P29 and N_gaps == nres, f"gaps={N_gaps} sum={sum_gaps}") check("T29: every gap is a positive multiple of 6 and max gap G2(T29) = 258", bool(np.all(np.nonzero(hist)[0] % 6 == 0)) and int(np.max(np.nonzero(hist)[0])) == 258, f"max={int(np.max(np.nonzero(hist)[0]))} min={int(np.min(np.nonzero(hist)[0]))}") nz = np.nonzero(hist)[0] check("T29: 41 distinct gap values (return #1021)", len(nz) == 41, f"got {len(nz)}") hv = {int(v): int(hist[v]) for v in nz} note("T29 kill-class multiplicities at p=31 " + str({d: hv.get(d, 0) for d in (60, 126, 186, 246)})) check("T29/p=31: multiplicities of {60,126,186,246} = 7 815 766 / 205 068 / 2 090 / 0 (#1021)", [hv.get(d, 0) for d in (60, 126, 186, 246)] == [7815766, 205068, 2090, 0], str([hv.get(d, 0) for d in (60, 126, 186, 246)])) t29 = {} for p in (31, 29, 37): idx = np.concatenate([c[p] for c in idxs]) typ = np.concatenate([c[p] for c in typs]) cf = census_fast(idx, typ, nres) n1, edges, nodes, big = census_summary(cf, nres, f"T29/p={p}") pairs = 2 * sum(hv.get(d, 0) for d in nz if d % p == 0) + \ sum(hv.get(d, 0) for d in nz if d % p in (2, p - 2)) w1 = sum(hv.get(d, 0) for d in nz if d % p in (0, 2, p - 2)) t29[p] = {"n1": n1, "edges": edges, "nodes": nodes, "pairs": pairs, "w1": w1, "census": {int(k): int(v) for k, v in big.items()}, "maxcomp": max(big)} check(f"T29/p={p}: PAIRS formula == census edge count == {pairs}", pairs == edges and nodes == 2 * nres, f"w1={w1}") check("T29/p=31: producer PAIRS = 8 025 014 (return #1016's decider, resolved)", t29[31]["pairs"] == 8025014, f"got {t29[31]['pairs']}") check("T29/p=31: weight-1 kill-class occurrence count = 8 022 924 (= 8 025 014 - hist(186))", t29[31]["w1"] == 8022924 and hv.get(186) == 2090, f"got {t29[31]['w1']}") col = [t29[31]["n1"], t29[31]["census"].get(2), t29[31]["census"].get(3), t29[31]["census"].get(4)] note("T29/p=31 column measured: " + str(col)) check("#161's fold-31 column = the kill-graph component census by size: " "413 380 422 / 7 999 018 / 12 992 / 4", col == [413380422, 7999018, 12992, 4], f"got {col}") check("T29/p=31: no component of size >= 5 (the alternation lemma's ceiling)", max(t29[31]["census"]) == 4, f"max size {max(t29[31]['census'])}") check("T29/p=31: the column is NOT a gap-histogram functional " "(n_2 = 7 999 018 != the weight-1 or the weight-2 gap count)", t29[31]["census"].get(2) not in (t29[31]["w1"], t29[31]["pairs"])) out = {"t23": t23, "t19_census": {int(k): int(v) for k, v in sorted(big19.items())}, "t19_n1": n1, "t29_census": t29, "t29_hist": {str(k): v for k, v in hv.items()}, "checks": CHECKS, "pass": PASS, "fail": FAIL} with open("job1922-result.json", "w", encoding="utf-8") as f: json.dump(out, f, indent=1, sort_keys=True) print(f"ALL_PASS={FAIL == 0} ({PASS} pass / {FAIL} fail)", flush=True) print(f"ledger wall {time.time()-T0:.1f}s -> stderr", file=sys.stderr, flush=True) if __name__ == "__main__": main()