"""
Sparse regression over a library of terms
=========================================

If the unknown law is a sparse combination of candidate terms, regression can
replace search. :class:`~eqdisco.SparseRegressor` builds a library -- here all
monomials up to degree 3 in three variables, 19 terms -- and selects a few by
sequentially thresholded least squares (STLSQ; Brunton, Proctor and Kutz, 2016),
the cross-validated Lasso, forward orthogonal least squares (FROLS) or best-subset
search. The target is a polynomial heat-release model with three terms.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

rng = np.random.default_rng(5)
X = rng.uniform(-1, 1, (200, 3))
y = 1.5 * X[:, 0] ** 2 * X[:, 1] - 0.8 * X[:, 2] + 0.6 * X[:, 0] * X[:, 2] + 0.02 * rng.normal(size=200)

# %%
# Four solvers on the same library
# --------------------------------
models = {m: eq.SparseRegressor(degree=3, method=m, threshold=0.05, max_terms=4, feature_names=["T", "p", "c"]).fit(X, y) for m in ("stlsq", "lasso", "frols", "best_subset")}
for m, s in models.items():
    print(f"{m:12s} {s.support_.sum():2d} terms  R2 {s.score(X, y):.5f}  {s.equation_}")
terms = [t.to_string() for t in models["stlsq"].terms_]
fig, ax = plt.subplots(figsize=(10, 3.3))
w = 0.2
for k, (m, s) in enumerate(models.items()):
    ax.bar(np.arange(len(terms)) + (k - 1.5) * w, s.coef_, width=w, color=eq.viz.OKABE_ITO[k], label=m)
ax.axhline(0, color="#6B7785", lw=0.8)
ax.set_xticks(range(len(terms)))
ax.set_xticklabels(terms, rotation=60, ha="right", fontsize=7)
ax.set_ylabel("coefficient")
ax.legend(frameon=False, fontsize=8, ncol=4)
fig.tight_layout()

# %%
# Parameter study: the STLSQ threshold and noise
# ----------------------------------------------
ths = np.logspace(-3, 0, 12)
fig, ax = plt.subplots(figsize=(4.8, 3.2))
for k, nz in enumerate((0.02, 0.1, 0.3)):
    yn = y + nz * rng.normal(size=len(y))
    n_by_threshold = [int(eq.SparseRegressor(degree=3, threshold=t).fit(X, yn).support_.sum()) for t in ths]
    print(f"noise {nz}: terms kept at thresholds {np.round(ths[::3], 3).tolist()}: {n_by_threshold[::3]}")
    ax.semilogx(ths, n_by_threshold, "o-", color=eq.viz.OKABE_ITO[k], ms=3, label=f"noise {nz}")
ax.axhline(3, color="#6B7785", ls="--", lw=1)
ax.set_xlabel("STLSQ threshold (relative)")
ax.set_ylabel("selected terms")
ax.legend(frameon=False, fontsize=8)
plt.show()
