"""Direct test of the sign rules for a puncture set U with an antipodal pair (IIS-Q-0003).

usage: python3 -I work/capset/q0003/q3_signtest.py LAYER PERK MODELLOG MATRIXFILE [MATRIXFILE ...]
The script reads the lines "k MATRIX" of the matrix files (36 digits, row by row).  For the first
PERK different matrices of each even k it makes a direct test of the two forms with an antipodal
pair {u,-u} in U:
  - split form: U = {u,-u} and V = {b}, for each class [u] of A and each point b of S;
  - unsplit form: U = {u,-u,w}, for each class [u] of A and each third point w of A.
For each puncture set it counts the free positions (the positions without a representation, with
the positions that have no representation before the punctures).  It finds the directions [z]
where the two positions z and -z are free.  P: a position in no cap.  X: a position of S that is
not in A.  Y: a position of A that is not in S.  C: a position in the two caps.  n is the number
of representations before the punctures.  It tests these rules:
  S1  A direction with n = 3 never has two free positions.
  S2  A direction with n = 2 of the category X never has two free positions.
  S3  A direction with n = 1 of the category X has two free positions only when its row has the
      A point in {u,-u} and u is not in S.
It also reads the model log of q3_cases.py.  It compares the largest direct count of each case
with the count of the model.  The direct count must be <= the count of the model.
The test is a test on samples.  It proves nothing.
"""
import sys
from collections import defaultdict

