"""Connection coefficients, a zero-energy quartic trace, and the oscillator product.

Run with Python 3, NumPy, and SciPy. Every constant uses the dimensionless
Hamiltonians written in the two Library endpoint articles.
"""

from math import cos, exp, pi, sin, sqrt

import numpy as np
from scipy.integrate import quad, solve_ivp
from scipy.optimize import brentq
from scipy.special import digamma, gamma, ive, kve, rgamma


def robin_ground():
    """A=2, B=1, increasing-coordinate derivative plus value at the outer end."""
    def coefficients(E):
        k = sqrt(E)
        a, b, c = (3-k)/2, (3+k)/2, 2.5
        constant = gamma(c)*gamma(.5)*rgamma(a)*rgamma(b)
        linear = gamma(c)*gamma(-.5)*rgamma(c-a)*rgamma(c-b)
        return constant, linear

    def robin(E):
        constant, linear = coefficients(E)
        return constant-linear

    expected = brentq(robin, 4, 9)
    k = brentq(lambda k: (1-k*k)*sin(k*pi/2)+k*cos(k*pi/2), 2, 3)
    assert abs(k*k-expected) < 2e-12

    def endpoint(E, epsilon):
        def rhs(x, y):
            return [y[1], (2/sin(x)**2-E)*y[0]]
        # Regular solution x^2(1+c*x^2+...), scaled by epsilon^(-2).
        c = (2/3-E)/10
        y = [1+c*epsilon**2, 2/epsilon+4*c*epsilon]
        sol = solve_ivp(rhs, (epsilon, pi/2), y, method="DOP853", rtol=2e-12, atol=1e-12)
        assert sol.success
        return epsilon**2*sol.y[:, -1]

    for epsilon in (.002, .001):
        measured = brentq(lambda E: sum(endpoint(E, epsilon)), 4, 9)
        assert abs(expected-measured) < 1e-10
        assert abs(endpoint(4, epsilon)[1]) < 1e-10 and abs(endpoint(9, epsilon)[0]) < 1e-10
        print(f"Robin ground E={measured:.10f}, initial x={epsilon:g}; Neumann 4, Dirichlet 9")


def quartic_trace():
    """Half-line x^4 with Dirichlet or Neumann data; scaled Bessel functions avoid overflow."""
    nu = 1/6

    def green(x, order=nu):
        t = x**3/3
        if t > 1e4:
            # I_nu K_nu = [1-(4nu^2-1)/(8t^2)+O(t^-4)]/(2t).
            return (1-(4*nu*nu-1)/(8*t*t))/(2*x*x)
        return x*ive(order, t)*kve(nu, t)/3

    total = (quad(green, 0, 1, epsabs=1e-12)[0]
             + quad(lambda u: green(1/u)/(u*u), 0, 1, epsabs=1e-12)[0])
    print(f"Half-line zero-energy Green trace: {total:.10f}")
    for split in (1, 2):
        neumann = (quad(green, 0, split, args=(-nu,), epsabs=2e-13, epsrel=2e-13)[0]
                   + quad(lambda u: green(1/u, -nu)/u**2, 0, 1/split,
                          epsabs=2e-13, epsrel=2e-13)[0])
        assert abs(neumann - 2*total) < 2e-12
        print(f"Split at {split}: Neumann trace {neumann:.10f}; Stokes slope {sqrt(3)*neumann:.10f}")
    for R in (4, 6, 8, 10):
        def rhs(x, y):
            u, du, v, dv = y
            return [du, x**4*u, dv, x**4*v-u]

        sol = solve_ivp(rhs, (0, R), [0, 1, 0, 0], method="DOP853", rtol=2e-12, atol=1e-13)
        assert sol.success
        u, _, v, _ = sol.y[:, -1]
        finite = -v/u
        # The finite Dirichlet Green function vanishes at R; use the same wall
        # in the independent Bessel integration to compare exactly like spectra.
        tR = R**3/3
        def finite_green(x):
            t = x**3/3
            correction = (x/3 * ive(nu, t)**2 * exp(2*(t-tR))
                          * kve(nu, tR)/ive(nu, tR))
            return green(x)-correction
        integral = quad(finite_green, 0, R, epsabs=1e-12)[0]
        assert abs(finite-integral) < 1e-11
        print(f"R={R}: finite-box trace {finite:.10f}; scaled missing trace {R*(total-finite):.7f}")


def oscillator_product():
    a0 = .75
    exact = gamma(a0)/gamma(a0-.25)
    for N in (100, 1000, 10000):
        t = 1/(4*np.arange(N)+3)
        factors = (np.log1p(-t)+t).sum()
        corrected = exp(factors+digamma(a0)/4)
        assert abs(corrected-exact) < .023/N
        print(f"N={N}: uncorrected {exp(np.log1p(-t).sum()):.7f}, "
              f"genus-one factors {exp(factors):.7f}, Wronskian-normalized {corrected:.7f}")


if __name__ == "__main__":
    robin_ground()
    quartic_trace()
    oscillator_product()
