"""Two independent contours for the Weber action and its first WKB correction."""
import numpy as np
from scipy.integrate import quad


def contours(a, count):
    # One CCW loop on the exterior sheet p ~ -iz, without principal-root resets.
    R = 1.7*a
    z = R*np.exp(2j*np.pi*np.arange(count)/count)
    p = -1j*z*np.sqrt(1 - (a/z)**2)
    s1 = -(2*a*a + 3*z*z)/(8*p**5)
    dz = 2j*np.pi*z/count
    return np.sum(p*dz), np.sum(s1*dz)


if __name__ == "__main__":
    for a in (.8, 1.3):
        segment = -2*quad(lambda x: np.sqrt(a*a-x*x), -a, a,
                          epsabs=2e-13, epsrel=2e-13)[0]
        for n in (32, 64, 128):
            closed, correction = contours(a, n)
            print("a, circle nodes, leading error, closed correction:",
                  a, n, abs(closed-segment), abs(correction))
        assert abs(closed-segment) < 2e-12 and abs(correction) < 2e-12
        # Follow z=iy downward with p=sqrt(a²+y²). Report the imaginary part.
        def open_integrand(y):
            return (2*a*a - 3*y*y) / (8*(a*a+y*y)**2.5)

        coefficient = quad(open_integrand, -np.inf, np.inf, epsabs=1e-13)[0]
        print("Imaginary part of first open correction:", coefficient)
        assert abs(coefficient - 1/(12*a*a)) < 2e-13
