Note
Go to the end to download the full example code or to run this example in your browser via Binder.
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)}")

<Axes: title={'left': 'frequent scenarios starting with O1084'}>
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)

observed: ['O1084', 'O1085']
next probability support context
0 O1084 0.518784 290 O1084 → O1085
1 O1085 0.250447 140 O1084 → O1085
2 O1133 0.239714 134 O1084 → O1085
3 O1080 0.216458 121 O1084 → O1085
4 O1081 0.148479 83 O1084 → O1085
<Axes: title={'left': 'what comes next? (confidence of the extensions of the longest matching frequent sequence)'}>
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()
top-1 accuracy on 421 traces: 0.38
Total running time of the script: (0 minutes 1.076 seconds)