"""
Episodes in one long alarm stream
=================================

Without trace boundaries, an alarm log is one long stream. Frequent *episodes*
(Mannila, Toivonen & Verkamo, 1997) are found in sliding windows: a serial
episode is ordered, a parallel one is a set. WINEPI counts the share of windows
containing the episode, MINEPI its minimal occurrences; the timeline shows the
minimal occurrences of the top episodes.
"""

import matplotlib.pyplot as plt

import spmviz as sv
from spmviz.viz import plot_episode_timeline

alarm = sv.datasets.load_alarm_log()
# the busiest day of the plant as a single stream (times in minutes)
log = sv.datasets.load_alarm_log(as_frame=True)
dates = log["timestamp"].dt.date
day = log[dates == dates.value_counts().index[0]]
events = [alarm.label(e) for e in day["event"]]
minutes = (day["timestamp"] - day["timestamp"].iloc[0]).dt.total_seconds().to_numpy() / 60
ep = sv.mine_episodes(events, times=minutes, window=10, min_frequency=0.02, max_length=3)
multi = ep.filter(min_length=2)
print(multi.to_frame().sort_values("frequency", ascending=False).head(8)[["pattern", "frequency", "minimal_occurrences"]])
plot_episode_timeline(ep, top=8)
# %%
# Parallel episodes
# -----------------
par = sv.mine_episodes(events, times=minutes, window=10, min_frequency=0.02, kind="parallel", max_length=3)
print(par.to_frame().sort_values("frequency", ascending=False).head(6)[["pattern", "frequency"]])
plt.show()
