#!/usr/bin/env python3 """Exact two-class covering-run / maxsum engine (index-space formulation). Object (route 56, the producer `attack-0829n-doubling-bridge.js` convention): P = s# (primorial), the level-s tile modulus A = { r in [0,P) : gcd(r,P)=gcd(r+2,P)=1 } (|A| = D_s = prod_{3<=p<=s}(p-2)) Q = the entering primes (s < q <= 2s] M = P * prod(Q) (period of the walk) a slot is a level-s tile slot, i.e. an integer r + i*P with r in A and i in [0, prod Q); a slot is KILLED iff (r + i*P) % q == 0 or (r + i*P) % q == q-2 for some q in Q; the walk enumerates the level-2s admissible integers v = r + i*P, r in A, i in [0, prod Q), in increasing order (the admissible-index space), and K*(s) = longest run of consecutive KILLED slots in that sequence maxsum_m(T_s) = max over windows of m consecutive slots (cyclically, period M) of (number of killed slots in the window) Ghat(s) = G2(P(s)#) = longest gap between consecutive level-s admissible slots msc(s) = maxsum_{K*+1}(T_s) / Ghat(s) (the producer's `msc`) gbar(s) = P / |A| (tile mean gap) rho(s, m) = maxsum_m(T_s) / (m * gbar(s)) (thick-ground factor) Why the index space is the right space: every admissible integer of the walk lies in [0, M), so the walk is a linear scan of the killed flags at the |A| * prod(Q) admissible integers. The producer iterates the same objects but visits all M slot positions (P * prod(Q)); the index space is smaller by the factor P/|A| = gbar(s) (13.8x at s = 13, 25.6x at s = 19) and it is what makes the s = 19 rung reachable. The engine never materialises a length-M array; it walks a chunk of copies at a time and keeps only running state (longest run, maxsum histogram modulo m, counts). """ import numpy as np from math import gcd def primes_upto(n): out = [] for k in range(2, n + 1): if all(k % p for p in out if p * p <= k): out.append(k) return out def primorial(ps): m = 1 for p in ps: m *= p return m def small_primes(n): return [p for p in primes_upto(n) if p <= n] def prime_factors(n): out, d = [], 2 while d * d <= n: if n % d == 0: out.append(d) while n % d == 0: n //= d d += 1 if n > 1: out.append(n) return out def admissible(P): """Residues r in [0,P) with gcd(r,P)=gcd(r+2,P)=1, ascending, as int64.""" r = np.arange(P, dtype=np.int64) ok = np.ones(P, dtype=bool) for p in prime_factors(P): # exactly the prime factors of the tile modulus ok &= (r % p) != 0 ok &= (r % p) != (p - 2) % p return r[ok] def _runs(flags): """Runs of True in a 1-D bool array: (start, length) arrays.""" if not flags.any(): return np.empty(0, dtype=np.int64), np.empty(0, dtype=np.int64) f = flags.astype(np.int8) d = np.diff(f) starts = np.flatnonzero(d == 1) + 1 ends = np.flatnonzero(d == -1) + 1 if f[0]: starts = np.concatenate(([0], starts)) if f[-1]: ends = np.concatenate((ends, [f.size])) n = min(starts.size, ends.size) starts, ends = starts[:n], ends[:n] return starts, ends - starts def exact_walk(P, Q, m_list=(), chunk_copies=512, max_run_stop=None, verbose=False): """Exact (K*, {m: maxsum_m}, |A|, copies walked) over the admissible-index space. P: tile modulus (s#); Q: the entering primes; m_list: window sizes for maxsum. max_run_stop: stop the run search once a run of this length is found. Returns a dict; `complete` says whether the full period was walked. """ Q = sorted(Q) A = admissible(P) nA = int(A.size) cQ = 1 for q in Q: cQ *= q M = P * cQ nhist = {m: np.zeros(m, dtype=np.int64) for m in m_list} longest = 0 run_prev = 0 # trailing run length carried across a chunk boundary total_dead = 0 copies_done = 0 complete = True while copies_done < cQ: c = min(chunk_copies, cQ - copies_done) ii = np.arange(copies_done, copies_done + c, dtype=np.int64) v2d = A[None, :] + ii[:, None] * P cnt = np.zeros((c, nA), dtype=np.uint8) for q in Q: t = v2d % q cnt += ((t == 0) | (t == (q - 2) % q)) dead = (cnt > 0).reshape(-1) total_dead += int(dead.sum()) if m_list: loc = np.flatnonzero(dead).astype(np.int64) if loc.size: for m in m_list: idx = (loc + copies_done * nA) % m nhist[m] += np.bincount(idx, minlength=m) starts, lens = _runs(dead) if starts.size: if starts[0] == 0 and run_prev: cand = run_prev + int(lens[0]) if cand > longest: longest = cand rest = lens[1:] else: rest = lens if rest.size: mx = int(rest.max()) if mx > longest: longest = mx if dead[-1]: nz = np.flatnonzero(~dead) run_prev = int(dead.size - 1 - nz[-1]) if nz.size else int(dead.size) else: run_prev = 0 copies_done += c if verbose and copies_done % (chunk_copies * 100) == 0: print(" copies %d/%d longest=%d dead=%d" % (copies_done, cQ, longest, total_dead), flush=True) if max_run_stop is not None and longest >= max_run_stop: complete = copies_done >= cQ break return {"P": P, "Q": Q, "nA": nA, "M": M, "K": longest, "maxsum": {m: int(nhist[m].max()) * m for m in m_list}, "total_dead": total_dead, "copies_walked": copies_done, "copies_total": cQ, "complete": complete} def brute_run(P, Q, limit=None, verbose=False): """Independent slow reference: natural (increasing) order of the walk. The walk enumerates the admissible integers v in [0, P*prod(Q)) in increasing order, not the (r, copy) index space; this reference scans that order directly and is the calibration for the fast engines. """ cQ = 1 for q in Q: cQ *= q M = P * cQ longest = 0 run = 0 for v in range(M): adm = gcd(v, P) == 1 and gcd(v + 2, P) == 1 if not adm: continue killed = any(v % q == 0 or v % q == (q - 2) % q for q in Q) if killed: run += 1 if run > longest: longest = run if limit and longest >= limit: return longest else: run = 0 return longest def walk_index_periodic(P, Q, m_list=(), verbose=False, max_run_stop=None): """Wrong-in-general shortcut kept ONLY as a cross-check hook: it treats the dead pattern of one tile copy as cyclic and misses runs that cross a copy boundary (it reports 4 instead of 8 at s = 13). Not used for results.""" raise NotImplementedError("superseded by exact_walk / maxsum_columns") def walk_gap_maxsum(P, Q, m, verbose=False): """Exact maxsum_m(T_s) = largest sum of m cyclically consecutive level-s gaps over the level-2s walk (producer convention, producer line 176). The walk is the increasing sequence of admissible integers L[j + c*nA] = A[j] + c*P, j in [0,nA), c in [0,R), nA = |A|, R = prod Q, of length N = nA*R. A window of m consecutive gaps starts at L[u] and ends at L[u+m] (indices cyclic mod N), so maxsum_m = max over u in [0,N) of (L[(u+m) mod N] (+N if it wrapped) - L[u]). Write m = qq*nA + rr (0 <= rr < nA) and index the start by (c, j). The end is at copy c+qq (+1 when j+rr >= nA) and column (j+rr) mod nA; the span is affine in qq, so the extreme admissibly-wrapping start dominates, giving a closed form. """ A = admissible(P) nA = int(A.size) R = 1 for q in Q: R *= q N = nA * R m = int(m) if m <= 0 or N == 0: return 0 if m >= N: full, rem = divmod(m, N) return full * N + walk_gap_maxsum(P, Q, rem) if rem else full * N idx = np.arange(nA, dtype=np.int64) # linear endpoint index s = idx + m; value L[u] = A[u mod nA] + P*(u // nA) s = idx + m span = A[s % nA] + P * (s // nA) - A[idx] return int(span.max()) def maxsum_columns(P, Q, m_list=(), q_batch=16, verbose=False): """Exact maxsum_m(T_s) for each m in m_list (producer convention).""" return {m: walk_gap_maxsum(P, Q, m, verbose=verbose) for m in m_list} def _kill_tables(P, Q, A): """Per-prime residue table: vals_q[j] = A[j] mod q (device-resident). Killed columns at copy offset z = c*P mod q are those with vals_q[j] in {(-z) mod q, (-z-2) mod q}; the (copies x columns) mask is then two broadcast scalar comparisons per prime per chunk -- the form a GPU likes. """ return {q: np.asarray(A % q, dtype=np.int64) for q in Q} def _kill_mask(npu, tab, Q, P, cc, nA): """(len(cc), nA) bool kill mask; works on numpy or cupy arrays.""" c = int(cc.size) dead = npu.zeros((c, nA), dtype=npu.bool_) for q in Q: vals = npu.asarray(tab[q]) z = ((cc % q) * (P % q)) % q for shift in (0, 2): tgt = (-z - shift) % q dead |= (vals[None, :] == tgt[:, None]) return dead def _seg_arange(n, npu=np): """Concatenated [0..n_i) for a segment-length vector, vectorised.""" n = npu.asarray(n) total = int(n.sum()) if total == 0: return npu.zeros(0, dtype=npu.int64) x = npu.arange(total, dtype=npu.int64) x -= npu.repeat(npu.cumsum(n, dtype=npu.int64) - n, n) return x def run_walk(P, Q, max_run_stop=None, chunk_copies=512, verbose=False, npu=None, q_last=()): """Exact K*(s) over the walk, chunk-vectorised. Traversal order: flattened (copy c, column j) for c in the chunk, j in [0,nA) -- which is exactly increasing v = A[j] + c*P, so consecutive flat indices are consecutive admissible integers and runs are runs of True in that flat order. """ npu = npu or np Q = sorted(Q) A = admissible(P) nA = int(A.size) R = 1 for q in Q: R *= q tab = _kill_tables(P, Q, A) longest = 0 run_prev = 0 c0 = 0 while c0 < R: c = min(chunk_copies, R - c0) cc = npu.arange(c0, c0 + c, dtype=npu.int64) dead = _kill_mask(npu, tab, Q, P, cc, nA) flat = dead.reshape(-1) if npu is not np: flat = npu.asnumpy(flat) starts, lens = _runs(flat) if starts.size: if starts[0] == 0 and run_prev: longest = max(longest, run_prev + int(lens[0])) rest = lens[1:] else: rest = lens if rest.size: longest = max(longest, int(rest.max())) if flat[-1]: nz = np.flatnonzero(~flat) run_prev = int(flat.size - 1 - nz[-1]) if nz.size else int(flat.size) else: run_prev = 0 c0 += c if verbose and (c0 % (chunk_copies * 2000) == 0): print(" copies %d/%d longest=%d" % (c0, R, longest), flush=True) if max_run_stop is not None and longest >= max_run_stop: return {"K": longest, "complete": False, "copies_walked": c0} return {"K": longest, "complete": True, "copies_walked": R} def longest_run_columns(P, Q, max_run_stop=None, col_batch=16, verbose=False): """Exact K*(s): longest run of consecutive killed slots. A run of consecutive killed slots is a set of dead values v, v+1, ..., v+L-1 that are consecutive ADMISSIBLE integers; because no two admissible integers are adjacent (all are odd), v+i must itself be admissible for every i, i.e. each is the successor of the previous one. So a run is a chain (j_0, c_0) -> (j_1, c_1) -> ... with either c_{i+1} = c_i and j_{i+1} = j_i + 1 (intra-copy step), or c_{i+1} = c_i + 1 and j_i = nA - 1, j_{i+1} = 0 (copy frontier step). The longest such chain is found by a DP over the columns j, carrying the run length of the last element of each copy. This is a 2-D chain, not a 1-D run in the (j + c*nA) index space. """ Q = sorted(Q) A = admissible(P) nA = int(A.size) R = 1 for q in Q: R *= q cm = np.arange(R, dtype=np.int64) # dead[c] per column, precomputed deadcol = [] for j in range(nA): d = np.zeros(R, dtype=bool) for q in Q: t = (A[j] + cm * (P % q)) % q d |= (t == 0) | (t == (q - 2) % q) deadcol.append(d) prev = np.zeros(R, dtype=np.int64) longest = 0 for _ in range(nA): # cyclic pass; the map saturates after <= nA passes newlongest = longest for j in range(nA): dead = deadcol[j] if j == 0: # frontier: (nA-1, c) -> (0, c+1); plus the wrap (nA-1, R-1) -> (0, 0) from_prev_col = np.where(dead, np.roll(prev, 1) + 1, 0) from_prev_col[0] = max(from_prev_col[0], (prev[-1] + 1) if dead[0] else 0) prev = from_prev_col else: prev = np.where(dead, prev + 1, 0) m = int(prev.max()) if prev.size else 0 if m > newlongest: newlongest = m if newlongest == longest: break longest = newlongest return longest, nA, nA def longest_run(P, Q, max_run_stop=None, chunk_copies=64, verbose=False): """Exact K*(s) as the longest run of consecutive killed slots in index space. Early exit: with max_run_stop = N+1 a completed return of N proves K* = N. """ Q = sorted(Q) A = admissible(P) nA = int(A.size) R = 1 for q in Q: R *= q longest = 0 run_prev = 0 c0 = 0 while c0 < R: c = min(chunk_copies, R - c0) ii = np.arange(c0, c0 + c, dtype=np.int64) v = A[None, :] + ii[:, None] * P cnt = np.zeros(v.shape, dtype=np.uint8) for q in Q: t = v % q cnt += ((t == 0) | (t == (q - 2) % q)) dead = (cnt > 0).reshape(-1) starts, lens = _runs(dead) if starts.size: if starts[0] == 0 and run_prev: longest = max(longest, run_prev + int(lens[0])) rest = lens[1:] else: rest = lens if rest.size: longest = max(longest, int(rest.max())) if dead[-1]: nz = np.flatnonzero(~dead) run_prev = int(dead.size - 1 - nz[-1]) if nz.size else int(dead.size) else: run_prev = 0 c0 += c if verbose and c0 % (chunk_copies * 500) == 0: print(" copies %d/%d longest=%d" % (c0, R, longest), flush=True) if max_run_stop is not None and longest >= max_run_stop: return longest, c0, R return longest, R, R