"""Hubbard and projected t-J examples. Python 3 with NumPy and SciPy."""
from itertools import combinations
from math import asinh, cosh, exp, pi, sqrt, tanh

import numpy as np
from scipy.integrate import quad
from scipy.optimize import brentq
from scipy.special import expit, j1


def basis(length, up, down, projected=False):
    """Bit 2j is spin up and bit 2j+1 spin down, in site order."""
    states = []
    for u in combinations(range(length), up):
        for d in combinations(range(length), down):
            if projected and not set(u).isdisjoint(d):
                continue
            states.append(sum(1 << (2*j) for j in u) + sum(2 << (2*j) for j in d))
    return states


def fermion(state, orbital, create):
    bit = 1 << orbital
    if bool(state & bit) == create:
        return None
    sign = (-1)**bin(state & (bit-1)).count("1")
    return state ^ bit, sign


def bonds(length, periodic):
    pairs = [(j,j+1) for j in range(length-1)]
    if periodic:
        if length < 3:
            raise ValueError("For a single two-site bond choose periodic=False.")
        pairs.append((length-1,0))
    return pairs


def hopping(states, length, periodic, t=1.0):
    indices = {state: i for i,state in enumerate(states)}
    matrix = np.zeros((len(states),len(states)))
    for col,state in enumerate(states):
        for a,b in bonds(length,periodic):
            for source,target in [(a,b),(b,a)]:
                for spin in (0,1):
                    first = fermion(state, 2*source+spin, False)
                    if first is None:
                        continue
                    second = fermion(first[0], 2*target+spin, True)
                    if second is not None and second[0] in indices:
                        matrix[indices[second[0]],col] -= t*first[1]*second[1]
    return matrix


def occupations(state, length):
    return [(state >> (2*j)) & 3 for j in range(length)]


def hubbard(states, length, interaction, periodic=True):
    doublons = [occupations(state,length).count(3) for state in states]
    return hopping(states,length,periodic) + np.diag(interaction*np.array(doublons))


def check_bound_pair(length, interaction=4.0):
    # Solve the relative-coordinate matching condition above the continuum.
    eq = lambda kappa: 4*np.sinh(kappa)*tanh(length*kappa/2)-interaction
    kappa = brentq(eq,0,asinh(interaction/4)+1,xtol=1e-15)
    energy = 4*cosh(kappa)
    distances = np.arange(length)
    profile = (-1.)**distances*np.cosh(kappa*(length/2-distances))
    profile /= np.linalg.norm(profile)
    states = basis(length,1,1)
    vector = []
    for x in range(length):
        for y in range(length):
            # c†_{x,up} c†_{y,down} is already in canonical order for x <= y.
            vector.append((1 if x <= y else -1)*profile[(x-y)%length]/sqrt(length))
    matrix = hubbard(states,length,interaction)
    residual = np.linalg.norm(matrix@vector-energy*np.array(vector))
    np.testing.assert_allclose(np.linalg.eigvalsh(matrix)[-1], energy, atol=7e-14,rtol=0)
    assert residual < 2e-13
    return energy, profile[0]**2, residual


def check_scattering_singlet():
    length, q = 4, pi/8
    interaction = 4*np.sin(q)
    matrix = hubbard(basis(length,1,1),length,interaction)
    ground = np.linalg.eigvalsh(matrix)[0]
    np.testing.assert_allclose(ground,-4*np.cos(q),atol=5e-15,rtol=0)
    return ground


def check_symmetry():
    length, interaction = 4, 4
    delta, field = .3, .8
    def centered_spectrum(up, down, u, detuning, h):
        constant = u*(length/4-(up+down)/2)
        constant -= detuning*(up+down-length)+h*(up-down)/2
        return np.linalg.eigvalsh(hubbard(basis(length,up,down),length,u))+constant
    lhs = centered_spectrum(3,1,interaction,delta,field)
    rhs = centered_spectrum(3,3,-interaction,field/2,2*delta)
    np.testing.assert_allclose(lhs,rhs,atol=3e-14,rtol=0)

    states = basis(length,1,1)
    matrix = hubbard(states,length,interaction)
    for q in (0,pi/2,pi):
        pair = np.zeros(len(states),dtype=complex)
        for j in range(length):
            pair[states.index(3 << (2*j))] = np.exp(1j*q*j)/sqrt(length)
        variance = np.linalg.norm(matrix@pair-interaction*pair)**2
        np.testing.assert_allclose(variance,4*(1+np.cos(q)),atol=1e-13)
        print("pair momentum, energy variance",q,variance)
    print("largest centered-sector spectrum difference",max(abs(lhs-rhs)))


