"""Finite XXZ Lindblad sectors and stationary observables. Python 3 and NumPy."""
import numpy as np


def spin_chain(n, w, delta, left, right, detuning=0):
    """First basis state is all up; left and right are population rates."""
    dimension = 2**n
    identity = np.eye(dimension)
    raising, polarization = [], []
    for site in range(n):
        bit = 1 << (n-1-site)
        down = np.array([s for s in range(dimension) if s & bit])
        plus = np.zeros_like(identity)
        plus[down ^ bit,down] = 1
        raising.append(plus)
        polarization.append(2*plus@plus.T-identity)
    bonds = [a@b.T for a,b in zip(raising,raising[1:])]
    h = sum(w*(b+b.T) for b in bonds)
    h += sum(delta*a@b for a,b in zip(polarization,polarization[1:]))
    h += detuning*(polarization[0]-polarization[-1])/4
    gen = -1j*(np.kron(identity,h)-np.kron(h.T,identity))
    for jump in (np.sqrt(left)*raising[0],np.sqrt(right)*raising[-1].T):
        loss = jump.T@jump
        gen += np.kron(jump,jump) - (np.kron(identity,loss)+np.kron(loss.T,identity))/2
    return gen, raising, bonds


def fixed_point(gen):
    dimension = int(np.sqrt(len(gen)))
    equations = gen.copy()
    equations[0] = np.eye(dimension).ravel()
    rhs = np.zeros(len(gen))
    rhs[0] = 1.
    rho = np.linalg.solve(equations,rhs).reshape((dimension,dimension),order="F")
    assert np.linalg.eigvalsh(rho)[0] > 0
    assert np.linalg.norm(gen@rho.ravel(order="F")) < 2e-13
    return rho


def contraction(n,delta,epsilon):
    """Contract the closed auxiliary paths, left to right, in polynomial gauge."""
    angle = np.arccos(delta)
    k = epsilon/(2*np.sin(angle))
    plus = np.array([[0.,1.],[0.,0.]])
    current = {0: np.ones((1,1),dtype=complex)}
    for site in range(n):
        next_paths = {}
        for r,prefix in current.items():
            s,c = np.sin(r*angle),np.cos(r*angle)
            b = np.sin((r+1)*angle)*(-(1+k*k)*s+2j*k*c)
            for height,op,weight in [(r,np.eye(2),c+1j*k*s),
                                     (r+1,plus,b),(r-1,plus.T,1)]:
                if 0 <= height <= n-site-1:
                    next_paths[height] = next_paths.get(height,0) + weight*np.kron(prefix,op)
        current = next_paths
    factor = current[0]
    raw = factor@factor.conj().T
    return raw/np.trace(raw)


def charges(n):
    numbers = np.array([n - bin(x).count("1") for x in range(2**n)])
    return (numbers[:,None]-numbers[None,:]).ravel(order="F")


def spectrum_parts(gen,charge):
    return {q: np.linalg.eigvals(gen[np.ix_(charge==q,charge==q)]) for q in np.unique(charge)}


def dimer_modes():
    gen,_,_ = spin_chain(2,2,0,2,2)
    charge = charges(2)
    references = {0: [0,-4,-2,-2,-2+4j,-2-4j],
                  1: [-1,-3,-2+1j*np.sqrt(7),-2-1j*np.sqrt(7)], 2: [-2]}
    for q,eigenvalues in spectrum_parts(gen,charge).items():
        gaps = [-x.real for x in eigenvalues if x.real < -1e-10]
        print("dimer charge sector, dimension, gap",q,len(eigenvalues),min(gaps))
        np.testing.assert_allclose(min(gaps),1 if abs(q)==1 else 2,atol=2e-13)
        # Match roots with multiplicity without sorting on nearly equal real parts.
        remaining = list(eigenvalues)
        for target in references[abs(q)]:
            nearest = min(range(len(remaining)),key=lambda i: abs(remaining[i]-target))
            assert abs(remaining.pop(nearest)-target) < 2e-12
    indices = [a+4*b for a,b in ((0,1),(0,2),(1,3),(2,3))]
    expected = [[-1,2j,0,2],[2j,-3,0,0],[0,2,-1,-2j],[0,0,-2j,-3]]
    np.testing.assert_allclose(gen[np.ix_(indices,indices)],expected,atol=2e-14)
    v = np.zeros((4,4),dtype=complex)
    v[0,1],v[0,2],v[1,3],v[2,3] = 1,1j,1j,1
    x = v+v.conj().T
    np.testing.assert_allclose(gen@x.ravel(order="F"),-x.ravel(order="F"),atol=2e-14)
    rho = fixed_point(gen)
    assert np.linalg.eigvalsh(rho+x/50)[0] > 0
    np.testing.assert_allclose(np.sum(abs(np.linalg.eigvalsh(x)))/2,2)


