"""
Five selection schemes on one problem
=====================================

Selection decides which individuals reproduce. eqdisco offers tournament
selection, double tournament with parsimony (Luke and Panait, 2002), ε-lexicase
selection, which judges candidates case by case (La Cava et al., 2016), NSGA-II on
error and size (Deb et al., 2002), and age--fitness Pareto optimization, which
protects young individuals from old, entrenched ones (Schmidt and Lipson, 2011).
The problem is Keijzer-14, :math:`8/(2+x^2+y^2)`, sampled at 100 points.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

prob = eq.datasets.get_problem("keijzer-14")
schemes = ["tournament", "double_tournament", "lexicase", "nsga2", "afp"]

# %%
# Five runs per scheme
# --------------------
runs = {}
for sel in schemes:
    runs[sel] = []
    for seed in range(5):
        sr = eq.SymbolicRegressor(population_size=200, generations=25, selection=sel, functions=("add", "sub", "mul", "div"), random_state=seed)
        sr.fit(prob.X_train, prob.y_train)
        runs[sel].append(sr)
for sel in schemes:
    print(f"{sel:18s} median final NMSE {np.median([r.history_['best_loss'].iloc[-1] for r in runs[sel]]) / np.var(prob.y_train):.2e}  "
          f"median test R2 {np.median([r.equation_.score(prob.X_test, prob.y_test) for r in runs[sel]]):.4f}  "
          f"median size {np.median([r.equation_.complexity for r in runs[sel]]):.0f}  "
          f"runs with test R2 > 0.999: {sum(r.equation_.score(prob.X_test, prob.y_test) > 0.999 for r in runs[sel])} of 5")
fig, axs = plt.subplots(1, 2, figsize=(10, 3.5))
for k, sel in enumerate(schemes):
    H = np.array([r.history_["best_loss"].to_numpy() for r in runs[sel]]) / np.var(prob.y_train)
    axs[0].semilogy(np.median(H, 0), color=eq.viz.OKABE_ITO[k], lw=2, label=sel)
    r2 = [r.equation_.score(prob.X_test, prob.y_test) for r in runs[sel]]
    size = [r.equation_.complexity for r in runs[sel]]
    axs[1].scatter(size, np.maximum(1 - np.array(r2), 1e-12), color=eq.viz.OKABE_ITO[k], s=30, label=sel)
axs[0].set_xlabel("generation")
axs[0].set_ylabel("median normalized MSE (train)")
axs[0].legend(frameon=False, fontsize=8)
axs[1].set_yscale("log")
axs[1].set_xlabel("size of the selected model")
axs[1].set_ylabel("$1-R^2$ on test data")
fig.tight_layout()

# %%
# Parameter study: the tournament size
# ------------------------------------
# Larger tournaments mean stronger selection pressure: faster progress, but a
# quicker loss of diversity.
sizes = [2, 4, 7, 12]
fig, ax = plt.subplots(figsize=(4.8, 3.2))
for k, t in enumerate(sizes):
    H = np.array([eq.SymbolicRegressor(population_size=200, generations=25, tournament_size=t, functions=("add", "sub", "mul", "div"), random_state=s).fit(prob.X_train, prob.y_train).history_["unique"] for s in range(3)])
    print(f"tournament size {t}: share of distinct structures at generation 25: {H.mean(0)[-1]:.2f}")
    ax.plot(H.mean(0), color=eq.viz.OKABE_ITO[k], label=f"tournament size {t}")
ax.set_xlabel("generation")
ax.set_ylabel("share of distinct structures")
ax.legend(frameon=False, fontsize=8)
plt.show()
