#!/usr/bin/env python3
"""Independent finite checks for Classical Hamiltonian Systems, Chapters 6–7.

Run: python3 check_global_perturbations.py
Dependencies: Python 3.9+, NumPy, SciPy, SymPy.
No network, source-page parsing, build mutation, or random sampling.

Scope: exact algebra for the stated finite examples, numerical minimization,
generator-flow remainder convergence, Melnikov quadrature convergence, and
complex NVE monodromy convergence. This does not prove KAM, Nekhoroshev,
Williamson/Eliasson, singular reduction, or the diffusion existence theorem.
The NVE obstruction has a separate analytic proof in its article.
"""
import json
import numpy as np
import sympy as sp
from scipy.integrate import quad, solve_ivp
from scipy.optimize import brentq, minimize_scalar


def zero(expr):
    residual = sp.simplify(sp.trigsimp(expr))
    assert residual == 0, residual


def bracket(f, g, qs, ps):
    return sum(sp.diff(f, q) * sp.diff(g, p)
               - sp.diff(f, p) * sp.diff(g, q) for q, p in zip(qs, ps))


def geometry():
    q1, q2, p1, p2 = sp.symbols("q1 q2 p1 p2", real=True)
    qs, ps = (q1, q2), (p1, p2)
    u, v, w = q1*q1+q2*q2, p1*p1+p2*p2, q1*p1+q2*p2
    J = q1*p2-q2*p1
    zero(u*v-w*w-J*J)
    for f, g, answer in [(u, v, 4*w), (u, w, 2*u), (v, w, -2*v),
                         (w, J, 0)]:
        zero(bracket(f, g, qs, ps)-answer)
    for f in (u, v, w):
        zero(bracket(u*v-w*w, f, qs, ps))
    a, b, lam = sp.symbols("a b lam")
    focus_flow = sp.Matrix([bracket(c, a*w+b*J, qs, ps)
                           for c in (*qs, *ps)])
    zero(focus_flow.jacobian((*qs, *ps)).charpoly(lam).as_expr()
         - ((lam-a)**2+b*b)*((lam+a)**2+b*b))
    oscillator = (q1*q1+p1*p1)/2
    assert sp.hessian(oscillator**2, (*qs, *ps)).subs(
        {c: 0 for c in (*qs, *ps)}) == sp.zeros(4)
    zero(bracket(sp.sqrt(u), w/sp.sqrt(u), qs, ps)-1)
    Q1, Q2, P1, P2 = sp.symbols("Q1 Q2 P1 P2", real=True)
    sub = {q1: (Q1-P1)/sp.sqrt(2), q2: (Q2-P2)/sp.sqrt(2),
           p1: (Q1+P1)/sp.sqrt(2), p2: (Q2+P2)/sp.sqrt(2)}
    zero(((v-u)/2).subs(sub)-(Q1*P1+Q2*P2))
    zero(J.subs(sub)-(Q1*P2-Q2*P1))
    for a in range(2):
        for b in range(2):
            zero(bracket(qs[a].subs(sub), ps[b].subs(sub),
                         (Q1, Q2), (P1, P2))-(a == b))
    s, z, j = sp.symbols("s z j", positive=True)
    jp = (1-s*s)/sp.sqrt(s)
    hp = (1-3*s*s)/(2*s)
    potential = j*j/(2*(1-z*z))+z
    zero(sp.diff(potential, z).subs({z: -s, j: jp}))
    zero(potential.subs({z: -s, j: jp})-hp)
    zero(sp.diff(hp, s)/sp.diff(jp, s)-1/sp.sqrt(s))
    min_errors = []
    for jnum in [0.2, 0.8, 1.5, 2.0]:
        snum = brentq(lambda x: (1-x*x)/np.sqrt(x)-jnum,
                     1e-8, 1, xtol=5e-15)
        numerical = minimize_scalar(
            lambda zz: jnum*jnum/(2*(1-zz*zz))+zz,
            bounds=(-1+1e-8, 1-1e-8), method="bounded",
            options={"xatol": 1e-13})
        hnum = (1-3*snum*snum)/(2*snum)
        min_errors.append(abs(numerical.fun-hnum))
    assert max(min_errors) < 1e-12
    # A regular seam crossing, not the cone vertex.
    t = sp.symbols("t", real=True)
    zero(sp.diff(t*t, t)-2*t)
    zero(sp.diff(t, t)-1)
    # Linear shear and dual angle transformation preserve the pairing.
    M = sp.Matrix([[1, 0], [1, 1]])
    assert M.det() == 1
    assert M.inv().T.T * M == sp.eye(2)
    intersection = sp.Matrix([[0, 1], [-1, 0]])
    assert M*intersection*M.T == intersection
    c = 0.3+0.2j
    before = -np.real(c*np.log(c)-c)/(2*np.pi)
    after = -np.real(c*(np.log(c)+2j*np.pi)-c)/(2*np.pi)
    shear_error = abs(after-before-c.imag)
    assert shear_error < 1e-15
    wrong_principal_reset = abs(before-before-c.imag)
    assert wrong_principal_reset > 0.1
    # Magnetic 2-form: divergence is d beta; flux obstructs exactness.
    x, y, zz = sp.symbols("x y z", real=True)
    radius = sp.sqrt(x*x+y*y+zz*zz)
    zero(sum(sp.diff(a/radius**3, a) for a in (x, y, zz)))
    b1, b2, b3 = sp.symbols("b1 b2 b3")
    B = sp.Matrix([[0, b3, -b2], [-b3, 0, b1], [b2, -b1, 0]])
    Omega = sp.zeros(3).row_join(sp.eye(3)).col_join(
        (-sp.eye(3)).row_join(B))
    assert sp.simplify(Omega.det()) == 1
    flux = 2*np.pi*quad(np.sin, 0, np.pi, epsabs=1e-12)[0]
    assert abs(flux-4*np.pi) < 1e-12
    return {"spherical_minimum_max_error": max(min_errors),
            "logarithmic_shear_error": shear_error,
            "principal_branch_negative_control": wrong_principal_reset,
            "magnetic_unit_flux": flux,
            "exact_brackets_and_normal_form": "zero residual"}


