"""
Pattern-induced higher-order networks: when history matters
===========================================================

The transition graph assumes that the next step depends only on the current
one. In the daily routines it does not: after *work* people go to *lunch* if they
came from the morning commute, but *commute* home if they came from lunch. A
higher-order network (Xu, Wickramarathne & Chawla, 2016) keeps such memory
nodes — ``work|commute`` is "work, reached after commute" — only where the
frequent sequences change the continuation distribution significantly
(Kullback–Leibler divergence above :math:`k/\\log_2(1+\\sigma)`).
"""

import matplotlib.pyplot as plt

import spmviz as sv
from spmviz.networks import higher_order_network
from spmviz.viz import plot_hon

db = sv.datasets.make_daily_routines(300, random_state=0)
H = higher_order_network(db, max_order=3, min_support=10)
memory = [v for v, d in H.nodes(data=True) if d["order"] > 1]
print(len(memory), "memory nodes:", memory[:8])
for v in ("work|commute", "work|lunch"):
    if v in H:
        print(v, "->", {w: round(d["probability"], 2) for _, w, d in H.out_edges(v, data=True)})
plot_hon(H)
# %%
# A first-order process has no memory
# -----------------------------------
# The web-shop journeys are generated by a first-order Markov chain: no memory node survives.
shop = sv.datasets.make_customer_journeys(1000, random_state=0)
plot_hon(shop, min_support=20)

# %%
# Parameter study: the threshold
# ------------------------------
for thr in (None, 0.1, 0.5, 1.0):
    Ht = higher_order_network(db, max_order=3, min_support=10, threshold=thr)
    print(f"threshold {thr}: {sum(d['order'] > 1 for _, d in Ht.nodes(data=True))} memory nodes")
plt.show()
