r"""
Association rules as a directed hypergraph
==========================================

Rules :math:`A\Rightarrow C` are hyperarcs from the antecedent to the
consequent set. Their confidence, lift and Zhang's metric quantify the
strength of the association; the weights of association-rule hypergraph
partitioning (Han et al. 1997) turn the frequent itemsets into a weighted
hypergraph whose clusters group mutually predictive themes.
"""

# %%
import matplotlib.pyplot as plt

import hatvis as hv

T = hv.datasets.make_news_transactions(150, random_state=0)
fi = hv.frequent_itemsets(T, min_support=0.04)
# [snippet:rules]
rules = hv.association_rules(fi, min_confidence=0.6)
D = hv.patterns.rule_hypergraph(rules.head(30))
w = hv.patterns.arhp_weights(fi)
W = hv.itemset_hypergraph(fi, min_size=2).with_weights(w.reindex(fi[fi["size"] >= 2]["itemset"]).to_numpy())
clusters = hv.hypergraph_louvain(W, random_state=0)
# [/snippet:rules]
print(rules.head(8)[["antecedent", "consequent", "support", "confidence", "lift", "zhang"]].to_string())
print(D)
for c, m in enumerate(hv.community.communities(clusters)):
    print(f"cluster {c}: {m}")

# %%
fig, ax = plt.subplots(figsize=(6.5, 4.5))
sc = ax.scatter(rules["support"], rules["confidence"], c=rules["lift"], cmap="viridis", s=18)
plt.colorbar(sc, ax=ax, label="lift")
ax.set_xlabel("support")
ax.set_ylabel("confidence")
plt.tight_layout()
