#!/usr/bin/env python3
"""Independent checks for Volume 2, Chapter 1.

Run: python3 check_actions.py
Dependencies: numpy, scipy, sympy, mpmath.
Symbolic identities are exact. Quadratures use 50 decimal digits. The driven
oscillator uses DOP853 on the ORIGINAL q,p equations, with a tighter independent
run and an ODE residual from finite differences of the dense interpolant.
Finite-speed error is distinct from discretization error; no sampled trajectory
is used as a proof of irrationality, a torus theorem, or an adiabatic theorem.
"""
import json
import math
import numpy as np
import mpmath as mp
import sympy as sp
from scipy.integrate import solve_ivp

mp.mp.dps = 50
checks = []
metrics = {}


def require(name, condition):
    if not bool(condition):
        raise AssertionError(name)
    checks.append(name)


def zero(name, expression):
    require(name, sp.simplify(expression) == 0)


def symbolic_checks():
    I, theta, mass, nu = sp.symbols("I theta mass nu", positive=True)
    q = sp.sqrt(2*I/(mass*nu))*sp.sin(theta)
    p = sp.sqrt(2*I*mass*nu)*sp.cos(theta)
    zero("oscillator canonical area", sp.diff(q, theta)*sp.diff(p, I)
         - sp.diff(q, I)*sp.diff(p, theta)-1)
    zero("oscillator action Hamiltonian", p**2/(2*mass)+mass*nu**2*q**2/2-nu*I)
    q1, p1, q2, p2 = sp.symbols("q1 p1 q2 p2", real=True)
    energies = sp.Matrix([(q1**2+p1**2)/2, (q2**2+p2**2)/2])
    jac = energies.jacobian([q1, p1, q2, p2])
    require("positive two-oscillator rank", jac.subs({q1:0,p1:1,q2:1,p2:0}).rank()==2)
    require("collapsed first cycle loses rank", jac.subs({q1:0,p1:0,q2:1,p2:0}).rank()==1)
    H = sum(energies)
    require("dependent H,H^2 negative control",
            sp.Matrix([H,H**2]).jacobian([q1,p1,q2,p2]).rank()==1)
    A = sp.Matrix([[1,1],[0,1]])
    require("primitive cycle change determinant", A.det()==1)
    require("inverse transpose preserves area", A.T*A.inv().T==sp.eye(2))
    momentum, step, inertia = sp.symbols("p dp J", positive=True)
    energy_step = ((momentum + step)**2 - momentum**2) / (2 * inertia)
    zero("rotor strip area per energy equals one-turn time",
         sp.limit(2 * sp.pi * step / energy_step, step, 0) - 2 * sp.pi * inertia / momentum)
    # The full three-frequency flow has one, not two, independent resonances.
    zero("three-frequency resonance", sp.Matrix([[2,-1,0]]).dot(sp.Matrix([1,2,sp.sqrt(2)])))
    require("irrational remaining frequency ratio", sp.sqrt(2).is_irrational)
    t = sp.symbols("t", real=True)
    qs = 4*sp.atan(sp.exp(t))-sp.pi
    ps = 4*sp.exp(t)/(1+sp.exp(2*t))
    zero("homoclinic first equation", sp.diff(qs,t)-ps)
    zero("homoclinic second equation", sp.diff(ps,t)+sp.sin(qs))
    zero("homoclinic energy", ps**2/2+1-sp.cos(qs)-2)
    # Derive the changing-frame equations from the original Hamilton equations.
    Q, P, w, b, c, dw, db, dc = sp.symbols("Q P w b c dw db dc", real=True)
    a = (w*w+b*b)/c
    S = sp.Matrix([[sp.sqrt(w/c),0],[b/sp.sqrt(c*w),sp.sqrt(c/w)]])
    Sinv = sp.Matrix([[sp.sqrt(c/w),0],[-b/sp.sqrt(c*w),sp.sqrt(w/c)]])
    # Use positive variables to avoid irrelevant square-root branches.
    wp, cp = sp.symbols("w c", positive=True)
    S, Sinv, a = [x.subs({w:wp,c:cp}) for x in (S,Sinv,a)]
    Sdot = sp.diff(S,wp)*dw+sp.diff(S,b)*db+sp.diff(S,cp)*dc
    original = sp.Matrix([[b,cp],[-a,-b]])
    k = (dw/wp-dc/cp)/2
    ell = (db-b*dc/cp)/wp
    expected = sp.Matrix([[k,wp],[-wp+ell,-k]])
    residual = sp.simplify((Sdot+S*original)*Sinv-expected)
    require("all changing-frame matrix entries", residual==sp.zeros(2))
    qdot, pdot = expected*sp.Matrix([Q,P])
    angular = (P*qdot-Q*pdot)/(Q*Q+P*P)
    zero("exact angular equation",
         angular.subs({Q:sp.sin(theta),P:sp.cos(theta)})
         -(wp+k*sp.sin(2*theta)-ell/2+ell*sp.cos(2*theta)/2))
    zero("exact logarithmic action equation",
         (2*(Q*qdot+P*pdot)/(Q*Q+P*P)).subs({Q:sp.sin(theta),P:sp.cos(theta)})
         -(-2*k*sp.cos(2*theta)+ell*sp.sin(2*theta)))
    gamma = -db/(2*wp)+b*dc/(2*wp*cp)
    alternate = b/(2*wp)*(dc/cp-dw/wp)
    zero("Hannay connection gauge difference",
         alternate-gamma-(db/(2*wp)-b*dw/(2*wp**2)))
    frozen=sp.simplify(S*original*Sinv)
    require("omitting moving frame is wrong",
            expected.subs({dw:0,dc:1,db:0})!=frozen)


