"""
Parameter optimization inside the search
========================================

Constants inside nonlinear functions -- the 0.8 in :math:`e^{-0.8x_0}` -- are hard
to evolve by mutation. Modern symbolic regression systems tune them by gradient
methods during the search (Kommenda et al., 2020; Burlacu et al., 2020). eqdisco
applies Levenberg--Marquardt with exact forward-mode Jacobians to the best share
of the offspring and writes the tuned values back into the genome (Lamarckian
learning). The target is :math:`y=2.5\\,e^{-0.8x_0}\\sin x_1`.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

rng = np.random.default_rng(1)
X = rng.uniform(-2, 2, (200, 2))
y = 2.5 * np.exp(-0.8 * X[:, 0]) * np.sin(X[:, 1])
funcs = ("add", "sub", "mul", "div", "exp", "sin")

# %%
# With and without Levenberg--Marquardt
# -------------------------------------
runs = {}
for opt in ("none", "lm"):
    runs[opt] = [
        eq.SymbolicRegressor(population_size=200, generations=20, optimize=opt, optimize_fraction=0.1, optimize_iterations=10, functions=funcs, random_state=s).fit(X, y)
        for s in range(5)
    ]
for opt, rr in runs.items():
    print(opt, [str(r.equation_) for r in rr[:2]])
for opt in ("none", "lm"):
    print(f"{opt:4s} median final NMSE {np.median([r.history_['best_loss'].iloc[-1] for r in runs[opt]]) / np.var(y):.2e}  "
          f"median evaluations {np.median([r.history_['n_evaluations'].iloc[-1] for r in runs[opt]]):.0f}")
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
for opt, color in (("none", "#D55E00"), ("lm", "#285780")):
    for r in runs[opt]:
        h = r.history_
        axs[0].semilogy(h["n_evaluations"], h["best_loss"] / np.var(y), color=color, lw=0.8, alpha=0.6)
    axs[0].plot([], [], color=color, label="no tuning" if opt == "none" else "Levenberg-Marquardt")
    eq.viz.plot_pareto(runs[opt][0], ax=axs[1], annotate=False, color=color, label=opt)
axs[0].set_xlabel("fitness evaluations")
axs[0].set_ylabel("normalized MSE of the best")
axs[0].legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# Parameter study: the share of optimized offspring
# -------------------------------------------------
fracs = [0.0, 0.05, 0.2, 0.5]
med = []
for f in fracs:
    vals = [eq.SymbolicRegressor(population_size=150, generations=15, optimize="lm", optimize_fraction=f, functions=funcs, random_state=s).fit(X, y).score(X, y) for s in range(3)]
    med.append(np.median(vals))
print("share optimized", fracs, "median 1-R2", [f"{1 - v:.1e}" for v in med])
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(fracs, 1 - np.array(med), "o-", color="#285780")
ax.set_yscale("log")
ax.set_xlabel("share of offspring tuned by LM")
ax.set_ylabel("median $1-R^2$")
plt.show()
