"""Model of the count of the free positions for each case of IIS-Q-0003 (proof review).

usage: python3 -I work/capset/q0003/q3_cases.py LOGDIR
The script reads the tables of q3_check for cap 0 from the logs in LOGDIR.  It builds the model
of Section 8 of my report and solves the model for each case with z3.  The model is my analysis
by hand of the text of iis:2611.00054.  The script proves only that the rules of the model give
the numbers that it prints.  A rule of the model can be wrong.

Names.  k is the size of A intersect S.  B = 56 - k/2 is the number of unshared classes.  A
direction is a class [z] of positions; it has the two positions z and -z.  P0: a position in no
cap (i = 0).  X: a position of S that is not in A.  Y: a position of A that is not in S.
n is the number N(z) of representations before the punctures: 0 (old), 1 (singleton), 2
(doubleton), 3 (triple).  h is the number of shared classes perpendicular to z.

Rules of the model.
R1  An old direction gives two positions.  A triple gives one position (no triple loses both
    signs).  A doubleton or a singleton gives two positions only when the rules R5 and R6 permit
    both signs, else one position.
R2  Group of the directions of X (P0 and X): at most cx directions.  The directions with h = 0
    of this group: at most D(B).
R3  Group of the directions of Y (P0 and Y): at most cy directions.  The directions with h = 0
    of this group: at most D(B).
R4  The old directions (n = 0) of P0 and X together are external to A, so they are one family
    for the tables of cap A: at most T0(B).  In the same way, the old directions of P0 and Y
    together are external to S: at most T0(B).  The model does not add the two limits.
R5  A doubleton gives two positions only in these cases.  Split form, U not antipodal: the two
    rows have the S endpoints b and -b, and the A endpoints b-z and b+z.  So all the doubled
    doubleton directions have one direction [b+z]: at most one in total (P0, X or Y).  U with
    an antipodal pair {a0,-a0} (both forms): the two rows have the A endpoints a0 and -a0.
    Each doubleton of P0 and of Y can give two positions.  A doubleton of X never gives two
    positions, because z-a0, z, z+a0 would be three points of S on a line.
R6  A singleton gives two positions only in these cases.  Split form, U not antipodal: one sign
    dies by a point u of U, the other sign by b.  So all the doubled singleton directions are
    [u-b]: at most two in total (P0, X or Y).  U with an antipodal pair: each singleton of P0
    and of Y can give two positions.  A singleton of X gives two positions only when the pair
    is not in S.  Then the row (a0,z-a0) and its negative die together.  If a0 is in S, the
    points a0, z-a0, -z of S are on a line, thus z = -a0 is a shared position.
R7  A position of X with n >= 1 is free when each of its rows has a killer.  A killer is a point
    of U that is not in S, or the point b (split form).  Two killers that are negatives of each
    other can not serve the same position (z-u, z, z+u would be three points of S on a line).
    A point of U that is in S serves only the position z = -x.  So a position of X with n rows
    needs n killers, or it is z = -x and it needs n - 1 killers.  At most p positions are of
    the second kind.  Number of killers: split form, U not antipodal: 3 - p.  Split form,
    U antipodal: 2 (p = 0) or 1 (p = 1).  Unsplit form, U not antipodal: 3 - p.  Unsplit form,
    U antipodal: 2, 1, 1, 0 for p = 0, 1, 2, 3.
R8  A position of Y with n rows needs n killers.  A killer is a point of U, or the point b.  If b
    is in A, then b serves only the position z = -b.
R9  A shared position (in A and in S) is free only when its row (-z,-z) dies.  So -z is a
    puncture.  With an antipodal U, also z can be the puncture.

Tables.  T0: intact masks.  D: dual masks.  W: one puncture, weak rule.  S: one puncture, strict
rule.  T2: two punctures, strict rule.  T3: three punctures, strict rule.  The number of
directions does not become smaller when the budget grows.  So the script uses, for a budget
between two computed budgets, the value at the larger computed budget.  It uses no constraint
when the budget is above all the computed budgets of a table (it prints 99).  The weak table and
the strict table are both upper bounds for one puncture, so the script uses the smaller value.
Each variable is at most 56, because there are 56 classes.  The script has no other limit for a
group without a table constraint.

Cases.  Split form: U has two points and S loses the point b.  w = 1 when b is in A.  p is the
number of points of U that are in S.  "U antipodal" means U = {u,-u}; then p is 0 or 1.
Unsplit form: U has three points and S is intact.  p is the number of points of U that are in
S.  "U antipodal" means that U = {a0,-a0,u} has one antipodal pair (U = -U is not possible for
three nonzero points); then p = 0 (no point in S), 1 (u is in S), 2 (the pair is in S) or 3
(all three points are in S).  "U not antipodal" means that U has no antipodal pair.  A point of
class of U that is in S makes the table budget of the other cap larger by one class.  With an
antipodal pair in S, the two points of the pair are in one class.  So the script adds one class
for p = 1 and p = 2, and two classes for p = 3.
"""
import re
import sys
from pathlib import Path

from z3 import Int, Optimize, Sum, sat

logdir = Path(sys.argv[1])


