"""Airy fold with nonconstant amplitude: exact transform and real quadrature."""
from math import cos, erfc, exp, pi, sqrt

from scipy.integrate import quad
from scipy.special import ai_zeros, airy


def measured(lam, z):
    # mu=1. By evenness of the real part the two half-lines contribute equally.
    a = z / lam**(2/3)
    def integrand(u):
        return exp(-u*u)*cos(lam*(u**3/3 - a*u))

    half, _ = quad(integrand, 0, 7, epsabs=2e-13, epsrel=2e-13, limit=1200)
    tail = lam**(1/3) * erfc(7) / (2*sqrt(pi))
    assert tail < 1e-20
    return lam**(1/3)*half/pi


if __name__ == "__main__":
    node = -ai_zeros(1)[0][0]
    for lam in (8., 27., 64.):
        t = lam**(-2/3)
        for z in (1., node, node + t*t):
            exact = exp(2*t**3/3 - z*t)*airy(t*t-z)[0]
            leading = exp(-z*t)*airy(-z)[0]
            direct = measured(lam, z)
            print("lambda, z, scaled integral, frozen-amplitude error, quadrature check:",
                  lam, z, direct, abs(direct-leading), abs(exact-direct))
            assert abs(direct-exact) < 1e-11
