"""Checks for the Library article "Integrable maps of the plane".

Lyness map F(x, y) = (y, (a + y)/x) on the positive quadrant, with invariant I = (1 + x)(1 + y)(x + y + a)/(xy) and
preserved two-form dx dy/(xy). On a level curve P_I = (1 + x)(1 + y)(x + y + a) - I x y = 0 the holomorphic
differential is omega = dx/P_y = -dy/P_x.
Checks:
  1. (SymPy) I(F(x, y)) = I(x, y); F preserves dx dy/(xy); F is the product of the horizontal switch
     (x, y) -> ((a + y)/x, y) and the reflection (x, y) -> (y, x), both involutions preserving I;
  2. along 10^5 iterates of the a = 2 orbit through (1, 1), I stays constant to 1e-12 (relative);
  3. translation: for a = 2 and four levels I, the Abel-Jacobi increment int_p^{F(p)} omega is the same at twenty
     points p of an orbit (spread below 1e-10 of the period);
  4. the rotation number rho = increment/period agrees with the mean angular advance over 10^5 iterates to 1e-4;
  5. for a = 1 every level gives rho = 1/5 to 1e-12 (the Lyness five-cycle);
  6. for a = 2, rho(I) decreases strictly on a grid of 40 levels I in (13.5, 400], starts at the linearized value
     arccos(1/4)/(2 pi) = 0.209785 as the oval shrinks onto the fixed point (2, 2), and stays above 1/5;
  7. Lyapunov exponents of Lyness orbits after 10^5 steps are below 1e-3 and fall as the orbit lengthens.
Controls: the perturbation x_{n+1} x_{n-1} = (a + x_n) exp(eps sin log x_n), which still preserves dx dy/(xy), lets I
drift by more than 1 percent at eps = 0.1 while its orbits still look regular (Lyapunov estimates below 1e-3), and at
eps = 1.5 has an outer orbit with Lyapunov exponent above 0.05.
Run with Python 3, NumPy and SymPy:  python3 integrable_planar_maps_check.py   (about 30 seconds)
"""
import numpy as np
import sympy as sp

P = np.polynomial.polynomial


def lyness(x, y, a):
    return y, (a + y) / x


def invariant(x, y, a):
    return (1 + x) * (1 + y) * (x + y + a) / (x * y)


def fixed_point(a):
    return (1 + np.sqrt(1 + 4 * a)) / 2


def symbolic_checks(checks):
    x, y, a = sp.symbols('x y a', positive=True)
    I = (1 + x) * (1 + y) * (x + y + a) / (x * y)
    X, Y = y, (a + y) / x
    same = sp.simplify(I.subs({x: X, y: Y}, simultaneous=True) - I) == 0
    jac = sp.Matrix([X, Y]).jacobian([x, y]).det()
    form = sp.simplify(jac / (X * Y) - 1 / (x * y)) == 0
    switch = ((a + y) / x, y)
    inv1 = sp.simplify(((a + switch[1]) / switch[0]) - x) == 0
    keep1 = sp.simplify(I.subs({x: switch[0]}, simultaneous=True) - I) == 0
    keep2 = sp.simplify(I.subs({x: y, y: x}, simultaneous=True) - I) == 0
    composite = (switch[1], switch[0])
    product = sp.simplify(composite[0] - X) == 0 and sp.simplify(composite[1] - Y) == 0
    print('symbolic: invariant', same, '; two-form', form, '; switch is an involution', inv1,
          '; switch and reflection keep I', keep1, keep2, '; F = reflection o switch', product)
    checks['Lyness invariant, preserved two-form and QRT factorization into two I-preserving involutions'] = all(
        [same, form, inv1, keep1, keep2, product])


