"""Half-filled Hubbard rings with a boundary twist. Energies in hopping units.

Run with Python 3, NumPy and SciPy. Site occupations are ordered separately
for each spin. Crossing the seam passes all other particles of that spin.
"""
from itertools import combinations
from math import pi, sin

import numpy as np
from scipy import sparse
from scipy.sparse.linalg import eigsh


def spin_block(length, number, phase):
    states = [sum(1 << j for j in sites)
              for sites in combinations(range(length), number)]
    index = {mask: i for i, mask in enumerate(states)}
    matrix = sparse.lil_matrix((len(states), len(states)), dtype=complex)
    for col, mask in enumerate(states):
        for j in range(length):
            target = (j + 1) % length
            if not mask & (1 << j) or mask & (1 << target):
                continue
            row = index[mask ^ (1 << j) ^ (1 << target)]
            hop = -1 if target else -(-1)**(number - 1) * np.exp(-1j * phase)
            matrix[row, col] += hop
            matrix[col, row] += np.conj(hop)
    return matrix.tocsr(), states


def lowest(length, electrons, interaction, phase, dense=False):
    up, a = spin_block(length, (electrons + 1)//2, phase)
    down, b = spin_block(length, electrons//2, phase)
    double = [bin(x & y).count("1") for x in a for y in b]
    h = (sparse.kron(up, sparse.eye(len(b))) +
         sparse.kron(sparse.eye(len(a)), down) +
         sparse.diags(interaction * np.array(double))).tocsr()
    if dense:
        return np.linalg.eigvalsh(h.toarray())[0]
    rng = np.random.default_rng(471)
    start = rng.normal(size=h.shape[0]) + 1j*rng.normal(size=h.shape[0])
    energies, vectors = eigsh(h, k=1, which="SA", v0=start, tol=1e-12)
    assert np.linalg.norm(h @ vectors[:, 0] - energies[0]*vectors[:, 0]) < 1e-10
    return energies[0]


def charge_gap(length, interaction, phase, dense=False):
    low, center, high = [lowest(length, length + offset, interaction, phase, dense)
                         for offset in (-1, 0, 1)]
    np.testing.assert_allclose(high - low, interaction, atol=1e-10, rtol=0)
    return low + high - 2*center


if __name__ == "__main__":
    for phase in np.linspace(0, pi, 9):
        free = charge_gap(6, 0., phase)
        np.testing.assert_allclose(free, 4*sin((pi-phase)/6), atol=1e-10, rtol=0)
        interacting = charge_gap(6, 4., phase)
        if np.isclose(phase % (pi/2), 0):
            direct = charge_gap(6, 4., phase, dense=True)
            np.testing.assert_allclose(interacting, direct, atol=1e-10, rtol=0)
        print(f"twist/pi {phase/pi:.3f}  gap/t (U/t=0, 4) {free:.8f} {interacting:.8f}")
