"""
Grade transitions of a polymerization reactor
=============================================

A polymer plant produces several grades -- here three target molecular
weights of poly(methyl methacrylate) -- and switches between them. The
historical record of such a plant is the raw material of three questions
studied by Dobos, Bankó and Abonyi: where are the steady grades and the
transitions, which grade is the reactor in, and which periods carry
information on the kinetic parameters. The isothermal MMA reactor of
Doyle, Ogunnaike and Pearson (1995) produces the data.
"""

import matplotlib.pyplot as plt
import numpy as np

import mvtsa as mv
from mvtsa import segmentation as sg
from mvtsa.datasets import MMA_PARAMETERS, simulate_mma_cstr
from mvtsa.explain import transition_graph

# %%
# A campaign of grade changes
# ---------------------------
# Initiator flow profile: three grades, ramped transitions, small random
# moves of the operators; sampling time 0.05 h.
rng = np.random.default_rng(2)
grades = {"A": 0.012, "B": 0.0168, "C": 0.026}
plan = ["A", "B", "C", "B", "A", "C", "A"]
FI = []
for g in plan:
    level = grades[g]
    if FI:
        FI.extend(np.linspace(FI[-1], level, 20))  # ramped transition
    FI.extend(level * (1 + 0.03 * np.repeat(rng.normal(size=8), 10)))
FI = np.asarray(FI)
Mn = simulate_mma_cstr(FI) * (1 + 0.003 * rng.normal(size=len(FI)))
X = np.column_stack([FI * 1000, Mn / 1000])  # L/h and kg/mol

# %%
# Steady grades and transitions
# -----------------------------
# Segment-and-cluster: a penalized bottom-up segmentation followed by the
# clustering of the Gaussian segment models into three states.
seg = sg.StateSegmenter(
    segmenter=sg.BottomUp("normal", penalty=40, initial_size=10), n_states=3
).segment(X)
print("segments:", seg.n_segments, "| grade sequence:", seg.labels.tolist())
G = transition_graph(seg, sampling_period=0.05)
print(
    {v: round(G.nodes[v]["total_duration"], 1) for v in G.nodes},
    "hours per state",
)
# %%
# The plan was A, B, C, B, A, C, A. The two direct transitions between A and
# C pass through the molecular weight of grade B, and are labelled B: the
# state sequence reads A, B, C, B, A, (B), C, (B), A.
fig, axes = plt.subplots(
    2, 1, figsize=(7, 4.6), sharex=True, gridspec_kw={"height_ratios": [3, 1]}
)
mv.viz.plot_segmentation(
    X, seg, names=["$F_I$ (L/h)", "$M_n$ (kg/mol)"], ax=axes[0]
)
mv.viz.plot_states(seg, ax=axes[1])

# %%
# Which periods identify the kinetics?
# ------------------------------------
names = ["kp", "kI"]
p0 = np.array([MMA_PARAMETERS[k] for k in names])
S = sg.finite_difference_sensitivities(
    lambda p: simulate_mma_cstr(FI, params=dict(zip(names, p, strict=True))),
    p0,
    rel_step=1e-4,
)
fs = sg.FisherSegmenter(
    n_segments=seg.n_segments, criterion="logD", window=20, initial_size=10
).fit(S)
print(
    fs.ranking_[["start", "stop", "logD"]]
    .head(5)
    .round(2)
    .to_string(index=False)
)
# %%
# The transitions are the informative periods; long steady operation adds
# little, in line with the segmentation-based experiment design of Dobos et
# al. (2009).
fig, ax = plt.subplots(figsize=(7, 2.4))
ax.plot(fs.criterion_, color="#009E73")
ax.set_ylabel("log det $F$ (window 20)")
ax.set_xlabel("sample")
for c in seg.change_points:
    ax.axvline(c, color="gray", ls=":", lw=0.8)
plt.show()
