-
Notifications
You must be signed in to change notification settings - Fork 1
/
shortest_paths.py
354 lines (289 loc) · 9.41 KB
/
shortest_paths.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# -*- coding: utf-8 -*-
"""
Shortest path algorithms for unweighted graphs.
"""
__author__ = """Aric Hagberg ([email protected])"""
# Copyright (C) 2004-2015 by
# Aric Hagberg <[email protected]>
# Dan Schult <[email protected]>
# Pieter Swart <[email protected]>
# All rights reserved.
# BSD license.
__all__ = ['bidirectional_shortest_path',
'single_source_shortest_path',
'single_source_shortest_path_length',
'all_pairs_shortest_path',
'all_pairs_shortest_path_length',
'predecessor']
import networkx as nx
def single_source_shortest_path_length(G,source,cutoff=None):
"""Compute the shortest path lengths from source to all reachable nodes.
Parameters
----------
G : NetworkX graph
source : node
Starting node for path
cutoff : integer, optional
Depth to stop the search. Only paths of length <= cutoff are returned.
Returns
-------
lengths : dictionary
Dictionary of shortest path lengths keyed by target.
Examples
--------
>>> G=nx.path_graph(5)
>>> length=nx.single_source_shortest_path_length(G,0)
>>> length[4]
4
>>> print(length)
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
See Also
--------
shortest_path_length
"""
seen={} # level (number of hops) when seen in BFS
level=0 # the current level
nextlevel={source:1} # dict of nodes to check at next level
while nextlevel:
thislevel=nextlevel # advance to next level
nextlevel={} # and start a new list (fringe)
for v in thislevel:
if v not in seen:
seen[v]=level # set the level of vertex v
nextlevel.update(G[v]) # add neighbors of v
if (cutoff is not None and cutoff <= level): break
level=level+1
return seen # return all path lengths as dictionary
def all_pairs_shortest_path_length(G, cutoff=None):
"""Computes the shortest path lengths between all nodes in ``G``.
Parameters
----------
G : NetworkX graph
cutoff : integer, optional
Depth at which to stop the search. Only paths of length at most
``cutoff`` are returned.
Returns
-------
lengths : dictionary
Dictionary of shortest path lengths keyed by source and target.
Notes
-----
The dictionary returned only has keys for reachable node pairs.
Examples
--------
>>> G = nx.path_graph(5)
>>> length = nx.all_pairs_shortest_path_length(G)
>>> print(length[1][4])
3
>>> length[1]
{0: 1, 1: 0, 2: 1, 3: 2, 4: 3}
"""
length = single_source_shortest_path_length
# TODO This can be trivially parallelized.
return {n: length(G, n, cutoff=cutoff) for n in G}
def bidirectional_shortest_path(G,source,target):
"""Return a list of nodes in a shortest path between source and target.
Parameters
----------
G : NetworkX graph
source : node label
starting node for path
target : node label
ending node for path
Returns
-------
path: list
List of nodes in a path from source to target.
Raises
------
NetworkXNoPath
If no path exists between source and target.
See Also
--------
shortest_path
Notes
-----
This algorithm is used by shortest_path(G,source,target).
"""
# call helper to do the real work
results=_bidirectional_pred_succ(G,source,target)
pred,succ,w=results
# build path from pred+w+succ
path=[]
# from source to w
while w is not None:
path.append(w)
w=pred[w]
path.reverse()
# from w to target
w=succ[path[-1]]
while w is not None:
path.append(w)
w=succ[w]
return path
def _bidirectional_pred_succ(G, source, target):
"""Bidirectional shortest path helper.
Returns (pred,succ,w) where
pred is a dictionary of predecessors from w to the source, and
succ is a dictionary of successors from w to the target.
"""
# does BFS from both source and target and meets in the middle
if target == source:
return ({target:None},{source:None},source)
# handle either directed or undirected
if G.is_directed():
Gpred=G.predecessors_iter
Gsucc=G.successors_iter
else:
Gpred=G.neighbors_iter
Gsucc=G.neighbors_iter
# predecesssor and successors in search
pred={source:None}
succ={target:None}
# initialize fringes, start with forward
forward_fringe=[source]
reverse_fringe=[target]
while forward_fringe and reverse_fringe:
if len(forward_fringe) <= len(reverse_fringe):
this_level=forward_fringe
forward_fringe=[]
for v in this_level:
for w in Gsucc(v):
if w not in pred:
forward_fringe.append(w)
pred[w]=v
if w in succ: return pred,succ,w # found path
else:
this_level=reverse_fringe
reverse_fringe=[]
for v in this_level:
for w in Gpred(v):
if w not in succ:
succ[w]=v
reverse_fringe.append(w)
if w in pred: return pred,succ,w # found path
raise nx.NetworkXNoPath("No path between %s and %s." % (source, target))
def single_source_shortest_path(G,source,cutoff=None):
"""Compute shortest path between source
and all other nodes reachable from source.
Parameters
----------
G : NetworkX graph
source : node label
Starting node for path
cutoff : integer, optional
Depth to stop the search. Only paths of length <= cutoff are returned.
Returns
-------
lengths : dictionary
Dictionary, keyed by target, of shortest paths.
Examples
--------
>>> G=nx.path_graph(5)
>>> path=nx.single_source_shortest_path(G,0)
>>> path[4]
[0, 1, 2, 3, 4]
Notes
-----
The shortest path is not necessarily unique. So there can be multiple
paths between the source and each target node, all of which have the
same 'shortest' length. For each target node, this function returns
only one of those paths.
See Also
--------
shortest_path
"""
level=0 # the current level
nextlevel={source:1} # list of nodes to check at next level
paths={source:[source]} # paths dictionary (paths to key from source)
if cutoff==0:
return paths
while nextlevel:
thislevel=nextlevel
nextlevel={}
for v in thislevel:
for w in G[v]:
if w not in paths:
paths[w]=paths[v]+[w]
nextlevel[w]=1
level=level+1
if (cutoff is not None and cutoff <= level): break
return paths
def all_pairs_shortest_path(G, cutoff=None):
"""Compute shortest paths between all nodes.
Parameters
----------
G : NetworkX graph
cutoff : integer, optional
Depth at which to stop the search. Only paths of length at most
``cutoff`` are returned.
Returns
-------
lengths : dictionary
Dictionary, keyed by source and target, of shortest paths.
Examples
--------
>>> G = nx.path_graph(5)
>>> path = nx.all_pairs_shortest_path(G)
>>> print(path[0][4])
[0, 1, 2, 3, 4]
See Also
--------
floyd_warshall()
"""
# TODO This can be trivially parallelized.
return {n: single_source_shortest_path(G, n, cutoff=cutoff) for n in G}
def predecessor(G,source,target=None,cutoff=None,return_seen=None):
""" Returns dictionary of predecessors for the path from source to all nodes in G.
Parameters
----------
G : NetworkX graph
source : node label
Starting node for path
target : node label, optional
Ending node for path. If provided only predecessors between
source and target are returned
cutoff : integer, optional
Depth to stop the search. Only paths of length <= cutoff are returned.
Returns
-------
pred : dictionary
Dictionary, keyed by node, of predecessors in the shortest path.
Examples
--------
>>> G=nx.path_graph(4)
>>> print(G.nodes())
[0, 1, 2, 3]
>>> nx.predecessor(G,0)
{0: [], 1: [0], 2: [1], 3: [2]}
"""
level=0 # the current level
nextlevel=[source] # list of nodes to check at next level
seen={source:level} # level (number of hops) when seen in BFS
pred={source:[]} # predecessor dictionary
while nextlevel:
level=level+1
thislevel=nextlevel
nextlevel=[]
for v in thislevel:
for w in G[v]:
if w not in seen:
pred[w]=[v]
seen[w]=level
nextlevel.append(w)
elif (seen[w]==level):# add v to predecessor list if it
pred[w].append(v) # is at the correct level
if (cutoff and cutoff <= level):
break
if target is not None:
if return_seen:
if not target in pred: return ([],-1) # No predecessor
return (pred[target],seen[target])
else:
if not target in pred: return [] # No predecessor
return pred[target]
else:
if return_seen:
return (pred,seen)
else:
return pred