"""
Multi-gene genetic programming
==============================

Instead of one tree, a multi-gene individual carries several small trees, the
genes :math:`F_1,\\dots,F_m`, and the model is their least-squares combination
:math:`w_0+\\sum_i w_iF_i` (Searson, Leahy and Willis, 2010). Genes evolve by
crossover inside genes and by exchanging whole genes between individuals. The
data come from a reaction rate with an inhibition term,
:math:`r=2c_Ac_B-0.5c_A^2+0.3\\,c_B/(1+c_A)`.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

rng = np.random.default_rng(3)
cA, cB = rng.uniform(0.1, 2, 300), rng.uniform(0.1, 2, 300)
X = np.column_stack([cA, cB])
r = 2 * cA * cB - 0.5 * cA**2 + 0.3 * cB / (1 + cA) + 0.01 * rng.normal(size=300)

# %%
# Fitting and the genes
# ---------------------
mg = eq.MultiGeneRegressor(population_size=250, generations=30, max_genes=4, functions=("add", "sub", "mul", "div"), feature_names=["cA", "cB"], random_state=0)
mg.fit(X, r)
print(mg.equation_)
print(mg.gene_table())
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
eq.viz.plot_pareto(mg, ax=axs[0], annotate=True, max_labels=4)
t = mg.gene_table()
t = t.rename(columns={"gene": "term"})
eq.viz.plot_terms(t, ax=axs[1])
fig.tight_layout()

# %%
# Parameter study: the maximum number of genes
# --------------------------------------------
fig, ax = plt.subplots(figsize=(4.5, 3))
for k, m in enumerate((1, 2, 4, 6)):
    h = np.median([eq.MultiGeneRegressor(population_size=200, generations=25, max_genes=m, functions=("add", "sub", "mul", "div"), random_state=s).fit(X, r).history_["best_loss"] for s in range(3)], axis=0)
    print(f"at most {m} genes: median final NMSE {h[-1] / np.var(r):.2e}")
    ax.semilogy(h / np.var(r), color=eq.viz.OKABE_ITO[k], label=f"at most {m} genes")
ax.set_xlabel("generation")
ax.set_ylabel("median normalized MSE")
ax.legend(frameon=False, fontsize=8)
plt.show()
