r"""
Frequent itemsets as a hypergraph
=================================

Frequent theme combinations of the news articles form a weighted hypergraph:
every frequent itemset is a hyperedge, its support the weight. Eclat and
Apriori give identical results; closed and maximal itemsets compress the
pattern set, and the inclusion lattice (Hasse diagram) of the closed
itemsets shows how the combinations nest.
"""

# %%
import matplotlib.pyplot as plt

import hatvis as hv
from hatvis.plotting import draw_hypergraph, plot_lattice

T = hv.datasets.make_news_transactions(150, random_state=0)
# [snippet:mine]
fi = hv.frequent_itemsets(T, min_support=0.05)
same = fi.equals(hv.frequent_itemsets(T, min_support=0.05, algorithm="apriori"))
closed = hv.closed_itemsets(fi)
maximal = hv.maximal_itemsets(fi)
IH = hv.itemset_hypergraph(closed[closed["support"] >= 0.08], min_size=2)
# [/snippet:mine]
print(f"{len(fi)} frequent, {len(closed)} closed, {len(maximal)} maximal itemsets; eclat == apriori: {same}")
print(maximal.head(6).to_string())

# %%
fig, ax = plt.subplots(figsize=(9, 7))
draw_hypergraph(IH.remove_isolated(), layout="force", style="smooth", width_by="weight", ax=ax, legend=False,
                pad=0.02, random_state=0, title="closed itemsets with support of at least 8%")
plt.tight_layout()

# %%
climate = {"CLIMATE", "EMISSIONS", "IPCC", "TEMPERATURE"}
sub = fi[fi["itemset"].map(lambda x: x <= climate)]
G = hv.patterns.inclusion_lattice(sub["itemset"], weights=sub["support"])
plot_lattice(G, title="inclusion lattice of the frequent itemsets of the climate narrative")
plt.gcf().set_size_inches(10, 4.8)
plt.tight_layout()
