#!/usr/bin/env python3 """Route 4, job 959: branch-and-certify refutation below the weighted frontier. Claim checked: prefix D (support a, n slots) has no phase cover. Proof shape: choose a prime q and branch on every phase b in 0..q-1. In the child, the slots killed by (q,b) are removed and q leaves Q. A cover of D through (q,b) is a cover of the residual (D', Q'), so the child is closed by * an exact weighted certificate on (D', Q'): integer w >= 0 with sum_{q' in Q'} max_b W(q',b) < W(D'), rechecked in integer arithmetic, or * recursion on a further prime (depth-limited). A node that is neither closed nor expanded is 'open', and then the claim is NOT certified. The LP (HiGHS) only proposes weights and branching primes; every closure is the integer recheck. Branching prime: the one whose depth-1 children have the fewest LP-unclosed phases (ties -> smaller q). stdout is the artifact. python tree959.py 9409 48 [maxdepth] # writes tree959--.cert.jsonl when certified Leaf records: {path: [[q,b],...], w: integer weights on the residual D in slot order}; branch records: {path, branch: q}. Check with checkcert959.py. """ import importlib.util import os import sys from collections import Counter import numpy as np from scipy.optimize import linprog from scipy.sparse import coo_matrix HERE = os.path.dirname(os.path.abspath(__file__)) s = importlib.util.spec_from_file_location('rw', os.path.join(HERE, 'r370-route4-weighted.py')) rw = importlib.util.module_from_spec(s) s.loader.exec_module(rw) sys.stdout.reconfigure(newline='\n') WDEN = 10 ** 7 OLD, QS0 = rw.old_primes(97), rw.new_primes(97) def killed(D, q, b): return [x for x in D if (x + b) % q == 0 or (x + b + 2) % q == 0] def lp_w(D, QS): """LP value v and dual weights w for residual (D, QS).""" if not D: return 99.0, None if not QS: return 0.0, [1.0] * len(D) off, o = {}, 0 for q in QS: off[q] = o o += q rows, cols, vals = [], [], [] for qi, q in enumerate(QS): for b in range(q): rows.append(qi); cols.append(off[q] + b); vals.append(1.0) for i, x in enumerate(D): r = len(QS) + i rows.append(r); cols.append(o); vals.append(1.0) for q in QS: rows.append(r); cols.append(off[q] + (-x) % q); vals.append(-1.0) rows.append(r); cols.append(off[q] + (-x - 2) % q); vals.append(-1.0) A = coo_matrix((vals, (rows, cols)), shape=(len(QS) + len(D), o + 1)).tocsr() b = np.concatenate([np.ones(len(QS)), np.zeros(len(D))]) c = np.zeros(o + 1); c[o] = -1.0 res = linprog(c, A_ub=A, b_ub=b, bounds=[(0, None)] * (o + 1), method='highs') assert res.status == 0 return -res.fun, list(-res.ineqlin.marginals[len(QS):]) def int_cert(D, QS, w): """Exact recheck; returns (sum max, W(D)) if a strict deficit, else None.""" if not QS: return (0, 1, [1] * len(D)) if D else None wi = [max(0, int(round(x * WDEN))) for x in w] tot = sum(wi) if tot == 0: return None sm = 0 for q in QS: W = Counter() for x, v in zip(D, wi): if v: W[(-x) % q] += v W[(-x - 2) % q] += v sm += max(W.values()) return (sm, tot, wi) if sm < tot else None STATS = Counter() CERT = [] def close(D, QS): v, w = lp_w(D, QS) STATS['lp'] += 1 if v < 1 - 1e-9: c = int_cert(D, QS, w) if c: return True, c return False, v def prove(D, QS, depth, maxdepth, path): """Return True iff (D, QS) is certified non-coverable by this tree.""" if not D: STATS['empty_residual'] += 1 return False # empty D is coverable: branch cannot be closed ok, c = close(D, QS) if ok: STATS['leaf_closed'] += 1 CERT.append({'path': path, 'w': c[2]}) return True if depth >= maxdepth: STATS['open'] += 1 return False # choose branching prime by fewest LP-unclosed children best = None for q in QS: rest = [p for p in QS if p != q] bad = 0 for b in range(q): if not close([x for x in D if x not in set(killed(D, q, b))], rest)[0]: bad += 1 if best and bad >= best[0]: break if best is None or bad < best[0]: best = (bad, q) if bad == 0: break q = best[1] rest = [p for p in QS if p != q] STATS[f'branch_depth{depth}'] += 1 CERT.append({'path': path, 'branch': q}) for b in range(q): K = set(killed(D, q, b)) if not prove([x for x in D if x not in K], rest, depth + 1, maxdepth, path + [(q, b)]): print(f' open node: path {path + [(q, b)]}', flush=True) return False if depth == 0: print(f'root branch prime q = {q}: all {q} phases closed', flush=True) return True def main(): a, n = int(sys.argv[1]), int(sys.argv[2]) maxdepth = int(sys.argv[3]) if len(sys.argv) > 3 else 2 D = rw.slots_from(a, n, OLD) print(f'# support a = {a}, prefix n = {n}, L = {D[-1] - a + 1}, Q = {QS0[0]}..{QS0[-1]} ({len(QS0)} primes), maxdepth {maxdepth}', flush=True) ok = prove(D, list(QS0), 0, maxdepth, []) if ok: import hashlib, json body = ''.join(json.dumps(r, separators=(',', ':')) + '\n' for r in CERT) fn = f'tree959-{a}-{n}.cert.jsonl' open(fn, 'w', newline='\n').write(body) print(f'certificate {fn}: {len(CERT)} records, sha256 {hashlib.sha256(body.encode()).hexdigest()}') print(('CERTIFIED NON-COVERABLE' if ok else 'NOT CERTIFIED') + ' ; ' + '; '.join(f'{k}={STATS[k]}' for k in sorted(STATS))) if __name__ == '__main__': main()