def directions(row):
    n = len(row)
    while n > 0 and row[n - 1] == 0:
        n -= 1
    return n


def per_set(names, tag):
    table = {}
    for name in names:
        for line in (logdir / name).read_text().splitlines():
            if not line.startswith(tag + " "):
                continue
            parts = re.split(r"(\d+):", line.split("|", 1)[1])
            for i in range(1, len(parts) - 1, 2):
                table.setdefault(int(parts[i]), []).append(directions(tuple(int(x) for x in parts[i + 1].split())))
    return {b: max(rows) for b, rows in table.items()}, {b: len(rows) for b, rows in table.items()}


def one_line(name):
    chunks = (logdir / name).read_text().split(":")
    table = {}
    budget = int(chunks[0])
    for i in range(1, len(chunks)):
        row = [int(x) for x in chunks[i].split()]
        if i < len(chunks) - 1:
            table[budget], budget = directions(tuple(row[:-1])), row[-1]
            continue
        table[budget] = directions(tuple(row))
    return table, {b: 1 for b in table}


P2 = ["q3_p2_low_L0.txt"] + ["q3_p2_L0_%d.log" % i for i in range(12)]
P3 = ["q3_p3_L0_%d.log" % i for i in range(12)]
TABLES = {
    "T0": one_line("q3_intact_L0.log"),
    "D": one_line("q3_dual_L0.log"),
    "W": per_set(["q3_p1w_full_L0.log"], "p1w"),
    "S": per_set(["q3_p1s_L0.log"], "p1s"),
    "T2": per_set(P2, "p2"),
    "T3": per_set(P3, "p3"),
}


def tab(kind, budget):
    """Return an upper bound for the budget, or None.  The number of directions does not become
    smaller when the budget grows.  So the value is the one at the smallest computed budget that
    is not below the budget."""
    table = TABLES[kind][0]
    upper = [b for b in sorted(table) if b >= budget]
    return table[min(upper)] if upper else None


def bound(kinds, budget):
    """Return the smallest upper bound from the tables in kinds.  The value 99 means that no table
    has a computed budget that is not below the budget (no constraint)."""
    values = [v for v in (tab(kind, budget) for kind in kinds) if v is not None]
    return min(values) if values else 99


