"""Finite graded-row and projected t–J checks. Run with Python 3 and NumPy."""

from itertools import product

import numpy as np


def graded_swap(state, i, j):
    """Exchange two slots by adjacent graded swaps; the hole 0 is even."""
    i, j = sorted((i, j))
    word = list(state)
    sign = 1
    # Move the right slot to i, then move the displaced left slot back to j.
    for k in [*range(j-1, i-1, -1), *range(i+1, j)]:
        if word[k] and word[k+1]:
            sign = -sign
        word[k], word[k+1] = word[k+1], word[k]
    return tuple(word), sign


def regular_row(length, supertrace):
    basis = list(product(range(2), repeat=length))
    result = np.zeros((len(basis), len(basis)), dtype=int)
    for column, state in enumerate(basis):
        for incoming in (0, 1):
            joint = (incoming, *state)
            coefficient = -1 if supertrace and incoming else 1
            for site in range(1, length+1):
                joint, sign = graded_swap(joint, 0, site)
                coefficient *= sign
            if joint[0] == incoming:
                result[basis.index(joint[1:]), column] += coefficient
    return result


def closing_signs():
    for length in (2, 3, 4, 5):
        row = regular_row(length, True)
        ordinary = regular_row(length, False)
        basis = list(product(range(2), repeat=length))
        for j, word in enumerate(basis):
            rotated = (word[-1], *word[:-1])
            expected = (-1)**(word[-1]*sum(word[:-1]))
            assert row[basis.index(rotated), j] == expected
        np.testing.assert_array_equal(np.linalg.matrix_power(row, length), np.eye(len(row)))
        parity = np.diag([(-1)**sum(word) for word in basis])
        np.testing.assert_array_equal(np.linalg.matrix_power(ordinary, length), parity)


def projected_annihilator(basis, site, spin):
    operator = np.zeros((len(basis), len(basis)))
    for column, state in enumerate(basis):
        if state[site] == spin:
            output = (*state[:site], 0, *state[site+1:])
            earlier = sum(entry != 0 for entry in state[:site])
            operator[basis.index(output), column] = (-1)**earlier
    return operator


def projected_ring():
    """Independent physical H/t and graded-permutation H/t on 3^3 states."""
    length = 3
    basis = list(product(range(3), repeat=length))
    dim = len(basis)
    up = [projected_annihilator(basis, j, 1) for j in range(length)]
    down = [projected_annihilator(basis, j, 2) for j in range(length)]
    number = [a.T@a + b.T@b for a, b in zip(up, down)]
    spin_z = [(a.T@a - b.T@b)/2 for a, b in zip(up, down)]
    spin_plus = [a.T@b for a, b in zip(up, down)]
    h = np.zeros((dim, dim))
    graded_h = np.zeros_like(h)
    for j in range(length):
        k = (j+1) % length
        for c in (up, down):
            h -= c[j].T@c[k] + c[k].T@c[j]
        h += 2*spin_z[j]@spin_z[k] - number[j]@number[k]/2
        h += spin_plus[j]@spin_plus[k].T + spin_plus[k]@spin_plus[j].T
        for column, state in enumerate(basis):
            output, sign = graded_swap(state, j, k)
            graded_h[basis.index(output), column] -= sign
    shifted = h + 2*sum(number) - length*np.eye(dim)
    np.testing.assert_array_equal(shifted, graded_h)
    for c in (up, down):
        creation = sum(c).T
        np.testing.assert_array_equal(h@creation - creation@h, -2*creation)

    polarized = [basis.index(word) for word in [(1,1,0), (1,0,1), (0,1,1)]]
    block = h[np.ix_(polarized, polarized)]
    np.testing.assert_array_equal(block, [[0,-1,1], [-1,0,-1], [1,-1,0]])
    np.testing.assert_allclose(np.linalg.eigvalsh(block), [-1,-1,2])
    faulty = block.copy()
    faulty[0,2] = faulty[2,0] = -1
    np.testing.assert_allclose(np.linalg.eigvalsh(faulty), [-2,1,1])
    return block


if __name__ == "__main__":
    closing_signs()
    print("Checked graded and ordinary closures on L=2,3,4,5.")
    print("Polarized three-site H/t:")
    print(projected_ring())
    print("Checked the physical and graded Hamiltonians and both odd generators on 27 states.")
