"""
Beyond the paper: fused similarities and pattern communities
=============================================================

The paper closes with two open questions: how to *combine* similarity measures,
and how to *segment* the network into groups. Here the confidence (tree
structure), transaction (co-occurrence) and content (longest common
subsequence) similarities are fused by similarity network fusion (Wang et al.,
2014), and Louvain communities of the similarity graph are extracted. Each
community is a candidate sub-process; its supporting traces form a sub-log.
"""

import matplotlib.pyplot as plt

import spmviz as sv
from spmviz.networks import pattern_communities, sublogs
from spmviz.viz import plot_communities, plot_transition_graph

db = sv.datasets.make_alarm_cascades(600, random_state=0)
ps = sv.mine(db, 0.05, max_length=5).filter(min_length=2)

# %%
# The fused map
# -------------
fused = sv.NBVFS("fused").fit(ps)
fused.plot(labels=14)
# %%
# Communities and sub-logs
# ------------------------
labels, modularity, G = pattern_communities(ps, similarity="transaction", knn=8)
print(f"{labels.max() + 1} communities, modularity {modularity:.2f}")
parts = sublogs(ps, labels)
for c, sub in parts.items():
    print(c, len(sub), "traces", sub.attributes["scenario"].value_counts().index[0])
plot_communities(ps, knn=8)

# %%
# One sub-log as a process map
# ----------------------------
plot_transition_graph(parts[0], top_edges=20, title="transition graph of the traces of community 1")

# %%
# Parameter study: resolution
# ---------------------------
for r in (0.5, 1.0, 2.0):
    lab, mod, _ = pattern_communities(ps, knn=8, resolution=r)
    print(f"resolution {r}: {lab.max() + 1} communities, modularity {mod:.2f}")
plt.show()
