"""
Designing a beer fermentation temperature profile
=================================================

The temperature profile of a lager fermentation trades batch time against
flavour: warm fermentation is fast but produces diacetyl and esters, cold
fermentation is clean but slow (de Andrés-Toro et al., 1998). The model of the
Simulink library used in the EASY-IEC paper describes sugar, ethanol, biomass,
diacetyl and ethyl acetate. The profile is a piecewise-linear curve through six
knots between 9 and 16 °C; the evaluator sees the profile and the predicted
concentrations and can *drag the knots* directly (the Lamarckian edit protocol
of EASY-IEC).
"""

# %%
# Presets and their outcomes
# --------------------------
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.problems import BeerFermentation
from easyiec.strategies import InteractiveGA

problem = BeerFermentation()
for name, x in problem.presets().items():
    o = problem.objectives(x)
    print(f"{name:18s} ethanol {o['ethanol']:.1f} g/L, batch time {o['batch_time']:.0f} h, "
          f"diacetyl {o['diacetyl']:.2f} ppm, ethyl acetate {o['ethyl_acetate']:.2f} ppm")

# %%
# Selections plus direct manipulation
# -----------------------------------
# The simulated brewer occasionally drags a knot of the chosen profile towards
# its own ideal (``edit_prob``); edited profiles enter the population as new
# individuals (origin ``"edit"``).
user = ei.SimulatedUser(problem, target="industrial-like", noise=0.04, edit_prob=0.3, edit_step=0.4, seed=5)
result = ei.run(problem, InteractiveGA(pop_size=8), user, generations=12, seed=5)
edits = [i for i in result.log.individuals.values() if i.origin == "edit"]
print(len(edits), "edited profiles;", problem.describe(result.best.genome))
ei.viz.plot_history(result.log, problem, steps=[0, 5, 11], max_items=8, size=1.3)

# %%
# The best profile
# ----------------
fig, ax = plt.subplots(figsize=(6, 5))
problem.render(result.best.genome, ax=ax)

# %%
# The genealogy shows where the edits entered
# -------------------------------------------
ei.viz.plot_genealogy(result.log)
plt.show()
