r"""
Statistically validated hyperedges
==================================

Frequent is not the same as significant: groups of very active vertices
co-occur often by chance. Testing every observed group against the iterated
hypergeometric null model (after Musciotto et al. 2021) keeps only the
over-expressed hyperedges. A planted set of repeated groups among random
noise is recovered.
"""

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

import hatvis as hv

rng = np.random.default_rng(0)
nodes = [f"n{i}" for i in range(40)]
planted = [["n1", "n2", "n3"], ["n4", "n5", "n6"], ["n7", "n8"], ["n1", "n9", "n10", "n11"]]
edges = [g for g in planted for _ in range(6)]
edges += [list(rng.choice(nodes, size=rng.integers(2, 5), replace=False)) for _ in range(300)]
H = hv.Hypergraph(edges)
# [snippet:validate]
table = hv.patterns.validated_hyperedges(H, alpha=0.01, correction="bonferroni")
# [/snippet:validate]
print(table.head(8).to_string())
print("validated:", [sorted(s) for s in table.loc[table["validated"], "hyperedge"]])

# %%
fig, ax = plt.subplots(figsize=(6.5, 4))
ax.scatter(table["multiplicity"] + rng.normal(0, 0.05, len(table)), -np.log10(table["p_value"].clip(1e-300)),
           c=np.where(table["validated"], hv.plotting.PALETTE[1], hv.plotting.GRAY), s=16)
ax.set_xlabel("multiplicity of the vertex set")
ax.set_ylabel(r"$-\log_{10}p$")
plt.tight_layout()
