#!/usr/bin/env python3
"""
Computer verification for Section 7 of the paper
    "Identifying codes of Archimedean grids"  (R. M. Sampaio).

Run with:  python3 verify.py      (Python >= 3.8, no external packages)

The script checks, for the snub hexagonal grid 3^4.6:
  * the facts (F1), (F2) and (F3);
  * that Table 3 is a correct certificate for the lower bound of Theorem 8,
    with the rules (R1) and (R2) of Table 2: every vertex outside C receives
    exactly 1, the rows partition all configurations of the ball N_2[u]
    around a codeword u, the rows marked impossible contain no admissible
    configuration, every entry q_w is the exact maximum of the amount that
    u sends to w, every entry r is the exact minimum of the amount that
    u receives, and every row satisfies  sum <= 2 + r;
  * the remark at the end of Section 7: no rule in which every vertex splits
    its charge according to fixed priorities among the positions
    v1, v2, v3, v4, v5 achieves the bound 1/3.

Every statement printed as "OK" is asserted; the script stops at the first
failure.
"""
from fractions import Fraction as F
from itertools import combinations


def ball(nbrs, c, r):
    seen, frontier = {c}, [c]
    for _ in range(r):
        new = []
        for f in frontier:
            for w in nbrs(f):
                if w not in seen:
                    seen.add(w)
                    new.append(w)
        frontier = new
    return seen


def closed(nbrs, v):
    return [v] + nbrs(v)


# Coordinates of Section 7: Z^2 with the six lattice neighbors below (the
# triangular grid); the snub hexagonal grid is Z^2 minus Z, Z = {3i+j = 0 mod 7}.
TRI = [(1, 0), (0, 1), (-1, 1), (-1, 0), (0, -1), (1, -1)]

inZ = lambda p: (3 * p[0] + p[1]) % 7 == 0
sn_isv = lambda i, j: not inZ((i, j))
add = lambda a, b: (a[0] + b[0], a[1] + b[1])
lat = lambda v: [add(v, d) for d in TRI]
sn_nbrs = lambda v: [w for w in lat(v) if not inZ(w)]
POS = ["v1", "v2", "v3", "v4", "v5"]


def zof(v):
    r = [w for w in lat(v) if inZ(w)]
    assert len(r) == 1
    return r[0]


def names(v):
    L = lat(v)
    k = L.index(zof(v))
    return {p: L[(k + t) % 6] for p, t in zip(POS, range(1, 6))}


sn_adj = lambda a, b: b in sn_nbrs(a)
Zadj = {(2, 1), (-1, 3), (3, -2), (-2, -1), (1, -3), (-3, 2)}
assert all(inZ(d) for d in Zadj)
for i in range(-10, 10):
    for j in range(-10, 10):
        if inZ((i, j)):
            assert inZ((-j, i + j))  # the map (i,j) -> (-j, i+j) preserves Z
            continue
        v = (i, j)
        n = names(v)
        E = {frozenset((p, q)) for p, q in combinations(POS, 2) if sn_adj(n[p], n[q])}
        assert E == {frozenset(e) for e in [("v1", "v2"), ("v2", "v3"), ("v3", "v4"), ("v4", "v5")]}  # F1
        z, z2, z3 = zof(v), zof(n["v3"]), zof(n["v2"])
        assert zof(n["v1"]) == z and zof(n["v5"]) == z and zof(n["v4"]) == z2  # F2
        assert all((a_[0] - b_[0], a_[1] - b_[1]) in Zadj for a_, b_ in [(z, z2), (z, z3), (z2, z3)])  # F2
        assert names(n["v1"])["v5"] == v and names(n["v5"])["v1"] == v  # F3
        assert names(n["v2"])["v3"] == v and names(n["v3"])["v2"] == v and names(n["v4"])["v4"] == v
print("OK  3^4.6: facts (F1), (F2), (F3) and invariance of Z")

