"""
A critical equation for reactor runaway
=======================================

An exothermic reactor runs away when heat generation outgrows heat removal.
Kummer, Varga and Abonyi (2019) formulated the prediction of runaway as a
classification problem whose decision boundary is an equation, and identified
the equation by genetic programming. :class:`~eqdisco.SymbolicClassifier` with
``decision="sign"`` does the same: the reactor is classified as running away
where the evolved :math:`f` is positive. With ``decision="logistic"`` the
probability of runaway is :math:`\\sigma(a+bf)`, and the parameters of the best
offspring are tuned on the cross-entropy. The labels come from the classical
Semenov criterion, so the true boundary is known. As in an Arrhenius plot, the
temperature enters as :math:`1000/T_0`.
"""

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

X, y = eq.datasets.make_runaway(800, random_state=0)
X.insert(0, "invT", 1000.0 / X.pop("T0"))  # Arrhenius coordinate
Xtr, ytr, Xte, yte = X.iloc[:500], y[:500], X.iloc[500:], y[500:]

# %%
# A critical equation and a probabilistic classifier
# --------------------------------------------------
funcs = ("add", "sub", "mul", "div", "log")
crit = eq.SymbolicClassifier(population_size=300, generations=30, decision="sign", functions=funcs, selection="double_tournament", random_state=0).fit(Xtr, ytr)
prob = eq.SymbolicClassifier(population_size=300, generations=30, decision="logistic", functions=funcs, optimize="lbfgs", parsimony=0.002, random_state=0).fit(Xtr, ytr)
print("critical equation:", eq.simplify.simplify(crit.equation_), "| test accuracy", crit.score(Xte, yte))
print("logistic model:   ", eq.simplify.simplify(prob.equation_), "| test accuracy", prob.score(Xte, yte))
fig, axs = plt.subplots(1, 2, figsize=(10, 3.6))
T0 = np.linspace(290, 350, 200)
UA = np.linspace(50, 500, 200)
G = np.array(np.meshgrid(T0, UA)).reshape(2, -1).T
grid = np.column_stack([1000.0 / G[:, 0], np.full(len(G), 1750.0), G[:, 1]])
for ax, m, title in ((axs[0], crit, "critical equation (sign)"), (axs[1], prob, "logistic probability")):
    z = m.decision_function(grid).reshape(200, 200) if m is crit else m.predict_proba(grid)[:, 1].reshape(200, 200)
    ax.contourf(T0, UA, z > (0 if m is crit else 0.5), levels=[-0.5, 0.5, 1.5], colors=["#E3EEF7", "#FBE3D6"])
    ax.contour(T0, UA, z, levels=[0 if m is crit else 0.5], colors=["#285780"], linewidths=2)
    sel = (np.abs(X["c0"] - 1750) < 300).to_numpy()
    ax.scatter(1000.0 / X.loc[sel, "invT"], X.loc[sel, "UA"], c=np.where(y[sel] == 1, "#D55E00", "#0072B2"), s=8, alpha=0.7)
    ax.set_xlabel("coolant temperature $T_0$ (K)")
    ax.set_ylabel("heat transfer UA (W/K)")
    ax.set_title(title + ", $c_0\\approx$ 1750", fontsize=9)
fig.tight_layout()

# %%
# Parameter study: label noise
# ----------------------------
noise = [0.0, 0.05, 0.1, 0.2]
acc = []
for ln in noise:
    Xn, yn = eq.datasets.make_runaway(800, random_state=1, label_noise=ln)
    Xn.insert(0, "invT", 1000.0 / Xn.pop("T0"))
    m = eq.SymbolicClassifier(population_size=200, generations=15, decision="logistic", functions=funcs, optimize="lbfgs", random_state=0).fit(Xn.iloc[:500], yn[:500])
    acc.append(m.score(X, y))  # accuracy against the noise-free labels
print("label noise", noise, "accuracy on clean labels", np.round(acc, 3).tolist())
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(noise, acc, "o-", color="#285780")
ax.set_xlabel("share of flipped training labels")
ax.set_ylabel("accuracy on clean labels")
plt.show()
