#!/usr/bin/env python3
"""Independent check of IIS-Q-0002 (cap set problem, isitsolved.com).

The question (ExactMargin).  Let C be the 236-point cap of Calderbank and Fishburn
in AG(7,3), in the coordinates of Edel and Bierbrauer, "Large caps in small
spaces", Table 1 (the design), Table 2 (the five layer types), Theorem 5.
For an outside point z let E(z) = {{a,b} in C : a != b, a + b + z = 0}, and let
O = {z : |E(z)| = 10}.  Claim: |O| = 24, and the number of pairs of
U E(z), z in O, through a point of C is 0 for 76 points and 3 for 160 points.
So k inserted points of O need at least ceil(10 k / 3) deletions.

This script builds the cap from the tables of the paper.  It checks the claim and
sharper statements by complete enumeration.  It needs Python 3.8 or later and the
standard library only.  It reads no file and it uses no random source.
Run:  python3 verify_q0002.py
The script ends with the line "ALL CHECKS PASSED" or it stops with an error.
"""
import hashlib
import itertools
from collections import Counter
from math import ceil, comb

# ------------------------------------------------------------------ the cap
# Table 1 of Edel and Bierbrauer: the ten blocks of the design D : 2-(6,3,2).
DESIGN = [(1, 2, 3), (2, 3, 6), (1, 2, 4), (2, 4, 5), (1, 3, 5),
          (2, 5, 6), (1, 4, 6), (3, 4, 5), (1, 5, 6), (3, 4, 6)]
ALL_TRIPLES = list(itertools.combinations(range(1, 7), 3))
CODESIGN = [t for t in ALL_TRIPLES if t not in DESIGN]

ZERO = (0,) * 7
ALL_POINTS = list(itertools.product(range(3), repeat=7))

PUBLISHED_HISTOGRAM = {10: 24, 11: 416, 12: 480, 13: 160, 14: 120, 15: 192,
                       16: 224, 18: 240, 25: 60, 30: 32, 38: 1, 56: 2}
PUBLISHED_HASH = "1d6a5c73bd44d4cd99e40cf97644dd4a0c37f1bd39e3f6edfc47fd9756240efe"


def check(cond, what):
    if not cond:
        print("FAIL: " + what)
        raise SystemExit(1)
    print("PASS: " + what)


def neg(x):
    return tuple(-a % 3 for a in x)


def add(x, y):
    return tuple((a + b) % 3 for a, b in zip(x, y))


def digits(x):
    return "".join(map(str, x))


def support(x):
    return [i for i in range(1, 7) if x[i]]


def suffixes_support(block):
    """All suffixes of weight 3 with support `block` (8 suffixes)."""
    out = []
    for vals in itertools.product((1, 2), repeat=3):
        s = [0] * 6
        for i, a in zip(block, vals):
            s[i - 1] = a
        out.append(tuple(s))
    return out


def suffixes_R():
    """Type R: weight 6, an even number of entries 2 (32 suffixes)."""
    return [v for v in itertools.product((1, 2), repeat=6) if v.count(2) % 2 == 0]


def suffixes_U():
    """Type U: weight 1 (12 suffixes)."""
    out = []
    for i in range(6):
        for a in (1, 2):
            s = [0] * 6
            s[i] = a
            out.append(tuple(s))
    return out


def build_cap():
    """Table 2: (0,D), (0,R), (1,Dbar), (1,R), (2,U).  A point is (prefix, 6 suffix digits)."""
    cap = set()
    for block in DESIGN:
        cap.update((0,) + s for s in suffixes_support(block))
    for s in suffixes_R():
        cap.add((0,) + s)
        cap.add((1,) + s)
    for block in CODESIGN:
        cap.update((1,) + s for s in suffixes_support(block))
    cap.update((2,) + s for s in suffixes_U())
    return cap


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


# ------------------------------------------------------------ two cap tests
def third_points(S):
    """Method 1.  The third point -x-y of the line through each pair x,y of S."""
    return [add(neg(x), neg(y)) for x, y in itertools.combinations(sorted(S), 2)]


