simple_paths.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. from heapq import heappop, heappush
  2. from itertools import count
  3. import networkx as nx
  4. from networkx.algorithms.shortest_paths.weighted import _weight_function
  5. from networkx.utils import not_implemented_for, pairwise
  6. __all__ = [
  7. "all_simple_paths",
  8. "is_simple_path",
  9. "shortest_simple_paths",
  10. "all_simple_edge_paths",
  11. ]
  12. @nx._dispatch
  13. def is_simple_path(G, nodes):
  14. """Returns True if and only if `nodes` form a simple path in `G`.
  15. A *simple path* in a graph is a nonempty sequence of nodes in which
  16. no node appears more than once in the sequence, and each adjacent
  17. pair of nodes in the sequence is adjacent in the graph.
  18. Parameters
  19. ----------
  20. G : graph
  21. A NetworkX graph.
  22. nodes : list
  23. A list of one or more nodes in the graph `G`.
  24. Returns
  25. -------
  26. bool
  27. Whether the given list of nodes represents a simple path in `G`.
  28. Notes
  29. -----
  30. An empty list of nodes is not a path but a list of one node is a
  31. path. Here's an explanation why.
  32. This function operates on *node paths*. One could also consider
  33. *edge paths*. There is a bijection between node paths and edge
  34. paths.
  35. The *length of a path* is the number of edges in the path, so a list
  36. of nodes of length *n* corresponds to a path of length *n* - 1.
  37. Thus the smallest edge path would be a list of zero edges, the empty
  38. path. This corresponds to a list of one node.
  39. To convert between a node path and an edge path, you can use code
  40. like the following::
  41. >>> from networkx.utils import pairwise
  42. >>> nodes = [0, 1, 2, 3]
  43. >>> edges = list(pairwise(nodes))
  44. >>> edges
  45. [(0, 1), (1, 2), (2, 3)]
  46. >>> nodes = [edges[0][0]] + [v for u, v in edges]
  47. >>> nodes
  48. [0, 1, 2, 3]
  49. Examples
  50. --------
  51. >>> G = nx.cycle_graph(4)
  52. >>> nx.is_simple_path(G, [2, 3, 0])
  53. True
  54. >>> nx.is_simple_path(G, [0, 2])
  55. False
  56. """
  57. # The empty list is not a valid path. Could also return
  58. # NetworkXPointlessConcept here.
  59. if len(nodes) == 0:
  60. return False
  61. # If the list is a single node, just check that the node is actually
  62. # in the graph.
  63. if len(nodes) == 1:
  64. return nodes[0] in G
  65. # check that all nodes in the list are in the graph, if at least one
  66. # is not in the graph, then this is not a simple path
  67. if not all(n in G for n in nodes):
  68. return False
  69. # If the list contains repeated nodes, then it's not a simple path
  70. if len(set(nodes)) != len(nodes):
  71. return False
  72. # Test that each adjacent pair of nodes is adjacent.
  73. return all(v in G[u] for u, v in pairwise(nodes))
  74. def all_simple_paths(G, source, target, cutoff=None):
  75. """Generate all simple paths in the graph G from source to target.
  76. A simple path is a path with no repeated nodes.
  77. Parameters
  78. ----------
  79. G : NetworkX graph
  80. source : node
  81. Starting node for path
  82. target : nodes
  83. Single node or iterable of nodes at which to end path
  84. cutoff : integer, optional
  85. Depth to stop the search. Only paths of length <= cutoff are returned.
  86. Returns
  87. -------
  88. path_generator: generator
  89. A generator that produces lists of simple paths. If there are no paths
  90. between the source and target within the given cutoff the generator
  91. produces no output. If it is possible to traverse the same sequence of
  92. nodes in multiple ways, namely through parallel edges, then it will be
  93. returned multiple times (once for each viable edge combination).
  94. Examples
  95. --------
  96. This iterator generates lists of nodes::
  97. >>> G = nx.complete_graph(4)
  98. >>> for path in nx.all_simple_paths(G, source=0, target=3):
  99. ... print(path)
  100. ...
  101. [0, 1, 2, 3]
  102. [0, 1, 3]
  103. [0, 2, 1, 3]
  104. [0, 2, 3]
  105. [0, 3]
  106. You can generate only those paths that are shorter than a certain
  107. length by using the `cutoff` keyword argument::
  108. >>> paths = nx.all_simple_paths(G, source=0, target=3, cutoff=2)
  109. >>> print(list(paths))
  110. [[0, 1, 3], [0, 2, 3], [0, 3]]
  111. To get each path as the corresponding list of edges, you can use the
  112. :func:`networkx.utils.pairwise` helper function::
  113. >>> paths = nx.all_simple_paths(G, source=0, target=3)
  114. >>> for path in map(nx.utils.pairwise, paths):
  115. ... print(list(path))
  116. [(0, 1), (1, 2), (2, 3)]
  117. [(0, 1), (1, 3)]
  118. [(0, 2), (2, 1), (1, 3)]
  119. [(0, 2), (2, 3)]
  120. [(0, 3)]
  121. Pass an iterable of nodes as target to generate all paths ending in any of several nodes::
  122. >>> G = nx.complete_graph(4)
  123. >>> for path in nx.all_simple_paths(G, source=0, target=[3, 2]):
  124. ... print(path)
  125. ...
  126. [0, 1, 2]
  127. [0, 1, 2, 3]
  128. [0, 1, 3]
  129. [0, 1, 3, 2]
  130. [0, 2]
  131. [0, 2, 1, 3]
  132. [0, 2, 3]
  133. [0, 3]
  134. [0, 3, 1, 2]
  135. [0, 3, 2]
  136. Iterate over each path from the root nodes to the leaf nodes in a
  137. directed acyclic graph using a functional programming approach::
  138. >>> from itertools import chain
  139. >>> from itertools import product
  140. >>> from itertools import starmap
  141. >>> from functools import partial
  142. >>>
  143. >>> chaini = chain.from_iterable
  144. >>>
  145. >>> G = nx.DiGraph([(0, 1), (1, 2), (0, 3), (3, 2)])
  146. >>> roots = (v for v, d in G.in_degree() if d == 0)
  147. >>> leaves = (v for v, d in G.out_degree() if d == 0)
  148. >>> all_paths = partial(nx.all_simple_paths, G)
  149. >>> list(chaini(starmap(all_paths, product(roots, leaves))))
  150. [[0, 1, 2], [0, 3, 2]]
  151. The same list computed using an iterative approach::
  152. >>> G = nx.DiGraph([(0, 1), (1, 2), (0, 3), (3, 2)])
  153. >>> roots = (v for v, d in G.in_degree() if d == 0)
  154. >>> leaves = (v for v, d in G.out_degree() if d == 0)
  155. >>> all_paths = []
  156. >>> for root in roots:
  157. ... for leaf in leaves:
  158. ... paths = nx.all_simple_paths(G, root, leaf)
  159. ... all_paths.extend(paths)
  160. >>> all_paths
  161. [[0, 1, 2], [0, 3, 2]]
  162. Iterate over each path from the root nodes to the leaf nodes in a
  163. directed acyclic graph passing all leaves together to avoid unnecessary
  164. compute::
  165. >>> G = nx.DiGraph([(0, 1), (2, 1), (1, 3), (1, 4)])
  166. >>> roots = (v for v, d in G.in_degree() if d == 0)
  167. >>> leaves = [v for v, d in G.out_degree() if d == 0]
  168. >>> all_paths = []
  169. >>> for root in roots:
  170. ... paths = nx.all_simple_paths(G, root, leaves)
  171. ... all_paths.extend(paths)
  172. >>> all_paths
  173. [[0, 1, 3], [0, 1, 4], [2, 1, 3], [2, 1, 4]]
  174. If parallel edges offer multiple ways to traverse a given sequence of
  175. nodes, this sequence of nodes will be returned multiple times:
  176. >>> G = nx.MultiDiGraph([(0, 1), (0, 1), (1, 2)])
  177. >>> list(nx.all_simple_paths(G, 0, 2))
  178. [[0, 1, 2], [0, 1, 2]]
  179. Notes
  180. -----
  181. This algorithm uses a modified depth-first search to generate the
  182. paths [1]_. A single path can be found in $O(V+E)$ time but the
  183. number of simple paths in a graph can be very large, e.g. $O(n!)$ in
  184. the complete graph of order $n$.
  185. This function does not check that a path exists between `source` and
  186. `target`. For large graphs, this may result in very long runtimes.
  187. Consider using `has_path` to check that a path exists between `source` and
  188. `target` before calling this function on large graphs.
  189. References
  190. ----------
  191. .. [1] R. Sedgewick, "Algorithms in C, Part 5: Graph Algorithms",
  192. Addison Wesley Professional, 3rd ed., 2001.
  193. See Also
  194. --------
  195. all_shortest_paths, shortest_path, has_path
  196. """
  197. if source not in G:
  198. raise nx.NodeNotFound(f"source node {source} not in graph")
  199. if target in G:
  200. targets = {target}
  201. else:
  202. try:
  203. targets = set(target)
  204. except TypeError as err:
  205. raise nx.NodeNotFound(f"target node {target} not in graph") from err
  206. if source in targets:
  207. return _empty_generator()
  208. if cutoff is None:
  209. cutoff = len(G) - 1
  210. if cutoff < 1:
  211. return _empty_generator()
  212. if G.is_multigraph():
  213. return _all_simple_paths_multigraph(G, source, targets, cutoff)
  214. else:
  215. return _all_simple_paths_graph(G, source, targets, cutoff)
  216. def _empty_generator():
  217. yield from ()
  218. def _all_simple_paths_graph(G, source, targets, cutoff):
  219. visited = {source: True}
  220. stack = [iter(G[source])]
  221. while stack:
  222. children = stack[-1]
  223. child = next(children, None)
  224. if child is None:
  225. stack.pop()
  226. visited.popitem()
  227. elif len(visited) < cutoff:
  228. if child in visited:
  229. continue
  230. if child in targets:
  231. yield list(visited) + [child]
  232. visited[child] = True
  233. if targets - set(visited.keys()): # expand stack until find all targets
  234. stack.append(iter(G[child]))
  235. else:
  236. visited.popitem() # maybe other ways to child
  237. else: # len(visited) == cutoff:
  238. for target in (targets & (set(children) | {child})) - set(visited.keys()):
  239. yield list(visited) + [target]
  240. stack.pop()
  241. visited.popitem()
  242. def _all_simple_paths_multigraph(G, source, targets, cutoff):
  243. visited = {source: True}
  244. stack = [(v for u, v in G.edges(source))]
  245. while stack:
  246. children = stack[-1]
  247. child = next(children, None)
  248. if child is None:
  249. stack.pop()
  250. visited.popitem()
  251. elif len(visited) < cutoff:
  252. if child in visited:
  253. continue
  254. if child in targets:
  255. yield list(visited) + [child]
  256. visited[child] = True
  257. if targets - set(visited.keys()):
  258. stack.append((v for u, v in G.edges(child)))
  259. else:
  260. visited.popitem()
  261. else: # len(visited) == cutoff:
  262. for target in targets - set(visited.keys()):
  263. count = ([child] + list(children)).count(target)
  264. for i in range(count):
  265. yield list(visited) + [target]
  266. stack.pop()
  267. visited.popitem()
  268. def all_simple_edge_paths(G, source, target, cutoff=None):
  269. """Generate lists of edges for all simple paths in G from source to target.
  270. A simple path is a path with no repeated nodes.
  271. Parameters
  272. ----------
  273. G : NetworkX graph
  274. source : node
  275. Starting node for path
  276. target : nodes
  277. Single node or iterable of nodes at which to end path
  278. cutoff : integer, optional
  279. Depth to stop the search. Only paths of length <= cutoff are returned.
  280. Returns
  281. -------
  282. path_generator: generator
  283. A generator that produces lists of simple paths. If there are no paths
  284. between the source and target within the given cutoff the generator
  285. produces no output.
  286. For multigraphs, the list of edges have elements of the form `(u,v,k)`.
  287. Where `k` corresponds to the edge key.
  288. Examples
  289. --------
  290. Print the simple path edges of a Graph::
  291. >>> g = nx.Graph([(1, 2), (2, 4), (1, 3), (3, 4)])
  292. >>> for path in sorted(nx.all_simple_edge_paths(g, 1, 4)):
  293. ... print(path)
  294. [(1, 2), (2, 4)]
  295. [(1, 3), (3, 4)]
  296. Print the simple path edges of a MultiGraph. Returned edges come with
  297. their associated keys::
  298. >>> mg = nx.MultiGraph()
  299. >>> mg.add_edge(1, 2, key="k0")
  300. 'k0'
  301. >>> mg.add_edge(1, 2, key="k1")
  302. 'k1'
  303. >>> mg.add_edge(2, 3, key="k0")
  304. 'k0'
  305. >>> for path in sorted(nx.all_simple_edge_paths(mg, 1, 3)):
  306. ... print(path)
  307. [(1, 2, 'k0'), (2, 3, 'k0')]
  308. [(1, 2, 'k1'), (2, 3, 'k0')]
  309. Notes
  310. -----
  311. This algorithm uses a modified depth-first search to generate the
  312. paths [1]_. A single path can be found in $O(V+E)$ time but the
  313. number of simple paths in a graph can be very large, e.g. $O(n!)$ in
  314. the complete graph of order $n$.
  315. References
  316. ----------
  317. .. [1] R. Sedgewick, "Algorithms in C, Part 5: Graph Algorithms",
  318. Addison Wesley Professional, 3rd ed., 2001.
  319. See Also
  320. --------
  321. all_shortest_paths, shortest_path, all_simple_paths
  322. """
  323. if source not in G:
  324. raise nx.NodeNotFound("source node %s not in graph" % source)
  325. if target in G:
  326. targets = {target}
  327. else:
  328. try:
  329. targets = set(target)
  330. except TypeError:
  331. raise nx.NodeNotFound("target node %s not in graph" % target)
  332. if source in targets:
  333. return []
  334. if cutoff is None:
  335. cutoff = len(G) - 1
  336. if cutoff < 1:
  337. return []
  338. if G.is_multigraph():
  339. for simp_path in _all_simple_edge_paths_multigraph(G, source, targets, cutoff):
  340. yield simp_path
  341. else:
  342. for simp_path in _all_simple_paths_graph(G, source, targets, cutoff):
  343. yield list(zip(simp_path[:-1], simp_path[1:]))
  344. def _all_simple_edge_paths_multigraph(G, source, targets, cutoff):
  345. if not cutoff or cutoff < 1:
  346. return []
  347. visited = [source]
  348. stack = [iter(G.edges(source, keys=True))]
  349. while stack:
  350. children = stack[-1]
  351. child = next(children, None)
  352. if child is None:
  353. stack.pop()
  354. visited.pop()
  355. elif len(visited) < cutoff:
  356. if child[1] in targets:
  357. yield visited[1:] + [child]
  358. elif child[1] not in [v[0] for v in visited[1:]]:
  359. visited.append(child)
  360. stack.append(iter(G.edges(child[1], keys=True)))
  361. else: # len(visited) == cutoff:
  362. for u, v, k in [child] + list(children):
  363. if v in targets:
  364. yield visited[1:] + [(u, v, k)]
  365. stack.pop()
  366. visited.pop()
  367. @not_implemented_for("multigraph")
  368. def shortest_simple_paths(G, source, target, weight=None):
  369. """Generate all simple paths in the graph G from source to target,
  370. starting from shortest ones.
  371. A simple path is a path with no repeated nodes.
  372. If a weighted shortest path search is to be used, no negative weights
  373. are allowed.
  374. Parameters
  375. ----------
  376. G : NetworkX graph
  377. source : node
  378. Starting node for path
  379. target : node
  380. Ending node for path
  381. weight : string or function
  382. If it is a string, it is the name of the edge attribute to be
  383. used as a weight.
  384. If it is a function, the weight of an edge is the value returned
  385. by the function. The function must accept exactly three positional
  386. arguments: the two endpoints of an edge and the dictionary of edge
  387. attributes for that edge. The function must return a number.
  388. If None all edges are considered to have unit weight. Default
  389. value None.
  390. Returns
  391. -------
  392. path_generator: generator
  393. A generator that produces lists of simple paths, in order from
  394. shortest to longest.
  395. Raises
  396. ------
  397. NetworkXNoPath
  398. If no path exists between source and target.
  399. NetworkXError
  400. If source or target nodes are not in the input graph.
  401. NetworkXNotImplemented
  402. If the input graph is a Multi[Di]Graph.
  403. Examples
  404. --------
  405. >>> G = nx.cycle_graph(7)
  406. >>> paths = list(nx.shortest_simple_paths(G, 0, 3))
  407. >>> print(paths)
  408. [[0, 1, 2, 3], [0, 6, 5, 4, 3]]
  409. You can use this function to efficiently compute the k shortest/best
  410. paths between two nodes.
  411. >>> from itertools import islice
  412. >>> def k_shortest_paths(G, source, target, k, weight=None):
  413. ... return list(
  414. ... islice(nx.shortest_simple_paths(G, source, target, weight=weight), k)
  415. ... )
  416. >>> for path in k_shortest_paths(G, 0, 3, 2):
  417. ... print(path)
  418. [0, 1, 2, 3]
  419. [0, 6, 5, 4, 3]
  420. Notes
  421. -----
  422. This procedure is based on algorithm by Jin Y. Yen [1]_. Finding
  423. the first $K$ paths requires $O(KN^3)$ operations.
  424. See Also
  425. --------
  426. all_shortest_paths
  427. shortest_path
  428. all_simple_paths
  429. References
  430. ----------
  431. .. [1] Jin Y. Yen, "Finding the K Shortest Loopless Paths in a
  432. Network", Management Science, Vol. 17, No. 11, Theory Series
  433. (Jul., 1971), pp. 712-716.
  434. """
  435. if source not in G:
  436. raise nx.NodeNotFound(f"source node {source} not in graph")
  437. if target not in G:
  438. raise nx.NodeNotFound(f"target node {target} not in graph")
  439. if weight is None:
  440. length_func = len
  441. shortest_path_func = _bidirectional_shortest_path
  442. else:
  443. wt = _weight_function(G, weight)
  444. def length_func(path):
  445. return sum(
  446. wt(u, v, G.get_edge_data(u, v)) for (u, v) in zip(path, path[1:])
  447. )
  448. shortest_path_func = _bidirectional_dijkstra
  449. listA = []
  450. listB = PathBuffer()
  451. prev_path = None
  452. while True:
  453. if not prev_path:
  454. length, path = shortest_path_func(G, source, target, weight=weight)
  455. listB.push(length, path)
  456. else:
  457. ignore_nodes = set()
  458. ignore_edges = set()
  459. for i in range(1, len(prev_path)):
  460. root = prev_path[:i]
  461. root_length = length_func(root)
  462. for path in listA:
  463. if path[:i] == root:
  464. ignore_edges.add((path[i - 1], path[i]))
  465. try:
  466. length, spur = shortest_path_func(
  467. G,
  468. root[-1],
  469. target,
  470. ignore_nodes=ignore_nodes,
  471. ignore_edges=ignore_edges,
  472. weight=weight,
  473. )
  474. path = root[:-1] + spur
  475. listB.push(root_length + length, path)
  476. except nx.NetworkXNoPath:
  477. pass
  478. ignore_nodes.add(root[-1])
  479. if listB:
  480. path = listB.pop()
  481. yield path
  482. listA.append(path)
  483. prev_path = path
  484. else:
  485. break
  486. class PathBuffer:
  487. def __init__(self):
  488. self.paths = set()
  489. self.sortedpaths = []
  490. self.counter = count()
  491. def __len__(self):
  492. return len(self.sortedpaths)
  493. def push(self, cost, path):
  494. hashable_path = tuple(path)
  495. if hashable_path not in self.paths:
  496. heappush(self.sortedpaths, (cost, next(self.counter), path))
  497. self.paths.add(hashable_path)
  498. def pop(self):
  499. (cost, num, path) = heappop(self.sortedpaths)
  500. hashable_path = tuple(path)
  501. self.paths.remove(hashable_path)
  502. return path
  503. def _bidirectional_shortest_path(
  504. G, source, target, ignore_nodes=None, ignore_edges=None, weight=None
  505. ):
  506. """Returns the shortest path between source and target ignoring
  507. nodes and edges in the containers ignore_nodes and ignore_edges.
  508. This is a custom modification of the standard bidirectional shortest
  509. path implementation at networkx.algorithms.unweighted
  510. Parameters
  511. ----------
  512. G : NetworkX graph
  513. source : node
  514. starting node for path
  515. target : node
  516. ending node for path
  517. ignore_nodes : container of nodes
  518. nodes to ignore, optional
  519. ignore_edges : container of edges
  520. edges to ignore, optional
  521. weight : None
  522. This function accepts a weight argument for convenience of
  523. shortest_simple_paths function. It will be ignored.
  524. Returns
  525. -------
  526. path: list
  527. List of nodes in a path from source to target.
  528. Raises
  529. ------
  530. NetworkXNoPath
  531. If no path exists between source and target.
  532. See Also
  533. --------
  534. shortest_path
  535. """
  536. # call helper to do the real work
  537. results = _bidirectional_pred_succ(G, source, target, ignore_nodes, ignore_edges)
  538. pred, succ, w = results
  539. # build path from pred+w+succ
  540. path = []
  541. # from w to target
  542. while w is not None:
  543. path.append(w)
  544. w = succ[w]
  545. # from source to w
  546. w = pred[path[0]]
  547. while w is not None:
  548. path.insert(0, w)
  549. w = pred[w]
  550. return len(path), path
  551. def _bidirectional_pred_succ(G, source, target, ignore_nodes=None, ignore_edges=None):
  552. """Bidirectional shortest path helper.
  553. Returns (pred,succ,w) where
  554. pred is a dictionary of predecessors from w to the source, and
  555. succ is a dictionary of successors from w to the target.
  556. """
  557. # does BFS from both source and target and meets in the middle
  558. if ignore_nodes and (source in ignore_nodes or target in ignore_nodes):
  559. raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
  560. if target == source:
  561. return ({target: None}, {source: None}, source)
  562. # handle either directed or undirected
  563. if G.is_directed():
  564. Gpred = G.predecessors
  565. Gsucc = G.successors
  566. else:
  567. Gpred = G.neighbors
  568. Gsucc = G.neighbors
  569. # support optional nodes filter
  570. if ignore_nodes:
  571. def filter_iter(nodes):
  572. def iterate(v):
  573. for w in nodes(v):
  574. if w not in ignore_nodes:
  575. yield w
  576. return iterate
  577. Gpred = filter_iter(Gpred)
  578. Gsucc = filter_iter(Gsucc)
  579. # support optional edges filter
  580. if ignore_edges:
  581. if G.is_directed():
  582. def filter_pred_iter(pred_iter):
  583. def iterate(v):
  584. for w in pred_iter(v):
  585. if (w, v) not in ignore_edges:
  586. yield w
  587. return iterate
  588. def filter_succ_iter(succ_iter):
  589. def iterate(v):
  590. for w in succ_iter(v):
  591. if (v, w) not in ignore_edges:
  592. yield w
  593. return iterate
  594. Gpred = filter_pred_iter(Gpred)
  595. Gsucc = filter_succ_iter(Gsucc)
  596. else:
  597. def filter_iter(nodes):
  598. def iterate(v):
  599. for w in nodes(v):
  600. if (v, w) not in ignore_edges and (w, v) not in ignore_edges:
  601. yield w
  602. return iterate
  603. Gpred = filter_iter(Gpred)
  604. Gsucc = filter_iter(Gsucc)
  605. # predecesssor and successors in search
  606. pred = {source: None}
  607. succ = {target: None}
  608. # initialize fringes, start with forward
  609. forward_fringe = [source]
  610. reverse_fringe = [target]
  611. while forward_fringe and reverse_fringe:
  612. if len(forward_fringe) <= len(reverse_fringe):
  613. this_level = forward_fringe
  614. forward_fringe = []
  615. for v in this_level:
  616. for w in Gsucc(v):
  617. if w not in pred:
  618. forward_fringe.append(w)
  619. pred[w] = v
  620. if w in succ:
  621. # found path
  622. return pred, succ, w
  623. else:
  624. this_level = reverse_fringe
  625. reverse_fringe = []
  626. for v in this_level:
  627. for w in Gpred(v):
  628. if w not in succ:
  629. succ[w] = v
  630. reverse_fringe.append(w)
  631. if w in pred:
  632. # found path
  633. return pred, succ, w
  634. raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
  635. def _bidirectional_dijkstra(
  636. G, source, target, weight="weight", ignore_nodes=None, ignore_edges=None
  637. ):
  638. """Dijkstra's algorithm for shortest paths using bidirectional search.
  639. This function returns the shortest path between source and target
  640. ignoring nodes and edges in the containers ignore_nodes and
  641. ignore_edges.
  642. This is a custom modification of the standard Dijkstra bidirectional
  643. shortest path implementation at networkx.algorithms.weighted
  644. Parameters
  645. ----------
  646. G : NetworkX graph
  647. source : node
  648. Starting node.
  649. target : node
  650. Ending node.
  651. weight: string, function, optional (default='weight')
  652. Edge data key or weight function corresponding to the edge weight
  653. ignore_nodes : container of nodes
  654. nodes to ignore, optional
  655. ignore_edges : container of edges
  656. edges to ignore, optional
  657. Returns
  658. -------
  659. length : number
  660. Shortest path length.
  661. Returns a tuple of two dictionaries keyed by node.
  662. The first dictionary stores distance from the source.
  663. The second stores the path from the source to that node.
  664. Raises
  665. ------
  666. NetworkXNoPath
  667. If no path exists between source and target.
  668. Notes
  669. -----
  670. Edge weight attributes must be numerical.
  671. Distances are calculated as sums of weighted edges traversed.
  672. In practice bidirectional Dijkstra is much more than twice as fast as
  673. ordinary Dijkstra.
  674. Ordinary Dijkstra expands nodes in a sphere-like manner from the
  675. source. The radius of this sphere will eventually be the length
  676. of the shortest path. Bidirectional Dijkstra will expand nodes
  677. from both the source and the target, making two spheres of half
  678. this radius. Volume of the first sphere is pi*r*r while the
  679. others are 2*pi*r/2*r/2, making up half the volume.
  680. This algorithm is not guaranteed to work if edge weights
  681. are negative or are floating point numbers
  682. (overflows and roundoff errors can cause problems).
  683. See Also
  684. --------
  685. shortest_path
  686. shortest_path_length
  687. """
  688. if ignore_nodes and (source in ignore_nodes or target in ignore_nodes):
  689. raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
  690. if source == target:
  691. if source not in G:
  692. raise nx.NodeNotFound(f"Node {source} not in graph")
  693. return (0, [source])
  694. # handle either directed or undirected
  695. if G.is_directed():
  696. Gpred = G.predecessors
  697. Gsucc = G.successors
  698. else:
  699. Gpred = G.neighbors
  700. Gsucc = G.neighbors
  701. # support optional nodes filter
  702. if ignore_nodes:
  703. def filter_iter(nodes):
  704. def iterate(v):
  705. for w in nodes(v):
  706. if w not in ignore_nodes:
  707. yield w
  708. return iterate
  709. Gpred = filter_iter(Gpred)
  710. Gsucc = filter_iter(Gsucc)
  711. # support optional edges filter
  712. if ignore_edges:
  713. if G.is_directed():
  714. def filter_pred_iter(pred_iter):
  715. def iterate(v):
  716. for w in pred_iter(v):
  717. if (w, v) not in ignore_edges:
  718. yield w
  719. return iterate
  720. def filter_succ_iter(succ_iter):
  721. def iterate(v):
  722. for w in succ_iter(v):
  723. if (v, w) not in ignore_edges:
  724. yield w
  725. return iterate
  726. Gpred = filter_pred_iter(Gpred)
  727. Gsucc = filter_succ_iter(Gsucc)
  728. else:
  729. def filter_iter(nodes):
  730. def iterate(v):
  731. for w in nodes(v):
  732. if (v, w) not in ignore_edges and (w, v) not in ignore_edges:
  733. yield w
  734. return iterate
  735. Gpred = filter_iter(Gpred)
  736. Gsucc = filter_iter(Gsucc)
  737. push = heappush
  738. pop = heappop
  739. # Init: Forward Backward
  740. dists = [{}, {}] # dictionary of final distances
  741. paths = [{source: [source]}, {target: [target]}] # dictionary of paths
  742. fringe = [[], []] # heap of (distance, node) tuples for
  743. # extracting next node to expand
  744. seen = [{source: 0}, {target: 0}] # dictionary of distances to
  745. # nodes seen
  746. c = count()
  747. # initialize fringe heap
  748. push(fringe[0], (0, next(c), source))
  749. push(fringe[1], (0, next(c), target))
  750. # neighs for extracting correct neighbor information
  751. neighs = [Gsucc, Gpred]
  752. # variables to hold shortest discovered path
  753. # finaldist = 1e30000
  754. finalpath = []
  755. dir = 1
  756. while fringe[0] and fringe[1]:
  757. # choose direction
  758. # dir == 0 is forward direction and dir == 1 is back
  759. dir = 1 - dir
  760. # extract closest to expand
  761. (dist, _, v) = pop(fringe[dir])
  762. if v in dists[dir]:
  763. # Shortest path to v has already been found
  764. continue
  765. # update distance
  766. dists[dir][v] = dist # equal to seen[dir][v]
  767. if v in dists[1 - dir]:
  768. # if we have scanned v in both directions we are done
  769. # we have now discovered the shortest path
  770. return (finaldist, finalpath)
  771. wt = _weight_function(G, weight)
  772. for w in neighs[dir](v):
  773. if dir == 0: # forward
  774. minweight = wt(v, w, G.get_edge_data(v, w))
  775. vwLength = dists[dir][v] + minweight
  776. else: # back, must remember to change v,w->w,v
  777. minweight = wt(w, v, G.get_edge_data(w, v))
  778. vwLength = dists[dir][v] + minweight
  779. if w in dists[dir]:
  780. if vwLength < dists[dir][w]:
  781. raise ValueError("Contradictory paths found: negative weights?")
  782. elif w not in seen[dir] or vwLength < seen[dir][w]:
  783. # relaxing
  784. seen[dir][w] = vwLength
  785. push(fringe[dir], (vwLength, next(c), w))
  786. paths[dir][w] = paths[dir][v] + [w]
  787. if w in seen[0] and w in seen[1]:
  788. # see if this path is better than the already
  789. # discovered shortest path
  790. totaldist = seen[0][w] + seen[1][w]
  791. if finalpath == [] or finaldist > totaldist:
  792. finaldist = totaldist
  793. revpath = paths[1][w][:]
  794. revpath.reverse()
  795. finalpath = paths[0][w] + revpath[1:]
  796. raise nx.NetworkXNoPath(f"No path between {source} and {target}.")