"""
Bloat and its control
=====================

Programs in genetic programming tend to grow without improving: *bloat*. Larger
programs are slower to evaluate, harder to read and generalize worse. This example
follows the mean program size on Nguyen-6, :math:`\\sin x+\\sin(x+x^2)`, under
four policies: no control besides the size limit, parsimony pressure (a penalty
per node added to the loss), double tournament (Luke and Panait, 2002), and
NSGA-II with size as a second objective.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

prob = eq.datasets.get_problem("nguyen-6")
base = dict(population_size=250, generations=30, functions=("add", "sub", "mul", "sin", "cos"), max_size=80, max_depth=14)
policies = {
    "size limit only": dict(),
    "parsimony 0.001": dict(parsimony=1e-3),
    "double tournament": dict(selection="double_tournament"),
    "NSGA-II (error, size)": dict(selection="nsga2"),
}

# %%
# Mean size and accuracy
# ----------------------
results = {}
for name, kw in policies.items():
    results[name] = [eq.SymbolicRegressor(random_state=s, **base, **kw).fit(prob.X_train, prob.y_train) for s in range(4)]
for name, rr in results.items():
    print(f"{name:22s} final mean size {np.mean([r.history_['mean_size'].iloc[-1] for r in rr]):5.1f}  "
          f"median best MSE {np.median([r.history_['best_loss'].iloc[-1] for r in rr]):.2e}  "
          f"median test 1-R2 {np.median([1 - r.equation_.score(prob.X_test, prob.y_test) for r in rr]):.2e}")
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
for k, (name, runs) in enumerate(results.items()):
    S = np.array([r.history_["mean_size"].to_numpy() for r in runs])
    axs[0].plot(S.mean(0), color=eq.viz.OKABE_ITO[k], lw=2, label=name)
    L = np.array([r.history_["best_loss"].to_numpy() for r in runs])
    axs[1].semilogy(np.median(L, 0), color=eq.viz.OKABE_ITO[k], lw=2, label=name)
axs[0].set_xlabel("generation")
axs[0].set_ylabel("mean program size (nodes)")
axs[1].set_xlabel("generation")
axs[1].set_ylabel("median best MSE")
axs[0].legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# Parameter study: the parsimony coefficient
# ------------------------------------------
coefs = [0, 1e-4, 1e-3, 1e-2]
sizes, errs = [], []
for c in coefs:
    rr = [eq.SymbolicRegressor(random_state=s, parsimony=c, **base).fit(prob.X_train, prob.y_train) for s in range(3)]
    sizes.append(np.mean([r.history_["mean_size"].iloc[-1] for r in rr]))
    errs.append(np.median([1 - r.equation_.score(prob.X_test, prob.y_test) for r in rr]))
print("parsimony", coefs, "mean size", np.round(sizes, 1).tolist(), "median test 1-R2", [f"{e:.1e}" for e in errs])
fig, ax = plt.subplots(figsize=(4.8, 3.2))
ax.plot(sizes, errs, "o-", color="#285780")
for c, s, e in zip(coefs, sizes, errs):
    ax.annotate(f"{c:g}", (s, e), xytext=(5, 3), textcoords="offset points", fontsize=8)
ax.set_xlabel("final mean program size")
ax.set_ylabel("median $1-R^2$ (test)")
ax.set_yscale("log")
plt.show()