def pullback_residuals(h, V, W, Z, R2, theta, actions):
    coords = (*theta, *actions)
    vf = [sp.diff(W, a) for a in actions]+[-sp.diff(W, q) for q in theta]
    vector = sp.lambdify(coords, vf, "numpy")
    hf, vfcn, zf, r2f = [sp.lambdify(coords, f, "numpy")
                         for f in (h, V, Z, R2)]
    x0 = np.array([0.37, -0.41, 0.8, 1.1])
    errors2, errors3 = [], []
    for eps in (0.02, 0.01, 0.005):
        sol = solve_ivp(lambda _, x: vector(*x), (0, eps), x0,
                        method="DOP853", rtol=2e-13, atol=2e-14)
        assert sol.success
        x = sol.y[:, -1]
        exact = hf(*x)+eps*vfcn(*x)
        order1 = hf(*x0)+eps*zf(*x0)
        order2 = order1+eps*eps*r2f(*x0)
        errors2.append(abs(exact-order1))
        errors3.append(abs(exact-order2))
    ratios2 = [errors2[i]/errors2[i+1] for i in range(2)]
    ratios3 = [errors3[i]/errors3[i+1] for i in range(2)]
    assert all(3.6 < r < 4.4 for r in ratios2), ratios2
    assert all(7.0 < r < 9.0 for r in ratios3), ratios3
    return {"epsilon": [0.02, 0.01, 0.005],
            "order_two_residuals": errors2, "ratios": ratios2,
            "order_three_residuals": errors3, "ratios_after_R2": ratios3}