def detuned_pair():
    for detuning in (-2,0,2):
        gen,_,bonds = spin_chain(2,1,0,1,1,detuning)
        rho = fixed_point(gen)
        j = np.trace(rho@(1j*(bonds[0]-bonds[0].T))).real
        expected = 2/(5+detuning**2)
        np.testing.assert_allclose([j,rho[1,2]], [expected,expected*(detuning+1j)/2],atol=2e-14)
        print("detuning, current, coherence",detuning,j,rho[1,2])


def finite_observables():
    for n,delta,epsilon in [(2,.5,1),(3,.5,1),(3,-.5,1),(4,.3,.7),(2,0,1),(3,0,1),(4,0,1)]:
        gen,raising,bonds = spin_chain(n,2,delta,2*epsilon,2*epsilon)
        rho = contraction(n,delta,epsilon)
        np.testing.assert_allclose(rho,fixed_point(gen),rtol=0,atol=2e-13)
        singular_values = np.linalg.svd(gen,compute_uv=False)
        assert sum(singular_values < 1e-11) == 1
        j = np.array([np.trace(rho@(4j*(b-b.T))).real for b in bonds])
        print("n, anisotropy, drive, Pauli currents",n,delta,epsilon,j)
        if delta == 0:
            np.testing.assert_allclose(j,8*epsilon/(4+epsilon**2),atol=2e-14)
        if n == 3:
            long_bond = raising[0]@raising[2].T
            chirality = np.trace(rho@(1j*(long_bond-long_bond.T))).real
            norm = 8+2*epsilon**2*(2+delta**2+epsilon**2/4)
            np.testing.assert_allclose(chirality,4*epsilon*delta/norm,atol=2e-14)
            print("end-to-end imaginary coherence observable",chirality)


def collective_dephasing():
    gen,_,_ = spin_chain(3,2,.5,2,2)
    rho = fixed_point(gen)
    charge = charges(3)
    gamma = 1/8
    modified = gen - gamma*np.diag(charge**2)
    np.testing.assert_allclose(fixed_point(modified),rho,rtol=0,atol=2e-14)
    np.testing.assert_allclose(gen[charge[:,None]!=charge[None,:]],0)
    for q in range(-3,4):
        block = np.ix_(charge==q,charge==q)
        np.testing.assert_allclose(modified[block]-gen[block],
                                   -gamma*q*q*np.eye(np.count_nonzero(charge==q)),atol=2e-14)
    print("maximally coherent sectors, decay rate before and after",
          -gen[charge==3][:,charge==3].item().real,-modified[charge==3][:,charge==3].item().real)
    cat = np.zeros((8,8))
    cat[0,-1] = cat[-1,0] = cat[0,0] = cat[-1,-1] = .5
    probe = np.zeros_like(cat)
    probe[0,-1] = probe[-1,0] = 1
    for generator,rate in ((gen,2),(modified,25/8)):
        np.testing.assert_allclose(generator.conj().T@probe.ravel(order="F"),
                                   -rate*probe.ravel(order="F"),atol=2e-14)
        np.testing.assert_allclose(np.trace(cat@probe),1.)


if __name__ == "__main__":
    dimer_modes()
    detuned_pair()
    finite_observables()
    collective_dephasing()
