"""Finite rank-one overlaps, inverse problem, twisted pair, and thermal lines.

Run with Python 3, NumPy and mpmath. The site labels start at zero in this file.
"""
import mpmath as mp
import numpy as np


def lifted_gate(local, length, site):
    dim=2**length
    mask=1<<(length-site-1)
    result=np.zeros((2*dim,2*dim),complex)
    for col in range(2*dim):
        aux,state=divmod(col,dim)
        spin=int(bool(state&mask))
        for other in range(4):
            a,b=divmod(other,2)
            row=a*dim+((state&~mask)|(b*mask))
            result[row,col]=local[other,2*aux+spin]
    return result


def monodromy(u, shifts, eta=1j, trigonometric=False, normalized=True):
    length=len(shifts)
    phi=np.sinh if trigonometric else lambda x:x
    product=np.eye(2**(length+1),dtype=complex)
    for site,xi in enumerate(shifts):
        a,b,c=phi(u-xi+eta),phi(u-xi),phi(eta)
        local=np.array([[a,0,0,0],[0,b,c,0],[0,c,b,0],[0,0,0,a]],complex)
        if normalized:
            local/=a
        product=lifted_gate(local,length,site)@product
    return product


def vector(roots,length,normalized=True):
    dim=2**length
    psi=np.eye(dim,dtype=complex)[:,0]
    for root in roots:
        matrix=monodromy(root,[0.5j]*length,normalized=normalized)
        psi=matrix[:dim,dim:]@psi
    return psi


def check_regular():
    roots=np.array([-0.5,0.5])
    probes=np.array([0.21,0.93])
    length=5
    def d(z):
        return ((z-0.5j)/(z+0.5j))**length
    def derivative(z,a):
        diff=z-roots
        other=1-a
        return 1j*(d(z)*(1+1j/diff[other])-(1-1j/diff[other]))/diff[a]**2
    numerator=np.array([[derivative(z,a) for z in probes] for a in range(2)])
    denominator=1/(probes[None,:]-roots[:,None])
    sl=np.linalg.det(numerator)/np.linalg.det(denominator)
    norm=np.vdot(vector(roots,length),vector(roots,length)).real
    direct=np.vdot(vector(roots,length),vector(probes,length))
    print("two-root overlap",sl,"norm",norm)
    assert abs(direct-sl)<2e-12 and abs(norm-160)<1e-12
    # Exactly one shared root. Scale its column before taking the limit.
    gaudin = np.array([[9, 1], [1, 9]])
    shared_residue = -(1 + 1j) * gaudin[0]
    partial = np.column_stack((shared_residue, numerator[:, 1]))
    cauchy = np.column_stack(([1, 0], denominator[:, 1]))
    overlap = np.linalg.det(partial) / np.linalg.det(cauchy)
    direct = np.vdot(vector(roots, length), vector([roots[0], probes[1]], length))
    print("one shared root", overlap, "spin-space error", abs(overlap - direct))
    assert abs(overlap - direct) < 2e-12
    for split in (1e-2,1e-4,1e-6):
        mu=roots+np.array([split,-2*split])
        num=np.array([[derivative(z,a) for z in mu] for a in range(2)])
        sval=np.linalg.det(num)/np.linalg.det(1/(mu[None,:]-roots[:,None]))
        print("diagonal limit",split,sval.real,abs(sval-160))

    # Solve the twisted Bethe equations on the real branch through these roots.
    def twisted_roots(angle):
        def phase(x, y):
            return mp.arg(d(x) * (x - y + mp.j) / (x - y - mp.j))

        def equations(x, y):
            return phase(x, y) - angle, phase(y, x) - angle

        return mp.findroot(equations, (-0.5, 0.5))

    with mp.workdps(45):
        response = np.linalg.solve(gaudin, [1, 1])
        for step in (mp.mpf("0.01"), mp.mpf("0.001")):
            slope = (twisted_roots(step) - twisted_roots(-step)) / (2 * step)
            print("twist step", float(step), "root slopes", [float(x) for x in slope])
            assert max(abs(float(x) - v) for x, v in zip(slope, response)) < 0.002 * step**2


def check_local():
    eta=0.7
    length=4
    dim=2**length
    for scale in (1,0.1,0.0):
        xi=scale*np.array([-0.2,0.07,0.14,0.22])
        past=np.eye(dim,dtype=complex)
        worst=0.0
        for site,z in enumerate(xi):
            t=monodromy(z,xi,eta,trigonometric=True)
            transfer=t[:dim,:dim]+t[dim:,dim:]
            future=past@transfer
            reconstructed=past@t[:dim,dim:]@np.linalg.inv(future)
            expected=np.zeros((dim,dim))
            mask=1<<(length-1-site)
            for j in range(dim):
                if not(j&mask):
                    expected[j|mask,j]=1
            worst=max(worst,np.max(abs(expected-reconstructed)))
            past=future
        print("inhomogeneity scale",scale,"max elementwise difference",worst)
        assert worst<3e-13

    # A coherent pair of sites distinguishes the two signs of the momentum.
    vacuum = np.eye(dim, dtype=complex)[:, 0]
    homogeneous = monodromy(0, np.zeros(length), eta, trigonometric=True)
    first = homogeneous[:dim, dim:] @ vacuum
    shift = homogeneous[:dim, :dim] + homogeneous[dim:, dim:]
    probe = (first + 1j * (shift @ first)) / np.sqrt(2)
    one_magnon = [1 << (length - 1 - site) for site in range(length)]
    k = 2 * np.pi * np.arange(length) / length
    fourier = np.exp(1j * np.outer(np.arange(length), k)) / np.sqrt(length)
    weights = abs(fourier.conj().T @ probe[one_magnon])**2
    print("two-site spin-flip weights", weights)
    np.testing.assert_allclose(weights, [0.25, 0.5, 0.25, 0], atol=1e-15)


