"""
Many objectives, one person: reference-point NSGA-II
====================================================

Controller tuning has several computable objectives (integral error,
overshoot, control effort, settling time) whose trade-off only a person can
settle. In the interactive NSGA-II the population evolves for a few silent
generations under Pareto dominance and crowding (Deb et al., 2002); then the
evaluator picks the responses they like, and the picks act as reference points
that bias the next silent phase (Deb and Sundar, 2006).
"""

# %%
# PID tuning with a hidden preferred trade-off
# --------------------------------------------
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.problems import PIDTuning
from easyiec.strategies import InteractiveNSGA2

problem = PIDTuning()
print(problem.objectives_names())
strategy = InteractiveNSGA2(pop_size=8, inner_size=40, inner_generations=5)
user = ei.SimulatedUser(problem, target="default", noise=0.05, seed=1)
result = ei.run(problem, strategy, user, generations=10, seed=1)
print(problem.describe(result.best.genome))
# %%
# The final inner population in objective space
# ---------------------------------------------
# Integral error against control effort (total variation of the input). Grey:
# the silent population; blue: its non-dominated front; circles: the last picks.
last = result.log.records[-1]
picked = [last.query.item(i) for i in last.feedback.chosen(last.query)]
pool = strategy.inner + [p for p in picked if p not in strategy.inner]
ei.viz.plot_pareto(problem, pool, objectives=["iae", "input_tv"], chosen=[p.id for p in picked])

# %%
# The step responses the user chose from in the last gallery
# ----------------------------------------------------------
ei.viz.plot_gallery(problem, last.query.items, chosen=last.feedback.chosen(last.query), ncols=8, size=1.4)
plt.show()
