# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Advance a coupled Hamiltonian with an exact reference in shifted momentum."""

from math import cos, dist, sin
from pathlib import Path
import sys

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "reference"))
from gauss_legendre_4 import step


def f(t, y):
    q, p = y
    P = p+q*q/2
    return P, -q-q*P


def J(t, y):
    q, p = y
    P = p+q*q/2
    return (q,1),(-1-P-q*q,-q)


q0, p0 = 0.7,0.3
P0 = p0+q0*q0/2
q = q0*cos(2)+P0*sin(2)
p = P0*cos(2)-q0*sin(2)-q*q/2
y = (q0,p0)
for n in range(20):
    y = step(f, J, n/10, y, 0.1)
print(f"Coupled oscillator at t=2: q={y[0]:.6f}, p={y[1]:.6f}")
print(f"Exact endpoint discrepancy below 1e-5: {dist(y, (q,p)) < 1e-5}")
