#!/usr/bin/env python3 """ crosssplit.py — Wave 13 SPLIT: the index-8-cross second-level split, generalised from wave6/deepexact/casesplit.py onto the fracsplit framework (any seed / free-set / coefficient set in {"1","h1","q1"}). Level 1 (inherited, unchanged): the covering-parity split of paritysplit.py — cases are all vectors v in P^free with sum(v) = R[e], case = full 729-equation scaled-integer instance + prod_t(e) == v_t per freed term. Disjoint + exhaustive (see paritysplit.py docstring). Level 2 (new; Wave 6's split, generalised): within a base case, split by the covering terms' total OFF-CENTRE INDEX-8-CROSS MASS m = sum over covering terms t (v_t != 0), factors F in {U,V,W} of |supp(F_t) ∩ OFF(c_F)|, where c_F is the wrong entry e's coordinate for factor F (U: e[0], V: e[1], W: e[2]) and OFF(c) = (row(c) ∪ col(c)) \\ {c} in the 3x3 grid of the 9-vector (index p = 3a+b; row = same a, col = same b). For e = (8,8,8) this is exactly Wave 6's definition: OFF = {2,5,6,7} for every factor (cross C = {2,5,6,7,8} = row 2 ∪ col 2, centre 8 excluded because a covering term is already nonzero there). Sub-cases are the values m = 0..12k (k = number of covering terms; each covering term contributes at most 3 factors x 4 off-centre positions = 12), run sparsest first (m ascending — Wave 6's prescribed order). Disjoint: a solution of the base case has one definite cross mass. Exhaustive: that mass lies in 0..12k, so the solution lies in exactly one sub-case. UNSAT on every sub-case of a base case = sound UNSAT of that base case; UNSAT on every base case = the level-1 result. The encoder core is NOT forked: build_instance / enumerate_cases / case_spec are imported verbatim from paritysplit.py (via the same import path fracsplit.py uses, including fracsplit's "q1" coefficient set registration), and the per-sub-case solver construction copies fracsplit.py's loop exactly, adding only (a) the level-1 product constraints (identical to fracsplit's) and (b) the cross-mass constraint above. On SAT: assemble with Fractions, exact self-check 0/729 required before saving (fracsplit's code path). Usage: crosssplit.py [--list] [--cases i,j,...] [--pattern a,b,c,d] [--max-sub N] Outcomes are appended to wave13/split/OUTCOMES.md immediately. verify.py is NOT imported; the caller CLI-verifies any saved file. """ import itertools import json import sys import time from fractions import Fraction import numpy as np sys.path.insert(0, "wave7/parity") import termfree # noqa: E402 termfree.COEFF_SETS["q1"] = [Fraction(0), Fraction(1), Fraction(-1), Fraction(1, 2), Fraction(-1, 2), Fraction(1, 4), Fraction(-1, 4), Fraction(3, 4), Fraction(-3, 4)] import paritysplit as ps # noqa: E402 (build_instance/enumerate_cases) from termfree import target333, fmt # noqa: E402 LOG = "wave13/split/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 pattern_of(v): return tuple(sorted((abs(x) for x in v), reverse=True)) def off_centre(c): """Off-centre cross positions around grid coordinate c (0..8).""" a, b = divmod(c, 3) cross = {3 * a + j for j in range(3)} | {3 * i + b for i in range(3)} return sorted(cross - {c}) def subcases_for(v, free, e): """Yield (m, covering_terms) descriptors: m ascending (sparsest first), covering = freed terms with v_t != 0.""" covering = [t for t, vt in zip(free, v) if vt != 0] return covering, list(range(0, 12 * len(covering) + 1)) 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, e, target_e = ps.build_instance(seed_path, free, cs_name) P, cases = ps.enumerate_cases(free, allowed, target_e) offs = [off_centre(e[0]), off_centre(e[1]), off_centre(e[2])] logline(f"**{tag} (crosssplit)**: seed={seed_path} free={free} " f"coeff={cs_name} D={D} allowed={allowed} P={P} wrong " f"entry e={e} R[e]={target_e} " f"residual_nnz={int(np.count_nonzero(R))} " f"base_cases={len(cases)} off-centre cross per factor " f"U/V/W={offs}**") sel = None for o in opts: if o.startswith("--cases="): sel = [int(x) for x in o.split("=")[1].split(",")] if o.startswith("--pattern="): pat = tuple(int(x) for x in o.split("=")[1].split(",")) sel = [i for i, v in enumerate(cases) if pattern_of(v) == pat] logline(f"{tag}: pattern {pat} selects base cases {sel}") todo = sel if sel is not None else list(range(len(cases))) if "--list" in opts: total = 0 for ci in todo: v = cases[ci] covering, ms = subcases_for(v, free, e) total += len(ms) print(f" base case {ci}: [{ps.case_spec(free, v)}] " f"pattern={pattern_of(v)} covering={covering} " f"sub-cases m=0..{12 * len(covering)} " f"({len(ms)} sub-cases)") print(f" total sub-cases over selection: {total}") return 0 max_sub = None m_min = None for o in opts: if o.startswith("--max-sub="): max_sub = int(o.split("=")[1]) if o.startswith("--m-min="): m_min = int(o.split("=")[1]) import z3 n_att = 0 n_unsat = 0 for ci in todo: v = cases[ci] spec = ps.case_spec(free, v) covering, ms = subcases_for(v, free, e) if m_min is not None: ms = [m for m in ms if m >= m_min] for m in ms: if max_sub is not None and n_att >= max_sub: logline(f"{tag}: max-sub {max_sub} reached; batch " f"stopped ({n_unsat} UNSAT so far)") return 0 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): s.add(U[t][e[0]] * V[t][e[1]] * W[t][e[2]] == vt) # Level-2: index-8-cross mass over the covering terms. terms = [] for t in covering: for fi, M in enumerate((U, V, W)): for p in offs[fi]: terms.append(z3.If(M[t][p] != 0, 1, 0)) s.add(z3.Sum(terms) == m) t0 = time.time() res = s.check() dt = time.time() - t0 n_att += 1 ctag = (f"{tag} base {ci} [{spec}] cross m={m}") if res == z3.sat: mdl = 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( mdl[U[t][p]].as_long(), D) outF["V"][p][t] = Fraction( mdl[V[t][p]].as_long(), D) outF["W"][p][t] = Fraction( mdl[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, 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: n_unsat += 1 logline(f"{ctag}: UNSAT in {dt:.1f}s") else: logline(f"{ctag}: NO CONCLUSION (unknown at {cap}s " f"cap, wall {dt:.1f}s)") logline(f"{tag}: cross batch done ({n_att} sub-cases attempted, " f"{n_unsat} UNSAT)") return 0 if __name__ == "__main__": sys.exit(main())