"""
NBVFS-WN: the weighted extension network
=========================================

Bántay & Abonyi (2024) draw frequent sequences as a network: every sequence is a
node, and an edge joins it to each of its one-event extensions. The edge weight
is the *confidence* of the extension, :math:`c(\\varphi_j)=\\sigma(\\varphi_j)/\\sigma(\\varphi_i)`:
the share of the sequences containing :math:`\\varphi_i` that continue with the
added event. Node color is the length, node size the cumulative confidence (the
share of the start event's sequences that reach the node). With a maximum gap
the frequent sequences are prefix-closed, so the network is a forest rooted at
the frequent single events.

The data are the UWV clickstream of the paper (343 sessions, 14 services); as in
the paper, CM-SPAM mines it with 1% minimum support, maximum gap 1 and maximum
length 10.
"""

import matplotlib.pyplot as plt

import spmviz as sv

# %%
# Mining as in the paper
# ----------------------
db = sv.datasets.load_clickstream()
ps = sv.mine(db, min_support=0.01, algorithm="cmspam", max_gap=1, max_length=10)
print(ps, "lengths", ps.lengths.min(), "-", ps.lengths.max())
print({k: db.label(k) for k in range(4)})
# %%
# Circle layout: one starting event in the center
# -----------------------------------------------
# The paper filters the network by the starting event; event 2 is "Hours worked".
wn = sv.NBVFS("wn", layout="circle", start_items=[2]).fit(ps)
wn.plot(labels=20, title="NBVFS-WN, sequences starting with 'Hours worked'")
# %%
# Hierarchical layout of all trees
# --------------------------------
sv.NBVFS("wn", layout="hierarchical", start_items=[0, 1, 2, 3]).fit(ps).plot(labels=12)

# %%
# Parameter study: pruning weak extensions
# ----------------------------------------
# Edges below a confidence threshold (and the subtrees below them) disappear; the
# strong continuations of a process stand out.
fig, axes = plt.subplots(1, 3, figsize=(14, 4.8))
for ax, mc in zip(axes, (0.0, 0.2, 0.4)):
    m = sv.NBVFS("wn", start_items=[2], min_confidence=mc).fit(ps)
    m.plot(ax=ax, legend=False, labels=10, title=f"min confidence {mc}: {m.graph_.number_of_nodes()} nodes")
plt.show()
