"""
The Pareto front and the choice of one model
============================================

A run returns the non-dominated models: each is the most accurate of its size.
Which one to report is a decision, and eqdisco makes it explicit
(:func:`~eqdisco.analysis.select_model`): the lowest error, an information
criterion, the knee of the front, a tolerance on the error, the score rule of
PySR (Cranmer, 2023), or the error on held-out data. The data are Nguyen-7,
:math:`\\ln(x+1)+\\ln(x^2+1)`, with 2 % noise.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.analysis import select_model

prob = eq.datasets.get_problem("nguyen-7", noise=0.02, n_train=100)

# %%
# One run, six rules
# ------------------
sr = eq.SymbolicRegressor(population_size=300, generations=30, functions=("add", "sub", "mul", "div", "log", "sqrt"), random_state=2)
sr.fit(prob.X_train, prob.y_train)
front = sr.pareto_front_
chosen = {rule: select_model(front, rule, prob.X_train, prob.y_train) for rule in ("best", "bic", "aic", "knee", "tolerance", "score")}
for rule, e in chosen.items():
    print(f"{rule:9s} size {e.complexity:3d}  test R2 {e.score(prob.X_test, prob.y_test):.5f}  {e}")
fig, axs = plt.subplots(1, 2, figsize=(11, 3.6))
eq.viz.plot_pareto(front, ax=axs[0], annotate=False)
eq.viz.plot_pareto(front, prob.X_test, prob.y_test, ax=axs[0], annotate=False, color="#009E73", label="test error")
marks = {"best": "v", "bic": "o", "aic": "s", "knee": "D", "tolerance": "^", "score": "P"}
for k, (rule, e) in enumerate(chosen.items()):
    axs[0].scatter([e.complexity], [e.metrics["mse"]], marker=marks[rule], s=90, facecolor="none", edgecolor=eq.viz.OKABE_ITO[k], lw=1.8, label=rule, zorder=5)
axs[0].legend(frameon=False, fontsize=7, ncol=2)
xs = np.linspace(0, 2, 200).reshape(-1, 1)
axs[1].scatter(prob.X_train[:, 0], prob.y_train, s=10, color="#6B7785", label="noisy data")
for k, rule in enumerate(("best", "bic", "knee")):
    axs[1].plot(xs, chosen[rule].predict(xs), color=eq.viz.OKABE_ITO[k], lw=1.5, label=f"{rule}: size {chosen[rule].complexity}")
axs[1].set_xlabel("x")
axs[1].legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# Parameter study: noise and the size of the chosen model
# -------------------------------------------------------
noises = [0.0, 0.01, 0.05, 0.1]
fig, ax = plt.subplots(figsize=(4.8, 3.2))
sizes_by_rule = {}
for k, rule in enumerate(("best", "bic", "knee")):
    sizes = []
    for nz in noises:
        p = eq.datasets.get_problem("nguyen-7", noise=nz, n_train=100)
        rr = eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "div", "log", "sqrt"), random_state=0, model_selection=rule)
        sizes.append(rr.fit(p.X_train, p.y_train).equation_.complexity)
    sizes_by_rule[rule] = sizes
    ax.plot(noises, sizes, "o-", color=eq.viz.OKABE_ITO[k], label=rule)
print("noise", noises, "size of the selected model", sizes_by_rule)
ax.set_xlabel("noise level")
ax.set_ylabel("size of the selected model")
ax.legend(frameon=False, fontsize=8)
plt.show()
