"""Third-party check of the union-of-masks tables (IIS-Q-0003): z3 and HiGHS.

usage: python3 -I work/capset/q0003/q3_third.py BINARY LOGDIR LAYER SOLVER SEED SAMPLE TIMEOUT [PYLIBS] [KIND] [BUDGETS]
SOLVER is z3 (an SMT solver) or highs (the MILP solver of scipy.optimize.milp).  PYLIBS is the
directory that holds scipy; the argument is necessary for highs only.
BINARY is the program q3_check.  Its mode "masks" gives 308 masks, one for each external direction
of the cap.  A mask has at most 56 marks.  The problem for one budget B and one number m is: do m
directions have a union of masks with at most B marks?
LOGDIR holds the logs of the mode "tables" of q3_check.  Each line of these logs gives the table
of one puncture set.  The script takes the reference value m from the line of that set.
For each set and each budget the script makes two tests of feasibility.  Test 1: m directions;
the solver must find them.  Test 2: m + 1 directions; the solver must prove that they are not
possible.  The script checks each solution by its own count of the union.  An answer UNKNOWN
(z3) or a time limit (HiGHS) is "no decision", not a disagreement.
  highs form: one Boolean for each direction and one for each mark.  The marks of a direction
         must be on when the direction is on (one aggregated row for each direction).  The sum of
         the marks is at most B.  Two directions with a union of more than B marks are not both
         on.  At least m directions are on.
  z3 form:   the same conditions with implications and pseudo-Boolean constraints.
SAMPLE is the number of the puncture sets for each kind and budget.  The kinds intact and dual
have one set.  The kinds p1w and p1s have 56 sets.  The kind p2 has 1540 sets.  The kind p3 has
27720 sets.  KIND limits the run to one kind.  BUDGETS (for example 36,38,42) limits the budgets.
The script proves nothing by itself: it compares the answer of a third-party solver with the
table of q3_check.  z3 5.4.1 and HiGHS (scipy 1.18.1) did not prove the upper bounds in a short
time.  See the logs of run_third.sh.
"""
import glob
import os
import random
import re
import subprocess
import sys
import time

binary, logdir, layer, solver = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4]
seed, sample, timeout = int(sys.argv[5]), int(sys.argv[6]), float(sys.argv[7])
pylibs = sys.argv[8] if len(sys.argv) > 8 else None
only = sys.argv[9] if len(sys.argv) > 9 else None
budgets = [int(x) for x in sys.argv[10].split(",")] if len(sys.argv) > 10 and sys.argv[10] != "-" else None
KINDS = ("intact", "dual", "p1w", "p1s", "p2", "p3")
FILES = {"intact": "q3_intact_L%d.log", "dual": "q3_dual_L%d.log", "p1s": "q3_p1s_L%d.log",
         "p1w": "q3_p1w_full_L%d.log", "p2": "q3_p2_L%d_*.log", "p3": "q3_p3_L%d_*.log"}


def reference(kind):
    """the table of each puncture set of one kind, from the logs: {cut: {budget: m}}"""
    rows = {}
    for name in sorted(glob.glob(os.path.join(logdir, FILES[kind] % layer))):
        with open(name, encoding="utf-8") as f:
            for ln in f:
                if "|" in ln:
                    head, tail = ln.split("|", 1)
                    words = head.split()
                    if not words or words[0] != kind:
                        continue
                    cut = tuple(int(x) for x in words[1:])
                else:
                    # the tables intact and dual have one line, with no name and no separator
                    if kind not in ("intact", "dual") or not re.search(r"\d+: \d", ln):
                        continue
                    cut, tail = (), ln
                row = {}
                counts = None
                # tokens: a number with a colon starts a budget; the other numbers are the counts
                for tok in re.findall(r"\d+:|\d+", tail):
                    if tok.endswith(":"):
                        counts = []
                        row[int(tok[:-1])] = counts
                    elif counts is not None:
                        counts.append(int(tok))
                # the count of depth d + 1 is zero when the list ends with zero: the maximum is d
                rows[cut] = {b: len(c) - (1 if c and c[-1] == 0 else 0) for b, c in row.items() if c}
    return rows


cache = {}


def masks(kind, cut):
    key = (kind, cut)
    if key not in cache:
        args = [binary, "masks", str(layer), kind, "-1"] + [str(x) for x in cut]
        out = subprocess.run(args, check=True, capture_output=True, text=True).stdout
        pm = [int(x) for x in out.split()]
        if len(pm) != 308:
            sys.exit("the binary gave %d masks, not 308" % len(pm))
        cache[key] = pm
        if len(cache) > 3000:
            cache.pop(next(iter(cache)))
    return cache[key]


def union_count(pm, chosen):
    u = 0
    for i in chosen:
        u |= pm[i]
    return bin(u).count("1")


def z3_feasible(pm, budget, mmin):
    import z3
    g = len(pm)
    dv = [z3.Bool("d%d" % i) for i in range(g)]
    wv = [z3.Bool("w%d" % p) for p in range(56)]
    s = z3.Solver()
    s.set("timeout", int(timeout * 1000))
    for i in range(g):
        marks = [wv[p] for p in range(56) if (pm[i] >> p) & 1]
        s.add(z3.Not(dv[i]) if not marks else z3.Implies(dv[i], z3.And(marks)))
    pairs = 0
    for i in range(g):
        for j in range(i + 1, g):
            if bin(pm[i] | pm[j]).count("1") > budget:
                s.add(z3.Or(z3.Not(dv[i]), z3.Not(dv[j])))
                pairs += 1
    s.add(z3.PbLe([(w, 1) for w in wv], budget))
    s.add(z3.PbGe([(d, 1) for d in dv], mmin))
    r = s.check()
    if r == z3.sat:
        model = s.model()
        return "found", [i for i in range(g) if z3.is_true(model[dv[i]])], pairs
    return ("proved", [], pairs) if r == z3.unsat else ("unknown", [], pairs)


