"""
The EASY-IEC algorithm: a self-adaptive evolution strategy driven by clicks
===========================================================================

EASY-IEC (Madár, Abonyi and Szeifert, 2005) is a (μ+λ) evolution strategy in
which the user's clicks define the parents: a candidate clicked once becomes a
parent, clicked twice it is also copied unchanged into the next gallery. Every
individual carries its own step sizes, mutated log-normally before the genes
(Schwefel's self-adaptation), so the search contracts automatically once the
user keeps choosing similar images.
"""

# %%
# Three classical strategies on a synthetic landscape
# ---------------------------------------------------
# A synthetic preference landscape in six dimensions gives the ground truth; the
# simulated user answers with Thurstonian noise. Ten seeds per strategy.
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.problems import SyntheticPreference
from easyiec.strategies import EasyIEC, InteractiveES, InteractiveGA
from easyiec.validation import run_benchmark
bench = run_benchmark(
    problems={"ellipsoid-6": lambda: SyntheticPreference(dim=6, kind="ellipsoid", seed=2)},
    strategies={"EASY-IEC": lambda: EasyIEC(pop_size=9), "(μ+λ)-ES": lambda: InteractiveES(pop_size=9),
                "GA": lambda: InteractiveGA(pop_size=9)},
    users={"user": lambda p, s: ei.SimulatedUser(p, target="random", noise=0.05, seed=s)},
    seeds=range(10), generations=20)
print(bench.summary.groupby("strategy")["best_true"].agg(["mean", "std"]).round(3))
ax = ei.viz.plot_convergence(bench.curves, by="strategy", title="ellipsoid landscape, d = 6, 10 seeds")

# %%
# Gene trajectories of one run
# ----------------------------
# The chosen individuals of each generation in the unit cube: the spread of the
# genes shrinks as the self-adapted step sizes decrease.
problem = SyntheticPreference(dim=6, kind="ellipsoid", seed=2)
user = ei.SimulatedUser(problem, target="random", noise=0.05, seed=4)
strategy = EasyIEC(pop_size=9)
result = ei.run(problem, strategy, user, generations=20, seed=4)
ei.viz.plot_gene_trajectories(result.log, problem)

# %%
# Self-adapted step sizes
# -----------------------
# The distribution of the mean step size of the final population (initially
# :math:`1/(2\sqrt d) \approx 0.20`).
ei.viz.plot_strategy_state(strategy)
plt.show()
