"""
Everything is logged: genealogy, lineage and the map of a session
=================================================================

A :class:`~easyiec.Session` records every individual ever created (shown or
not), every query and every answer with cumulative counters of items, decisions,
human answers and API cost. The log is the raw material of every analysis and
plot in the package and can be saved to JSON and reloaded.
"""

# %%
# A logged session with the EASY-IEC algorithm
# --------------------------------------------
# The superformula of Gielis (2003) draws logos with 13 genes. The EASY-IEC
# strategy keeps the evaluator's *selected* individuals as parents and copies
# the ones marked *keep* unchanged (Madár et al., 2005).
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.problems import SuperShape
from easyiec.strategies import EasyIEC

problem = SuperShape()
user = ei.SimulatedUser(problem, target="random", noise=0.04, seed=11)
session = ei.Session(problem, EasyIEC(pop_size=9), user, seed=11)
result = session.run(15)
log = result.log
print(len(log.individuals), "individuals created,", len(log.shown_ids()), "shown")
print(log.to_frame()[["step", "n_items_cum", "n_decisions_cum", "best_true"]].tail(4))
session.save("supershape_session.json")
again = ei.core.log.SessionLog.load("supershape_session.json")
print(len(again.records), "records restored")
# %%
# The genealogy
# -------------
# Each dot is a shown individual, placed by generation; lines lead to parents.
# Chosen individuals are filled; the line of descent of the best one is drawn
# thick.
ei.viz.plot_genealogy(log)

# %%
# The line of descent of the best individual
# ------------------------------------------
# A lineage follows the first parent back to the initial population.
ei.viz.plot_lineage(log, problem, size=1.0)

# %%
# The map of the session
# ----------------------
# Classical multidimensional scaling places the shown genomes in the plane;
# colour codes the generation. The population contracts towards the region the
# evaluator liked.
ei.viz.plot_embedding(log, problem, method="mds", color="generation")
plt.show()
