#!/usr/bin/env python3
"""
l5_phase_lift.py - executable reading of the forum.zchg.org 733/5 "P-NP_2" recursion

    X_{t+1} = P_{V(I_cons)}[ (X_t (x) [1,1]^T) + (+)_r [ +i^k ; -i^k ] e_{i*(r)}^T ],
    k = floor(4 * frac(t / phi)),   rows of X live in L5^N = {0, +-1, +-i}^N

and its derived quantities
    V = C X^T,  A = |C||X|^T,  S = (A + Re V)/2,  U = w 1^T - A.

WHAT IS FIXED BY THE POST (implemented literally)
  * the doubling  X (x) [1,1]  with +i^k on one copy and -i^k on the other
  * the Weyl clock k = floor(4 {t/phi})
  * S, U as above; w = per-clause width (so U = undecided literals per clause)
  * success = every clause satisfied; t_halt <= ceil(N log_phi 2) is the claimed bound

WHAT THE TEXT DOES NOT PIN DOWN (choices made here, all swappable)
  * i*(r): which undecided variable row r splits on.   -> Engine.branch()  (weighted-occurrence score)
  * P_{V(I_cons)}: the projection.                      -> Engine.project() (--prune)
        none           identity (pure doubling, rank = 2^t)
        contradiction  annihilate rows with a falsified clause
        unit           contradiction + unit propagation to fixpoint
    and the conserved-quantity filter conservation_ok() below, which defaults to
    "keep everything" because alpha_h, alpha_E are not computable from the text.
  * what happens when i^k is imaginary (a "parked" variable): see branch() docstring.

The --check audit enumerates all models (N <= ~20) and verifies that EVERY satisfying
assignment is still covered by some surviving row after each step. Any proposed
definition of i*, P or conservation_ok must pass this before its rank numbers mean anything.

usage
  python3 l5_phase_lift.py solve file.cnf [--prune unit] [--phase real|weyl|infer]
  python3 l5_phase_lift.py bench --n 16 20 24 28 32 --seeds 6 --ratio 4.26 \
         --phase real weyl --prune none contradiction unit [--ladder ./ladder_prob] [--check]
"""
import argparse, itertools, math, os, random, statistics, subprocess, sys, tempfile, time
import numpy as np

PHI = (1 + 5 ** 0.5) / 2


# ----------------------------------------------------------------- instances
def gen_3sat(n, ratio, rng):
    m = round(ratio * n)
    out = []
    for _ in range(m):
        vs = rng.sample(range(1, n + 1), 3)
        out.append([v if rng.random() < 0.5 else -v for v in vs])
    return out


def write_cnf(path, n, clauses):
    with open(path, "w") as f:
        f.write(f"p cnf {n} {len(clauses)}\n")
        for c in clauses:
            f.write(" ".join(map(str, c)) + " 0\n")


def read_cnf(path):
    n, clauses, cur = 0, [], []
    for line in open(path):
        if not line.strip() or line[0] == "c":
            continue
        if line[0] == "p":
            n = int(line.split()[2])
            continue
        for tok in line.split():
            x = int(tok)
            if x == 0:
                clauses.append(cur); cur = []
            else:
                cur.append(x)
    return n, clauses


def check_model(clauses, assign):  # assign: array indexed 0..n-1 with +-1
    return all(any((l > 0) == (assign[abs(l) - 1] > 0) for l in c) for c in clauses)


def all_models(n, clauses, limit=4000):
    bits = ((np.arange(2 ** n)[:, None] >> np.arange(n)) & 1).astype(np.int8) * 2 - 1
    C = np.zeros((len(clauses), n), np.int8)
    for i, c in enumerate(clauses):
        for l in c:
            C[i, abs(l) - 1] = 1 if l > 0 else -1
    true = (np.abs(C).sum(1)[None, :] + bits.astype(np.int16) @ C.T.astype(np.int16)) // 2
    models = bits[(true >= 1).all(1)]
    if len(models) > limit:
        models = models[np.random.default_rng(0).choice(len(models), limit, replace=False)]
    return models


# ------------------------------------------------------------------ the hook
def conservation_ok(X):
    """Placeholder for V(I_cons): rows violating the conservation ideal are annihilated.
    The post gives I_cons = <sin(pi*alpha_h(x)), sin(pi*alpha_E(x))> but alpha_h/alpha_E as
    functions of a row x are not specified in the text. Replace this and run --check."""
    return np.ones(len(X), dtype=bool)


