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 +151 -0
- graphwise/centrality.py +314 -0
- graphwise/community.py +422 -0
- graphwise/connectivity.py +245 -0
- graphwise/dag.py +160 -0
- graphwise/eulerian.py +170 -0
- graphwise/exceptions.py +47 -0
- graphwise/flow.py +155 -0
- graphwise/graph.py +321 -0
- graphwise/py.typed +0 -0
- graphwise/shortest_paths.py +502 -0
- graphwise/spanning_trees.py +122 -0
- graphwise/traversal.py +129 -0
- graphwise/union_find.py +127 -0
- graphwise-0.1.0.dist-info/METADATA +247 -0
- graphwise-0.1.0.dist-info/RECORD +18 -0
- graphwise-0.1.0.dist-info/WHEEL +4 -0
- graphwise-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
"""Shortest paths: single-source, point-to-point, all-pairs and k-shortest.
|
|
2
|
+
|
|
3
|
+
Choosing an algorithm
|
|
4
|
+
---------------------
|
|
5
|
+
===================== ========================== ================== ==================
|
|
6
|
+
Algorithm Problem Negative weights? Time
|
|
7
|
+
===================== ========================== ================== ==================
|
|
8
|
+
BFS single source, unweighted n/a O(V + E)
|
|
9
|
+
Dijkstra single source no O((V + E) log V)
|
|
10
|
+
A* one pair, with a heuristic no ≤ Dijkstra
|
|
11
|
+
Bellman-Ford single source yes, finds cycles O(VE)
|
|
12
|
+
Floyd-Warshall all pairs, dense graphs yes, finds cycles O(V³)
|
|
13
|
+
Johnson all pairs, sparse graphs yes, finds cycles O(VE + V² log V)
|
|
14
|
+
Yen k shortest simple paths no O(kV · Dijkstra)
|
|
15
|
+
===================== ========================== ================== ==================
|
|
16
|
+
|
|
17
|
+
Conventions
|
|
18
|
+
-----------
|
|
19
|
+
Single-source functions return ``(dist, pred)``. ``dist[v]`` is the
|
|
20
|
+
shortest distance from the source to ``v``, and ``pred[v]`` is the node
|
|
21
|
+
before ``v`` on that path. Unreachable nodes appear in neither dict. Turn
|
|
22
|
+
``pred`` into a path with :func:`reconstruct_path`. All-pairs functions
|
|
23
|
+
return the same thing as dicts of dicts, keyed by source first.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import heapq
|
|
29
|
+
from collections.abc import Callable, Collection, Hashable
|
|
30
|
+
from itertools import count, pairwise
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
from .exceptions import NegativeCycle, NoPath
|
|
34
|
+
from .graph import _BaseGraph
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"dijkstra",
|
|
38
|
+
"astar",
|
|
39
|
+
"bellman_ford",
|
|
40
|
+
"floyd_warshall",
|
|
41
|
+
"johnson",
|
|
42
|
+
"yen_k_shortest_paths",
|
|
43
|
+
"shortest_path",
|
|
44
|
+
"reconstruct_path",
|
|
45
|
+
"path_weight",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
Dist = dict[Any, float]
|
|
49
|
+
Pred = dict[Any, Any]
|
|
50
|
+
WeightFn = Callable[[Any, Any, float], float]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def reconstruct_path(pred: Pred, source: Hashable, target: Hashable) -> list[Any]:
|
|
54
|
+
"""Follow predecessor links from ``target`` back to ``source``.
|
|
55
|
+
|
|
56
|
+
Raises :class:`NoPath` if ``target`` was not reached.
|
|
57
|
+
|
|
58
|
+
>>> reconstruct_path({"b": "a", "c": "b"}, "a", "c")
|
|
59
|
+
['a', 'b', 'c']
|
|
60
|
+
"""
|
|
61
|
+
if target == source:
|
|
62
|
+
return [source]
|
|
63
|
+
if target not in pred:
|
|
64
|
+
raise NoPath(f"no path from {source!r} to {target!r}")
|
|
65
|
+
path = [target]
|
|
66
|
+
while path[-1] != source:
|
|
67
|
+
path.append(pred[path[-1]])
|
|
68
|
+
path.reverse()
|
|
69
|
+
return path
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def path_weight(graph: _BaseGraph[Any], path: list[Any]) -> float:
|
|
73
|
+
"""Return the total weight of ``path``, a list of nodes."""
|
|
74
|
+
return sum(graph.weight(u, v) for u, v in pairwise(path))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# --------------------------------------------------------------------------
|
|
78
|
+
# Dijkstra
|
|
79
|
+
# --------------------------------------------------------------------------
|
|
80
|
+
def _dijkstra(
|
|
81
|
+
adj: dict[Any, dict[Any, float]],
|
|
82
|
+
source: Any,
|
|
83
|
+
target: Any = None,
|
|
84
|
+
*,
|
|
85
|
+
weight: WeightFn | None = None,
|
|
86
|
+
blocked_nodes: Collection[Any] = (),
|
|
87
|
+
blocked_edges: Collection[tuple[Any, Any]] = (),
|
|
88
|
+
) -> tuple[Dist, Pred]:
|
|
89
|
+
"""The Dijkstra engine that Johnson and Yen reuse with their own options."""
|
|
90
|
+
dist: Dist = {}
|
|
91
|
+
pred: Pred = {}
|
|
92
|
+
best: dict[Any, float] = {source: 0}
|
|
93
|
+
tie = count() # tie-breaker, so nodes never need to be comparable
|
|
94
|
+
heap: list[tuple[float, int, Any]] = [(0, next(tie), source)]
|
|
95
|
+
while heap:
|
|
96
|
+
d, _, u = heapq.heappop(heap)
|
|
97
|
+
if u in dist: # stale entry: u was already settled more cheaply
|
|
98
|
+
continue
|
|
99
|
+
dist[u] = d
|
|
100
|
+
if u == target:
|
|
101
|
+
break
|
|
102
|
+
for v, w in adj[u].items():
|
|
103
|
+
if v in dist or v in blocked_nodes or (u, v) in blocked_edges:
|
|
104
|
+
continue
|
|
105
|
+
if weight is not None:
|
|
106
|
+
w = weight(u, v, w)
|
|
107
|
+
if w < 0:
|
|
108
|
+
raise ValueError(
|
|
109
|
+
f"Dijkstra requires non-negative weights; edge ({u!r}, {v!r}) "
|
|
110
|
+
f"has weight {w}. Use bellman_ford or johnson instead."
|
|
111
|
+
)
|
|
112
|
+
nd = d + w
|
|
113
|
+
if v not in best or nd < best[v]:
|
|
114
|
+
best[v] = nd
|
|
115
|
+
pred[v] = u
|
|
116
|
+
heapq.heappush(heap, (nd, next(tie), v))
|
|
117
|
+
# Keep only settled nodes. With an early exit, pred may hold tentative entries.
|
|
118
|
+
return dist, {v: p for v, p in pred.items() if v in dist}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def dijkstra(
|
|
122
|
+
graph: _BaseGraph[Any], source: Hashable, target: Hashable | None = None
|
|
123
|
+
) -> tuple[Dist, Pred]:
|
|
124
|
+
"""Single-source shortest paths for non-negative weights.
|
|
125
|
+
|
|
126
|
+
Dijkstra's algorithm is greedy. It keeps a min-heap of tentative
|
|
127
|
+
distances and repeatedly *settles* the closest unsettled node. That
|
|
128
|
+
node's distance is then final, because with non-negative weights any
|
|
129
|
+
other route to it would have to be at least as long. Each settled node
|
|
130
|
+
*relaxes* its outgoing edges.
|
|
131
|
+
|
|
132
|
+
If ``target`` is given, the search stops as soon as the target is settled.
|
|
133
|
+
|
|
134
|
+
Time O((V + E) log V) with a binary heap, space O(V).
|
|
135
|
+
|
|
136
|
+
>>> from graphwise import DiGraph
|
|
137
|
+
>>> g = DiGraph([(1, 2, 5), (2, 3, 2), (1, 4, 9), (1, 5, 3), (5, 6, 2), (6, 4, 2)])
|
|
138
|
+
>>> dist, pred = dijkstra(g, 1)
|
|
139
|
+
>>> dist[4], reconstruct_path(pred, 1, 4)
|
|
140
|
+
(7, [1, 5, 6, 4])
|
|
141
|
+
|
|
142
|
+
References: Dijkstra, E. W. (1959). A note on two problems in connexion
|
|
143
|
+
with graphs. *Numerische Mathematik* 1.
|
|
144
|
+
"""
|
|
145
|
+
graph._check_node(source)
|
|
146
|
+
return _dijkstra(graph._adj, source, target)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
# --------------------------------------------------------------------------
|
|
150
|
+
# A*
|
|
151
|
+
# --------------------------------------------------------------------------
|
|
152
|
+
def astar(
|
|
153
|
+
graph: _BaseGraph[Any],
|
|
154
|
+
source: Hashable,
|
|
155
|
+
target: Hashable,
|
|
156
|
+
heuristic: Callable[[Any, Any], float] | None = None,
|
|
157
|
+
) -> tuple[float, list[Any]]:
|
|
158
|
+
"""Point-to-point shortest path guided by a heuristic. Returns ``(length, path)``.
|
|
159
|
+
|
|
160
|
+
A* is Dijkstra with the priority queue ordered by ``g(v) + h(v)``.
|
|
161
|
+
``g(v)`` is the known distance from ``source`` to ``v``, and ``h(v)``
|
|
162
|
+
estimates the remaining distance from ``v`` to ``target``. The result is
|
|
163
|
+
optimal if ``h`` is *admissible*, meaning it never overestimates. Typical
|
|
164
|
+
choices are straight-line distance on a map, or Manhattan distance on a
|
|
165
|
+
grid. With ``h = 0`` (the default), A* is exactly Dijkstra.
|
|
166
|
+
|
|
167
|
+
This version reopens a node when it finds a cheaper route, so it stays
|
|
168
|
+
correct for admissible heuristics that are not *consistent*.
|
|
169
|
+
|
|
170
|
+
Raises :class:`NoPath` if ``target`` is unreachable.
|
|
171
|
+
|
|
172
|
+
>>> from graphwise import Graph
|
|
173
|
+
>>> grid = Graph([((x, y), (x + 1, y)) for x in range(3) for y in range(4)]
|
|
174
|
+
... + [((x, y), (x, y + 1)) for x in range(4) for y in range(3)])
|
|
175
|
+
>>> manhattan = lambda a, b: abs(a[0] - b[0]) + abs(a[1] - b[1])
|
|
176
|
+
>>> astar(grid, (0, 0), (3, 3), manhattan)[0]
|
|
177
|
+
6
|
|
178
|
+
|
|
179
|
+
References: Hart, Nilsson & Raphael (1968). A formal basis for the
|
|
180
|
+
heuristic determination of minimum cost paths. *IEEE Trans. SSC* 4(2).
|
|
181
|
+
"""
|
|
182
|
+
graph._check_node(source)
|
|
183
|
+
graph._check_node(target)
|
|
184
|
+
h = heuristic or (lambda _u, _t: 0)
|
|
185
|
+
adj = graph._adj
|
|
186
|
+
g_score: dict[Any, float] = {source: 0}
|
|
187
|
+
pred: Pred = {}
|
|
188
|
+
tie = count()
|
|
189
|
+
heap: list[tuple[float, int, float, Any]] = [(h(source, target), next(tie), 0, source)]
|
|
190
|
+
while heap:
|
|
191
|
+
_, _, g, u = heapq.heappop(heap)
|
|
192
|
+
if u == target:
|
|
193
|
+
return g, reconstruct_path(pred, source, target)
|
|
194
|
+
if g > g_score[u]: # stale entry
|
|
195
|
+
continue
|
|
196
|
+
for v, w in adj[u].items():
|
|
197
|
+
if w < 0:
|
|
198
|
+
raise ValueError(f"A* requires non-negative weights; edge ({u!r}, {v!r})")
|
|
199
|
+
ng = g + w
|
|
200
|
+
if v not in g_score or ng < g_score[v]:
|
|
201
|
+
g_score[v] = ng
|
|
202
|
+
pred[v] = u
|
|
203
|
+
heapq.heappush(heap, (ng + h(v, target), next(tie), ng, v))
|
|
204
|
+
raise NoPath(f"no path from {source!r} to {target!r}")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# --------------------------------------------------------------------------
|
|
208
|
+
# Bellman-Ford
|
|
209
|
+
# --------------------------------------------------------------------------
|
|
210
|
+
def _bellman_ford(adj: dict[Any, dict[Any, float]], dist: Dist) -> tuple[Dist, Pred]:
|
|
211
|
+
"""Relax every edge until nothing changes, starting from ``dist``.
|
|
212
|
+
|
|
213
|
+
Starting with ``dist = {v: 0 for every v}`` is the same as adding a virtual
|
|
214
|
+
source with a zero-weight edge to every node, which is the trick Johnson's
|
|
215
|
+
algorithm uses. Doing it this way means no extra node is added to the
|
|
216
|
+
graph, so it cannot clash with a real node's label.
|
|
217
|
+
"""
|
|
218
|
+
pred: Pred = {}
|
|
219
|
+
# With no negative cycle the values settle within len(adj) - 1 passes, so
|
|
220
|
+
# a pass that still changes something after that means a cycle. (One spare
|
|
221
|
+
# pass covers the all-zero start, which acts like an extra virtual source.)
|
|
222
|
+
for _ in range(len(adj) + 1):
|
|
223
|
+
changed = False
|
|
224
|
+
for u, nbrs in adj.items():
|
|
225
|
+
du = dist.get(u)
|
|
226
|
+
if du is None:
|
|
227
|
+
continue
|
|
228
|
+
for v, w in nbrs.items():
|
|
229
|
+
if v not in dist or du + w < dist[v]:
|
|
230
|
+
dist[v] = du + w
|
|
231
|
+
pred[v] = u
|
|
232
|
+
changed = True
|
|
233
|
+
if not changed:
|
|
234
|
+
return dist, pred
|
|
235
|
+
raise NegativeCycle("graph contains a negative-weight cycle")
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def bellman_ford(graph: _BaseGraph[Any], source: Hashable) -> tuple[Dist, Pred]:
|
|
239
|
+
"""Single-source shortest paths that allow negative edge weights.
|
|
240
|
+
|
|
241
|
+
A shortest path without cycles has at most V - 1 edges, so relaxing every
|
|
242
|
+
edge V - 1 times is enough. If an edge can still be relaxed after that, a
|
|
243
|
+
negative cycle is reachable and "shortest" is undefined, so this raises
|
|
244
|
+
:class:`NegativeCycle`. This version stops early once a pass changes
|
|
245
|
+
nothing.
|
|
246
|
+
|
|
247
|
+
In an undirected graph a negative edge is itself a negative cycle
|
|
248
|
+
(``u -> v -> u``).
|
|
249
|
+
|
|
250
|
+
Time O(VE), space O(V).
|
|
251
|
+
|
|
252
|
+
>>> from graphwise import DiGraph
|
|
253
|
+
>>> g = DiGraph([(1, 2, 5), (2, 3, 2), (1, 4, 9), (3, 4, -3)])
|
|
254
|
+
>>> dist, pred = bellman_ford(g, 1)
|
|
255
|
+
>>> dist[4], reconstruct_path(pred, 1, 4)
|
|
256
|
+
(4, [1, 2, 3, 4])
|
|
257
|
+
|
|
258
|
+
References: Bellman, R. (1958). On a routing problem. *Quarterly of Applied
|
|
259
|
+
Mathematics* 16. Arbitrage detection in currency markets is a classic use:
|
|
260
|
+
with weights ``-log(rate)``, a negative cycle is a profitable loop.
|
|
261
|
+
"""
|
|
262
|
+
graph._check_node(source)
|
|
263
|
+
return _bellman_ford(graph._adj, {source: 0})
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# --------------------------------------------------------------------------
|
|
267
|
+
# All-pairs
|
|
268
|
+
# --------------------------------------------------------------------------
|
|
269
|
+
def floyd_warshall(graph: _BaseGraph[Any]) -> tuple[dict[Any, Dist], dict[Any, Pred]]:
|
|
270
|
+
"""All-pairs shortest paths by dynamic programming over intermediate nodes.
|
|
271
|
+
|
|
272
|
+
After processing node ``k``, ``dist[i][j]`` is the shortest ``i -> j`` path
|
|
273
|
+
whose intermediate nodes all come from the first ``k`` nodes. Only three
|
|
274
|
+
nested loops, which makes it hard to beat on small, dense graphs. Raises
|
|
275
|
+
:class:`NegativeCycle` if a negative cycle exists.
|
|
276
|
+
|
|
277
|
+
Time O(V³), space O(V²).
|
|
278
|
+
|
|
279
|
+
>>> from graphwise import DiGraph
|
|
280
|
+
>>> dist, pred = floyd_warshall(DiGraph([("a", "b", 1), ("b", "c", -2), ("a", "c", 4)]))
|
|
281
|
+
>>> dist["a"]["c"]
|
|
282
|
+
-1
|
|
283
|
+
|
|
284
|
+
References: Floyd, R. W. (1962). Algorithm 97: Shortest Path. *CACM* 5(6).
|
|
285
|
+
"""
|
|
286
|
+
nodes = list(graph._adj)
|
|
287
|
+
inf = float("inf")
|
|
288
|
+
dist = {u: dict.fromkeys(nodes, inf) for u in nodes}
|
|
289
|
+
pred: dict[Any, Pred] = {u: {} for u in nodes}
|
|
290
|
+
for u in nodes:
|
|
291
|
+
dist[u][u] = 0
|
|
292
|
+
for v, w in graph._adj[u].items():
|
|
293
|
+
if w < dist[u][v]:
|
|
294
|
+
dist[u][v] = w
|
|
295
|
+
pred[u][v] = u
|
|
296
|
+
for k in nodes:
|
|
297
|
+
dk = dist[k]
|
|
298
|
+
for i in nodes:
|
|
299
|
+
di = dist[i]
|
|
300
|
+
dik = di[k]
|
|
301
|
+
if dik == inf:
|
|
302
|
+
continue
|
|
303
|
+
for j in nodes:
|
|
304
|
+
nd = dik + dk[j]
|
|
305
|
+
if nd < di[j]:
|
|
306
|
+
di[j] = nd
|
|
307
|
+
pred[i][j] = pred[k][j]
|
|
308
|
+
for u in nodes:
|
|
309
|
+
if dist[u][u] < 0:
|
|
310
|
+
raise NegativeCycle("graph contains a negative-weight cycle")
|
|
311
|
+
finite = {u: {v: d for v, d in dist[u].items() if d != inf} for u in nodes}
|
|
312
|
+
return finite, pred
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def johnson(graph: _BaseGraph[Any]) -> tuple[dict[Any, Dist], dict[Any, Pred]]:
|
|
316
|
+
"""All-pairs shortest paths for sparse graphs that may have negative weights.
|
|
317
|
+
|
|
318
|
+
1. Run Bellman-Ford from a virtual source joined to every node by a
|
|
319
|
+
zero-weight edge. This gives a *potential* ``h(v)`` for every node, and
|
|
320
|
+
raises :class:`NegativeCycle` if a negative cycle exists.
|
|
321
|
+
2. Reweight every edge as ``w'(u, v) = w(u, v) + h(u) - h(v)``. The
|
|
322
|
+
triangle inequality makes every ``w'`` non-negative. Every ``s -> t``
|
|
323
|
+
path changes by the same constant ``h(s) - h(t)``, so the shortest
|
|
324
|
+
paths themselves stay the same.
|
|
325
|
+
3. Run Dijkstra from every node on the reweighted graph, then undo the
|
|
326
|
+
shift: ``d(s, t) = d'(s, t) - h(s) + h(t)``.
|
|
327
|
+
|
|
328
|
+
Time O(VE + V(V + E) log V). On sparse graphs that is far better than
|
|
329
|
+
Floyd-Warshall's O(V³).
|
|
330
|
+
|
|
331
|
+
>>> from graphwise import DiGraph
|
|
332
|
+
>>> dist, pred = johnson(DiGraph([(1, 2, -1), (2, 3, -1), (1, 3, 5)]))
|
|
333
|
+
>>> dist[1][3], reconstruct_path(pred[1], 1, 3)
|
|
334
|
+
(-2, [1, 2, 3])
|
|
335
|
+
|
|
336
|
+
References: Johnson, D. B. (1977). Efficient algorithms for shortest paths
|
|
337
|
+
in sparse networks. *JACM* 24(1).
|
|
338
|
+
"""
|
|
339
|
+
adj = graph._adj
|
|
340
|
+
h, _ = _bellman_ford(adj, dict.fromkeys(adj, 0))
|
|
341
|
+
|
|
342
|
+
def reweight(u: Any, v: Any, w: float) -> float:
|
|
343
|
+
# Mathematically >= 0. Clamp float round-off such as -1e-17.
|
|
344
|
+
return max(0, w + h[u] - h[v])
|
|
345
|
+
|
|
346
|
+
all_dist: dict[Any, Dist] = {}
|
|
347
|
+
all_pred: dict[Any, Pred] = {}
|
|
348
|
+
for s in adj:
|
|
349
|
+
d, p = _dijkstra(adj, s, weight=reweight)
|
|
350
|
+
all_dist[s] = {t: dt - h[s] + h[t] for t, dt in d.items()}
|
|
351
|
+
all_pred[s] = p
|
|
352
|
+
return all_dist, all_pred
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
# --------------------------------------------------------------------------
|
|
356
|
+
# Yen's k shortest simple paths
|
|
357
|
+
# --------------------------------------------------------------------------
|
|
358
|
+
def yen_k_shortest_paths(
|
|
359
|
+
graph: _BaseGraph[Any], source: Hashable, target: Hashable, k: int
|
|
360
|
+
) -> list[tuple[float, list[Any]]]:
|
|
361
|
+
"""The ``k`` shortest loopless paths from ``source`` to ``target``.
|
|
362
|
+
|
|
363
|
+
Returns up to ``k`` pairs of ``(length, path)``, shortest first (fewer
|
|
364
|
+
if fewer simple paths exist).
|
|
365
|
+
|
|
366
|
+
Yen's algorithm builds on the previous path found. For each node of
|
|
367
|
+
that path, taken as the *spur node*, it:
|
|
368
|
+
|
|
369
|
+
* fixes the *root path*, which is the prefix up to the spur node;
|
|
370
|
+
* blocks the next edge of every accepted path that shares that root, so
|
|
371
|
+
the search must branch off somewhere new;
|
|
372
|
+
* blocks the nodes of the root path, so the new path stays simple;
|
|
373
|
+
* runs Dijkstra from the spur node to the target, and joins the result to
|
|
374
|
+
the root to make a candidate.
|
|
375
|
+
|
|
376
|
+
The cheapest candidate becomes the next path. The input graph is never
|
|
377
|
+
modified. Applications include route alternatives, network redundancy
|
|
378
|
+
planning, and ranking candidate explanations in a knowledge graph.
|
|
379
|
+
|
|
380
|
+
Time O(k · V · (V + E) log V).
|
|
381
|
+
|
|
382
|
+
>>> from graphwise import DiGraph
|
|
383
|
+
>>> g = DiGraph([("C", "D", 3), ("C", "E", 2), ("D", "F", 4), ("E", "D", 1),
|
|
384
|
+
... ("E", "F", 2), ("E", "G", 3), ("F", "G", 2), ("F", "H", 1),
|
|
385
|
+
... ("G", "H", 2)])
|
|
386
|
+
>>> [length for length, _ in yen_k_shortest_paths(g, "C", "H", 3)]
|
|
387
|
+
[5, 7, 8]
|
|
388
|
+
|
|
389
|
+
References: Yen, J. Y. (1971). Finding the k shortest loopless paths in a
|
|
390
|
+
network. *Management Science* 17(11).
|
|
391
|
+
"""
|
|
392
|
+
if k < 1:
|
|
393
|
+
raise ValueError("k must be at least 1")
|
|
394
|
+
graph._check_node(source)
|
|
395
|
+
graph._check_node(target)
|
|
396
|
+
adj = graph._adj
|
|
397
|
+
directed = graph.is_directed
|
|
398
|
+
|
|
399
|
+
dist, pred = _dijkstra(adj, source, target)
|
|
400
|
+
if target not in dist:
|
|
401
|
+
return []
|
|
402
|
+
accepted: list[tuple[float, list[Any]]] = [
|
|
403
|
+
(dist[target], reconstruct_path(pred, source, target))
|
|
404
|
+
]
|
|
405
|
+
seen_paths = {tuple(accepted[0][1])}
|
|
406
|
+
candidates: list[tuple[float, int, list[Any]]] = []
|
|
407
|
+
tie = count()
|
|
408
|
+
|
|
409
|
+
while len(accepted) < k:
|
|
410
|
+
prev_path = accepted[-1][1]
|
|
411
|
+
for i in range(len(prev_path) - 1):
|
|
412
|
+
spur = prev_path[i]
|
|
413
|
+
root = prev_path[: i + 1]
|
|
414
|
+
blocked_edges: set[tuple[Any, Any]] = set()
|
|
415
|
+
for _, p in accepted:
|
|
416
|
+
if p[: i + 1] == root and len(p) > i + 1:
|
|
417
|
+
blocked_edges.add((p[i], p[i + 1]))
|
|
418
|
+
if not directed:
|
|
419
|
+
blocked_edges.add((p[i + 1], p[i]))
|
|
420
|
+
blocked_nodes = set(root[:-1])
|
|
421
|
+
sd, sp = _dijkstra(
|
|
422
|
+
adj, spur, target, blocked_nodes=blocked_nodes, blocked_edges=blocked_edges
|
|
423
|
+
)
|
|
424
|
+
if target not in sd:
|
|
425
|
+
continue
|
|
426
|
+
path = root[:-1] + reconstruct_path(sp, spur, target)
|
|
427
|
+
key = tuple(path)
|
|
428
|
+
if key not in seen_paths:
|
|
429
|
+
seen_paths.add(key)
|
|
430
|
+
length = path_weight(graph, root) + sd[target]
|
|
431
|
+
heapq.heappush(candidates, (length, next(tie), path))
|
|
432
|
+
if not candidates:
|
|
433
|
+
break
|
|
434
|
+
length, _, path = heapq.heappop(candidates)
|
|
435
|
+
accepted.append((length, path))
|
|
436
|
+
return accepted
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
# --------------------------------------------------------------------------
|
|
440
|
+
# Convenience front door
|
|
441
|
+
# --------------------------------------------------------------------------
|
|
442
|
+
def shortest_path(
|
|
443
|
+
graph: _BaseGraph[Any],
|
|
444
|
+
source: Hashable,
|
|
445
|
+
target: Hashable,
|
|
446
|
+
*,
|
|
447
|
+
method: str = "auto",
|
|
448
|
+
heuristic: Callable[[Any, Any], float] | None = None,
|
|
449
|
+
) -> tuple[float, list[Any]]:
|
|
450
|
+
"""Return ``(length, path)`` for the shortest ``source -> target`` path.
|
|
451
|
+
|
|
452
|
+
``method`` is one of:
|
|
453
|
+
|
|
454
|
+
* ``"auto"`` (default): A* if a heuristic is given, Bellman-Ford if the
|
|
455
|
+
graph has a negative weight, Dijkstra otherwise.
|
|
456
|
+
* ``"dijkstra"``, ``"bellman_ford"``, ``"astar"``.
|
|
457
|
+
* ``"bfs"``: fewest edges, ignoring weights. The length is the hop count.
|
|
458
|
+
|
|
459
|
+
Raises :class:`NoPath` if ``target`` is unreachable.
|
|
460
|
+
|
|
461
|
+
>>> from graphwise import Graph
|
|
462
|
+
>>> shortest_path(Graph([("a", "b", 1), ("b", "c", 1), ("a", "c", 5)]), "a", "c")
|
|
463
|
+
(2, ['a', 'b', 'c'])
|
|
464
|
+
"""
|
|
465
|
+
graph._check_node(source)
|
|
466
|
+
graph._check_node(target)
|
|
467
|
+
if method == "auto":
|
|
468
|
+
if heuristic is not None:
|
|
469
|
+
method = "astar"
|
|
470
|
+
elif any(w < 0 for _, _, w in graph.edges()):
|
|
471
|
+
method = "bellman_ford"
|
|
472
|
+
else:
|
|
473
|
+
method = "dijkstra"
|
|
474
|
+
|
|
475
|
+
if method == "astar":
|
|
476
|
+
return astar(graph, source, target, heuristic)
|
|
477
|
+
if method == "dijkstra":
|
|
478
|
+
dist, pred = dijkstra(graph, source, target)
|
|
479
|
+
elif method == "bellman_ford":
|
|
480
|
+
dist, pred = bellman_ford(graph, source)
|
|
481
|
+
elif method == "bfs":
|
|
482
|
+
dist, pred = _bfs_paths(graph, source)
|
|
483
|
+
else:
|
|
484
|
+
raise ValueError(f"unknown method {method!r}")
|
|
485
|
+
path = reconstruct_path(pred, source, target)
|
|
486
|
+
return dist[target], path
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _bfs_paths(graph: _BaseGraph[Any], source: Any) -> tuple[Dist, Pred]:
|
|
490
|
+
dist: Dist = {source: 0}
|
|
491
|
+
pred: Pred = {}
|
|
492
|
+
frontier = [source]
|
|
493
|
+
while frontier:
|
|
494
|
+
nxt = []
|
|
495
|
+
for u in frontier:
|
|
496
|
+
for v in graph._adj[u]:
|
|
497
|
+
if v not in dist:
|
|
498
|
+
dist[v] = dist[u] + 1
|
|
499
|
+
pred[v] = u
|
|
500
|
+
nxt.append(v)
|
|
501
|
+
frontier = nxt
|
|
502
|
+
return dist, pred
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Minimum spanning trees (and forests) of undirected graphs.
|
|
2
|
+
|
|
3
|
+
A minimum spanning tree (MST) connects every node using the cheapest possible
|
|
4
|
+
set of edges. It has exactly V - 1 edges and no cycles. If the graph is
|
|
5
|
+
disconnected, these functions return a minimum spanning *forest*, one tree
|
|
6
|
+
per connected component.
|
|
7
|
+
|
|
8
|
+
Both algorithms here are greedy, and both are correct because of the *cut
|
|
9
|
+
property*. Split the nodes into any two groups. The lightest edge crossing
|
|
10
|
+
between the groups belongs to some MST.
|
|
11
|
+
|
|
12
|
+
* **Kruskal**: sort all edges by weight and add each one unless it would
|
|
13
|
+
close a cycle. Union-find answers "would it close a cycle?" in near-constant
|
|
14
|
+
time. Best for sparse graphs, or when the edges already arrive as a list.
|
|
15
|
+
* **Prim**: grow one tree from a start node, always adding the cheapest edge
|
|
16
|
+
that leaves the tree. It is structured like Dijkstra, but the heap key is
|
|
17
|
+
the edge weight rather than the path length. Best for dense graphs.
|
|
18
|
+
|
|
19
|
+
Uses: network and circuit design at minimum cost, single-linkage clustering
|
|
20
|
+
(build the MST, then delete the k - 1 heaviest edges), and the
|
|
21
|
+
2-approximation for metric TSP.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import heapq
|
|
27
|
+
from collections.abc import Hashable
|
|
28
|
+
from itertools import count
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from .graph import Graph
|
|
32
|
+
from .union_find import DisjointSet
|
|
33
|
+
|
|
34
|
+
__all__ = ["kruskal_mst", "prim_mst", "minimum_spanning_tree"]
|
|
35
|
+
|
|
36
|
+
Edge = tuple[Any, Any, float]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _require_undirected(graph: Any) -> None:
|
|
40
|
+
if getattr(graph, "is_directed", False):
|
|
41
|
+
raise TypeError(
|
|
42
|
+
"minimum spanning trees are defined for undirected graphs; "
|
|
43
|
+
"call graph.to_undirected() first"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def kruskal_mst(graph: Graph[Any]) -> list[Edge]:
|
|
48
|
+
"""Kruskal's algorithm. Returns the MST (or forest) edges as ``(u, v, w)``.
|
|
49
|
+
|
|
50
|
+
Time O(E log E), dominated by the sort. The union-find operations are
|
|
51
|
+
effectively O(1) each.
|
|
52
|
+
|
|
53
|
+
>>> from graphwise import Graph
|
|
54
|
+
>>> g = Graph([(0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4)])
|
|
55
|
+
>>> kruskal_mst(g)
|
|
56
|
+
[(2, 3, 4), (0, 3, 5), (0, 1, 10)]
|
|
57
|
+
|
|
58
|
+
References: Kruskal, J. B. (1956). On the shortest spanning subtree of a
|
|
59
|
+
graph and the traveling salesman problem. *Proc. AMS* 7.
|
|
60
|
+
"""
|
|
61
|
+
_require_undirected(graph)
|
|
62
|
+
ds: DisjointSet[Any] = DisjointSet(graph.nodes())
|
|
63
|
+
tree: list[Edge] = []
|
|
64
|
+
target = len(graph) - 1
|
|
65
|
+
for u, v, w in sorted(graph.edges(), key=lambda e: e[2]):
|
|
66
|
+
if ds.union(u, v): # False means u and v are already connected: a cycle
|
|
67
|
+
tree.append((u, v, w))
|
|
68
|
+
if len(tree) == target:
|
|
69
|
+
break
|
|
70
|
+
return tree
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def prim_mst(graph: Graph[Any], start: Hashable | None = None) -> list[Edge]:
|
|
74
|
+
"""Prim's algorithm. Returns the MST (or forest) edges as ``(u, v, w)``.
|
|
75
|
+
|
|
76
|
+
Growth begins at ``start`` (default: the first node). When that component
|
|
77
|
+
is finished, Prim's restarts from the next unvisited node, so a
|
|
78
|
+
disconnected graph still gets a full spanning forest.
|
|
79
|
+
|
|
80
|
+
Time O(E log V) with a binary heap.
|
|
81
|
+
|
|
82
|
+
>>> from graphwise import Graph
|
|
83
|
+
>>> g = Graph([(0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4)])
|
|
84
|
+
>>> sum(w for _, _, w in prim_mst(g, start=0))
|
|
85
|
+
19
|
|
86
|
+
|
|
87
|
+
References: Prim, R. C. (1957). Shortest connection networks and some
|
|
88
|
+
generalizations. *Bell System Technical Journal* 36(6). (Also Jarník, 1930.)
|
|
89
|
+
"""
|
|
90
|
+
_require_undirected(graph)
|
|
91
|
+
adj = graph._adj
|
|
92
|
+
if start is not None:
|
|
93
|
+
graph._check_node(start)
|
|
94
|
+
roots = ([start] if start is not None else []) + list(adj)
|
|
95
|
+
visited: set[Any] = set()
|
|
96
|
+
tree: list[Edge] = []
|
|
97
|
+
tie = count()
|
|
98
|
+
for root in roots:
|
|
99
|
+
if root in visited:
|
|
100
|
+
continue
|
|
101
|
+
visited.add(root)
|
|
102
|
+
heap = [(w, next(tie), root, v) for v, w in adj[root].items()]
|
|
103
|
+
heapq.heapify(heap)
|
|
104
|
+
while heap:
|
|
105
|
+
w, _, u, v = heapq.heappop(heap)
|
|
106
|
+
if v in visited: # both endpoints are already in the tree
|
|
107
|
+
continue
|
|
108
|
+
visited.add(v)
|
|
109
|
+
tree.append((u, v, w))
|
|
110
|
+
for x, wx in adj[v].items():
|
|
111
|
+
if x not in visited:
|
|
112
|
+
heapq.heappush(heap, (wx, next(tie), v, x))
|
|
113
|
+
return tree
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def minimum_spanning_tree(graph: Graph[Any], method: str = "kruskal") -> list[Edge]:
|
|
117
|
+
"""Return MST edges using ``method``, either ``"kruskal"`` or ``"prim"``."""
|
|
118
|
+
if method == "kruskal":
|
|
119
|
+
return kruskal_mst(graph)
|
|
120
|
+
if method == "prim":
|
|
121
|
+
return prim_mst(graph)
|
|
122
|
+
raise ValueError(f"unknown method {method!r}; use 'kruskal' or 'prim'")
|