def check_three_site_path():
    states = basis(3,1,1)
    hops = hopping(states,3,False)
    intermediates = [j for j,s in enumerate(states) if 3 in occupations(s,3)]
    projected = -(hops[:,intermediates]@hops[intermediates,:])
    initial = states.index(1 | (2 << 2))
    finals = [states.index((1 << 2) | (2 << 4)),states.index((2 << 2) | (1 << 4))]
    amplitudes = projected[finals,initial]
    np.testing.assert_allclose(amplitudes,[-1,1])
    return amplitudes


def check_dimer_probes(interaction=16.0):
    states = basis(2,1,1)
    energies,vectors = np.linalg.eigh(hubbard(states,2,interaction,periodic=False))
    charge, spin = [], []
    local_sz = (0,.5,-.5,0)
    for state in states:
        a,b = occupations(state,2)
        charge.append((bin(a).count("1")-bin(b).count("1"))/2)
        spin.append(local_sz[a]-local_sz[b])
    fraction = (1-interaction/sqrt(interaction**2+16))/2
    for name,probe,expected_energy,expected_weight in [
        ("spin",spin,0,1-fraction),("charge",charge,interaction,fraction)]:
        weights = abs(vectors.T@(np.array(probe)*vectors[:,0]))**2
        index = np.argmax(weights)
        np.testing.assert_allclose([energies[index],weights[index]],
                                   [expected_energy,expected_weight],atol=3e-14)
        assert sum(weights)-weights[index] < 1e-14
        print("dimer probe, frequency, weight",name,energies[index]-energies[0],weights[index])


def bulk_gap(interaction,tol):
    # t=1, unshifted Hamiltonian. Evaluate the full plateau width in two forms.
    def bessel(w):
        return (j1(w)/w if w else .5)*expit(-interaction*w/2)
    def positive(y):
        z = 2*pi*y/interaction
        return sqrt((y-1)*(y+1))*2*exp(-z)/(-np.expm1(-2*z))
    options = dict(epsabs=tol,epsrel=tol,limit=300)
    return (interaction-4+8*quad(bessel,0,np.inf,**options)[0],
            16/interaction*quad(positive,1,np.inf,**options)[0])


def projected_exchange(states,length):
    """Coefficient of J on the no-doublon periodic Fock basis."""
    indices = {state:j for j,state in enumerate(states)}
    exchange = np.zeros((len(states),len(states)))
    for col,state in enumerate(states):
        occ = occupations(state,length)
        for a,b in bonds(length,True):
            if {occ[a],occ[b]} == {1,2}:
                exchange[col,col] -= .5
                swapped = state ^ (3 << (2*a)) ^ (3 << (2*b))
                exchange[indices[swapped],col] += .5
    return exchange


def check_graded_descendant():
    length = 4
    states = basis(length,1,1,projected=True)
    vector = np.zeros(len(states),dtype=complex)
    for x in range(length):
        for y in range(length):
            if x != y:
                state,sign = fermion(2 << (2*x),2*y,True)
                vector[states.index(state)] += sign*np.exp(1j*pi*x/2)/sqrt(length)
    np.testing.assert_allclose(np.vdot(vector,vector),length-1)
    vector /= np.linalg.norm(vector)
    kinetic = hopping(states,length,True)
    exchange = projected_exchange(states,length)
    for coupling in (2,3):
        acted = (kinetic + coupling*exchange)@vector
        mean = np.vdot(vector,acted).real
        residual = np.linalg.norm(acted-mean*vector)
        print("t-J exchange, energy, best-scalar residual",coupling,mean,residual)
        np.testing.assert_allclose([mean,residual],[-2-(coupling-2)/3,
                                  abs(coupling-2)*sqrt(2)/3],atol=2e-14)


if __name__ == "__main__":
    print("four-site real-momentum singlet energy",check_scattering_singlet())
    for length in (4,8,16):
        print("bound pair L, E, double occupancy, residual",length,*check_bound_pair(length))
    check_symmetry()
    print("three-site virtual path coefficients in units t²/U",check_three_site_path())
    check_dimer_probes()
    for tol in (1e-9,1e-12):
        gaps = bulk_gap(16,tol)
        np.testing.assert_allclose(gaps,12.3448274518086,rtol=0,atol=1e-13)
        print("bulk full gaps at U=16, tolerance",tol,gaps)
    check_graded_descendant()
