"""
Cooperative GP with OLS credit assignment (new in eqdisco)
==========================================================

In :class:`~eqdisco.CooperativeOLSRegressor` the population is a shared library
of basis functions. Each generation, forward orthogonal least squares selects the
subset that best explains the data; selected individuals earn their ERR, the
others the share of the residual they could explain, so the population keeps
searching for what the model still misses. The selection path gives nested models
of every size, a Pareto front at no extra cost. The target mixes a periodic, a
multiplicative and a rational term.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

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

# %%
# A cooperative run
# -----------------
coop = eq.CooperativeOLSRegressor(population_size=150, generations=30, max_terms=6, random_state=0).fit(X, y)
print(coop.equation_)
print(coop.history_.tail(3))
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
h = coop.history_
axs[0].semilogy(h["generation"], 1 - h["r2"], color="#285780", lw=2, label="$1-R^2$ of the current model")
ax2 = axs[0].twinx()
ax2.step(h["generation"], h["n_terms"], color="#D55E00", where="post")
ax2.set_ylabel("terms in the model", color="#D55E00")
axs[0].set_xlabel("generation")
axs[0].legend(frameon=False, fontsize=8)
eq.viz.plot_pareto(coop, ax=axs[1], annotate=True, max_labels=4)
fig.tight_layout()

# %%
# Parameter study: library size
# -----------------------------
sizes = [40, 80, 150, 300]
med = [np.median([1 - eq.CooperativeOLSRegressor(population_size=s, generations=20, random_state=k).fit(X, y).score(X, y) for k in range(3)]) for s in sizes]
print("population", sizes, "median 1-R2", [f"{v:.1e}" for v in med])
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(sizes, med, "o-", color="#285780")
ax.set_yscale("log")
ax.set_xlabel("population (library) size")
ax.set_ylabel("median $1-R^2$")
plt.show()
