r"""Random hypergraphs and null models.
Null models separate structure from chance: a pattern is interesting only if
it is rarer or more frequent than in random hypergraphs that share some basic
properties with the data (sizes, degrees, communities).
"""
from __future__ import annotations
import numpy as np
import pandas as pd
from .core import Hypergraph
__all__ = ["uniform_random", "random_hypergraph", "chung_lu", "configuration_model", "planted_partition",
"temporal_random"]
[docs]
def random_hypergraph(n: int, sizes, random_state=None, nodes=None) -> Hypergraph:
"""Random hypergraph with a prescribed size sequence (each hyperedge a uniform random subset)."""
rng = np.random.default_rng(random_state)
nodes = [f"v{i}" for i in range(n)] if nodes is None else list(nodes)
edges = [list(rng.choice(n, size=int(s), replace=False)) for s in sizes]
return Hypergraph([[nodes[i] for i in sorted(e)] for e in edges], nodes=nodes)
[docs]
def chung_lu(degrees, sizes, random_state=None) -> Hypergraph:
r"""Chung–Lu hypergraph: vertices enter a hyperedge with probability proportional to their degree.
``degrees`` is a mapping (or sequence) of target degrees, ``sizes`` the
size sequence. Expected degrees match the targets when no vertex dominates
(Aksoy et al. 2017).
"""
rng = np.random.default_rng(random_state)
if isinstance(degrees, (dict, pd.Series)):
nodes = list(degrees.keys()) if isinstance(degrees, dict) else list(degrees.index)
d = np.array([degrees[v] for v in nodes], dtype=float)
else:
d = np.asarray(degrees, dtype=float)
nodes = [f"v{i}" for i in range(len(d))]
p = d / d.sum()
edges = []
for s in sizes:
idx = rng.choice(len(nodes), size=int(min(s, (p > 0).sum())), replace=False, p=p)
edges.append([nodes[i] for i in sorted(idx)])
return Hypergraph(edges, nodes=nodes)
[docs]
def configuration_model(H: Hypergraph, n_steps: int | None = None, random_state=None) -> Hypergraph:
r"""Degree- and size-preserving randomization by pairwise reshuffles (Chodrow 2020).
A step picks two hyperedges :math:`e,f`, keeps their common vertices
:math:`e\cap f` in both, and redistributes the vertices of the symmetric
difference at random while keeping :math:`|e|` and :math:`|f|`. Every
vertex degree and hyperedge size is preserved and no hyperedge gets a
repeated vertex. ``n_steps`` defaults to ten times the number of hyperedges.
"""
rng = np.random.default_rng(random_state)
edges = [list(m) for _, m in H]
m = len(edges)
if m < 2:
return H.copy()
n_steps = 10 * m if n_steps is None else n_steps
for _ in range(n_steps):
a, b = rng.choice(m, size=2, replace=False)
ea, eb = set(edges[a]), set(edges[b])
common = ea & eb
rest = sorted((ea | eb) - common, key=str)
if not rest:
continue
rng.shuffle(rest)
na = len(ea) - len(common)
edges[a] = sorted(common | set(rest[:na]), key=str)
edges[b] = sorted(common | set(rest[na:]), key=str)
return Hypergraph(dict(zip(H.edges, edges, strict=True)), nodes=H.nodes, weights=H.weights,
name=f"configuration model of {H.name or 'H'}")
[docs]
def planted_partition(n: int, n_communities: int, m: int, sizes=(2, 3, 4), p_in: float = 0.8,
random_state=None) -> tuple[Hypergraph, pd.Series]:
r"""Hypergraph stochastic block model with planted communities.
Vertices are split into ``n_communities`` equal groups. Each of the ``m``
hyperedges draws its size uniformly from ``sizes``; with probability
``p_in`` all its vertices come from one random community, otherwise from
the whole vertex set. Returns the hypergraph and the ground-truth labels.
"""
rng = np.random.default_rng(random_state)
nodes = [f"v{i}" for i in range(n)]
labels = np.repeat(np.arange(n_communities), int(np.ceil(n / n_communities)))[:n]
members = [np.where(labels == c)[0] for c in range(n_communities)]
edges = []
for _ in range(m):
s = int(rng.choice(sizes))
if rng.random() < p_in:
pool = members[rng.integers(n_communities)]
else:
pool = np.arange(n)
s = min(s, len(pool))
edges.append([nodes[i] for i in sorted(rng.choice(pool, size=s, replace=False))])
H = Hypergraph(edges, nodes=nodes, name="planted partition")
return H, pd.Series(labels, index=nodes, name="community")
[docs]
def temporal_random(n: int, m_per_step: int, n_steps: int, sizes=(2, 3, 4), persistence: float = 0.5,
random_state=None):
"""Temporal hypergraph with tunable persistence: a fraction of the hyperedges is repeated from the last step."""
from .core import TemporalHypergraph
rng = np.random.default_rng(random_state)
nodes = [f"v{i}" for i in range(n)]
edges, times, prev = [], [], []
for t in range(n_steps):
cur = []
for _ in range(m_per_step):
if prev and rng.random() < persistence:
e = prev[rng.integers(len(prev))]
else:
e = sorted(rng.choice(n, size=int(rng.choice(sizes)), replace=False))
cur.append(list(e))
edges += [[nodes[i] for i in e] for e in cur]
times += [t] * len(cur)
prev = cur
return TemporalHypergraph(edges, times=times, nodes=nodes, name="temporal random")