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/community.py ADDED
@@ -0,0 +1,422 @@
1
+ """Community structure: clustering coefficients, modularity, label propagation, Louvain.
2
+
3
+ Real networks are rarely uniform. They have dense pockets, such as friend
4
+ groups, fraud rings, functional modules in protein networks, or desks that
5
+ trade with each other, joined by sparser links. This module measures that
6
+ structure and finds it.
7
+
8
+ * **Clustering coefficient**: how close a node's neighbours are to forming a
9
+ clique ("are my friends friends with each other?").
10
+ * **Modularity**: how much denser the edges inside communities are than a
11
+ random graph with the same degrees would give.
12
+ * **Label propagation**: near-linear-time community detection, in which every
13
+ node repeatedly adopts the label most common among its neighbours. The
14
+ semi-supervised variant spreads a few known labels to the rest of the graph.
15
+ * **Louvain**: greedy, multi-level modularity optimisation. It is the standard
16
+ first choice for community detection on large graphs.
17
+
18
+ Community detection here ignores edge direction. Pass a :class:`DiGraph` and
19
+ it is treated as undirected.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import random
25
+ from collections import defaultdict
26
+ from collections.abc import Hashable, Iterable, Mapping
27
+ from typing import Any
28
+
29
+ from .graph import Graph, _BaseGraph, _undirected_adj
30
+
31
+ __all__ = [
32
+ "clustering",
33
+ "average_clustering",
34
+ "approximate_average_clustering",
35
+ "modularity",
36
+ "label_propagation",
37
+ "propagate_labels",
38
+ "louvain",
39
+ ]
40
+
41
+ Adj = dict[Any, dict[Any, float]]
42
+
43
+
44
+ def _rng(seed: int | random.Random | None) -> random.Random:
45
+ return seed if isinstance(seed, random.Random) else random.Random(seed)
46
+
47
+
48
+ # --------------------------------------------------------------------------
49
+ # Clustering coefficients
50
+ # --------------------------------------------------------------------------
51
+ def clustering(graph: Graph[Any], *, weighted: bool = False) -> dict[Any, float]:
52
+ """Local clustering coefficient of every node in an undirected graph.
53
+
54
+ ``C(u) = 2 · T(u) / (deg(u) · (deg(u) - 1))``. ``T(u)`` is the number of
55
+ triangles through ``u``, which is the fraction of the possible links among
56
+ ``u``'s neighbours that actually exist. Self-loops are ignored.
57
+
58
+ With ``weighted=True`` each triangle counts as the geometric mean of its
59
+ three edge weights, after dividing by the largest weight in the graph
60
+ (Onnela et al. 2005). This matches networkx.
61
+
62
+ >>> from graphwise import Graph
63
+ >>> clustering(Graph([(1, 2), (2, 3), (3, 1), (3, 4)]))
64
+ {1: 1.0, 2: 1.0, 3: 0.3333333333333333, 4: 0.0}
65
+
66
+ References: Watts, D. J. & Strogatz, S. H. (1998). Collective dynamics of
67
+ 'small-world' networks. *Nature* 393.
68
+ """
69
+ if graph.is_directed:
70
+ raise TypeError("clustering requires an undirected Graph; use graph.to_undirected()")
71
+ adj = graph._adj
72
+ max_w = max((w for nbrs in adj.values() for w in nbrs.values()), default=1) or 1
73
+ out = {}
74
+ for i, nbrs in adj.items():
75
+ i_nbrs = set(nbrs) - {i}
76
+ d = len(i_nbrs)
77
+ if d < 2:
78
+ out[i] = 0.0
79
+ continue
80
+ total = 0.0
81
+ seen: set[Any] = set()
82
+ for j in i_nbrs:
83
+ seen.add(j)
84
+ for k in i_nbrs & (set(adj[j]) - seen): # each triangle once per i
85
+ if weighted:
86
+ total += (adj[i][j] * adj[j][k] * adj[k][i] / max_w**3) ** (1 / 3)
87
+ else:
88
+ total += 1
89
+ out[i] = 2 * total / (d * (d - 1))
90
+ return out
91
+
92
+
93
+ def average_clustering(graph: Graph[Any], *, weighted: bool = False) -> float:
94
+ """Mean of :func:`clustering` over all nodes, with zeros included."""
95
+ if len(graph) == 0:
96
+ raise ValueError("average clustering is undefined for the empty graph")
97
+ c = clustering(graph, weighted=weighted)
98
+ return sum(c.values()) / len(c)
99
+
100
+
101
+ def approximate_average_clustering(
102
+ graph: Graph[Any], trials: int = 1000, *, seed: int | random.Random | None = None
103
+ ) -> float:
104
+ """Estimate :func:`average_clustering` by random sampling, in O(trials) time.
105
+
106
+ Each trial picks a random node and two of its neighbours, and checks
107
+ whether those two are linked. The fraction of closed triangles is an
108
+ unbiased estimate of the average clustering. The standard error is at most
109
+ ``0.5 / sqrt(trials)``, whatever the graph size, which makes this the way
110
+ to go on graphs too large for the exact method.
111
+
112
+ References: Schank, T. & Wagner, D. (2005). Approximating clustering
113
+ coefficient and transitivity. *JGAA* 9(2).
114
+ """
115
+ if graph.is_directed:
116
+ raise TypeError("clustering requires an undirected Graph; use graph.to_undirected()")
117
+ if len(graph) == 0:
118
+ raise ValueError("average clustering is undefined for the empty graph")
119
+ rng = _rng(seed)
120
+ adj = graph._adj
121
+ nodes = list(adj)
122
+ closed = 0
123
+ for _ in range(trials):
124
+ u = rng.choice(nodes)
125
+ nbrs = [v for v in adj[u] if v != u]
126
+ if len(nbrs) < 2:
127
+ continue
128
+ a, b = rng.sample(nbrs, 2)
129
+ if b in adj[a]:
130
+ closed += 1
131
+ return closed / trials
132
+
133
+
134
+ # --------------------------------------------------------------------------
135
+ # Modularity
136
+ # --------------------------------------------------------------------------
137
+ def _check_partition(nodes: Iterable[Any], communities: Iterable[Iterable[Any]]) -> list[set[Any]]:
138
+ comms = [set(c) for c in communities]
139
+ seen: set[Any] = set()
140
+ for c in comms:
141
+ if seen & c:
142
+ raise ValueError("communities overlap; they must form a partition")
143
+ seen |= c
144
+ if seen != set(nodes):
145
+ raise ValueError("communities must cover every node exactly once")
146
+ return comms
147
+
148
+
149
+ def modularity(
150
+ graph: _BaseGraph[Any],
151
+ communities: Iterable[Iterable[Hashable]],
152
+ *,
153
+ resolution: float = 1.0,
154
+ weighted: bool = True,
155
+ ) -> float:
156
+ """Newman-Girvan modularity of a partition of the nodes.
157
+
158
+ Undirected: ``Q = Σ_c [ L_c / m - γ (d_c / 2m)² ]``. ``L_c`` is the weight
159
+ inside community ``c``, ``d_c`` is the total degree of its nodes, and
160
+ ``m`` is the total edge weight. Directed graphs use the out-degree times
161
+ in-degree form (Leicht & Newman, 2008). ``Q`` is at most 1. Values above
162
+ about 0.3 usually mean real community structure. A larger ``resolution``
163
+ (γ) favours smaller communities.
164
+
165
+ >>> from graphwise import Graph
166
+ >>> g = Graph([(1, 2), (2, 3), (3, 1), (4, 5), (5, 6), (6, 4), (3, 4)])
167
+ >>> round(modularity(g, [{1, 2, 3}, {4, 5, 6}]), 4)
168
+ 0.3571
169
+
170
+ References: Newman, M. E. J. & Girvan, M. (2004). Finding and evaluating
171
+ community structure in networks. *Phys. Rev. E* 69.
172
+ """
173
+ comms = _check_partition(graph, communities)
174
+ adj = graph._adj
175
+
176
+ def wt(w: float) -> float:
177
+ return w if weighted else 1
178
+
179
+ out_deg: dict[Any, float] = defaultdict(float)
180
+ in_deg: dict[Any, float] = defaultdict(float)
181
+ for u, v, w in graph.edges():
182
+ out_deg[u] += wt(w)
183
+ in_deg[v] += wt(w)
184
+ if not graph.is_directed: # an undirected edge adds to both endpoints' degree
185
+ out_deg[v] += wt(w)
186
+ in_deg[u] += wt(w)
187
+ deg_sum = sum(out_deg.values())
188
+ if deg_sum == 0:
189
+ raise ValueError("modularity is undefined for a graph with no edge weight")
190
+ if graph.is_directed:
191
+ m = deg_sum
192
+ norm = 1 / m**2
193
+ else:
194
+ m = deg_sum / 2
195
+ norm = 1 / deg_sum**2
196
+
197
+ q = 0.0
198
+ for c in comms:
199
+ internal = 0.0
200
+ for u in c:
201
+ for v, w in adj[u].items():
202
+ if v in c:
203
+ internal += wt(w)
204
+ if not graph.is_directed:
205
+ loops = sum(wt(adj[u][u]) for u in c if u in adj[u])
206
+ internal = (internal + loops) / 2 # each edge was seen from both ends
207
+ out_sum = sum(out_deg[u] for u in c)
208
+ in_sum = sum(in_deg[u] for u in c) if graph.is_directed else out_sum
209
+ q += internal / m - resolution * out_sum * in_sum * norm
210
+ return q
211
+
212
+
213
+ # --------------------------------------------------------------------------
214
+ # Label propagation
215
+ # --------------------------------------------------------------------------
216
+ def _label_votes(
217
+ adj: Adj, node: Any, labels: Mapping[Any, Any], weighted: bool
218
+ ) -> dict[Any, float]:
219
+ votes: dict[Any, float] = defaultdict(float)
220
+ for v, w in adj[node].items():
221
+ if v != node and labels.get(v) is not None:
222
+ votes[labels[v]] += w if weighted else 1
223
+ return votes
224
+
225
+
226
+ def _propagate(
227
+ adj: Adj,
228
+ labels: dict[Any, Any],
229
+ frozen: set[Any],
230
+ weighted: bool,
231
+ rng: random.Random,
232
+ max_iter: int,
233
+ ) -> dict[Any, Any]:
234
+ nodes = [v for v in adj if v not in frozen]
235
+ for _ in range(max_iter):
236
+ rng.shuffle(nodes)
237
+ changed = False
238
+ for v in nodes:
239
+ votes = _label_votes(adj, v, labels, weighted)
240
+ if not votes:
241
+ continue
242
+ top = max(votes.values())
243
+ best = [lbl for lbl, c in votes.items() if c == top]
244
+ if labels[v] not in best: # keep the current label on a tie, so it converges
245
+ labels[v] = rng.choice(best)
246
+ changed = True
247
+ if not changed:
248
+ break
249
+ return labels
250
+
251
+
252
+ def label_propagation(
253
+ graph: _BaseGraph[Any],
254
+ *,
255
+ weighted: bool = False,
256
+ seed: int | random.Random | None = None,
257
+ max_iter: int = 100,
258
+ ) -> list[set[Any]]:
259
+ """Asynchronous label propagation community detection (Raghavan et al., 2007).
260
+
261
+ Every node starts with its own label. In a random order, each node takes
262
+ the label most common among its neighbours (weighted by edge weight if
263
+ ``weighted=True``), with ties broken at random. The process stops when
264
+ every node already holds one of its neighbourhood's top labels. Each pass
265
+ costs O(E), and only a few passes are usually needed.
266
+
267
+ The result depends on the random order, so pass ``seed`` for
268
+ reproducibility.
269
+
270
+ >>> from graphwise import Graph
271
+ >>> g = Graph([(1, 2), (2, 3), (3, 1), (4, 5), (5, 6), (6, 4)])
272
+ >>> sorted(sorted(c) for c in label_propagation(g, seed=1))
273
+ [[1, 2, 3], [4, 5, 6]]
274
+
275
+ References: Raghavan, Albert & Kumara (2007). Near linear time algorithm to
276
+ detect community structures in large-scale networks. *Phys. Rev. E* 76.
277
+ """
278
+ adj = _undirected_adj(graph)
279
+ labels = {v: i for i, v in enumerate(adj)}
280
+ labels = _propagate(adj, labels, set(), weighted, _rng(seed), max_iter)
281
+ groups: dict[Any, set[Any]] = defaultdict(set)
282
+ for v, lbl in labels.items():
283
+ groups[lbl].add(v)
284
+ return list(groups.values())
285
+
286
+
287
+ def propagate_labels(
288
+ graph: _BaseGraph[Any],
289
+ seed_labels: Mapping[Hashable, Hashable],
290
+ *,
291
+ weighted: bool = False,
292
+ seed: int | random.Random | None = None,
293
+ max_iter: int = 100,
294
+ ) -> dict[Any, Any]:
295
+ """Semi-supervised label propagation: spread a few known labels to the rest.
296
+
297
+ Nodes listed in ``seed_labels`` keep their label throughout. The other
298
+ nodes start unlabelled and take the majority label among their labelled
299
+ neighbours. A node that no seed can reach ends up labelled ``None``.
300
+
301
+ Typical uses: classify accounts from a handful of confirmed fraud cases,
302
+ tag documents from a few hand-labelled examples, or assign sectors in a
303
+ supply-chain graph.
304
+
305
+ >>> from graphwise import Graph
306
+ >>> g = Graph([("a", "b"), ("b", "c"), ("x", "y"), ("y", "z"), ("c", "x")])
307
+ >>> propagate_labels(g, {"a": "red", "z": "blue"}, seed=0)["b"]
308
+ 'red'
309
+ """
310
+ adj = _undirected_adj(graph)
311
+ for v in seed_labels:
312
+ graph._check_node(v)
313
+ labels: dict[Any, Any] = {v: seed_labels.get(v) for v in adj}
314
+ return _propagate(adj, labels, set(seed_labels), weighted, _rng(seed), max_iter)
315
+
316
+
317
+ # --------------------------------------------------------------------------
318
+ # Louvain
319
+ # --------------------------------------------------------------------------
320
+ def _louvain_one_level(
321
+ adj: Adj, resolution: float, rng: random.Random
322
+ ) -> tuple[dict[Any, Any], bool]:
323
+ """Local moving phase: move single nodes while modularity strictly improves."""
324
+ # Weighted degree. A self-loop counts twice, as usual for undirected graphs.
325
+ k = {u: sum(nbrs.values()) + nbrs.get(u, 0) for u, nbrs in adj.items()}
326
+ m2 = sum(k.values())
327
+ com = {u: u for u in adj}
328
+ tot = dict(k) # total degree of each community
329
+ order = list(adj)
330
+ rng.shuffle(order)
331
+ improved = False
332
+ moved = True
333
+ while moved:
334
+ moved = False
335
+ for u in order:
336
+ c_old = com[u]
337
+ links: dict[Any, float] = defaultdict(float)
338
+ for v, w in adj[u].items():
339
+ if v != u:
340
+ links[com[v]] += w
341
+ tot[c_old] -= k[u] # take u out of its community
342
+ # The gain from joining c is proportional to k_{u,in}(c) - γ·Σtot(c)·k_u / 2m.
343
+ best_c = c_old
344
+ best_gain = links.get(c_old, 0.0) - resolution * tot[c_old] * k[u] / m2
345
+ for c, w_in in links.items():
346
+ gain = w_in - resolution * tot[c] * k[u] / m2
347
+ if gain > best_gain + 1e-12:
348
+ best_c, best_gain = c, gain
349
+ tot[best_c] += k[u]
350
+ if best_c != c_old:
351
+ com[u] = best_c
352
+ moved = improved = True
353
+ return com, improved
354
+
355
+
356
+ def _aggregate(adj: Adj, com: dict[Any, Any]) -> Adj:
357
+ """Turn each community into a single node. Internal weight becomes a self-loop."""
358
+ new: dict[Any, dict[Any, float]] = defaultdict(lambda: defaultdict(float))
359
+ for u, nbrs in adj.items():
360
+ cu = com[u]
361
+ new[cu] # touch, so isolated communities stay in the graph
362
+ for v, w in nbrs.items():
363
+ cv = com[v]
364
+ if u == v:
365
+ new[cu][cu] += w
366
+ elif cu == cv:
367
+ new[cu][cu] += w / 2 # the internal edge is seen from both u and v
368
+ else:
369
+ new[cu][cv] += w
370
+ return {u: dict(nbrs) for u, nbrs in new.items()}
371
+
372
+
373
+ def louvain(
374
+ graph: _BaseGraph[Any],
375
+ *,
376
+ resolution: float = 1.0,
377
+ weighted: bool = True,
378
+ seed: int | random.Random | None = None,
379
+ ) -> list[set[Any]]:
380
+ """Louvain community detection by greedy, multi-level modularity optimisation.
381
+
382
+ Two phases repeat until modularity stops improving:
383
+
384
+ 1. **Local moving.** Visit the nodes in random order. Move each node into
385
+ the neighbouring community that raises modularity most, and keep going
386
+ until no single move helps. The change in modularity from a move
387
+ depends only on the node's links to the target community and that
388
+ community's total degree, so each pass costs O(E).
389
+ 2. **Aggregation.** Merge each community into one "super-node". Edges
390
+ between communities become weighted edges, and edges inside a
391
+ community become a self-loop. Then run phase 1 again on the smaller
392
+ graph.
393
+
394
+ In practice it takes about O(E log V) time, and it scales to graphs with
395
+ millions of edges. The result depends on the visit order, so pass
396
+ ``seed`` for reproducibility. Communities come back largest first.
397
+
398
+ >>> from graphwise import Graph
399
+ >>> g = Graph([(1, 2), (2, 3), (3, 1), (4, 5), (5, 6), (6, 4), (3, 4)])
400
+ >>> sorted(sorted(c) for c in louvain(g, seed=0))
401
+ [[1, 2, 3], [4, 5, 6]]
402
+
403
+ References: Blondel, Guillaume, Lambiotte & Lefebvre (2008). Fast unfolding
404
+ of communities in large networks. *J. Stat. Mech.* P10008.
405
+ """
406
+ rng = _rng(seed)
407
+ adj = _undirected_adj(graph)
408
+ if not weighted:
409
+ adj = {u: dict.fromkeys(nbrs, 1.0) for u, nbrs in adj.items()}
410
+ members: dict[Any, set[Any]] = {u: {u} for u in adj}
411
+ if not any(w for nbrs in adj.values() for w in nbrs.values()): # no edge weight at all
412
+ return list(members.values())
413
+ while True:
414
+ com, improved = _louvain_one_level(adj, resolution, rng)
415
+ if not improved:
416
+ break
417
+ merged: dict[Any, set[Any]] = defaultdict(set)
418
+ for u, c in com.items():
419
+ merged[c] |= members[u]
420
+ members = dict(merged)
421
+ adj = _aggregate(adj, com)
422
+ return sorted(members.values(), key=len, reverse=True)
@@ -0,0 +1,245 @@
1
+ """Connectivity: components, strongly connected components, bridges, cut vertices.
2
+
3
+ * **Connected components** answer "which nodes can reach each other?" in an
4
+ undirected graph.
5
+ * **Strongly connected components (SCCs)** answer the same question for a
6
+ directed graph, where reaching ``v`` from ``u`` and ``u`` from ``v`` must
7
+ both hold. Shrinking each SCC to a single node always leaves a DAG (the
8
+ *condensation*).
9
+ * **Bridges** are edges, and **articulation points** (cut vertices) are
10
+ nodes, whose removal disconnects the graph. They are the single points of
11
+ failure in a network.
12
+
13
+ Tarjan's algorithms find SCCs, bridges and articulation points in a single
14
+ O(V + E) DFS. Each node is given ``disc[v]``, its DFS discovery time, and
15
+ ``low[v]``, the smallest discovery time reachable from ``v``'s DFS subtree
16
+ using at most one back edge.
17
+
18
+ * For a tree edge ``u -> v``: if ``low[v] > disc[u]``, nothing below ``v`` can
19
+ get back above ``u`` except through this edge, so ``(u, v)`` is a bridge.
20
+ * If ``low[v] >= disc[u]`` and ``u`` is not the root, then ``u`` is an
21
+ articulation point. The root is one when it has two or more DFS children.
22
+ * In the SCC version, a node with ``low[v] == disc[v]`` is the root of a
23
+ component, which is popped off the stack.
24
+
25
+ Every DFS here keeps an explicit stack, so graphs with long paths (over about
26
+ 1000 nodes) do not hit Python's recursion limit.
27
+
28
+ References
29
+ ----------
30
+ * Tarjan, R. E. (1972). Depth-first search and linear graph algorithms.
31
+ *SIAM J. Computing* 1(2).
32
+ * Hopcroft, J. & Tarjan, R. E. (1973). Algorithm 447: efficient algorithms for
33
+ graph manipulation. *CACM* 16(6).
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ from collections.abc import Iterator
39
+ from typing import Any
40
+
41
+ from .graph import DiGraph, Graph, _BaseGraph, _undirected_adj
42
+
43
+ __all__ = [
44
+ "connected_components",
45
+ "is_connected",
46
+ "strongly_connected_components",
47
+ "condensation",
48
+ "bridges",
49
+ "articulation_points",
50
+ ]
51
+
52
+
53
+ def connected_components(graph: _BaseGraph[Any]) -> list[set[Any]]:
54
+ """Return the connected components as a list of sets.
55
+
56
+ For a :class:`DiGraph`, edge direction is ignored, which gives the
57
+ *weakly* connected components. Time O(V + E).
58
+
59
+ >>> from graphwise import Graph
60
+ >>> connected_components(Graph([(1, 2), (3, 4)], nodes=[5]))
61
+ [{5}, {1, 2}, {3, 4}]
62
+ """
63
+ adj = _undirected_adj(graph)
64
+ seen: set[Any] = set()
65
+ components = []
66
+ for root in adj:
67
+ if root in seen:
68
+ continue
69
+ seen.add(root)
70
+ comp = {root}
71
+ frontier = [root]
72
+ while frontier:
73
+ u = frontier.pop()
74
+ for v in adj[u]:
75
+ if v not in seen:
76
+ seen.add(v)
77
+ comp.add(v)
78
+ frontier.append(v)
79
+ components.append(comp)
80
+ return components
81
+
82
+
83
+ def is_connected(graph: _BaseGraph[Any]) -> bool:
84
+ """Return True if the graph has exactly one (weakly) connected component."""
85
+ if len(graph) == 0:
86
+ raise ValueError("connectivity is undefined for the empty graph")
87
+ return len(connected_components(graph)) == 1
88
+
89
+
90
+ def strongly_connected_components(graph: DiGraph[Any]) -> list[set[Any]]:
91
+ """Tarjan's algorithm. Returns the SCCs in reverse topological order.
92
+
93
+ Each SCC comes out only after every SCC it can reach, so the *last*
94
+ component is a source in the condensation DAG.
95
+
96
+ Time O(V + E).
97
+
98
+ >>> from graphwise import DiGraph
99
+ >>> g = DiGraph([(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 5), (5, 3)])
100
+ >>> strongly_connected_components(g)
101
+ [{3, 4, 5}, {0, 1, 2}]
102
+ """
103
+ if not graph.is_directed:
104
+ raise TypeError("strongly connected components require a DiGraph")
105
+ adj = graph._adj
106
+ disc: dict[Any, int] = {}
107
+ low: dict[Any, int] = {}
108
+ stack: list[Any] = []
109
+ on_stack: set[Any] = set()
110
+ result: list[set[Any]] = []
111
+ clock = 0
112
+ for root in adj:
113
+ if root in disc:
114
+ continue
115
+ disc[root] = low[root] = clock
116
+ clock += 1
117
+ stack.append(root)
118
+ on_stack.add(root)
119
+ work: list[tuple[Any, Iterator[Any]]] = [(root, iter(adj[root]))]
120
+ while work:
121
+ v, it = work[-1]
122
+ for w in it:
123
+ if w not in disc: # tree edge: descend
124
+ disc[w] = low[w] = clock
125
+ clock += 1
126
+ stack.append(w)
127
+ on_stack.add(w)
128
+ work.append((w, iter(adj[w])))
129
+ break
130
+ if w in on_stack: # back or cross edge within the current SCC
131
+ low[v] = min(low[v], disc[w])
132
+ else: # v is finished
133
+ work.pop()
134
+ if work:
135
+ parent = work[-1][0]
136
+ low[parent] = min(low[parent], low[v])
137
+ if low[v] == disc[v]: # v is the root of an SCC
138
+ comp = set()
139
+ while True:
140
+ w = stack.pop()
141
+ on_stack.discard(w)
142
+ comp.add(w)
143
+ if w == v:
144
+ break
145
+ result.append(comp)
146
+ return result
147
+
148
+
149
+ def condensation(graph: DiGraph[Any]) -> tuple[DiGraph[int], dict[Any, int]]:
150
+ """Collapse each SCC to a single node. The result is always a DAG.
151
+
152
+ Returns ``(dag, membership)``. ``dag`` has nodes ``0..k-1``, numbered in
153
+ the order :func:`strongly_connected_components` returns the SCCs, and
154
+ ``membership`` maps each original node to its SCC's number. Every DAG
155
+ algorithm, such as topological sort or longest path, can then run on the
156
+ condensation.
157
+
158
+ >>> from graphwise import DiGraph
159
+ >>> dag, member = condensation(DiGraph([(1, 2), (2, 1), (2, 3)]))
160
+ >>> dag.edges(), member[1] == member[2] != member[3]
161
+ ([(1, 0, 1)], True)
162
+ """
163
+ sccs = strongly_connected_components(graph)
164
+ member = {v: i for i, comp in enumerate(sccs) for v in comp}
165
+ dag: DiGraph[int] = DiGraph(nodes=range(len(sccs)))
166
+ for u, v, _ in graph.edges():
167
+ cu, cv = member[u], member[v]
168
+ if cu != cv:
169
+ dag.add_edge(cu, cv)
170
+ return dag, member
171
+
172
+
173
+ _NO_PARENT = object()
174
+
175
+
176
+ def _lowpoint_dfs(graph: Graph[Any]) -> tuple[list[tuple[Any, Any]], set[Any]]:
177
+ """One iterative Hopcroft-Tarjan DFS that finds both bridges and cut vertices."""
178
+ if graph.is_directed:
179
+ raise TypeError(
180
+ "bridges and articulation points are defined for undirected graphs; "
181
+ "call graph.to_undirected() first"
182
+ )
183
+ adj = graph._adj
184
+ disc: dict[Any, int] = {}
185
+ low: dict[Any, int] = {}
186
+ found_bridges: list[tuple[Any, Any]] = []
187
+ cut_vertices: set[Any] = set()
188
+ clock = 0
189
+ for root in adj:
190
+ if root in disc:
191
+ continue
192
+ disc[root] = low[root] = clock
193
+ clock += 1
194
+ root_children = 0
195
+ work: list[tuple[Any, Any, Iterator[Any]]] = [(root, _NO_PARENT, iter(adj[root]))]
196
+ while work:
197
+ u, parent, it = work[-1]
198
+ for v in it:
199
+ if v in (u, parent): # skip self-loops and the tree edge back up
200
+ continue
201
+ if v in disc: # back edge
202
+ low[u] = min(low[u], disc[v])
203
+ else:
204
+ disc[v] = low[v] = clock
205
+ clock += 1
206
+ work.append((v, u, iter(adj[v])))
207
+ break
208
+ else: # u is finished: report to its parent
209
+ work.pop()
210
+ if parent is _NO_PARENT:
211
+ continue
212
+ low[parent] = min(low[parent], low[u])
213
+ if low[u] > disc[parent]:
214
+ found_bridges.append((parent, u))
215
+ if parent == root:
216
+ root_children += 1
217
+ elif low[u] >= disc[parent]:
218
+ cut_vertices.add(parent)
219
+ if root_children > 1:
220
+ cut_vertices.add(root)
221
+ return found_bridges, cut_vertices
222
+
223
+
224
+ def bridges(graph: Graph[Any]) -> list[tuple[Any, Any]]:
225
+ """Return every bridge: an edge whose removal adds a connected component.
226
+
227
+ Time O(V + E).
228
+
229
+ >>> from graphwise import Graph
230
+ >>> bridges(Graph([(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 5), (5, 3)]))
231
+ [(1, 3)]
232
+ """
233
+ return _lowpoint_dfs(graph)[0]
234
+
235
+
236
+ def articulation_points(graph: Graph[Any]) -> set[Any]:
237
+ """Return every articulation point: a node whose removal adds a component.
238
+
239
+ Time O(V + E).
240
+
241
+ >>> from graphwise import Graph
242
+ >>> sorted(articulation_points(Graph([(0, 1), (1, 2), (2, 0), (1, 3), (3, 4)])))
243
+ [1, 3]
244
+ """
245
+ return _lowpoint_dfs(graph)[1]