# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Second-order convergence at a fixed horizon, for both KDK and DKD, on two problems."""

import math
import sys
from pathlib import Path

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

failures = []


def check(label, errors, lo=1.9, hi=2.1):
    orders = [math.log2(a / b) for a, b in zip(errors, errors[1:])]
    ok = all(lo < o < hi for o in orders)
    print(f"{'PASS' if ok else 'FAIL'} {label}: orders " + ", ".join(f"{o:.3f}" for o in orders) + f" (expected in ({lo}, {hi}))")
    if not ok:
        failures.append(label)


# Harmonic oscillator, exact solution (cos t, -sin t), horizon t = 10.
for scheme in ("kdk", "dkd"):
    errs = []
    for n in (100, 200, 400, 800, 1600):
        _, q, p = integrate((1.0,), (0.0,), 10.0 / n, n, (1.0,), lambda q: (-q[0],), scheme=scheme)[-1]
        errs.append(max(abs(q[0] - math.cos(10.0)), abs(p[0] + math.sin(10.0))))
    check(f"harmonic oscillator, {scheme.upper()}", errs)

# Kepler orbit with eccentricity 0.5 (semi-major axis 1, period 2*pi):
# after exactly one period the exact solution returns to its start.
E = 0.5
Q0, P0 = (1.0 - E, 0.0), (0.0, math.sqrt((1.0 + E) / (1.0 - E)))


def kepler_force(q):
    r3 = (q[0] * q[0] + q[1] * q[1]) ** 1.5
    return (-q[0] / r3, -q[1] / r3)


for scheme in ("kdk", "dkd"):
    errs = []
    for n in (400, 800, 1600, 3200):
        _, q, p = integrate(Q0, P0, 2 * math.pi / n, n, (1.0, 1.0), kepler_force, scheme=scheme)[-1]
        errs.append(max(abs(a - b) for a, b in zip(q + p, Q0 + P0)))
    check(f"Kepler one period, {scheme.upper()}", errs)

# Non-unit masses: a 2-coordinate oscillator with m = (2, 0.5), k = (2, 8), so omega = (1, 4).
mass, k = (2.0, 0.5), (2.0, 8.0)
omega = [math.sqrt(ki / mi) for ki, mi in zip(k, mass)]
errs = []
for n in (200, 400, 800, 1600):
    _, q, p = integrate((1.0, 1.0), (0.0, 0.0), 5.0 / n, n, mass, lambda q: (-k[0] * q[0], -k[1] * q[1]))[-1]
    exact_q = [math.cos(w * 5.0) for w in omega]
    exact_p = [-m * w * math.sin(w * 5.0) for m, w in zip(mass, omega)]
    errs.append(max(abs(a - b) for a, b in zip(q + p, exact_q + exact_p)))
check("oscillator with masses (2, 0.5)", errs)

sys.exit(1 if failures else 0)
