graphwise 0.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.
graphwise/__init__.py ADDED
@@ -0,0 +1,151 @@
1
+ """graphwise: canonical graph algorithms in readable, tested, dependency-free Python.
2
+
3
+ Every algorithm is a plain function that takes a :class:`Graph` or
4
+ :class:`DiGraph` as its first argument::
5
+
6
+ >>> import graphwise as gw
7
+ >>> g = gw.DiGraph([("a", "b", 4), ("a", "c", 1), ("c", "b", 2)])
8
+ >>> gw.shortest_path(g, "a", "b")
9
+ (3, ['a', 'c', 'b'])
10
+
11
+ Each submodule groups one family of algorithms, and its docstring explains
12
+ the ideas behind them: ``graphwise.shortest_paths``, ``graphwise.centrality``,
13
+ ``graphwise.community``, ``graphwise.connectivity``, ``graphwise.dag``,
14
+ ``graphwise.eulerian``, ``graphwise.flow``, ``graphwise.spanning_trees``,
15
+ ``graphwise.traversal`` and ``graphwise.union_find``.
16
+ """
17
+
18
+ from .centrality import (
19
+ betweenness_centrality,
20
+ closeness_centrality,
21
+ degree_centrality,
22
+ harmonic_centrality,
23
+ in_degree_centrality,
24
+ out_degree_centrality,
25
+ pagerank,
26
+ )
27
+ from .community import (
28
+ approximate_average_clustering,
29
+ average_clustering,
30
+ clustering,
31
+ label_propagation,
32
+ louvain,
33
+ modularity,
34
+ propagate_labels,
35
+ )
36
+ from .connectivity import (
37
+ articulation_points,
38
+ bridges,
39
+ condensation,
40
+ connected_components,
41
+ is_connected,
42
+ strongly_connected_components,
43
+ )
44
+ from .dag import (
45
+ find_cycle,
46
+ is_dag,
47
+ topological_generations,
48
+ topological_sort,
49
+ topological_sort_dfs,
50
+ topological_sort_kahn,
51
+ )
52
+ from .eulerian import eulerian_circuit, eulerian_path, has_eulerian_circuit, has_eulerian_path
53
+ from .exceptions import (
54
+ EdgeNotFound,
55
+ GraphError,
56
+ NegativeCycle,
57
+ NodeNotFound,
58
+ NoPath,
59
+ NotADAG,
60
+ NotEulerian,
61
+ )
62
+ from .flow import max_flow, minimum_cut
63
+ from .graph import DiGraph, Graph
64
+ from .shortest_paths import (
65
+ astar,
66
+ bellman_ford,
67
+ dijkstra,
68
+ floyd_warshall,
69
+ johnson,
70
+ path_weight,
71
+ reconstruct_path,
72
+ shortest_path,
73
+ yen_k_shortest_paths,
74
+ )
75
+ from .spanning_trees import kruskal_mst, minimum_spanning_tree, prim_mst
76
+ from .traversal import bfs, bfs_layers, dfs, random_walk
77
+ from .union_find import DisjointSet
78
+
79
+ __version__ = "0.1.0"
80
+
81
+ __all__ = [
82
+ # data structures
83
+ "Graph",
84
+ "DiGraph",
85
+ "DisjointSet",
86
+ # traversal
87
+ "bfs",
88
+ "bfs_layers",
89
+ "dfs",
90
+ "random_walk",
91
+ # DAGs
92
+ "topological_sort",
93
+ "topological_sort_kahn",
94
+ "topological_sort_dfs",
95
+ "topological_generations",
96
+ "is_dag",
97
+ "find_cycle",
98
+ # shortest paths
99
+ "dijkstra",
100
+ "astar",
101
+ "bellman_ford",
102
+ "floyd_warshall",
103
+ "johnson",
104
+ "yen_k_shortest_paths",
105
+ "shortest_path",
106
+ "reconstruct_path",
107
+ "path_weight",
108
+ # spanning trees
109
+ "kruskal_mst",
110
+ "prim_mst",
111
+ "minimum_spanning_tree",
112
+ # connectivity
113
+ "connected_components",
114
+ "is_connected",
115
+ "strongly_connected_components",
116
+ "condensation",
117
+ "bridges",
118
+ "articulation_points",
119
+ # Eulerian
120
+ "eulerian_circuit",
121
+ "eulerian_path",
122
+ "has_eulerian_circuit",
123
+ "has_eulerian_path",
124
+ # centrality
125
+ "degree_centrality",
126
+ "in_degree_centrality",
127
+ "out_degree_centrality",
128
+ "closeness_centrality",
129
+ "harmonic_centrality",
130
+ "betweenness_centrality",
131
+ "pagerank",
132
+ # community
133
+ "clustering",
134
+ "average_clustering",
135
+ "approximate_average_clustering",
136
+ "modularity",
137
+ "label_propagation",
138
+ "propagate_labels",
139
+ "louvain",
140
+ # flow
141
+ "max_flow",
142
+ "minimum_cut",
143
+ # exceptions
144
+ "GraphError",
145
+ "NodeNotFound",
146
+ "EdgeNotFound",
147
+ "NoPath",
148
+ "NotADAG",
149
+ "NegativeCycle",
150
+ "NotEulerian",
151
+ ]
@@ -0,0 +1,314 @@
1
+ """Centrality: which nodes matter most?
2
+
3
+ Each measure has its own idea of "important":
4
+
5
+ ===================== =============================================== ==================
6
+ Measure A node is central if it ... Time
7
+ ===================== =============================================== ==================
8
+ Degree has many direct connections O(V + E)
9
+ Closeness is near every other node on average O(V · SSSP)
10
+ Harmonic is near many nodes (works when disconnected) O(V · SSSP)
11
+ Betweenness (Brandes) lies on many shortest paths between others O(VE + V² log V)
12
+ PageRank is pointed to by other important nodes O(iters · E)
13
+ ===================== =============================================== ==================
14
+
15
+ Distance-based measures use edge weights as *distances* (higher means
16
+ farther) when ``weighted=True``, and hop counts otherwise. For directed
17
+ graphs, closeness and harmonic centrality measure distances *from* each node,
18
+ which is outward reach. To measure how reachable a node is *from* the rest of
19
+ the graph, pass ``graph.reverse()``. (networkx uses that inward convention.)
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import heapq
25
+ from collections import deque
26
+ from collections.abc import Hashable, Mapping
27
+ from itertools import count
28
+ from typing import Any
29
+
30
+ from .exceptions import GraphError
31
+ from .graph import _BaseGraph
32
+ from .shortest_paths import _bfs_paths, _dijkstra
33
+
34
+ __all__ = [
35
+ "degree_centrality",
36
+ "in_degree_centrality",
37
+ "out_degree_centrality",
38
+ "closeness_centrality",
39
+ "harmonic_centrality",
40
+ "betweenness_centrality",
41
+ "pagerank",
42
+ ]
43
+
44
+
45
+ def _scale(graph: _BaseGraph[Any]) -> float:
46
+ return 1 / (len(graph) - 1) if len(graph) > 1 else 1
47
+
48
+
49
+ def _degree_based(graph: _BaseGraph[Any], degree: Any) -> dict[Any, float]:
50
+ if len(graph) <= 1: # convention shared with networkx: a lone node is fully central
51
+ return dict.fromkeys(graph, 1.0)
52
+ s = _scale(graph)
53
+ return {v: degree(v) * s for v in graph}
54
+
55
+
56
+ def degree_centrality(graph: _BaseGraph[Any]) -> dict[Any, float]:
57
+ """Degree divided by ``n - 1``, the largest degree possible.
58
+
59
+ For a :class:`DiGraph` the degree is in-degree plus out-degree, so values
60
+ can be as high as 2.
61
+
62
+ >>> from graphwise import Graph
63
+ >>> degree_centrality(Graph([("hub", "a"), ("hub", "b"), ("hub", "c")]))["hub"]
64
+ 1.0
65
+ """
66
+ return _degree_based(graph, graph.degree) # type: ignore[attr-defined]
67
+
68
+
69
+ def in_degree_centrality(graph: _BaseGraph[Any]) -> dict[Any, float]:
70
+ """In-degree divided by ``n - 1``. (DiGraph only.)"""
71
+ if not graph.is_directed:
72
+ raise TypeError("in_degree_centrality requires a DiGraph")
73
+ return _degree_based(graph, graph.in_degree) # type: ignore[attr-defined]
74
+
75
+
76
+ def out_degree_centrality(graph: _BaseGraph[Any]) -> dict[Any, float]:
77
+ """Out-degree divided by ``n - 1``. (DiGraph only.)"""
78
+ if not graph.is_directed:
79
+ raise TypeError("out_degree_centrality requires a DiGraph")
80
+ return _degree_based(graph, graph.out_degree) # type: ignore[attr-defined]
81
+
82
+
83
+ def _distances(graph: _BaseGraph[Any], source: Any, weighted: bool) -> dict[Any, float]:
84
+ if weighted:
85
+ return _dijkstra(graph._adj, source)[0]
86
+ return _bfs_paths(graph, source)[0]
87
+
88
+
89
+ def closeness_centrality(
90
+ graph: _BaseGraph[Any], *, weighted: bool = True, wf_improved: bool = True
91
+ ) -> dict[Any, float]:
92
+ """Closeness: ``(r - 1) / Σ d(u, v)`` over the ``r`` nodes ``u`` can reach.
93
+
94
+ The reciprocal of the average distance from ``u`` to the nodes it can
95
+ reach. With ``wf_improved=True`` (Wasserman & Faust) the score is also
96
+ multiplied by ``(r - 1) / (n - 1)``, so a node that reaches only a small
97
+ corner of a disconnected graph is not over-rated.
98
+
99
+ >>> from graphwise import Graph
100
+ >>> c = closeness_centrality(Graph([(1, 2), (2, 3), (3, 4)]))
101
+ >>> round(c[2], 3), round(c[1], 3)
102
+ (0.75, 0.5)
103
+
104
+ References: Freeman, L. C. (1979). Centrality in social networks:
105
+ conceptual clarification. *Social Networks* 1(3).
106
+ """
107
+ n = len(graph)
108
+ out = {}
109
+ for u in graph:
110
+ dist = _distances(graph, u, weighted)
111
+ total = sum(dist.values())
112
+ score = 0.0
113
+ if total > 0 and n > 1:
114
+ reach = len(dist) - 1
115
+ score = reach / total
116
+ if wf_improved:
117
+ score *= reach / (n - 1)
118
+ out[u] = score
119
+ return out
120
+
121
+
122
+ def harmonic_centrality(
123
+ graph: _BaseGraph[Any], *, weighted: bool = True, normalized: bool = False
124
+ ) -> dict[Any, float]:
125
+ """Harmonic centrality: ``Σ 1 / d(u, v)`` over every ``v ≠ u``.
126
+
127
+ An unreachable node adds ``1/∞ = 0``, so unlike closeness this stays
128
+ well-defined on disconnected graphs. With ``normalized=True`` the sum is
129
+ divided by ``n - 1``, which puts it in [0, 1] for unit weights. Pairs at
130
+ distance 0 (joined by zero-weight edges) are skipped.
131
+
132
+ >>> from graphwise import Graph
133
+ >>> harmonic_centrality(Graph([(1, 2), (2, 3)]))[2]
134
+ 2.0
135
+
136
+ References: Marchiori & Latora (2000). Harmony in the small-world.
137
+ *Physica A* 285.
138
+ """
139
+ out = {}
140
+ for u in graph:
141
+ dist = _distances(graph, u, weighted)
142
+ score = sum(1 / d for d in dist.values() if d != 0)
143
+ out[u] = score * _scale(graph) if normalized else score
144
+ return out
145
+
146
+
147
+ def _brandes_sssp(
148
+ adj: dict[Any, dict[Any, float]], s: Any, weighted: bool
149
+ ) -> tuple[list[Any], dict[Any, list[Any]], dict[Any, float]]:
150
+ """Return ``(S, P, sigma)``.
151
+
152
+ ``S`` is the nodes in order of non-decreasing distance from ``s``, ``P``
153
+ maps each node to its predecessors on shortest paths, and ``sigma`` counts
154
+ the shortest paths to each node.
155
+ """
156
+ order: list[Any] = []
157
+ preds: dict[Any, list[Any]] = {v: [] for v in adj}
158
+ sigma: dict[Any, float] = dict.fromkeys(adj, 0.0)
159
+ sigma[s] = 1.0
160
+ dist: dict[Any, float] = {}
161
+ if not weighted:
162
+ dist[s] = 0
163
+ q = deque([s])
164
+ while q:
165
+ v = q.popleft()
166
+ order.append(v)
167
+ for w in adj[v]:
168
+ if w not in dist:
169
+ dist[w] = dist[v] + 1
170
+ q.append(w)
171
+ if dist[w] == dist[v] + 1:
172
+ sigma[w] += sigma[v]
173
+ preds[w].append(v)
174
+ return order, preds, sigma
175
+
176
+ seen = {s: 0.0}
177
+ tie = count()
178
+ heap: list[tuple[float, int, Any, Any]] = [(0.0, next(tie), None, s)]
179
+ while heap:
180
+ d, _, pred, v = heapq.heappop(heap)
181
+ if v in dist:
182
+ continue
183
+ if pred is not None:
184
+ sigma[v] += sigma[pred]
185
+ order.append(v)
186
+ dist[v] = d
187
+ for w, wt in adj[v].items():
188
+ vw = d + wt
189
+ if w not in dist and (w not in seen or vw < seen[w]):
190
+ seen[w] = vw
191
+ heapq.heappush(heap, (vw, next(tie), v, w))
192
+ sigma[w] = 0.0
193
+ preds[w] = [v]
194
+ elif w not in dist and vw == seen[w]: # another shortest path, same length
195
+ sigma[w] += sigma[v]
196
+ preds[w].append(v)
197
+ return order, preds, sigma
198
+
199
+
200
+ def betweenness_centrality(
201
+ graph: _BaseGraph[Any], *, normalized: bool = True, weighted: bool = True
202
+ ) -> dict[Any, float]:
203
+ """Brandes' algorithm. The share of shortest paths that pass through each node.
204
+
205
+ ``BC(v) = Σ σ_st(v) / σ_st`` over all pairs ``s ≠ v ≠ t``. ``σ_st`` is the
206
+ number of shortest ``s -> t`` paths, and ``σ_st(v)`` is how many of them
207
+ pass through ``v``.
208
+
209
+ Brandes' insight is that this can be computed without listing any pairs.
210
+ After one shortest-path search from ``s``, a single backward sweep in order
211
+ of decreasing distance builds up each node's *dependency*
212
+ ``δ_s(v) = Σ_{w : v ∈ P(w)} (σ_sv / σ_sw) · (1 + δ_s(w))``.
213
+
214
+ ``normalized=True`` divides by ``(n - 1)(n - 2)``, the number of ordered
215
+ pairs. Undirected graphs count each pair once. The results match networkx.
216
+
217
+ Time O(VE) unweighted, O(VE + V² log V) weighted.
218
+
219
+ >>> from graphwise import Graph
220
+ >>> betweenness_centrality(Graph([(1, 2), (2, 3)]), normalized=False)
221
+ {1: 0.0, 2: 1.0, 3: 0.0}
222
+
223
+ References: Brandes, U. (2001). A faster algorithm for betweenness
224
+ centrality. *J. Mathematical Sociology* 25(2).
225
+ """
226
+ adj = graph._adj
227
+ bc: dict[Any, float] = dict.fromkeys(adj, 0.0)
228
+ for s in adj:
229
+ order, preds, sigma = _brandes_sssp(adj, s, weighted)
230
+ delta = dict.fromkeys(order, 0.0)
231
+ while order:
232
+ w = order.pop()
233
+ coeff = (1 + delta[w]) / sigma[w]
234
+ for v in preds[w]:
235
+ delta[v] += sigma[v] * coeff
236
+ if w != s:
237
+ bc[w] += delta[w]
238
+ n = len(adj)
239
+ if normalized:
240
+ scale = 1 / ((n - 1) * (n - 2)) if n > 2 else None
241
+ else:
242
+ scale = None if graph.is_directed else 0.5
243
+ if scale is not None:
244
+ bc = {v: c * scale for v, c in bc.items()}
245
+ return bc
246
+
247
+
248
+ def pagerank(
249
+ graph: _BaseGraph[Any],
250
+ alpha: float = 0.85,
251
+ *,
252
+ personalization: Mapping[Hashable, float] | None = None,
253
+ weighted: bool = True,
254
+ max_iter: int = 100,
255
+ tol: float = 1e-6,
256
+ ) -> dict[Any, float]:
257
+ """PageRank by power iteration. Returns a dict of scores that sums to 1.
258
+
259
+ Picture a random surfer. With probability ``alpha`` they follow an
260
+ outgoing edge, chosen in proportion to its weight. Otherwise they
261
+ *teleport* to a node drawn from ``personalization`` (uniform by default).
262
+ A surfer at a node with no out-links (a dangling node) always teleports.
263
+ PageRank is the stationary distribution of this Markov chain.
264
+
265
+ Setting ``personalization`` gives *personalized PageRank*, which ranks
266
+ nodes by how close they are to a seed set. It is widely used for
267
+ recommendations and for spreading fraud or risk scores through a network.
268
+
269
+ Raises :class:`GraphError` if the iteration does not converge within
270
+ ``max_iter`` steps.
271
+
272
+ >>> from graphwise import DiGraph
273
+ >>> pr = pagerank(DiGraph([("a", "b"), ("b", "c"), ("c", "a"), ("d", "c")]))
274
+ >>> max(pr, key=pr.get)
275
+ 'c'
276
+
277
+ References: Page, Brin, Motwani & Winograd (1999). The PageRank citation
278
+ ranking: bringing order to the web. Stanford InfoLab.
279
+ """
280
+ adj = graph._adj
281
+ n = len(adj)
282
+ if n == 0:
283
+ return {}
284
+ if personalization is None:
285
+ p = dict.fromkeys(adj, 1.0 / n)
286
+ else:
287
+ unknown = set(personalization) - set(adj)
288
+ if unknown:
289
+ raise GraphError(f"personalization has nodes not in the graph: {unknown}")
290
+ total = float(sum(personalization.values()))
291
+ if total <= 0:
292
+ raise ValueError("personalization values must sum to a positive number")
293
+ p = {v: personalization.get(v, 0) / total for v in adj}
294
+
295
+ # Row-normalise the out-edges, so each row is a probability distribution.
296
+ out_w = {u: (sum(nbrs.values()) if weighted else len(nbrs)) for u, nbrs in adj.items()}
297
+ dangling = [u for u, w in out_w.items() if w == 0]
298
+
299
+ x = dict.fromkeys(adj, 1.0 / n)
300
+ for _ in range(max_iter):
301
+ last = x
302
+ x = dict.fromkeys(adj, 0.0)
303
+ dangle_sum = alpha * sum(last[u] for u in dangling)
304
+ for u, nbrs in adj.items():
305
+ if out_w[u] == 0:
306
+ continue
307
+ share = alpha * last[u] / out_w[u]
308
+ for v, w in nbrs.items():
309
+ x[v] += share * (w if weighted else 1)
310
+ for v in x:
311
+ x[v] += (dangle_sum + (1.0 - alpha)) * p[v]
312
+ if sum(abs(x[v] - last[v]) for v in x) < n * tol:
313
+ return x
314
+ raise GraphError(f"pagerank failed to converge in {max_iter} iterations")