"""Exact finite Hermitian bath return; NumPy only. Units hbar=1, bandwidth W=8."""
import numpy as np


def return_probability(count, coupling, matrix_element, times):
    width = 8
    bath = width*((np.arange(count) + .5)/count - .5)
    hamiltonian = np.diag(np.r_[0, bath])
    hamiltonian[0, 1:] = hamiltonian[1:, 0] = coupling*matrix_element/np.sqrt(count)
    energy, eigenvectors = np.linalg.eigh(hamiltonian)
    weights = abs(eigenvectors[0, :])**2
    np.testing.assert_allclose(weights.sum(), 1, atol=1e-13)
    np.testing.assert_allclose(weights @ energy**2, (coupling*matrix_element)**2, rtol=1e-13)
    return abs(np.exp(-1j * np.outer(times, energy)) @ weights)**2


if __name__ == "__main__":
    for n in (80, 160):
        for v in (1, .7):
            for g in (.25, .35):
                rates = []
                for lo, hi in [(1, 4), (8, 25), (65, 75)]:
                    t = np.arange(lo, hi+.05, .1)
                    p = return_probability(n, g, v, t)
                    rates.append(-np.polyfit(t, np.log(p), 1)[0])
                print(n, v, g, "rates:", *(f"{x:.7f}" for x in rates))
