"""
Sparse identification of the Lorenz system
==========================================

SINDy (Brunton, Proctor and Kutz, 2016) regresses the time derivatives of the
states on a library of candidate terms and keeps few of them by thresholded least
squares. On the chaotic Lorenz system it recovers the three equations
:math:`\\dot x=\\sigma(y-x)`, :math:`\\dot y=x(\\rho-z)-y`, :math:`\\dot z=xy-\\beta z`
from a single trajectory. The identified model is then simulated from the same
initial state: the trajectories agree for a while and diverge later, as two runs
of any chaotic system do, but stay on the same attractor.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.datasets import lorenz

t, Z = lorenz(T=10, dt=0.002)

# %%
# Identification
# --------------
sindy = eq.SINDy(degree=2, threshold=0.05, feature_names=["x", "y", "z"]).fit(Z, t)
print(sindy.model_)
Zs = sindy.simulate(Z[0], t)
fig = plt.figure(figsize=(11, 3.6))
ax0 = fig.add_subplot(1, 3, 1)
terms = [str(tt) for tt in sindy.terms_]
im = ax0.imshow(np.abs(sindy.coef_), cmap="Blues", aspect="auto")
ax0.set_yticks(range(3))
ax0.set_yticklabels(["dx/dt", "dy/dt", "dz/dt"])
ax0.set_xticks(range(len(terms)))
ax0.set_xticklabels(terms, rotation=70, fontsize=7)
for i in range(3):
    for j in range(len(terms)):
        if sindy.coef_[i, j]:
            ax0.text(j, i, f"{sindy.coef_[i, j]:.2f}", ha="center", va="center", fontsize=6, color="white" if abs(sindy.coef_[i, j]) > 10 else "black")
ax1 = fig.add_subplot(1, 3, 2)
eq.viz.plot_phase_portrait(Z, Zs, ax=ax1, dims=(0, 2), names=["x", "y", "z"])
ax2 = fig.add_subplot(1, 3, 3)
ax2.plot(t, Z[:, 0], color="#6B7785", lw=1, label="data")
ax2.plot(t, Zs[:, 0], color="#D55E00", lw=1, ls="--", label="model")
ax2.set_xlabel("time")
ax2.set_ylabel("x")
ax2.legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# Parameter study: measurement noise and the derivative estimate
# --------------------------------------------------------------
noises = [0.0, 0.002, 0.01, 0.03]
fig, ax = plt.subplots(figsize=(4.8, 3.2))
for k, method in enumerate(("finite_difference", "savgol")):
    errs = []
    for nz in noises:
        tn, Zn = lorenz(T=10, dt=0.002, noise=nz, random_state=1)
        s = eq.SINDy(threshold=0.05, derivative_method=method, window=41).fit(Zn, tn)
        errs.append(abs(s.coef_[0, [str(x) for x in s.terms_].index("z0")] + 10) / 10)
    print(method, "noise", noises, "relative error of the -10 x coefficient", np.round(errs, 4).tolist())
    ax.plot(noises, errs, "o-", color=eq.viz.OKABE_ITO[k], label=method)
ax.set_yscale("log")
ax.set_xlabel("noise (relative to the signal std)")
ax.set_ylabel("relative error of $\\sigma$")
ax.legend(frameon=False, fontsize=8)
plt.show()