def highs_feasible(pm, budget, mmin):
    np, scipy, Bounds, LinearConstraint, milp, coo_matrix = API
    g = len(pm)
    rows, cols, vals = [], [], []
    for i, m in enumerate(pm):
        marks = [p for p in range(56) if (m >> p) & 1]
        # one aggregated row: len(marks) * d[i] - sum of the marks of i <= 0
        for p in marks:
            rows.append(i)
            cols.append(g + p)
            vals.append(-1.0)
        rows.append(i)
        cols.append(i)
        vals.append(float(len(marks)))
    a = coo_matrix((np.array(vals), (rows, cols)), shape=(g, g + 56)).tocsr()
    pr, pc, pv = [], [], []
    q = 0
    for i in range(g):
        for j in range(i + 1, g):
            if bin(pm[i] | pm[j]).count("1") > budget:
                pr += [q, q]
                pc += [i, j]
                pv += [1.0, 1.0]
                q += 1
    b = coo_matrix((np.array(pv), (pr, pc)), shape=(q, g + 56)).tocsr()
    wsum = coo_matrix((np.ones(56), (np.zeros(56, dtype=int), np.arange(g, g + 56))), shape=(1, g + 56)).tocsr()
    dsum = coo_matrix((np.ones(g), (np.zeros(g, dtype=int), np.arange(0, g))), shape=(1, g + 56)).tocsr()
    cons = [LinearConstraint(a, -np.inf, 0.0), LinearConstraint(b, -np.inf, 1.0),
            LinearConstraint(wsum, -np.inf, float(budget)), LinearConstraint(dsum, float(mmin), np.inf)]
    opts = {"disp": False, "presolve": True, "time_limit": timeout, "mip_rel_gap": 0.0}
    res = milp(np.zeros(g + 56), constraints=cons, integrality=np.ones(g + 56),
               bounds=Bounds(np.zeros(g + 56), np.ones(g + 56)), options=opts)
    if res.status == 2:
        return "proved", [], q
    if res.status == 0 and res.x is not None:
        return "found", [i for i in range(g) if res.x[i] > 0.5], q
    return "unknown", [], q


def highs_api():
    sys.path.insert(0, pylibs)
    import numpy as np
    import scipy
    from scipy.optimize import Bounds, LinearConstraint, milp
    from scipy.sparse import coo_matrix
    return np, scipy, Bounds, LinearConstraint, milp, coo_matrix


if solver == "z3":
    import z3
    FEASIBLE = z3_feasible
    print("z3 version %s" % z3.get_version_string(), flush=True)
elif solver == "highs":
    API = highs_api()
    FEASIBLE = highs_feasible
    print("scipy %s, solver HiGHS of scipy.optimize.milp" % API[1].__version__, flush=True)
else:
    sys.exit("the solver must be z3 or highs")

instances = []
for kind in KINDS:
    if only and kind != only:
        continue
    rows = reference(kind)
    cuts = sorted(rows)
    if len(cuts) > sample:
        cuts = random.Random(seed).sample(cuts, sample)
    for cut in cuts:
        for budget in sorted(rows[cut]):
            if budgets and budget not in budgets:
                continue
            instances.append((kind, cut, budget, rows[cut][budget]))
start = time.time()
tot = agree = disagree = nodec = 0
longest = 0.0
stat = {}
for kind, cut, budget, table in instances:
    pm = masks(kind, cut)
    r = []
    worst = 0.0
    for test in (1, 2):
        t0 = time.time()
        status, chosen, pairs = FEASIBLE(pm, budget, table if test == 1 else table + 1)
        worst = max(worst, time.time() - t0)
        if test == 1:
            r.append("yes" if status == "found" and len(chosen) >= table and union_count(pm, chosen) <= budget
                     else ("no" if status == "proved" else "unknown"))
        else:
            r.append("yes" if status == "proved"
                     else ("no" if status == "found" and len(chosen) >= table + 1 and union_count(pm, chosen) <= budget else "unknown"))
    longest = max(longest, worst)
    verdict = "agree" if r == ["yes", "yes"] else ("disagree" if "no" in r else "no decision")
    tot += 1
    agree += verdict == "agree"
    disagree += verdict == "disagree"
    nodec += verdict == "no decision"
    st = stat.setdefault((kind, budget), [0, 0, 0, 0, 0, 0.0])
    st[0] += 1
    st[1] += r[0] == "yes"
    st[2] += r[1] == "yes"
    st[3] += verdict == "disagree"
    st[4] += verdict == "no decision"
    st[5] = max(st[5], worst)
    if verdict != "agree":
        print("NO DECISION or DISAGREE: %s cut %s budget %d table %d : test 1 %s, test 2 %s" % (kind, cut, budget, table, r[0], r[1]), flush=True)
for kind, budget in sorted(stat):
    s = stat[(kind, budget)]
    print("%s budget %d : sets %d : test 1 found %d, test 2 proved %d, agree %d, disagree %d, no decision %d : longest solve %.2f s" % (
        kind, budget, s[0], s[1], s[2], s[0] - s[3] - s[4], s[3], s[4], s[5]), flush=True)
print("solver %s, layer %d: instances %d, agree %d, disagree %d, no decision %d, longest solve %.2f s, seconds %.0f" % (
    solver, layer, tot, agree, disagree, nodec, longest, time.time() - start), flush=True)
if tot == 0 or disagree:
    sys.exit(1)
