r"""
Community detection on a planted-partition hypergraph
=====================================================

A hypergraph stochastic block model with four communities is clustered by
the Louvain-type maximization of the strict hypergraph modularity, by
Louvain on the clique expansion, by spectral clustering with the hypergraph
Laplacian and by label propagation. The adjusted Rand index (ARI) against the
planted partition is reported as the share of intra-community hyperedges
:math:`p_\mathrm{in}` decreases.
"""

# %%
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.metrics import adjusted_rand_score

import hatvis as hv

rows = []
for p_in in (0.9, 0.75, 0.6, 0.45, 0.3):
    H, truth = hv.models.planted_partition(120, 4, 300, sizes=(2, 3, 4, 5), p_in=p_in, random_state=0)
    # [snippet:methods]
    methods = {
        "hypergraph Louvain": hv.hypergraph_louvain(H, random_state=0),
        "clique Louvain": hv.louvain(H, random_state=0),
        "spectral (Zhou)": hv.spectral_clustering(H, 4, random_state=0),
        "label propagation": hv.label_propagation(H, random_state=0),
    }
    # [/snippet:methods]
    for name, lab in methods.items():
        rows.append({"p_in": p_in, "method": name, "ARI": adjusted_rand_score(truth, lab),
                     "Q": hv.modularity(H, lab), "communities": lab.nunique()})
df = pd.DataFrame(rows)
print(df.pivot(index="p_in", columns="method", values="ARI").round(3))

# %%
fig, ax = plt.subplots(figsize=(7, 4))
for k, (name, sub) in enumerate(df.groupby("method", sort=False)):
    ax.plot(sub["p_in"], sub["ARI"], "o-", label=name, color=hv.plotting.PALETTE[k])
ax.set_xlabel(r"share of intra-community hyperedges $p_\mathrm{in}$")
ax.set_ylabel("adjusted Rand index")
ax.invert_xaxis()
ax.legend(frameon=False)
plt.tight_layout()
