"""Lowest zero-momentum Lee-Yang pair, real mL = 8, 12, 16.

Requires Python 3, NumPy and SciPy. Dorey and Tateo, hep-th/9607167v2,
Eqs. (1.5)-(1.9), (3.2)-(3.3) and (3.7). Energies are in mass units.
Run this file to compare independent quadratures and on-shell quantization.
"""
from math import pi
import numpy as np
from numpy.polynomial.legendre import leggauss
from scipy.optimize import brentq, root


POLE_SINE = np.sin(pi / 3)


def scattering(theta):
    momentum = np.sinh(theta)
    return (momentum + 1j * POLE_SINE) / (momentum - 1j * POLE_SINE)


def kernel(theta):
    return -2 * POLE_SINE * np.cosh(theta) / (np.sinh(theta)**2 + POLE_SINE**2)


def quadrature(cutoff, count, method):
    """Return nodes and weights including the convolution measure 1/(2 pi)."""
    if method == "gauss":
        nodes, weights = leggauss(count)
        return cutoff * nodes, cutoff * weights / (2 * pi)
    if method == "trapezoid":
        nodes = np.linspace(-cutoff, cutoff, count + 1)
        weights = np.full(nodes.size, (2 * cutoff / count) / (2 * pi))
        weights[[0, -1]] *= 0.5
        return nodes, weights
    raise ValueError("Select gauss or trapezoid")


def thermal_log(driving, convolution):
    """Iterate log(1 + exp(-epsilon)) for fixed source position."""
    values = np.logaddexp(0.0, -driving)
    for _ in range(100):
        updated = np.logaddexp(0.0, convolution @ values - driving)
        if np.max(abs(updated - values)) < 1.e-15:
            return updated
        values = updated
    raise RuntimeError("Real-axis iteration did not converge")


def solve_pair(r, cutoff, count, method):
    nodes, weights = quadrature(cutoff, count, method)
    convolution = kernel(nodes[:, None] - nodes[None, :]) * weights
    free_drive = r * np.cosh(nodes)
    energy_weights = weights * np.cosh(nodes)
    vacuum = -energy_weights @ thermal_log(free_drive, convolution)
    x_by = brentq(lambda x: r * np.sinh(x) + np.angle(scattering(2*x)) - 2*pi, 0, 2)

    def evaluate(parameters):
        x, log_offset = parameters
        delta = -np.exp(log_offset)
        z = x + 1j * (pi / 6 + delta)
        driving = free_drive + 2 * np.log(abs(scattering(nodes - z)))
        driving += 2 * np.log(abs(scattering(nodes + z.conjugate())))
        values = thermal_log(driving, convolution)
        continued = r * np.cosh(z) - (weights * kernel(z - nodes)) @ values
        # The denominator sin(2y)-sin(pi/3) is tiny. Evaluate its factorization.
        difference = 2 * np.cos(pi / 3 + delta) * np.sin(delta)
        pole_log = np.log(abs((2 * POLE_SINE + difference) / difference)) + 1j*pi
        residual = continued + np.log(scattering(2*x)) - np.log(scattering(2*z)) - pole_log
        subtracted = 4 * np.cosh(x) * np.sin(z.imag) - energy_weights @ values
        return residual, subtracted

    # The modulus of the zero condition close to the positive bound-state pole.
    log_seed = np.log(2 * POLE_SINE * abs(scattering(2*x_by + 1j*pi/3)))
    log_seed -= r * np.cosh(x_by) * np.cos(pi / 6)

    def equations(parameters):
        value, _ = evaluate(parameters)
        return [value.real, value.imag]

    result = root(equations, [x_by, log_seed], tol=1.e-11)
    residual, energy = evaluate(result.x)
    if not result.success or abs(residual) > 2.e-11:
        raise RuntimeError("The active zero did not satisfy its complex condition")
    x, log_offset = result.x
    return np.array([x, -np.exp(log_offset), energy, vacuum, energy-vacuum,
                     2*np.cosh(x_by), abs(residual)])


if __name__ == "__main__":
    print("mL  x  y-pi/6  E_sub/m  E_vac,sub/m  gap/m  E_BY/m  |zero residual|")
    for size in (8, 12, 16):
        gauss = solve_pair(size, 5, 128, "gauss")
        trapezoid = solve_pair(size, 6, 480, "trapezoid")
        change = np.max(abs(gauss[:6] - trapezoid[:6]))
        print(size, *(f"{v:.12g}" for v in trapezoid))
        print(f"  largest difference between quadratures: {change:.3g}")
        assert change < 2.e-10
