#!/usr/bin/env python3
"""Side check for Section 1 of my report on IIS-Q-0002: the tables of the paper.

Table 1 of "Large caps in small spaces" by Y. Edel and J. Bierbrauer gives ten blocks.
Table 2 of the copy of the paper that I used prints the type Dbar for the prefixes 0 and 1.
This program builds the four sets of 236 points that have the type D or the type Dbar for the
prefixes 0 and 1.  It counts the lines of each set.

usage: python3 -I check_paper_table.py
The program reads no file.  It uses the standard library only (hashlib, itertools).
"""
import hashlib
import itertools

BLOCKS = ["123", "124", "135", "146", "156", "236", "245", "256", "345", "346"]
KNOWN_HASH = "1d6a5c73bd44d4cd99e40cf97644dd4a0c37f1bd39e3f6edfc47fd9756240efe"
WITNESS = ["0110010", "1120020", "2100000"]
n_fail = 0


def check(cond, what):
    global n_fail
    if cond:
        print("PASS: " + what)
    else:
        n_fail += 1
        print("FAIL: " + what)


def digits(x):
    return "".join(str(v) for v in x)


def all_triples():
    return [frozenset(t) for t in itertools.combinations(range(6), 3)]


def design_property(blocks):
    """True if each point is in 5 blocks and each pair of points is in exactly 2 blocks."""
    blocks = [frozenset(int(c) - 1 for c in b) for b in blocks]
    if len(set(blocks)) != 10 or any(len(b) != 3 for b in blocks):
        return False
    for p in range(6):
        if sum(p in b for b in blocks) != 5:
            return False
    for p, q in itertools.combinations(range(6), 2):
        if sum(p in b and q in b for b in blocks) != 2:
            return False
    return True


def vectors_d(blocks):
    """Weight 3, the support is a block, no entry 0."""
    out = []
    for b in blocks:
        s = [int(c) - 1 for c in b]
        for e in itertools.product((1, 2), repeat=3):
            v = [0] * 6
            for pos, val in zip(s, e):
                v[pos] = val
            out.append(tuple(v))
    return out


def vectors_r():
    """Weight 6, an even number of entries 2."""
    return [v for v in itertools.product((1, 2), repeat=6) if v.count(2) % 2 == 0]


def vectors_u():
    """Weight 1."""
    return [tuple(a if j == i else 0 for j in range(6)) for i in range(6) for a in (1, 2)]


def build(first, second):
    """The points (t, v): t = 0 and 1 with the type D of the argument, and t = 2 with type U."""
    r, u = vectors_r(), vectors_u()
    return set([(0,) + v for v in first] + [(0,) + v for v in r]
                + [(1,) + v for v in second] + [(1,) + v for v in r] + [(2,) + v for v in u])


def lines_of(points):
    """The number of lines in the set, and the lines in increasing order."""
    pts = sorted(points)
    found = []
    for x, y in itertools.combinations(pts, 2):
        z = tuple(-(a + b) % 3 for a, b in zip(x, y))
        if y < z and z in points:
            found.append((x, y, z))
    return len(found), found


def coordinate_hash(points):
    text = "".join(digits(x) + "\n" for x in sorted(points))
    return hashlib.sha256(text.encode("ascii")).hexdigest()


def main():
    blocks = [frozenset(int(c) - 1 for c in b) for b in BLOCKS]
    other = [t for t in all_triples() if t not in blocks]
    check(len(blocks) == 10 and design_property(BLOCKS),
          "the ten blocks of Table 1 are on 6 points; each point is in 5 blocks; each pair of points is in exactly 2 blocks")
    check(len(other) == 10 and design_property(["".join(str(p + 1) for p in sorted(t)) for t in other]),
          "the other ten triples form a design with the same two properties")
    other_names = ["".join(str(p + 1) for p in sorted(t)) for t in other]
    d, db, r, u = vectors_d(BLOCKS), vectors_d(other_names), vectors_r(), vectors_u()
    check((len(d), len(db), len(r), len(u)) == (80, 80, 32, 12), "the types have 80, 80, 32 and 12 vectors")

    table = [
        ("A", "(0,D) (0,R) (1,Dbar) (1,R) (2,U)", d, db, 0),
        ("B", "(0,Dbar) (0,R) (1,Dbar) (1,R) (2,U)", db, db, 240),
        ("C", "(0,Dbar) (0,R) (1,D) (1,R) (2,U)", db, d, 0),
        ("D", "(0,D) (0,R) (1,D) (1,R) (2,U)", d, d, 240),
    ]
    sets, lines = {}, {}
    for name, desc, first, second, want in table:
        pts = build(first, second)
        n, found = lines_of(pts)
        sets[name], lines[name] = pts, found
        print("SET %s %s: points %d, lines %d, coordinate hash %s" % (name, desc, len(pts), n, coordinate_hash(pts)))
        if found:
            print("FIRST LINE of set %s: %s %s %s" % (name, digits(found[0][0]), digits(found[0][1]), digits(found[0][2])))
        check(len(pts) == 236, "set %s has 236 points" % name)
        check(n == want, "set %s has %d lines" % (name, want))
    check(coordinate_hash(sets["A"]) == KNOWN_HASH, "the coordinate hash of set A is the hash of the question")
    # Count of the lines of set B by hand: 10 blocks, 3 coordinates of the block, 2 values of the
    # entry of the point of type U, 4 choices of the two other entries.
    check(10 * 3 * 2 * 4 == 240, "the count by hand gives 10 * 3 * 2 * 4 = 240 lines")

    def support(v):
        return frozenset(j for j in range(1, 7) if v[j])

    # Structure of the lines of the sets with one design: one point in each layer, the two points of
    # weight 3 have one support, and it is a block that contains the coordinate of the third point.
    for name, design in (("B", other), ("D", blocks)):
        check(all(x[0] == 0 and y[0] == 1 and z[0] == 2 and support(x) == support(y)
                  and frozenset(j - 1 for j in support(x)) in design and support(z) <= support(x)
                  for x, y, z in lines[name]),
              "each line of set %s has one point in each layer, and the two points of weight 3 have one block as support" % name)

    w = [tuple(int(c) for c in s) for s in WITNESS]
    total = tuple(sum(x[i] for x in w) % 3 for i in range(7))
    check(total == (0,) * 7, "the three points %s add to 0" % " ".join(WITNESS))
    check(tuple(sorted(w)) in lines["B"], "the three points are in set B and form one of its lines")
    check(frozenset((0, 1, 4)) not in blocks, "125 is not a block of Table 1")
    check(w[0] not in sets["A"] and w[1] in sets["A"] and w[2] in sets["A"],
          "the first point is not in set A; the two other points are in set A")
    check(w[0] in sets["C"] and w[1] not in sets["C"] and w[2] in sets["C"],
          "the second point is not in set C; the two other points are in set C")
    print("WITNESS LINE of set B: %s" % " ".join(WITNESS))
    if n_fail:
        print("FAILED CHECKS: %d" % n_fail)
        return 1
    print("ALL CHECKS PASSED")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
