"""
Orthogonal least squares and the error reduction ratio
======================================================

A linear-in-parameters model :math:`y=w_0+\\sum_i w_iF_i(\\mathbf x)` can be
assessed term by term. Orthogonal least squares (Chen, Billings and Luo, 1989)
orthogonalizes the regressors and assigns each term its *error reduction ratio*
(ERR): the share of the output variance it explains beyond the terms before it.
Forward selection by ERR (FROLS) builds a model term by term; the ERR values
also show that a term's contribution depends on the order of orthogonalization
when regressors are correlated.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.models import library_matrix, polynomial_library
from eqdisco.ols import forward_ols, ols_err

rng = np.random.default_rng(0)
X = rng.uniform(-1, 1, (300, 3))
X[:, 2] = 0.9 * X[:, 0] + 0.2 * X[:, 2]  # x2 strongly correlated with x0
y = 1.2 * X[:, 0] + 0.9 * X[:, 2] - 0.8 * X[:, 0] * X[:, 1] + 0.02 * rng.normal(size=300)

# %%
# Forward selection over a polynomial library
# -------------------------------------------
terms = polynomial_library(3, degree=2)
Phi = library_matrix(terms, X)
res = forward_ols(Phi, y, criterion="bic")
labels = [t.to_string() for t in terms]
for j in res.order:
    print(f"{labels[j]:10s} ERR = {res.err[j]:.4f}  weight = {res.coef[j]: .3f}")
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
eq.viz.plot_err_path(res, ax=axs[0], labels=labels)
axs[0].set_title("FROLS on 9 candidate terms", fontsize=9)

# %%
# The ERR depends on the order
# ----------------------------
sel = res.order[:3]
orders = [sel, sel[::-1], [sel[1], sel[0], sel[2]]]
E = np.array([ols_err(Phi[:, sel], y, order=[sel.index(o) for o in od]).err for od in orders])
w = 0.25
for k, od in enumerate(orders):
    axs[1].bar(np.arange(3) + (k - 1) * w, E[k], width=w, color=eq.viz.OKABE_ITO[k], label="order: " + ", ".join(labels[o] for o in od))
axs[1].set_xticks(range(3))
axs[1].set_xticklabels([labels[s] for s in sel])
axs[1].set_ylabel("ERR")
axs[1].legend(frameon=False, fontsize=7)
fig.tight_layout()

# %%
# Parameter study: noise and the number of selected terms
# -------------------------------------------------------
noises = [0.0, 0.05, 0.2, 0.5]
n_terms = {c: [] for c in ("bic", "aic", "err")}
for nz in noises:
    yn = y + nz * rng.normal(size=len(y))
    for c in n_terms:
        n_terms[c].append(len(forward_ols(Phi, yn, criterion=c, err_tol=1e-3).order))
print("ERR of the three terms in three orders:", np.round(E, 4).tolist())
print("terms selected by noise", noises, n_terms)
fig, ax = plt.subplots(figsize=(4.5, 3))
for k, (c, v) in enumerate(n_terms.items()):
    ax.plot(noises, v, "o-", color=eq.viz.OKABE_ITO[k], label=c.upper() if c != "err" else "ERR > 0.001")
ax.axhline(3, color="#6B7785", ls="--", lw=1)
ax.set_xlabel("noise standard deviation")
ax.set_ylabel("selected terms")
ax.legend(frameon=False, fontsize=8)
plt.show()
