"""
Interactive MAP-Elites: a diverse archive instead of one winner
===============================================================

Designers often want a *repertoire* of good, different solutions rather than a
single optimum. MAP-Elites (Mouret and Clune, 2015) keeps one elite per cell of
a behaviour grid. In the interactive version the evaluator only decides duels
between a newcomer and the incumbent elite of its cell; empty cells are filled
without asking, so effort concentrates where a decision is really needed.
"""

# %%
# An archive of Julia sets
# ------------------------
# The two behaviour descriptors are image features: the entropy of the
# grey-level histogram and the colourfulness of Hasler and Süsstrunk (2003).
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.problems import JuliaSet
from easyiec.strategies import InteractiveMAPElites

problem = JuliaSet()
strategy = InteractiveMAPElites(bins=5, batch=10, n_init=20, max_pairs=6)
user = ei.SimulatedUser(problem, target="random", noise=0.05, seed=2)
result = ei.run(problem, strategy, user, generations=25, seed=2)
print(f"archive coverage {strategy.coverage():.0%}, {result.summary()['queries']} queries, "
      f"{result.summary()['items']} items shown")
# %%
# The archive
# -----------
# Colour: the ground-truth utility of each elite.
ei.viz.plot_strategy_state(strategy)

# %%
# The repertoire
# --------------
# The elites ordered by cell; each is the best the user has seen in its niche.
elites = [strategy.archive[c] for c in sorted(strategy.archive)]
ei.viz.plot_gallery(problem, elites, ncols=8, size=1.0,
                    labels=[f"{c[0]},{c[1]}" for c in sorted(strategy.archive)])
plt.show()