def perturbation():
    t1, t2, I1, I2 = sp.symbols("t1 t2 I1 I2", real=True)
    theta, actions = (t1, t2), (I1, I2)
    pb = lambda f, g: bracket(f, g, theta, actions)
    A, phase, d = I1*I2, 2*t1-t2, 2-sp.sqrt(2)
    h = I1+sp.sqrt(2)*I2
    V, W = A*sp.cos(phase), A/d*sp.sin(phase)
    zero(pb(h, W)+V)
    R2 = -A*(2*I2-I1)/(2*d)
    zero(pb(V, W)/2-R2)
    wrong_sign = sp.lambdify((*theta, *actions), V+pb(h, -W), "numpy")
    negative = abs(wrong_sign(.37, -.41, .8, 1.1))
    assert negative > 0.1
    nonres = pullback_residuals(h, V, W, 0*I1, R2, theta, actions)
    h = I1+I2
    V = A*(1+sp.cos(2*t1))*(1+sp.cos(2*t2))
    Z = A*(1+sp.cos(2*(t1-t2))/2)
    W = A*(sp.sin(2*t1)/2+sp.sin(2*t2)/2+sp.sin(2*(t1+t2))/8)
    zero(pb(h, W)+V-Z)
    zero(pb(h, Z))
    Jslow, Nslow, psi = sp.symbols("J N psi", real=True)
    reduced = Jslow*(Nslow-Jslow)*(1+sp.cos(2*psi)/2)
    determinant = sp.det(sp.hessian(reduced, (psi, Jslow)))
    assert sp.simplify(determinant.subs({psi: 0, Jslow: Nslow/2})) == 3*Nslow**2/2
    assert sp.simplify(determinant.subs({psi: sp.pi/2, Jslow: Nslow/2})) == -Nslow**2/2
    R2 = (pb(V, W)+pb(Z, W))/2
    resonant = pullback_residuals(h, V, W, Z, R2, theta, actions)
    # The discarded resonant term is not small because of a nonzero divisor.
    bad_average_residual = Z-A
    assert abs(float(bad_average_residual.subs(
        {t1: 0, t2: 0, I1: 1, I2: 1}))) == .5
    eps, t, a, th = sp.symbols("eps t a th", real=True)
    Hdrift = (I1**2-I2**2)/2-eps*sp.cos(t1+t2)
    orbit = {I1: a+eps*t, I2: a+eps*t,
             t1: th+a*t+eps*t*t/2,
             t2: -sp.pi/2-th-a*t-eps*t*t/2}
    for q in (*theta, *actions):
        zero(sp.diff(orbit[q], t)-pb(q, Hdrift).subs(orbit))
    zero(Hdrift.subs(orbit))
    return {"nonresonant_flow": nonres, "resonant_flow": resonant,
            "wrong_generator_sign_residual": negative,
            "drifting_orbit": "zero residual"}


def melnikov():
    t = sp.symbols("t", real=True)
    q = 4*sp.atan(sp.exp(t))
    p = 2/sp.cosh(t)
    # Exponential simplification avoids assumptions about inverse-angle branches.
    zero((sp.diff(q, t)-p).rewrite(sp.exp))
    zero((sp.diff(p, t)-sp.expand_trig(sp.sin(q))).rewrite(sp.exp))
    zero((p*p/2+sp.expand_trig(sp.cos(q))-1).rewrite(sp.exp))
    errors, tail_errors = [], []
    for freq, phase in [(0.7, .37), (1.0, .8), (2.0, 1.2)]:
        exact = -2*np.pi*freq**2/np.sinh(np.pi*freq/2)*np.sin(phase)
        seq = []
        for T in (8., 12., 16.):
            integral = quad(
                lambda x: 4/np.cosh(x)**2*np.tanh(x)
                * np.cos(freq*x+phase), -T, T,
                epsabs=2e-12, epsrel=2e-12, limit=200)[0]
            seq.append(abs(integral-exact))
        assert seq[-1] < 1e-11
        assert seq[-1] < seq[0]*1e-5
        errors.append(seq[-1])
        tail_errors.append(seq)
    wrong_sign = 2*abs(-2*np.pi/np.sinh(np.pi/2)*np.sin(.8))
    assert wrong_sign > 1
    return {"T": [8, 12, 16], "truncation_errors": tail_errors,
            "max_final_error": max(errors),
            "wrong_sign_negative_control": wrong_sign}


