"""Reproduce the eight-ququart graph and the loss Hessian using only NumPy."""
from collections import Counter
from itertools import combinations
import json
import numpy as np

ROWS = (0x5500, 0xaa00, 0x1b40, 0x2d80, 0xaf40, 0xf580, 0x7e14, 0xe928,
        0xacbd, 0x5856, 0xe179, 0x93de, 0x0a65, 0x05fa, 0x06e1, 0x0db2)
LABELS = np.arange(1 << 16)
PARITY = np.array([int(i).bit_count() % 2 for i in LABELS], dtype=int)
CUTS = [(1, *tail) for tail in combinations(range(2, 9), 3)]
BAD = (1, 2, 4, 7)


def positions(sites):
    return [2*(8-site) + k for site in sites for k in (0, 1)]


def embed(small, positions_):
    return sum(((small >> i) & 1) << bit for i, bit in enumerate(positions_))


def graph_phase(rows):
    return 1 - 2 * (sum(((LABELS >> i) & 1) * PARITY[LABELS & row & ((1 << i)-1)]
                        for i, row in enumerate(rows)) % 2)


def cut_rank(rows, side):
    mask = sum(1 << i for i in positions(side))
    pivots = {}
    for bit in positions(side):
        vector = rows[bit] & ~mask
        while vector:
            pivot = vector.bit_length()-1
            if pivot not in pivots:
                pivots[pivot] = vector
                break
            vector ^= pivots[pivot]
    return len(pivots)


def curvature_counts():
    for i, row in enumerate(ROWS):
        assert not (row >> i & 1)
        assert all((row >> j & 1) == (ROWS[j] >> i & 1) for j in range(16))
    image = np.zeros_like(LABELS)
    for i, row in enumerate(ROWS):
        image ^= ((LABELS >> i) & 1) * row
    counts = np.zeros((2, len(LABELS)), dtype=int)
    for side in CUTS:
        local = embed(np.arange(256), positions(side))
        x, z = local[:, None], local[None, :]
        syndrome = image[x] ^ z
        component = PARITY[x & z]
        for j in (0, 1):
            counts[j] += np.bincount(syndrome[component == j], minlength=len(LABELS))
        x_stabs = local[np.any(syndrome == 0, axis=1)]
        for u in x_stabs:
            counts -= PARITY[u & LABELS]
    local_tangents = set()
    for site in range(1, 9):
        words = embed(np.arange(4), positions([site]))
        for x in words:
            for z in words:
                if x or z:
                    local_tangents.add((1-int(PARITY[x & z]), int(z ^ image[x])))
    counts[:, 0] = -1  # radial direction and global phase
    assert set(map(tuple, np.argwhere(counts == 0))) == local_tangents
    assert len(local_tangents) == 120 and np.min(counts[:, 1:]) == 0
    return counts[:, 1:]


def double_cz(rows, edges):
    changed = list(rows)
    for i, j in edges:
        changed[i] ^= 1 << j
        changed[j] ^= 1 << i
    return changed


def repair_table():
    inside = positions(BAD)
    outside = sorted(set(range(16)) - set(inside))
    outcomes = []
    for edges in combinations([(i, j) for i in inside for j in outside], 2):
        updated = double_cz(ROWS, edges)
        if cut_rank(updated, BAD) == 8:
            costs = [(1 << (8-cut_rank(updated, cut))) - 1 for cut in CUTS]
            outcomes.append((sum(costs), edges, costs))
    best, edges, costs = min(outcomes)
    assert len(outcomes) == 90 and best == 6
    return best, edges, costs


def verify_erasure():
    # Reference site 1, triple E = {2,4,7}, and four surviving sites.
    state = graph_phase(ROWS).reshape((4,)*8)
    matrix = state.transpose(0,1,3,6,2,4,5,7).reshape(4, -1)
    walsh = np.array([[(-1)**((i & j).bit_count()) for j in range(4)] for i in range(4)])
    blocks = (walsh @ matrix).reshape(4, 64, 256)
    for block in blocks:
        assert np.vdot(block, block) == 65536
    for p, q in combinations(blocks, 2):
        assert not np.any(p @ q.T) and not np.any(p.T @ q)


def validate_amplitudes(rows):
    tensor = graph_phase(rows).astype(np.int32).reshape((4,)*8)
    for side in CUTS:
        other = sorted(set(range(1, 9)) - set(side))
        perm = tuple(i-1 for i in (*side, *other))
        m = np.ascontiguousarray(tensor.transpose(perm).reshape(256, 256))
        gram = (m @ m.T).astype(np.int64)
        rank = 1 << cut_rank(rows, side)
        assert np.trace(gram) == 65536
        assert np.array_equal(gram @ gram, (65536 // rank) * gram)


def main():
    hist = Counter(map(int, curvature_counts().ravel()))
    assert min(i for i in hist if i) == 2
    ranks = [cut_rank(ROWS, cut) for cut in CUTS]
    assert Counter(ranks) == {8: 34, 6: 1} and ranks[CUTS.index(BAD)] == 6
    validate_amplitudes(ROWS)
    verify_erasure()
    best, edges, costs = repair_table()
    validate_amplitudes(double_cz(ROWS, edges))
    print(json.dumps({"adjacency_rows": ROWS, "cut_ranks_over_F2": ranks, "repair_count": 90,
                      "repair_edges": edges, "repair_costs": costs,
                      "hessian_multiplicities_in_units_of_8_over_35": dict(sorted(hist.items()))},
                     indent=2))


if __name__ == "__main__":
    main()
