#!/usr/bin/env python3 """Basin inheritance of the free paired maximum (route 113, job #2733). Object (return #675's, reused verbatim): W = x# (primorial), tau even in [0, W) adm(tau) = { r in [0,W) : gcd(r,W)=1 and gcd((r+tau) mod W, W)=1 } cover(tau) = (longest cyclic gap between consecutive elements of adm(tau)) - 1 Gates: cover(0)+1 = A048670, cover(2) = A144311, 1 + max_even cover = A288815. A lift of tau from level x to the next prime x' is any even tau' == tau (mod W). Subcommands: gates full sweep of every even offset; G1-G3 per level sweep --out F full even-offset sweep: max, argmax, histogram band --dmax N exhaustive band test: smallest d whose band lifts to the optimum lifts --taus F lift a supplied list of offsets (one per line) """ import argparse, json, os, sys, time import numpy as np # Published gate values, indexed by the prime x (OEIS, as printed on the pages; # A288815 is an ILP optimum per return #675's account, not a proven maximum). GATE = { # x: (A048670 := cover(0)+1, A144311 := cover(2), A288815 := 1 + max cover) 2: (2, 1, 2), 3: (4, 5, 6), 5: (6, 11, 18), 7: (10, 29, 30), 11: (14, 41, 66), 13: (22, 65, 150), 17: (26, 107, 192), 19: (34, 149, 258), } 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 build_level(x): """Return (W, iscop): iscop[r] True iff gcd(r, W) == 1.""" ps = primes_upto(x) W = 1 for p in ps: W *= p iscop = np.ones(W, dtype=bool) iscop[0] = False for p in ps: iscop[0::p] = False return W, iscop, ps def cover_of(iscop, taus): """cover(tau) for each tau. adm = iscop & rot(iscop, -tau); longest cyclic gap - 1. The rotation sign is load-bearing: rot(NC, -tau) is the correct mask. rot(NC, +tau) is the mirror image, which is invisible on tau = 0 and tau = 2 (cover(tau) = cover(W-tau)) and shows up only as a mirrored argmax set -- return #687's recorded producer bug. """ W = iscop.size taus = np.atleast_1d(np.asarray(taus, dtype=np.int64)) out = np.empty(taus.size, dtype=np.int64) for i in range(taus.size): t = int(taus[i]) % W adm = iscop & np.roll(iscop, -t) idx = np.flatnonzero(adm) if idx.size < 2: out[i] = W - 1 continue d = np.diff(idx) wrap = W - int(idx[-1]) + int(idx[0]) out[i] = (int(d.max()) if d.size else 0) if wrap > out[i]: out[i] = wrap out[i] -= 1 return out def even_offsets(W): return np.arange(0, W, 2, dtype=np.int64) def pm1_run(x): """Independent construction of A144311 from its OEIS NAME, sharing no code with cover(): the longest sequence of consecutive integers each == 1 or -1 modulo at least one of the first n primes. Used only as a cross-check on the identity cover(2) = A144311(n). (Degenerate at n <= 2, where the first terms are convention-bound: A144311(1) = 1.) """ W, _, ps = build_level(x) q = np.zeros(W, dtype=bool) for p in ps: q[1::p] = True q[(p - 1) % p::p] = True idx = np.flatnonzero(~q) if idx.size < 2: return int(W) d = np.diff(idx) wrap = W - int(idx[-1]) + int(idx[0]) return int(max(int(d.max()), wrap) - 1) def gate_check(x, iscop, verbose=True): W = iscop.size taus = even_offsets(W) cov = cover_of(iscop, taus) mx = int(cov.max()) argmax = taus[cov == mx] g = GATE[x] # NOTE: index by tau, never by array position -- taus = [0,2,4,...], so cov[2] is tau = 4. rows = { "x": x, "W": int(W), "even_offsets": int(taus.size), "cover0_plus1": int(cover_of(iscop, [0])[0]) + 1, "gate_A048670": g[0], "cover2": int(cover_of(iscop, [2])[0]), "gate_A144311": g[1], "one_plus_max": mx + 1, "gate_A288815": g[2], "argmax_count": int(argmax.size), "argmax_min": int(argmax.min()), "argmax_max": int(argmax.max()), "pm1_run_independent": pm1_run(x), } rows["G2b_pm1_agrees_with_cover2"] = (rows["pm1_run_independent"] == rows["cover2"]) if not rows["G2b_pm1_agrees_with_cover2"]: rows["G2_pm1_note"] = "degenerate convention at n <= 2" if x <= 3 else "DISAGREEMENT" rows["G1"] = rows["cover0_plus1"] == g[0] rows["G2"] = rows["cover2"] == g[1] rows["G3"] = rows["one_plus_max"] == g[2] if verbose: sys.stderr.write( "x=%d W=%d offsets=%d cover(0)+1=%d(%s) cover(2)=%d(%s) 1+max=%d(%s) argmax=%d\n" % (x, W, taus.size, rows["cover0_plus1"], rows["G1"], rows["cover2"], rows["G2"], rows["one_plus_max"], rows["G3"], argmax.size)) return rows, cov, taus, argmax def cmd_gates(a): out = [] for x in a.levels: W, iscop, _ = build_level(x) t0 = time.time() rows, _, _, _ = gate_check(x, iscop) rows["secs"] = round(time.time() - t0, 3) out.append(rows) ok = all(r["G1"] and r["G2"] and r["G3"] for r in out) doc = {"tool": "basin.py/1", "kind": "gates", "rows": out, "all_gates_pass": ok} print(json.dumps(doc, indent=1, sort_keys=True)) return 0 if ok else 1 def cmd_sweep(a): x = a.levels[0] W, iscop, _ = build_level(x) t0 = time.time() rows, cov, taus, argmax = gate_check(x, iscop) hist = np.bincount(cov) nz = [(int(v), int(c)) for v, c in enumerate(hist) if c] doc = {"tool": "basin.py/1", "kind": "sweep", "gate": rows, "histogram": nz, "argmax_offsets": [int(v) for v in argmax], "top_values": sorted(nz, key=lambda kv: -kv[0])[:12], "secs": round(time.time() - t0, 3), "per_offset_us": round((time.time() - t0) / max(1, taus.size) * 1e6, 2)} sys.stderr.write("sweep x=%d: max=%d hist_tail=%s\n" % (x, rows["one_plus_max"] - 1, doc["top_values"][:6])) if a.out: with open(a.out, "w", encoding="utf-8") as f: json.dump(doc, f, indent=1, sort_keys=True) else: print(json.dumps(doc, indent=1, sort_keys=True)) return 0 def cmd_band(a): """Exhaustive band test x -> xp. band B_d = { even tau : cover_x(tau) >= max_x - d }; test every even lift tau' == tau (mod W) in [0, W*xp). Report the smallest d whose band contains a lift attaining the published level-xp optimum, plus band sizes and lifts tested. """ x, xp = sorted(a.levels)[:1] + [a.levels[1]] if len(a.levels) > 1 else (a.levels[0], None) x, xp = a.levels[0], a.levels[1] W, iscop, _ = build_level(x) Wp, iscopp, _ = build_level(xp) t0 = time.time() rows, cov, taus, argmax = gate_check(x, iscop) maxx = int(cov.max()) target = GATE[xp][2] - 1 # published exact optimum in cover units kn = Wp // W # number of even lifts per offset order = np.argsort(-cov) # descending cover taus_sorted = taus[order] cov_sorted = cov[order] best = -1 best_tau = None best_lift = None first_d = None trace = [] tested = 0 seen = 0 d = 0 while d <= a.dmax: cut = maxx - d # members whose cover >= cut hi = int(np.searchsorted(-cov_sorted, -cut, side="right")) members = taus_sorted[:hi] new = members[seen:] seen = hi if new.size: lifts = (new[:, None] + np.arange(kn, dtype=np.int64)[None, :] * W).ravel() cv = cover_of(iscopp, lifts) tested += int(lifts.size) m = int(cv.max()) if m > best: best = m j = int(cv.argmax()) best_lift = int(lifts[j]) best_tau = int(best_lift % W) trace.append({"d": d, "band_size": int(hi), "new_members": int(new.size), "lifts_tested": int(lifts.size), "cum_lifts": tested, "best_cover_at_level_xp": best, "best_lift": best_lift, "secs": round(time.time() - t0, 2)}) sys.stderr.write("d=%d band=%d new=%d lifts=%d cum=%d best=%d elapsed=%.1fs\n" % (d, hi, new.size, lifts.size, tested, best, time.time() - t0)) if best >= target and first_d is None: first_d = d if first_d is not None: break d += 1 doc = {"tool": "basin.py/1", "kind": "band", "pair": [x, xp], "W": int(W), "Wp": int(Wp), "lifts_per_offset": int(kn), "gate_x": rows, "max_x": maxx, "target_cover_at_xp": target, "target_A288815": GATE[xp][2], "smallest_d_reaching_target": first_d, "best_cover_reached": best, "best_lift": best_lift, "best_lift_mod_W": best_tau, "lifts_tested": tested, "dmax": a.dmax, "trace": trace, "secs": round(time.time() - t0, 2)} if a.out: with open(a.out, "w", encoding="utf-8") as f: json.dump(doc, f, indent=1, sort_keys=True) else: print(json.dumps(doc, indent=1, sort_keys=True)) return 0 def cmd_lifts(a): x, xp = a.levels[0], a.levels[1] W, iscop, _ = build_level(x) Wp, iscopp, _ = build_level(xp) taus = [int(l) for l in open(a.taus, encoding="utf-8") if l.strip()] kn = Wp // W arr = np.asarray(taus, dtype=np.int64) lifts = (arr[:, None] + np.arange(kn, dtype=np.int64)[None, :] * W).ravel() t0 = time.time() cv = cover_of(iscopp, lifts) doc = {"tool": "basin.py/1", "kind": "lifts", "pair": [x, xp], "offsets": len(taus), "lifts_tested": int(lifts.size), "lifts_per_offset": int(kn), "best_cover": int(cv.max()), "best_lift": int(lifts[int(cv.argmax())]), "best_lift_mod_W": int(lifts[int(cv.argmax())] % W), "per_offset_best": [int(cover_of(iscopp, arr[i:i+1] + np.arange(kn, dtype=np.int64)*W).max()) for i in range(min(len(taus), a.per))], "secs": round(time.time() - t0, 2)} print(json.dumps(doc, indent=1, sort_keys=True)) return 0 def cmd_toplist(a): """Sweep every even offset at level x and write the offsets whose cover >= min_cover. This is the band B_d for d = max_cover - min_cover, materialised, because the band test needs the offsets themselves and a histogram alone cannot reconstruct them. """ x = a.levels[0] W, iscop, _ = build_level(x) taus = even_offsets(W) keep = [] t0 = time.time() chunk = 5000 for i in range(0, taus.size, chunk): c = cover_of(iscop, taus[i:i + chunk]) sel = c >= a.min_cover for t, v in zip(taus[i:i + chunk][sel], c[sel]): keep.append([int(t), int(v)]) sys.stderr.write("toplist x=%d %d/%d kept=%d %.1fs\n" % (x, min(i + chunk, taus.size), taus.size, len(keep), time.time() - t0)) sys.stderr.flush() mx = max(v for _, v in keep) if keep else None doc = {"tool": "basin.py/1", "kind": "toplist", "x": x, "W": int(W), "min_cover": a.min_cover, "count": len(keep), "max_cover_seen": mx, "offsets": keep, "secs": round(time.time() - t0, 2)} with open(a.out, "w", encoding="utf-8") as f: json.dump(doc, f, sort_keys=True) sys.stderr.write("toplist x=%d wrote %d offsets >= %d to %s\n" % (x, len(keep), a.min_cover, a.out)) return 0 def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest="cmd", required=True) t = sub.add_parser("toplist") t.add_argument("levels", type=int, nargs=1) t.add_argument("--min-cover", dest="min_cover", type=int, required=True) t.add_argument("--out", required=True) t.set_defaults(func=cmd_toplist) g = sub.add_parser("gates"); g.add_argument("levels", type=int, nargs="+"); g.add_argument("--out") g.set_defaults(func=cmd_gates) s = sub.add_parser("sweep"); s.add_argument("levels", type=int, nargs=1); s.add_argument("--out") s.set_defaults(func=cmd_sweep) b = sub.add_parser("band") b.add_argument("levels", type=int, nargs=2) b.add_argument("--dmax", type=int, default=40) b.add_argument("--out") b.set_defaults(func=cmd_band) l = sub.add_parser("lifts") l.add_argument("levels", type=int, nargs=2) l.add_argument("--taus", required=True) l.add_argument("--per", type=int, default=0) l.set_defaults(func=cmd_lifts) a = ap.parse_args() return a.func(a) if __name__ == "__main__": sys.exit(main())