"""Two-site relative Toda ground state on the line, with hbar=1 and Lambda=1/2.

Run with Python 3, NumPy and SciPy. All quantities are in the units of the article.
"""

import math

import numpy as np
from scipy.integrate import quad
from scipy.linalg import eigh_tridiagonal, eigvalsh
from scipy.optimize import brentq
from scipy.special import eval_genlaguerre, gammaln, loggamma


HBAR = 1.0
SCALE = 0.5


def grid_energy(radius, step):
    intervals = round(2 * radius / step)
    step = 2 * radius / intervals
    x = np.linspace(-radius, radius, intervals + 1)[1:-1]
    kinetic = (HBAR / step) ** 2
    diagonal = 2 * kinetic + 2 * SCALE**2 * np.cosh(x)
    return eigh_tridiagonal(
        diagonal, np.full(len(x) - 1, -kinetic),
        select="i", select_range=(0, 0), eigvals_only=True,
    )[0]


def hermite_energy(size):
    # Oscillator units x=(a+a†)/sqrt(2); the even sector contains the ground state.
    states = 2 * np.arange(size)
    matrix = np.zeros((size, size))
    for i, n in enumerate(states):
        for j, m in enumerate(states[i:], i):
            gap = m - n
            overlap = math.exp(0.25 + 0.5 * (gammaln(n + 1) - gammaln(m + 1)))
            cosh = overlap * 2 ** (-gap / 2) * eval_genlaguerre(n, gap, -0.5)
            kinetic = (n + 0.5) if gap == 0 else 0.0
            if gap == 2:
                kinetic = -0.5 * math.sqrt((n + 1) * (n + 2))
            matrix[i, j] = matrix[j, i] = HBAR**2 * kinetic + 2 * SCALE**2 * cosh
    return eigvalsh(matrix, subset_by_index=(0, 0))[0]


def action(energy):
    turning = np.arccosh(energy / (2 * SCALE**2))
    integral = quad(
        lambda x: math.sqrt(max(0.0, energy - 2 * SCALE**2 * np.cosh(x))),
        0.0, turning, epsabs=1e-12,
    )[0]
    return 4 * integral


def gauge_estimate(include_first):
    q = SCALE**4 if include_first else 0.0

    def period(a):
        return (a * np.log(HBAR**2 / SCALE**2) - np.pi * HBAR / 2
                + 2 * HBAR * loggamma(1 + 1j * a / HBAR).imag
                + 4 * q * a / (a**2 + HBAR**2)**2)

    root = brentq(lambda a: period(a) - np.pi * HBAR / 2, 0.01, 8.0)
    return root**2 / 4 + 2 * q / (root**2 + HBAR**2)


if __name__ == "__main__":
    for radius, step in [(8, 0.04), (8, 0.02), (8, 0.01), (10, 0.01)]:
        print(f"Dirichlet radius {radius:2d}, step {step:.2f}: {grid_energy(radius, step):.10f}")
    for size in [8, 12, 18]:
        print(f"Even Hermite basis {size:2d}: {hermite_energy(size):.10f}")
    bs = brentq(lambda e: action(e) - np.pi * HBAR, 2 * SCALE**2 + 1e-9, 6)
    print(f"Bohr-Sommerfeld: {bs:.10f}")
    for include_first in [False, True]:
        print(f"Gauge estimate, {int(include_first)} instanton orders: {gauge_estimate(include_first):.10f}")