def integral_checks():
    mass, kap = mp.mpf("2.3"), mp.mpf("0.7")
    C4 = mp.beta(mp.mpf(1)/4,mp.mpf(3)/2)/mp.pi
    worst = mp.mpf(0)
    for E in map(mp.mpf,["0.4","2","10"]):
        amp = (4*E/kap)**mp.mpf(".25")
        # Area quadrature and time quadrature use different substitutions.
        area = 2*amp*mp.sqrt(2*mass*E)/mp.pi*mp.quad(lambda r:mp.sqrt(1-r**4),[0,1])
        period = 4*mp.sqrt(2*mass/kap)/amp*mp.quad(
            lambda u:1/mp.sqrt(1+mp.sin(u)**2),[0,mp.pi/2])
        exactI = C4*mp.sqrt(mass)*kap**(-mp.mpf(".25"))*E**mp.mpf(".75")
        exactT = mp.beta(mp.mpf(".25"),mp.mpf(".5"))*mp.sqrt(mass)*kap**(-mp.mpf(".25"))*E**(-mp.mpf(".25"))
        worst=max(worst,abs(area/exactI-1),abs(period/exactT-1))
        require("quartic independent quadratures E="+str(E),
                abs(area/exactI-1)<mp.mpf("1e-45") and abs(period/exactT-1)<mp.mpf("1e-45"))
        require("quartic action-period derivative E="+str(E),
                abs((mp.mpf(".75")*exactI/E)/(period/(2*mp.pi))-1)<mp.mpf("1e-45"))
    metrics["quartic_max_relative_quadrature_error_50dps"]=float(worst)
    deltas=[mp.mpf(10)**(-j) for j in [2,4,6,8]]
    errors=[]
    for delta in deltas:
        lib=4*mp.ellipk(1-delta/2)  # m parameter, not modulus.
        rot=4/mp.sqrt(4+2*delta)*mp.ellipk(2/(2+delta))
        L=mp.log(32/delta)
        errors.append([float(delta),float(abs(lib-2*L)),float(abs(rot-L))])
        require("matched-side period ratio delta="+str(delta),abs(lib/rot-2)<3*delta)
        require("logarithmic period remainder delta="+str(delta),
                abs(lib-2*L)<delta*L and abs(rot-L)<delta*L)
        # Elliptic action formulas independently check integrated asymptotics.
        mlib=1-delta/2
        Ilib=8/mp.pi*(mp.ellipe(mlib)-(1-mlib)*mp.ellipk(mlib))
        Irot=2*mp.sqrt(4+2*delta)/mp.pi*mp.ellipe(2/(2+delta))
        require("libration action singular term delta="+str(delta),
                abs(Ilib-(8/mp.pi-delta/mp.pi*(L+1)))<delta**2*L)
        require("rotation action singular term delta="+str(delta),
                abs(Irot-(4/mp.pi+delta/(2*mp.pi)*(L+1)))<delta**2*L)
    metrics["pendulum_asymptotic_absolute_errors"]=errors
    # Independent ODE event: starting at q=0, first downward zero is half a libration.
    for energy in [0.4,1.9,1.99]:
        def crossing(t,y): return y[0]
        crossing.direction=-1
        crossing.terminal=True
        sol=solve_ivp(lambda t,y:[y[1],-math.sin(y[0])],(0,100),
                      [0,math.sqrt(2*energy)],method="DOP853",rtol=2e-13,
                      atol=2e-14,events=crossing,max_step=0.05)
        require("pendulum ODE half-period event",len(sol.t_events[0])==1)
        observed=2*sol.t_events[0][0]
        target=float(4*mp.ellipk(energy/2))
        require("pendulum independent ODE period E="+str(energy),abs(observed-target)<2e-9)
        metrics["pendulum_ODE_period_error_"+str(energy)]=abs(observed-target)
    # At a fixed detuning check both the integral and an independent quadrature.
    frequency,T=mp.mpf("0.013"),mp.mpf("37")
    exact=(mp.exp(1j*frequency*T)-1)/(1j*frequency*T)
    direct=mp.quad(lambda t:mp.exp(1j*frequency*t),[0,T])/T
    require("character-average quadrature",abs(exact-direct)<mp.mpf("1e-45"))
    require("detuning averaging bound",abs(exact)<=min(1,2/(T*frequency)))
    require("resonant character survives",abs(mp.quad(lambda t:1,[0,T])/T-1)<mp.mpf("1e-45"))


