r"""
Hyper-cores
===========

The :math:`(k,m)`-hyper-core keeps the vertices that belong to at least
:math:`k` hyperedges with at least :math:`m` members inside the core
(Mancastroppa et al. 2023). The core numbers for growing :math:`m` and the
resulting hyper-coreness reveal a densely interacting nucleus in a
synthetic hypergraph with a planted core.
"""

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

import hatvis as hv

rng = np.random.default_rng(0)
core = [f"c{i}" for i in range(8)]
periph = [f"p{i}" for i in range(40)]
edges = [list(rng.choice(core, size=rng.integers(3, 6), replace=False)) for _ in range(25)]
edges += [list(rng.choice(core + periph, size=rng.integers(2, 4), replace=False)) for _ in range(60)]
H = hv.Hypergraph(edges)
# [snippet:cores]
cores = pd.DataFrame({f"m={m}": hv.hypercore_numbers(H, m) for m in range(2, 6)})
R = hv.hypercoreness(H)
# [/snippet:cores]
print(cores.loc[core + periph[:4]])
print("top 8 by hyper-coreness:", list(R.sort_values(ascending=False).index[:8]))

# %%
fig, axes = plt.subplots(1, 2, figsize=(11, 4.2))
for m in cores.columns:
    axes[0].plot(range(len(cores)), cores[m].sort_values(ascending=False).to_numpy(), label=m)
axes[0].set_xlabel("vertices (sorted)")
axes[0].set_ylabel("core number")
axes[0].legend(frameon=False)
hv.plotting.plot_ranking(R, top=12, ax=axes[1], title="hyper-coreness")
plt.tight_layout()
