"""
Where does the process branch? The continuation-entropy tree
============================================================

A new view: the prefix tree of web-shop journeys colored by the *entropy of
what comes next* at every node, :math:`H=-\\sum_e P(e\\mid\\text{prefix})\\log_2 P(e\\mid\\text{prefix})`
(the end of the journey included). Green nodes have a predictable next step,
vermilion nodes are decision points where visitors scatter. For process
monitoring the vermilion nodes are where an early warning or a nudge pays off.
"""

import matplotlib.pyplot as plt

import spmviz as sv
from spmviz.viz import plot_prefix_tree
db = sv.datasets.make_customer_journeys(1000, random_state=0)
plot_prefix_tree(db, max_depth=4, min_count=25, color_by="entropy",
                 title="continuation entropy of the web-shop journeys")
# %%
# The numbers behind the colors
# -----------------------------
ps = sv.mine(db, 0.05, max_gap=1, max_length=4)
ct = sv.measures.continuation_table(ps)
print(ct.sort_values("entropy", ascending=False).head(8)[["pattern", "entropy", "top_next"]])

# %%
# Parameter study: history length
# -------------------------------
# Does a longer history make the next page more predictable? Mean entropy by prefix length:
ct["length"] = ps.lengths
print(ct.groupby("length")["entropy"].mean().round(2))
plt.show()