def pendulum_measurements():
    interval = 2 * mp.ellipk(mp.mpf("0.5"))
    k = mp.findroot(lambda k: 2 * mp.ellipk(1 / k**2) / k - interval,
                    (mp.mpf("1.1"), mp.mpf("1.2")))
    crossings = []
    for speed, target, direction in [(math.sqrt(2), 0, -1), (float(2 * k), 2 * math.pi, 1)]:
        def gate(time, state):
            return state[0] - target

        gate.direction = direction
        gate.terminal = True
        solution = solve_ivp(lambda t, y: (y[1], -math.sin(y[0])), (0, 6), (0, speed),
                             method="DOP853", rtol=2e-13, atol=2e-14, max_step=0.05,
                             events=gate)
        require("reached bottom gate", solution.success and len(solution.t_events[0]) == 1)
        time = solution.t_events[0][0]
        velocity = solution.y_events[0][0][1]
        require("matched elapsed time", abs(time - float(interval)) < 2e-12)
        require("predicted signed return speed", abs(velocity - direction * speed) < 2e-12)
        crossings.append({"elapsed_time": time, "return_speed": velocity})
    metrics["matched_bottom_gate"] = crossings

    # Integrate the vertical extent of the sublevel set in the (q,p) strip.
    # This uses the Hamiltonian directly and includes both signs of momentum.
    def area(energy):
        limit = 2 * mp.asin(mp.sqrt(energy / 2)) if energy < 2 else mp.pi
        return 4 * mp.quad(lambda q: mp.sqrt(max(0, 2 * energy - 4 * mp.sin(q / 2)**2)),
                           [0, limit])

    require("critical sublevel area", abs(area(2) - 16) < mp.mpf("1e-45"))
    step = mp.mpf("1e-9")
    densities = {}
    for energy in [mp.mpf("1.99"), mp.mpf("2.01")]:
        expected = (4 * mp.ellipk(energy / 2) if energy < 2 else
                    8 * mp.ellipk(2 / energy) / mp.sqrt(2 * energy))
        observed = (area(energy + step) - area(energy - step)) / (2 * step)
        require("sublevel density counts every connected orbit",
                abs(observed - expected) < mp.mpf("1e-11"))
        densities[str(energy)] = float(observed)
    metrics["area_per_unit_energy"] = densities


