"""
Case study: early warning in alarm management
=============================================

Operators of a chemical plant face alarm floods. Frequent sequences of alarms
and operator actions (Bántay et al., 2023; Bántay & Abonyi, 2024) give two aids:
a map of the typical scenarios, and an online prediction of the next event from
the longest frequent sequence that matches the alarms seen so far.
"""

import matplotlib.pyplot as plt

import spmviz as sv
from spmviz.viz import plot_prediction, plot_prefix_tree

db = sv.datasets.load_alarm_log()
ps = sv.mine(db, 0.01, algorithm="cmspam", max_gap=2, max_length=10)

# %%
# Scenario trees of the most frequent alarm
# -----------------------------------------
top_alarm = ps.filter(max_length=1).sort("support").patterns[0][0][0]
plot_prefix_tree(ps.filter(starts_with=top_alarm), max_depth=4, max_children=3, title=f"frequent scenarios starting with {db.label(top_alarm)}")

# %%
# Online prediction
# -----------------
long = ps.filter(min_length=3).sort("support").patterns[0]
observed = [e[0] for e in long[:2]]
print("observed:", [db.label(i) for i in observed])
print(sv.predict_next(ps, observed))
plot_prediction(ps, observed)
# %%
# How often is the top prediction right?
# --------------------------------------
# Leave-one-out on the traces would be the honest test; here, a quick check on
# the traces that contain the observed prefix.
hits = total = 0
for s in db:
    items = [e[0] for e in s]
    for j in range(len(items) - 2):
        if items[j:j + 2] == observed:
            pred = sv.predict_next(ps, observed, k=1)
            total += 1
            hits += int(len(pred) and pred.iloc[0]["next"] == db.label(items[j + 2]))
            break
print(f"top-1 accuracy on {total} traces: {hits / max(total, 1):.2f}")
plt.show()
