"""Quartic double-well tunneling, with Python 3, NumPy and SciPy.

H=-h^2 d^2/dx^2+(x^2-1)^2. Centered second differences, Dirichlet
endpoints at +/-R. Compare Garg, arXiv:cond-mat/0003115, Eqs. (5.1)-(5.5).
"""
import math

import numpy as np
from scipy.integrate import simpson
from scipy.linalg import eigh_tridiagonal


def eigensystem(h, radius, step, vectors=False):
    intervals = round(2*radius/step)
    step = 2*radius/intervals
    x = np.linspace(-radius, radius, intervals+1)[1:-1]
    kinetic = h*h/(step*step)
    diag = 2*kinetic+(x*x-1)**2
    edge = np.full(len(x)-1, -kinetic)
    return eigh_tridiagonal(diag, edge, eigvals_only=not vectors,
                            select='i', select_range=(0, 1), tol=2e-13)


def splitting(h, radius, step):
    energies = eigensystem(h, radius, step)
    return energies[1]-energies[0]


def midpoint_flux(step):
    """Apply the continuous Green identity to interpolated grid wavefunctions."""
    h, radius = .1, 3
    energies, states = eigensystem(h, radius, step, vectors=True)
    midpoint = (len(states)-1)//2
    first, second = states.T
    assert first @ first[::-1] > .9999 and second @ second[::-1] < -.9999
    even = (first + first[::-1])/2
    odd = (second - second[::-1])/2
    slope = (8*(odd[midpoint+1]-odd[midpoint-1])
             - (odd[midpoint+2]-odd[midpoint-2]))/(12*step)
    # Include the zero endpoint. Normalization and arbitrary signs cancel.
    overlap = simpson(np.r_[even[midpoint:]*odd[midpoint:], 0.], dx=step)
    return energies[1]-energies[0], h*h*even[midpoint]*slope/overlap


if __name__ == '__main__':
    print("h     R=3 dx=.004   R=3 dx=.002   R=3.5 dx=.002  leading  ratio")
    for h in (0.20, 0.15, 0.10):
        gaps = [splitting(h, r, dx) for r, dx in ((3,.004),(3,.002),(3.5,.002))]
        leading = 16*math.sqrt(2*h/math.pi)*math.exp(-4/(3*h))
        print(f"{h:.2f}", *(f"{gap:.9g}" for gap in gaps),
              f"{leading:.9g}", f"{gaps[-1]/leading:.6f}")
    errors = []
    for step in (.004, .002, .001):
        gap, flux = midpoint_flux(step)
        errors.append(abs(gap-flux))
        print(f"dx {step}: eigenvalue gap {gap:.11g}, midpoint flux/overlap {flux:.11g}")
    assert all(3.8 < a/b < 4.2 for a, b in zip(errors, errors[1:]))
