"""
Operating regions of a pH neutralization process
================================================

The process gain of a pH reactor changes by orders of magnitude along the
titration curve, so a single linear model cannot describe it. Segmenting
the record by its local *dynamics* (dynamic PCA, Bankó, 2015) and fitting a
first-order ARX model to every segment shows how the local gain and time
constant depend on the operating point -- the information needed to
schedule a gain-scheduled controller.
"""

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

import mvtsa as mv
from mvtsa import segmentation as sg

P = mv.datasets.simulate_ph_cstr(T=960, random_state=3)

# %%
# Segmentation by local dynamics
# ------------------------------
seg = sg.DPCASegmenter(n_segments=8, lags="auto", n_components=0.99).segment(P)
rows = []
for a, b in seg.segments:
    u, y = P[a:b, 0], P[a:b, 1]
    A = np.column_stack([y[:-1], u[:-1], np.ones(b - a - 1)])
    (a1, b1, _), *_ = np.linalg.lstsq(A, y[1:], rcond=None)
    rows.append(
        {
            "start": a,
            "stop": b,
            "mean pH": y.mean(),
            "local gain": b1 / (1 - a1) if a1 < 1 else np.nan,
            "pole": a1,
        }
    )
print(pd.DataFrame(rows).round(3).to_string(index=False))
mv.viz.plot_segmentation(P, seg, names=["base flow", "pH"])

# %%
# Local gain against the operating point
# --------------------------------------
df = pd.DataFrame(rows)
fig, ax = plt.subplots(figsize=(4.8, 3.2))
ax.semilogy(df["mean pH"], np.abs(df["local gain"]), "o", color="#285780")
ax.set_xlabel("mean pH of the segment")
ax.set_ylabel("|local static gain|")
plt.show()
