# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Quartic double well: only processing together with the corrected potential is fourth order.

Setup of the paper's Table 7: V0 = q^4/4 - q^2/2, unit mass, (q0, p0) = (0.3, 0.9),
T = 6, against a fine RK4 reference. V*_h = V0 - (h^2/24) V0'(q)^2 is the analytic
target potential of the paper's Eq. (39), standing in for a perfectly trained model.
"""

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "reference"))
from processed_dkd import dkd_step, rollout  # noqa: E402

Q0, P0, T, MASS = 0.3, 0.9, 6.0, (1.0,)


def grad_v0(q):
    return (q[0] ** 3 - q[0],)


def grad_target(h):
    # Gradient of V0 - (h^2/24) (V0')^2 = V0' (1 - (h^2/12) V0'').
    return lambda q: ((q[0] ** 3 - q[0]) * (1 - h * h * (3 * q[0] ** 2 - 1) / 12),)


def reference(n=24000):
    q, p, dt = Q0, P0, T / n
    f = lambda q, p: (p, q - q ** 3)  # noqa: E731
    for _ in range(n):
        a = f(q, p)
        b = f(q + dt / 2 * a[0], p + dt / 2 * a[1])
        c = f(q + dt / 2 * b[0], p + dt / 2 * b[1])
        d = f(q + dt * c[0], p + dt * c[1])
        q += dt / 6 * (a[0] + 2 * b[0] + 2 * c[0] + d[0])
        p += dt / 6 * (a[1] + 2 * b[1] + 2 * c[1] + d[1])
    return q, p


EXACT = reference()


def leapfrog(h, grad):
    q, p = (Q0,), (P0,)
    for _ in range(round(T / h)):
        q, p = dkd_step(q, p, h, MASS, grad)
    return math.hypot(q[0] - EXACT[0], p[0] - EXACT[1])


def processed(h, grad):
    n = round(T / h)
    _, q, p = rollout((Q0,), (P0,), h, n, MASS, grad, every=n)[-1]
    return math.hypot(q[0] - EXACT[0], p[0] - EXACT[1])


print("Global error at T = 6 (columns: scheme, potential)")
print(f"{'h':>6} {'DKD, V0':>11} {'DKD, V*':>11} {'proc, V0':>11} {'proc, V*':>11}")
previous = None
for h in (0.2, 0.1, 0.05, 0.025):
    row = (leapfrog(h, grad_v0), leapfrog(h, grad_target(h)), processed(h, grad_v0), processed(h, grad_target(h)))
    print(f"{h:>6} " + " ".join(f"{e:>11.3e}" for e in row))
    if previous:
        print(f"{'order':>6} " + " ".join(f"{math.log2(a / b):>11.2f}" for a, b in zip(previous, row)))
    previous = row
