"""
Informative segments for parameter estimation (MMA polymerization)
==================================================================

Which parts of a long operating record are worth using to identify a
process model? Dobos, Bankó and Abonyi (2009) answer it with optimal
experiment design: the Fisher information matrix of a time window, built
from the output sensitivities with respect to the model parameters, tells
how much the window says about the parameters. The criterion series is
segmented, and the segments are ranked by information. The case study is
the isothermal free-radical polymerization of methyl methacrylate in a
CSTR (Doyle, Ogunnaike and Pearson, 1995).
"""

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import segmentation as sg
from mvtsa.datasets import MMA_PARAMETERS, simulate_mma_cstr

# %%
# An operating record
# -------------------
# Constant operation, a grade change, excitation by random steps, and
# constant operation again (sampling time 0.05 h).
rng = np.random.default_rng(0)
FI = np.r_[
    np.full(100, 0.016783),
    np.full(100, 0.025),
    0.02 + 0.006 * np.repeat(rng.choice([-1, 1], 20), 5),
    np.full(100, 0.016783),
]
y = simulate_mma_cstr(FI)

# %%
# Sensitivities and Fisher-information segmentation
# -------------------------------------------------
names = ["kp", "kI", "kfm"]
p0 = np.array([MMA_PARAMETERS[k] for k in names])


def simulate(p):
    return simulate_mma_cstr(FI, params=dict(zip(names, p, strict=True)))


S = sg.finite_difference_sensitivities(
    simulate, p0, rel_step=1e-4
)  # (T, 1, 3), scaled
fs = sg.FisherSegmenter(
    n_segments=5, criterion="logD", window=20, initial_size=10
).fit(S)
print(fs.segmentation_.change_points)
print(fs.ranking_[["segment", "start", "stop", "logD", "E"]].round(2))
# %%
# The excitation period and the transient of the grade change carry the
# information; the constant operating periods add almost nothing, so they
# can be left out of the identification data set.

fig, axes = plt.subplots(3, 1, figsize=(7, 5.5), sharex=True)
axes[0].step(np.arange(len(FI)), FI, color="#285780", where="post")
axes[0].set_ylabel("$F_I$ (m³/h)")
axes[1].plot(y / 1000, color="#E69F00")
axes[1].set_ylabel("$M_n$ (kg/mol)")
axes[2].plot(fs.criterion_, color="#009E73")
axes[2].set_ylabel("log det $F$")
axes[2].set_xlabel("sample")
for ax in axes:
    for c in fs.segmentation_.change_points:
        ax.axvline(c, color="gray", ls=":", lw=1)

# %%
# Parameter study: the window of the criterion series
# ---------------------------------------------------
# A short window localizes the transients sharply but splits the excitation
# period; a long one blurs the boundaries.
for w in (10, 20, 40):
    f = sg.FisherSegmenter(
        n_segments=5, criterion="logD", window=w, initial_size=10
    ).fit(S)
    best = f.ranking_.iloc[0]
    print(
        f"window {w}: change points {f.segmentation_.change_points}, most informative {int(best.start)}-{int(best.stop)}"
    )
plt.show()
