hatvis 1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hatvis/community.py ADDED
@@ -0,0 +1,318 @@
1
+ r"""Community detection and clustering of hypergraphs.
2
+
3
+ * hypergraph modularity (strict / all-or-nothing form of Kamiński et al. 2019
4
+ and Chodrow, Veldt and Benson 2021) and the graph modularity of projections;
5
+ * a Louvain-type local-moving and aggregation heuristic that maximizes the
6
+ hypergraph modularity directly;
7
+ * Louvain on the clique expansion or on the line graph (as in Nagy et al. 2022);
8
+ * label propagation on the vertex–hyperedge incidence structure;
9
+ * spectral co-clustering of the incidence matrix (simultaneous clusters of
10
+ vertices and hyperedges, Dhillon 2001).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections import defaultdict
16
+
17
+ import networkx as nx
18
+ import numpy as np
19
+ import pandas as pd
20
+
21
+ from .core import Hypergraph
22
+ from .representations import clique_expansion, line_graph
23
+ from .spectral import _relabel
24
+
25
+ __all__ = ["modularity", "graph_modularity", "hypergraph_louvain", "louvain", "label_propagation",
26
+ "spectral_coclustering", "partition_sizes", "communities"]
27
+
28
+
29
+ def _as_labels(H: Hypergraph, partition) -> dict:
30
+ if isinstance(partition, pd.Series):
31
+ return partition.to_dict()
32
+ if isinstance(partition, dict):
33
+ return dict(partition)
34
+ if isinstance(partition, (list, tuple)) and partition and isinstance(partition[0], (set, frozenset, list)):
35
+ return {v: c for c, block in enumerate(partition) for v in block}
36
+ return dict(zip(H.nodes, partition, strict=True))
37
+
38
+
39
+ def modularity(H: Hypergraph, partition, resolution: float = 1.0) -> float:
40
+ r"""Strict (all-or-nothing) hypergraph modularity.
41
+
42
+ .. math::
43
+
44
+ Q=\frac{1}{W}\sum_{k\ge2}\Big[\sum_{e\in E_k}w_e\,[e\subseteq A_{\sigma}]
45
+ -\gamma\,W_k\sum_{c}\Big(\frac{\mathrm{vol}(A_c)}{\mathrm{vol}(V)}\Big)^{k}\Big],
46
+
47
+ where a hyperedge counts as internal only if *all* its vertices are in the
48
+ same community, :math:`W_k` is the total weight of the hyperedges of size
49
+ :math:`k`, :math:`W=\sum_k W_k`, :math:`\mathrm{vol}(A)=\sum_{i\in A}d_i` and
50
+ :math:`\gamma` is the resolution. This is the strict modularity of Kamiński
51
+ et al. (2019); the all-or-nothing modularity of Chodrow et al. (2021) has
52
+ the same structure with size-dependent weights. Singletons are ignored.
53
+ """
54
+ lab = _as_labels(H, partition)
55
+ sizes = H.edge_sizes().to_numpy()
56
+ w = H.weights
57
+ keep = sizes >= 2
58
+ if not keep.any():
59
+ return 0.0
60
+ Hb = H.binary_incidence()
61
+ deg = np.asarray(Hb[:, keep] @ w[keep]).ravel()
62
+ vol = deg.sum()
63
+ comm_vol = defaultdict(float)
64
+ for v, d in zip(H.nodes, deg, strict=True):
65
+ comm_vol[lab[v]] += d
66
+ W = w[keep].sum()
67
+ inside = 0.0
68
+ for (_e, mem), sz, we in zip(H, sizes, w, strict=True):
69
+ if sz >= 2 and len({lab[v] for v in mem}) == 1:
70
+ inside += we
71
+ expected = 0.0
72
+ for k in np.unique(sizes[keep]):
73
+ Wk = w[keep & (sizes == k)].sum()
74
+ expected += Wk * sum((cv / vol) ** k for cv in comm_vol.values())
75
+ return float((inside - resolution * expected) / W)
76
+
77
+
78
+ def graph_modularity(H: Hypergraph, partition, projection: str = "clique", weighting: str = "count",
79
+ resolution: float = 1.0) -> float:
80
+ """Newman–Girvan modularity of a projection (clique expansion of the vertices)."""
81
+ lab = _as_labels(H, partition)
82
+ G = clique_expansion(H, weighting)
83
+ comms = defaultdict(set)
84
+ for v in G.nodes:
85
+ comms[lab[v]].add(v)
86
+ return float(nx.community.modularity(G, list(comms.values()), weight="weight", resolution=resolution))
87
+
88
+
89
+ def _strict_setup(H):
90
+ sizes = H.edge_sizes().to_numpy()
91
+ w = H.weights
92
+ keep = np.where(sizes >= 2)[0]
93
+ Hb = H.binary_incidence().tocsc()
94
+ edges = [(int(sizes[k]), float(w[k]), Hb.indices[Hb.indptr[k]:Hb.indptr[k + 1]]) for k in keep]
95
+ deg = np.zeros(H.n_nodes)
96
+ for _, we, mem in edges:
97
+ deg[mem] += we
98
+ W = sum(we for _, we, _ in edges)
99
+ Wk: dict[int, float] = defaultdict(float)
100
+ for size, we, _ in edges:
101
+ Wk[size] += we
102
+ node_edges = [[] for _ in range(H.n_nodes)]
103
+ for eid, (_, _, mem) in enumerate(edges):
104
+ for v in mem:
105
+ node_edges[v].append(eid)
106
+ return edges, deg, W, dict(Wk), node_edges
107
+
108
+
109
+ def _local_moving(edges, deg, W, Wk, node_edges, comm, resolution, rng):
110
+ vol = deg.sum()
111
+ cvol = defaultdict(float)
112
+ for v, c in enumerate(comm):
113
+ cvol[c] += deg[v]
114
+ ecount = []
115
+ for _, _, mem in edges:
116
+ cnt = defaultdict(int)
117
+ for v in mem:
118
+ cnt[comm[v]] += 1
119
+ ecount.append(cnt)
120
+
121
+ def vol_term(a_vol, c_vol, d):
122
+ return sum(Wk[k] * ((a_vol - d) ** k + (c_vol + d) ** k - a_vol ** k - c_vol ** k) / vol ** k for k in Wk)
123
+
124
+ moved_any = False
125
+ while True:
126
+ moved = 0
127
+ for v in rng.permutation(len(comm)):
128
+ a = comm[v]
129
+ d = deg[v]
130
+ cand = set()
131
+ for eid in node_edges[v]:
132
+ cand.update(ecount[eid].keys())
133
+ cand.discard(a)
134
+ if not cand:
135
+ continue
136
+ base = -sum(edges[eid][1] for eid in node_edges[v] if ecount[eid].get(a, 0) == edges[eid][0])
137
+ best_gain, best_c = 0.0, a
138
+ for c_ in cand:
139
+ g = base + sum(edges[eid][1] for eid in node_edges[v] if ecount[eid].get(c_, 0) + 1 == edges[eid][0])
140
+ gain = (g - resolution * vol_term(cvol[a], cvol[c_], d)) / W
141
+ if gain > best_gain + 1e-12:
142
+ best_gain, best_c = gain, c_
143
+ if best_c != a:
144
+ for eid in node_edges[v]:
145
+ ec = ecount[eid]
146
+ ec[a] -= 1
147
+ if ec[a] == 0:
148
+ del ec[a]
149
+ ec[best_c] += 1
150
+ cvol[a] -= d
151
+ cvol[best_c] += d
152
+ comm[v] = best_c
153
+ moved += 1
154
+ if moved == 0:
155
+ return comm, moved_any
156
+ moved_any = True
157
+
158
+
159
+ def _greedy_merge(edges, deg, W, Wk, comm, resolution):
160
+ vol = deg.sum()
161
+ merged_any = False
162
+ while True:
163
+ cvol = defaultdict(float)
164
+ for v, c in enumerate(comm):
165
+ cvol[c] += deg[v]
166
+ gain_edges: dict[tuple, float] = defaultdict(float)
167
+ for _, we, mem in edges:
168
+ cs = {comm[v] for v in mem}
169
+ if len(cs) == 2:
170
+ gain_edges[tuple(sorted(cs))] += we
171
+ best, pair = 0.0, None
172
+ for (a, b), ge in gain_edges.items():
173
+ dv = sum(Wk[k] * ((cvol[a] + cvol[b]) ** k - cvol[a] ** k - cvol[b] ** k) / vol ** k for k in Wk)
174
+ gain = (ge - resolution * dv) / W
175
+ if gain > best + 1e-12:
176
+ best, pair = gain, (a, b)
177
+ if pair is None:
178
+ return comm, merged_any
179
+ comm = np.where(comm == pair[1], pair[0], comm)
180
+ merged_any = True
181
+
182
+
183
+ def hypergraph_louvain(H: Hypergraph, resolution: float = 1.0, init: str = "clique", random_state=None,
184
+ max_rounds: int = 20) -> pd.Series:
185
+ r"""Maximize the strict hypergraph modularity (:func:`modularity`) by local moving and merging.
186
+
187
+ Under the strict definition a hyperedge counts as internal only when all
188
+ its vertices are in the same community, so single-vertex moves from a
189
+ singleton start rarely pay off. The heuristic therefore (1) starts from
190
+ the Louvain partition of the clique expansion (``init="clique"``) or from
191
+ singletons (``init="singletons"``), (2) moves single vertices to the
192
+ neighbouring community with the largest exact modularity gain and (3)
193
+ greedily merges pairs of communities as long as :math:`Q` increases
194
+ (the aggregation idea of Blondel et al. 2008 and the CNM-type merging
195
+ considered for hypergraph modularity by Kamiński et al.). Steps 2–3 are
196
+ repeated until nothing changes.
197
+ """
198
+ rng = np.random.default_rng(random_state)
199
+ edges, deg, W, Wk, node_edges = _strict_setup(H)
200
+ if W == 0:
201
+ return pd.Series(np.arange(H.n_nodes), index=H.nodes, name="community")
202
+ if init == "clique":
203
+ comm = louvain(H, weighting="pairs", resolution=resolution,
204
+ random_state=int(rng.integers(1 << 31))).to_numpy().copy()
205
+ elif init == "singletons":
206
+ comm = np.arange(H.n_nodes)
207
+ else:
208
+ raise ValueError("init must be 'clique' or 'singletons'")
209
+ for _ in range(max_rounds):
210
+ comm, moved = _local_moving(edges, deg, W, Wk, node_edges, comm, resolution, rng)
211
+ comm, merged = _greedy_merge(edges, deg, W, Wk, comm, resolution)
212
+ if not moved and not merged:
213
+ break
214
+ return _relabel(pd.Series(comm, index=H.nodes, name="community"))
215
+
216
+
217
+ def louvain(H: Hypergraph, target: str = "nodes", weighting: str = "count", resolution: float = 1.0,
218
+ s: int = 1, random_state=None) -> pd.Series:
219
+ """Louvain communities of a projection (networkx implementation).
220
+
221
+ ``target="nodes"``: communities of the vertices in the clique expansion;
222
+ ``target="edges"``: communities of the hyperedges in the weighted
223
+ :math:`s`-line graph (equivalently, vertex communities of the dual
224
+ hypergraph). Nagy et al. (2022) used both views to find activity-based and
225
+ element-based modules of a manufacturing space.
226
+ """
227
+ if target == "nodes":
228
+ G = clique_expansion(H, weighting)
229
+ labels = H.nodes
230
+ elif target == "edges":
231
+ G = line_graph(H, s=s, weighted=True)
232
+ labels = H.edges
233
+ else:
234
+ raise ValueError("target must be 'nodes' or 'edges'")
235
+ comms = nx.community.louvain_communities(G, weight="weight", resolution=resolution, seed=random_state)
236
+ comms = sorted(comms, key=lambda c: (-len(c), sorted(map(str, c))))
237
+ lab = {v: c for c, block in enumerate(comms) for v in block}
238
+ out = pd.Series([lab.get(x, -1) for x in labels], index=labels, name="community")
239
+ if (out < 0).any(): # elements missing from the projection (e.g. |e| < s): own communities
240
+ nxt = out.max() + 1
241
+ for x in out.index[out < 0]:
242
+ out[x] = nxt
243
+ nxt += 1
244
+ return out.astype(int)
245
+
246
+
247
+ def label_propagation(H: Hypergraph, max_iter: int = 100, random_state=None) -> pd.Series:
248
+ r"""Label propagation through the incidence structure (after Raghavan et al. 2007).
249
+
250
+ Each hyperedge adopts the weighted majority label of its vertices, then
251
+ each vertex adopts the weighted majority label of its hyperedges (weights
252
+ :math:`w_e b_{ie}`); ties are broken at random. Iterates until stable.
253
+ """
254
+ rng = np.random.default_rng(random_state)
255
+ B = H.incidence.tocsr()
256
+ Bc = B.tocsc()
257
+ lab = np.arange(H.n_nodes)
258
+ w = H.weights
259
+ for _ in range(max_iter):
260
+ elab = np.empty(H.n_edges, dtype=int)
261
+ for k in range(H.n_edges):
262
+ rows = Bc.indices[Bc.indptr[k]:Bc.indptr[k + 1]]
263
+ vals = Bc.data[Bc.indptr[k]:Bc.indptr[k + 1]]
264
+ elab[k] = _vote(lab[rows], vals, rng) if rows.size else -1
265
+ changed = 0
266
+ for i in rng.permutation(H.n_nodes):
267
+ cols = B.indices[B.indptr[i]:B.indptr[i + 1]]
268
+ if not cols.size:
269
+ continue
270
+ vals = B.data[B.indptr[i]:B.indptr[i + 1]] * w[cols]
271
+ new = _vote(elab[cols], vals, rng)
272
+ if new != lab[i]:
273
+ lab[i] = new
274
+ changed += 1
275
+ if changed == 0:
276
+ break
277
+ return _relabel(pd.Series(lab, index=H.nodes, name="community"))
278
+
279
+
280
+ def _vote(labels, weights, rng) -> int:
281
+ score = defaultdict(float)
282
+ for lb, wt in zip(labels, weights, strict=True):
283
+ score[int(lb)] += float(wt)
284
+ best = max(score.values())
285
+ winners = sorted(k for k, s in score.items() if s >= best - 1e-12)
286
+ return int(winners[0] if len(winners) == 1 else rng.choice(winners))
287
+
288
+
289
+ def spectral_coclustering(H: Hypergraph, n_clusters: int, random_state=None) -> tuple[pd.Series, pd.Series]:
290
+ r"""Simultaneous clustering of vertices and hyperedges (spectral co-clustering, Dhillon 2001).
291
+
292
+ Bipartite spectral partitioning of the (weighted) incidence matrix, as
293
+ implemented in scikit-learn. Returns ``(vertex labels, hyperedge labels)``;
294
+ a pair of equal labels defines a bicluster — a block of the incidence
295
+ matrix that the seriated matrix plot can highlight. Empty rows or columns
296
+ receive the label ``-1``.
297
+ """
298
+ from sklearn.cluster import SpectralCoclustering
299
+ X = H.incidence.toarray() * H.weights[None, :]
300
+ rows = np.where(X.sum(axis=1) > 0)[0]
301
+ cols = np.where(X.sum(axis=0) > 0)[0]
302
+ model = SpectralCoclustering(n_clusters=n_clusters, random_state=random_state).fit(X[np.ix_(rows, cols)])
303
+ rl = np.full(H.n_nodes, -1)
304
+ cl = np.full(H.n_edges, -1)
305
+ rl[rows] = model.row_labels_
306
+ cl[cols] = model.column_labels_
307
+ return (pd.Series(rl, index=H.nodes, name="vertex bicluster"),
308
+ pd.Series(cl, index=H.edges, name="hyperedge bicluster"))
309
+
310
+
311
+ def partition_sizes(partition: pd.Series) -> pd.Series:
312
+ """Number of members per community, largest first."""
313
+ return partition.value_counts().sort_values(ascending=False)
314
+
315
+
316
+ def communities(partition: pd.Series) -> list[list]:
317
+ """Partition as a list of member lists (community 0 first)."""
318
+ return [list(partition.index[partition == c]) for c in sorted(partition.unique())]