def twist_h(length,mag,angle):
    dim=2**length
    sector=[s for s in range(dim) if bin(s).count("1")==mag]
    h=np.zeros((len(sector),len(sector)),complex)
    for i,state in enumerate(sector):
        for j in range(length):
            ma=1<<(length-1-j)
            mb=1<<(length-1-(j+1)%length)
            if bool(state&ma)!=bool(state&mb):
                phase=np.exp(-1j*angle*(1 if state&ma else -1)) if j==length-1 else 1
                h[i,i]+=0.5
                h[sector.index(state^ma^mb),i]-=phase/2
    return sector,h


def check_twist():
    mp.mp.dps=70
    for angle in (0.4,0.2,0.1,0.05):
        b=mp.mpf(angle)
        def equations(x,y):
            lam=x+mp.j*y
            diff=2*mp.j*y
            eq=(lam+mp.j/2)**4*(diff-mp.j)-mp.exp(-mp.j*b)*(lam-mp.j/2)**4*(diff+mp.j)
            return mp.re(eq),mp.im(eq)
        x,y=mp.findroot(equations,(b/4-b**3/96,mp.mpf("0.5")+b**4/256),tol=mp.mpf("1e-62"))
        assert y>mp.mpf("0.5") and abs(x-b/4)<b*b
        roots=[complex(x,y),complex(x,-y)]
        raw=vector(roots,4,normalized=False)
        raw_norm=np.linalg.norm(raw)
        psi=raw/raw_norm
        sec,h=twist_h(4,2,angle)
        eig,vec=np.linalg.eigh(h)
        overlaps=abs(vec.conj().T@psi[sec])**2
        chosen=np.argmax(overlaps)
        assert abs(1-overlaps[chosen])<1e-12
        # A local raising at site zero maps the two-flip state onto the one-flip sector.
        one,h1=twist_h(4,1,angle)
        def raised(s):
            return np.array([s[state|8] if not state&8 else 0 for state in one])
        final=raised(psi)
        initial_ed=np.zeros(16,complex)
        initial_ed[sec]=vec[:,chosen]
        energies,finals=np.linalg.eigh(h1)
        selected=np.abs(energies-1)<0.4
        doublet = energies[selected]
        predicted = [1 - np.sin(angle / 4), 1 + np.sin(angle / 4)]
        np.testing.assert_allclose(doublet, predicted, atol=2e-15, rtol=0)
        w=np.sum(abs(finals[:,selected].conj().T@final)**2)
        wed=np.sum(abs(finals[:,selected].conj().T@raised(initial_ed))**2)
        residual=np.linalg.norm(h@psi[sec]-eig[chosen]*psi[sec])
        print("twist",angle,"raw norm",raw_norm,"projected weight",w,
              "total",np.vdot(final,final).real,"eigen residual",residual)
        print("  frequencies of the two descendants", doublet - eig[chosen])
        assert abs(w-wed)<1e-9 and abs(np.vdot(final,final)-0.5)<1e-9


def check_thermal_lines():
    """Eight-site density mode, beta J = 1 and chemical potential zero."""
    length = 8
    energy = -2 * np.cos(2 * np.pi * np.arange(length) / length)
    target = (np.arange(length) + 2) % length
    gaps = np.array([-2*np.sqrt(2), -2, 0, 2, 2*np.sqrt(2)])
    weights = np.zeros(len(gaps))
    partition = 0.0
    for state in range(2**length):
        occupied = np.array([bool(state & (1 << k)) for k in range(length)])
        boltzmann = np.exp(-sum(energy[occupied]))
        partition += boltzmann
        for k in np.flatnonzero(occupied & ~occupied[target]):
            gap = energy[target[k]] - energy[k]
            line = np.argmin(abs(gaps - gap))
            assert abs(gaps[line] - gap) < 1e-14
            weights[line] += boltzmann / length
    weights /= partition

    # Independent contraction in the product measure of the momentum occupations.
    fermi = 1 / (1 + np.exp(energy))
    hops = fermi * (1 - fermi[target]) / length
    gaps_per_hop = energy[target] - energy
    contracted = [sum(hops[np.isclose(gaps_per_hop, gap)]) for gap in gaps]
    np.testing.assert_allclose(weights, contracted, atol=1e-15, rtol=0)
    np.testing.assert_allclose(weights[:2], np.exp(gaps[:2]) * weights[::-1][:2],
                               atol=1e-15, rtol=0)
    assert abs(sum(weights) - 0.25) < 1e-15
    print("thermal density weights", weights, "first moment", np.dot(gaps, weights))


if __name__=="__main__":
    check_regular()
    check_local()
    check_twist()
    check_thermal_lines()
