"""
NBVFS-CM: confidence-based MDS map
===================================

The weighted network only links a sequence with its direct extensions. The CM
map gives every pair of sequences a similarity: adjacent sequences have the
confidence of their extension, and sequences further apart in the same tree the
largest product of confidences along a path (a max-product transitive closure
:math:`\\mathbf{A}^*`). Metric multidimensional scaling of
:math:`\\mathbf{D}=\\mathbf{1}-\\mathbf{A}^*` places similar sequences close
together; node size is the support, color the starting event, edges join a
sequence to its parent.
"""

import matplotlib.pyplot as plt

import spmviz as sv
from spmviz.networks import confidence_matrix, transitive_confidence

db = sv.datasets.load_clickstream()
ps = sv.mine(db, 0.01, algorithm="cmspam", max_gap=1, max_length=10)

# %%
# The enriched confidence matrix
# ------------------------------
A = confidence_matrix(ps)              # a_ij = c(phi_j) if phi_i is the parent of phi_j
S = transitive_confidence(A)           # max-product closure of max(A, A^T)
print("non-zero similarities:", (A > 0).sum(), "->", (S > 0).sum() - len(ps))
# %%
# The map, highlighting three starting events
# -------------------------------------------
cm = sv.NBVFS("cm").fit(ps)
print("normalized stress:", round(cm.stress_, 3))
cm.plot(start_items=[2, 3, 4], labels=16)
# %%
# Parameter study: projection method
# ----------------------------------
# Classical scaling is deterministic and fast; SMACOF minimizes the stress
# (default); a neighbourhood method keeps local groups but distorts distances.
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
for ax, method in zip(axes, ("classical", "smacof")):
    m = sv.NBVFS("cm", mds=method).fit(ps)
    m.plot(ax=ax, legend=False, labels=8, title=f"{method}: stress {m.stress_:.2f}")
plt.show()