def lines_inside(S):
    """Method 1: the lines with all three points in S, as sets of 3 points (each line is found three times)."""
    out = set()
    for x, y in itertools.combinations(sorted(S), 2):
        t = add(neg(x), neg(y))
        if t in S:
            out.add(frozenset((x, y, t)))
    return out


def directions():
    """The 1093 directions with first nonzero digit 1."""
    return [d for d in ALL_POINTS if d != ZERO and next(a for a in d if a) == 1]


def scan_lines(S):
    """Method 2: visit each of the 796797 lines of AG(7,3) once; return (number of lines, most points of S on one line, Counter of the outside point of each line with two points of S)."""
    most, n_lines, sec = 0, 0, Counter()
    for d in directions():
        dd = add(d, d)
        for p in ALL_POINTS:
            q, r = add(p, d), add(p, dd)
            if not (p < q and p < r):
                continue
            n_lines += 1
            k = (p in S) + (q in S) + (r in S)
            most = max(most, k)
            if k == 2:
                sec[p if p not in S else q if q not in S else r] += 1
    return n_lines, most, sec


# ------------------------------------------------------------ vertex covers
def components(vertices, edges):
    """The connected parts with at least one edge, each as a sorted list."""
    adj = {v: set() for v in vertices}
    for a, b in edges:
        adj[a].add(b)
        adj[b].add(a)
    seen, out = set(), []
    for v in sorted(vertices):
        if v in seen or not adj[v]:
            continue
        stack, comp = [v], set()
        while stack:
            u = stack.pop()
            if u in comp:
                continue
            comp.add(u)
            stack.extend(adj[u])
        seen |= comp
        out.append(sorted(comp))
    return out


def min_cover(vertices, edges):
    """A smallest vertex cover of the graph, as (size, set); each connected part has at most 16 vertices, and all its subsets are examined."""
    size, cover = 0, set()
    for comp in components(vertices, edges):
        if len(comp) > 16:
            print("FAIL: a connected part of a blocking graph has more than 16 vertices")
            raise SystemExit(1)
        cs = set(comp)
        ce = [e for e in edges if e[0] in cs]
        found = None
        for n in range(len(comp) + 1):
            for sub in itertools.combinations(comp, n):
                s = set(sub)
                if all(a in s or b in s for a, b in ce):
                    found = s
                    break
            if found is not None:
                break
        size += len(found)
        cover |= found
    return size, cover


def tau(edges):
    """Size of a smallest vertex cover of the graph with these edges."""
    return min_cover({v for e in edges for v in e}, edges)[0]


