r"""
Ott, Grebogi and Yorke: controlling chaos with small kicks
==========================================================

A chaotic attractor contains infinitely many unstable periodic orbits.
Ott, Grebogi and Yorke realised that this is an opportunity: wait until
the chaotic orbit wanders close to one of them, then use tiny changes of
a parameter to hold it there. For the Henon map
:math:`x' = 1 - a x^2 + y,\ y' = b x` with :math:`a = 1.4,\ b = 0.3` the
saddle fixed point is

.. math::

    x^* = \frac{-(1 - b) + \sqrt{(1 - b)^2 + 4a}}{2a} = 0.6314,

with eigenvalues :math:`\lambda_u \approx -1.92` and
:math:`\lambda_s \approx 0.156`. Near it the kick

.. math::

    \delta a_n = -\frac{\lambda_u\,\mathbf f_u\cdot\delta z_n}{\mathbf f_u\cdot\mathbf w},
    \qquad \mathbf w = \frac{\partial F}{\partial a} = (-x^{*2}, 0),

with :math:`\mathbf f_u` the left unstable eigenvector, puts the next point
on the stable manifold, and the orbit then falls onto :math:`z^*` by a
factor :math:`\lambda_s` per step. Kicks bigger than
:math:`|\delta a| \le 0.01` are never applied.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.chaos.systems.synchronization import ogy_control

a, b, max_kick = 1.4, 0.3, 0.01

# %%
# Control switched on at iteration 200
# ------------------------------------
res = ogy_control(a, b, max_kick=max_kick, n_iter=3000, state0=(0.1, 0.0), control_from=200)
free = ogy_control(a, b, max_kick=0.0, n_iter=20000, state0=(0.1, 0.0))
xs, ys = res.fixed_point
lam_u, lam_s = res.eigenvalues
n = np.arange(res.states.shape[0])
print(f"fixed point ({xs:.4f}, {ys:.4f}), eigenvalues {lam_u:.4f}, {lam_s:.4f}")
print(f"captured at iteration {res.capture_iteration}")

fig, axes = plt.subplots(1, 3, figsize=(14, 4.2))
ax = axes[0]
ax.plot(free.states[100:, 0], free.states[100:, 1], ",", color="0.6")
ax.plot(res.states[:, 0], res.states[:, 1], ".", ms=2, color="C0", label="controlled orbit")
ax.plot(xs, ys, "r*", ms=14, label=r"$z^*$")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Henon attractor and its fixed point")
ax.legend(loc="lower left")

ax = axes[1]
ax.plot(n, res.states[:, 0], "C0-", lw=0.6)
ax.axhline(xs, color="r", ls="--", lw=0.8)
ax.axvline(200, color="0.5", ls=":", lw=0.8)
ax.set_xlabel("iteration")
ax.set_ylabel("x")
ax.set_title("chaos, then capture")

# %%
# Kicks are small, and vanish once the orbit is held
# --------------------------------------------------
cap = res.capture_iteration
assert cap is not None
dist = np.hypot(res.states[:, 0] - xs, res.states[:, 1] - ys)
ax = axes[2]
ax.semilogy(n[:-1], np.maximum(np.abs(res.kicks), 1e-18), "C1.", ms=3, label=r"$|\delta a_n|$")
ax.semilogy(n, np.maximum(dist, 1e-18), "C0-", lw=0.8, label=r"$|z_n - z^*|$")
k = np.arange(cap, cap + 15)
ax.semilogy(k, dist[cap] * np.abs(lam_s) ** (k - cap), "k:", label=r"$|\lambda_s|^n$")
ax.axhline(max_kick, color="0.5", ls="--", lw=0.8)
ax.set_xlim(cap - 50, cap + 40)
ax.set_ylim(1e-18, 1)
ax.set_xlabel("iteration")
ax.legend(fontsize=8)
plt.tight_layout()
plt.show()

decay = dist[cap + 2 : cap + 8]
ratios = decay[1:] / decay[:-1]
print(f"contraction per step after capture: {ratios.mean():.4f} (lambda_s = {lam_s:.4f})")

# %%
# Check
# -----
# The fixed point and its eigenvalues follow from the map; without control
# the orbit stays chaotic; with it, every kick respects the bound, the
# orbit contracts onto :math:`z^*` at the stable rate, and the kicks die away.
assert abs(xs - 0.6314) < 1e-4
assert abs(lam_u * lam_s + b) < 1e-12
assert np.std(free.states[-1000:, 0]) > 0.3
assert cap > 200
assert np.max(np.abs(res.kicks)) <= max_kick
assert np.allclose(ratios, abs(lam_s), rtol=0.05)
assert dist[-1] < 1e-12 and np.all(np.abs(res.kicks[-100:]) < 1e-12)