def driven(epsilon, direction=1, max_step=0.12, tighter=False, frequency_only=False):
    B,C,theta0=0.5,0.5,0.37
    duration=2*math.pi/epsilon
    def parameters(t):
        s=direction*epsilon*t
        if frequency_only:
            w=1+0.2*math.sin(s)
            return w*w,0.0,1.0,w
        b=B*math.sin(s)
        c=math.exp(C*math.cos(s))
        return (1+b*b)/c,b,c,1.0
    a,b,c,w=parameters(0)
    Q0,P0=math.sqrt(2)*math.sin(theta0),math.sqrt(2)*math.cos(theta0)
    initial=[math.sqrt(c/w)*Q0,math.sqrt(w/c)*P0-b/math.sqrt(c*w)*Q0]
    def rhs(t,y):
        a,b,c,w=parameters(t)
        return [b*y[0]+c*y[1],-a*y[0]-b*y[1]]
    sol=solve_ivp(rhs,(0,duration),initial,method="DOP853",
                  rtol=2e-13 if tighter else 2e-11,
                  atol=2e-14 if tighter else 2e-12,max_step=max_step,dense_output=True)
    require("driven oscillator integration success",sol.success)
    a,b,c,w=parameters(duration)
    q,p=sol.y[:,-1]
    Q=math.sqrt(w/c)*q
    P=(c*p+b*q)/math.sqrt(c*w)
    # For the frequency-only loop the sine integrates to zero over the full cycle.
    dynamical=duration
    predicted=0.0 if frequency_only else -direction*math.pi*B*C/2
    wrap=lambda x:math.atan2(math.sin(x),math.cos(x))
    geometric=wrap(math.atan2(Q,P)-theta0-dynamical)
    error=abs(wrap(geometric-predicted))
    variation=0.0
    for t,q,p in zip(sol.t,sol.y[0],sol.y[1]):
        a,b,c,w=parameters(t)
        variation=max(variation,abs((a*q*q+2*b*q*p+c*p*p)/(2*w)-1))
    # A five-point derivative of the dense interpolant, separate from solve_ivp's RHS.
    resid=0.0
    h=0.002
    for t in np.linspace(0.02,duration-0.02,61):
        derivative=(-sol.sol(t+2*h)+8*sol.sol(t+h)-8*sol.sol(t-h)+sol.sol(t-2*h))/(12*h)
        resid=max(resid,float(np.linalg.norm(derivative-np.asarray(rhs(t,sol.sol(t))),np.inf)))
    return {"epsilon":epsilon,"direction":direction,"geometric_angle":geometric,
            "predicted_angle":predicted,"phase_error":error,
            "sampled_max_relative_action_variation":variation,
            "dense_ODE_residual_infinity_norm":resid,"final_state":sol.y[:,-1]}


def adiabatic_checks():
    runs=[driven(eps) for eps in [0.1,0.05,0.025,0.0125]]
    for r in runs:
        require("finite-speed phase bound "+str(r["epsilon"]),r["phase_error"]<2*r["epsilon"])
        require("sampled adiabatic action bound "+str(r["epsilon"]),
                r["sampled_max_relative_action_variation"]<2*r["epsilon"])
        require("dense original-ODE residual "+str(r["epsilon"]),
                r["dense_ODE_residual_infinity_norm"]<2e-8)
    refined=driven(0.0125,max_step=0.06,tighter=True)
    discretization=float(np.linalg.norm(refined["final_state"]-runs[-1]["final_state"],np.inf))
    require("step and tolerance refinement",discretization<2e-8)
    require("adiabatic error distinct from solver error",runs[-1]["phase_error"]>100*discretization)
    require("geometric angle not zero negative control",abs(runs[-1]["geometric_angle"])>0.3)
    reverse=driven(0.025,direction=-1)
    require("reversed loop reverses geometric sign",reverse["geometric_angle"]>0.3)
    require("wrong orientation rejected",abs(reverse["geometric_angle"]+math.pi/8)>0.7)
    simple=driven(0.025,frequency_only=True)
    require("frequency-only zero holonomy limit",simple["phase_error"]<0.03)
    metrics["hannay_loop"]=[{k:v for k,v in r.items() if k!="final_state"} for r in runs]
    metrics["hannay_final_state_refinement_infinity_norm"]=discretization
    metrics["hannay_reverse_loop"]={k:v for k,v in reverse.items() if k!="final_state"}
    metrics["frequency_only_loop"]={k:v for k,v in simple.items() if k!="final_state"}


if __name__=="__main__":
    symbolic_checks()
    integral_checks()
    pendulum_measurements()
    adiabatic_checks()
    print(json.dumps({"status":"all checks passed","checks":len(checks),"metrics":metrics},indent=2))
