#!/usr/bin/env python3 """ paritysplit_gen.py — Wave 42 GENERALISED covering-parity case split for term-freeing instances on arbitrary-residual seeds. This file is a copy of wave7/parity/paritysplit.py (which is NOT modified — the campaign's decided instances were built with it) with build_instance and the case enumeration generalised from "exactly one wrong entry, have-0/want-1" to any residual: any number of wrong entries, either sign, vector covering targets computed from the residual as built. The generalisation is regression-checked to reproduce the stock enumeration EXACTLY on already-decided instances (wave42/regress.py; record in wave42/REPORT.md). Method. Freeze all seed terms except `free`; the freed terms must reproduce the residual R = D^3*T - sum(frozen) in the scaled-integer encoding of termfree.py (D = lcm of seed and coefficient denominators; freed entries range over the finite set A = {D*s : s in coeff_set}). Let `entries` be the seed's wrong entries (the stock driver asserted exactly one, with have 0 / want 1; this copy accepts any nonempty set, either sign). In ANY solution of the full instance, the equation at each wrong entry e reads sum_{t in free} U_t[e0]*V_t[e1]*W_t[e2] = R[e] (scaled ints) so each freed term contributes a VECTOR of covering products, one component per wrong entry. The achievable vectors are computed exactly from the entries' (slot, row) coordinates: a term's entries at those coordinates range over A, and the vector set is the set of per-entry products over all assignments (capturing the coupling when two entries share a coordinate; for a single entry the vector set is the stock P = {a*b*c : a,b,c in A}). The cases are exactly the tuples of achievable vectors whose componentwise sum is the target vector (R[e])_e: pairwise disjoint (a solution's vector tuple is unique) and exhaustive (every solution has one). Each case adds the constraints prod_t(e) == v_t[e] for every wrong entry e to the full 729-equation instance and is decided by a fresh z3 Solver. UNSAT on every case = sound UNSAT of the whole instance (for this free-set + coefficient set, rest frozen). Any case left unrun or unknown leaves the instance UNDECIDED — reported as such, never as UNSAT. For coeff "1" (A={0,+-1}, P={-1,0,1}) and R[e]=+1 this reproduces Wave 6's split exactly: free-4 -> 16 cases (4 single-cover "A", 12 triple-cover "B"); free-3 -> 6 cases. For coeff "h1" (D=2, A={0,+-1,+-2}, P={0,+-1,+-2,+-4,+-8}) and R[e]=8 the enumeration is by construction (all vectors in P^free summing to 8). Usage: paritysplit_gen.py [--list] [--cases i,j,...] [--max-cases N] Cases run most-pinned first (more covering terms, then larger total |product| — Wave 6 evidence: triple-cover cases decided fastest). Every case outcome is appended to OUTCOMES.md immediately. On SAT: assemble, exact Fraction self-check, save to . verify.py is NOT imported; the caller CLI-verifies any saved file. """ import itertools import json import sys import time from fractions import Fraction from math import gcd import numpy as np import os # noqa: E402 _HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, _HERE) from termfree import COEFF_SETS, lcm, target333, fmt # noqa: E402 LOG = os.path.join(_HERE, "OUTCOMES.md") def logline(msg): line = f"- [{time.strftime('%H:%M:%S')}] {msg}" print(line, flush=True) with open(LOG, "a") as f: f.write(line + "\n") def build_instance(seed_path, free, cs_name): """Return (F, r, D, allowed, R, entries, targets), scaled ints.""" S = COEFF_SETS[cs_name] d = json.load(open(seed_path)) assert (d["a"], d["b"], d["c"]) == (3, 3, 3) F = {name: [[Fraction(x) if isinstance(x, str) else Fraction(x) for x in row] for row in d[name]] for name in ("U", "V", "W")} r = len(F["U"][0]) D = 1 for name in ("U", "V", "W"): for row in F[name]: for x in row: D = lcm(D, x.denominator) for s in S: D = lcm(D, s.denominator) A = {name: np.array([[int(D * x) for x in row] for row in F[name]], dtype=np.int64) for name in ("U", "V", "W")} # the seed's own wrong entries (unscaled check on the seed itself) # GENERALISED (Wave 42): the stock driver asserted exactly one # wrong entry with diff == +D**3 (on-support have-0/want-1). # This copy accepts any nonempty set of wrong entries, either # sign; the covering targets are R[e] as computed, per entry. T = target333() seedT = np.einsum("pt,qt,st->pqs", A["U"], A["V"], A["W"]) diff = (D ** 3) * T - seedT wrong = np.argwhere(diff != 0) assert len(wrong) >= 1, "seed has no wrong entries — nothing to repair" entries = [tuple(int(x) for x in w) for w in wrong] frozen = [t for t in range(r) if t not in free] R = (D ** 3) * T - np.einsum("pt,qt,st->pqs", A["U"][:, frozen], A["V"][:, frozen], A["W"][:, frozen]) allowed = sorted(int(D * s) for s in S) targets = [int(R[e]) for e in entries] return F, r, D, allowed, R, entries, targets def enumerate_cases(free, allowed, entries, targets): """Achievable covering vectors + the case list (see docstring). Returns (VS, cases): VS is the sorted list of achievable covering vectors (tuples, one component per wrong entry); cases are tuples of vectors, one per freed term, whose componentwise sum is `targets`. Order: most-pinned first (more nonzero components, then larger total |.|, then the tuple itself). For a single entry this reproduces the stock order exactly: the stock sort was stable over lexicographic product order, which the explicit tuple tiebreak reproduces. """ coords = [] for e in entries: for slot in range(3): key = (slot, e[slot]) if key not in coords: coords.append(key) vecs = set() for assign in itertools.product(allowed, repeat=len(coords)): val = dict(zip(coords, assign)) vec = [] for e in entries: p = 1 for slot in range(3): p *= val[(slot, e[slot])] vec.append(p) vecs.add(tuple(vec)) VS = sorted(vecs) targets = tuple(targets) maxabs = max(abs(x) for v in VS for x in v) if VS else 0 cases = [] def rec(i, acc, chosen): if i == len(free): if tuple(acc) == targets: cases.append(tuple(chosen)) return rem = (len(free) - i) * maxabs if any(abs(targets[j] - acc[j]) > rem for j in range(len(entries))): return for v in VS: chosen.append(v) rec(i + 1, [acc[j] + v[j] for j in range(len(entries))], chosen) chosen.pop() rec(0, [0] * len(entries), []) cases.sort(key=lambda cs: (-sum(1 for v in cs for x in v if x != 0), -sum(abs(x) for v in cs for x in v), cs)) return VS, cases def case_spec(free, v): if len(v[0]) == 1: return ",".join(f"{t}:{vec[0]:+d}" for t, vec in zip(free, v)) return ",".join( f"{t}:(" + ",".join(f"{x:+d}" for x in vec) + ")" for t, vec in zip(free, v)) def main(): args = [a for a in sys.argv[1:] if not a.startswith("--")] opts = [a for a in sys.argv[1:] if a.startswith("--")] seed_path, free_csv, cs_name = args[0], args[1], args[2] cap = int(args[3]) out_path, tag = args[4], args[5] free = sorted(int(x) for x in free_csv.split(",")) F, r, D, allowed, R, entries, targets = build_instance( seed_path, free, cs_name) P, cases = enumerate_cases(free, allowed, entries, targets) logline(f"**{tag}**: seed={seed_path} free={free} coeff={cs_name} " f"D={D} allowed={allowed} P={P} wrong entries={entries} " f"R[entries]={targets} " f"residual_nnz={int(np.count_nonzero(R))} " f"cases={len(cases)}**") if "--list" in opts: for i, v in enumerate(cases): print(f" case {i}: [{case_spec(free, v)}]") return 0 sel = None for o in opts: if o.startswith("--cases="): sel = [int(x) for x in o.split("=")[1].split(",")] max_cases = None for o in opts: if o.startswith("--max-cases="): max_cases = int(o.split("=")[1]) todo = sel if sel is not None else list(range(len(cases))) if max_cases is not None: todo = todo[:max_cases] import z3 for ci in todo: v = cases[ci] spec = case_spec(free, v) U = {t: [z3.Int(f"U_{p}_{t}") for p in range(9)] for t in free} V = {t: [z3.Int(f"V_{q}_{t}") for q in range(9)] for t in free} W = {t: [z3.Int(f"W_{s}_{t}") for s in range(9)] for t in free} s = z3.Solver() s.set("timeout", cap * 1000) for M in (U, V, W): for t in free: for var in M[t]: s.add(z3.Or([var == a for a in allowed])) for p in range(9): for q in range(9): for ss in range(9): expr = 0 for t in free: expr = expr + U[t][p] * V[t][q] * W[t][ss] s.add(expr == int(R[p, q, ss])) for t, vt in zip(free, v): for j, e in enumerate(entries): s.add(U[t][e[0]] * V[t][e[1]] * W[t][e[2]] == vt[j]) t0 = time.time() res = s.check() dt = time.time() - t0 ctag = f"{tag} case {ci}/{len(cases) - 1} [{spec}]" if res == z3.sat: m = s.model() outF = {name: [row[:] for row in F[name]] for name in ("U", "V", "W")} for t in free: for p in range(9): outF["U"][p][t] = Fraction(m[U[t][p]].as_long(), D) outF["V"][p][t] = Fraction(m[V[t][p]].as_long(), D) outF["W"][p][t] = Fraction(m[W[t][p]].as_long(), D) T = target333() wrong = sum( 1 for p in range(9) for q in range(9) for ss in range(9) if sum(outF["U"][p][t] * outF["V"][q][t] * outF["W"][ss][t] for t in range(r)) != T[p, q, ss]) if wrong == 0: out = {"a": 3, "b": 3, "c": 3, "field": "Q", "U": [[fmt(x) for x in row] for row in outF["U"]], "V": [[fmt(x) for x in row] for row in outF["V"]], "W": [[fmt(x) for x in row] for row in outF["W"]]} with open(out_path, "w") as f: json.dump(out, f) logline(f"**{ctag}: SAT in {dt:.1f}s — assembled " f"self-check 0/729, SAVED {out_path} — " f"CANDIDATE RECORD, CLI-verify fresh**") return 0 logline(f"{ctag}: SAT but self-check {wrong} wrong — " f"ENCODING BUG, do not trust") return 2 if res == z3.unsat: logline(f"{ctag}: UNSAT in {dt:.1f}s") else: logline(f"{ctag}: NO CONCLUSION (unknown at {cap}s cap, " f"wall {dt:.1f}s)") logline(f"{tag}: case batch done ({len(todo)} of {len(cases)} cases " f"attempted)") return 0 if __name__ == "__main__": sys.exit(main())