# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Documented failure: a velocity-dependent force breaks the method.

Damped oscillator q'' = -q - g q'. Plugging F(q, p) into velocity Verlet with the
momentum available at each kick is a common mistake. It is no longer symplectic
and the global error drops to first order, the failure signature documented in
SKILL.md. The correct choice for such a problem is a general ODE solver
(for example Dormand-Prince RK45) or a splitting designed for the dissipation.
"""

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "reference"))

G = 0.5
T = 10.0


def naive_verlet(n):
    h = T / n
    q, p = 1.0, 0.0
    for _ in range(n):
        p_half = p + 0.5 * h * (-q - G * p)
        q = q + h * p_half
        p = p_half + 0.5 * h * (-q - G * p_half)
    return q, p


def exact(t):
    w = math.sqrt(1 - G * G / 4)
    decay = math.exp(-G * t / 2)
    q = decay * (math.cos(w * t) + G / (2 * w) * math.sin(w * t))
    p = -decay * (1 + G * G / (4 * w * w)) * w * math.sin(w * t)
    return q, p


qe, pe = exact(T)
errs = []
for n in (200, 400, 800, 1600):
    q, p = naive_verlet(n)
    errs.append(max(abs(q - qe), abs(p - pe)))
orders = [math.log2(a / b) for a, b in zip(errs, errs[1:])]
ok = all(0.85 < o < 1.15 for o in orders)
print(f"{'PASS' if ok else 'FAIL'} damped oscillator with a naive velocity-dependent kick: orders "
      + ", ".join(f"{o:.3f}" for o in orders) + " (first order, as documented)")
sys.exit(0 if ok else 1)
