"""Checks for the Library article "The second Painlevé equation".

P_II in the DLMF convention (Clarkson, DLMF eq. 32.2.2): w'' = 2 w^3 + z w + alpha.
Checks:
  1. (SymPy) the Flaschka-Newell pair of DLMF 32.4.6-32.4.7 is compatible exactly when w solves P_II;
  2. (SymPy) the Backlund maps of DLMF 32.7.2 send solutions with parameter alpha to alpha + 1 and alpha - 1;
  3. (SymPy) the Okamoto sigma-function of DLMF 32.6.9-32.6.13 satisfies its second-order equation on solutions;
  4. (SymPy) the Laurent series at a movable pole has residue eps = +-1, a0 = 0, a1 = -eps z0/6,
     a2 = -(alpha + eps)/4 and a free coefficient at order (z - z0)^3;
  5. (SymPy) the recurrence DLMF 32.8.6 gives polynomials Q_n of degree n(n+1)/2 that match those printed in DLMF
     32.8.7 for n = 2-4 and 6, and w = d/dz log(Q_{n-1}/Q_n) solves P_II with alpha = n for n = 1..6 (exact rational
     arithmetic at three points); the Airy
     solutions of DLMF 32.10.4-32.10.6 solve P_II with alpha = 1/2 and 3/2, and at a zero of phi the alpha = 1/2
     solution has the Laurent series -1/tau + z0 tau/6 + tau^2/8 + z0^2 tau^3/180;
  6. (SymPy) v = (3t)^(-1/3) w(x (3t)^(-1/3)) solves mKdV v_t - 6 v^2 v_x + v_xxx = 0 exactly when
     w'' - 2w^3 - zw is constant (DLMF 32.13.1-32.13.2);
  7. real solutions with alpha = 0 and w ~ k Ai(x) at +infinity: for k = -0.5, 0.2, 0.5, 0.8, 0.95 the amplitude and
     phase fitted on |x| in [80, 160] agree with the Ablowitz-Segur formulas DLMF 32.11.6-32.11.9 (relative error
     below 1e-3 in d, 5e-3 rad in theta0) and improve on each of the windows [20, 40], [40, 80], [80, 160];
  8. for |k| = 1.1 the solution reaches a pole whose residue is sign(k) to 1e-3 (DLMF 32.11.11);
  9. Fredholm determinants select solutions: q = sqrt(lam) ((I - lam K_Ai)^-1 Ai)(s) on (s, infinity), computed by
     Nystrom quadrature, agrees with the ODE solution for k = sqrt(lam): lam = 1/4, 1/2 on s in [-8, 4] and lam = 1
     on [-6, 4] to 1e-9 (for lam = 1 against a 40-digit integration); at s = -8, where the largest eigenvalue of K is
     within about 2e-8 of 1, to 1e-6; and (log F2)' = q'^2 - s q^2 - q^4 to 1e-8 for s >= -6;
  10. the k = 1 (Hastings-McLeod) solution grows like sqrt(|x|/2): ratio within 1e-3 of 1 at x = -10.
Controls: the Backlund map with the sign of w' reversed fails; Q_5 with the z^3 coefficient -313600 (as read from the
DLMF TeX source) in place of the recurrence value -3136000 gives no solution; the linear Airy amplitude |k|/sqrt(pi) misses d by
more than 10 percent at k = 0.8; changing k = 1 by 1e-6 in either direction changes the behaviour before x = -10
(a pole above; below, the solution changes sign and oscillates); double-precision integration of the k = 1 solution departs from the Fredholm values by
more than 1e-3 before x = -8.
Run with Python 3, NumPy, SciPy, SymPy and mpmath:  python3 painleve_ii_check.py   (about 20 seconds)
"""
import mpmath as mp
import numpy as np
import sympy as sp
from scipy.integrate import solve_ivp
from scipy.optimize import least_squares
from scipy.special import airy, loggamma

z, al, w0, w1, w2, lam, z0, eps = sp.symbols('z alpha w0 w1 w2 lambda z0 epsilon')
PII = 2 * w0 ** 3 + z * w0 + al


def D(expr, rhs=PII):
    """Total z-derivative on functions of (z, w, w'), using w'' = rhs."""
    return sp.diff(expr, z) + sp.diff(expr, w0) * w1 + sp.diff(expr, w1) * rhs