def loop_matrix(g, center, steps):
    # Both loops start at t=1/2 and have positive orientation.
    offset = .5-center
    def rhs(phi, Y):
        t = center+offset*np.exp(1j*phi)
        dt = 1j*(t-center)
        A = np.array([[0, 1], [g/(t*(t-1)), 0]], dtype=complex)
        return dt*A @ Y
    Y = np.eye(2, dtype=complex)
    h = 2*np.pi/steps
    for i in range(steps):
        x = i*h
        k1 = rhs(x, Y)
        k2 = rhs(x+h/2, Y+h*k1/2)
        k3 = rhs(x+h/2, Y+h*k2/2)
        k4 = rhs(x+h, Y+h*k3)
        Y += h*(k1+2*k2+2*k3+k4)/6
    return Y


def galois():
    q1, q2, p1, p2, g, t = sp.symbols("q1 q2 p1 p2 g t")
    qs, ps = (q1, q2), (p1, p2)
    H = (p1*p1+p2*p2)/2-g*q2*q2/(2*q1*(q1-1))
    coordinates = sp.Matrix([q1, q2, p1, p2])
    flow = sp.Matrix([bracket(c, H, qs, ps) for c in coordinates])
    orbit = {q1: t, q2: 0, p1: 1, p2: 0}
    assert flow.subs(orbit) == sp.Matrix([1, 0, 0, 0])
    normal = flow.jacobian(coordinates).subs(orbit).extract([1, 3], [1, 3])
    assert normal == sp.Matrix([[0, 1], [g/(t*(t-1)), 0]])
    zero(sp.diff(t*(t-1), t, 2)-2/(t*(t-1))*t*(t-1))
    result = {}
    for coupling in (1, 2):
        matrices = [(loop_matrix(coupling, 0, n),
                     loop_matrix(coupling, 1, n))
                    for n in (512, 1024, 2048)]
        differences = [max(np.linalg.norm(matrices[i+1][j]-matrices[i][j])
                           for j in range(2)) for i in range(2)]
        assert differences[1] < differences[0]/10
        M0, M1 = matrices[-1]
        det_error = max(abs(np.linalg.det(M)-1) for M in (M0, M1))
        trace_error = max(abs(np.trace(M)-2) for M in (M0, M1))
        nil_error = max(np.linalg.norm((M-np.eye(2)) @ (M-np.eye(2)))
                        for M in (M0, M1))
        comm = np.linalg.norm(M0@M1-M1@M0)
        assert det_error < 2e-8 and trace_error < 2e-8
        assert nil_error < 2e-7
        if coupling == 1:
            assert comm > 1
        else:
            assert comm < 2e-7
            fixed_vector = np.array([-.25, 0], dtype=complex)
            assert np.linalg.norm(M0@fixed_vector-fixed_vector) < 1e-8
        result[str(coupling)] = {
            "steps": [512, 1024, 2048], "refinement_differences": differences,
            "refinement_ratio": differences[0]/differences[1],
            "determinant_error": det_error, "trace_error": trace_error,
            "nilpotence_residual": nil_error, "commutation_residual": comm}
    return result


if __name__ == "__main__":
    report = {"geometry": geometry(), "perturbation": perturbation(),
              "melnikov": melnikov(), "galois": galois()}
    print(json.dumps(report, indent=2))
    print("PASS: finite-example algebra, convergence, and negative controls.")
