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/__init__.py ADDED
@@ -0,0 +1,117 @@
1
+ """hatvis — Hypergraph Analysis and Visualization Toolbox.
2
+
3
+ The Python successor of the MATLAB HAT-VIS toolbox (Czvetkó and Abonyi 2024)
4
+ and of the HyperGodot viewer (Ficsor et al. 2025): hypergraph data structures
5
+ and representations, interchange with other hypergraph libraries, similarity-
6
+ based and force-directed layouts, matrix and set visualizations, structural
7
+ analysis, centrality, clustering, frequent patterns, higher-order motifs, null
8
+ models, combinatorial problem solving, dynamics and learning on hypergraphs.
9
+
10
+ >>> import hatvis as hv
11
+ >>> H = hv.Hypergraph({"e1": ["a", "b", "c"], "e2": ["b", "c", "d"], "e3": ["d", "e"]})
12
+ >>> int(H.summary()["hyperedges"])
13
+ 3
14
+ >>> hv.s_betweenness(H, s=1).round(2).to_dict()
15
+ {'e1': 0.0, 'e2': 1.0, 'e3': 0.0}
16
+ """
17
+
18
+ from . import (
19
+ centrality,
20
+ community,
21
+ datasets,
22
+ dynamics,
23
+ interactive,
24
+ io,
25
+ layout,
26
+ learning,
27
+ metrics,
28
+ models,
29
+ motifs,
30
+ partition,
31
+ patterns,
32
+ plotting,
33
+ problems,
34
+ qfd,
35
+ representations,
36
+ seriation,
37
+ similarity,
38
+ spectral,
39
+ temporal,
40
+ )
41
+ from .centrality import (
42
+ average_s_centrality,
43
+ clique_eigenvector,
44
+ degree_centrality,
45
+ edge_strength,
46
+ h_eigenvector,
47
+ hypercore_numbers,
48
+ hypercoreness,
49
+ node_edge_eigenvector,
50
+ pagerank,
51
+ s_betweenness,
52
+ s_centrality_table,
53
+ s_closeness,
54
+ s_eigenvector,
55
+ s_harmonic_closeness,
56
+ z_eigenvector,
57
+ )
58
+ from .community import (
59
+ graph_modularity,
60
+ hypergraph_louvain,
61
+ label_propagation,
62
+ louvain,
63
+ modularity,
64
+ spectral_coclustering,
65
+ )
66
+ from .core import DirectedHypergraph, Hypergraph, TemporalHypergraph, union
67
+ from .interactive import to_html
68
+ from .io import from_hif, read_hif, read_hypergodot, to_hif, write_hif, write_hypergodot
69
+ from .layout import (
70
+ layout_bipartite,
71
+ layout_circular,
72
+ layout_force,
73
+ layout_grid,
74
+ layout_membership,
75
+ layout_quality,
76
+ layout_radial,
77
+ layout_similarity,
78
+ layout_spectral,
79
+ )
80
+ from .metrics import (
81
+ degree_distribution,
82
+ s_component_profile,
83
+ s_connected_components,
84
+ s_diameter,
85
+ s_distance,
86
+ simpliciality,
87
+ size_distribution,
88
+ )
89
+ from .patterns import association_rules, closed_itemsets, frequent_itemsets, itemset_hypergraph, maximal_itemsets
90
+ from .representations import clique_adjacency, clique_expansion, laplacian, line_graph, s_line_graph, star_expansion
91
+ from .seriation import seriate
92
+ from .similarity import dissimilarity, edge_similarity, transitive_closure, vertex_similarity
93
+ from .spectral import spectral_clustering, spectral_embedding, transition_matrix
94
+
95
+ __version__ = "1.0"
96
+
97
+ __all__ = [
98
+ "Hypergraph", "DirectedHypergraph", "TemporalHypergraph", "union",
99
+ "centrality", "community", "datasets", "dynamics", "interactive", "io", "layout", "learning", "metrics",
100
+ "models", "motifs", "partition", "patterns", "plotting", "problems", "qfd", "representations",
101
+ "seriation", "similarity", "spectral", "temporal",
102
+ "clique_adjacency", "clique_expansion", "star_expansion", "line_graph", "s_line_graph", "laplacian",
103
+ "to_hif", "from_hif", "read_hif", "write_hif", "read_hypergodot", "write_hypergodot", "to_html",
104
+ "vertex_similarity", "edge_similarity", "transitive_closure", "dissimilarity",
105
+ "degree_distribution", "size_distribution", "s_connected_components", "s_distance", "s_diameter",
106
+ "s_component_profile", "simpliciality",
107
+ "degree_centrality", "edge_strength", "s_betweenness", "s_closeness", "s_harmonic_closeness",
108
+ "s_eigenvector", "average_s_centrality", "s_centrality_table", "clique_eigenvector", "z_eigenvector",
109
+ "h_eigenvector", "node_edge_eigenvector", "pagerank", "hypercore_numbers", "hypercoreness",
110
+ "transition_matrix", "spectral_embedding", "spectral_clustering",
111
+ "modularity", "graph_modularity", "hypergraph_louvain", "louvain", "label_propagation",
112
+ "spectral_coclustering",
113
+ "frequent_itemsets", "closed_itemsets", "maximal_itemsets", "association_rules", "itemset_hypergraph",
114
+ "layout_similarity", "layout_force", "layout_membership", "layout_circular", "layout_grid", "layout_radial",
115
+ "layout_spectral", "layout_bipartite", "layout_quality", "seriate",
116
+ "__version__",
117
+ ]
hatvis/centrality.py ADDED
@@ -0,0 +1,324 @@
1
+ r"""Centrality measures for vertices and hyperedges.
2
+
3
+ * degree-type: (weighted) degree, hyperedge size and strength;
4
+ * :math:`s`-walk based (Aksoy et al. 2020): :math:`s`-betweenness,
5
+ :math:`s`-closeness, harmonic :math:`s`-closeness, :math:`s`-eigenvector and
6
+ their averages over :math:`s` (Nagy et al. 2022);
7
+ * spectral: clique-expansion eigenvector (CEC), Z- and H-eigenvector
8
+ centralities of uniform hypergraphs (Benson 2019), nonlinear node–edge
9
+ eigenvector centralities (Tudisco and Higham 2021), hypergraph PageRank;
10
+ * hyper-coreness (Mancastroppa et al. 2023).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Callable
16
+
17
+ import networkx as nx
18
+ import numpy as np
19
+ import pandas as pd
20
+ import scipy.sparse as sp
21
+
22
+ from .core import Hypergraph
23
+ from .representations import clique_adjacency, line_graph, tensor_apply
24
+
25
+ __all__ = [
26
+ "degree_centrality", "edge_strength", "s_betweenness", "s_closeness", "s_harmonic_closeness",
27
+ "s_eigenvector", "average_s_centrality", "s_centrality_table", "clique_eigenvector",
28
+ "z_eigenvector", "h_eigenvector", "node_edge_eigenvector", "pagerank", "hypercore_numbers",
29
+ "hypercoreness",
30
+ ]
31
+
32
+
33
+ def degree_centrality(H: Hypergraph, weighted: bool = False, normalized: bool = True) -> pd.Series:
34
+ """Vertex degree, divided by the number of hyperedges (or the total weight) when ``normalized``."""
35
+ d = H.degrees(weighted=weighted).astype(float)
36
+ if normalized:
37
+ tot = H.weights.sum() if weighted else H.n_edges
38
+ d = d / tot if tot else d
39
+ return d.rename("degree centrality")
40
+
41
+
42
+ def edge_strength(H: Hypergraph, normalized: bool = False) -> pd.Series:
43
+ r"""Strength of a hyperedge: :math:`w_e\sum_{i} b_{ie}` (size for an unweighted hypergraph)."""
44
+ s = pd.Series(np.asarray(H.incidence.sum(axis=0)).ravel() * H.weights, index=H.edges, name="strength")
45
+ return s / s.sum() if normalized and s.sum() else s
46
+
47
+
48
+ def _lg(H, s, edges):
49
+ return line_graph(H if edges else H.dual(), s=s, weighted=True)
50
+
51
+
52
+ def _index(H, edges):
53
+ return H.edges if edges else H.nodes
54
+
55
+
56
+ def s_betweenness(H: Hypergraph, s: int = 1, edges: bool = True, normalized: bool = True) -> pd.Series:
57
+ r"""The :math:`s`-betweenness centrality (Aksoy et al. 2020).
58
+
59
+ :math:`BC_s(e)=\sum_{f\ne e\ne g}\sigma^s_{fg}(e)/\sigma^s_{fg}`, the share of
60
+ shortest :math:`s`-walks between other hyperedges that pass through
61
+ :math:`e`; it is the betweenness of :math:`e` in the :math:`s`-line graph.
62
+ ``edges=False`` ranks the vertices (via the dual). Elements with
63
+ :math:`|e|<s` get 0.
64
+ """
65
+ G = _lg(H, s, edges)
66
+ bc = nx.betweenness_centrality(G, normalized=normalized)
67
+ return pd.Series(bc, name=f"{s}-betweenness").reindex(_index(H, edges)).fillna(0.0)
68
+
69
+
70
+ def s_closeness(H: Hypergraph, s: int = 1, edges: bool = True) -> pd.Series:
71
+ r"""The :math:`s`-closeness centrality: reciprocal mean :math:`s`-distance to the reachable elements.
72
+
73
+ Computed as networkx closeness on the :math:`s`-line graph (Wasserman–Faust
74
+ scaling for disconnected graphs).
75
+ """
76
+ G = _lg(H, s, edges)
77
+ cc = nx.closeness_centrality(G)
78
+ return pd.Series(cc, name=f"{s}-closeness").reindex(_index(H, edges)).fillna(0.0)
79
+
80
+
81
+ def s_harmonic_closeness(H: Hypergraph, s: int = 1, edges: bool = True) -> pd.Series:
82
+ r"""Harmonic :math:`s`-closeness: :math:`HCC_s(e)=\frac{1}{|E_s|-1}\sum_{f\in E_s, f\ne e} 1/d_s(e,f)`,
83
+ with :math:`E_s=\{e:|e|\ge s\}` (unreachable pairs contribute 0)."""
84
+ G = _lg(H, s, edges)
85
+ n = G.number_of_nodes()
86
+ hc = nx.harmonic_centrality(G)
87
+ out = {k: v / (n - 1) if n > 1 else 0.0 for k, v in hc.items()}
88
+ return pd.Series(out, name=f"harmonic {s}-closeness").reindex(_index(H, edges)).fillna(0.0)
89
+
90
+
91
+ def s_eigenvector(H: Hypergraph, s: int = 1, edges: bool = True, weight: str | None = None) -> pd.Series:
92
+ """The :math:`s`-eigenvector centrality: principal eigenvector of the :math:`s`-line graph."""
93
+ G = _lg(H, s, edges)
94
+ if G.number_of_edges() == 0:
95
+ return pd.Series(0.0, index=_index(H, edges), name=f"{s}-eigenvector")
96
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype=float)
97
+ x = _perron(A)
98
+ return pd.Series(dict(zip(G.nodes, x, strict=True)), name=f"{s}-eigenvector").reindex(
99
+ _index(H, edges)).fillna(0.0)
100
+
101
+
102
+ def average_s_centrality(H: Hypergraph, func: Callable = s_betweenness, s_max: int = 3, edges: bool = True,
103
+ **kwargs) -> pd.Series:
104
+ r"""Average of an :math:`s`-centrality over :math:`s=1,\dots,s_{\max}`.
105
+
106
+ :math:`\overline{C}_{s_{\max}}(e)=\frac{1}{s_{\max}}\sum_{s=1}^{s_{\max}}C_s(e)`, the averaged
107
+ :math:`s`-betweenness and harmonic :math:`s`-closeness used by Nagy et al.
108
+ (2022) to rank the elements of a manufacturing space.
109
+ """
110
+ vals = [func(H, s=s, edges=edges, **kwargs) for s in range(1, s_max + 1)]
111
+ return (sum(vals) / s_max).rename(f"mean {func.__name__} (s<={s_max})")
112
+
113
+
114
+ def s_centrality_table(H: Hypergraph, s_values=(1, 2, 3), edges: bool = True) -> pd.DataFrame:
115
+ """Table of :math:`s`-betweenness and harmonic :math:`s`-closeness for several :math:`s` values."""
116
+ cols = {}
117
+ for s in s_values:
118
+ cols[f"BC s={s}"] = s_betweenness(H, s, edges)
119
+ cols[f"HCC s={s}"] = s_harmonic_closeness(H, s, edges)
120
+ return pd.DataFrame(cols)
121
+
122
+
123
+ def _perron(A, tol: float = 1e-10, max_iter: int = 2000) -> np.ndarray:
124
+ """Positive principal eigenvector (1-norm) of a non-negative matrix by shifted power iteration."""
125
+ n = A.shape[0]
126
+ x = np.ones(n) / n
127
+ M = sp.csr_array(A) + sp.eye_array(n) # shift: aperiodic, same eigenvector
128
+ for _ in range(max_iter):
129
+ y = M @ x
130
+ s = y.sum()
131
+ if s == 0:
132
+ return x
133
+ y /= s
134
+ if np.abs(y - x).sum() < tol:
135
+ return y
136
+ x = y
137
+ return x
138
+
139
+
140
+ def clique_eigenvector(H: Hypergraph, weighting: str = "count") -> pd.Series:
141
+ r"""Clique-expansion eigenvector centrality (CEC; Benson 2019): Perron vector of :math:`\mathbf{A}`.
142
+
143
+ Normalized to unit 1-norm. On a disconnected hypergraph the shifted power
144
+ iteration concentrates on the dominant component.
145
+ """
146
+ A = clique_adjacency(H, weighting, dense=False)
147
+ return pd.Series(_perron(A), index=H.nodes, name="CEC")
148
+
149
+
150
+ def z_eigenvector(H: Hypergraph, alpha: float = 1.0, tol: float = 1e-10, max_iter: int = 5000) -> pd.Series:
151
+ r"""Z-eigenvector centrality (ZEC) of a uniform hypergraph (Benson 2019).
152
+
153
+ Solves :math:`\mathcal{A}\mathbf{x}^{k-1}=\lambda\mathbf{x}`, :math:`\|\mathbf{x}\|_1=1`,
154
+ :math:`\mathbf{x}>0` with the shifted symmetric higher-order power method
155
+ (Kolda and Mayo 2011), :math:`\mathbf{x}\leftarrow(\mathcal{A}\mathbf{x}^{k-1}+\alpha\mathbf{x})/\|\cdot\|_1`.
156
+ Z-eigenvectors need not be unique; the iteration starts from the uniform vector.
157
+ """
158
+ _require_uniform(H)
159
+ x = np.ones(H.n_nodes) / H.n_nodes
160
+ for _ in range(max_iter):
161
+ y = tensor_apply(H, x) + alpha * x
162
+ y /= y.sum()
163
+ if np.abs(y - x).sum() < tol:
164
+ break
165
+ x = y
166
+ return pd.Series(y, index=H.nodes, name="ZEC")
167
+
168
+
169
+ def h_eigenvector(H: Hypergraph, tol: float = 1e-10, max_iter: int = 5000) -> pd.Series:
170
+ r"""H-eigenvector centrality (HEC) of a uniform hypergraph (Benson 2019).
171
+
172
+ Solves :math:`\mathcal{A}\mathbf{x}^{k-1}=\lambda\mathbf{x}^{[k-1]}` with the
173
+ Ng–Qi–Zhou iteration :math:`\mathbf{x}\leftarrow(\mathcal{A}\mathbf{x}^{k-1})^{[1/(k-1)]}`,
174
+ which converges to the unique positive eigenvector for a connected
175
+ hypergraph (Perron–Frobenius theory for tensors). A small shift keeps the
176
+ iteration aperiodic.
177
+ """
178
+ k = _require_uniform(H)
179
+ x = np.ones(H.n_nodes) / H.n_nodes
180
+ for _ in range(max_iter):
181
+ y = np.power(tensor_apply(H, x) + 1e-12 + 0.5 * x ** (k - 1), 1.0 / (k - 1))
182
+ y /= y.sum()
183
+ if np.abs(y - x).sum() < tol:
184
+ break
185
+ x = y
186
+ return pd.Series(y, index=H.nodes, name="HEC")
187
+
188
+
189
+ def _require_uniform(H: Hypergraph) -> int:
190
+ if not H.is_uniform():
191
+ raise ValueError("ZEC/HEC are defined for uniform hypergraphs; use uniform_layers or clique_eigenvector")
192
+ return H.rank()
193
+
194
+
195
+ def node_edge_eigenvector(H: Hypergraph, kind: str = "linear", p: float = 10.0, tol: float = 1e-10,
196
+ max_iter: int = 2000) -> tuple[pd.Series, pd.Series]:
197
+ r"""Node and edge nonlinear eigenvector centralities (Tudisco and Higham 2021).
198
+
199
+ Solves the coupled system :math:`\lambda\mathbf{x}=g(\mathbf{B}\mathbf{W}f(\mathbf{y}))`,
200
+ :math:`\mu\mathbf{y}=\psi(\mathbf{B}^\mathsf{T}\varphi(\mathbf{x}))` with positive
201
+ :math:`\mathbf{x}` (vertices) and :math:`\mathbf{y}` (hyperedges), using the
202
+ iteration :math:`\mathbf{x}\leftarrow\sqrt{\mathbf{x}\odot g(\mathbf{B}\mathbf{W}f(\mathbf{y}))}`,
203
+ :math:`\mathbf{y}\leftarrow\sqrt{\mathbf{y}\odot\psi(\mathbf{B}^\mathsf{T}\varphi(\mathbf{x}))}` with
204
+ normalization. ``kind``:
205
+
206
+ * ``"linear"``: all maps identity (the HITS-like pair of singular vectors);
207
+ * ``"log-exp"``: :math:`f=g=\mathrm{id}`, :math:`\varphi=\ln`, :math:`\psi=\exp` — a hyperedge is
208
+ important if all its vertices are (geometric mean);
209
+ * ``"max"``: :math:`\varphi(x)=x^p`, :math:`\psi(x)=x^{1/p}` — a hyperedge is as
210
+ important as its most important vertex (``p`` large).
211
+
212
+ Returns ``(vertex centrality, edge centrality)``, each with unit 1-norm.
213
+ """
214
+ B = H.binary_incidence()
215
+ W = H.weights
216
+ if kind == "linear":
217
+ phi, psi = (lambda x: x), (lambda x: x)
218
+ elif kind == "log-exp":
219
+ phi, psi = np.log, np.exp
220
+ elif kind == "max":
221
+ phi, psi = (lambda x: np.power(x, p)), (lambda x: np.power(x, 1.0 / p))
222
+ else:
223
+ raise ValueError("kind must be 'linear', 'log-exp' or 'max'")
224
+ x = np.ones(H.n_nodes) / H.n_nodes
225
+ y = np.ones(H.n_edges) / H.n_edges
226
+ for _ in range(max_iter):
227
+ u = np.sqrt(x * (B @ (W * y)))
228
+ if kind == "log-exp":
229
+ sizes = np.maximum(np.asarray(B.sum(axis=0)).ravel(), 1)
230
+ v = np.sqrt(y * psi((B.T @ phi(np.maximum(x, 1e-300))) / sizes))
231
+ else:
232
+ v = np.sqrt(y * psi(B.T @ phi(x)))
233
+ u = u / max(u.sum(), 1e-300)
234
+ v = v / max(v.sum(), 1e-300)
235
+ if np.abs(u - x).sum() + np.abs(v - y).sum() < tol:
236
+ x, y = u, v
237
+ break
238
+ x, y = u, v
239
+ return (pd.Series(x, index=H.nodes, name=f"node centrality ({kind})"),
240
+ pd.Series(y, index=H.edges, name=f"edge centrality ({kind})"))
241
+
242
+
243
+ def pagerank(H: Hypergraph, alpha: float = 0.85, personalization=None, edge_dependent: bool = True,
244
+ tol: float = 1e-12, max_iter: int = 1000) -> pd.Series:
245
+ r"""PageRank of the hypergraph random walk.
246
+
247
+ The walker at vertex :math:`u` picks a hyperedge :math:`e\ni u` with
248
+ probability :math:`w_e/d_u` and then a vertex :math:`v\in e` with probability
249
+ :math:`\gamma_e(v)/\sum_{x\in e}\gamma_e(x)` (Zhou et al. 2006). With
250
+ ``edge_dependent=True`` the incidence values act as edge-dependent vertex
251
+ weights :math:`\gamma_e(v)=b_{ve}` (Chitra and Raphael 2019); otherwise the
252
+ second step is uniform. With probability :math:`1-\alpha` the walker teleports.
253
+ """
254
+ from .spectral import transition_matrix
255
+ P = transition_matrix(H, "edge_dependent" if edge_dependent else "zhou")
256
+ n = H.n_nodes
257
+ if personalization is None:
258
+ t = np.ones(n) / n
259
+ else:
260
+ t = pd.Series(personalization).reindex(H.nodes).fillna(0.0).to_numpy(float)
261
+ t = t / t.sum()
262
+ dangling = np.asarray(P.sum(axis=1)).ravel() == 0
263
+ x = t.copy()
264
+ PT = P.T.tocsr()
265
+ for _ in range(max_iter):
266
+ y = alpha * (PT @ x + x[dangling].sum() * t) + (1 - alpha) * t
267
+ if np.abs(y - x).sum() < tol:
268
+ x = y
269
+ break
270
+ x = y
271
+ return pd.Series(x / x.sum(), index=H.nodes, name="PageRank")
272
+
273
+
274
+ def hypercore_numbers(H: Hypergraph, m: int = 2) -> pd.Series:
275
+ r"""Core numbers of the :math:`(k,m)`-hyper-core decomposition (Mancastroppa et al. 2023).
276
+
277
+ The :math:`(k,m)`-hyper-core is the maximal sub-hypergraph in which every
278
+ vertex belongs to at least :math:`k` hyperedges that have at least :math:`m`
279
+ vertices *inside the core* (hyperedges shrink as vertices are removed).
280
+ Returns, for each vertex, the largest :math:`k` for which it is in the core.
281
+ """
282
+ edges = [set(mem) for _, mem in H]
283
+ alive = set(H.nodes)
284
+ core = dict.fromkeys(H.nodes, 0)
285
+
286
+ def degrees():
287
+ d = dict.fromkeys(alive, 0)
288
+ for e in edges:
289
+ ee = e & alive
290
+ if len(ee) >= m:
291
+ for v in ee:
292
+ d[v] += 1
293
+ return d
294
+
295
+ k = 0
296
+ d = degrees()
297
+ while alive:
298
+ k += 1
299
+ while True:
300
+ low = [v for v in alive if d[v] < k]
301
+ if not low:
302
+ break
303
+ alive.difference_update(low)
304
+ d = degrees()
305
+ for v in alive:
306
+ core[v] = k
307
+ return pd.Series(core, name=f"hyper-core number (m={m})").reindex(H.nodes)
308
+
309
+
310
+ def hypercoreness(H: Hypergraph, m_values=None) -> pd.Series:
311
+ r"""Hyper-coreness :math:`R(i)=\sum_{m}C_m(i)/k_{\max}(m)` (Mancastroppa et al. 2023).
312
+
313
+ :math:`C_m(i)` is the :math:`m`-core number of vertex :math:`i`
314
+ (:func:`hypercore_numbers`) and :math:`k_{\max}(m)` its maximum over the
315
+ vertices; the sum runs over :math:`m=2,\dots,|e|_{\max}` by default.
316
+ """
317
+ m_values = range(2, max(H.rank(), 2) + 1) if m_values is None else m_values
318
+ total = pd.Series(0.0, index=H.nodes)
319
+ for m in m_values:
320
+ c = hypercore_numbers(H, m).astype(float)
321
+ if c.max() > 0:
322
+ total += c / c.max()
323
+ return total.rename("hyper-coreness")
324
+