"""
Model order selection for NARX models
=====================================

Which lags matter? For every pair of orders :math:`(n_a, n_b)`,
:func:`~eqdisco.dynamics.narx_order_scan` builds a second-degree polynomial NARX
library and selects terms by forward orthogonal least squares with the Bayesian
information criterion -- the classical FROLS approach of the NARMAX literature
(Billings, 2013). The system is a second-order Hammerstein model with a quadratic
input nonlinearity and equation-error noise, so the scan should point to
:math:`n_a=2`. With measurement noise on the output instead, the equation error
becomes colored and higher orders are selected to compensate -- the parameter
study shows the effect.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.dynamics import narx_order_scan

rng = np.random.default_rng(1)
T = 500
u = rng.uniform(-1, 1, T)
v = u + 0.5 * u**2
e = 0.01 * rng.normal(size=T)
y = np.zeros(T)
for k in range(2, T):
    y[k] = 1.2 * y[k - 1] - 0.5 * y[k - 2] + 0.4 * v[k - 1] + e[k]

# %%
# The scan
# --------
scan = narx_order_scan(u, y, max_na=4, max_nb=3, degree=2)
print(scan.head(5)[["na", "nb", "n_terms", "r2", "bic", "terms"]])
M = scan.pivot(index="na", columns="nb", values="bic")
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
im = axs[0].imshow(M.to_numpy(), cmap="Blues_r", aspect="auto")
axs[0].set_xticks(range(M.shape[1]))
axs[0].set_xticklabels(M.columns)
axs[0].set_yticks(range(M.shape[0]))
axs[0].set_yticklabels(M.index)
axs[0].set_xlabel("input order $n_b$")
axs[0].set_ylabel("output order $n_a$")
fig.colorbar(im, ax=axs[0], label="BIC")
best = scan.iloc[0]
m = eq.NARXRegressor(eq.SparseRegressor(degree=2, method="frols"), na=int(best["na"]), nb=int(best["nb"])).fit(u[:300], y[:300])
eq.viz.plot_simulation(np.arange(200), y[300:], m.simulate(u[300:], y[300:]), ax=axs[1], labels=("measured", f"free run, na={int(best['na'])}, nb={int(best['nb'])}"))
fig.tight_layout()

# %%
# Parameter study: measurement noise and the selected order
# ---------------------------------------------------------
noises = [0.0, 0.05, 0.2]
fig, ax = plt.subplots(figsize=(4.5, 3))
for k, nz in enumerate(noises):
    s = narx_order_scan(u, y + nz * rng.normal(size=T), max_na=4, max_nb=3)
    best_by_na = s.groupby("na")["bic"].min()
    print(f"noise {nz}: best na by BIC = {int(best_by_na.idxmin())}")
    ax.plot(best_by_na.index, best_by_na - best_by_na.min(), "o-", color=eq.viz.OKABE_ITO[k], label=f"measurement noise {nz}")
ax.set_xlabel("output order $n_a$")
ax.set_ylabel("BIC above the best")
ax.legend(frameon=False, fontsize=8)
plt.show()
