"""Check frame and position closure by integrating the normalized loop and its derivative."""
import math
import numpy as np
from scipy.integrate import solve_ivp


def skew(v):
    a, b, c = v
    return np.array([[0, -c, b], [c, 0, -a], [-b, a, 0]])


def closing_test(lam, tol):
    x = -1.0  # X=x+y in the article; both asymptotic tangents are regular here.
    phi = 4 * math.atan(math.exp(x))
    phi_x = 2 / math.cosh(x)
    c, s = math.cos(phi), math.sin(phi)
    connection = skew([(lam+c/lam)/2, s/(2*lam), -phi_x/2])
    derivative = skew([(lam-c/lam)/2, -s/(2*lam), 0])
    def rhs(y, state):
        frame, df = state.reshape((2, 3, 3))
        return np.stack((frame @ connection, df @ connection + frame @ derivative)).ravel()
    init = np.stack((np.eye(3), np.zeros((3, 3)))).ravel()
    sol = solve_ivp(rhs, (0, 2*math.pi), init, method="DOP853", rtol=tol, atol=tol/100)
    if not sol.success:
        raise RuntimeError(sol.message)
    frame, df = sol.y[:, -1].reshape((2, 3, 3))
    logarithmic = df @ frame.T
    displacement = np.linalg.norm([logarithmic[2,1], logarithmic[0,2], logarithmic[1,0]])
    expected = 2*math.pi*abs(math.sinh(math.log(lam)))
    frame_error = np.linalg.norm(frame-np.eye(3), ord="fro")
    assert frame_error < 100*tol and abs(displacement-expected) < 300*tol
    return frame_error, displacement


if __name__ == "__main__":
    for lam in (1, 2+math.sqrt(3)):
        for tol in (1e-9, 1e-12):
            err, distance = closing_test(lam, tol)
            print(f"lambda={lam:.8f} rtol={tol:g} frame error={err:.3g} displacement={distance:.12g}")