# rules (R1) and (R2): Table 2 (a) and (b); names relative to the receiving vertex v
S1 = {
    ("v2", "v5"): ["v5"], ("v2", "v3"): ["v2"], ("v1", "v3"): ["v1"],
    ("v1", "v2", "v5"): ["v1", "v5"], ("v1", "v2", "v3"): ["v1", "v2"], ("v1", "v2", "v4"): ["v1", "v2"],
    ("v1", "v3", "v4"): ["v1", "v3"], ("v1", "v3", "v5"): ["v1", "v5"], ("v2", "v3", "v4"): ["v2", "v3"],
    ("v2", "v3", "v5"): ["v2", "v5"], ("v2", "v4", "v5"): ["v4", "v5"], ("v3", "v4", "v5"): ["v3", "v4"],
    ("v1", "v2", "v3", "v4"): ["v2", "v3"], ("v1", "v2", "v3", "v5"): ["v2", "v5"],
    ("v1", "v3", "v4", "v5"): ["v3", "v4"], ("v2", "v3", "v4", "v5"): ["v3", "v4"],
    ("v1", "v2", "v3", "v4", "v5"): ["v2", "v3", "v4"],
}
S2 = {("v1",): "v1", ("v3",): "v3", ("v4",): "v4", ("v1", "v2"): "v2",
      ("v2", "v4"): "v4", ("v4", "v5"): "v5", ("v1", "v2", "v5"): "v2"}
assert len(S1) == 17 and len(S2) == 7


def receives(v, C):
    """The amounts that v receives, as a dict {codeword: amount}."""
    n = names(v)
    cn = tuple(p for p in POS if n[p] in C)
    if v not in C:
        g = S1.get(cn, cn)
        return {n[p]: F(1, len(g)) for p in g}
    if cn in S2:
        return {n[S2[cn]]: F(1, 2)}
    return {}


# the ball N_2[u] of Figure 7; u has z(u) = u + (-1,0)
u = (1, 0)
assert zof(u) == (0, 0)
nu = names(u)
lab = {"u": u, **nu}
for k, off in {"z1": (-1, -1), "z2": (0, -2), "z3": (1, -2), "z4": (2, -1), "z5": (2, 0),
               "z6": (0, 2), "z7": (-1, 2), "z8": (-2, 2), "z9": (-2, 1)}.items():
    lab[k] = add(u, off)
B2 = ball(sn_nbrs, u, 2)
assert set(lab.values()) == B2 and len(B2) == 15
assert {lab[k] for k in ("v1", "v5", "z1", "z9")} <= set(lat(zof(u)))
assert {lab["z5"], lab["z6"]} <= set(lat(zof(lab["v3"]))) and {lab["z3"], lab["z4"]} <= set(lat(zof(lab["v2"])))

# admissible configurations: the two conditions stated in the proof of Theorem 8
Nc = lambda x: set(closed(sn_nbrs, x))
B4 = ball(sn_nbrs, u, 4)
nonempty = [x for x in B2 if Nc(x) <= B2]
pairs = [(x, y) for x in B2 for y in B4 if y != x and (Nc(x) ^ Nc(y)) <= B2]
B2l = sorted(B2)
configs = []
for mask in range(1 << 15):
    C = {B2l[i] for i in range(15) if mask >> i & 1}
    if u in C:
        adm = all(Nc(x) & C for x in nonempty) and all((Nc(x) ^ Nc(y)) & C for x, y in pairs)
        configs.append((C, adm))

