"""
CMA-ES, interactive PSO and pairwise differential evolution
===========================================================

Three continuous optimizers adapted to judged fitness. The interactive CMA-ES
needs only the *order* of the candidates, so a ranking or a selection suffices
(Hansen, 2016). The interactive PSO of Madár, Abonyi and Szeifert (2005) moves
the swarm towards the candidates the user picks as personal and global bests.
Differential evolution asks a single question per trial vector — *is the
offspring better than its parent?* — which makes it a natural pairwise method.
"""

# %%
# Convergence on a rotated multimodal landscape
# ---------------------------------------------
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.problems import SyntheticPreference
from easyiec.strategies import InteractiveCMAES, InteractiveDE, InteractivePSO, RandomSearch
from easyiec.validation import run_benchmark
bench = run_benchmark(
    problems={"multimodal-5": lambda: SyntheticPreference(dim=5, kind="multimodal", seed=1)},
    strategies={"CMA-ES (rank)": lambda: InteractiveCMAES(pop_size=8, protocol="rank"),
                "IPSO (select 1)": lambda: InteractivePSO(pop_size=8),
                "DE (pairs)": lambda: InteractiveDE(pop_size=8),
                "random": lambda: RandomSearch(pop_size=8)},
    users={"user": lambda p, s: ei.SimulatedUser(p, target="random", noise=0.05, seed=s)},
    seeds=range(10), max_items=200, generations=None)
print(bench.summary.groupby("strategy")[["best_true", "items", "queries"]].mean().round(3))
# %%
# Items shown versus elementary decisions
# ---------------------------------------
# Counting shown items favours methods that show many candidates at once;
# counting elementary decisions (one per pair, one per item looked at in a
# gallery) gives a fairer picture of the evaluator's effort.
from easyiec.validation import curve_frame  # noqa: E402

labels = [r.strategy for r in bench.results]
fig, axes = plt.subplots(1, 2, figsize=(10, 3.6))
ei.viz.plot_convergence(curve_frame(bench.results, "n_items", labels), ax=axes[0], title="vs. items shown")
ei.viz.plot_convergence(curve_frame(bench.results, "n_decisions", labels), x="n_decisions", ax=axes[1],
                        title="vs. elementary decisions")

# %%
# Inside the strategies
# ---------------------
# After 20 generations the CMA-ES covariance has elongated along the valley of
# the landscape, and the swarm of the PSO has gathered around the global best.
problem = SyntheticPreference(dim=5, kind="ellipsoid", seed=1)
cma, pso = InteractiveCMAES(pop_size=8), InteractivePSO(pop_size=8)
for s in (cma, pso):
    ei.run(problem, s, ei.SimulatedUser(problem, target="random", noise=0.05, seed=3), generations=20, seed=3)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.4))
ei.viz.plot_strategy_state(cma, ax=axes[0])
ei.viz.plot_strategy_state(pso, ax=axes[1])
plt.show()
