"""
Diversity: semantic crossover and islands
=========================================

A population that converges to copies of one structure stops exploring. Two
remedies are compared on Vladislavleva-7. Semantic similarity-based crossover
(Uy et al., 2011) swaps only subtrees that behave similarly but not identically
on the data, so that offspring differ from their parents in small semantic steps.
The island model splits the population into sub-populations that exchange their
best individuals periodically, which keeps several lines of search alive.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

prob = eq.datasets.get_problem("vladislavleva-7")
variants = {
    "subtree crossover": dict(),
    "semantic crossover": dict(crossover="semantic"),
    "4 islands": dict(n_islands=4, migration_interval=5, migration_size=2),
}

# %%
# Diversity and progress
# ----------------------
results = {name: [eq.SymbolicRegressor(population_size=240, generations=25, functions=("add", "sub", "mul", "sin"), random_state=s, **kw).fit(prob.X_train, prob.y_train) for s in range(4)] for name, kw in variants.items()}
for name, rr in results.items():
    print(f"{name:20s} mean share of distinct structures {np.mean([r.history_['unique'].mean() for r in rr]):.3f}  "
          f"median final NMSE {np.median([r.history_['best_loss'].iloc[-1] for r in rr]) / np.var(prob.y_train):.2e}")
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
for k, (name, rr) in enumerate(results.items()):
    U = np.array([r.history_["unique"] for r in rr])
    L = np.array([r.history_["best_loss"] for r in rr]) / np.var(prob.y_train)
    axs[0].plot(U.mean(0), color=eq.viz.OKABE_ITO[k], lw=2, label=name)
    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("share of distinct structures")
axs[1].set_xlabel("generation")
axs[1].set_ylabel("median normalized MSE")
axs[0].legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# Parameter study: migration interval
# -----------------------------------
intervals = [2, 5, 10, 25]
med = []
for mi in intervals:
    med.append(np.median([eq.SymbolicRegressor(population_size=240, generations=25, n_islands=4, migration_interval=mi, functions=("add", "sub", "mul", "sin"), random_state=s).fit(prob.X_train, prob.y_train).history_["best_loss"].iloc[-1] for s in range(3)]))
print("migration interval", intervals, "median final NMSE", [f"{m / np.var(prob.y_train):.2e}" for m in med])
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(intervals, np.array(med) / np.var(prob.y_train), "o-", color="#285780")
ax.set_xlabel("migration interval (generations)")
ax.set_ylabel("median final normalized MSE")
ax.set_yscale("log")
plt.show()