def types(k):
    """Return the number h for each n of the positions of P0 and of the positions internal to a cap."""
    p0, internal = {}, {}
    for n in range(4):
        a, b = n - (16 - k // 2), n - (20 - k // 2)
        if a % 3 == 0 and 0 <= a // 3 <= k // 2:
            p0[n] = a // 3
        if b % 3 == 0 and 0 <= b // 3 <= k // 2:
            internal[n] = b // 3
    return p0, internal


def shared_types(k):
    """Return the number h for each n <= 3 of the positions that are in the two caps."""
    out = {}
    for n in (1, 2, 3):
        c = n - (24 - k // 2)
        if c % 3 == 0 and 0 <= c // 3 <= k // 2:
            out[n] = c // 3
    return out


IN_S = {0: "none", 1: "u", 2: "the pair", 3: "all three"}


def label(form, p, anti, w):
    """Return the name of the case."""
    if not anti:
        text = "U not antipodal, p=%d" % p
    elif form == "split":
        text = "U antipodal, p=%d" % p
    else:
        text = "U antipodal, points in S: %s" % IN_S[p]
    return text + (", b in A %d" % w if form == "split" else "")


def solve(k, form, p, anti, w):
    B = 56 - k // 2
    p0, internal = types(k)
    can_share = bool(shared_types(k))
    # R7: the number of killers for the positions of X.
    if not anti:
        keff = 3 - p
    elif form == "split":
        keff = 2 if p == 0 else 1
    else:
        # Points of U that are not in S: p = 0: the pair and u (the pair counts one time); p = 1
        # (u in S): the pair; p = 2 (the pair in S): u; p = 3: none.
        keff = {0: 2, 1: 1, 2: 1, 3: 0}[p]
    caps_x = {n: (None if n <= keff else (p if n - 1 <= keff else 0)) for n in (1, 2, 3)}
    if form == "split":
        cy = bound(["W", "S"], B + p)
        cx = bound(["W", "S"], B + w) if anti else bound(["T2"], B + w)
        caps_y = {1: None, 2: None, 3: (1 if w else None)}
        shared_max = min(3, p + (1 if anti and p >= 1 else 0) + w) if can_share else 0
        glob_double, glob_single = (None if anti else 1), (None if anti else 2)
        x_single = anti and p == 0
    else:
        # Points of U in S make classes of S punctured: 0, 1, 1, 2 classes for p = 0, 1, 2, 3 (the
        # two points of an antipodal pair are in one class).
        cy = bound(["T0"], B + ((0, 1, 1, 2)[p] if anti else p))
        cx = bound(["T2" if anti else "T3"], B)
        caps_y = {1: None, 2: None, 3: None}
        shared_max = min(3, p) if can_share else 0
        glob_double, glob_single = (None if anti else 0), (None if anti else 0)
        # R6: a singleton of X doubles only when the pair is not in S.
        x_single = anti and p in (0, 1)
    dual, intact = bound(["D"], B), bound(["T0"], B)
    opt = Optimize()
    var, two = {}, {}
    for cat, tps, caps in (("P", p0, {0: None, 1: None, 2: None, 3: None}), ("X", internal, caps_x), ("Y", internal, caps_y)):
        for n in tps:
            cap = None if n == 0 else caps[n]
            if cap == 0:
                continue
            x = Int("v_%s_%d" % (cat, n))
            opt.add(x >= 0, x <= 56)
            if cap is not None:
                opt.add(x <= cap)
            var[cat, n] = x
            if n in (1, 2):
                y = Int("two_%s_%d" % (cat, n))
                opt.add(y >= 0, y <= x)
                # R5 and R6: a singleton of X doubles only when the antipodal pair is not in S.
                eligible = (form == "split") if not anti else (cat != "X" or (n == 1 and x_single))
                if not eligible:
                    opt.add(y == 0)
                two[cat, n] = y

    def h_of(cat, n):
        return (p0 if cat == "P" else internal)[n]

    opt.add(Sum([x for (c, _), x in var.items() if c != "Y"]) <= cx)
    opt.add(Sum([x for (c, _), x in var.items() if c != "X"]) <= cy)
    opt.add(Sum([x for (c, n), x in var.items() if c != "Y" and h_of(c, n) == 0]) <= dual)
    opt.add(Sum([x for (c, n), x in var.items() if c != "X" and h_of(c, n) == 0]) <= dual)
    # R4: the old directions of P0 and X are external to A (one family for the tables of A).  The
    # old directions of P0 and Y are external to S (one family for the tables of S).
    opt.add(Sum([x for (c, n), x in var.items() if n == 0 and c != "Y"]) <= intact)
    opt.add(Sum([x for (c, n), x in var.items() if n == 0 and c != "X"]) <= intact)
    if glob_double is not None:
        opt.add(Sum([y for (_, n), y in two.items() if n == 2]) <= glob_double)
    if glob_single is not None:
        opt.add(Sum([y for (_, n), y in two.items() if n == 1]) <= glob_single)
    shared = Int("shared")
    opt.add(shared >= 0, shared <= shared_max)
    objective = 2 * Sum([x for (_, n), x in var.items() if n == 0]) + Sum([x for (_, n), x in var.items() if n == 3])
    objective = objective + Sum([var[c, n] + two[c, n] for (c, n) in var if n in (1, 2)]) + shared
    opt.maximize(objective)
    if opt.check() != sat:
        raise SystemExit("no solution for %s k=%d p=%d anti=%d w=%d" % (form, k, p, anti, w))
    model = opt.model()
    parts = ["%s%s=%d" % (c, n, model[x].as_long()) for (c, n), x in sorted(var.items())]
    parts += ["%s%s x2=%d" % (c, n, model[y].as_long()) for (c, n), y in sorted(two.items()) if model[y].as_long()]
    parts.append("shared=%d" % model[shared].as_long())
    return model.eval(objective).as_long(), cx, cy, dual, intact, " ".join(parts)


for kind in ("T0", "D", "W", "S", "T2", "T3"):
    table, sets = TABLES[kind]
    print("table %s: %s" % (kind, " ".join("%d:%d(%d sets)" % (b, table[b], sets[b]) for b in sorted(table))))

best = {}
# The text of the author has the cases 26 to 64.  The script also computes the larger overlaps.
for k in range(26, 113, 2):
    p0, internal = types(k)
    print("k %d: B %d, positions in no cap %s, positions internal to a cap %s, shared positions %s" % (
        k, 56 - k // 2,
        " ".join("N=%d:h=%d" % (n, h) for n, h in sorted(p0.items())),
        " ".join("N=%d:h=%d" % (n, h) for n, h in sorted(internal.items())),
        " ".join("N=%d:h=%d" % (n, (n - 24 + k // 2) // 3) for n in range(1, 4) if (n - 24 + k // 2) % 3 == 0 and (n - 24 + k // 2) // 3 >= 0)))
    cases = [("split", p, False, w) for p in (0, 1, 2) for w in (0, 1)]
    cases += [("split", p, True, w) for p in (0, 1) for w in (0, 1)]
    cases += [("unsplit", p, False, 0) for p in (0, 1, 2, 3)]
    cases += [("unsplit", p, True, 0) for p in (0, 1, 2, 3)]
    for form, p, anti, w in cases:
        value, cx, cy, dual, intact, parts = solve(k, form, p, anti, w)
        best[form, k] = max(best.get((form, k), 0), value)
        show = lambda v: "none" if v == 99 else str(v)
        print("  %s k=%d %s: X directions <= %s, Y directions <= %s, dual <= %d, intact <= %d: positions <= %d   [%s]" % (
            form, k, label(form, p, anti, w), show(cx), show(cy), dual, intact, value, parts))

print("summary: the largest count for each form and each k")
for form in ("split", "unsplit"):
    print("  %s: %s" % (form, " ".join("%d:%d" % (k, best[form, k]) for k in range(26, 113, 2))))
print("largest count in all cases: %d" % max(best.values()))
