r"""
Semi-supervised learning and hyperedge prediction
=================================================

With labels for only a few vertices, hypergraph label spreading (Zhou et al.
2006), the same with class mass normalization, and a simplified hypergraph
neural network (HGNN propagation followed by logistic regression) classify
the rest. The accuracy is shown against the
fraction of labeled vertices. Hiding hyperedges and scoring them against
random vertex sets measures how predictable the higher-order structure is.
"""

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

import hatvis as hv

H, truth = hv.models.planted_partition(150, 3, 400, sizes=(2, 3, 4), p_in=0.75, random_state=0)
rng = np.random.default_rng(0)
rows = []
for frac in (0.02, 0.05, 0.1, 0.2, 0.4):
    for _rep in range(5):
        lab = truth.astype(float).where(rng.random(H.n_nodes) < frac)
        if lab.nunique() < 3:
            continue
        # [snippet:ssl]
        pred_ls = hv.learning.label_spreading(H, lab, alpha=0.9).idxmax(axis=1)
        pred_cm = hv.learning.label_spreading(H, lab, alpha=0.9, class_mass_normalization=True).idxmax(axis=1)
        pred_hg = hv.learning.hgnn_classifier(H, np.eye(H.n_nodes), lab, n_layers=2).astype(float)
        # [/snippet:ssl]
        rows.append({"labeled": frac, "label spreading": (pred_ls == truth).mean(),
                     "label spreading, class mass norm.": (pred_cm == truth).mean(),
                     "simplified HGNN": (pred_hg == truth).mean()})
acc = pd.DataFrame(rows).groupby("labeled").mean()
print(acc.round(3))
# [snippet:prediction]
pred = pd.DataFrame({m: hv.learning.hyperedge_prediction(H, method=m, random_state=0)
                     for m in ("mean_jaccard", "min_cooccurrence", "adamic_adar")}).T
# [/snippet:prediction]
print(pred.round(3))

# %%
fig, ax = plt.subplots(figsize=(6, 3.8))
acc.plot(ax=ax, marker="o", color=hv.plotting.PALETTE[:3])
ax.set_xscale("log")
ax.set_xlabel("fraction of labeled vertices")
ax.set_ylabel("accuracy")
ax.legend(frameon=False)
plt.tight_layout()
