"""
Five algorithms, one answer
===========================

The package implements PrefixSpan (pattern growth), SPAM and CM-SPAM (vertical
bitmaps, the algorithm used by Bántay & Abonyi, 2024), SPADE (vertical id-lists)
and GSP (level-wise). They differ in speed, never in the result: the same
patterns with the same supports and supporting sequences. External miners
(the ``prefixspan`` package, ``seq2pat``, ``gsppy``, SPMF) return the same
:class:`~spmviz.PatternSet` and can be compared in the same way.
"""

import time

import matplotlib.pyplot as plt
import numpy as np

import spmviz as sv

db = sv.datasets.make_customer_journeys(1000, random_state=1)

# %%
# Run all built-in miners
# -----------------------
results, times = {}, {}
for alg in ["prefixspan", "cmspam", "spam", "spade", "gsp"]:
    t0 = time.perf_counter()
    results[alg] = sv.mine(db, min_support=0.03, algorithm=alg, max_length=6)
    times[alg] = time.perf_counter() - t0
ref = results["prefixspan"]
for alg, ps in results.items():
    same = ps.patterns == ref.patterns and np.array_equal(ps.support, ref.support)
    print(f"{alg:10s} {len(ps):5d} patterns  {times[alg]:6.3f} s  identical={same}")
# %%
# An external back end
# --------------------
# The ``prefixspan`` package (PyPI) is used when installed.
try:
    ext = sv.mine(db, 0.03, algorithm="prefixspan-py", max_length=6)
    print("prefixspan-py:", len(ext), "patterns, identical:", dict(zip(ext.patterns, ext.support)) == dict(zip(ref.patterns, ref.support)))
except ImportError:
    print("the prefixspan package is not installed")

# %%
# Run times
# ---------
fig, ax = plt.subplots(figsize=(6, 3))
ax.barh(list(times), list(times.values()), color="#285780")
ax.set_xlabel("seconds")
ax.set_title("same patterns, different algorithms", loc="left", fontsize=10)
for s in ("top", "right"):
    ax.spines[s].set_visible(False)

# %%
# Parameter study: top-k instead of a threshold
# ---------------------------------------------
# When no sensible threshold is known, ask for the k most frequent patterns.
top = sv.topk(db, k=10, max_length=6)
print(top.to_frame()[["pattern", "support"]])
plt.show()