# -------------------------------------------------------------------- engine
class Engine:
    def __init__(self, n, clauses, prune="unit", phase="real", dedupe="exact"):
        self.n, self.clauses, self.m = n, clauses, len(clauses)
        self.prune, self.phase, self.dedupe = prune, phase, dedupe
        C = np.zeros((self.m, n), np.float32)
        for i, c in enumerate(clauses):
            for l in c:
                C[i, abs(l) - 1] = 1.0 if l > 0 else -1.0
        self.C, self.absC = C, np.abs(C)
        self.w = self.absC.sum(1)

    # clause statistics on the REAL part (Re in {-1,0,+1}); +-i counts as undecided
    def stats(self, X):
        Re = np.rint(X.real).astype(np.float32)
        Ar = self.absC @ np.abs(Re).T
        Vr = self.C @ Re.T
        return (Ar + Vr) / 2, (Ar - Vr) / 2, self.w[:, None] - Ar  # true, false, free

    def literal_S(self, X):  # S = (A + Re V)/2 exactly as written (A uses |X|, so +-i inflates it)
        A = self.absC @ np.abs(X).T
        V = self.C @ X.T
        return 0.5 * (A + V.real)

    # ------------------------------------------------- inference ("infer" phase)
    def _propagate_keep(self, X):
        """Unit-propagate every row WITHOUT dropping any; return (dead mask, #forced literals)."""
        X = X.copy(); forced = np.zeros(len(X)); dead = np.zeros(len(X), bool)
        for _ in range(self.n):
            T, F, Fr = self.stats(X)
            dead |= (F == self.w[:, None]).any(0)
            unit = (T == 0) & (Fr == 1) & ~dead[None, :]
            if not unit.any():
                break
            ii, kk = np.nonzero(unit)
            free = (self.absC[ii] > 0) & (np.rint(X.real[kk]) == 0)
            jj = free.argmax(1)
            X[kk, jj] = self.C[ii, jj]
            np.add.at(forced, kk, 1)
        T, F, Fr = self.stats(X)
        dead |= (F == self.w[:, None]).any(0)
        return dead, forced

    def lookahead(self, X, score, K=3):
        """i*(r) by inference: for the K best-scoring candidates, probe BOTH vantages (+1 and -1)
        with unit propagation. A candidate where both die annihilates the row; where one dies the
        other vantage is forced (interference collapse, no doubling); otherwise score by the
        product of propagation yields (march-style). Phase is therefore never wasted."""
        r = len(X); K = min(K, self.n)
        top = np.argsort(-score, axis=1)[:, :K]
        best = np.full(r, -1.0); star = top[:, 0].copy(); rows = np.arange(r)
        for j in range(K):
            v = top[:, j]
            ok = score[rows, v] >= 0
            Xp, Xm = X.copy(), X.copy()
            Xp[rows, v], Xm[rows, v] = 1, -1
            dp, ap = self._propagate_keep(Xp)
            dm, am = self._propagate_keep(Xm)
            sc = np.where(dp & dm, 1e9, np.where(dp | dm, 1e8 + ap + am, (ap + 1) * (am + 1)))
            sc = np.where(ok, sc, -1.0)
            upd = sc > best
            best = np.where(upd, sc, best); star = np.where(upd, v, star)
        return star

    # ------------------------------------------------------------ i*(r) + doubling
    def branch(self, X, t):
        """Each row with an undecided variable is doubled; on variable i*(r) the two copies
        get +i^k and -i^k (written, not added, so parked +-i entries stay on the lattice).
        k=0 -> (+1,-1) classic split; k=2 -> (-1,+1) same split swapped; k odd -> (+i,-i):
        both copies have identical real part, i.e. a phase twin that decides nothing.
        i*(r): untouched (==0) variables first, parked ones only if none; within a class,
        highest sum over unsatisfied clauses of 2^-(free literals) (a MOMS/Jeroslow-Wang score)."""
        k = int(4 * ((t / PHI) % 1.0)) if self.phase == "weyl" else 0
        T, F, Fr = self.stats(X)
        wt = np.where(T >= 1, 0.0, 2.0 ** (-Fr)).astype(np.float32)  # m x r
        score = wt.T @ self.absC                                       # r x n
        cand = np.rint(X.real) == 0
        score = np.where(X == 0, score + 1e6, np.where(cand, score, -1.0))
        has = cand.any(1)
        star = self.lookahead(X, score) if self.phase == "infer" else score.argmax(1)
        d = 1j ** k
        idx = np.nonzero(has)[0]
        A, B = X[idx].copy(), X[idx].copy()
        A[np.arange(len(idx)), star[idx]] = d
        B[np.arange(len(idx)), star[idx]] = -d
        return np.concatenate([X[~has], A, B])

    # ------------------------------------------------------------ P_{V(I_cons)}
    def project(self, X):
        if self.prune != "none":
            while len(X):
                T, F, Fr = self.stats(X)
                X = X[~(F == self.w[:, None]).any(0)]       # annihilate contradictions
                if self.prune == "contradiction" or not len(X):
                    break
                T, Fr = T[:, ~(F == self.w[:, None]).any(0)], Fr[:, ~(F == self.w[:, None]).any(0)]
                unit = (T == 0) & (Fr == 1)
                if not unit.any():
                    break
                ii, kk = np.nonzero(unit)
                free = (self.absC[ii] > 0) & (np.rint(X.real[kk]) == 0)
                jj = free.argmax(1)
                X[kk, jj] = self.C[ii, jj]                   # forced literal; conflicts surface next pass
        if len(X):
            X = X[conservation_ok(X)]
        if len(X) and self.dedupe != "none":
            Re = np.rint(X.real).astype(np.int8)
            key = Re if self.dedupe == "real" else np.concatenate([Re, np.rint(X.imag).astype(np.int8)], 1)
            _, idx = np.unique(key, axis=0, return_index=True)
            X = X[np.sort(idx)]
        return X

    def audit(self, X, models):
        if models is None or not len(models) or len(X) > 3000:
            return 0
        Re = np.rint(X.real).astype(np.int8)
        covered = np.zeros(len(models), bool)
        for row in Re:
            covered |= ((row == 0) | (models == row)).all(1)
        return int((~covered).sum())

    # ---------------------------------------------------------------- driver
    def run(self, max_rows=50000, t_max=None, models=None):
        t_max = t_max or 4 * self.n + 10
        t0 = time.perf_counter()
        X = self.project(np.zeros((1, self.n), complex))
        peak, hist, phantom, violations = len(X), [len(X)], 0, 0
        res = dict(result="TMAX")
        for t in range(t_max + 1):
            if len(X) == 0:
                res = dict(result="UNSAT"); break
            T, F, Fr = self.stats(X)
            done = (T >= 1).all(0)
            if self.phase == "weyl":
                phantom = max(phantom, int(((self.literal_S(X) >= 1).all(0) & ~done).sum()))
            if done.any():
                a = np.rint(X[np.argmax(done)].real); a[a == 0] = 1
                assert check_model(self.clauses, a), "witness failed verification"
                res = dict(result="SAT"); break
            if len(X) > max_rows:
                res = dict(result="ROWCAP"); break
            X = self.project(self.branch(X, t))
            peak = max(peak, len(X)); hist.append(len(X))
            violations += self.audit(X, models)
        res.update(t=len(hist) - 1, peak=peak, hist=hist, phantom_S=phantom,
                   violations=violations, secs=time.perf_counter() - t0)
        return res


