"""
GP-OLS: pruning terms by their error reduction ratio
====================================================

GP-OLS (Madár, Abonyi and Szeifert, 2005) evolves linear-in-parameters models
with the function set :math:`\\{+,\\times\\}`, reads every individual as a sum of
terms, and lets orthogonal least squares judge them: terms whose error reduction
ratio is below a threshold are removed from the individual. The search is spared
from carrying useless terms and returns compact, interpretable models. eqdisco
adds a backward check of the unique contribution of every term, which removes
collinear terms that received a high ERR only because of their position.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

rng = np.random.default_rng(1)
X = rng.uniform(-1, 1, (300, 4))
y = 2 * X[:, 0] * X[:, 1] - 1.5 * X[:, 2] ** 2 + 0.5 * X[:, 0] * X[:, 2] * X[:, 3] + 0.02 * rng.normal(size=300)

# %%
# GP-OLS and plain multi-gene GP
# ------------------------------
gpols = eq.GPOLSRegressor(population_size=250, generations=30, max_genes=6, err_threshold=0.01, random_state=0).fit(X, y)
mggp = eq.MultiGeneRegressor(population_size=250, generations=30, max_genes=6, functions=("add", "mul"), random_state=0).fit(X, y)
print("GP-OLS:", gpols.equation_)
print("MGGP:  ", mggp.equation_)
print(gpols.gene_table())
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
eq.viz.plot_terms(gpols.gene_table().rename(columns={"gene": "term"}), ax=axs[0])
axs[0].set_title("terms of the GP-OLS model", fontsize=9)
for k, (name, m) in enumerate((("GP-OLS", gpols), ("MGGP", mggp))):
    axs[1].plot(m.history_["mean_size"], color=eq.viz.OKABE_ITO[k], lw=2, label=f"{name}: final model size {m.equation_.complexity}")
axs[1].set_xlabel("generation")
axs[1].set_ylabel("mean individual size")
axs[1].legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# Parameter study: the ERR threshold
# ----------------------------------
thresholds = [0.001, 0.005, 0.01, 0.05, 0.1]
sizes, r2s = [], []
for th in thresholds:
    m = eq.GPOLSRegressor(population_size=200, generations=25, err_threshold=th, random_state=0).fit(X, y)
    sizes.append(m.equation_.complexity)
    r2s.append(m.score(X, y))
print("ERR threshold", thresholds, "size", sizes, "R2", np.round(r2s, 5).tolist())
fig, ax = plt.subplots(figsize=(4.8, 3))
ax.plot(thresholds, sizes, "o-", color="#285780")
ax.set_xscale("log")
ax.set_xlabel("ERR threshold")
ax.set_ylabel("model size", color="#285780")
ax2 = ax.twinx()
ax2.plot(thresholds, r2s, "s--", color="#D55E00")
ax2.set_ylabel("$R^2$", color="#D55E00")
plt.show()