class Oval:
    """The real oval of the level I around the positive fixed point, in polar coordinates about that point."""

    def __init__(self, I, a):
        self.I, self.a = I, a
        s = fixed_point(a)
        self.c = np.array([s, s])

    def radius(self, theta):
        ct, st = np.cos(theta), np.sin(theta)
        px, py = np.array([self.c[0], ct]), np.array([self.c[1], st])
        poly = P.polysub(P.polymul(P.polymul(P.polyadd([1.0], px), P.polyadd([1.0], py)),
                                   P.polyadd(P.polyadd(px, py), [self.a])),
                         self.I * P.polymul(px, py))
        roots = P.polyroots(poly)
        real = roots[np.abs(roots.imag) < 1e-9].real
        return real[real > 0].min()

    def grad(self, x, y):
        I, a = self.I, self.a
        return (1 + y) * (2 * x + y + a + 1) - I * y, (1 + x) * (x + 2 * y + a + 1) - I * x

    def omega(self, theta):
        """omega / d theta along the oval."""
        r = self.radius(theta)
        e, ep = np.array([np.cos(theta), np.sin(theta)]), np.array([-np.sin(theta), np.cos(theta)])
        x, y = self.c + r * e
        Px, Py = self.grad(x, y)
        rp = -r * (Px * ep[0] + Py * ep[1]) / (Px * e[0] + Py * e[1])
        dx, dy = rp * e[0] - r * np.sin(theta), rp * e[1] + r * np.cos(theta)
        return dx / Py if abs(Py) > abs(Px) else -dy / Px

    def period(self, m=2048):
        th = np.linspace(0, 2 * np.pi, m, endpoint=False)
        return 2 * np.pi / m * sum(self.omega(t) for t in th)

    def increment(self, t0, t1, m=120):
        g, w = np.polynomial.legendre.leggauss(m)
        th = (t0 + t1) / 2 + (t1 - t0) / 2 * g
        return (t1 - t0) / 2 * sum(wi * self.omega(t) for wi, t in zip(w, th))


def point_on_level(I, a):
    """A point (x, x) of the oval on the diagonal above the fixed point."""
    s = fixed_point(a)
    lo, hi = s, s + 1.0
    while invariant(hi, hi, a) < I:
        hi *= 2
    for _ in range(200):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if invariant(mid, mid, a) < I else (lo, mid)
    return (lo + hi) / 2, (lo + hi) / 2


def rotation(I, a, points=20, angle_steps=100000):
    """Abel-Jacobi rotation number (clockwise, the direction of motion), its spread over orbit points, and the mean
    angular advance over angle_steps iterates."""
    oval = Oval(I, a)
    T = oval.period()
    x, y = point_on_level(I, a)
    incs = []
    for _ in range(points):
        X, Y = lyness(x, y, a)
        t0 = np.arctan2(y - oval.c[1], x - oval.c[0])
        t1 = np.arctan2(Y - oval.c[1], X - oval.c[0])
        dt = (t0 - t1) % (2 * np.pi)                    # clockwise advance
        incs.append(-oval.increment(t0, t0 - dt) / T)
        x, y = X, Y
    incs = np.array(incs)
    x, y = point_on_level(I, a)
    total = 0.0
    for _ in range(angle_steps):
        X, Y = lyness(x, y, a)
        t0 = np.arctan2(y - oval.c[1], x - oval.c[0])
        t1 = np.arctan2(Y - oval.c[1], X - oval.c[0])
        total += (t0 - t1) % (2 * np.pi)
        x, y = X, Y
    return incs.mean(), incs.max() - incs.min(), total / (2 * np.pi * angle_steps)


def lyapunov(step, jac, x, y, n):
    v = np.array([1.0, 0.0])
    acc = 0.0
    for _ in range(n):
        v = jac(x, y) @ v
        nv = np.linalg.norm(v)
        acc += np.log(nv)
        v /= nv
        x, y = step(x, y)
    return acc / n


