"""
The industrial alarm log of the paper
=====================================

The log of a hydrofluoric-acid alkylation plant (Bántay & Abonyi, 2024): 28,536
alarms (codes 100–499, printed ``A…``) and operator actions (codes above 1000,
printed ``O…``) in 3,956 traces. As in the paper, CM-SPAM mines it with 1%
minimum support and maximum gap 2. The three maps answer three questions: which
alarm follows which (WN), which scenarios belong to the same alarm chain (CM),
and which scenarios occur in the same traces (TM).
"""

import matplotlib.pyplot as plt

import spmviz as sv
db = sv.datasets.load_alarm_log()
ps = sv.mine(db, min_support=0.01, algorithm="cmspam", max_gap=2, max_length=10)
print(ps, "lengths", ps.lengths.min(), "-", ps.lengths.max())
top = ps.filter(min_length=1, max_length=1).sort("support")
print("most frequent events:", top.labels()[:8])
# %%
# Weighted network of the most frequent starting alarm
# ----------------------------------------------------
start = top.patterns[0][0][0]
sv.NBVFS("wn", start_items=[start]).fit(ps).plot(labels=18)

# %%
# Confidence and transaction maps
# -------------------------------
fig, axes = plt.subplots(1, 2, figsize=(15, 6))
sv.NBVFS("cm").fit(ps).plot(ax=axes[0], legend=False, labels=12, start_items=top.start_items()[:3])
sv.NBVFS("tm").fit(ps).plot(ax=axes[1], legend=False, labels=12, start_items=top.start_items()[:3])

# %%
# Alarms and operator actions
# ---------------------------
# Which patterns end with an operator action, and how confident is the step to it?
ops = ps.filter(min_length=2).filter(mask=[db.label(p[-1][-1]).startswith("O") for p in ps.filter(min_length=2).patterns])
print(ops.sort("confidence").to_frame()[["pattern", "support", "confidence"]].head(10))
plt.show()
