"""
NBVFS-TM: transaction-based MDS map
====================================

The third map ignores the tree structure: two sequences are similar when they
are supported by the same traces (Jaccard similarity of their supporting
sequence sets). Groups of sequences that occur together — the events of a
sub-process running in parallel with others — form clusters. The synthetic
alarm floods below interleave cascades of four sub-processes (pump, cooling,
compressor, separator) with nuisance alarms; the TM map separates the four
cascades without knowing them.
"""

import matplotlib.pyplot as plt

import spmviz as sv

# %%
# Interleaved alarm cascades
# --------------------------
db = sv.datasets.make_alarm_cascades(600, random_state=0)
print(db.attributes["scenario"].value_counts().head())
ps = sv.mine(db, min_support=0.05, max_length=5)
tm = sv.NBVFS("tm").fit(ps)
tm.plot(labels=14)
# %%
# The same map for the cooling cascade only
# -----------------------------------------
tm.plot(start_items=["C-HITEMP", "C-HIPRES", "C-VALVE", "OP-COOLADJ"], labels=10,
        title="NBVFS-TM, sequences of the cooling sub-process highlighted")

# %%
# Parameter study: the minimum support
# ------------------------------------
# Lower supports add rare combinations (cascades mixed with nuisance alarms)
# between the clusters; higher supports keep only the cores.
fig, axes = plt.subplots(1, 3, figsize=(15, 4.6))
for ax, ms in zip(axes, (0.03, 0.06, 0.12)):
    p = sv.mine(db, ms, max_length=5)
    sv.NBVFS("tm").fit(p).plot(ax=ax, legend=False, labels=0, title=f"min support {ms}: {len(p)} sequences")
plt.show()
