"""One-particle Lindblad evolution on a finite periodic chain.

Python 3, NumPy and SciPy. Lattice spacing, hopping and dephasing rate are one.
Distances are shortest distances to the preparation site on the ring.
"""
import numpy as np
from scipy.sparse import csr_matrix, diags, eye, kron
from scipy.sparse.linalg import expm_multiply


def ring_moments(length, time_step, steps):
    sites = np.arange(length)
    shift = csr_matrix((np.ones(length), ((sites + 1) % length, sites)),
                       shape=(length, length))
    hamiltonian = -shift - shift.T
    unit = eye(length, format="csr")
    # Flatten by rows. Left multiplication acts on the first tensor index.
    commutator = kron(hamiltonian, unit) - kron(unit, hamiltonian.T)
    off_diagonal = np.ones((length, length)) - np.eye(length)
    generator = -1j * commutator - diags(off_diagonal.ravel())
    initial = np.zeros(length**2)
    initial[0] = 1
    evolved = expm_multiply(generator, initial, start=0, stop=time_step*steps,
                            num=steps + 1)
    populations = np.real(evolved[:, sites*(length + 1)])
    np.testing.assert_allclose(populations.sum(axis=1), 1., atol=2e-13, rtol=0)
    assert populations.min() >= -2e-14
    distance_squared = np.minimum(sites, length - sites)**2
    return populations @ distance_squared


def on_line(time):
    return 4 * (time + np.expm1(-time))


if __name__ == "__main__":
    times = np.arange(5)
    exact = on_line(times)
    for length in (40, 64):
        values = ring_moments(length, 1, 4)
        np.testing.assert_allclose(values, exact, atol=5e-12, rtol=0)
        print(f"L={length}: M2 at times 1, 2 and 4 = {values[[1, 2, 4]]}")
    for length in (8, 16):
        plateau = (length**2 + 2) / 12
        at_late_time = ring_moments(length, 120, 1)[-1]
        np.testing.assert_allclose(at_late_time, plateau, atol=2e-9, rtol=0)
        print(f"L={length}: long-time squared displacement = {at_late_time:.8f}")