# ----------------------------------------------------------------- benchmark
def run_ladder(binary, n, clauses, seed, secs):
    with tempfile.NamedTemporaryFile("w", suffix=".cnf", delete=False) as f:
        path = f.name
    write_cnf(path, n, clauses)
    try:
        out = subprocess.run([binary, path, "2.06", str(secs), str(seed)],
                             capture_output=True, text=True, timeout=secs + 15).stdout.split()
    finally:
        os.unlink(path)
    t = [float(x[5:]) for x in out if x.startswith("time=")]
    return out[0] if out else "ERR", (t[0] if t else float("nan"))


def fit(xs, ys):
    if len(xs) < 3:
        return float("nan"), float("nan")
    s, b = np.polyfit(xs, ys, 1)
    pred = s * np.array(xs) + b
    ss_res, ss_tot = ((np.array(ys) - pred) ** 2).sum(), ((np.array(ys) - np.mean(ys)) ** 2).sum()
    return s, (1 - ss_res / ss_tot) if ss_tot > 0 else float("nan")


def bench(a):
    configs = list(itertools.product(a.phase, a.prune))
    med_peak = {c: [] for c in configs}
    print(f"ratio={a.ratio}  seeds={a.seeds}  max_rows={a.max_rows}  dedupe={a.dedupe}")
    for n in a.n:
        agg = {c: [] for c in configs}
        lad = []
        for s in range(a.seeds):
            rng = random.Random(1000 * n + s)
            cl = gen_3sat(n, a.ratio, rng)
            models = all_models(n, cl) if (a.check and n <= 20) else None
            for c in configs:
                agg[c].append(Engine(n, cl, c[1], c[0], a.dedupe).run(a.max_rows, models=models))
            if a.ladder:
                lad.append(run_ladder(a.ladder, n, cl, s + 1, a.ladder_secs))
        print(f"\nN={n:<4d} m={round(a.ratio * n)}")
        print(f"  {'phase':<6}{'prune':<14}{'SAT':>4}{'UNS':>4}{'CAP':>4}{'TMX':>4}  "
              f"{'med t':>6}{'med peak':>10}{'log2(peak)/N':>14}{'med s':>8}{'phantomS':>9}{'viol':>5}")
        for c in configs:
            R = agg[c]
            cnt = lambda k: sum(r["result"] == k for r in R)
            mp = statistics.median(r["peak"] for r in R)
            med_peak[c].append((n, mp, cnt("ROWCAP") > 0))
            print(f"  {c[0]:<6}{c[1]:<14}{cnt('SAT'):>4}{cnt('UNSAT'):>4}{cnt('ROWCAP'):>4}{cnt('TMAX'):>4}  "
                  f"{statistics.median(r['t'] for r in R):>6.0f}{mp:>10.0f}{math.log2(max(mp,1)) / n:>14.3f}"
                  f"{statistics.median(r['secs'] for r in R):>8.2f}{max(r['phantom_S'] for r in R):>9d}"
                  f"{sum(r['violations'] for r in R):>5d}")
        if lad:
            solved = [x[1] for x in lad if x[0] == "SAT"]
            med = statistics.median(solved) if solved else float("nan")
            print(f"  ladder_prob: {len(solved)}/{len(lad)} solved (cannot certify UNSAT); median time over solved {med:.4f}s")
    print("\nscaling of median peak rows (censored at max_rows where CAP>0, so slopes are lower bounds)")
    for c in configs:
        pts = med_peak[c]
        ns = [p[0] for p in pts]; lp = [math.log2(max(p[1], 1)) for p in pts]
        se, re = fit(ns, lp)
        sp, rp = fit([math.log2(x) for x in ns], lp)
        cens = any(p[2] for p in pts)
        print(f"  {c[0]:<6}{c[1]:<14} exp-fit: peak~2^({se:.3f}*N) R2={re:.3f} | "
              f"poly-fit: peak~N^{sp:.2f} R2={rp:.3f}{'  [censored]' if cens else ''}")


