"""Finite eight-vertex checks. Place check_periodic_row.py in the same folder.

Run with Python 3 and NumPy. Bits are ordered (horizontal, vertical), with
incoming states in columns and outgoing states in rows.
"""

from collections import Counter
from itertools import product
from math import atanh, cosh, log, sinh, sqrt

import numpy as np

from check_periodic_row import row, vertex


def weights(a, b, c, d):
    local = vertex(float(a), b, c)
    local[0, 3] = local[3, 0] = d
    return local


def conserved_parity():
    local = weights(2, 1, 3, 0.5)
    for width in (2, 3):
        transfer = row([local] * width)
        states = list(product((0, 1), repeat=width))
        even = [i for i, bits in enumerate(states) if sum(bits) % 2 == 0]
        odd = [i for i, bits in enumerate(states) if sum(bits) % 2 == 1]
        assert not transfer[np.ix_(even, odd)].any()
        assert not transfer[np.ix_(odd, even)].any()
        even_block = transfer[np.ix_(even, even)]
        if width == 2:
            odd_block = transfer[np.ix_(odd, odd)]
            assert np.allclose(np.linalg.eigvalsh(even_block), (2, 8))
            assert np.allclose(np.linalg.eigvalsh(odd_block), (-21 / 4, 53 / 4))
            print("Width 2 leading eigenvalues: even 8, odd 53/4")
        else:
            complements = [len(states) - 1 - i for i in even]
            assert np.array_equal(even_block, transfer[np.ix_(complements, complements)])
            perron_vector = np.array([1, 2, 2, 2])
            assert np.array_equal(even_block @ perron_vector, 36 * perron_vector)
            print("Width 3 complementary blocks agree; both Perron roots are 36")


def count_pair_vertices():
    local = weights(1, 1, 1, 1)
    by_cut = [Counter(), Counter()]
    for edges in product((0, 1), repeat=8):
        horizontal = np.array(edges[:4]).reshape(2, 2)
        vertical = np.array(edges[4:]).reshape(2, 2)
        created = removed = 0
        for y, x in product(range(2), repeat=2):
            incoming = 2 * horizontal[y, x - 1] + vertical[y - 1, x]
            outgoing = 2 * horizontal[y, x] + vertical[y, x]
            if not local[outgoing, incoming]:
                break
            created += int(incoming == 0 and outgoing == 3)
            removed += int(incoming == 3 and outgoing == 0)
        else:
            assert created == removed
            cut_parity = sum(vertical[0]) % 2
            by_cut[cut_parity][created + removed] += 1
    assert by_cut == [{0: 8, 2: 8}, {0: 10, 2: 4, 4: 2}]
    for fugacity in (0, 0.5, 1, 2):
        local = weights(1, 1, 1, fugacity)
        transfer = row([local, local])
        diagonal = np.diag(transfer @ transfer)
        for counts, indices in zip(by_cut, ([0, 3], [1, 2])):
            direct = sum(n * fugacity**d for d, n in counts.items())
            assert diagonal[indices].sum() == direct
    print("2x2 counts for D = 0, 2, 4")
    for sector, counts, variance in zip(("even", "odd"), by_cut, (1, 2)):
        total = sum(counts.values())
        mean = sum(n * d for d, n in counts.items()) / total
        assert mean == 1
        assert sum(n * (d - mean)**2 for d, n in counts.items()) / total == variance
        print(f"  {sector} cut: {[counts[d] for d in (0, 2, 4)]}, variance {variance}")


def gaussian_gate():
    identity = np.eye(2)
    x = np.array([[0, 1], [1, 0]])
    y = np.array([[0, -1j], [1j, 0]])
    z = np.diag([1, -1])
    xx = np.kron(x, x)
    gamma2, gamma3 = np.kron(y, identity), np.kron(z, x)
    assert np.array_equal(-1j * gamma2 @ gamma3, xx)
    swap = vertex(1, 0, 1)
    gate = swap @ weights(2, 1, 2, 1)
    alpha = atanh(0.5)
    exponential = cosh(alpha) * np.eye(4) + sinh(alpha) * xx
    assert np.allclose(gate, sqrt(3) * exponential)
    free_gate = gate
    gate = swap @ weights(sqrt(5), 1, 2, 1)
    tau = log(4 / 3) / 4
    parity = np.array([1, -1, -1, 1])
    balanced = np.diag(np.exp(-tau * parity)) @ gate
    for matrix, expected in ((gate, (4, 3)), (balanced, (sqrt(12), sqrt(12)))):
        determinants = [
            np.linalg.det(matrix[np.ix_(indices, indices)])
            for indices in ([0, 3], [1, 2])
        ]
        assert np.allclose(determinants, expected)
    majoranas = [np.kron(x, identity), gamma2, gamma3, np.kron(z, y)]
    for matrix, ratio in ((free_gate, 0), (gate, 1 / 7), (balanced, 0)):
        image = matrix @ gamma2 @ np.linalg.inv(matrix)
        linear = sum(np.trace(g @ image) * g / 4 for g in majoranas)
        cubic = image - linear
        assert np.isclose(np.linalg.norm(cubic) / np.linalg.norm(linear), ratio)
    print("Cubic-to-linear Majorana norm ratios: free 0, deformed 1/7, balanced 0")


if __name__ == "__main__":
    conserved_parity()
    count_pair_vertices()
    gaussian_gate()
