#!/usr/bin/env python3 """Route 4, job 959: the weighted (fractional) certificate as an exact LP. For a finite old-admissible D (p = 97) and Q = primes in (p, 2p], let v(D) = max { z : y(q,.) >= 0, sum_b y(q,b) <= 1 for each q, sum_q [y(q,-s) + y(q,-s-2)] >= z for each s in D }. By LP duality v(D) = min over w >= 0, sum w = 1 of sum_q max_b W(q,b), the quantity #370 minimised by multiplicative weights. A cover is an integral y with coverage >= 1, so v(D) < 1 certifies NON-COVERABILITY (the weighted family decides D), and v(D) >= 1 means no weight vector does (the family is silent). v is non-increasing along prefixes, so each support has one weighted frontier n* = min { n : v(prefix_n) < 1 }. Both sides are re-verified in exact integer arithmetic, not by LP tolerance: * deficit side: the LP's dual w, rounded to integers, must satisfy sum_q max_b W(q,b) < sum_s w_s exactly; * silent side: the LP's y, floored to integers over DEN per prime (so each prime's total stays <= DEN), must cover every slot with total >= DEN. A side that fails its exact check is printed as 'unverified', never as decided. Tight prefixes (F1 = |D| - sum_q M(q) = 0) are decided by #370's own branches (route4-weighted.py, imported unchanged: dead slot, else disjoint argmax tiling). stdout is the artifact; timing goes to stderr. No randomness. python sprint959.py frozen # (3) frontier on a = 9409, n = 1..70 python sprint959.py census 9409 500 200 # (1)+(2) supports a = 9409 + 500k """ import importlib.util import os import sys import time 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__)) spec = importlib.util.spec_from_file_location('rw', os.path.join(HERE, 'r370-route4-weighted.py')) rw = importlib.util.module_from_spec(spec) spec.loader.exec_module(rw) sys.stdout.reconfigure(newline='\n') T0 = time.time() DEN = 10 ** 9 WDEN = 10 ** 7 P = 97 OLD, QS = rw.old_primes(P), rw.new_primes(P) OFF = {} o = 0 for q in QS: OFF[q] = o o += q NY = o def log(*a): print(*a, file=sys.stderr) def lp(D): """Return (v, y-list-per-prime, w) from HiGHS for prefix D.""" n = len(D) rows, cols, vals = [], [], [] for qi, q in enumerate(QS): # sum_b y(q,b) <= 1 for b in range(q): rows.append(qi); cols.append(OFF[q] + b); vals.append(1.0) for i, s in enumerate(D): # z - sum_q [y(q,r1)+y(q,r2)] <= 0 r = len(QS) + i rows.append(r); cols.append(NY); vals.append(1.0) for q in QS: rows.append(r); cols.append(OFF[q] + (-s) % q); vals.append(-1.0) rows.append(r); cols.append(OFF[q] + (-s - 2) % q); vals.append(-1.0) A = coo_matrix((vals, (rows, cols)), shape=(len(QS) + n, NY + 1)).tocsr() b = np.concatenate([np.ones(len(QS)), np.zeros(n)]) c = np.zeros(NY + 1); c[NY] = -1.0 res = linprog(c, A_ub=A, b_ub=b, bounds=[(0, None)] * (NY + 1), method='highs') assert res.status == 0, res.message v = -res.fun y = res.x[:NY] w = -res.ineqlin.marginals[len(QS):] return v, y, w def exact_deficit(D, w): 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 s, x in zip(D, wi): if x: W[(-s) % q] += x W[(-s - 2) % q] += x sm += max(W.values()) return (sm, tot) if sm < tot else None def exact_silent(D, y): yi = np.floor(np.maximum(y, 0) * DEN).astype(np.int64) for q in QS: assert int(yi[OFF[q]:OFF[q] + q].sum()) <= DEN worst = None for s in D: cov = 0 for q in QS: cov += int(yi[OFF[q] + (-s) % q]) + int(yi[OFF[q] + (-s - 2) % q]) worst = cov if worst is None else min(worst, cov) if worst >= DEN: return worst - DEN # >= 0 verifies a fractional cover # v = 1 exactly: floor rounding cannot close; recover the rational vertex from fractions import Fraction yf = [Fraction(float(x)).limit_denominator(10 ** 6) if x > 1e-12 else Fraction(0) for x in y] for q in QS: if sum(yf[OFF[q]:OFF[q] + q]) > 1: return worst - DEN cmin = min(sum(yf[OFF[q] + (-s) % q] + yf[OFF[q] + (-s - 2) % q] for q in QS) for s in D) return 0 if cmin >= 1 else worst - DEN # 0: exact rational cover, coverage >= 1 def decide(D): v, y, w = lp(D) if v < 1 - 1e-9: d = exact_deficit(D, w) return v, ('DEFICIT' if d else 'deficit-unverified'), d sl = exact_silent(D, y) return v, ('SILENT' if sl >= 0 else 'silent-unverified'), sl def f1_list(D): c = {q: Counter() for q in QS} out = [] for n, s in enumerate(D, 1): for q in QS: c[q][(-s) % q] += 1 c[q][(-s - 2) % q] += 1 out.append(n - sum(max(c[q].values()) for q in QS)) return out def frontier(sl, hi): """Smallest n <= hi with v(prefix_n) < 1 (bisection, v non-increasing).""" memo = {} def dec(n): if n not in memo: memo[n] = decide(sl[:n]) return memo[n] if dec(hi)[0] >= 1 - 1e-9: return None, memo lo_n, hi_n = 1, hi while lo_n < hi_n: m = (lo_n + hi_n) // 2 if dec(m)[0] < 1 - 1e-9: hi_n = m else: lo_n = m + 1 dec(lo_n) if lo_n > 1: dec(lo_n - 1) return lo_n, memo def frozen(): a = 9409 sl = rw.slots_from(a, 70, OLD) f1 = f1_list(sl) print('## (3) Weighted frontier on the frozen support a = 9409 (exact LP value v(n))') print('n L F1 v(n) verdict exact check') for n in range(1, 71): v, verdict, ex = decide(sl[:n]) L = sl[n - 1] - a + 1 if verdict == 'DEFICIT': chk = f'sum_q max_b W = {ex[0]} < W(D) = {ex[1]}' elif verdict == 'SILENT': chk = f'integer fractional cover, slack {ex} / {DEN}' else: chk = str(ex) print(f'{n:<4d} {L:<6d} {f1[n-1]:<4d} {v:.10f} {verdict:<19s} {chk}') log('frozen done %.1fs' % (time.time() - T0)) def census(a0, step, count): NMAX = 90 print(f'## (1)+(2) Census over supports a = {a0} + {step}k, k = 0..{count - 1} (p = {P}, prefixes n <= {NMAX})') print('a n* L* F1(n*) v(n*-1) v(n*) tight prefixes: n/L/branch/witness/v/weighted') st = Counter() dead_pos = Counter() dead_off = Counter() fr_L = [] for k in range(count): a = a0 + step * k sl = rw.slots_from(a, NMAX, OLD) f1 = f1_list(sl) ns, memo = frontier(sl, NMAX) st['supports'] += 1 tights = [n for n in range(1, NMAX + 1) if f1[n - 1] == 0] parts = [] for n in tights: D = sl[:n] c, M, am = rw.capacity(D, QS) v_, why, wit, nodes = rw.tight_verdict(D, QS, M, am, 0) vv, verdict, ex = memo[n] if n in memo else decide(D) st['tight'] += 1 st['tight_' + v_] += 1 st['branch_' + why] += 1 st['tight_weighted_' + verdict] += 1 if why == 'argmax_disjoint_tiling_absent': st['tiling_branch_weighted_' + verdict] += 1 if why == 'slot_in_no_argmax_kill_set': dead_pos[wit] += 1 dead_off[wit - a] += 1 wtxt = f's={wit}' elif why == 'argmax_disjoint_tiling_absent': wtxt = f'nodes={nodes}' else: wtxt = 'cover' parts.append(f'{n}/{sl[n-1]-a+1}/{why.split("_")[0]}/{wtxt}/{vv:.4f}/{verdict}') if ns is None: st['no_frontier_le_NMAX'] += 1 print(f'{a:<7d} - - - - - ' + '; '.join(parts)) continue v1 = memo[ns][0] v0 = memo[ns - 1][0] if ns > 1 else float('nan') ok = memo[ns][1] == 'DEFICIT' and (ns == 1 or memo[ns - 1][1] == 'SILENT') st['frontier_exact' if ok else 'frontier_unverified'] += 1 if f1[ns - 1] < 0: st['frontier_F1_negative'] += 1 Ls = sl[ns - 1] - a + 1 fr_L.append(Ls) print(f'{a:<7d} {ns:<3d} {Ls:<6d} {f1[ns-1]:<7d} {v0:.10f} {v1:.10f} ' + ('; '.join(parts) if parts else '(no tight prefix)')) if k % 20 == 19: log(f'k={k} {time.time() - T0:.0f}s') print('') print('summary: ' + '; '.join(f'{k}={st[k]}' for k in sorted(st))) if fr_L: print(f'weighted frontier L*: min {min(fr_L)}, median {sorted(fr_L)[len(fr_L)//2]}, max {max(fr_L)}') print('dead-slot absolute positions (count): ' + ', '.join(f'{s}:{c}' for s, c in sorted(dead_pos.items()))) print(f'distinct dead-slot positions: {len(dead_pos)}; distinct offsets from a: {len(dead_off)}') log('census done %.1fs' % (time.time() - T0)) if __name__ == '__main__': if sys.argv[1] == 'frozen': frozen() else: census(int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))