"""Checks of heat capacity, oscillator expectations and two response functions.

Run with Python 3, NumPy, SciPy and SymPy. Printed values are dimensionless.
"""
from math import pi

import numpy as np
import sympy as sp
from scipy.integrate import quad
from scipy.linalg import expm


def oscillator_capacity(x):
    x = np.asarray(x, dtype=float)
    # x/(2 sinh(x/2)) written using a decaying exponential at high frequency.
    ratio = np.divide(x, -np.expm1(-x), out=np.ones_like(x), where=(x != 0))
    return ratio**2 * np.exp(-x)


def thermal_ring(count, b, pinning=4.):
    theta = 2*pi*np.arange(count)/count
    x = b*np.sqrt((pinning/count)**2 + 4*np.sin(theta/2)**2)
    return oscillator_capacity(x).mean()


def thermal_limit(b):
    return quad(lambda t: oscillator_capacity(2*b*np.sin(t/2)), 0, pi)[0]/pi


def cubic_ground_state():
    x = sp.symbols("x", real=True)
    epsilon = sp.symbols("epsilon", positive=True)
    wave = sp.exp(-x*x/(2*epsilon)) / (sp.pi*epsilon)**sp.Rational(1,4)
    momentum_cube = lambda f: (-sp.I*epsilon)**3 * sp.diff(f, x, 3)
    comm = (x**3*momentum_cube(wave)-momentum_cube(x**3*wave))/(sp.I*epsilon)
    measured = sp.simplify(sp.integrate(wave*comm, (x, -sp.oo, sp.oo)))
    assert measured == 3*epsilon**2/4
    print("Ground-state cubic commutator:", measured)


def ring_covariance():
    for count in (6, 11, 20):
        eye = np.eye(count)
        pinning = 0.75
        stiffness = (pinning**2+2)*eye - np.roll(eye, 1, axis=1) - np.roll(eye, -1, axis=1)
        column = np.linalg.solve(stiffness, eye[:, 0])
        q = np.exp(-np.arccosh(1+pinning**2/2))
        r = np.arange(count)
        predicted = (q**r+q**(count-r))/(1+q**count)
        np.testing.assert_allclose(predicted, column/column[0], rtol=2e-13)


def amplified_residual():
    time, coupling, defect = 5., 100., 1e-3
    augmented = np.array([[-1.,coupling,0.],[0.,-1.,defect],[0.,0.,0.]])
    actual = expm(time*augmented)[:2,2]
    expected = defect*np.array([coupling*(1-(1+time)*np.exp(-time)),1-np.exp(-time)])
    np.testing.assert_allclose(actual, expected)
    print("Error for a constant residual:", actual)


def corrected_charge():
    q, r, p, s, a, b, e = sp.symbols("q r p s a b epsilon")
    energy = (p**2 + s**2 + a*q*q + b*r*r)/2 + e*q*r
    charge = (p*p + a*q*q)/2 + e*(a*q*r+p*s)/(a-b) + e**2*(q*q+r*r)/(2*(a-b))
    bracket = sum(sp.diff(charge,x)*sp.diff(energy,y)-sp.diff(charge,y)*sp.diff(energy,x)
                  for x,y in ((q,p),(r,s)))
    assert sp.simplify(bracket) == 0


if __name__ == "__main__":
    for beta_scale in (0.25, 1., 2.):
        limit = thermal_limit(beta_scale)
        values = [thermal_ring(n, beta_scale) for n in (4, 16, 64, 256)]
        assert abs(values[-1]-limit) < abs(values[-2]-limit)
        print("Thermal scale, four ring refinements, limiting value:", beta_scale, values, limit)
    cubic_ground_state()
    ring_covariance()
    amplified_residual()
    corrected_charge()