# ------------------------------------------------------------ main checks
def main():
    print("== A. construction from the tables of the paper")
    check(len(DESIGN) == 10 and len(set(DESIGN)) == 10 and len(CODESIGN) == 10,
          "the design has 10 different blocks, its complement has 10 blocks")
    pair_count = Counter(tuple(sorted((b[i], b[j]))) for b in DESIGN for i, j in itertools.combinations(range(3), 2))
    check(pair_count == {p: 2 for p in itertools.combinations(range(1, 7), 2)},
          "each pair of coordinates 1..6 is in exactly two blocks (2-(6,3,2) design)")
    check([len(f()) for f in (suffixes_R, suffixes_U)] == [32, 12]
          and all(len(suffixes_support(b)) == 8 for b in ALL_TRIPLES),
          "types D and Dbar give 80 suffixes each, R gives 32, U gives 12")
    cap = build_cap()
    check(len(cap) == 236, "the five layer types give 236 different points")
    check(Counter(x[0] for x in cap) == {0: 112, 1: 112, 2: 12}, "the layers have 112, 112 and 12 points")
    check(coordinate_hash(cap) == PUBLISHED_HASH,
          "SHA-256 of the sorted 7-digit rows (one final LF each) is " + PUBLISHED_HASH)
    pts = sorted(cap)

    print("== B. the cap property, two methods")
    thirds = third_points(cap)
    check(len(thirds) == comb(236, 2) == 27730, "there are 27730 pairs of cap points")
    check(not lines_inside(cap) and len(thirds) == 27730,
          "method 1 (pair sums): no third point of a pair is in the cap")
    n_lines, most, sec2 = scan_lines(cap)
    check(len(directions()) == 1093 and n_lines == 796797, "method 2 visits each of the 796797 lines of AG(7,3) once")
    check(most == 2, "method 2 (all lines): no line has three cap points")

    print("== C. secant counts, two methods")
    sec1 = Counter(t for t in thirds if t not in cap)
    check(sec1 == sec2, "the two methods give the same secant count for each of the 1951 outside points")
    check(dict(sorted(Counter(sec1.values()).items())) == PUBLISHED_HISTOGRAM,
          "secant histogram 10:24, 11:416, 12:480, 13:160, 14:120, 15:192, 16:224, 18:240, 25:60, 30:32, 38:1, 56:2")
    check(len(sec1) == 1951 and sum(sec1.values()) == 27730, "1951 outside points and 27730 secants in total")
    by_class = Counter((z[0], len(support(z)), sec1[z]) for z in sec1)
    check(dict(sorted(by_class.items())) == {
        (0, 0, 56): 1, (0, 1, 10): 12, (0, 2, 14): 60, (0, 3, 13): 80, (0, 4, 12): 240,
        (0, 5, 11): 192, (0, 6, 16): 32,
        (1, 0, 56): 1, (1, 1, 10): 12, (1, 2, 14): 60, (1, 3, 13): 80, (1, 4, 12): 240,
        (1, 5, 11): 192, (1, 6, 16): 32,
        (2, 0, 38): 1, (2, 2, 25): 60, (2, 3, 16): 160, (2, 4, 18): 240, (2, 5, 15): 192,
        (2, 6, 11): 32, (2, 6, 30): 32},
        "by (prefix, suffix weight): the count 10 occurs only for suffix weight 1 in layers 0 and 1")

    print("== C2. symmetries: each class of the table is one orbit")
    IDENT = (1, 2, 3, 4, 5, 6)

    def compose(p, q):
        """The permutation p after q, on the labels 1..6."""
        return tuple(p[q[i - 1] - 1] for i in range(1, 7))

    def design_image(p):
        return {tuple(sorted(p[i - 1] for i in b)) for b in DESIGN}

    P_KEEP = [p for p in itertools.permutations(range(1, 7)) if design_image(p) == set(DESIGN)]
    P_SWAP = [p for p in itertools.permutations(range(1, 7)) if design_image(p) == set(CODESIGN)]
    kind = {p: 0 for p in P_KEEP}
    kind.update({p: 1 for p in P_SWAP})
    PP = P_KEEP + P_SWAP
    check(len(P_KEEP) == 60 and len(P_SWAP) == 60
          and all(compose(p, q) in kind and kind[compose(p, q)] == (kind[p] + kind[q]) % 2
                  for p in PP for q in PP),
          "60 suffix permutations map the design to itself and 60 map it to its complement; the 120 form a group")
    EVENS = [e for e in itertools.product((True, False), repeat=6) if e.count(False) % 2 == 0]

    def image(eps, p, x):
        """The map (eps, p): y[p(i-1)] = eps[i-1] * x[i] for i = 1..6; the prefix changes to 1 - x_0 only if p swaps."""
        y = [0] * 7
        for i in range(1, 7):
            y[p[i - 1]] = x[i] if eps[i - 1] else -x[i] % 3
        y[0] = x[0] if kind[p] == 0 else (1 - x[0]) % 3
        return tuple(y)

    check(len(EVENS) == 32 and EVENS[0] == (True,) * 6
          and all({image(e, p, x) for x in pts} == cap for e in EVENS for p in PP),
          "each of the 32 x 120 = 3840 maps (an even number of suffix sign changes, such a permutation) "
          "maps the cap to itself")

    def orbit(x):
        seen, stack = {x}, [x]
        while stack:
            u = stack.pop()
            for v in [image(e, IDENT, u) for e in EVENS] + [image(EVENS[0], q, u) for q in PP]:
                if v not in seen:
                    seen.add(v)
                    stack.append(v)
        return seen

    orbits, unseen = [], set(ALL_POINTS)
    while unseen:
        o = orbit(min(unseen))
        orbits.append(o)
        unseen -= o

    def class_of(x):
        return ("01" if x[0] in (0, 1) else "2", len(support(x)), sec1[x] if x in sec1 else -1)

    O10 = {z for z, n in sec1.items() if n == 10}
    check(len(O10) == 24 and orbit(min(O10)) == O10,
          "the orbit of one point with 10 secants is the set of the 24 points with 10 secants: they are one orbit")
    out_orbits = [o for o in orbits if not (o & cap)]
    classes = {("01" if x[0] in (0, 1) else "2", len(support(x)), n) for x, n in sec1.items()}
    check(len(out_orbits) == 14 and all(len({class_of(x) for x in o}) == 1 for o in out_orbits)
          and all(sum(1 for o in out_orbits if class_of(min(o)) == cl) == 1 for cl in classes)
          and sorted(len(o) for o in orbits if o & cap) == [12, 64, 160]
          and all(len({class_of(x)[:2] for x in o}) == 1 for o in orbits if o & cap),
          "the 1951 outside points form 14 orbits; each is one class (prefix set {0,1} or {2}, suffix weight, "
          "secant count); the 236 cap points form 3 orbits with 12, 64 and 160 points, each of one layer type U, R, D")
    for o in orbits:
        cl = class_of(min(o))
        print("ORBIT size=%d cap_points=%d prefix_set=%s suffix_weight=%d secants=%s"
              % (len(o), len(o & cap), cl[0], cl[1], "none" if cl[2] < 0 else cl[2]))
    elig = sorted(len(o) for o in out_orbits if max(sec1[x] for x in o) <= 21)
    check(elig == [24, 32, 64, 120, 160, 160, 192, 240, 384, 480] and sum(elig) == 1856,
          "the outside points with at most 21 secants (1856 points) form 10 orbits with 24, 384, 32, 480, 160, 120, 192, "
          "64, 160, 240 points (the numbers of iis:2611.00008 and iis:2611.00029)")

    print("== D. the claim of IIS-Q-0002")
    O = sorted(z for z, n in sec1.items() if n == 10)
    check(O == sorted((t,) + u for t in (0, 1) for u in suffixes_U()),
          "O has 24 points: O = {(t, a e_i) : t in {0,1}, a in {1,2}, i in 1..6}")
    E = {z: set() for z in O}
    for z in O:
        for x in pts:
            y = add(neg(z), neg(x))
            if x < y and y in cap:
                E[z].add((x, y))
    check(all(len(E[z]) == 10 for z in O), "each z in O has exactly 10 blocking pairs")
    check(all(len({v for p in E[z] for v in p}) == 20 for z in O),
          "the 10 blocking pairs of one outsider have 20 different endpoints (a matching)")
    allpairs = set()
    for z in O:
        allpairs |= E[z]
    check(len(allpairs) == 240 == 10 * len(O), "the 240 blocking pairs are 240 different pairs")
    label = {p: z for z in O for p in E[z]}
    check(len(label) == 240, "each blocking pair has one outsider: its sum -a-b determines it")
    deg = Counter()
    for a, b in allpairs:
        deg[a] += 1
        deg[b] += 1
    check(Counter(deg[x] for x in pts) == {0: 76, 3: 160},
          "incidence histogram of the 240 pairs on the 236 cap points: 0 for 76 points, 3 for 160 points")
    check(sum(deg[x] for x in pts) == 480, "480 endpoints in total, that is 2 times 240")

    print("== E. structure (the facts of the proof in the report)")
    check(all(deg[x] == (3 if len(support(x)) == 3 else 0) for x in pts),
          "a point of suffix weight 3 (types D, Dbar) is in 3 pairs; a point of type R or U is in none")
    check(all(a[0] == b[0] and support(a) == support(b) for a, b in allpairs),
          "each blocking pair joins two points of one layer with the same support")
    comps = components(pts, sorted(allpairs))
    check(len(comps) == 40 and all(len(c) == 4 for c in comps),
          "the 240 pairs form 40 connected parts with 4 points each")
    parts = []
    for c in comps:
        ce = [(a, b, label[(a, b)]) for a, b in itertools.combinations(c, 2) if (a, b) in label]
        parts.append((c, ce))
    check(all(len(ce) == 6 and len({z for _, _, z in ce}) == 6 for _, ce in parts),
          "each part is a complete graph K4: its 6 pairs have 6 different outsiders")
    check(Counter(ce[0][2][0] for _, ce in parts) == {0: 20, 1: 20}, "20 parts in layer 0 and 20 parts in layer 1")
    check(Counter(z for _, ce in parts for _, _, z in ce) == Counter({z: 10 for z in O}),
          "each outsider labels exactly one pair in each of 10 parts")
    ok_form = True
    for (x, y), z in label.items():
        i = support(z)[0]
        ok_form = ok_form and x[0] == y[0] == z[0] and x[i] == y[i] == z[i] and support(x) == support(y) \
            and len(support(x)) == 3 and i in support(x) and all(x[j] == neg(y)[j] for j in support(x) if j != i)
    check(ok_form, "form of each blocking pair {x,y} of z = (t, a e_i): x_0 = y_0 = t; x and y have one support, "
                   "a block with i; x_i = y_i = a; x_j = -y_j on the other two coordinates of the block")
    ids = set()
    for c, ce in parts:
        t, B, par = c[0][0], tuple(support(c[0])), c[0][1:].count(2) % 2
        if set(c) == {(t,) + s for s in suffixes_support(B) if s.count(2) % 2 == par}:
            ids.add((t, B, par))
    check(ids == {(t, B, par) for t, BL in ((0, DESIGN), (1, CODESIGN)) for B in BL for par in (0, 1)},
          "the 40 parts are the sets (layer t, block B, parity p): t = 0 with B in the design, t = 1 with B in the "
          "complement design; the part has the 4 suffixes on B with parity p of the number of entries 2")
    ok_k4 = True
    for c, ce in parts:
        for e1, e2 in itertools.combinations(ce, 2):
            same = support(e1[2])[0] == support(e2[2])[0]
            ok_k4 = ok_k4 and len({e1[0], e1[1]} & {e2[0], e2[1]}) == (0 if same else 1)
    check(ok_k4, "in each part: two pairs with labels of one coordinate have no common point; "
                 "two pairs with labels of two coordinates have one common point")
    # the tau value of a part depends only on which of its 6 outsiders are selected
    part_table = []
    for c, ce in parts:
        tab = {}
        for m in range(64):
            sel = {ce[j][2] for j in range(6) if m >> j & 1}
            tab[m] = tau([(a, b) for a, b, z in ce if z in sel])
        part_table.append(tab)
    # The edges of a part, in the order of itertools.combinations: bit j selects ce[j].
    K4E = list(itertools.combinations(range(4), 2))

    def tau_K4_rule(m):
        """The cover size of the part of K4 with the edges of the mask m, by the rule in the report."""
        sel = [K4E[j] for j in range(6) if m >> j & 1]
        n = len(sel)
        if n == 0:
            return 0
        if len(set.intersection(*[set(e) for e in sel])) >= 1:
            return 1
        return 2 if n <= 5 else 3

    check(all(tab[m] == tau_K4_rule(m) for tab in part_table for m in range(64)),
          "cover size in each of the 40 parts for each of its 64 edge sets = the K4 rule "
          "(0 for no edge; 1 if all edges share a point; 2 for 2 to 5 edges without a common point; 3 for 6 edges)")
    pos = [{z: j for j, (_, _, z) in enumerate(ce)} for _, ce in parts]

    def tau_parts(T):
        Ts = set(T)
        return sum(tab[sum(1 << pos[i][z] for z in Ts if z in pos[i])] for i, tab in enumerate(part_table))

    def tau_generic(T):
        return tau(sorted(set().union(*(E[z] for z in T))))

    print("== F. the bound of the question, and the exact numbers")
    ok_eq, ok_bound, n_sub = True, True, 0
    for k in (1, 2, 3):
        for T in itertools.combinations(O, k):
            n_sub += 1
            t = tau_generic(T)
            ok_eq = ok_eq and t == tau_parts(T)
            ok_bound = ok_bound and t >= max(10, ceil(10 * k / 3))
    check(n_sub == 24 + 276 + 2024, "all 2324 subsets of O with at most 3 points are examined")
    check(ok_eq, "for each of them: the cover size by connected parts = the cover size by the 40 K4 parts")
    check(ok_bound, "for each of them: tau >= max(10, ceil(10k/3))")

    # complete enumeration of all 2^24 subsets, by layers (4096 subsets in each layer)
    layers = [[z for z in O if z[0] == t] for t in (0, 1)]
    dist = []
    for t in (0, 1):
        idx = [i for i, (_, ce) in enumerate(parts) if ce[0][2][0] == t]
        d = Counter()
        for r in range(1 << len(layers[t])):
            T = [layers[t][i] for i in range(len(layers[t])) if r >> i & 1]
            d[(len(T), tau_parts(T))] += 1
        dist.append(d)
    check(dist[0] == dist[1], "the two layers give the same table for their 4096 subsets")
    full = Counter()
    for (j0, v0), n0 in dist[0].items():
        for (j1, v1), n1 in dist[1].items():
            full[(j0 + j1, v0 + v1)] += n0 * n1
    ok_cnt = all(sum(n for (k, v), n in full.items() if k == kk) == comb(24, kk) for kk in range(25))
    check(ok_cnt, "the table counts all 2^24 = 16777216 subsets of O, C(24,k) for each k")
    rows = []
    for k in range(25):
        ks = [v for (kk, v), n in full.items() if kk == k and n > 0]
        lo, hi = min(ks), max(ks)
        rows.append((k, lo, full[(k, lo)], hi, full[(k, hi)], ceil(10 * k / 3)))
    check(all(lo >= max(10, ceil(10 * k / 3)) if k else True for k, lo, _, _, _, _ in rows),
          "for each k the least tau is at least max(10, ceil(10k/3))")
    check(rows[1][1] == 10 and rows[24][1] == 120 and rows[24][2] == 1, "tau of one outsider is 10; tau(O) = 120")
    check(all(lo > max(10, ceil(10 * k / 3)) for k, lo, _, _, _, _ in rows if k >= 2),
          "for k = 2..24 the least tau is larger than max(10, ceil(10k/3)): the bound of the question is not sharp")
    check(rows[1][1] == 10 == max(10, ceil(10 / 3)), "for k = 1 the least tau is 10")
    print("\nTAU k least number_of_subsets largest number_of_subsets ceil(10k/3)")
    for k, lo, nlo, hi, nhi, b in rows:
        print("TAU %2d %3d %8d %3d %8d %3d" % (k, lo, nlo, hi, nhi, b))
    print("\nDIST k tau number_of_subsets")
    for (k, v), n in sorted(full.items()):
        print("DIST %2d %3d %8d" % (k, v, n))

    print("== G. joint insertion: least deletions D for a cap (C - D) union T")
    def residual(T):
        """For a set T of outsiders: the forced deletions (points of C on a line through two points of T) and the pairs without a forced endpoint."""
        forced = set()
        for z1, z2 in itertools.combinations(sorted(T), 2):
            p = add(neg(z1), neg(z2))
            if p in cap:
                forced.add(p)
        edges = sorted(set().union(*(E[z] for z in T)))
        return forced, [(a, b) for a, b in edges if a not in forced and b not in forced]

    def joint_cost(T):
        forced, edges = residual(T)
        s, cov = min_cover({v for e in edges for v in e}, edges)
        return len(forced) + s, forced | cov

    def part_kind(comp, edges):
        """The type of one connected part of a blocking graph; key = (points, pairs, largest degree)."""
        cs = set(comp)
        d = Counter(v for a, b in edges if a in cs for v in (a, b))
        table = {(2, 1, 1): "one edge", (3, 2, 2): "path on 3 points", (4, 3, 2): "path on 4 points",
                 (4, 3, 3): "star of 3 edges", (3, 3, 2): "triangle"}
        return table.get((len(comp), sum(d.values()) // 2, max(d.values())), "other")

    expected = {1: {10: 24},
                2: {16: 120, 20: 144, 21: 12},
                3: {18: 160, 21: 160, 26: 1320, 27: 240, 30: 120, 31: 24},
                4: {22: 480, 28: 1680, 29: 480, 30: 240, 31: 1440, 32: 2970, 33: 1080,
                    34: 60, 36: 1560, 37: 600, 40: 30, 42: 6}}
    published_parts = {"one edge": 41040, "path on 3 points": 8640, "path on 4 points": 480,
                       "star of 3 edges": 160, "triangle": 160}
    published_witness = (
        [tuple(int(c) for c in s) for s in "0000001 0000010 0000100".split()],
        [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()])
    direct, witness_all, parts_k = {}, {}, {}
    for k in (1, 2, 3, 4):
        costs, witness, kinds = Counter(), {}, Counter()
        ok_f = True
        for T in itertools.combinations(O, k):
            c, D = joint_cost(T)
            costs[c] += 1
            witness.setdefault(c, (T, D))
            _, edges = residual(T)
            for comp in components({v for e in edges for v in e}, edges):
                kinds[part_kind(comp, edges)] += 1
            Ts = set(T)
            thirds_T = [add(neg(a), neg(b)) for a, b in itertools.combinations(T, 2)]
            F = {p for p in thirds_T if p in cap}
            rule = {(2,) + z[1:] for z in T if z[0] == 0 and (1,) + z[1:] in Ts}
            ok_f = ok_f and F == rule and all(p not in Ts for p in thirds_T) and c == tau_generic(T) + len(rule)
        direct.update({(k, c): n for c, n in costs.items()})
        witness_all[k], parts_k[k] = witness, kinds
        ok_w = True
        for c, (T, D) in sorted(witness.items()):
            S = (cap - D) | set(T)
            ok_w = ok_w and len(D) == c and not (D & set(T)) and not lines_inside(S) and len(S) == 236 - c + k
        print("JOINT k=%d %s" % (k, " ".join("%d:%d" % kv for kv in sorted(costs.items()))))
        check(dict(costs) == expected[k], "k=%d: exact joint insertion costs for all %d subsets" % (k, comb(24, k)))
        check(ok_w, "k=%d: for each cost value, one witness set (C - D) union T has no line" % k)
        check(ok_f, "k=%d: for each subset T: T is a cap; the third point of each pair of T that is in C is a point "
                    "(2, a e_i) with (0, a e_i) and (1, a e_i) in T; cost = tau(T) + the number of these points" % k)
        cmin = min(costs)
        T, D = witness[cmin]
        print("WITNESS k=%d cost=%d T=%s" % (k, cmin, " ".join(digits(z) for z in T)))
        print("WITNESS k=%d D=%s" % (k, " ".join(digits(x) for x in sorted(D))))
    check(min(expected[2]) == 16 and min(expected[3]) == 18 and min(expected[4]) == 22,
          "least joint costs for k=2,3,4 are 16, 18, 22")
    check(dict(parts_k[3]) == published_parts, "k=3: connected parts of all blocking graphs after the forced deletions: "
          "one edge 41040, path on 3 points 8640, path on 4 points 480, star of 3 edges 160, triangle 160 "
          "(the five counts of iis:2611.00005)")
    check(all("other" not in parts_k[k] for k in (1, 2, 3)), "k=1..3: each connected part has one of these five types")
    for k in (1, 2, 3, 4):
        print("PARTS k=%d %s" % (k, " ".join("%s:%d" % kv for kv in sorted(parts_k[k].items()))))
    Tw, Dw = published_witness
    Sw = (cap - set(Dw)) | set(Tw)
    check(len(Tw) == 3 and set(Tw) <= set(O) and len(Dw) == 18 and set(Dw) <= cap and len(Sw) == 221
          and not lines_inside(Sw) and set(witness_all[3][18][0]) == set(Tw) and set(witness_all[3][18][1]) == set(Dw),
          "the witness of iis:2611.00005: its triple T and its 18 deletions D give a cap (C - D) union T with 221 points; "
          "my verifier finds the same T and the same D")

    # cost = tau + f for all 2^24 subsets, by the two layers; bit i of a layer mask selects layers[t][i] (the same (i, a) in both layers)
    tau_layer = [[tau_parts([layers[t][i] for i in range(12) if r >> i & 1]) for r in range(1 << 12)]
                 for t in (0, 1)]
    pc = [bin(r).count("1") for r in range(1 << 12)]
    J = [[0] * 133 for _ in range(25)]
    t0, t1 = tau_layer
    for r0 in range(1 << 12):
        a, k0 = t0[r0], pc[r0]
        for r1 in range(1 << 12):
            J[k0 + pc[r1]][a + t1[r1] + pc[r0 & r1]] += 1
    check(all(sum(J[k]) == comb(24, k) for k in range(25)),
          "the joint cost table counts all 2^24 subsets of O, C(24,k) for each k")
    check(all(J[k][c] == n for (k, c), n in direct.items()) and
          all(J[k][c] == 0 for k in range(1, 5) for c in range(133) if (k, c) not in direct),
          "for k = 1..4 the table cost = tau + f agrees with the direct costs of all 12950 subsets")
    print("\nJOINTALL k cost:number_of_subsets (all 2^24 subsets, by the formula cost = tau + f)")
    for k in range(1, 25):
        print("JOINTALL k=%d %s" % (k, " ".join("%d:%d" % (c, J[k][c]) for c in range(133) if J[k][c])))
    print("\nJMIN k least_cost largest_cost size_of_largest_cap_(C-D)_union_T")
    sizes = []
    for k in range(1, 25):
        cs = [c for c in range(133) if J[k][c]]
        sizes.append(236 - cs[0] + k)
        print("JMIN k=%d %d %d %d" % (k, cs[0], cs[-1], 236 - cs[0] + k))
    check(max(sizes) == 227 == sizes[0], "the largest cap of the form (C - D) union T with T a nonempty subset of O has 227 points")
    print("\nUNLOCK budget largest_k_with_tau_at_most_budget largest_k_with_cost_at_most_budget")
    for d in range(0, 22):
        print("UNLOCK %2d %2d %2d" % (d, max(k for k in range(25) if any(v <= d and n for (kk, v), n in full.items()
                                                               if kk == k)),
                                    max(k for k in range(25) if any(J[k][c] for c in range(d + 1)))))

    print("== H. controls: the tests detect lines and wrong covers")
    for z in O[:4]:
        check(len(lines_inside(cap | {z})) == 10, "control: cap plus %s has exactly 10 lines" % digits(z))
    _, most, _ = scan_lines(cap | {O[0]})
    check(most == 3, "control: the line scan finds a line with 3 points in cap plus one outsider")
    z0 = O[0]
    x = min(v for p in E[z0] for v in p)
    check(deg[x] == 3 and sum(x in p for p in E[z0]) == 1,
          "control: each endpoint of a pair of E(z) is in exactly one pair of E(z), and in 3 pairs in total")
    check(len(lines_inside(cap - {x} | {z0})) == 9, "control: one deletion of an endpoint leaves 9 lines through the outsider")
    x = next(v for v in pts if deg[v] == 3 and all(v not in p for p in E[z0]))
    check(len(lines_inside(cap - {x} | {z0})) == 10,
          "control: one deletion of a point in 3 pairs of other outsiders, in no pair of E(z), leaves 10 lines")
    x = next(v for v in pts if deg[v] == 0)
    check(len(lines_inside(cap - {x} | {O[0]})) == 10, "control: one deletion of a point in 0 pairs leaves 10 lines")
    K4 = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
    check(tau(K4) == 3 and tau(K4[:1]) == 1 and tau(K4[:2]) == 1 and tau([(0, 1), (2, 3)]) == 2
          and tau(K4[:4]) == 2 and tau(K4[:5]) == 2 and tau([(0, 1), (1, 2), (2, 0)]) == 2
          and tau(K4[:3]) == 1,
          "control: cover sizes: K4 3, one edge 1, two edges at a point 1, two separate edges 2, "
          "four edges of K4 2, five edges of K4 2, triangle 2, star of three edges 1")
    print("\nALL CHECKS PASSED")


if __name__ == "__main__":
    main()