def main():
    checks, controls = {}, {}
    symbolic_checks(checks)

    a = 2.0
    x, y = 1.0, 1.0
    I0 = invariant(x, y, a)
    drift = 0.0
    for _ in range(100000):
        x, y = lyness(x, y, a)
        drift = max(drift, abs(invariant(x, y, a) / I0 - 1))
    print(f'a = 2 orbit through (1, 1): I = {I0}, largest relative drift over 1e5 steps {drift:.1e}')
    checks['invariant conserved along 1e5 iterates (1e-12 relative)'] = drift < 1e-12

    spreads, agree = [], []
    print('   I      rho (Abel-Jacobi)   spread    rho (angles, 1e5 steps)')
    for I in (14.0, 16.0, 25.0, 60.0):
        rho, spread, rho_angle = rotation(I, a)
        spreads.append(spread)
        agree.append(abs(rho - rho_angle))
        print(f'{I:6.1f}   {rho:.12f}   {spread:.1e}   {rho_angle:.6f}')
    checks['Abel-Jacobi increment is the same at twenty orbit points (spread < 1e-10)'] = max(spreads) < 1e-10
    checks['Abel-Jacobi rotation number equals the mean angular advance (1e-4)'] = max(agree) < 1e-4

    five = [rotation(I, 1.0, points=5, angle_steps=10)[0] for I in (12.0, 20.0, 50.0)]
    print('a = 1 rotation numbers:', ' '.join(f'{r:.14f}' for r in five))
    checks['a = 1: rotation number 1/5 on every level (1e-12)'] = max(abs(r - 0.2) for r in five) < 1e-12

    levels = np.geomspace(13.5 + 1e-3, 400.0, 40)
    rhos = np.array([rotation(I, a, points=3, angle_steps=10)[0] for I in levels])
    lin = np.arccos(1 / (2 * fixed_point(a))) / (2 * np.pi)
    print(f'rho(I) for a = 2: {rhos[0]:.6f} at I = {levels[0]:.4f} (linearized {lin:.6f}), {rhos[-1]:.6f} at I = 400')
    checks['rho decreases strictly in I, starts at the linearized value and stays above 1/5'] = (
        np.all(np.diff(rhos) < 0) and abs(rhos[0] - lin) < 1e-3 and rhos.min() > 0.2)

    jac = lambda x, y: np.array([[0.0, 1.0], [-(a + y) / x ** 2, 1 / x]])
    lyap = {}
    for n in (10000, 100000):
        lyap[n] = lyapunov(lambda x, y: lyness(x, y, a), jac, 1.0, 1.0, n)
    print('Lyness Lyapunov estimates:', ', '.join(f'N = {n}: {v:.2e}' for n, v in lyap.items()))
    checks['Lyness Lyapunov estimate below 1e-3 at N = 1e5 and falling with N'] = (
        lyap[100000] < 1e-3 and lyap[100000] < lyap[10000])

    def perturbed(eps):
        f = lambda y: (a + y) * np.exp(eps * np.sin(np.log(y)))
        fp = lambda y: np.exp(eps * np.sin(np.log(y))) * (1 + (a + y) * eps * np.cos(np.log(y)) / y)
        return (lambda x, y: (y, f(y) / x)), (lambda x, y: np.array([[0.0, 1.0], [-f(y) / x ** 2, fp(y) / x]]))

    step, pjac = perturbed(0.1)
    drifts, weak = [], []
    for start in (0.6, 0.3, 0.15):
        x, y = start, start
        I0 = invariant(x, y, a)
        worst = 0.0
        for _ in range(20000):
            x, y = step(x, y)
            worst = max(worst, abs(invariant(x, y, a) / I0 - 1))
        drifts.append(worst)
        weak.append(lyapunov(step, pjac, start, start, 100000))
    step, pjac = perturbed(1.5)
    strong = [lyapunov(step, pjac, start, start, 100000) for start in (0.6, 0.15, 0.04)]
    print('perturbation eps = 0.1: largest relative drift of I', ' '.join(f'{d:.2f}' for d in drifts),
          '; Lyapunov', ' '.join(f'{e:.1e}' for e in weak), '| eps = 1.5: Lyapunov', ' '.join(f'{e:.3f}' for e in strong))
    controls['eps = 0.1: I drifts by more than 1 percent although the orbits look regular (Lyapunov < 1e-3)'] = (
        max(drifts) > 1e-2 and max(weak) < 1e-3)
    controls['eps = 1.5: an outer orbit is chaotic (Lyapunov > 0.05)'] = max(strong) > 0.05

    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if ok else 'FAIL'}  control: {name}")
    if not all(checks.values()) or not all(controls.values()):
        raise SystemExit(1)


if __name__ == '__main__':
    main()
