"""
Differential equations by genetic programming
=============================================

When the right-hand side is not a sparse combination of library terms, any
symbolic regressor can be fitted to the estimated derivatives, one state at a
time (:class:`~eqdisco.SymbolicODE`). The predator--prey model of Lotka and
Volterra, :math:`\\dot x=ax-bxy`, :math:`\\dot y=dxy-cy`, is identified from a
noisy trajectory: the derivatives are estimated by a smoothing spline, the
equations by genetic programming with parameter optimization.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.datasets import lotka_volterra

t, Z = lotka_volterra(T=30, dt=0.05, noise=0.005)

# %%
# Identification
# --------------
gp = eq.SymbolicRegressor(population_size=250, generations=25, functions=("add", "sub", "mul"), optimize="lm", random_state=0)
ode = eq.SymbolicODE(gp, derivative_method="spline", feature_names=["prey", "predator"]).fit(Z, t)
print(ode.model_)
Zs = ode.simulate(Z[0], t)
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
for j, name in enumerate(["prey", "predator"]):
    axs[0].plot(t, Z[:, j], color=eq.viz.OKABE_ITO[j], lw=1, alpha=0.6, label=f"{name} (data)")
    axs[0].plot(t, Zs[:, j], color=eq.viz.OKABE_ITO[j], lw=1.5, ls="--", label=f"{name} (model)")
axs[0].set_xlabel("time")
axs[0].legend(frameon=False, fontsize=7, ncol=2)
eq.viz.plot_phase_portrait(Z, Zs, ax=axs[1], names=["prey", "predator"])
fig.tight_layout()

# %%
# Parameter study: derivative estimators under noise
# --------------------------------------------------
from eqdisco.dynamics import derivative  # noqa: E402

true = np.column_stack([1.0 * Z[:, 0] - 0.4 * Z[:, 0] * Z[:, 1], 0.1 * Z[:, 0] * Z[:, 1] - 0.4 * Z[:, 1]])
noises = [0.0, 0.005, 0.02, 0.05]
fig, ax = plt.subplots(figsize=(4.8, 3.2))
for k, m in enumerate(("finite_difference", "savgol", "spline")):
    err = []
    for nz in noises:
        tn, Zn = lotka_volterra(T=30, dt=0.05, noise=nz, random_state=2)
        _, Z0 = lotka_volterra(T=30, dt=0.05)
        tr = np.column_stack([1.0 * Z0[:, 0] - 0.4 * Z0[:, 0] * Z0[:, 1], 0.1 * Z0[:, 0] * Z0[:, 1] - 0.4 * Z0[:, 1]])
        d = derivative(Zn, tn, m, window=15)
        err.append(np.sqrt(np.mean((d - tr) ** 2)) / np.std(tr))
    print(m, "noise", noises, "relative RMS derivative error", np.round(err, 3).tolist())
    ax.plot(noises, err, "o-", color=eq.viz.OKABE_ITO[k], label=m)
ax.set_xlabel("noise level")
ax.set_ylabel("relative RMS error of the derivative")
ax.legend(frameon=False, fontsize=8)
plt.show()
