r"""
Pecora and Carroll: synchronizing two chaotic Lorenz systems
============================================================

Two chaotic systems started apart diverge exponentially, so it seems they
could never run in step. Pecora and Carroll showed that they can if one
drives the other. The transmitter is a Lorenz system; the receiver is a
copy of the Lorenz equations for :math:`(y', z')` with the transmitted
:math:`x(t)` in place of its own :math:`x`,

.. math::

    \dot y' = x(\rho - z') - y', \qquad \dot z' = x y' - \beta z'.

The receiver locks onto the transmitter, :math:`(y', z') \to (y, z)`, from
any initial state when both of its *conditional* Lyapunov exponents
(its exponents along the driven trajectory) are negative. For
:math:`\sigma = 10,\ \rho = 28,\ \beta = 8/3` they are about
:math:`(-1.8, -1.9)` for the :math:`x` drive and exactly
:math:`(-\beta, -\sigma)` for the :math:`y` drive, while the :math:`z` drive
has a zero exponent and does not synchronize.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.chaos.systems.synchronization import PecoraCarrollLorenz

# %%
# The receiver locks onto the transmitter
# ---------------------------------------
# The receiver starts at :math:`(y', z') = (-10, 30)`, far from the
# transmitter's :math:`(1, 1)`.
x_drive = PecoraCarrollLorenz("x")
t, states = x_drive.trajectory(n_steps=3000)
err_x = x_drive.synchronization_error(states)

fig, axes = plt.subplots(1, 3, figsize=(14, 4.2))
ax = axes[0]
ax.plot(t, states[:, 1], "k-", lw=1, label="transmitter y")
ax.plot(t, states[:, 3], "C3--", lw=1, label="receiver y'")
ax.set_xlim(0, 8)
ax.set_xlabel("t")
ax.set_title("x drive: y' joins y")
ax.legend(loc="lower right")

# %%
# Conditional Lyapunov exponents decide which drive works
# -------------------------------------------------------
lam = {d: PecoraCarrollLorenz(d).conditional_lyapunov_exponents() for d in "xyz"}
for d, (l1, l2) in lam.items():
    print(f"{d} drive: conditional exponents {l1:+.3f}, {l2:+.3f}")

ax = axes[1]
for d, colour in zip("xyz", ["C0", "C1", "C2"]):
    system = PecoraCarrollLorenz(d)
    _, s = system.trajectory(n_steps=3000)
    e = system.synchronization_error(s)
    ax.semilogy(t, np.maximum(e, 1e-16), color=colour, label=rf"{d} drive, $\lambda_1 = {lam[d][0]:+.2f}$")
window = (t > 2) & (t < 12)
slope = np.polyfit(t[window], np.log(err_x[window]), 1)[0]
ax.semilogy(t, 30 * np.exp(lam["x"][0] * t), "k:", lw=1, label=r"$e^{\lambda_1 t}$, x drive")
ax.set_ylim(1e-16, 1e3)
ax.set_xlabel("t")
ax.set_ylabel("synchronization error")
ax.legend(fontsize=8)
print(f"x-drive error decays at rate {slope:.3f}")

# %%
# Synchronized and unsynchronized receivers
# -----------------------------------------
# Plotting the receiver against the transmitter, a synchronized receiver
# collapses onto the diagonal; the :math:`z`-driven one wanders off it.
z_drive = PecoraCarrollLorenz("z")
_, sz = z_drive.trajectory(n_steps=3000)
ax = axes[2]
ax.plot(sz[1000:, 0], sz[1000:, 3], ".", ms=1, color="C2", label="z drive: x' vs x")
ax.plot(states[1000:, 1], states[1000:, 3], ".", ms=1, color="C0", label="x drive: y' vs y")
ax.set_xlabel("transmitter")
ax.set_ylabel("receiver")
ax.set_aspect("equal")
ax.legend(markerscale=8, fontsize=8)
plt.tight_layout()
plt.show()

# %%
# Check
# -----
# The x-driven receiver synchronizes at the rate of its largest
# conditional exponent; the y drive's exponents are exactly
# :math:`-\beta` and :math:`-\sigma`; the z drive's largest is zero, and its
# receiver does not synchronize.
assert err_x[0] > 10 and err_x[-1] < 1e-8
assert np.all(lam["x"] < 0)
assert abs(slope - lam["x"][0]) < 0.3
assert np.allclose(lam["y"], [-8 / 3, -10], atol=1e-4)
assert abs(lam["z"][0]) < 0.05
assert z_drive.synchronization_error(sz)[-1] > 1
