"""Finite full-trace spin propagator. NumPy, periodic spin half, H=sum S_j.S_{j+1}."""

import numpy as np


def propagators(length, times):
    times = np.asarray(times)
    correlations = np.zeros((len(times), length))
    for down in range(length+1):
        states = [b for b in range(2**length) if bin(b).count("1") == down]
        index = {b:i for i,b in enumerate(states)}
        spins = np.array([[0.5-((b>>j)&1) for j in range(length)] for b in states])
        h = np.diag(np.sum(spins*np.roll(spins, -1, axis=1), axis=1))
        for i,bits in enumerate(states):
            for j in range(length):
                k = (j+1)%length
                if ((bits>>j) ^ (bits>>k)) & 1:
                    h[index[bits ^ (1<<j) ^ (1<<k)], i] += 0.5
        energy, v = np.linalg.eigh(h)
        initial = v.T @ (spins[:,0,None]*v)
        for i,t in enumerate(times):
            phase = np.exp(1j*energy*t)
            evolved = (phase[:,None]*phase.conj()[None,:])*initial
            diag = np.sum((v@evolved)*v, axis=1).real
            correlations[i] += diag@spins / 2**length
    np.testing.assert_allclose(np.sum(correlations,axis=1), 0.25, rtol=0, atol=2e-14)
    return correlations / 0.25


if __name__ == "__main__":
    for length in [8,10,12]:
        times = np.array([1.,2.,3.,4.])
        p = propagators(length,times)
        distance = np.minimum(np.arange(length),length-np.arange(length))
        for cutoff in [2,length//2]:
            moment = p @ (distance**2*(distance<=cutoff))
            # Effective width exponent uses paired times, no fit and no renormalization of tails.
            alpha12 = np.log(moment[1]/moment[0])/(2*np.log(2))
            alpha24 = np.log(moment[3]/moment[1])/(2*np.log(2))
            print(length,cutoff,*[round(float(x),6) for x in moment],f"{alpha12:.5f}",f"{alpha24:.5f}")