DESIGN = {(0, 1, 2), (0, 1, 3), (0, 2, 4), (0, 3, 5), (0, 4, 5), (1, 2, 5), (1, 3, 4), (1, 4, 5), (2, 3, 4), (2, 3, 5)}
PW = [1, 3, 9, 27, 81, 243]
DIG = [[(v // PW[i]) % 3 for i in range(6)] for v in range(729)]
NEG = [sum(((3 - d) % 3) * PW[i] for i, d in enumerate(DIG[v])) for v in range(729)]
ADD = [[0] * 729 for _ in range(729)]
for a in range(729):
    da, row = DIG[a], ADD[a]
    for b in range(729):
        db = DIG[b]
        row[b] = sum(((da[i] + db[i]) % 3) * PW[i] for i in range(6))
NAME = {"none": (0, 0), "u": (1, 0), "the pair": (0, 1), "all three": (1, 1)}


def cap(layer):
    pts = []
    for v in range(729):
        support = tuple(i for i in range(6) if DIG[v][i])
        if len(support) == 6 and DIG[v].count(2) % 2 == 0:
            pts.append(v)
        elif len(support) == 3 and ((support in DESIGN) == (layer == 0)):
            pts.append(v)
    return pts


def digits(v):
    return "".join(str(d) for d in DIG[v])


def read_model(path):
    model = {}
    for line in open(path).read().splitlines():
        if not line.startswith("  ") or "U antipodal" not in line:
            continue
        form, rest = line.strip().split(" k=", 1)
        k = int(rest.split(" ", 1)[0])
        head, rest = rest.rsplit(": positions <= ", 1)
        value = int(rest.split()[0])
        case = head.split(":")[0]
        if form == "split":
            model[form, k, int(case.split("p=")[1].split(",")[0]), int(case.split("b in A ")[1])] = value
        else:
            model[form, k, NAME[head.split(": ", 1)[1].split(":")[0]]] = value
    return model


def main():
    layer, perk, model = int(sys.argv[1]), int(sys.argv[2]), read_model(sys.argv[3])
    A = cap(layer)
    classes = [a for a in A if a < NEG[a]]
    matrices = defaultdict(list)
    for name in sys.argv[4:]:
        for line in open(name).read().splitlines():
            parts = line.split()
            if len(parts) != 2 or len(parts[1]) != 36 or not parts[1].isdigit():
                continue
            group = matrices[int(parts[0])]
            if len(group) < perk and parts[1] not in group:
                group.append(parts[1])
    tested, sets = 0, 0
    direct, doubled = {}, defaultdict(int)
    bad = {"S1": 0, "S2": 0, "S3": 0}
    example = None

    def lost(z, U, V):
        for a, s in rows[z]:
            if a not in U and s not in V:
                return False
        return True

    for k in sorted(matrices):
        for text in matrices[k]:
            T = [[int(text[6 * i + j]) for j in range(6)] for i in range(6)]
            S = []
            for a in A:
                d = DIG[a]
                S.append(sum((sum(T[i][j] * d[j] for j in range(6)) % 3) * PW[i] for i in range(6)))
            inB, inS = [False] * 729, [False] * 729
            for a in A:
                inB[a] = True
            for s in S:
                inS[s] = True
            if sum(inB[s] for s in S) != k:
                raise SystemExit("the overlap of a matrix is not the number of its line: " + text)
            N = [0] * 729
            for a in A:
                row = ADD[a]
                for s in S:
                    N[row[s]] += 1
            cand = [z for z in range(1, 729) if 1 <= N[z] <= 3]
            rows = {}
            for z in cand:
                rr = []
                for a in A:
                    s = ADD[z][NEG[a]]
                    if inS[s]:
                        rr.append((a, s))
                if len(rr) != N[z]:
                    raise SystemExit("the number of rows is not N: " + text)
                rows[z] = tuple(rr)
            old = sum(1 for z in range(1, 729) if N[z] == 0)
            tested += 1
            for u in classes:
                pair = (u, NEG[u])
                for form in ("split", "unsplit"):
                    thirds = S if form == "split" else [w for w in A if w != u and w != NEG[u]]
                    for third in thirds:
                        if form == "split":
                            U, V = pair, (third,)
                            case = (k, int(inS[u]), int(inB[third]))
                        else:
                            U, V = pair + (third,), ()
                            case = (k, int(inS[u]), int(inS[third]))
                        sets += 1
                        total, free = old, {}
                        for z in cand:
                            if lost(z, U, V):
                                free[z] = True
                                total += 1
                        direct[form, case] = max(direct.get((form, case), 0), total)
                        for z in cand:
                            if z > NEG[z] or z not in free or NEG[z] not in free:
                                continue
                            cat = "C" if inB[z] and inS[z] else "X" if inS[z] else "Y" if inB[z] else "P"
                            doubled[form, cat, N[z]] += 1
                            if N[z] == 3:
                                bad["S1"] += 1
                            elif cat == "X" and N[z] == 2:
                                bad["S2"] += 1
                            elif cat == "X" and rows[z][0][0] not in pair:
                                bad["S3"] += 1
                            if cat == "X" and example is None:
                                example = (k, form, text, digits(u), digits(third), digits(z), N[z], int(inS[u]))
    print("layer %d, matrices tested %d, puncture sets tested %d" % (layer, tested, sets))
    print("matrices for each k: %s" % " ".join("%d:%d" % (k, len(matrices[k])) for k in sorted(matrices)))
    print("directions with two free positions, by form, category and n: %s" % (
        " ".join("%s %s n=%d: %d" % (key[0], key[1], key[2], doubled[key]) for key in sorted(doubled)) or "none"))
    print("violations: S1 %d, S2 %d, S3 %d" % (bad["S1"], bad["S2"], bad["S3"]))
    print("first direction of the category X with n = 1 and two free positions: %s" % (example,))
    wrong = 0
    for key in sorted(direct, key=lambda x: (x[0], x[1][0], x[1][1], x[1][2])):
        form, (k, c1, c2) = key
        want = model.get((form, k, c1, c2) if form == "split" else (form, k, (c1, c2)))
        if want is None:
            print("  %s k=%d case %d,%d: largest direct count %d, the model has no case" % (form, k, c1, c2, direct[key]))
            continue
        wrong += direct[key] > want
        print("  %s k=%d case %d,%d: largest direct count %d, model %d, %s" % (
            form, k, c1, c2, direct[key], want, "ok" if direct[key] <= want else "MODEL VIOLATION"))
    print("model violations: %d" % wrong)
    print("largest direct count with an antipodal pair: %d" % (max(direct.values()) if direct else 0))


main()
