"""
A first interactive session: evolving a Julia set
=================================================

An interactive evolutionary algorithm shows a gallery of candidates, the
evaluator picks the ones they like, and the algorithm breeds the next gallery
from the picks. Here the evaluator is a *simulated user* who secretly prefers one
particular Julia set; because its taste is known, we can measure how close each
gallery came to it — the ground truth that a real person cannot give us.
"""

# %%
# Problem, strategy and evaluator
# -------------------------------
# A :class:`~easyiec.problems.JuliaSet` has ten genes: the complex constant
# in polar form, zoom, centre, four colour genes and the interior shade. The interactive GA shows nine images per
# generation and asks for the ones worth keeping (the *select* protocol).
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.problems import JuliaSet
from easyiec.strategies import InteractiveGA
problem = JuliaSet()
user = ei.SimulatedUser(problem, target="random", noise=0.05, seed=3)
result = ei.run(problem, InteractiveGA(pop_size=9), user, generations=12, seed=3)
print(result)
print(problem.describe(result.best.genome))
# %%
# What the evaluator saw
# ----------------------
# The film strip shows four galleries; the chosen images carry a frame. The
# population drifts towards the hidden target within a few generations.
ei.viz.plot_history(result.log, problem, steps=[0, 3, 7, 11], max_items=9, size=0.9)

# %%
# The hidden target and the best image found
# ------------------------------------------
# The simulated user's target is an ordinary genome, so it can be drawn.
fig, axes = plt.subplots(1, 2, figsize=(5.2, 2.7))
problem.render(user.target, ax=axes[0])
axes[0].set_title("hidden target", fontsize=9)
problem.render(result.best.genome, ax=axes[1])
axes[1].set_title(f"best found (utility {problem.utility(result.best.genome, user.target):.2f})", fontsize=9)

# %%
# The anytime curve
# -----------------
# The true utility of the best individual is plotted against the number of
# images shown — the classical measure of evaluator effort in IEC.
ax = ei.viz.plot_anytime(result, label="interactive GA")
ax.set_title("best true utility vs. images shown")
plt.show()
