"""Independent finite-ring checks for the quench preparation chapter (NumPy)."""

import numpy as np


def sites(matrix, positions):
    size = len(positions)
    result = np.eye(1)
    for i in range(size):
        result = np.kron(result, matrix[positions[i]])
    return result


def ising():
    length = 6
    identity = np.eye(2)
    spin_x = np.array([[0, 1], [1, 0]])
    spin_z = np.diag([1, -1])
    ops = [identity, spin_x, spin_z]
    field = np.zeros((2**length,) * 2)
    bonds = np.zeros_like(field)
    for j in range(length):
        labels = [0] * length
        labels[j] = 2
        field += sites(ops, labels)
        labels[j] = labels[(j + 1) % length] = 1
        bonds += sites(ops, labels)
    even = [n for n in range(2**length) if bin(n).count("1") % 2 == 0]
    indices = np.ix_(even, even)
    field, bonds = field[indices], bonds[indices]
    initial = np.linalg.eigh(-bonds - 0.5 * field)[1][:, 0]
    energies, eigenstates = np.linalg.eigh(-bonds - 2.0 * field)
    weights = eigenstates.T @ initial
    k = (2 * np.arange(length // 2) + 1) * np.pi / length
    r0 = np.sqrt(1.25 - np.cos(k))
    r = np.sqrt(5.0 - 4.0 * np.cos(k))
    c0, c = (0.5 - np.cos(k)) / r0, (2.0 - np.cos(k)) / r
    projection = (2.0 - 2.5 * np.cos(k)) / (r0 * r)
    for time in [0.0, 0.25, 0.5]:
        state = eigenstates @ (weights * np.exp(-1j * energies * time))
        magnetization = np.vdot(state, field @ state).real / length
        predicted = np.mean(c * projection + (c0 - c * projection) * np.cos(4 * r * time))
        np.testing.assert_allclose(magnetization, predicted, rtol=0, atol=1e-13)
        print(f"Ising Jt={time:.2f} magnetization={magnetization:.9f}")


def dimer_currents():
    length = 6
    h = np.zeros((length, length))
    density = np.zeros_like(h)
    local = np.array([[3, np.sqrt(3)], [np.sqrt(3), 1]]) / 4
    for j in range(length):
        h[j, (j + 1) % length] = h[(j + 1) % length, j] = -1.0
        if j % 2 == 0:
            density[j:j+2, j:j+2] = local
    for j in range(length):
        k = (j + 1) % length
        current = np.zeros_like(h, dtype=complex)
        current[j, k], current[k, j] = -1j, 1j
        value = np.trace(density @ current)
        slope = np.trace(density @ (1j * (h @ current - current @ h)))
        np.testing.assert_allclose([value, slope], [0, (-1)**j], atol=1e-14)
    print("Dimer currents: all zero, slopes alternating +1 and -1")


def swaps_and_overlaps():
    for length in [4, 6, 8]:
        basis = [n for n in range(2**length) if bin(n).count("1") == length // 2]
        index = {bits: row for row, bits in enumerate(basis)}
        permutations = []
        ham = np.zeros((len(basis),) * 2)
        for j in range(length):
            k = (j + 1) % length
            swap = np.zeros_like(ham)
            for col, bits in enumerate(basis):
                opposite = ((bits >> j) ^ (bits >> k)) & 1
                new = bits ^ ((1 << j) | (1 << k)) if opposite else bits
                swap[index[new], col] = 1
                if opposite:
                    ham[index[new], col] += 0.5
                    ham[col, col] -= 1.0  # Delta=2, J=1
            permutations.append(swap)
        pattern = sum(1 << j for j in range(0, length, 2))
        state = np.eye(len(basis))[:, index[pattern]]
        odd = np.zeros(len(basis))
        for j, left in enumerate(permutations):
            right = permutations[(j + 1) % length]
            odd += left @ (right @ state) - right @ (left @ state)
        assert np.all(odd == 0)
        if length == 4:
            partner = np.eye(len(basis))[:, index[2 * pattern]]
            energy, vector = np.linalg.eigh(ham)
            for initial in [state, (state + partner) / np.sqrt(2)]:
                weights = (vector.T @ initial)**2
                assert abs(sum(weights) - 1) < 1e-14
                print("Neel", [(round(e, 8), round(w, 8))
                               for e, w in zip(energy, weights) if w > 1e-12])
    print("Odd-charge annihilation exact on lengths 4, 6 and 8")


if __name__ == "__main__":
    dimer_currents()
    ising()
    swaps_and_overlaps()
