"""
First steps: four sequences of the PrefixSpan paper
====================================================

The database of Pei et al. (2001) has four customers; each bought itemsets
(several items at once) in a sequence. A *sequential pattern* is a sequence of
itemsets contained, in order, in at least ``min_support`` customers. We mine the
patterns contained in at least half of the customers and show them as a glyph
table: events as colored tiles, simultaneous items stacked, the support and the
confidence of the last extension as bars.
"""

# %%
# The data and the patterns
# -------------------------
import matplotlib.pyplot as plt

import spmviz as sv
from spmviz.viz import plot_patterns
db = sv.datasets.load_prefixspan_example()
for sid, s in zip(db.ids, db):
    print(sid, sv.format_pattern(s, "angle"))

ps = sv.mine(db, min_support=0.5)          # in at least 2 of the 4 sequences
print(len(ps), "frequent sequential patterns")
print(ps.to_frame().head(12)[["pattern", "support", "confidence"]])
# %%
# A glyph table of the longest patterns
# -------------------------------------
# Long patterns are the interesting ones; ``sort("length")`` puts them first.
plot_patterns(ps.filter(min_length=3), top=12, by="length")

# %%
# Closed and maximal patterns
# ---------------------------
# Many of the 53 patterns repeat each other: a pattern is *closed* if no longer
# pattern has the same support, *maximal* if no longer pattern is frequent at
# all. The lossless closed set and the compact maximal set are what we usually draw.
print(len(ps.closed()), "closed,", len(ps.maximal()), "maximal")
print(ps.maximal().labels("angle"))
# %%
# Parameter study: the minimum support
# ------------------------------------
# Lowering the threshold makes the number of patterns explode; the closed and the
# maximal sets grow much more slowly.
counts = sv.measures.pattern_counts(db, [1.0, 0.75, 0.5, 0.25])
print(counts)
sv.viz.plot_explosion(counts)
plt.show()