# Table 3, transcribed from the paper.
# Columns: P (codeword neighbors of u) | further assumptions |
# upper bounds for q_u1, ..., q_u5, their sum, lower bound for r.
CERT = """
-                 | !z3 !z4                     | impossible
-                 | !z3 z4 !z5                  | impossible
-                 | !z3 z4 z5 !z8 !z9           | 1 0 0 0 1 2 0
-                 | !z3 z4 z5 z8 !z9            | 1 0 0 1/2 1/2 2 0
-                 | !z3 z4 z5 z9                | 1 0 0 1/2 1/2 2 0
-                 | z3 !z4 !z5                  | impossible
-                 | z3 !z4 z5 !z8 !z9           | 1/2 1/2 0 0 1 2 0
-                 | z3 !z4 z5 z8 !z9            | 1/2 1/2 0 1/2 1/2 2 0
-                 | z3 !z4 z5 z9                | 1/2 1/2 0 1/2 1/2 2 0
-                 | z3 z4 !z8 !z9               | 1/2 0 1/2 0 1 2 0
-                 | z3 z4 z8 !z9                | 1/2 0 1/2 1/2 1/2 2 0
-                 | z3 z4 z9                    | 1/2 0 1/2 1/2 1/2 2 0
u5                | !z3                         | 1 1 0 0 0 2 0
u5                | z3                          | 1/2 1/2 1 0 0 2 0
u4                | !z4 !z6                     | 1 1 0 1/2 0 5/2 1/2
u4                | !z4 z6                      | 1 1 0 0 1/2 5/2 1/2
u4                | z4                          | 1 0 1/2 1/2 1/2 5/2 1/2
u4 u5             | -                           | 1 1 1/2 0 0 5/2 1/2
u3                | -                           | 1 0 0 1/2 1 5/2 1/2
u3 u5             | -                           | 1 0 0 1/2 1/2 2 0
u3 u4             | -                           | 1 0 1/2 0 1/2 2 0
u3 u4 u5          | -                           | 1 0 1/2 0 0 3/2 0
u2                | !z3 !z6                     | 1/2 0 0 1 1/2 2 0
u2                | z3 !z6                      | 0 0 1/2 1 1/2 2 0
u2                | !z3 z6                      | 1/2 0 0 1/2 1 2 0
u2                | z3 z6                       | 0 0 1/2 1/2 1 2 0
u2 u5             | !z3 !z6                     | 1/2 1/2 1/2 1/2 0 2 0
u2 u5             | !z3 z6                      | 1/2 1/2 1/2 0 1/2 2 0
u2 u5             | z3                          | 0 0 1 1/2 1/2 2 0
u2 u4             | -                           | 1/2 1/2 1/2 1/2 1/2 5/2 1/2
u2 u4 u5          | -                           | 1/2 1/2 1/2 0 0 3/2 0
u2 u3             | -                           | 1/2 0 0 1/2 1 2 0
u2 u3 u5          | -                           | 1/2 0 0 1/2 1/2 3/2 0
u2 u3 u4          | -                           | 1/2 0 0 0 1/2 1 0
u2 u3 u4 u5       | -                           | 1/2 0 0 0 0 1/2 0
u1                | !z5 !z6 !z7                 | 0 1/2 1/2 1 1/2 5/2 1/2
u1                | !z5 !z6 z7                  | 0 1/2 1 1/2 1/2 5/2 1/2
u1                | !z5 z6 !z7 !z8 !z9          | 0 1/2 1/2 1/2 1 5/2 1/2
u1                | !z5 z6 z7 !z8 !z9           | 0 1/2 1 0 1 5/2 1/2
u1                | !z5 z6 z8 !z9               | 0 1/2 1 1/2 1/2 5/2 1/2
u1                | !z5 z6 z9                   | 0 1/2 1 1/2 1/2 5/2 1/2
u1                | z5                          | 0 1/2 0 1 1 5/2 1/2
u1 u5             | !z6                         | 0 1/2 1 1/2 0 2 0
u1 u5             | z6                          | 0 1/2 1 0 1/2 2 0
u1 u4             | -                           | 0 1/2 1/2 1/2 1/2 2 0
u1 u4 u5          | -                           | 0 1/2 1/2 0 0 1 0
u1 u3             | -                           | 0 1/2 0 1/2 1 2 0
u1 u3 u5          | -                           | 0 1/2 0 1/2 1/2 3/2 0
u1 u3 u4          | -                           | 0 1/2 1/2 0 1/2 3/2 0
u1 u3 u4 u5       | -                           | 0 1/2 1/2 0 0 1 0
u1 u2             | !z6                         | 0 0 1 1 1/2 5/2 1/2
u1 u2             | z6                          | 0 0 1 1/2 1 5/2 1/2
u1 u2 u5          | -                           | 1/2 0 1 1/2 1/2 5/2 1/2
u1 u2 u4          | -                           | 1/2 0 1/2 1/2 1/2 2 0
u1 u2 u4 u5       | -                           | 1/2 0 1/2 0 0 1 0
u1 u2 u3          | -                           | 1/2 0 0 1/2 1 2 0
u1 u2 u3 u5       | -                           | 1/2 0 0 1/2 1/2 3/2 0
u1 u2 u3 u4       | -                           | 1/2 0 0 0 1/2 1 0
u1 u2 u3 u4 u5    | -                           | 1/2 0 0 0 0 1/2 0
""".strip()

