"""Job #2534 (pursue route 97), part 2: the changed ingredient after Bonferroni-3 failed. Hunter's bound (Hunter 1976; Worsley 1982): for events A_1..A_m and ANY spanning tree T on {1..m}, |union A_i| <= sum_i |A_i| - sum_{(i,j) in T} |A_i cap A_j|. It is a second-order bound with no triple term, so the S3 penalty that sank Bonferroni-3 is absent. On the mod-6 wheel every per-start quantity depends on the residue tuple (s mod p)_p, all tuples occur once per period, and the Hunter right side for a FIXED tree T is a TREE-STRUCTURED function of the tuple: H_T(r) = sum_p g_p(r_p) - sum_{(p,q) in T} f_pq(r_p, r_q), with g_p(r) = |K_p(r) cap W| and f_pq(r, r') = |K_p(r) cap K_q(r') cap W| (tables of size p and p*q for a window W of length L). So max_s H_T(s) is computed EXACTLY by max-sum message passing on the tree, in time O(sum_{edges} p*q), with no enumeration of the period: a valid, coupled, exactly certifiable upper bound on max_s |U cap W_s| for every tree, and the best tree gives B_H* = min over spanning trees T of max_r H_T(r). Wang's capacity sum is the empty-forest case (no edges). PRE-REGISTERED (before this run). F1 (correctness): tree DP equals brute force over all 85,085 starts at Q = {5..17} for every tree and window. F2 (validity): B_H* >= max_s |union| at every Q and window. F3 (gain): B_H* < 0.9 * capacity for at least one frontier window (L = M or M+1); otherwise the route's failure clause fires for this family too. Trees: all 125 spanning trees of K_5 (Q = {5..17}) and all 16,807 of K_7 (Q = {5..23}) via Pruefer codes. Also reported per window: the ideal per-start Hunter with the per-start maximum spanning tree (brute force at 5..17 only), to show how much the fixed-tree restriction costs. Stdout: ledger + JSON; stderr: progress. RUN: python hunter2534.py --out hunter2534.json """ import argparse, json, math, sys, time, itertools import numpy as np A144311 = {7: 107, 9: 203} QS = {'5..17': [5, 7, 11, 13, 17], '5..23': [5, 7, 11, 13, 17, 19, 23]} log = sys.stderr def tables(Q, L): g, f, kill = {}, {}, {} for p in Q: inv = pow(6, -1, p); kill[p] = np.array([[((r + j) % p in (inv, (p - inv) % p)) for j in range(L)] for r in range(p)], dtype=np.int64) g[p] = kill[p].sum(axis=1) for p, q in itertools.combinations(Q, 2): f[(p, q)] = kill[p] @ kill[q].T return g, f, kill def fpair(f, p, q): return f[(p, q)] if (p, q) in f else f[(q, p)].T def prufer_trees(n): """all labelled spanning trees on n vertices as edge lists (Pruefer decoding); n^(n-2) trees.""" for code in itertools.product(range(n), repeat=n - 2): degree = [1] * n for c in code: degree[c] += 1 edges = [] for c in code: for leaf in range(n): if degree[leaf] == 1: edges.append((leaf, c)); degree[leaf] -= 1; degree[c] -= 1; break u, v = [i for i in range(n) if degree[i] == 1] edges.append((u, v)); yield edges def tree_max(Q, edges, g, f): """max over residue tuples of sum_p g_p(r_p) - sum_{edges} f_pq(r_p, r_q), by max-sum message passing rooted at Q[0].""" n = len(Q); adj = {i: [] for i in range(n)} for a, b in edges: adj[a].append(b); adj[b].append(a) order, parent, seen = [], {0: None}, {0}; stack = [0] while stack: x = stack.pop(); order.append(x) for y in adj[x]: if y not in seen: seen.add(y); parent[y] = x; stack.append(y) val = {} for x in reversed(order): v = g[Q[x]].astype(np.float64).copy() for y in adj[x]: if parent.get(y) == x: F = fpair(f, Q[x], Q[y]) # shape (p_x, p_y) v = v + (val[y][None, :] - F).max(axis=1) val[x] = v return float(val[0].max()) def brute_hunter(Q, edges, g, f, P): s = np.arange(P, dtype=np.int64); tot = np.zeros(P, dtype=np.int64) for i, p in enumerate(Q): tot += g[p][s % p] for a, b in edges: F = fpair(f, Q[a], Q[b]); tot -= F[s % Q[a], s % Q[b]] return int(tot.max()) def main(): ap = argparse.ArgumentParser(); ap.add_argument('--out', required=True); a = ap.parse_args(); ledger = [] def check(tag, ok, detail): ledger.append(f"{'PASS' if ok else 'FAIL'} {tag} :: {detail}"); print(ledger[-1], file=log, flush=True) prev = json.load(open('bonf2534.json')) # union maxima, capacity sums and M from part 1 out = {'instrument': 'hunter2534.py', 'job': 2534, 'ledger': ledger, 'levels': {}} for name, Q in QS.items(): t0 = time.time(); P = math.prod(Q); M = prev['levels'][name]['M']; lv = {'Q': Q, 'M': M, 'windows': {}} trees = list(prufer_trees(len(Q))); print(f'{name}: {len(trees)} spanning trees', file=log, flush=True) for L in sorted({53, M + 1, M}): t1 = time.time(); g, f, kill = tables(Q, L); pw = prev['levels'][name]['windows'][str(L)] cap, maxU = pw['capacity_sum'], pw['max_union'] vals = np.array([tree_max(Q, T, g, f) for T in trees]); best = int(np.argmin(vals)); BH = float(vals[best]) rec = {'L': L, 'capacity_sum': cap, 'max_union': maxU, 'trees': len(trees), 'B_H_star': BH, 'best_tree': [(Q[a], Q[b]) for a, b in trees[best]], 'tree_values_min_median_max': [float(vals.min()), float(np.median(vals)), float(vals.max())], 'gain_ratio': BH / cap} if name == '5..17': bf = brute_hunter(Q, trees[best], g, f, P); rec['brute_best_tree'] = bf sample = [0, 7, 31, 64, 99, best]; ok = all(abs(tree_max(Q, trees[i], g, f) - brute_hunter(Q, trees[i], g, f, P)) < 1e-9 for i in sample) check(f'F1_treeDP_equals_brute_{name}_L{L}', ok, f'{len(sample)} trees incl. the best: DP == brute force over {P} starts') # ideal per-start Hunter: per start take the maximum spanning tree (brute, 85k starts x 10 pair tables): Kruskal per start is slow in Python; use all 125 trees vectorised s = np.arange(P, dtype=np.int64); S1 = sum(g[p][s % p] for p in Q); ideal = np.full(P, -1) for T in trees: tw = np.zeros(P, dtype=np.int64) for a_, b_ in T: F = fpair(f, Q[a_], Q[b_]); tw += F[s % Q[a_], s % Q[b_]] ideal = np.maximum(ideal, tw) rec['ideal_per_start_hunter_max'] = int((S1 - ideal).max()) check(f'F2_validity_{name}_L{L}', BH >= maxU - 1e-9, f'B_H* = {BH:.1f} >= max union {maxU}') check(f'F3_gain_{name}_L{L}', BH < 0.9 * cap, f'B_H* = {BH:.1f} vs capacity {cap} (ratio {BH / cap:.3f}); max union {maxU}; best tree {rec["best_tree"]}') lv['windows'][str(L)] = rec print(f'{name} L={L}: cap {cap} union {maxU} B_H* {BH:.1f} (ratio {BH / cap:.3f}) trees {len(trees)} ({time.time() - t1:.1f}s)' + (f" ideal per-start Hunter {rec.get('ideal_per_start_hunter_max')}" if 'ideal_per_start_hunter_max' in rec else ''), file=log, flush=True) lv['secs'] = round(time.time() - t0, 1); out['levels'][name] = lv; json.dump(out, open(a.out, 'w'), indent=1) v = {'F1_treeDP_correct': all('PASS' in l for l in ledger if 'F1_' in l), 'F2_all_valid': all('PASS' in l for l in ledger if 'F2_' in l), 'F3_gain_at_frontier': any('PASS' in l for l in ledger if 'F3_gain' in l and ('_L17' in l or '_L18' in l or '_L33' in l or '_L34' in l)), 'ratios': {f'{n}_L{L}': w['gain_ratio'] for n, lv in out['levels'].items() for L, w in lv['windows'].items()}} out['verdict'] = v; json.dump(out, open(a.out, 'w'), indent=1) print('\n'.join(ledger)); print('VERDICT ' + json.dumps(v, sort_keys=True)); return 0 if __name__ == '__main__': sys.exit(main())