"""
Fighting fatigue with a surrogate of the evaluator
==================================================

User fatigue is the central limitation of IEC (Takagi, 2001): people tire after
a few hundred judgments. A surrogate model trained on the answers so far can
pre-screen the offspring so that the evaluator sees only the most promising
ones — the synthetic-fitness idea of Llorà et al. (2005) and the
comparison-based surrogates of Loshchilov et al. (2010). A Bradley–Terry
model on random Fourier features is refitted after every answer. In *screen*
mode it chooses 6 of 27 offspring to show; in *pre-selection* mode every
offspring of a nine-image GA competes with three of its mutants and only the
best-predicted one is shown.
"""

# %%
# A GA with and without the surrogate on a multimodal landscape
# -------------------------------------------------------------
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.problems import SyntheticPreference
from easyiec.strategies import InteractiveGA, SurrogateAssisted
from easyiec.validation import run_benchmark
bench = run_benchmark(
    problems={"multimodal-8": lambda: SyntheticPreference(dim=8, kind="multimodal", seed=3)},
    strategies={"GA, 9 shown": lambda: InteractiveGA(pop_size=9),
                "screen: 6 of 27 shown": lambda: SurrogateAssisted(InteractiveGA(pop_size=27), n_show=6),
                "pre-selection: best of 4": lambda: SurrogateAssisted(InteractiveGA(pop_size=9), mode="preselect",
                                                                      n_candidates=4, explore=0.2)},
    users={"tiring user": lambda p, s: ei.SimulatedUser(p, target="random", noise=0.05, fatigue=0.5,
                                                       fatigue_scale=150, seed=s)},
    seeds=range(12), max_items=180, generations=None)
print(bench.summary.groupby("strategy")[["best_true", "items", "queries"]].mean().round(3))
ei.viz.plot_convergence(bench.curves, by="strategy", title="multimodal landscape, d = 8, tiring user, 12 seeds")

# %%
# On the multimodal landscape both surrogate modes find the global peak more
# often than the plain GA at the same number of images. On a unimodal sphere the
# advantage disappears: a well-tuned GA already produces good offspring, and a
# model fitted to a few dozen comparisons adds little (see the benchmark
# chapter of the book).

# %%
# How good was the screening?
# ---------------------------
# The ground-truth utility of the shown candidates per query in one run of the
# surrogate-assisted GA: after the first queries the gallery is filled with
# better-than-average offspring.
problem = SyntheticPreference(dim=8, kind="multimodal", seed=3)
user = ei.SimulatedUser(problem, target="random", noise=0.05, seed=1)
res = ei.run(problem, SurrogateAssisted(InteractiveGA(pop_size=27), n_show=6), user, generations=25, seed=1)
ei.viz.plot_utility_by_step(res.log)
plt.show()
