"""Current, magnetization and finite-period observables. Requires NumPy and SciPy."""

from functools import reduce
import numpy as np
from scipy.linalg import expm, solve_sylvester


identity = np.eye(2)
plus = np.array([[0., 1.], [0., 0.]])
minus = plus.T
z = np.diag([1., -1.])


def tensor(*operators):
    return reduce(np.kron, operators)


def local(op, site, length):
    factors = [identity] * length
    factors[site] = op
    return tensor(*factors)


def stationary(length, hopping, interaction, left, right):
    dimension = 2**length
    one = np.eye(dimension)
    up = [local(plus, j, length) for j in range(length)]
    zz = [local(z, j, length) for j in range(length)]
    bonds = [up[j] @ up[j+1].T for j in range(length-1)]
    h = sum(hopping*(b+b.T) for b in bonds)
    h += interaction*sum(zz[j]@zz[j+1] for j in range(length-1))
    generator = -1j*(np.kron(one, h) - np.kron(h.T, one))
    for jump in [np.sqrt(left)*up[0], np.sqrt(right)*up[-1].T]:
        g = jump.T@jump
        generator += np.kron(jump, jump) - (np.kron(one, g)+np.kron(g.T, one))/2
    rhs = np.zeros(dimension**2)
    rhs[0] = 1.
    system = generator.copy()
    system[0] = one.flatten()
    rho = np.linalg.solve(system,rhs).reshape((dimension,dimension),order='F')
    assert np.min(np.linalg.eigvalsh(rho)) > -1e-12
    np.testing.assert_allclose(np.trace(rho), 1., atol=1e-13)
    current = [np.trace(rho @ (1j*hopping*(b-b.T))).real for b in bonds]
    magnet = [np.trace(rho@op).real for op in zz]
    np.testing.assert_allclose(current, left*(1-magnet[0])/2, atol=1e-13)
    np.testing.assert_allclose(current, right*(1+magnet[-1])/2, atol=1e-13)
    return generator, rho, magnet, current


def short_xxz(delta, epsilon):
    # Only auxiliary heights 0 and 1 occur in three sites.
    s = np.eye(8) + 1j*epsilon*(tensor(plus,minus,identity) +
        tensor(identity,plus,minus) + (delta+1j*epsilon/2)*tensor(plus,identity,minus))
    rho = s @ s.conj().T
    rho /= np.trace(rho)
    gen, direct, magnet, current = stationary(3,2,delta,2*epsilon,2*epsilon)
    residual = np.linalg.norm(gen@rho.flatten(order='F'))
    np.testing.assert_allclose(rho,direct,atol=1e-13)
    return magnet, current, residual, np.linalg.eigvalsh(rho)[0]


def free_contacts(length, hopping, left, right):
    adjacency = np.diag(np.ones(length-1),1)
    drive = np.zeros((length,length))
    drive[0,0] = left
    loss = drive.copy()
    loss[-1,-1] = right
    drift = -1j*hopping*(adjacency+adjacency.T)-loss/2
    covariance = solve_sylvester(drift,drift.conj().T,-drive)
    current = 2*hopping*np.diag(covariance,1).imag
    expected = 1/(1/left+1/right+(left+right)/(4*hopping**2))
    np.testing.assert_allclose(current, expected, atol=1e-12)
    return current[0], covariance.diagonal().real[[0,-1]]


def swap(count, a, b):
    matrix = np.eye(2**count).reshape([2]*(2*count))
    return matrix.swapaxes(a,b).reshape(2**count,2**count)


def circuit(d, angle):
    length = 4
    one = np.eye(2**length)
    bonds = [swap(length,j,(j+1)%length) for j in range(length)]
    gates = [(one+1j*d*p)/(1+1j*d) for p in bonds]
    period = gates[0]@gates[2]@gates[1]@gates[3]
    kicked = expm(-1j*angle*local(plus+minus,0,length)/2)@period
    big = np.eye(2**(length+1))
    row, derivative = big, 0*big
    for site in range(length):
        p = swap(length+1,0,site+1)
        x = d/2-(-1)**(site+1)*d/2
        r = (p+1j*x*big)/(1+1j*x)
        dr = 1j*(big-p)/(1+1j*x)**2
        derivative, row = dr@row+r@derivative, r@row
    trace_aux = lambda a: a.reshape(2,16,2,16).trace(axis1=0,axis2=2)
    q = np.linalg.solve(trace_aux(row),trace_aux(derivative)/1j)
    np.testing.assert_allclose(q,q.conj().T,atol=1e-13)
    np.testing.assert_allclose(q@period,period@q,atol=1e-13)
    h0 = sum(p-one for p in bonds)
    uniform = expm(1j*np.arctan(d)*h0)
    observable = local(z,0,length)@local(z,1,length)
    transverse = local(-1j*(plus-minus),0,length) @ local(z,1,length)
    for theta in [-angle, angle]:
        rotated = expm(-1j*theta*local(plus+minus,0,length)/2) @ period[:,5]
        signal = np.vdot(rotated, transverse @ rotated).real
        before = np.vdot(period[:,5], observable @ period[:,5]).real
        np.testing.assert_allclose(signal, -before*np.sin(theta), atol=1e-14)
        print(f'angle {theta}, transverse correlator {signal:.8f}')
    for name,unitary in [('exact',period),('rotation',kicked),('uniform',uniform)]:
        state = one[:,5]   # up,down,up,down
        for t in range(5):
            print(name,t,*(round(float(np.vdot(state,a@state).real),8)
                           for a in [q,h0,observable]))
            state = unitary@state


if __name__ == "__main__":
    for rates in [(1.,1.),(1.,3.)]:
        _, rho, mag, j = stationary(2,1,0,*rates)
        print('pair',rates,np.diag(rho).real,rho[1,2],mag,j)
    for epsilon in [.5,1.]:
        print('XXZ',epsilon,short_xxz(.5,epsilon))
    for length in [2,4,8,16]:
        for gamma in [.5,2.]:
            print('contacts',length,gamma,free_contacts(length,1,gamma,gamma))
    circuit(.5,.4)
