"""Finite-ring spectral checks for the repulsive gas and XX chain. Python 3 + NumPy."""
from itertools import combinations, product
from math import pi, atan
import numpy as np
from numpy.polynomial.legendre import leggauss


def relative_root(level, coupling, length):
    lower, upper = 2*level*pi/length,(2*level+1)*pi/length
    for _ in range(64):
        k = (lower+upper)/2
        if length*k/2-level*pi-atan(coupling/(2*k)) > 0:
            upper = k
        else:
            lower = k
    return (lower+upper)/2


def gas_spectrum(coupling=2.0, length=2*pi):
    q = 4*pi/length
    ground = relative_root(0,coupling,length)
    def norm(k):
        return length*(1+np.sinc(k*length/pi))/2
    def weight(k):
        integrals = [np.sinc((ground+s*k+t*q/2)*length/(2*pi))
                     for s,t in product((-1,1),repeat=2)]
        amplitude = -length*sum(integrals)/(4*np.sqrt(norm(ground)*norm(k)))
        return 4*amplitude**2/length
    moments = np.zeros(2)
    lowest_lines = []
    for level in range(100):
        k = relative_root(level,coupling,length)
        omega = q*q/2 + 2*(k*k-ground*ground)
        w = weight(k)
        moments += np.array([w,omega*w])
        if level<3:
            lowest_lines.append((omega, w))
            print(f"c={coupling:g} level={level} freq={omega:.10f} weight={w:.12f}")
    x, weights = leggauss(96)
    r = length*(x+1)/2
    g2 = np.cos(ground*(r-length/2))**2/norm(ground)
    equal_time = 2*(weights @ (g2*np.cos(q*r/2)**2))
    print("summed, equal-time, f-sum",moments,equal_time,2*q*q/length)
    assert abs(moments[0]-equal_time)<1e-10
    assert abs(moments[1]-2*q*q/length)<2e-8
    return np.array(lowest_lines)


def spin_spectrum(length=8, particles=3, transfer=2):
    basis = list(combinations(range(length),particles))
    positions = np.array(basis)
    states = [sum(1<<s for s in tup) for tup in basis]
    index = {state:i for i,state in enumerate(states)}
    hamiltonian = np.zeros((len(states),len(states)))
    operator = np.zeros(len(states),dtype=complex)
    for column,state in enumerate(states):
        for site in range(length):
            neighbor = (site+1)%length
            a,b = (state>>site)&1,(state>>neighbor)&1
            if a != b:
                hamiltonian[index[state^(1<<site)^(1<<neighbor)],column] -= 0.5
            if a*b:
                operator[column] += np.exp(2j*pi*transfer*site/length)/np.sqrt(length)
    # Closing a spin hop crosses the other particles in the Slater basis.
    boundary_shift = 0.5 if particles % 2 == 0 else 0
    momenta = 2*pi*(np.arange(length) + boundary_shift)/length
    def wave(indices):
        return np.linalg.det(np.exp(1j*positions[:,:,None]*momenta[list(indices)])/np.sqrt(length))
    sea = set(np.argsort(-np.cos(momenta))[:particles])
    initial = wave(sorted(sea))
    target = operator*initial
    reference = -sum(np.cos(momenta[list(sea)]))
    sectors = {}
    first_moments = np.zeros(particles + 1)
    lines = {}
    allowed_count = 0
    reached = {}
    for final in combinations(range(length),particles):
        pairs = len(sea.difference(final))
        freq = -sum(np.cos(momenta[list(final)]))-reference
        key = round(freq,9)
        weight = abs(np.vdot(wave(final),target))**2
        assert np.isfinite(weight)
        allowed = (sum(final) - sum(sea) - transfer) % length == 0
        allowed_count += allowed
        if weight>1e-16:
            assert allowed and pairs <= 2
            reached[final] = weight
            sectors[pairs] = sectors.get(pairs,0)+weight
            first_moments[pairs] += freq * weight
            lines[(key,pairs)] = lines.get((key,pairs),0)+weight
    energies,vectors = np.linalg.eigh(hamiltonian)
    assert np.max(np.abs(hamiltonian@initial-reference*initial))<1e-13
    for freq in {key for key,pairs in lines}:
        mask = np.abs(energies-reference-freq)<1e-7
        observed = np.sum(abs(vectors[:,mask].T.conj()@target)**2)
        expected = sum(w for (key,pairs),w in lines.items() if key==freq)
        assert abs(observed-expected)<1e-13
    total = np.vdot(target,target).real
    assert abs(sum(sectors.values())-total)<1e-13
    energy_moment = np.vdot(target, hamiltonian @ target - reference * target).real
    np.testing.assert_allclose(first_moments.sum(), energy_moment, atol=1e-13, rtol=0)
    if (length, particles, transfer) == (8, 3, 2):
        assert allowed_count == 7 and len(reached) == 6
        exact_upper = (3 - 2*np.sqrt(2)) / 256
        np.testing.assert_allclose(reached[(1, 4, 5)], exact_upper, atol=1e-14, rtol=0)
    print("momentum-allowed and nonzero target counts", allowed_count, len(reached))
    print("pairs, weight, fraction",[(p,w,w/total) for p,w in sorted(sectors.items())])
    print("lines",sorted(lines.items()),"equal-time",total)
    print("first moment by pair number", first_moments, "direct", energy_moment)


if __name__ == "__main__":
    free_lines = gas_spectrum(0)
    np.testing.assert_allclose(free_lines[:, 1], [0, 1/pi, 0], atol=1e-13, rtol=0)
    np.testing.assert_allclose(free_lines[1, 0], 4, atol=1e-13, rtol=0)
    gas_spectrum()
    strong_lines = gas_spectrum(1e8)
    np.testing.assert_allclose(strong_lines[:2, 0], [2, 6], atol=6e-8, rtol=0)
    np.testing.assert_allclose(strong_lines[:2, 1], 1/(2*pi), atol=4e-9, rtol=0)
    spin_spectrum()
