"""
Controlling an exothermic reactor at its unstable steady state
==============================================================

A continuous stirred tank reactor with an exothermic first-order reaction has
three steady states; the middle one is open-loop unstable (Seborg et al.,
2016). The controller must move the reactor temperature from 350 K to 355 K and
reject a 3 K rise of the feed temperature without a dangerous temperature
excursion. Two controller families are tuned interactively: a PID with
setpoint weighting, and a dynamic matrix controller (DMC; Cutler and Ramaker,
1980) supervising a stabilizing inner proportional loop.
"""

# %%
# PID and DMC, the same simulated engineer
# ----------------------------------------
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.problems import CSTRControl
from easyiec.strategies import InteractiveCMAES

results = {}
for controller in ["pid", "dmc"]:
    problem = CSTRControl(controller=controller)
    user = ei.SimulatedUser(problem, target="default", noise=0.04, seed=2)
    results[controller] = (problem, ei.run(problem, InteractiveCMAES(pop_size=8), user, generations=12, seed=2))
    print(controller, problem.describe(results[controller][1].best.genome))
# %%
# The chosen responses
# --------------------
# Reactor temperature, coolant temperature and concentration for the best PID
# and the best DMC tuning.
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for ax, (c, (problem, res)) in zip(axes, results.items()):
    problem.render(res.best.genome, ax=ax)
    ax.set_title(f"{c.upper()}: best true utility {res.best_true:.2f}", fontsize=9)

# %%
# Progress of the two sessions
# ----------------------------
ax = None
for k, (c, (_, res)) in enumerate(results.items()):
    ax = ei.viz.plot_anytime(res, ax=ax, label=c.upper(), color=["#285780", "#D55E00"][k], show_shown=False)
ax.legend(frameon=False, fontsize=8)
plt.show()
