#!/usr/bin/env python3 """tightcert - compact certificates for two-class residue cover instances. An instance is a pair (D, Q): a finite set of admissible "slots" D of integers and a finite set of moduli Q. For q in Q and phase b in Z/q let K(q,b) = { s in D : s = -b or s = -(b+2) (mod q) }, the slots killed by choosing phase b at modulus q. A *cover* is a choice of one phase per modulus whose union is D. This is the shape solveathome's twin-prime route 4 reduces its phase-domain CSP to. This module decides such instances and emits small, independently checkable certificates - no SAT solver, no resolution or LRAT proof. Rules, in increasing generality, all sound: counting F1 = |D| - sum_q max_b |K(q,b)| > 0 => non-coverable. tight F1 = 0 forces any cover to attain every per-modulus maximum with pairwise DISJOINT kill sets (rigidity: |D| = |union| <= sum|K| <= sum max = |D|), so either an exact tiling exists (=> coverable, with an explicit model) or the instance is refuted by a slot in no argmax kill set, or by an exhausted disjoint-tiling search. weighted w >= 0 on D with sum_q max_b W(q,b) < W(D), W(q,b) = sum_{s in K(q,b)} w_s => non-coverable. This is the LP relaxation of `counting`: w = 1_D reproduces F1 exactly. Its optimum is m* = max_mu min_{s in D} P_mu(s killed) over independent per-modulus phase distributions mu (LP duality), so a weighted certificate exists iff m* < 1, and its optimum is attained at a rational w. weighted_exhausted a rational mu with min_{s in D} P_mu(s killed) >= 1 is a certificate that NO weighted certificate exists here: the relaxation is provably exhausted at this instance. It says nothing about coverability. Negative results are certificates too: `weighted_exhausted` is the honest bounded negative for the weighted family, and every certificate (either direction) is re-checked with exact rational arithmetic by `verify`. All rules are cross-checked against `oracle`, an independent complete search over phase assignments that uses none of the above reasoning. CLI python3 tightcert.py certify --input frozen.json [--json] [--no-weights] python3 tightcert.py certify --p 97 --a 9409 --L 4432 python3 tightcert.py verify --cert cert.json --input frozen.json python3 tightcert.py selftest [--json] """ import os # Deterministic linear algebra: a threaded BLAS can sum in a different order and # change the last bits, which would break a byte-stable artifact and could round a # rational certificate differently. Set before numpy is imported. for _v in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): os.environ.setdefault(_v, '1') import argparse # noqa: E402 import hashlib # noqa: E402 import json # noqa: E402 import sys # noqa: E402 import time # noqa: E402 from fractions import Fraction # noqa: E402 from math import gcd # noqa: E402 import numpy as np # noqa: E402 T0 = time.time() sys.stdout.reconfigure(newline='\n') # byte-stable artifact on any platform def log(*a): print(*a, file=sys.stderr) # ----------------------------------------------------------------- primitives def is_prime(n): return n >= 2 and all(n % d for d in range(2, n) if d * d <= n) def prime_band(p, a, L): """(old primes <= p, Q = primes in (p,2p], admissible twin starts in [a,a+L)).""" old = [n for n in range(2, p + 1) if is_prime(n)] qs = [n for n in range(p + 1, 2 * p + 1) if is_prime(n)] D = [s for s in range(a, a + L) if all(s % r and (s + 2) % r for r in old)] return old, qs, D def kill_matrix(D, qs): """A[q] = boolean (q x |D|), A[q][b,i] = phase b at q kills D[i].""" Dn = np.asarray(D, dtype=np.int64) out = {} for q in qs: b = np.arange(q, dtype=np.int64)[:, None] out[q] = (((Dn[None, :] + b) % q == 0) | ((Dn[None, :] + b + 2) % q == 0)) return out def capacity(D, qs): """M[q] = max_b |K(q,b)|, the maximising phases, and the bitmasks.""" A = kill_matrix(D, qs) M, am, masks = {}, {}, {} for q in qs: sizes = A[q].sum(axis=1) M[q] = int(sizes.max()) am[q] = tuple(int(b) for b in np.nonzero(sizes == M[q])[0]) masks[q] = [int(''.join('1' if v else '0' for v in A[q][b][::-1]), 2) for b in range(q)] return M, am, masks def budget(D, qs): """(F1, M). F1 > 0 => counting certificate fires.""" M, _, _ = capacity(D, qs) return len(D) - sum(M.values()), M def cover_from_phases(D, qs, phases): K = set() for q, b in zip(qs, phases): K.update(s for s in D if (s + b) % q == 0 or (s + b + 2) % q == 0) return set(D) <= K, sorted(set(D) - K) def oracle(D, qs, cap=2_000_000, witness=None): """Independent decision: complete search over phase assignments. Slots and moduli are bitmasks. Three admissible devices only: * unit propagation: an uncovered slot no unused modulus can kill fails; * the counting bound: with U uncovered, the unused moduli kill at most sum_q max_b |K(q,b) cap U| slots of U, so a deficit refutes U (and D); * MRV branching on the uncovered slot with the fewest remaining killers. It never uses a per-modulus maximum of D, an argmax set, or the rigidity lemma, so it is independent of every certificate rule here. Returns (coverable, nodes); raises RuntimeError past `cap` nodes. If `witness` is a list it is filled with the chosen (q, b) pairs of a cover when coverable and cleared otherwise, so a caller can emit an explicit model. """ if not D: return True, 0 D = sorted(D) A = kill_matrix(D, qs) kmask = {q: [int(''.join('1' if v else '0' for v in A[q][b][::-1]), 2) for b in range(q)] for q in qs} cand = {q: 0 for q in qs} for q in qs: for mk in kmask[q]: cand[q] |= mk qlist = list(qs) nodes = [0] def kills_of(U, q): best = 0 for mk in kmask[q]: c = (mk & U).bit_count() if c > best: best = c return best def rec(U, unused): nodes[0] += 1 if nodes[0] > cap: raise RuntimeError('oracle node cap exceeded') if U == 0: return True if sum(kills_of(U, q) for q in unused) < U.bit_count(): return False # MRV: uncovered slot with the fewest remaining killers best_s, best_deg, best_qs = None, None, None Uu = U while Uu: s = (Uu & -Uu).bit_length() - 1 Uu &= Uu - 1 ok = [q for q in unused if cand[q] >> s & 1] if not ok: return False # unit propagation if best_deg is None or len(ok) < best_deg: best_s, best_deg, best_qs = s, len(ok), ok if best_deg == 1: break for q in best_qs: for b in ((-D[best_s]) % q, (-D[best_s] - 2) % q): if rec(U & ~kmask[q][b], unused - {q}): return True return False full = (1 << len(D)) - 1 chosen = [] def rec2(U, unused): nodes[0] += 1 if nodes[0] > cap: raise RuntimeError('oracle node cap exceeded') if U == 0: return True if sum(kills_of(U, q) for q in unused) < U.bit_count(): return False best_s, best_deg, best_qs = None, None, None Uu = U while Uu: s = (Uu & -Uu).bit_length() - 1 Uu &= Uu - 1 ok = [q for q in unused if cand[q] >> s & 1] if not ok: return False if best_deg is None or len(ok) < best_deg: best_s, best_deg, best_qs = s, len(ok), ok if best_deg == 1: break for q in best_qs: for b in ((-D[best_s]) % q, (-D[best_s] - 2) % q): chosen.append((q, b)) if rec2(U & ~kmask[q][b], unused - {q}): return True chosen.pop() return False coverable = rec2(full, frozenset(qlist)) if witness is not None else rec(full, frozenset(qlist)) if witness is not None: witness[:] = list(chosen) if coverable else [] return coverable, nodes[0] def model_certificate(D, qs, cap=2_000_000): """Explicit covering model as a certificate, or (None, nodes) when there is none. The returned dict is exactly what `verify` accepts for rule 'tiling': one phase per modulus of qs, unused moduli set to 0. Any caller can therefore check the model with `python3 tightcert.py verify`, independently of the search that produced it. """ w = [] try: coverable, nodes = oracle(D, qs, cap=cap, witness=w) except RuntimeError as e: return None, str(e) if not coverable: return None, nodes phase_of = dict(w) return {'kind': 'coverable', 'rule': 'tiling', 'phases': [phase_of.get(q, 0) for q in qs], 'assigned': sorted(phase_of), 'nodes': nodes}, nodes # ------------------------------------------------------------ tight / rigidity def tight_verdict(D, qs, node_cap=2_000_000): """Decide a tight instance (sum_q M(q) == |D|) exactly.""" M, am, masks = capacity(D, qs) assert sum(M.values()) == len(D), 'not tight' idx = {s: i for i, s in enumerate(D)} dead = [s for s in D if not any(masks[q][b] >> idx[s] & 1 for q in qs for b in am[q])] if dead: return 'noncoverable', {'rule': 'tight_dead_slot', 'dead_slots': dead} order = sorted(qs, key=lambda q: (-M[q], q)) full = (1 << len(D)) - 1 nodes = [0] def rec(i, used, picked): nodes[0] += 1 if nodes[0] > node_cap: raise RuntimeError('tiling node cap exceeded') if used == full: return list(picked) if i == len(order): return None if used.bit_count() + sum(M[q] for q in order[i:]) < len(D): return None q = order[i] for b in am[q]: K = masks[q][b] if K & used: continue r = rec(i + 1, used | K, picked + [(q, b)]) if r is not None: return r return None tiling = rec(0, 0, []) if tiling is None: return 'noncoverable', {'rule': 'tight_no_tiling', 'nodes': nodes[0]} return 'coverable', {'rule': 'tiling', 'phases': [b for _, b in tiling], 'nodes': nodes[0]} # ------------------------------------------------------------------ weighted # m* = min_w sum_q max_b W(q,b) (sum w = 1) = max_mu min_s P_mu(s killed). # Both bounds are optimized by exponentiated-gradient ascent/descent on the # relevant simplex, on one stacked boolean matrix A_all (sum(qs) x |D|). def stack(D, qs): A = kill_matrix(D, qs) blocks, starts, sizes = [], [], [] row = 0 for q in qs: starts.append(row) sizes.append(q) blocks.append(A[q]) row += q return np.vstack(blocks), np.array(starts), np.array(sizes), A def per_block_max(vals, starts, sizes): return np.maximum.reduceat(vals, starts) def dual_ascent(D, qs, iters=12000, etas=(0.5, 1.0, 2.0, 4.0)): """Best feasible dual mu found: maximizes min_s P_mu(s killed). Any mu is feasible, so the returned minimum is a valid LOWER bound on m* = max_mu min_s P_mu; >= 1 means no weighted certificate exists at all. Exponentiated-gradient ascent per modulus block, several step constants. """ A_all, starts, sizes, _ = stack(D, qs) m = A_all.shape[0] uniform = np.empty(m) for st, sz in zip(starts, sizes): uniform[st:st + sz] = 1.0 / sz best = (-1.0, None, None) for eta in etas: mu = uniform.copy() for it in range(iters): p = mu @ A_all lo = float(p.min()) if lo > best[0]: best = (lo, mu.copy(), eta) s = int(p.argmin()) mu = mu * np.exp((eta / np.sqrt(it + 1.0)) * A_all[:, s]) blk = np.add.reduceat(mu, starts) mu = mu / np.repeat(blk, sizes) lo, flat, eta = best return lo, {q: flat[st:st + sz].copy() for q, st, sz in zip(qs, starts, sizes)}, eta def weighted_bracket(D, qs, iters=4000, eta_p=1.0, eta_d=1.0, dual_iters=None): """Return (upper, lower, w, mu) with upper >= m* >= lower. upper = a primal w (upper bound on m*; < 1 certifies non-coverability once re-checked exactly). lower = a feasible dual mu (lower bound on m*; >= 1 certifies that no weighted certificate exists). """ A_all, starts, sizes, _ = stack(D, qs) n = len(D) m = A_all.shape[0] # primal: exponentiated gradient on the simplex w = np.full(n, 1.0 / n) best_upper, best_w = None, None for it in range(iters): vals = A_all @ w mx = per_block_max(vals, starts, sizes) f = float(mx.sum()) if best_upper is None or f < best_upper: best_upper, best_w = f, w.copy() arg = np.empty(len(starts), dtype=np.int64) for i, (st, sz) in enumerate(zip(starts, sizes)): arg[i] = st + int(vals[st:st + sz].argmax()) g = A_all[arg].sum(axis=0) step = eta_p / np.sqrt(it + 1.0) w = w * np.exp(-step * g) tot = w.sum() w = w / tot if tot > 0 else np.full(n, 1.0 / n) # dual: multiplicative weights on each modulus' phase distribution mu_all = np.full(m, 0.0) for st, sz in zip(starts, sizes): mu_all[st:st + sz] = 1.0 / sz best_lower = -1.0 for it in range(iters): p = mu_all @ A_all lo = float(p.min()) if lo > best_lower: best_lower = lo s_star = int(p.argmin()) step = eta_d / np.sqrt(it + 1.0) mu_all = mu_all * np.exp(step * A_all[:, s_star]) for st, sz in zip(starts, sizes): blk = mu_all[st:st + sz] mu_all[st:st + sz] = blk / blk.sum() p = mu_all @ A_all best_lower = max(best_lower, float(p.min())) # a deeper, multi-step-constant dual ascent usually beats the inline loop mu = {q: mu_all[st:st + sz].copy() for q, st, sz in zip(qs, starts, sizes)} deep_lo, deep_mu, _ = dual_ascent(D, qs, iters=dual_iters or max(2000, iters)) if deep_lo > best_lower: return best_upper, deep_lo, best_w, deep_mu return best_upper, best_lower, best_w, mu def _reduce(ints): g = 0 for x in ints: g = gcd(g, int(x)) return [int(x) // max(1, g) for x in ints] if g else list(map(int, ints)) def primal_candidates(D, qs, mu=None, iters=6000, refine_iters=8000): """Candidate primal weight vectors, best-first. The global exponentiated-gradient descent, then support-restricted descents seeded by the dual optimum's tight set (complementary slackness says the optimal w is supported there), at several tolerances. """ A_all, starts, sizes, A = stack(D, qs) n = len(D) def eg(cols, iters_, eta=1.2): cols = np.asarray(cols) w = np.full(len(cols), 1.0 / len(cols)) best = None for it in range(iters_): vals = (A_all[:, cols] @ w) f = float(per_block_max(vals, starts, sizes).sum()) if best is None or f < best[0]: best = (f, w.copy()) arg = np.empty(len(starts), dtype=np.int64) for i, (st, sz) in enumerate(zip(starts, sizes)): arg[i] = st + int(vals[st:st + sz].argmax()) g = A_all[arg][:, cols].sum(axis=0) w = w * np.exp(-(eta / np.sqrt(it + 1.0)) * g) tot = w.sum() w = w / tot if tot > 0 else np.full(len(cols), 1.0 / len(cols)) return best out = [] gb = eg(np.arange(n), iters) if gb: out.append(gb) if mu is not None: p = np.zeros(n) for q in qs: p += mu[q] @ A[q] for tol in (0.01, 0.03, 0.06, 0.12, 0.25): S = np.nonzero(p <= p.min() + tol)[0] if len(S) == 0 or len(S) == n: continue rb = eg(S, refine_iters) if rb: full = np.zeros(n) full[S] = rb[1] out.append((rb[0], full)) out.sort(key=lambda t: t[0]) return [w for _, w in out] def positive_certificate(D, qs, candidates, scales=(50, 100, 500, 1000, 9999, 10 ** 5, 10 ** 6, 10 ** 7)): """First exactly verified rational w with sum_q max_b W(q,b) < W(D).""" if candidates is not None and not isinstance(candidates, (list, tuple)): candidates = [candidates] for w in candidates or []: w = np.asarray(w, dtype=float) for scale in scales: ints = np.round(w * scale).astype(np.int64) keep = np.nonzero(ints > 0)[0] if len(keep) == 0: continue sub = [D[i] for i in keep] ws = _reduce([ints[i] for i in keep]) ok, ratio = check_weights(sub, qs, ws) if ok: return {'rule': 'weighted', 'slots': sub, 'weights': ws, 'ratio': [ratio.numerator, ratio.denominator]}, ratio return None, None def check_weights(D, qs, weights): """Exact: sum_q max_b W(q,b) < W(D)? Returns (strict, ratio).""" assert len(D) == len(weights) and all(w > 0 for w in weights) total = 0 for q in qs: best = 0 for b in range(q): v = sum(w for s, w in zip(D, weights) if (s + b) % q == 0 or (s + b + 2) % q == 0) best = max(best, v) total += best return total < sum(weights), Fraction(total, sum(weights)) def negative_certificate(D, qs, mu, denoms=(10 ** 3, 10 ** 4, 10 ** 5, 10 ** 6)): """Exact rational mu with min_s P_mu(s killed) >= 1, or None. Such a mu proves m* >= 1, i.e. no weighted certificate of any shape exists for this instance. P_mu(s) = sum_q ( mu_q[(-s) mod q] + mu_q[(-s-2) mod q] ). """ for Dn in denoms: ints = {} for q in qs: v = np.round(np.asarray(mu[q], dtype=float) * Dn).astype(np.int64) v[v < 0] = 0 if v.sum() == 0: return None, None # repair the denominator exactly diff = int(Dn - v.sum()) if diff != 0: j = int(v.argmax()) v[j] = max(0, v[j] + diff) if int(v.sum()) != Dn: break ints[q] = [int(x) for x in v] else: worst = None for s in D: tot = sum(ints[q][(-s) % q] + ints[q][(-s - 2) % q] for q in qs) if worst is None or tot < worst: worst = tot if worst is not None and worst >= Dn: return {'rule': 'weighted_exhausted', 'denominator': Dn, 'mu': {str(q): ints[q] for q in qs}, 'min_probability': [worst, Dn]}, Fraction(worst, Dn) return None, None def check_mu(D, qs, mu_ints, denom): """Exact: min_s sum_q (mu_q[(-s)%q]+mu_q[(-s-2)%q]) >= denom?""" for q in qs: if sum(mu_ints[str(q)]) != denom: return False, None if any(x < 0 for x in mu_ints[str(q)]): return False, None worst = None for s in D: tot = sum(mu_ints[str(q)][(-s) % q] + mu_ints[str(q)][(-s - 2) % q] for q in qs) worst = tot if worst is None else min(worst, tot) return worst >= denom, Fraction(worst, denom) # ----------------------------------------------------------------- the unified def certify(D, qs, weights=True, iters=4000, dual_iters=None, force_weights=False): """Decide a cover instance. force_weights skips the counting/tight shortcuts, which is how the frozen (tight) instance is also given a weighted certificate.""" D = sorted(D) M, _, _ = capacity(D, qs) f1 = len(D) - sum(M.values()) out = {'instance': {'N': len(D), 'Q': list(qs), 'sum_M': sum(M.values()), 'F1': f1, 'D_sha256': hashlib.sha256(','.join(map(str, D)).encode()).hexdigest()}, 'M': [M[q] for q in qs]} if not force_weights: if f1 > 0: out.update({'kind': 'noncoverable', 'rule': 'counting'}) return out if f1 == 0: kind, det = tight_verdict(D, qs) out.update({'kind': kind, **det}) return out out.update({'kind': 'undecided', 'rule': 'none'}) if weights: upper, lower, w, mu = weighted_bracket(D, qs, iters=iters, dual_iters=dual_iters) out['weighted'] = {'ratio_upper': round(upper, 9), 'ratio_lower': round(lower, 9)} cands = primal_candidates(D, qs, mu=mu, iters=max(2000, iters), refine_iters=max(4000, iters)) pos, ratio = positive_certificate(D, qs, cands) if pos: out.update({'kind': 'noncoverable', 'rule': 'weighted', 'slots': pos['slots'], 'weights': pos['weights'], 'ratio': pos['ratio']}) return out neg, bound = negative_certificate(D, qs, mu) if neg: out.update({'kind': 'undecided', 'rule': 'weighted_exhausted', 'denominator': neg['denominator'], 'mu': neg['mu'], 'min_probability': neg['min_probability']}) else: out.update({'kind': 'undecided', 'rule': 'none'}) return out def verify(cert, D, qs): """Re-check a certificate exactly. Returns (ok, [(name, ok), ...]).""" D = sorted(D) checks = [] rule = cert.get('rule', 'none') if rule == 'counting': f1, M = budget(D, qs) checks.append((f'counting: F1 = {f1} > 0', f1 > 0)) checks.append((f'counting: sum_q M(q) = {sum(M.values())} < |D| = {len(D)}', sum(M.values()) < len(D))) elif rule in ('tight_dead_slot', 'tight_no_tiling'): M, am, masks = capacity(D, qs) idx = {s: i for i, s in enumerate(D)} checks.append((f'{rule}: tight, sum_q M(q) = {sum(M.values())} = |D| = {len(D)}', sum(M.values()) == len(D))) if rule == 'tight_dead_slot': ok = True for s in cert['dead_slots']: checks.append((f'{rule}: slot {s} is in D', s in D)) for q in qs: for b in am[q]: if masks[q][b] >> idx[s] & 1: ok = False checks.append((f'{rule}: no argmax phase kills {cert["dead_slots"]}', ok)) else: order = sorted(qs, key=lambda q: (-M[q], q)) full = (1 << len(D)) - 1 def rec(i, used): if used == full: return True if i == len(order): return False if used.bit_count() + sum(M[q] for q in order[i:]) < len(D): return False for b in am[order[i]]: K = masks[order[i]][b] if not (K & used) and rec(i + 1, used | K): return True return False checks.append((f'{rule}: a fresh disjoint-tiling search finds none', rec(0, 0) is False)) elif rule == 'weighted': ok, ratio = check_weights(cert['slots'], qs, cert['weights']) checks.append((f'weighted: sum_q max_b W(q,b)/W(D) = {ratio} < 1', ok)) checks.append((f'weighted: every weighted slot is in D', all(s in D for s in cert['slots']))) elif rule == 'weighted_exhausted': ok, prob = check_mu(D, qs, cert['mu'], cert['denominator']) checks.append((f'weighted_exhausted: min_s P_mu(s killed) = {prob} >= 1', ok)) elif rule == 'tiling': ok, un = cover_from_phases(D, qs, cert['phases']) checks.append((f'tiling: phases cover all {len(D)} slots', ok and not un)) elif rule == 'oracle_exhaustive': # Weakest but still re-runnable: the independent phase search is re-run. try: truth, nodes = oracle(D, qs, cap=cert.get('oracle_nodes', 0) + 2_000_000) checks.append((f'oracle_exhaustive: independent phase search finds no ' f'cover ({nodes} nodes)', truth is False)) except RuntimeError as e: checks.append((f'oracle_exhaustive: oracle capped ({e})', False)) else: checks.append(('undecided: nothing to verify', True)) return all(v for _, v in checks), checks # ------------------------------------------------------------------- selftest def selftest(max_a=40, oracle_cap=8000, iters=200, dual_iters=500): """Validate every rule against the oracle on many small instances. An instance whose independent oracle search exceeds `oracle_cap` nodes is skipped rather than decided, so the run is bounded and deterministic; the skipped count is reported so the coverage is honest. """ stat = {'instances': 0, 'skipped': 0, 'agree': 0, 'disagree': 0, 'undecided': 0, 'by_rule': {}, 'cert_failures': 0, 'unsound': 0} bad = [] for p in (13, 17, 19, 23): for L in (12, 20, 30, 45, 60, 90): for a in range(3, max_a): _, qs, D = prime_band(p, a, L) if not D: continue try: truth, _ = oracle(D, qs, cap=oracle_cap) except RuntimeError: stat['skipped'] += 1 continue res = certify(D, qs, iters=iters, dual_iters=dual_iters) rule = res.get('rule', 'none') stat['instances'] += 1 stat['by_rule'][rule] = stat['by_rule'].get(rule, 0) + 1 ok, checks = verify(res, D, qs) if not ok: stat['cert_failures'] += 1 bad.append((p, a, L, len(D), 'CERTIFICATE FAILED', rule, [c for c in checks if not c[1]])) if res['kind'] == 'undecided': stat['undecided'] += 1 continue if (res['kind'] == 'coverable') == truth: stat['agree'] += 1 else: stat['disagree'] += 1 bad.append((p, a, L, len(D), truth, res['kind'], rule)) if truth and rule == 'weighted': stat['unsound'] += 1 bad.append((p, a, L, len(D), 'weighted certificate on a COVERABLE instance', rule)) return stat, bad # ------------------------------------------------------------------------ CLI def load_instance(args): """Build (p, a, L, qs, D) from either a prime band or an explicit instance. An input file may carry either shape: band {"p": 97, "a": 9409, "L": 4432, "cap": 32768} explicit {"D": [9419, ...], "Q": [101, ...]} <- any covering instance The explicit form is what lets another agent point this toolkit at its own frozen instance without reproducing a prime-band convention. """ if args.input: meta = json.load(open(args.input, encoding='utf-8')) if 'D' in meta and 'Q' in meta: D = sorted(set(int(s) for s in meta['D'])) qs = [int(q) for q in meta['Q']] return meta.get('p', ''), meta.get('a', ''), meta.get('L', ''), qs, D p, a = meta['p'], meta['a'] L = args.L or meta.get('L') cap = args.cap or meta.get('cap', 32768) _, qs, slots = prime_band(p, a, cap) return p, a, L, qs, [s for s in slots if s < a + L] _, qs, D = prime_band(args.p, args.a, args.L) return args.p, args.a, args.L, qs, D def main(): ap = argparse.ArgumentParser(description='tightcert - compact cover certificates') sub = ap.add_subparsers(dest='cmd', required=True) c = sub.add_parser('certify') c.add_argument('--p', type=int, default=97) c.add_argument('--a', type=int, default=9409) c.add_argument('--L', type=int, default=4432) c.add_argument('--cap', type=int, default=32768) c.add_argument('--input') c.add_argument('--no-weights', action='store_true') c.add_argument('--force-weights', action='store_true') c.add_argument('--iters', type=int, default=4000) c.add_argument('--dual-iters', type=int, default=None) c.add_argument('--json', action='store_true') v = sub.add_parser('verify') v.add_argument('--cert', required=True) v.add_argument('--p', type=int, default=97) v.add_argument('--a', type=int, default=9409) v.add_argument('--L', type=int, default=4432) v.add_argument('--cap', type=int, default=32768) v.add_argument('--input') s = sub.add_parser('selftest') s.add_argument('--json', action='store_true') s.add_argument('--max-a', type=int, default=40) s.add_argument('--oracle-cap', type=int, default=8000) s.add_argument('--iters', type=int, default=200) sol = sub.add_parser('solve') sol.add_argument('--p', type=int, default=97) sol.add_argument('--a', type=int, default=9409) sol.add_argument('--L', type=int, default=4432) sol.add_argument('--cap', type=int, default=32768) sol.add_argument('--input') sol.add_argument('--no-weights', action='store_true') sol.add_argument('--force-weights', action='store_true') sol.add_argument('--iters', type=int, default=4000) sol.add_argument('--dual-iters', type=int, default=None) sol.add_argument('--oracle-cap', type=int, default=2_000_000) sol.add_argument('--json', action='store_true') args = ap.parse_args() if args.cmd == 'selftest': stat, bad = selftest(args.max_a, oracle_cap=args.oracle_cap, iters=args.iters) if args.json: print(json.dumps({'stat': stat, 'bad': bad[:10]}, indent=1, sort_keys=True)) else: print(f'instances {stat["instances"]} agree {stat["agree"]} ' f'disagree {stat["disagree"]} undecided {stat["undecided"]} ' f'skipped(oracle cap) {stat["skipped"]}') print('rules used: ' + json.dumps(stat['by_rule'], sort_keys=True)) print(f'certificate re-checks failed {stat["cert_failures"]}, ' f'unsound claims {stat["unsound"]}') for b in bad[:10]: print(' BAD', b) print('SELFTEST ' + ('PASS' if stat['disagree'] == 0 and stat['cert_failures'] == 0 and stat['unsound'] == 0 else 'FAIL')) return 0 if (stat['disagree'] == 0 and stat['cert_failures'] == 0 and stat['unsound'] == 0) else 1 p, a, L, qs, D = load_instance(args) if args.cmd == 'certify': res = certify(D, qs, weights=not args.no_weights, iters=args.iters, dual_iters=args.dual_iters, force_weights=args.force_weights) truth, nodes = oracle(D, qs) res['oracle'] = {'coverable': truth, 'nodes': nodes} res['instance'].update({'p': p, 'a': a, 'L': L}) ok, checks = verify(res, D, qs) res['last_check_ok'] = ok if args.json: print(json.dumps(res, indent=1, sort_keys=True)) return 0 print(f'p={p} a={a} L={L} |D|={len(D)} sum_q M(q)={res["instance"]["sum_M"]} ' f'F1={res["instance"]["F1"]}') print(f'verdict: {res["kind"]} rule: {res.get("rule")}') print(f'oracle (independent phase search): coverable={truth} ({nodes} nodes)') if 'weighted' in res: print(f'weighted ratio bracket [lower, upper] = ' f'[{res["weighted"]["ratio_lower"]:.6f}, {res["weighted"]["ratio_upper"]:.6f}]' f' (a certificate needs < 1)') if res.get('rule') == 'weighted': print(f'weight certificate ratio {res["ratio"][0]}/{res["ratio"][1]} ' f'on {len(res["slots"])} slots') if res.get('rule') == 'weighted_exhausted': print(f'exhausted certificate: min_s P_mu = {res["min_probability"][0]}/' f'{res["min_probability"][1]} >= 1 (no weighted certificate exists)') if res.get('rule') == 'tight_dead_slot': print(f'dead slot(s): {res["dead_slots"]}') print('certificate re-check: ' + ('PASS' if ok else 'FAIL ' + str(checks))) return 0 if args.cmd == 'solve': # One entry point for a foreign instance. The certificate rules try # first and give a compact refutation; if all of them are silent - which # includes `weighted_exhausted`, a bounded NEGATIVE about the weighted # family and not a verdict on the instance - the independent oracle # decides and, when coverable, emits an explicit model. Either way the # answer is a certificate this toolkit re-checks, never just a yes/no. res = certify(D, qs, weights=not args.no_weights, iters=args.iters, dual_iters=args.dual_iters, force_weights=args.force_weights) if res['kind'] == 'undecided': model, detail = model_certificate(D, qs, cap=args.oracle_cap) if model is not None: res = {'instance': res['instance'], 'M': res['M'], 'kind': 'coverable', 'rule': 'tiling', 'phases': model['phases'], 'assigned': model['assigned'], 'nodes': model['nodes']} elif isinstance(detail, int): res = {'instance': res['instance'], 'M': res['M'], 'kind': 'noncoverable', 'rule': 'oracle_exhaustive', 'oracle_nodes': detail} else: res = dict(res, oracle={'result': 'capped', 'detail': detail}) ok, checks = verify(res, D, qs) res['last_check_ok'] = ok res['instance'].update({'p': p, 'a': a, 'L': L}) if args.json: print(json.dumps(res, indent=1, sort_keys=True)) return 0 print(f'|D|={len(D)} |Q|={len(qs)} sum_q M(q)={res["instance"]["sum_M"]} ' f'F1={res["instance"]["F1"]}') if res['kind'] == 'coverable': print(f'COVERABLE: explicit model, phases {res["phases"]} over Q={qs} ' f'(verify re-checks the union)') elif res['kind'] == 'noncoverable': print(f'NON-COVERABLE: rule {res.get("rule")}' + (f', dead slot(s) {res["dead_slots"]}' if res.get('rule') == 'tight_dead_slot' else '') + (f', weight ratio {res["ratio"][0]}/{res["ratio"][1]}' if res.get('rule') == 'weighted' else '')) else: print(f'UNDECIDED: rules silent/bounded (last: {res.get("rule")})' + (f', oracle capped' if res.get('oracle', {}).get('result') == 'capped' else '')) print('certificate re-check: ' + ('PASS' if ok else 'FAIL ' + str(checks))) return 0 cert = json.load(open(args.cert, encoding='utf-8')) ok, checks = verify(cert, D, qs) for name, val in checks: print(f'[{"ok" if val else "FAIL"}] {name}') print('VERIFY ' + ('PASS' if ok else 'FAIL')) return 0 if ok else 1 if __name__ == '__main__': sys.exit(main() or 0)