"""2kwas: independent check of iis:2611.00310 (IIS-Q-0002, the 236-point cap in F_3^7).

Written from the definitions in the paper (and Edel-Bierbrauer's design); the authors' programs were not run.
Prints every number the paper states, so they can be compared line by line.

usage: python3 -I cap_check.py > cap_check.out
"""
import itertools, hashlib
from collections import Counter, defaultdict
import numpy as np

# ---------------------------------------------------------------- points, designs, the cap
D_TXT = ['123', '124', '135', '146', '156', '236', '245', '256', '345', '346']
DES = [frozenset(int(c) for c in b) for b in D_TXT]
TRIPLES = [frozenset(c) for c in itertools.combinations(range(1, 7), 3)]
DBAR = [b for b in TRIPLES if b not in DES]


def design_ok(des):
    pt = Counter(j for b in des for j in b)
    pr = Counter(p for b in des for p in itertools.combinations(sorted(b), 2))
    return len(des) == 10 and set(pt.values()) == {5} and len(pr) == 15 and set(pr.values()) == {2}


ALL = list(itertools.product(range(3), repeat=7))           # x = (x0; x1..x6), x0 = prefix
def supp(x): return frozenset(j for j in range(1, 7) if x[j])
def n2(x): return sum(1 for j in range(1, 7) if x[j] == 2)
def third(x, y): return tuple((-a - b) % 3 for a, b in zip(x, y))
def s7(x): return ''.join(map(str, x))


def build(des0, des1):
    C = []
    for x in ALL:
        p, s = x[0], supp(x)
        if p in (0, 1):
            des = des0 if p == 0 else des1
            if (len(s) == 3 and s in des) or (len(s) == 6 and n2(x) % 2 == 0):
                C.append(x)
        elif len(s) == 1:
            C.append(x)
    return C


def count_lines(C):
    S = set(C)
    return sum(1 for x, y in itertools.combinations(C, 2) if third(x, y) in S) // 3


def typ(x):
    w = len(supp(x))
    if x[0] == 2: return 'U'
    if w == 6: return 'R'
    return 'D' if x[0] == 0 else "D'"


print("design D: 10 blocks, each point in 5, each pair in 2:", design_ok(DES))
print("complement Dbar:", sorted(''.join(map(str, sorted(b))) for b in DBAR), "same parameters:", design_ok(DBAR))

C = build(DES, DBAR)
S = set(C)
print("cap size", len(C), "by type", dict(Counter(typ(x) for x in C)))
print("lines in C (should be 0):", count_lines(C))
rows = sorted(s7(x) for x in C)
target = '1d6a5c73bd44d4cd99e40cf97644dd4a0c37f1bd39e3f6edfc47fd9756240efe'
for name, data in [("rows joined by \\n, final \\n", '\n'.join(rows) + '\n'), ("rows joined by \\n", '\n'.join(rows)),
                   ("rows concatenated", ''.join(rows))]:
    h = hashlib.sha256(data.encode()).hexdigest()
    print("sha256 (%s): %s %s" % (name, h, "MATCHES the stated hash" if h == target else ""))

print("the four layer-design choices (prefix 0, prefix 1): number of lines")
for n0, d0 in (("D", DES), ("Dbar", DBAR)):
    for n1, d1 in (("D", DES), ("Dbar", DBAR)):
        print("   ", n0, n1, count_lines(build(d0, d1)))
CC = build(DBAR, DBAR)
ex = [(1, 0, 1, 0, 0, 1, 0)[:0] or tuple(int(c) for c in s) for s in ('0110010', '1120020', '2100000')]
print("example line 0110010 + 1120020 + 2100000 = 0 in the Dbar/Dbar set:", all(e in set(CC) for e in ex),
      third(ex[0], ex[1]) == ex[2])

# ---------------------------------------------------------------- secants of outside points
OUT = [z for z in ALL if z not in S]
sec = defaultdict(list)
for x, y in itertools.combinations(C, 2):
    z = third(x, y)
    assert z not in S
    sec[z].append((x, y))
