r"""
Simpliciality and nestedness: hypergraph or simplicial complex?
===============================================================

Simpliciality (Landry, Young and Eikmeier 2024) measures how close a
hypergraph is to a simplicial complex, in which every subset of a hyperedge
is itself a hyperedge. A simplicial complex, a random hypergraph and a
hypergraph of frequent itemsets (downward closed by construction) are
compared; node motifs of order three show the same contrast at the local
level.
"""

# %%
import matplotlib.pyplot as plt
import pandas as pd

import hatvis as hv

T = hv.datasets.make_news_transactions(150, random_state=0)
cases = {
    "simplicial complex": hv.representations.simplicial_closure(hv.models.uniform_random(12, 8, 4, random_state=0)),
    "random hypergraph": hv.models.random_hypergraph(30, [2, 3, 4] * 30, random_state=0),
    "frequent itemsets": hv.itemset_hypergraph(hv.frequent_itemsets(T, 0.05), min_size=2),
    "news articles": T,
}
# [snippet:simpliciality]
table = pd.DataFrame({name: pd.concat([hv.simpliciality(H, max_size=12), hv.metrics.nestedness(H)])
                      for name, H in cases.items()}).T
# [/snippet:simpliciality]
print(table[["simplicial fraction", "edit simpliciality", "face edit simpliciality", "included fraction"]].round(3).to_string())
motifs = pd.DataFrame({name: hv.motifs.node_motifs(H) for name, H in cases.items()}).T
print(motifs.to_string())

# %%
fig, ax = plt.subplots(figsize=(7.5, 3.8))
table[["simplicial fraction", "edit simpliciality", "face edit simpliciality"]].plot.bar(
    ax=ax, rot=0, color=hv.plotting.PALETTE[:3])
ax.set_ylim(0, 1.05)
ax.legend(frameon=False, fontsize=8)
plt.tight_layout()
