"""
Nonlinear input--output identification with GP-OLS
===================================================

The benchmark system of Narendra and Parthasarathy (1990),

.. math:: y(k+1)=\\frac{y(k)}{1+y(k)^2}+u(k)^3,

is identified from 300 samples of a random input. :class:`~eqdisco.NARXRegressor`
builds the lagged regressors :math:`y(k-1), u(k-1)` and passes them to GP-OLS,
the method proposed for exactly this task (Madár, Abonyi and Szeifert, 2005). The
model is validated on fresh data both by one-step-ahead prediction and by
free-run simulation, in which its own outputs are fed back -- the stricter test.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.datasets import narendra_parthasarathy

u, y = narendra_parthasarathy(600, random_state=0)
u_tr, y_tr, u_te, y_te = u[:300], y[:300], u[300:], y[300:]

# %%
# Identification
# --------------
narx = eq.NARXRegressor(eq.GPOLSRegressor(population_size=250, generations=30, functions=("add", "mul", "div"), max_genes=5, random_state=0), na=1, nb=1, nk=1)
narx.fit(u_tr, y_tr)
print("y(k) =", narx.equation_)
print(f"one-step R2 {narx.score(u_te, y_te, 'prediction'):.4f}, free-run R2 {narx.score(u_te, y_te, 'simulation'):.4f}")
fig, axs = plt.subplots(2, 1, figsize=(9, 4.6), sharex=True)
k = np.arange(len(y_te))
eq.viz.plot_simulation(k, y_te, narx.predict(u_te, y_te), ax=axs[0], labels=("measured", "one-step prediction"))
eq.viz.plot_simulation(k, y_te, narx.simulate(u_te, y_te), ax=axs[1], labels=("measured", "free-run simulation"))
axs[1].set_xlabel("sample k")
for a in axs:
    a.set_xlim(0, 120)
fig.tight_layout()

# %%
# Parameter study: the length of the identification data
# ------------------------------------------------------
lengths = [50, 100, 200, 300]
sim = []
for n in lengths:
    m = eq.NARXRegressor(eq.GPOLSRegressor(population_size=200, generations=25, functions=("add", "mul", "div"), random_state=0), na=1, nb=1).fit(u[:n], y[:n])
    sim.append(m.score(u_te, y_te, "simulation"))
print("training length", lengths, "free-run R2", np.round(sim, 4).tolist())
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(lengths, sim, "o-", color="#285780")
ax.set_xlabel("identification samples")
ax.set_ylabel("free-run $R^2$ on test data")
plt.show()
