"""
PID tuning by looking at step responses
=======================================

Control engineers judge a loop by its step response — rise, overshoot,
oscillation, the effort of the actuator, the recovery after a load disturbance
— and weigh these properties differently from plant to plant. This was the
first application of EASY-IEC (Madár, Abonyi and Szeifert, 2005). The plant is
a first-order process with dead time, :math:`G(s)=Ke^{-\\theta s}/(\\tau s+1)`;
the controller is a two-degree-of-freedom PID with setpoint weight *b* and
derivative filter *N*. The SIMC rules of Skogestad (2003) give a well-known
reference tuning.
"""

# %%
# An evaluator who prefers the SIMC response
# ------------------------------------------
import matplotlib.pyplot as plt

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

problem = PIDTuning(K=1.0, tau=10.0, theta=3.0)
simc = problem.presets()["SIMC"]
print(problem.describe(simc))
user = ei.SimulatedUser(problem, target="SIMC", noise=0.04, seed=3)
result = ei.run(problem, EasyIEC(pop_size=9), user, generations=12, seed=3)
print(problem.describe(result.best.genome))
# %%
# The first and the last gallery
# ------------------------------
ei.viz.plot_history(result.log, problem, steps=[0, 11], max_items=9, size=1.25)

# %%
# Best response against the SIMC reference
# ----------------------------------------
fig, axes = plt.subplots(1, 3, figsize=(11, 3.2))
for ax, (lab, x) in zip(axes, [("sluggish preset", problem.presets()["sluggish"]),
                               ("SIMC (Skogestad, 2003)", simc), ("best found by IEC", result.best.genome)]):
    problem.render(x, ax=ax)
    o = problem.objectives(x)
    ax.set_title(f"{lab}\nIAE {o['iae']:.1f}, overshoot {o['overshoot']:.0f} %", fontsize=8)
plt.show()
