#!/usr/bin/env python3 """job 2732 / return #1365's corrected next step -- BOUND THE KILLER MARGINAL. Object (route 112, its own definitions, as built and gated in #1365): marg(P,q,R) = K*(P, R u {q}) - K*(P,R), with T_P slots = residues r with gcd(r,P)=gcd(r+2,P)=1, period Mp = P*prod(R)*q, x killed iff x = 0 or -2 (mod s) for some s in the killer set, and K* the maximal cyclic run of consecutive killed slots. By the theorem shipped in #1365 (one induction on route 98's proven (i)) a chain step obeys K*(P*q_1*...*q_k, R) <= K*(P, R u {q_1..q_k}), so an upper bound on this marginal IS an upper bound on the chain step. WHY THIS RUN. Route 116 (linked successor of route 112) and route 112's corrected next_step ask for the marginal over the two classes no sweep has reached: every |R| = 5 row with Mp <= 3e8, and |R| in {3,4} at P = 30030. PRE-REGISTERED FALSIFIERS (written before the run; each is a single observation): F1 any row with marg <= 0 -> refutes route 112's proved strict positivity F2 any row with marg > floor(2A/q) + 1 -> refutes the drop-shaped marginal candidate F3 two rows with equal (q,|R|,P) and different marg -> refutes an arrangement-free law in those args F4 any NEW row with marg > 4 -> the killer marginal exceeds the tile-dial's measured rise ceiling (the dials decouple) F5 any row with marg > A -> the marginal exceeds the old run length PRE-REGISTERED CANDIDATE BOUNDS tested on every row (new rows + the 15747 served rows): C1 marg <= floor(2A/q) C2 marg <= floor(2A/q) + 1 C3 marg <= q - 1 C4 marg <= A C5 marg <= 2*floor(A/q) + 1 PRE-REGISTERED DELIVERABLE. Either the smallest cell where every candidate fails (scoping the bound away) or the candidates that survive everywhere plus the measured ceiling per (q,|R|) and the reachability arithmetic for the classes the stated cap cannot reach. python killer-marginal.py --mode gates python killer-marginal.py --mode price python killer-marginal.py --mode margin --out killer-marginal.json """ import argparse import itertools import json import os import time import numpy as np VERSION = "1.0.0" HERE = os.path.dirname(os.path.abspath(__file__)) GATES = [(30, (7, 11, 19), 9), (390, (7, 11, 19), 8), (30, (7, 11, 13, 19), 10), (30, (7, 13, 19, 23), 12), (330, (7, 13, 19, 23), 10)] PRIMES = [p for p in range(2, 98) if all(p % d for d in range(2, int(p ** 0.5) + 1))] PS = [30, 210, 2310, 30030] SERVED_ROWS = ["rows-a1.json", "rows-a2.json", "rows-b1.json", "rows-r5.json"] def slot_pattern(B): r = np.arange(B, dtype=np.int64) return (np.gcd(r, B) == 1) & (np.gcd(r + 2, B) == 1) def killed_mask(L, S): k = np.zeros(L, dtype=bool) for q in S: k[0::q] = True k[(-2) % q::q] = True return k def max_cyclic_run(alive, killed, L): flags = killed[alive] n = int(flags.size) if n == 0: return 0 idx = np.flatnonzero(flags) if idx.size == 0: return 0 if int(idx.size) == n: return n brk = np.flatnonzero(np.diff(idx) != 1) starts = np.concatenate(([0], brk + 1)) ends = np.concatenate((brk, [idx.size - 1])) lens = (idx[ends] - idx[starts] + 1).astype(np.int64) best = int(lens.max()) if len(lens) > 1 and idx[0] == 0 and idx[-1] == n - 1: best = max(best, int(lens[0] + lens[-1])) return best def kstar(B, S): L = B for q in S: L *= q return max_cyclic_run(np.tile(slot_pattern(B), L // B), killed_mask(L, S), L) def blocked_scan(B, S, L, window, a0, a1, st): """Scan slots [a0,a1) of modulus L and fold the run statistics into the state st. st = {best, carry, first_run, total_alive}; the state is the whole point: a scan of Mp ~ 6.5e9 slots takes minutes, so it is done in resumable chunks against a checkpoint file (--mode scan) and the final answer is finalize(st). The chunk boundaries carry `carry` (the killed run that is still open at a1) into the next chunk, so chunking is exact, not approximate. """ carry = st["carry"] first_run = st["first_run"] best = st["best"] total_alive = st["total_alive"] a = a0 while a < a1: W = min(window, a1 - a) x = np.arange(a, a + W, dtype=np.int64) alive = (np.gcd(x, B) == 1) & (np.gcd(x + 2, B) == 1) killed = np.zeros(W, dtype=bool) for s in S: killed[(-a) % s::s] = True killed[((-2 - a) % s) % s::s] = True flags = killed[alive] n = int(flags.size) total_alive += n if n: idx = np.flatnonzero(flags) brk = np.flatnonzero(np.diff(idx) != 1) starts = np.concatenate(([0], brk + 1)) ends = np.concatenate((brk, [idx.size - 1])) lens = (idx[ends] - idx[starts] + 1).astype(np.int64) runs = [int(v) for v in lens] opens = idx[0] == 0 closes = idx[-1] == n - 1 if opens and carry: runs[0] += carry if first_run is None and opens and a == 0: first_run = runs[0] if closes: carry = runs[-1] if len(runs) > 1: best = max(best, max(runs[:-1])) else: carry = 0 best = max(best, max(runs)) else: carry = 0 a += W return {"best": best, "carry": carry, "first_run": first_run, "total_alive": total_alive, "a": a} def finalize(st): """K* from a completed scan state: the only extra case is the cyclic wrap.""" best, carry, first_run, total_alive = (st["best"], st["carry"], st["first_run"], st["total_alive"]) if total_alive and best >= total_alive: return total_alive if first_run is not None and carry: # the modulus both opens and closes with a killed run: cyclically they are ONE run best = max(best, min(first_run + carry, total_alive)) return max(best, carry) def blocked_kstar(B, S, L, window=1 << 25): """K*(B,S) on modulus L by WINDOWED scan: O(window) memory instead of O(L). Same object as kstar(B,S); blocked_kstar is checked against the five custody values in --mode blocked-gates before it is used on any class that needs it. Runs are carried across window boundaries, and the final carry is merged with the run that opens the modulus, so the cyclic wrap is handled exactly as in the direct path. """ return finalize(blocked_scan(B, S, L, window, 0, L, {"best": 0, "carry": 0, "first_run": None, "total_alive": 0})) def mode_scan(P, ks, L, window, state_path, maxsecs): """Chunked, resumable scan of one (P, killer, modulus): the 6.5e9-slot object needs minutes.""" st = {"best": 0, "carry": 0, "first_run": None, "total_alive": 0, "a": 0} if state_path and os.path.exists(state_path): st = json.load(open(state_path, encoding="utf-8")) t0 = time.time() while st["a"] < L and time.time() - t0 < maxsecs: a1 = min(L, st["a"] + window * 8) st = blocked_scan(P, ks, L, window, st["a"], a1, st) if state_path: with open(state_path, "w", encoding="utf-8") as fh: json.dump(st, fh) print("scanned %d/%d (%.1f%%) best=%d carry=%d %.1fs" % (st["a"], L, 100.0 * st["a"] / L, st["best"], st["carry"], time.time() - t0), flush=True) done = st["a"] >= L K = finalize(st) if done else None print(json.dumps({"mode": "scan", "P": P, "killer": list(ks), "slots": L, "window": window, "complete": done, "K": K, "state": st})) return 0 if done else 4 def mode_blocked_gates(window): """Custody for the windowed path: it must reproduce the same five published values.""" rows, ok = [], True for (B, S, want) in GATES: L = B for q in S: L *= q got = blocked_kstar(B, S, L, window) direct = kstar(B, S) good = got == want == direct ok = ok and good rows.append({"base": B, "R": list(S), "expected": want, "blocked": got, "direct": direct, "M": L, "window": window, "pass": good}) print("K*(%-4d,%-20s) expected %2d blocked %2d direct %2d M=%-9d %s" % (B, "{" + ",".join(map(str, S)) + "}", want, got, direct, L, "PASS" if good else "FAIL")) print(json.dumps({"mode": "blocked-gates", "all_pass": ok, "rows": rows}, indent=1)) return 0 if ok else 3 def mode_gates(): rows, ok = [], True for (B, S, want) in GATES: got = kstar(B, S) good = got == want ok = ok and good M = B for q in S: M *= q rows.append({"base": B, "R": list(S), "expected": want, "observed": got, "M": M, "pass": good}) print("K*(%-4d,%-20s) expected %2d observed %2d M=%-9d %s" % (B, "{" + ",".join(map(str, S)) + "}", want, got, M, "PASS" if good else "FAIL")) print(json.dumps({"mode": "gates", "all_pass": ok, "rows": rows}, indent=1)) return 0 if ok else 3 def min_modulus(P, nR): """Smallest Mp = P*prod(R)*q over R of size nR and q coprime, as arithmetic only.""" cand = [p for p in PRIMES if P % p] best = None for R in itertools.combinations(cand, nR): M = P for r in R: M *= r toon = [q for q in cand if q not in R] if not toon: continue Mp = M * min(toon) if best is None or Mp < best[0]: best = (Mp, R, min(toon)) return best def mode_price(): out = {} for P in PS: for nR in (3, 4, 5): b = min_modulus(P, nR) if not b: continue Mp, R, q = b out["P=%d|R|=%d" % (P, nR)] = { "min_Mp": Mp, "R": list(R), "q": q, "bool_arrays_gb": round(2 * Mp / 1e9, 3), "accessible_at_16gb": 2 * Mp <= 16e9, } stated = 3e8 out["stated_cap_Mp"] = stated out["classes_with_rows_at_stated_cap"] = { k: v["min_Mp"] <= stated for k, v in out.items() if isinstance(v, dict)} print(json.dumps(out, indent=1, sort_keys=True)) return 0 def new_rows(cls): """The classes the request names. r5 : |R| = 5 with Mp <= 3e8 (the stated cap; P=30 only, 12 rows) p30030 : P = 30030 with |R| in {3,4} -- at the stated cap this class is EMPTY (the smallest primes not dividing 30030 are 17, 19, 23, so |R|=3 needs Mp >= 6.47e9 and |R|=4 needs >= 2.0e11); the reachable part is |R| = 3 at Mp = 6.47e9, reached here by the windowed scan. """ todo = [] if cls in ("r5", "all"): for P in PS: cand = [q for q in PRIMES if P % q] for R in itertools.combinations(cand, 5): M = P for r in R: M *= r for q in cand: if q not in R and M * q <= 3e8: todo.append((P, q, R, M, M * q)) if cls in ("p30030", "all"): cand = [p for p in PRIMES if 30030 % p] for nR, cap in ((2, 3e8), (3, 6.5e9)): for R in itertools.combinations(cand, nR): M = 30030 for r in R: M *= r for q in cand: if q not in R and M * q <= cap: todo.append((30030, q, R, M, M * q)) return sorted(set(todo)) def marginal(P, q, R, M, Mp): aliveP = np.tile(slot_pattern(P), Mp // P) kill = killed_mask(Mp, R) A = max_cyclic_run(aliveP[:M], kill[:M], M) kill[0::q] = True kill[(-2) % q::q] = True K = max_cyclic_run(aliveP, kill, Mp) del aliveP, kill return A, K, K - A def mode_margin(out_path, cls, window, kcache=None): kc = {} if kcache and os.path.exists(kcache): kc = json.load(open(kcache, encoding="utf-8")) def cached(key, fn): if key in kc: return kc[key] v = fn() kc[key] = v if kcache: with open(kcache, "w", encoding="utf-8") as fh: json.dump(kc, fh) return v served = [] for f in SERVED_ROWS: p = os.path.join(HERE, f) if os.path.exists(p): d = json.load(open(p, encoding="utf-8")) for r in d["rows"]: r = dict(r) r["q"] = r["p"] # the served files name the entering prime p r["source"] = f served.append(r) fresh = [] for (P, q, R, M, Mp) in new_rows(cls): t0 = time.time() A = cached("A|%d|%s|%d" % (P, R, M), lambda: blocked_kstar(P, R, M, window) if M > 2e8 else kstar(P, R)) ks = tuple(sorted(tuple(R) + (q,))) K = cached("K|%d|%s|%d" % (P, ks, Mp), lambda: blocked_kstar(P, ks, Mp, window) if Mp > 2e8 else kstar(P, ks)) marg = K - A dt = time.time() - t0 fresh.append({"P": P, "q": q, "R": list(R), "nR": len(R), "M": M, "Mp": Mp, "A": A, "K": K, "marginal": marg, "source": "fresh", "method": "blocked" if Mp > 2e8 else "direct", "secs": round(dt, 1)}) print("P=%-5d q=%-3d R=%-22s A=%-3d K=%-3d marginal=%2d Mp=%-12d %s %.1fs" % (P, q, "{" + ",".join(map(str, R)) + "}", A, K, marg, Mp, "blocked" if Mp > 2e8 else "direct", dt), flush=True) if out_path: with open(out_path + ".partial", "w", encoding="utf-8") as fh: json.dump({"class": cls, "window": window, "partial": True, "rows": fresh}, fh, indent=1) allrows = served + fresh # margins for the served rows were computed by the same definition in #1365 for r in allrows: r.setdefault("marginal", r["marginal"]) cands = { "C1_floor2A_over_q": lambda r: (2 * r["A"]) // r["q"], "C2_floor2A_over_q_plus1": lambda r: (2 * r["A"]) // r["q"] + 1, "C3_q_minus_1": lambda r: r["q"] - 1, "C4_A": lambda r: r["A"], "C5_2floorA_over_q_plus1": lambda r: 2 * ((r["A"]) // r["q"]) + 1, } cand_res = {} for name, f in cands.items(): viol = [r for r in allrows if r["marginal"] > f(r)] fresh_viol = [r for r in fresh if r["marginal"] > f(r)] cand_res[name] = {"violations_all": len(viol), "violations_fresh": len(fresh_viol), "worst": max((r["marginal"] - f(r) for r in allrows), default=None), "example": ({k: viol[0][k] for k in ("P", "q", "A", "marginal")} if viol else None)} def split(keyf): cells = {} for r in allrows: cells.setdefault(keyf(r), set()).add(r["marginal"]) return {"cells": len(cells), "cells_with_more_than_one_marginal": sum(1 for v in cells.values() if len(v) > 1)} func = {"by_A_q": split(lambda r: (r["A"], r["q"])), "by_A_q_P": split(lambda r: (r["A"], r["q"], r["P"])), "by_A_q_nR": split(lambda r: (r["A"], r["q"], r["nR"])), "by_A_q_nR_P": split(lambda r: (r["A"], r["q"], r["nR"], r["P"]))} percell = {} for r in allrows: k = "%d|%d" % (r["q"], r["nR"]) percell[k] = max(percell.get(k, -10 ** 9), r["marginal"]) fresh_cells = {} for r in fresh: k = "%d|%d|%d" % (r["P"], r["q"], r["nR"]) fresh_cells[k] = r["marginal"] f4 = [r for r in fresh if r["marginal"] > 4] f5 = [r for r in allrows if r["marginal"] > r["A"]] res = { "tool": "job2732/killer-marginal.py", "version": VERSION, "mode": "margin", "served_rows": len(served), "fresh_rows": len(fresh), "total_rows": len(allrows), "fresh_rows_detail": fresh, "fresh_marginal_hist": {str(v): sum(1 for r in fresh if r["marginal"] == v) for v in sorted({r["marginal"] for r in fresh})}, "marginal_hist_all": {str(v): sum(1 for r in allrows if r["marginal"] == v) for v in sorted({r["marginal"] for r in allrows})}, "max_marginal_all": max(r["marginal"] for r in allrows), "max_marginal_fresh": max((r["marginal"] for r in fresh), default=None), "candidates": cand_res, "functionality": func, "max_marginal_by_q_and_Rsize": percell, "fresh_by_P_q_Rsize": fresh_cells, "F1_marg_le_0": sum(1 for r in allrows if r["marginal"] <= 0), "F2_violations_of_C2": cand_res["C2_floor2A_over_q_plus1"]["violations_all"], "F3_split_cells_A_q_P": func["by_A_q_P"]["cells_with_more_than_one_marginal"], "F4_fresh_over_4": len(f4), "F4_examples": f4[:5], "F5_marg_gt_A": len(f5), "price": mode_price_dict(), } print(json.dumps({k: v for k, v in res.items() if k not in ("fresh_rows_detail", "max_marginal_by_q_and_Rsize", "fresh_by_P_q_Rsize")}, indent=1, sort_keys=True)) print("fresh rows:") for r in fresh: print(" P=%-6d q=%-3d |R|=%d R=%s Mp=%-12d A=%-3d K=%-3d marg=%d" % (r["P"], r["q"], r["nR"], r["R"], r["Mp"], r["A"], r["K"], r["marginal"])) if out_path: with open(out_path, "w", encoding="utf-8", newline="\n") as fh: json.dump(res, fh, indent=1, sort_keys=True) fh.write("\n") return 0 def mode_price_dict(): out = {} for P in PS: for nR in (3, 4, 5): b = min_modulus(P, nR) if b: out["P=%d|R|=%d" % (P, nR)] = {"min_Mp": b[0], "R": list(b[1]), "q": b[2], "two_bool_arrays_GB": round(2 * b[0] / 1e9, 3), "fits_16_GB": 2 * b[0] <= 16e9} return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--mode", choices=["gates", "blocked-gates", "price", "margin", "scan"], default="gates") ap.add_argument("--class", dest="cls", choices=["r5", "p30030", "all"], default="all") ap.add_argument("--base", type=int, default=30030) ap.add_argument("--killer", default="17,19,23,29") ap.add_argument("--slots", type=int, default=6469693230) ap.add_argument("--state", default=None) ap.add_argument("--kcache", default=None) ap.add_argument("--maxsecs", type=float, default=480.0) ap.add_argument("--window", type=int, default=1 << 25) ap.add_argument("--out", default=None) a = ap.parse_args() if a.mode == "gates": return mode_gates() if a.mode == "blocked-gates": return mode_blocked_gates(a.window) if a.mode == "scan": return mode_scan(a.base, tuple(int(v) for v in a.killer.split(",")), a.slots, a.window, a.state, a.maxsecs) if a.mode == "price": return mode_price() return mode_margin(a.out, a.cls, a.window, a.kcache) if __name__ == "__main__": raise SystemExit(main())