"""
ERR-guided variation: an experimental operator (new in eqdisco)
===============================================================

Orthogonal least squares tells not only which terms to prune but also which
genes are weak and which are strong. ERR-guided variation uses this: the gene to
be mutated or replaced is drawn with probability inversely proportional to its
ERR, and the gene donated to another individual with probability proportional
to it (``err_guided=True``) or uniformly (``err_guided="replace"``). Does the
guidance help? Ten runs of each variant on a six-term polynomial target answer
the question -- an honest benchmark is part of proposing an operator.
"""

import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

import eqdisco as eq

rng = np.random.default_rng(2)
X = rng.uniform(-1, 1, (300, 6))
y = (3 * X[:, 0] * X[:, 1] * X[:, 2] - 2 * X[:, 3] ** 2 + X[:, 1] * X[:, 4] + 0.5 * X[:, 0] + X[:, 2] * X[:, 3] * X[:, 5] - 1.5 * X[:, 0] * X[:, 4]
     + 0.01 * rng.normal(size=300))
variants = {"uniform": False, "guided replacement": "replace", "fully guided": True}

# %%
# Ten runs per variant
# --------------------
final, hist = {}, {}
for name, g in variants.items():
    runs = [eq.MultiGeneRegressor(population_size=150, generations=25, max_genes=8, functions=("add", "mul"), err_guided=g, random_state=s).fit(X, y) for s in range(10)]
    hist[name] = np.array([r.history_["best_loss"] for r in runs]) / np.var(y)
    final[name] = hist[name][:, -1]
print({k: f"{np.median(v):.2e}" for k, v in final.items()})
print("Mann-Whitney p (uniform vs fully guided):", stats.mannwhitneyu(final["uniform"], final["fully guided"]).pvalue)
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
for k, (name, H) in enumerate(hist.items()):
    axs[0].semilogy(np.median(H, 0), color=eq.viz.OKABE_ITO[k], lw=2, label=name)
axs[0].set_xlabel("generation")
axs[0].set_ylabel("median normalized MSE of the best")
axs[0].legend(frameon=False, fontsize=8)
axs[1].boxplot(list(final.values()), tick_labels=list(final), widths=0.5)
axs[1].set_yscale("log")
axs[1].set_ylabel("final normalized MSE (10 runs)")
fig.tight_layout()

# %%
# Parameter study: share of gene-level crossover
# ----------------------------------------------
ps = [0.1, 0.3, 0.6]
fig, ax = plt.subplots(figsize=(4.5, 3))
for k, (name, g) in enumerate((("uniform", False), ("fully guided", True))):
    med = [np.median([eq.MultiGeneRegressor(population_size=150, generations=15, max_genes=8, functions=("add", "mul"), err_guided=g, p_high_level=p, random_state=s).fit(X, y).history_["best_loss"].iloc[-1] for s in range(3)]) for p in ps]
    print(name, "p_high_level", ps, "median NMSE", [f"{v / np.var(y):.2e}" for v in med])
    ax.plot(ps, np.array(med) / np.var(y), "o-", color=eq.viz.OKABE_ITO[2 * k], label=name)
ax.set_yscale("log")
ax.set_xlabel("share of high-level (gene) crossover")
ax.set_ylabel("median final normalized MSE")
ax.legend(frameon=False, fontsize=8)
plt.show()