def solve(a):
    n, cl = read_cnf(a.file)
    models = all_models(n, cl) if (a.check and n <= 20) else None
    r = Engine(n, cl, a.prune, a.phase, a.dedupe).run(a.max_rows, models=models)
    print({k: v for k, v in r.items() if k != "hist"})
    print("rows per step:", r["hist"])


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    sub = p.add_subparsers(dest="cmd", required=True)
    for name in ("solve", "bench"):
        q = sub.add_parser(name)
        q.add_argument("--max-rows", dest="max_rows", type=int, default=50000)
        q.add_argument("--dedupe", choices=["none", "exact", "real"], default="exact")
        q.add_argument("--check", action="store_true", help="soundness audit (N<=20)")
        if name == "solve":
            q.add_argument("file")
            q.add_argument("--prune", choices=["none", "contradiction", "unit"], default="unit")
            q.add_argument("--phase", choices=["real", "weyl", "infer"], default="real")
        else:
            q.add_argument("--n", type=int, nargs="+", default=[14, 18, 22, 26])
            q.add_argument("--seeds", type=int, default=5)
            q.add_argument("--ratio", type=float, default=4.26)
            q.add_argument("--phase", nargs="+", choices=["real", "weyl", "infer"], default=["real", "weyl"])
            q.add_argument("--prune", nargs="+", choices=["none", "contradiction", "unit"],
                           default=["none", "contradiction", "unit"])
            q.add_argument("--ladder", default=None, help="path to compiled ladder_prob")
            q.add_argument("--ladder-secs", dest="ladder_secs", type=float, default=5.0)
    a = p.parse_args()
    solve(a) if a.cmd == "solve" else bench(a)