cnt = {z: len(sec[z]) for z in OUT}
print("outside points", len(OUT), "with a secant", sum(1 for z in OUT if cnt[z] > 0))
print("secant histogram", sorted(Counter(cnt.values()).items()), "sum", sum(cnt.values()), "C(236,2) =", 236 * 235 // 2)
cls = Counter((('0/1' if z[0] < 2 else '2'), len(supp(z)), cnt[z]) for z in OUT)
print("classes (prefix, weight, secants): points")
for k in sorted(cls): print("   ", k, cls[k])

O = sorted(z for z in OUT if cnt[z] == 10)
O_expected = sorted(tuple([t] + [a if j == i else 0 for j in range(1, 7)]) for t in (0, 1) for a in (1, 2) for i in range(1, 7))
print("|O| =", len(O), " O = {(t, a e_i)}:", O == O_expected, " min secant count over outside points:", min(cnt.values()))
ends = {z: {p for e in sec[z] for p in e} for z in O}
print("each z in O: 10 secants on 20 distinct endpoints:", all(len(sec[z]) == 10 and len(ends[z]) == 20 for z in O))
U = {frozenset(e): z for z in O for e in sec[z]}
print("|U| =", len(U), "(240 pairs expected; total secants of O:", sum(len(sec[z]) for z in O), ")")
inc = Counter()
for e in U:
    for p in e: inc[p] += 1
hist = Counter(inc[p] for p in C)
print("incidence histogram over cap points", sorted(hist.items()),
      " points in no pair by type", dict(Counter(typ(p) for p in C if inc[p] == 0)),
      " in three pairs by type", dict(Counter(typ(p) for p in C if inc[p] == 3)))

# ---------------------------------------------------------------- components of the 240-pair graph
adj = defaultdict(set)
for e in U:
    a, b = tuple(e); adj[a].add(b); adj[b].add(a)
seen, comps = set(), []
for v in adj:
    if v in seen: continue
    stack, comp = [v], set()
    while stack:
        u = stack.pop()
        if u in comp: continue
        comp.add(u); stack.extend(adj[u] - comp)
    seen |= comp; comps.append(comp)
k4 = all(len(c) == 4 and sum(len(adj[u] & c) for u in c) == 12 for c in comps)
same_part = all(len({(u[0], supp(u), n2(u) % 2) for u in c}) == 1 for c in comps)
print("components:", len(comps), " all K4:", k4, " each = one part (prefix, support, parity of #2s):", same_part)
Oidx = {z: i for i, z in enumerate(O)}
labels_ok = True
comp_edges = []
for c in comps:
    cl = sorted(c)
    es = []
    for a, b in itertools.combinations(range(4), 2):
        z = U[frozenset((cl[a], cl[b]))]
        es.append((a, b, Oidx[z]))
    t = cl[0][0]; B = supp(cl[0])
    if sorted(O[i] for _, _, i in es) != sorted(tuple([t] + [a if j == i else 0 for j in range(1, 7)]) for i in B for a in (1, 2)):
        labels_ok = False
    comp_edges.append(es)
print("labels of the six pairs of each part = the six points (t, a e_i), i in B:", labels_ok)


def min_vc_small(edges, nv=4):
    best = nv
    for m in range(1 << nv):
        if all((m >> a) & 1 or (m >> b) & 1 for a, b in edges):
            best = min(best, bin(m).count('1'))
    return best


VC = []
for es in comp_edges:
    VC.append(np.array([min_vc_small([(a, b) for j, (a, b, _) in enumerate(es) if (s >> j) & 1]) for s in range(64)], dtype=np.int16))

# ---------------------------------------------------------------- tau(T) and c(T) for all 2^24 subsets T of O
N = 1 << 24
T = np.arange(N, dtype=np.uint32)
tau = np.zeros(N, dtype=np.int16)
for es, tab in zip(comp_edges, VC):
    idx = np.zeros(N, dtype=np.uint32)
    for j, (_, _, lab) in enumerate(es):
        idx |= ((T >> np.uint32(lab)) & np.uint32(1)) << np.uint32(j)
    tau += tab[idx]
k = np.bitwise_count(T).astype(np.int16)
f = np.zeros(N, dtype=np.int16)
for i in range(1, 7):
    for a in (1, 2):
        z0 = Oidx[tuple([0] + [a if j == i else 0 for j in range(1, 7)])]
        z1 = Oidx[tuple([1] + [a if j == i else 0 for j in range(1, 7)])]
        f += (((T >> np.uint32(z0)) & 1) & ((T >> np.uint32(z1)) & 1)).astype(np.int16)
cost = tau + f
print("Table 3 / Table 6: k, least tau (#), largest tau (#), ceil(10k/3), least cost, largest cost, largest cap 236+k-least cost")
for kk in range(25):
    sel = k == kk
    tk, ck = tau[sel], cost[sel]
    lo, hi = int(tk.min()), int(tk.max())
    print("   %2d  %3d (%6d)  %3d (%6d)  %3d   %3d  %3d  %3d" % (kk, lo, int((tk == lo).sum()), hi, int((tk == hi).sum()),
          -(-10 * kk // 3), int(ck.min()), int(ck.max()), 236 + kk - int(ck.min())))
for kk in (1, 2, 3, 4):
    sel = k == kk
    print("Table 4, k=%d tau distribution:" % kk, sorted(Counter(tau[sel].tolist()).items()))
    print("Table 5, k=%d cost distribution:" % kk, sorted(Counter(cost[sel].tolist()).items()))
print("least tau > max(10, ceil(10k/3)) for every k >= 2:",
      all(int(tau[k == kk].min()) > max(10, -(-10 * kk // 3)) for kk in range(2, 25)))

# ---------------------------------------------------------------- direct check of c(T) without the part structure
def insertion_cost(Tset):
    """least |D|, D subset of C, with (C - D) + T a cap: exact vertex cover with forced vertices, generic search"""
    Tl = list(Tset)
    for a, b in itertools.combinations(Tl, 2):
        assert third(a, b) not in set(Tl)                        # T itself is a cap
    forced = {third(a, b) for a, b in itertools.combinations(Tl, 2) if third(a, b) in S}
    edges = set()
    for z in Tl:
        for x in C:
            y = third(x, z)
            if y in S and x != y:
                e = frozenset((x, y))
                if not (e & forced): edges.add(e)
    edges = [tuple(e) for e in edges]
    return len(forced) + vc_exact(edges)


def vc_exact(edges):
    if not edges: return 0
    g = defaultdict(set)
    for a, b in edges: g[a].add(b); g[b].add(a)
    # split into connected components
    seen, total = set(), 0
    for v in list(g):
        if v in seen: continue
        st, comp = [v], set()
        while st:
            u = st.pop()
            if u in comp: continue
            comp.add(u); st.extend(g[u] - comp)
        seen |= comp
        ce = [(a, b) for a, b in edges if a in comp]
        total += vc_branch(ce)
    return total


def vc_branch(edges):
    if not edges: return 0
    g = defaultdict(set)
    for a, b in edges: g[a].add(b); g[b].add(a)
    v = max(g, key=lambda u: len(g[u]))
    if len(g[v]) == 1:                                           # matching
        return len(edges)
    r1 = 1 + vc_exact([e for e in edges if v not in e])          # take v
    nb = g[v]
    r2 = len(nb) + vc_exact([e for e in edges if not (set(e) & nb)])   # take all neighbours of v
    return min(r1, r2)


Ol = O
bad = 0; nchk = 0
for kk in (1, 2, 3):
    for Tt in itertools.combinations(range(24), kk):
        m = sum(1 << i for i in Tt)
        c_direct = insertion_cost([Ol[i] for i in Tt])
        nchk += 1
        if c_direct != int(cost[m]): bad += 1
print("direct cost = tau + f for all subsets with k <= 3:", nchk, "subsets,", bad, "mismatches")
rng = np.random.default_rng(20261128)
bad = 0; nchk = 0
for kk in range(4, 25):
    for _ in range(40):
        Tt = sorted(rng.choice(24, size=kk, replace=False).tolist())
        m = sum(1 << i for i in Tt)
        nchk += 1
        if insertion_cost([Ol[i] for i in Tt]) != int(cost[m]): bad += 1
print("direct cost = tau + f on random subsets with k = 4..24 (40 each):", nchk, "subsets,", bad, "mismatches")

# ---------------------------------------------------------------- Section 9: the four points A and the deletion set D
A = [tuple(int(c) for c in s) for s in ('0000001', '0000010', '0000100', '2112222')]
print("A outside C:", all(a not in S for a in A), " secant counts", [cnt[a] for a in A])
pairsA = {frozenset(e) for a in A for e in sec[a]}
print("pairs of A:", sum(cnt[a] for a in A), "distinct:", len(pairsA))
forcedA = {third(a, b) for a, b in itertools.combinations(A, 2) if third(a, b) in S}
print("forced deletions (third point of two points of A in C):", len(forcedA), " cost of A:", insertion_cost(A))
Dtxt = "0001101 0001110 0002101 0002110 0010011 0010110 0011001 0020011 0020110 0021001 0100011 0100101 0101010 0112222 0120100 0200011 0200101 0201010 0220100 0221000".split()
Dset = {tuple(int(c) for c in s) for s in Dtxt}
NEW = [x for x in C if x not in Dset] + A
print("|D| =", len(Dset), " D subset of C:", Dset <= S, " |(C-D)+A| =", len(NEW), " lines:", count_lines(NEW))
NS = set(NEW)
nosec = [z for z in ALL if z not in NS and not any(third(x, z) in NS and third(x, z) != x for x in NEW)]
print("outside points of (C-D)+A without a secant:", len(nosec), "; are they exactly A:", sorted(nosec) == sorted(A))
# structure of the 41 pairs of A as a graph: component shapes
ga = defaultdict(set)
for e in pairsA:
    a, b = tuple(e); ga[a].add(b); ga[b].add(a)
seen, shapes = set(), Counter()
for v in ga:
    if v in seen: continue
    st, comp = [v], set()
    while st:
        u = st.pop()
        if u in comp: continue
        comp.add(u); st.extend(ga[u] - comp)
    seen |= comp
    ne = sum(len(ga[u] & comp) for u in comp) // 2
    degs = sorted(len(ga[u] & comp) for u in comp)
    shapes[(len(comp), ne, tuple(degs))] += 1
print("components of the 41 pairs (vertices, edges, degrees): count", sorted(shapes.items()))

# ---------------------------------------------------------------- Section 7: the 3840 maps
def apply(x, perm, flips, swap):
    y = [0] * 7
    y[0] = (1 - x[0]) if (swap and x[0] < 2) else x[0]
    for j in range(1, 7):
        v = x[j]
        if flips >> (j - 1) & 1: v = (-v) % 3
        y[perm[j]] = v
    return tuple(y)


maps = []
for p in itertools.permutations(range(1, 7)):
    perm = dict(zip(range(1, 7), p))
    img = {frozenset(perm[j] for j in b) for b in DES}
    if img == set(DES): swap = False
    elif img == set(DBAR): swap = True
    else: continue
    for flips in range(64):
        if bin(flips).count('1') % 2 == 0:
            maps.append((perm, flips, swap))
npres = sum(1 for p in itertools.permutations(range(1, 7)) if {frozenset(dict(zip(range(1, 7), p))[j] for j in b) for b in DES} == set(DES))
print("permutations keeping D:", npres, " maps:", len(maps), " each maps C onto C:",
      all({apply(x, *mp) for x in C} == S for mp in maps))
# orbits on outside points
orb = {}
oid = 0
for z in OUT:
    if z in orb: continue
    st = [z]
    while st:
        u = st.pop()
        if u in orb: continue
        orb[u] = oid
        st.extend(apply(u, *mp) for mp in maps)
    oid += 1
osz = Counter(orb.values())
print("orbits on outside points:", oid, " sizes:", sorted(osz.values()))
print("orbits = the 14 classes (prefix 0/1 or 2, weight, secants):",
      len({(('0/1' if z[0] < 2 else '2'), len(supp(z)), cnt[z]) for z in OUT}) == oid and
      all(len({(('0/1' if z[0] < 2 else '2'), len(supp(z)), cnt[z]) for z in OUT if orb[z] == o}) == 1 for o in range(oid)))
small = sorted(osz[o] for o in range(oid) if cnt[next(z for z in OUT if orb[z] == o)] <= 21)
print("orbits with at most 21 secants:", len(small), "sizes", small, "total", sum(small))

# ---------------------------------------------------------------- Section 9, last sentence, read as: outside points of C
# (points not in C) that have no secant inside C - D
CD = [x for x in C if x not in Dset]
CDS = set(CD)
free = [z for z in ALL if z not in S and not any(third(x, z) in CDS and third(x, z) != x for x in CD)]
print("points outside C with no secant in C - D:", len(free), "; exactly A:", sorted(free) == sorted(A))
free2 = [z for z in ALL if z not in CDS and not any(third(x, z) in CDS and third(x, z) != x for x in CD)]
print("points outside C - D (deleted points included) with no secant in C - D:", len(free2),
      "= A plus the deleted points:", sorted(free2) == sorted(A + list(Dset)))
print("(C - D) + A is a complete cap (every other point has a secant in it):", len(nosec) == 0)

# ---------------------------------------------------------------- iis:2611.00005 witness quoted in Section 9 of the paper
T5 = [tuple(int(c) for c in s) for s in "0000001 0000010 0000100".split()]
D5 = {tuple(int(c) for c in s) for s in ("0001101 0001110 0002101 0002110 0010011 0010110 0011001 0012001 0020011 0020110 "
                                          "0100011 0100101 0101010 0102010 0110100 0120100 0200011 0200101").split()}
N5 = [x for x in C if x not in D5] + T5
print("00005 witness: T in O:", all(t in set(O) for t in T5), "|D| =", len(D5), "D in C:", D5 <= S,
      "|(C-D)+T| =", len(N5), "lines:", count_lines(N5), "cost of T:", insertion_cost(T5))
# iis:2611.00005 subgraph counts over all 2024 triples of O: shapes of connected components inside the parts
shape = Counter()
for Tt in itertools.combinations(range(24), 3):
    Ts = set(Tt)
    for es in comp_edges:
        sub = [(a, b) for a, b, lab in es if lab in Ts]
        if not sub: continue
        g = defaultdict(set)
        for a, b in sub: g[a].add(b); g[b].add(a)
        seen = set()
        for v in g:
            if v in seen: continue
            st, cp = [v], set()
            while st:
                u = st.pop()
                if u in cp: continue
                cp.add(u); st.extend(g[u] - cp)
            seen |= cp
            ne = sum(len(g[u] & cp) for u in cp) // 2
            degs = tuple(sorted(len(g[u] & cp) for u in cp))
            name = {(2, 1): 'single edge', (3, 2): 'three-vertex path'}.get((len(cp), ne))
            if name is None:
                name = {(1, 1, 2, 2): 'four-vertex path', (1, 1, 1, 3): 'three-leaf star', (2, 2, 2): 'triangle'}.get(degs, str((len(cp), ne, degs)))
            shape[name] += 1
print("component shapes over all 2024 triples:", dict(shape))
