"""
Library learning: reusing building blocks (new in eqdisco)
==========================================================

Many laws repeat a motif: a sum of exponentials, a ratio of polynomials, a
product appearing twice. With ``library_learning=True`` eqdisco periodically mines
the frequent subtrees of the best individuals
(:func:`~eqdisco.analysis.mine_library`) and inserts them into new offspring, so
that a block found once can be reused elsewhere in the tree. The target repeats
the block :math:`m=x_0x_1+x_2` three times: :math:`y=m^2+\\sin m+m\\,x_3`.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

rng = np.random.default_rng(0)
X = rng.uniform(-1.5, 1.5, (250, 4))
m = X[:, 0] * X[:, 1] + X[:, 2]
y = m**2 + np.sin(m) + m * X[:, 3]
funcs = ("add", "sub", "mul", "sin")

# %%
# With and without the library
# ----------------------------
runs = {}
for lib in (False, True):
    runs[lib] = [eq.SymbolicRegressor(population_size=250, generations=30, functions=funcs, library_learning=lib, library_interval=3, p_library=0.05, random_state=s).fit(X, y) for s in range(6)]
learned = eq.analysis.mine_library([r.ind for r in runs[True][0]._final_population[:50]], max_blocks=5)
print("library of run 0:", [str(blk) for blk in learned])
for lib in (False, True):
    print("with library" if lib else "without library", f"median final NMSE {np.median([r.history_['best_loss'].iloc[-1] for r in runs[lib]]) / np.var(y):.2e}")
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
for lib, color in ((False, "#D55E00"), (True, "#285780")):
    L = np.array([r.history_["best_loss"] for r in runs[lib]]) / np.var(y)
    for h in L:
        axs[0].semilogy(h, color=color, lw=0.6, alpha=0.4)
    axs[0].semilogy(np.median(L, 0), color=color, lw=2.2, label="with library" if lib else "without library")
    axs[1].scatter([r.equation_.complexity for r in runs[lib]], [max(1 - r.score(X, y), 1e-12) for r in runs[lib]], color=color, s=30)
axs[0].set_xlabel("generation")
axs[0].set_ylabel("normalized MSE of the best")
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$")
fig.tight_layout()

# %%
# Parameter study: the injection rate
# -----------------------------------
rates = [0.0, 0.02, 0.05, 0.1, 0.2]
med = [np.median([eq.SymbolicRegressor(population_size=250, generations=30, functions=funcs, library_learning=p > 0, library_interval=3, p_library=p, random_state=s).fit(X, y).history_["best_loss"].iloc[-1] for s in range(3)]) for p in rates]
print("injection rate", rates, "median final NMSE", [f"{m / np.var(y):.2e}" for m in med])
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(rates, np.array(med) / np.var(y), "o-", color="#285780")
ax.set_xlabel("share of offspring built from the library")
ax.set_ylabel("median final normalized MSE")
ax.set_yscale("log")
plt.show()
