# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Reproduce numbers stated in the paper (Jiang, Guo, Zhu & Li, 2026) with the reference code.

1. Table 7 (Appendix A.5): global errors on the quartic double well for DKD and processed
   DKD with V0 and with V*_h, every entry to three significant digits, and the slopes.
2. h^2 coefficients of the modified Hamiltonians on the unit harmonic oscillator:
   Lemma 4.1 (KDK and DKD, Eqs. (31)-(32)), Lemma 4.3 (processed DKD, Eq. (37)) and
   Remark A.4 (the five-stage splitting), extracted from the exact matrix logarithm.
3. Appendix A.5: with the step-specific potential the processed scheme keeps an h^4
   velocity term -73/5760, so it cannot be compensated to sixth order.
4. Proposition A.3(i), Eq. (66): the DKD local-error combination is -h^3/12 M^-1 V'' M^-1 p.
5. Force counts of Section 4.5, Figure 5 and Table 4, and the postprocessing share of Section 5.3,
   counted on the reference rollout.
"""

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, drift, kick, postprocessor_shears, process, rollout  # noqa: E402

failures = []


def verdict(ok, text):
    print(f"{'PASS' if ok else 'FAIL'} {text}")
    if not ok:
        failures.append(text)


def rk4(q, p, T, n, force, m=1.0):
    dt = T / n
    f = lambda q, p: (p / m, force(q))  # 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


# 1. Table 7.
TABLE7 = {  # (scheme, potential): errors at h = 0.2, 0.1, 0.05, 0.025 and printed slopes
    ("DKD", "V0"): ((3.28e-2, 8.15e-3, 2.03e-3, 5.08e-4), (2.01, 2.00, 2.00)),
    ("DKD", "V*"): ((5.50e-3, 1.43e-3, 3.62e-4, 9.07e-5), (1.94, 1.99, 2.00)),
    ("processed DKD", "V0"): ((2.91e-2, 7.17e-3, 1.79e-3, 4.46e-4), (2.02, 2.00, 2.00)),
    ("processed DKD", "V*"): ((4.69e-4, 2.83e-5, 1.75e-6, 1.09e-7), (4.05, 4.01, 4.00)),
}
exact = rk4(0.3, 0.9, 6.0, 24000, lambda q: q - q ** 3)
grad_v0 = lambda q: (q[0] ** 3 - q[0],)  # noqa: E731


def grad_star(h):
    return lambda q: ((q[0] ** 3 - q[0]) * (1 - h * h * (3 * q[0] ** 2 - 1) / 12),)


def table7_error(scheme, potential, h):
    n = round(6.0 / h)
    g = grad_v0 if potential == "V0" else grad_star(h)
    if scheme == "DKD":
        q, p = (0.3,), (0.9,)
        for _ in range(n):
            q, p = dkd_step(q, p, h, (1.0,), g)
    else:
        _, q, p = rollout((0.3,), (0.9,), h, n, (1.0,), g, every=n)[-1]
    return math.hypot(q[0] - exact[0], p[0] - exact[1])


for (scheme, potential), (printed, slopes) in TABLE7.items():
    got = [table7_error(scheme, potential, h) for h in (0.2, 0.1, 0.05, 0.025)]
    ok = all(float(f"{g:.2e}") == e for g, e in zip(got, printed))
    got_slopes = [round(math.log2(a / b), 2) for a, b in zip(got, got[1:])]
    verdict(ok and got_slopes == list(slopes), f"Table 7, {scheme} with {potential}: " + ", ".join(f"{g:.2e}" for g in got) + f"; slopes {', '.join(f'{s:.2f}' for s in got_slopes)}")


# 2.-3. Modified Hamiltonians of linear maps on the unit oscillator, V = kappa q^2/2, m = 1.
def matmul(a, b):
    return [[sum(a[i][k] * b[k][j] for k in range(2)) for j in range(2)] for i in range(2)]


def shear_matrix(kind, t, kappa):
    return [[1.0, t], [0.0, 1.0]] if kind == "D" else [[1.0, 0.0], [-t * kappa, 1.0]]


def compose(shears, kappa):
    """Matrix of applying the shears in the listed order to (q, p)."""
    m = [[1.0, 0.0], [0.0, 1.0]]
    for kind, t in shears:
        m = matmul(shear_matrix(kind, t, kappa), m)
    return m


def hamiltonian_matrix(a, h):
    """S with H~ = z^T S z / 2 for the map A = exp(h J S), via the exact 2x2 logarithm."""
    phi = math.acos((a[0][0] + a[1][1]) / 2)
    f = phi / (math.sin(phi) * h)
    g = [[f * (a[0][0] - math.cos(phi)), f * a[0][1]], [f * a[1][0], f * (a[1][1] - math.cos(phi))]]
    # g = J S with J = [[0, 1], [-1, 0]], so S = [[-g10, -g11], [g00, g01]].
    return [[-g[1][0], -g[1][1]], [g[0][0], g[0][1]]]


def h2_coefficients(build):
    """(c_P, c_S, cross) in H~ = T + V + h^2 (c_P P + c_S S) + ..., Richardson in h."""
    def raw(h):
        s = hamiltonian_matrix(build(h), h)
        return (s[1][1] - 1) / (2 * h * h), (s[0][0] - 1) / (2 * h * h), s[0][1] / (h * h)
    a, b = raw(0.02), raw(0.01)
    return [(4 * y - x) / 3 for x, y in zip(a, b)]


def processed(h, kappa=1.0):
    post = compose(postprocessor_shears(h), kappa)
    pre = compose([(k, -t) for k, t in reversed(postprocessor_shears(h))], kappa)
    return matmul(post, matmul(compose([("D", h / 2), ("K", h), ("D", h / 2)], kappa), pre))


A4B = (1 - 1 / math.sqrt(3)) / 2
EXPECTED = {
    "Lemma 4.1, KDK: c_P = 1/12, c_S = -1/24": (lambda h: compose([("K", h / 2), ("D", h), ("K", h / 2)], 1.0), (1 / 12, -1 / 24)),
    "Lemma 4.1, DKD: c_P = -1/24, c_S = 1/12": (lambda h: compose([("D", h / 2), ("K", h), ("D", h / 2)], 1.0), (-1 / 24, 1 / 12)),
    "Lemma 4.3, processed DKD: c_P = 0, c_S = 1/24": (processed, (0.0, 1 / 24)),
    "Remark A.4, five-stage splitting: c_P = 0, c_S = (2 - sqrt 3)/24": (
        lambda h: compose([("D", A4B * h), ("K", h / 2), ("D", (1 - 2 * A4B) * h), ("K", h / 2), ("D", A4B * h)], 1.0),
        (0.0, (2 - math.sqrt(3)) / 24)),
}
for label, (build, (cp, cs)) in EXPECTED.items():
    got = h2_coefficients(build)
    d = max(abs(got[0] - cp), abs(got[1] - cs), abs(got[2]))
    verdict(d < 1e-9, f"{label}: got {got[0]:+.10f}, {got[1]:+.10f} (difference {d:.1e})")

# Appendix A.5: kappa = 1 - h^2/12 - (19/1920) h^4 removes the h^2 and h^4 position terms,
# but the velocity equation keeps (1 - 73/5760 h^4) p.
def sixth(h):
    s = hamiltonian_matrix(processed(h, 1 - h * h / 12 - 19 / 1920 * h ** 4), h)
    return (s[1][1] - 1) / h ** 4, (s[0][0] - 1) / h ** 4


(v1, q1), (v2, q2) = sixth(0.1), sixth(0.05)
velocity, position = (4 * v2 - v1) / 3, (4 * q2 - q1) / 3
verdict(abs(velocity + 73 / 5760) < 1e-7 and abs(position) < 1e-7,
        f"Appendix A.5: h^4 velocity coefficient {velocity:+.9f} (paper -73/5760 = {-73 / 5760:+.9f}); h^4 position coefficient {position:+.1e}")

# 4. Proposition A.3(i) on the double well with mass 1.7: combination / (h^3 V''(q0) p0 / m^2) -> -1/12.
m, q0, p0 = 1.7, 0.3, 0.9


def ratio(h):
    q1, p1 = dkd_step((q0,), (p0,), h, (m,), grad_v0)
    qe, pe = rk4(q0, p0, h, 400, lambda q: q - q ** 3, m)
    return ((q1[0] - qe) - h / 2 * (p1[0] - pe) / m) / (h ** 3 * (3 * q0 * q0 - 1) * p0 / (m * m))


r = 2 * ratio(0.01) - ratio(0.02)
verdict(abs(r + 1 / 12) < 1e-4, f"Proposition A.3(i): DKD local-error combination / (h^3 M^-1 V'' M^-1 p) = {r:+.6f} (paper -1/12)")

# 5. Force counts (Section 4.5, Figure 5 and Table 4): 200 fs runs, counted on the reference rollout.
calls = {"n": 0}


def counting(q):
    calls["n"] += 1
    return (q[0],)


def count(h_fs, out_fs):
    calls["n"] = 0
    rollout((0.1,), (0.0,), h_fs, round(200 / h_fs), (1.0,), counting, every=round(out_fs / h_fs))
    return calls["n"]


for h_fs, out_fs, paper in ((2, 2, "504"), (2, 20, "144"), (0.5, 10, "484"), (1, 10, "284"), (2, 10, "184"), (2, 200, "N + 8 = 108")):
    n = count(h_fs, out_fs)
    verdict(n == int(paper.split()[-1]), f"h = {h_fs} fs, output every {out_fs} fs over 200 fs: {n} force evaluations (paper {paper})")
post_share = count(2, 2) - round(200 / 2) - 4
verdict(post_share == 400, f"at 2 fs with output every 2 fs, {post_share} of 504 evaluations are postprocessing (paper 400, Section 5.3)")

sys.exit(1 if failures else 0)
