"""Pressure and density of the repulsive Bose gas. Python 3 + NumPy; run this file."""
from math import erfc, exp, log, pi, sqrt
import numpy as np
from numpy.polynomial.legendre import leggauss


def thermal_state(cutoff, order, mu=0.0, temperature=1.0, coupling=1.0, tol=1e-13):
    """Gauss-Legendre Nyström quadrature on [-cutoff,cutoff], Newton for epsilon."""
    x, w = leggauss(order)
    k, w = cutoff*x, cutoff*w
    delta = k[:, None]-k[None, :]
    kernel = coupling / (pi*(coupling**2+delta**2)) * w[None, :]
    identity = np.eye(order)
    bare = k*k-mu
    eps = bare.copy()
    for iteration in range(40):
        thermal = np.logaddexp(0.0, -eps/temperature)
        filling = np.exp(-np.logaddexp(0.0, eps/temperature))
        residual = eps-bare + temperature*(kernel @ thermal)
        jacobian = identity-kernel*filling[None, :]
        if np.max(np.abs(residual)) <= tol:
            break
        eps -= np.linalg.solve(jacobian, residual)
    else:
        raise ArithmeticError("Pseudoenergy residual did not converge")
    # rho_p = filling * (1/(2π) + K rho_p). Rows now carry the filling.
    particles = np.linalg.solve(identity-filling[:, None]*kernel, filling/(2*pi))
    return w, thermal, filling, particles, kernel, np.max(np.abs(residual))


def equilibrium(cutoff, order, mu=0.0, temperature=1.0, coupling=1.0, tol=1e-13):
    w, thermal, _, particles, _, residual = thermal_state(cutoff, order, mu, temperature, coupling, tol)
    pressure = temperature*(w @ thermal)/(2*pi)
    return pressure, w @ particles, residual


def density_response(cutoff, order, mu=0.0, temperature=1.0, coupling=1.0):
    w, _, filling, particles, kernel, _ = thermal_state(cutoff, order, mu, temperature, coupling)
    slots = 1/(2*pi) + kernel @ particles
    charge = np.linalg.solve(np.eye(order)-kernel*filling[None, :], np.ones(order))
    np.testing.assert_allclose(charge, 2*pi*slots, atol=2e-13, rtol=0)
    return w @ (slots*filling*(1-filling)*charge**2) / temperature


def dilute_coefficient():
    # T=c=1, so the fugacity is exp(mu).
    b2 = (exp(.5)*erfc(1/sqrt(2))-.5)/sqrt(2)
    estimates = []
    for fugacity in (.02, .01, .005):
        pressure, _, _ = equilibrium(8, 128, mu=log(fugacity))
        estimate = (2*sqrt(pi)*pressure-fugacity)/fugacity**2
        estimates.append(estimate)
        print("fugacity, second coefficient estimate", fugacity, estimate)
    extrapolated = 2*estimates[-1] - estimates[-2]
    assert abs(extrapolated-b2) < 1e-5
    print("zero-fugacity coefficient, extrapolated estimate", b2, extrapolated)


def residual_on_fresh_nodes(order):
    """Reintegrate the lesson's coarse T=c=1, mu=0 solution on a finer grid."""
    cutoff = 8
    coarse, _ = leggauss(order)
    fine, fine_weights = leggauss(384)
    coarse, fine = cutoff*coarse, cutoff*fine
    weights, thermal, *_ = thermal_state(cutoff, order)

    def kernel(a, b):
        return 1 / (pi * (1 + (a[:, None]-b)**2))

    continued = fine**2 - kernel(fine, coarse) @ (weights*thermal)
    integrand = np.logaddexp(0., -continued)
    residual = continued - fine**2 + kernel(fine, fine) @ (cutoff*fine_weights*integrand)
    return np.max(abs(residual))


def report():
    for cutoff, order in [(3,96),(4,96),(6,96),(8,32),(8,48),(8,64),(8,96),(8,128)]:
        p, n, residual = equilibrium(cutoff,order)
        print(f"B={cutoff} N={order:3}   p={p:.12f} n={n:.12f} residual={residual:.1e}")
    p, n, _ = equilibrium(8,128)
    for h in [0.1,0.01,0.001,0.0001]:
        dp = (equilibrium(8,128,h)[0]-equilibrium(8,128,-h)[0])/(2*h)
        print(f"dμ={h:.4g}  pressure derivative={dp:.12f}  error={abs(dp-n):.2e}")
    # At fixed μ/c² and T/c² the dimensionless pressure and density agree.
    scaled_p, scaled_n, _ = equilibrium(16,128,temperature=4.0,coupling=2.0)
    assert abs(scaled_p/8-p) < 1e-11 and abs(scaled_n/2-n) < 1e-11
    assert abs(dp-n) < 1e-8
    assert abs(equilibrium(8,96)[0]-p)<1e-9 and abs(equilibrium(8,96)[1]-n)<1e-9
    for tol in [1e-6,1e-10,1e-13]:
        print("iteration tolerance",tol,equilibrium(8,128,tol=tol))
    print("T=1, μ=1, c=2",equilibrium(8,128,mu=1,coupling=2))
    response = density_response(8,128)
    for h in (.01, .001, .0001):
        slope = (equilibrium(8,128,h)[1]-equilibrium(8,128,-h)[1])/(2*h)
        print("dμ, density slope, dressed response", h, slope, response)
    assert abs(slope-response) < 1e-8
    dilute_coefficient()
    disagreements = [residual_on_fresh_nodes(order) for order in (32, 64, 128)]
    print("residual on fresh nodes after 32, 64, 128 coarse nodes", disagreements)
    assert disagreements[0] > 1e-3 and disagreements[1] < 5e-7 and disagreements[2] < 1e-12


if __name__ == "__main__":
    report()