rows = []
for line in CERT.splitlines():
    P, A, V = (c.strip() for c in line.split("|"))
    P = frozenset() if P == "-" else frozenset("v" + x[1:] for x in P.split())  # u_i is the i-th neighbor v_i of u
    A = {} if A == "-" else {t.lstrip("!"): not t.startswith("!") for t in A.split()}
    V = None if V == "impossible" else [F(t) for t in V.split()]
    rows.append((P, A, V))
assert len(rows) == 59
assert {r[0] for r in rows} == {frozenset(c) for k in range(6) for c in combinations(POS, k)}

row_q = {i: {p: F(0) for p in POS} for i in range(len(rows))}
row_r = {i: None for i in range(len(rows))}
for C, adm in configs:
    P = frozenset(p for p in POS if nu[p] in C)
    match = [i for i, r in enumerate(rows) if r[0] == P and all((lab[k] in C) == b for k, b in r[1].items())]
    assert len(match) == 1, "rows do not partition the cases"
    i = match[0]
    if adm:
        for w in closed(sn_nbrs, u):
            got = sum(receives(w, C).values())
            assert got == 1 if w not in C else got in (0, F(1, 2))
        for p in POS:
            row_q[i][p] = max(row_q[i][p], receives(nu[p], C).get(u, F(0)))
        r = sum(receives(u, C).values())
        row_r[i] = r if row_r[i] is None else min(row_r[i], r)
for i, (P, A, V) in enumerate(rows):
    if V is None:
        assert row_r[i] is None, ("impossible row has admissible configurations", sorted(P), A)
    else:
        assert row_r[i] is not None
        assert [row_q[i][p] for p in POS] == V[:5], ("q entry is not the exact maximum", sorted(P), A)
        assert sum(V[:5]) == V[5] and V[6] == row_r[i], ("sum or r entry wrong", sorted(P), A)
        assert V[5] <= 2 + V[6]
print("OK  3^4.6: Table 3 is a correct certificate for Theorem 8 (59 rows, all entries exact, sum <= 2 + r)")

# remark at the end of Section 7: no fixed-priority rule achieves 1/3.
# Each vertex w of N[u] gets 1 in total, split equally among the codewords of
# I(w) of highest priority (v = w itself); u must give at most 3 in total,
# which is the condition q <= 2 + r in the formulation of the paper.
def weak_orders(items):
    if not items:
        yield []
        return
    first, rest = items[0], items[1:]
    for wo in weak_orders(rest):
        for i in range(len(wo)):
            yield wo[:i] + [wo[i] | {first}] + wo[i + 1:]
        for i in range(len(wo) + 1):
            yield wo[:i] + [{first}] + wo[i:]

sigs = set()
for C, adm in configs:
    if adm:
        sig = []
        for w in closed(sn_nbrs, u):
            inv = {x: p for p, x in names(w).items()}
            inv[w] = "v"
            sig.append((frozenset(inv[x] for x in closed(sn_nbrs, w) if x in C), inv[u]))
        sigs.add(tuple(sig))
good = 0
for wo in weak_orders(["v"] + POS):
    rank = {p: i for i, blk in enumerate(wo) for p in blk}
    ok = True
    for sig in sigs:
        lam = F(0)
        for Iw, up in sig:
            best = min(rank[p] for p in Iw)
            top = [p for p in Iw if rank[p] == best]
            if up in top:
                lam += F(1, len(top))
        if lam > 3:
            ok = False
            break
    good += ok
assert good == 0
print("OK  3^4.6: no fixed-priority rule (4683 weak orders on v,v1,v2,v3,v4,v5) achieves 1/3")
print("All checks passed.")
