"""Neel-quench interval entropies and a free-particle Airy front, in units J=hbar=1.

Run with Python 3, NumPy and SciPy. The exact covariance is for the infinite chain.
"""

import numpy as np
from scipy.integrate import quad
from scipy.special import airy, jv, xlogy


def interval_entropy(length, time):
    sites = np.arange(length)
    separation = sites[:, None] - sites[None, :]
    propagator = (1j ** separation) * jv(separation, 4.0 * time)
    covariance = (np.eye(length) + propagator * (-1) ** sites) / 2
    np.testing.assert_allclose(covariance, covariance.conj().T, atol=1e-14)
    eigenvalues = np.linalg.eigvalsh(covariance)
    assert eigenvalues[0] > -1e-12 and eigenvalues[-1] < 1 + 1e-12
    p = np.clip(eigenvalues, 0, 1)
    return -sum(xlogy(p, p) + xlogy(1-p, 1-p))


def pair_entropy(length, time):
    def mode(k):
        return min(length, 4 * time * np.sin(k))

    split = [np.arcsin(length / (4*time))] if 4*time > length else []
    integral, error = quad(mode, 0, np.pi/2, points=split, epsabs=1e-11)
    assert error < 1e-9
    return 2 * np.log(2) * integral / np.pi


if __name__ == "__main__":
    for ratio in [0.08, 0.3, 2.0]:
        for length in [24, 48, 96]:
            time = ratio * length
            print("interval", length, ratio, interval_entropy(length, time)/length,
                  pair_entropy(length, time)/length)
    for time in [32, 256, 2048]:
        for z in [0, 2]:
            site = round(2*time + z*time**(1/3))
            actual_z = (site - 2*time)/time**(1/3)
            print("front", time, site, time**(1/3)*jv(site, 2*time), airy(actual_z)[0])