def symbolic_checks(checks, controls):
    s1, s2, s3 = sp.Matrix([[0, 1], [1, 0]]), sp.Matrix([[0, -sp.I], [sp.I, 0]]), sp.diag(1, -1)
    A = -sp.I * (4 * lam ** 2 + 2 * w0 ** 2 + z) * s3 - 2 * w1 * s2 + (4 * lam * w0 - al / lam) * s1
    B = -sp.I * lam * s3 + w0 * s1
    F = (A.applyfunc(lambda e: D(e, w2)) - B.diff(lam) + A * B - B * A).applyfunc(sp.expand)
    on_shell = F.subs(w2, PII).applyfunc(sp.simplify)
    ratio = sp.simplify(F[0, 1] / (w2 - PII))
    print('Lax compatibility:', 'zero on solutions' if on_shell == sp.zeros(2) else on_shell, '; off-diagonal entry =',
          ratio, 'x (w\'\' - 2w^3 - zw - alpha)')
    checks['Flaschka-Newell compatibility is equivalent to P_II (DLMF 32.4.6-32.4.7)'] = (
        on_shell == sp.zeros(2) and sp.simplify(ratio) != 0)

    def backlund(sign, flip=1):
        W = -w0 - (2 * al + sign) / (2 * w0 ** 2 + sign * flip * 2 * w1 + z)
        W1 = D(W)
        W2 = D(W1)
        return sp.simplify(sp.together(W2 - 2 * W ** 3 - z * W - (al + sign)))

    res = [backlund(+1), backlund(-1)]
    wrong = backlund(+1, flip=-1)
    print('Backlund residuals T+ and T-:', res, '; with the sign of w\' reversed:', 'nonzero' if wrong != 0 else 0)
    checks['Backlund maps T+ and T- (DLMF 32.7.2) shift alpha by +1 and -1'] = res == [0, 0]
    controls['reversing the sign of w\' in T+ fails'] = wrong != 0

    p = w1 + w0 ** 2 + z / 2
    sigma = p ** 2 / 2 - (w0 ** 2 + z / 2) * p - (al + sp.Rational(1, 2)) * w0
    s_1 = D(sigma)
    s_2 = D(s_1)
    sig_res = sp.simplify(sp.expand(s_2 ** 2 + 4 * s_1 ** 3 + 2 * s_1 * (z * s_1 - sigma) - (al + sp.Rational(1, 2)) ** 2 / 4))
    conv = sp.simplify((4 * s_2 + 2 * al + 1) / (8 * s_1) - w0), sp.simplify(-2 * s_1 - p)
    print('sigma-form residual:', sig_res, '; converse 32.6.14-32.6.15:', conv)
    checks['sigma-function equation and its inverse (DLMF 32.6.13-32.6.15)'] = sig_res == 0 and conv == (0, 0)

    tau = sp.symbols('tau')
    a = sp.symbols('a0:6')
    series = eps / tau + sum(a[j] * tau ** j for j in range(6))
    res = sp.expand(sp.diff(series, tau, 2) - 2 * series ** 3 - (z0 + tau) * series - al)
    eqs = [sp.expand(res.coeff(tau, k)) for k in range(-3, 3)]
    sol = sp.solve([e.subs(eps ** 2, 1).subs(eps ** 3, eps) for e in eqs[1:4]], [a[0], a[1], a[2]], dict=True)[0]
    order_three = sp.simplify(eqs[4].subs(sol).subs(eps ** 2, 1).subs(eps ** 3, eps).subs(eps ** 4, 1))
    lead = sp.factor(eqs[0])
    print('pole: leading', lead, '; a0, a1, a2 =', sol[a[0]], sol[a[1]], sol[a[2]],
          '; coefficient equation at the resonance:', order_three)
    checks['Laurent series: residue +-1, a1 = -eps z0/6, a2 = -(alpha+eps)/4, free a3'] = (
        sp.simplify(lead.subs(eps, 1)) == 0 and sp.simplify(lead.subs(eps, -1)) == 0 and sol[a[0]] == 0
        and sp.simplify(sol[a[1]] + eps * z0 / 6) == 0 and sp.simplify(sol[a[2]] + (al + eps) / 4) == 0
        and order_three == 0)

    zz = sp.symbols('z')
    Q = [sp.Integer(1), zz]
    for n in range(1, 7):
        num = sp.expand(zz * Q[n] ** 2 + 4 * sp.diff(Q[n], zz) ** 2 - 4 * Q[n] * sp.diff(Q[n], zz, 2))
        quo, rem = sp.div(num, Q[n - 1], zz)
        assert rem == 0
        Q.append(sp.expand(quo))
    # Q_2-Q_4 and Q_6 as printed in DLMF 32.8.7. For Q_5 the TeX source read for the article shows the z^3
    # coefficient -313600; the recurrence gives -3136000, and only the latter passes the exact checks below.
    dlmf = {2: zz ** 3 + 4, 3: zz ** 6 + 20 * zz ** 3 - 80, 4: zz ** 10 + 60 * zz ** 7 + 11200 * zz,
            6: (zz ** 21 + 280 * zz ** 18 + 18480 * zz ** 15 + 627200 * zz ** 12 - 17248000 * zz ** 9
                + 1448832000 * zz ** 6 + 19317760000 * zz ** 3 - 38635520000)}
    match = all(sp.expand(Q[n] - dlmf[n]) == 0 for n in dlmf)
    degrees = [sp.degree(Q[n], zz) for n in range(1, 7)]

    def exact_solution(Qa, Qb, n):
        w = sp.diff(Qa, zz) / Qa - sp.diff(Qb, zz) / Qb
        r = sp.diff(w, zz, 2) - 2 * w ** 3 - zz * w - n
        return all(sp.nsimplify(r.subs(zz, pt)) == 0 for pt in (sp.Rational(3, 7), sp.Rational(-5, 3), sp.Rational(11, 2)))

    ok = all(exact_solution(Q[n - 1], Q[n], n) for n in range(1, 7))
    printed5 = Q[5] - Q[5].coeff(zz, 3) * zz ** 3 - 313600 * zz ** 3
    printed_ok = exact_solution(Q[4], printed5, 5)
    print('Q_n degrees', degrees, '; Q_2-Q_4 and Q_6 equal DLMF 32.8.7:', match, '; Q_5 =', Q[5],
          '; rational solutions exact:', ok, '; with -313600 z^3 in Q_5:', printed_ok)
    checks['Q_n have degree n(n+1)/2, match DLMF 32.8.7 for n = 2-4, 6, and give rational solutions for n <= 6'] = (
        match and degrees == [n * (n + 1) // 2 for n in range(1, 7)] and ok)
    controls['Q_5 with z^3 coefficient -313600 instead of -3136000 gives no solution'] = not printed_ok

    f0, f1 = sp.symbols('phi0 phi1')
    Dphi = lambda e: sp.diff(e, z) + sp.diff(e, f0) * f1 + sp.diff(e, f1) * (-z * f0 / 2)
    w_half = -f1 / f0
    r_half = sp.simplify(Dphi(Dphi(w_half)) - 2 * w_half ** 3 - z * w_half - sp.Rational(1, 2))
    Phi = f1 / f0
    w_3half = Phi - 1 / (2 * Phi ** 2 + z)
    r_3half = sp.simplify(Dphi(Dphi(w_3half)) - 2 * w_3half ** 3 - z * w_3half - sp.Rational(3, 2))
    tau_ = sp.symbols('tau')
    c = sp.symbols('c0:8')
    phi_series = sum(c[j] * tau_ ** j for j in range(8))
    ode = sp.expand(sp.diff(phi_series, tau_, 2) + (z0 + tau_) / 2 * phi_series)
    sol_c = sp.solve([ode.coeff(tau_, j) for j in range(6)] + [c[0], c[1] - 1], c, dict=True)[0]
    phis = phi_series.subs(sol_c)
    laurent = sp.expand(sp.series(-sp.diff(phis, tau_) / phis, tau_, 0, 4).removeO())
    expected = -1 / tau_ + z0 * tau_ / 6 + tau_ ** 2 / 8 + z0 ** 2 * tau_ ** 3 / 180
    print('Airy solutions: residuals at alpha = 1/2 and 3/2:', r_half, r_3half, '; Laurent series at a zero of phi:',
          laurent)
    checks['Airy solutions at alpha = 1/2 and 3/2 (DLMF 32.10.4-32.10.6); at a zero of phi, residue -1, a2 = 1/8, '
           'h = z0^2/180'] = r_half == 0 and r_3half == 0 and sp.simplify(laurent - expected) == 0

    x, t, y = sp.symbols('x t y', positive=True)
    W = sp.sin(y) + y ** 2 / 5 + sp.exp(-y / 3)                  # an arbitrary explicit profile
    zeta = x * (3 * t) ** sp.Rational(-1, 3)
    v = (3 * t) ** sp.Rational(-1, 3) * W.subs(y, zeta)
    mkdv = sp.diff(v, t) - 6 * v ** 2 * sp.diff(v, x) + sp.diff(v, x, 3)
    target = sp.diff(sp.diff(W, y, 2) - 2 * W ** 3 - y * W, y).subs(y, zeta)
    ratios = [complex(sp.N((mkdv / target * (3 * t) ** sp.Rational(4, 3)).subs({x: xv, t: tv}), 20))
              for xv, tv in ((0.7, 0.4), (-1.3, 2.1), (2.2, 0.9))]
    print('mKdV reduction: (3t)^(4/3) (v_t - 6v^2 v_x + v_xxx) / (d/dz)(w\'\' - 2w^3 - zw) at three points:',
          ', '.join(f'{r.real:.15f}' for r in ratios))
    checks['mKdV similarity reduction gives P_II with alpha a constant of integration (DLMF 32.13.2)'] = all(
        abs(r - 1) < 1e-12 for r in ratios)


def ode_solution(k, left, right=8.0, rtol=1e-12):
    a, ap, _, _ = airy(right)
    sol = solve_ivp(lambda x, y: [y[1], 2 * y[0] ** 3 + x * y[0]], (right, left), [k * a, k * ap],
                    method='DOP853', rtol=rtol, atol=1e-16 * max(abs(k), 1e-3), dense_output=True)
    return sol


def ablowitz_segur(k):
    d2 = -np.log(1 - k * k) / np.pi
    theta0 = 1.5 * d2 * np.log(2) + loggamma(1 - 0.5j * d2).imag + 0.25 * np.pi * (1 - 2 * np.sign(k))
    return np.sqrt(d2), theta0


def fit_window(sol, k, r1, r2, n=4000):
    r = np.linspace(r1, r2, n)
    y = sol.sol(-r)[0] * r ** 0.25
    d0, th0 = ablowitz_segur(k)
    model = lambda p: p[0] * np.sin(2 / 3 * r ** 1.5 - 0.75 * p[0] ** 2 * np.log(r) - p[1]) - y
    fit = least_squares(model, [d0 * 1.02, th0 + 0.05], xtol=1e-15, ftol=1e-15)
    d, th = fit.x
    th = th0 + np.angle(np.exp(1j * (th - th0)))
    return d, th


def resolvent_q(s, lam_, m=70, length=18.0):
    """sqrt(lam) ((I - lam K_Ai)^-1 Ai)(s) on L^2(s, infinity) by Gauss-Legendre Nystrom with interpolation."""
    xg, wg = np.polynomial.legendre.leggauss(m)
    xs, ws = s + (xg + 1) * length / 2, wg * length / 2
    ai, aip, _, _ = airy(xs)

    def kernel(x, y, ax, apx, ay, apy):
        with np.errstate(divide='ignore', invalid='ignore'):
            K = (ax[:, None] * apy[None, :] - apx[:, None] * ay[None, :]) / (x[:, None] - y[None, :])
        return K

    K = kernel(xs, xs, ai, aip, ai, aip)
    K[np.diag_indices(m)] = aip ** 2 - xs * ai ** 2
    phi = np.linalg.solve(np.eye(m) - lam_ * K * ws[None, :], ai)
    a_s, ap_s, _, _ = airy(np.array([s]))
    Ks = kernel(np.array([s]), xs, a_s, ap_s, ai, aip)[0]
    return np.sqrt(lam_) * (a_s[0] + lam_ * np.sum(Ks * ws * phi))


def log_F2_derivative(s, h=1e-3):
    def F(v, m=70, length=18.0):
        x, w = np.polynomial.legendre.leggauss(m)
        x, w = v + (x + 1) * length / 2, w * length / 2
        ai, aip, _, _ = airy(x)
        with np.errstate(divide='ignore', invalid='ignore'):
            K = (ai[:, None] * aip[None, :] - aip[:, None] * ai[None, :]) / (x[:, None] - x[None, :])
        K[np.diag_indices(m)] = aip ** 2 - x * ai ** 2
        sw = np.sqrt(w)
        return np.linalg.slogdet(np.eye(m) - sw[:, None] * K * sw[None, :])[1]
    return (-F(s + 2 * h) + 8 * F(s + h) - 8 * F(s - h) + F(s - 2 * h)) / (12 * h)


def hastings_mcleod_mp(xs, k=1, x0=12, dps=40, cap=50.0):
    """(w_k, w_k') at the points xs (< x0) by a 40-digit Taylor integration in y = -x, with initial data k Ai at x0.
    Points are visited from right to left in steps of at most 0.05; if |w| exceeds cap the solution is near a pole,
    and that point and all further ones are reported as infinite instead of integrating into the pole."""
    mp.mp.dps = dps
    k = mp.mpf(k)
    f = mp.odefun(lambda y, U: [U[1], 2 * U[0] ** 3 - y * U[0]], -x0, [k * mp.airyai(x0), -k * mp.airyai(x0, derivative=1)])
    out, current, value, blown = {}, -mp.mpf(x0), mp.mpf(0), False
    for x in sorted(xs, reverse=True):
        target = -mp.mpf(x)
        while not blown and current < target:
            # near a pole of residue +-1 the distance to it is about 1/|w|; never step more than 0.3 of that
            current = min(current + min(mp.mpf('0.05'), mp.mpf('0.3') / max(abs(value), 1)), target)
            value = f(current)[0]
            if abs(value) > cap:
                blown = True
        out[x] = (float('inf'), float('inf')) if blown else (float(f(target)[0]), float(-f(target)[1]))
    return [out[x] for x in xs]


def main():
    checks, controls = {}, {}
    symbolic_checks(checks, controls)

    # 7. Ablowitz-Segur connection formulas.
    print('   k      window       d fitted   d formula   theta0 fitted  theta0 formula')
    worst_d, worst_th, improving = 0.0, 0.0, True
    for k in (-0.5, 0.2, 0.5, 0.8, 0.95):
        sol = ode_solution(k, -170.0)
        d0, th0 = ablowitz_segur(k)
        errs = []
        for r1, r2 in ((20, 40), (40, 80), (80, 160)):
            d, th = fit_window(sol, k, r1, r2)
            errs.append((abs(d / d0 - 1), abs(th - th0)))
            print(f'{k:6.2f}  [{r1:3d},{r2:3d}]  {d:10.6f}  {d0:10.6f}  {th:12.6f}  {th0:12.6f}')
        worst_d, worst_th = max(worst_d, errs[-1][0]), max(worst_th, errs[-1][1])
        improving &= errs[0][0] > errs[1][0] > errs[2][0] and errs[0][1] > errs[1][1] > errs[2][1]
    print(f'worst on [80, 160]: relative error in d {worst_d:.1e}, error in theta0 {worst_th:.1e} rad')
    checks['Ablowitz-Segur amplitude and phase on [80, 160] (d to 1e-3, theta0 to 5e-3) and improving'] = (
        worst_d < 1e-3 and worst_th < 5e-3 and improving)
    d08 = ablowitz_segur(0.8)[0]
    print(f'linear Airy amplitude at k = 0.8: {0.8 / np.sqrt(np.pi):.6f} against d = {d08:.6f}')
    controls['linear amplitude |k|/sqrt(pi) misses d by more than 10 percent at k = 0.8'] = (
        abs(0.8 / np.sqrt(np.pi) / d08 - 1) > 0.1)

    # 8. Poles for |k| > 1.
    slopes = {}
    for k in (1.1, -1.1):
        blow = lambda x, y: abs(y[0]) - 1e6
        blow.terminal = True
        a, ap, _, _ = airy(8.0)
        sol = solve_ivp(lambda x, y: [y[1], 2 * y[0] ** 3 + x * y[0]], (8.0, -20.0), [k * a, k * ap],
                        method='DOP853', rtol=1e-12, atol=1e-18, events=blow, dense_output=True)
        xe = sol.t_events[0][0]
        xs = np.linspace(xe + 1e-3, xe + 1e-5, 50)[::-1]
        vals = sol.sol(xs)[0]
        sel = (np.abs(vals) > 1e3) & (np.abs(vals) < 1e6)
        slope = np.polyfit(xs[sel], 1 / vals[sel], 1)[0]
        slopes[k] = slope
        print(f'k = {k:+.1f}: pole near x = {xe:.6f}; slope of 1/w near the pole {slope:+.6f}')
    checks['for |k| = 1.1 a pole with residue sign(k) (DLMF 32.11.11), to 1e-3'] = all(
        abs(slopes[k] - np.sign(k)) < 1e-3 for k in slopes)

    # 9-10. Fredholm selection and the Hastings-McLeod solution.
    grid = np.linspace(-8.0, 4.0, 25)
    worst = {}
    for lam_ in (0.25, 0.5):
        sol = ode_solution(np.sqrt(lam_), -9.0)
        worst[lam_] = max(abs(resolvent_q(s, lam_) - sol.sol(s)[0]) for s in grid)
    hm = hastings_mcleod_mp(list(grid))
    err1 = {s: abs(resolvent_q(s, 1.0) - q) for s, (q, _) in zip(grid, hm)}
    worst[1.0] = max(e for s, e in err1.items() if s >= -6)
    gap = {}
    for s in (-8.0, -6.0):
        x, w = np.polynomial.legendre.leggauss(70)
        x, w = s + (x + 1) * 9, w * 9
        ai, aip, _, _ = airy(x)
        with np.errstate(divide='ignore', invalid='ignore'):
            K = (ai[:, None] * aip[None, :] - aip[:, None] * ai[None, :]) / (x[:, None] - x[None, :])
        K[np.diag_indices(70)] = aip ** 2 - x * ai ** 2
        gap[s] = 1 - np.linalg.eigvalsh(np.sqrt(w)[:, None] * K * np.sqrt(w)[None, :])[-1]
    print('max |resolvent - ODE| on s in [-8, 4]:', ', '.join(f'lambda = {l}: {e:.1e}' for l, e in worst.items() if l < 1),
          f'; lambda = 1: {worst[1.0]:.1e} on [-6, 4], {err1[-8.0]:.1e} at s = -8, where 1 - (largest eigenvalue of K) is '
          f'{gap[-8.0]:.1e} (at s = -6: {gap[-6.0]:.1e})')
    checks['resolvent q matches the ODE solution, k = sqrt(lambda): lambda = 1/4, 1/2 on [-8, 4], lambda = 1 on [-6, 4] '
           '(1e-9), and lambda = 1 at s = -8 within 1e-6'] = max(worst.values()) < 1e-9 and err1[-8.0] < 1e-6
    u_err = {}
    for s, (q, qp) in zip(grid[::4], hm[::4]):
        u_err[s] = abs(log_F2_derivative(s) - (qp ** 2 - s * q ** 2 - q ** 4))
    print('(log F2)\' against q\'^2 - s q^2 - q^4:', ', '.join(f's = {s:g}: {e:.1e}' for s, e in u_err.items()))
    checks['(log F2)\' = q\'^2 - s q^2 - q^4 with the Hastings-McLeod solution (1e-8 for s >= -6)'] = max(
        e for s, e in u_err.items() if s >= -6) < 1e-8
    far = hastings_mcleod_mp([-10.0])[0][0]
    print(f'Hastings-McLeod at x = -10: {far:.10f}; sqrt(5) = {np.sqrt(5):.10f}; ratio {far / np.sqrt(5):.6f}')
    checks['Hastings-McLeod solution grows like sqrt(|x|/2): ratio at x = -10 within 1e-3 of 1'] = (
        abs(far / np.sqrt(5) - 1) < 1e-3)
    up = hastings_mcleod_mp([-6.0, -8.0, -10.0], k=1 + 1e-6)
    down = hastings_mcleod_mp([-6.0, -8.0, -10.0], k=1 - 1e-6)
    print('k = 1 + 1e-6 at x = -6, -8, -10:', ' '.join(f'{v:.4g}' for v, _ in up),
          '; k = 1 - 1e-6:', ' '.join(f'{v:.4g}' for v, _ in down))
    controls['k = 1 +- 1e-6 leaves the positive Hastings-McLeod branch before x = -10 (pole above, sign change below)'] = (
        not np.isfinite(up[-1][0])) and min(v for v, _ in down) < 0
    dp = ode_solution(1.0, -9.0)
    dev = [(s, abs(dp.sol(s)[0] - q)) for s, (q, _) in zip(grid, hm)]
    first = next((s for s, e in sorted(dev, reverse=True) if e > 1e-3), None)
    print('double-precision k = 1 integration departs from the 40-digit solution by more than 1e-3 first at x =',
          first)
    controls['double-precision integration of k = 1 departs by 1e-3 before x = -8'] = first is not None and first > -8

    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if ok else 'FAIL'}  control: {name}")
    if not all(checks.values()) or not all(controls.values()):
        raise SystemExit(1)


if __name__ == '__main__':
    main()
