"""Energy-matched temperature, paired saddle and Ising relaxation (NumPy, SciPy)."""

import numpy as np
from scipy.optimize import brentq


def evaluate(points):
    k = (np.arange(points) + 0.5) * np.pi / points
    cos_k = np.cos(k)
    r0, r = np.sqrt(1.25 - cos_k), np.sqrt(5 - 4*cos_k)
    c0, c = (0.5 - cos_k)/r0, (2 - cos_k)/r
    d = (2 - 2.5*cos_k)/(r0*r)
    p = (1-d)/2
    energy = -np.mean(r*d)
    beta = brentq(lambda b: energy + np.mean(r*np.tanh(b*r)), 0, 4, xtol=1e-14)
    gibbs = np.tanh(beta*r)
    magnetization = np.mean(c*d)
    hopping = np.mean((1 - 2*cos_k)*d/r)
    # The second correlator comes from the rotated bond symbol, independently of energy.
    np.testing.assert_allclose(energy, -hopping-2*magnetization, atol=1e-14)
    np.testing.assert_allclose(p + (1-p), 1, atol=1e-14)
    np.testing.assert_allclose(energy, np.mean(r*(2*p-1)), atol=1e-14)
    print(f"{points:6d} momenta, quasiparticle density={np.mean(p):.9f}")
    print(f"energy={energy:.9f}, beta*J={beta:.9f}")
    print(f"stationary mz={magnetization:.9f} xx={hopping:.9f}")
    print(f"thermal mz={np.mean(c*gibbs):.9f} xx={np.mean((1-2*cos_k)*gibbs/r):.9f}")
    for t in [16, 32, 64, 100, 200]:
        exact = np.mean((c0-c*d)*np.cos(4*r*t))
        leading = (-3*np.cos(4*t+3*np.pi/4)/(4*t)**1.5
                   - np.cos(12*t-3*np.pi/4)/(9*(4*t/3)**1.5))/(4*np.sqrt(np.pi))
        print(f"Jt={t:3d}: transient={exact:+.9e} leading={leading:+.9e}")
    return np.array([energy, beta, magnetization, hopping, np.mean(p)])


if __name__ == "__main__":
    low = evaluate(8192)
    high = evaluate(65536)
    np.testing.assert_allclose(low, high, atol=2e-14, rtol=0)
