"""
Explaining operating regimes
============================

Once the regimes of a process are found, the operators need to know what
they mean. A shallow decision tree turns the state labels into readable
rules on the process variables; the regime transition network shows how
the process moves between them; the boundary contributions tell which
variables changed at every switch.
"""

import matplotlib.pyplot as plt

import mvtsa as mv
from mvtsa import segmentation as sg
from mvtsa.explain import (
    boundary_contributions,
    explain_states,
    transition_graph,
)

X, cps, states = mv.datasets.make_regime_process(
    n_regimes=3, n_segments=12, length=120, random_state=6
)
names = ["temperature", "pressure", "flow", "level"]
seg = sg.GaussianHMMSegmenter(n_states=3, sticky=10, min_duration=15).segment(
    X
)

# %%
# Rules
# -----
ex = explain_states(X, seg, names=names, max_depth=2)
print(f"training accuracy of the rules: {ex['accuracy']:.3f}")
print(ex["rules"])
print(ex["importances"].round(3))
# %%
# Transitions and their causes
# ----------------------------
G = transition_graph(seg)
for a, b in G.edges:
    print(
        f"{a} -> {b}: {G.edges[a, b]['count']} times, p = {G.edges[a, b]['probability']:.2f}"
    )
print(boundary_contributions(X, seg, kind="all", names=names).round(2).head())
fig, axes = plt.subplots(
    1, 2, figsize=(9, 3.6), gridspec_kw={"width_ratios": [2, 1]}
)
mv.viz.plot_segmentation(X, seg, truth=cps, ax=axes[0])
mv.viz.plot_transition_graph(G, ax=axes[1])
plt.show()
