"""Finite-chain illustrations for the Research dossiers. Requires NumPy and SciPy.
Run: python3 quantum_dynamics_checks.py
Printed data use the units and the boundary orientations of the linked articles.
"""
from itertools import combinations
import numpy as np
from scipy.linalg import eigh_tridiagonal, expm
from scipy.special import airy, jv, xlogy


def projected_quench():
    """Probability in the nonzero-Q3 subspace at fixed magnetization."""
    length = 6
    states = [sum(1 << j for j in occupied) for occupied in combinations(range(length), 3)]
    swaps = []
    for j in range(length):
        k = (j + 1) % length
        swap = np.zeros((len(states), len(states)))
        for col, bits in enumerate(states):
            different = ((bits >> j) ^ (bits >> k)) & 1
            out = bits ^ ((1 << j) | (1 << k)) if different else bits
            swap[states.index(out), col] = 1
        swaps.append(swap)
    h = -sum(swaps) / 2
    q = 1j * sum(s @ swaps[(j+1) % length] - swaps[(j+1) % length] @ s for j, s in enumerate(swaps))
    assert np.linalg.norm(h @ q - q @ h) < 1e-12
    vals, vecs = np.linalg.eigh(q)
    for word in ("101010", "110010", "111000"):
        i = states.index(int(word, 2))
        weights = abs(vecs[i, :])**2
        print("Q3", word, "weight outside kernel", weights[abs(vals) > 1e-9].sum(),
              "second moment", np.dot(vals**2, weights))


def fronts():
    """Infinite-line step, exact Bessel density and Airy-edge comparison."""
    print("Airy edge diagonal at zero", airy(0.)[1]**2)
    for t in (32, 64, 128, 256, 512):
        sites = np.arange(0, 2*t+60)
        bessel_squared = jv(sites, t)**2
        bulk = bessel_squared[t//2:].sum()
        edge = (t/2)**(1/3)*bessel_squared[t:].sum()
        tail = jv(np.arange(2*t+60, 3*t+120), t)**2
        print("front", t, "density(ray=.5)", bulk, "scaled(edge)", edge, "added tail", tail.sum())
    # Site zero is occupied on both geometries. Keep time fixed while moving
    # both boundaries away, independently of truncating the Bessel series.
    time = 32
    for length in (80, 128, 192):
        origin = length//2-1
        energies, modes = eigh_tridiagonal(np.zeros(length), -.5*np.ones(length-1))
        occupations = modes[:origin+1, :].T
        amplitudes = (modes[[origin+16,origin+32], :]*np.exp(-1j*time*energies)) @ occupations
        densities = np.sum(abs(amplitudes)**2, axis=1)
        reference = [np.sum(jv(np.arange(j, 3*time),time)**2) for j in (16,32)]
        print("open length",length,"density differences from infinite chain",densities-reference)
        if length >= 128:
            assert np.max(abs(densities-reference)) < 2e-13


def entropy_windows():
    """Thermodynamic interpretation requires a separate size/interval limit."""
    def entropy(matrix, sites):
        vals = np.clip(np.linalg.eigvalsh(matrix[np.ix_(sites, sites)]), 0, 1)
        return -np.sum(xlogy(vals, vals) + xlogy(1-vals, 1-vals))
    for length in (48, 96):
        translation = np.roll(np.eye(length), 1, axis=0)
        h = -(translation + translation.T)/2
        u = expm(-1j*h*2)
        c = u[:, ::3] @ u[:, ::3].conj().T
        a, b, d = list(range(3)), list(range(3, 6)), list(range(6, 9))
        ent = lambda sites: entropy(c, sites)
        tripartite = ent(a)+ent(b)+ent(d)-ent(a+b)-ent(a+d)-ent(b+d)+ent(a+b+d)
        print("period-three", length, "S(A), S(A union C), I3", ent(a), ent(a+d), tripartite)


def weak_breaking():
    """One-magnon ring. Compare exact diagonalization with the two-level formula."""
    length = 8
    tr = np.roll(np.eye(length), 1, axis=0)
    h0 = -(tr + tr.T)/2
    v = np.diag((-1.)**np.arange(length))
    momentum = np.ones(length) / np.sqrt(length)
    for coupling in (.1, .2):
        for t in (.05, 1., 3., 6.):
            state = expm(-1j*(h0+coupling*v)*t) @ momentum
            missing = 1-abs(np.vdot(momentum, state))**2
            exact = coupling**2/(1+coupling**2)*np.sin(np.sqrt(1+coupling**2)*t)**2
            assert abs(missing-exact) < 1e-13 and abs(np.vdot(state,state)-1)<1e-13
            print("weak breaking", coupling, t, "occupation loss", missing)

if __name__ == "__main__":
    projected_quench()
    fronts()
    entropy_windows()
    weak_breaking()
