shortestaugmentingpath.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. """
  2. Shortest augmenting path algorithm for maximum flow problems.
  3. """
  4. from collections import deque
  5. import networkx as nx
  6. from .edmondskarp import edmonds_karp_core
  7. from .utils import CurrentEdge, build_residual_network
  8. __all__ = ["shortest_augmenting_path"]
  9. def shortest_augmenting_path_impl(G, s, t, capacity, residual, two_phase, cutoff):
  10. """Implementation of the shortest augmenting path algorithm."""
  11. if s not in G:
  12. raise nx.NetworkXError(f"node {str(s)} not in graph")
  13. if t not in G:
  14. raise nx.NetworkXError(f"node {str(t)} not in graph")
  15. if s == t:
  16. raise nx.NetworkXError("source and sink are the same node")
  17. if residual is None:
  18. R = build_residual_network(G, capacity)
  19. else:
  20. R = residual
  21. R_nodes = R.nodes
  22. R_pred = R.pred
  23. R_succ = R.succ
  24. # Initialize/reset the residual network.
  25. for u in R:
  26. for e in R_succ[u].values():
  27. e["flow"] = 0
  28. # Initialize heights of the nodes.
  29. heights = {t: 0}
  30. q = deque([(t, 0)])
  31. while q:
  32. u, height = q.popleft()
  33. height += 1
  34. for v, attr in R_pred[u].items():
  35. if v not in heights and attr["flow"] < attr["capacity"]:
  36. heights[v] = height
  37. q.append((v, height))
  38. if s not in heights:
  39. # t is not reachable from s in the residual network. The maximum flow
  40. # must be zero.
  41. R.graph["flow_value"] = 0
  42. return R
  43. n = len(G)
  44. m = R.size() / 2
  45. # Initialize heights and 'current edge' data structures of the nodes.
  46. for u in R:
  47. R_nodes[u]["height"] = heights[u] if u in heights else n
  48. R_nodes[u]["curr_edge"] = CurrentEdge(R_succ[u])
  49. # Initialize counts of nodes in each level.
  50. counts = [0] * (2 * n - 1)
  51. for u in R:
  52. counts[R_nodes[u]["height"]] += 1
  53. inf = R.graph["inf"]
  54. def augment(path):
  55. """Augment flow along a path from s to t."""
  56. # Determine the path residual capacity.
  57. flow = inf
  58. it = iter(path)
  59. u = next(it)
  60. for v in it:
  61. attr = R_succ[u][v]
  62. flow = min(flow, attr["capacity"] - attr["flow"])
  63. u = v
  64. if flow * 2 > inf:
  65. raise nx.NetworkXUnbounded("Infinite capacity path, flow unbounded above.")
  66. # Augment flow along the path.
  67. it = iter(path)
  68. u = next(it)
  69. for v in it:
  70. R_succ[u][v]["flow"] += flow
  71. R_succ[v][u]["flow"] -= flow
  72. u = v
  73. return flow
  74. def relabel(u):
  75. """Relabel a node to create an admissible edge."""
  76. height = n - 1
  77. for v, attr in R_succ[u].items():
  78. if attr["flow"] < attr["capacity"]:
  79. height = min(height, R_nodes[v]["height"])
  80. return height + 1
  81. if cutoff is None:
  82. cutoff = float("inf")
  83. # Phase 1: Look for shortest augmenting paths using depth-first search.
  84. flow_value = 0
  85. path = [s]
  86. u = s
  87. d = n if not two_phase else int(min(m**0.5, 2 * n ** (2.0 / 3)))
  88. done = R_nodes[s]["height"] >= d
  89. while not done:
  90. height = R_nodes[u]["height"]
  91. curr_edge = R_nodes[u]["curr_edge"]
  92. # Depth-first search for the next node on the path to t.
  93. while True:
  94. v, attr = curr_edge.get()
  95. if height == R_nodes[v]["height"] + 1 and attr["flow"] < attr["capacity"]:
  96. # Advance to the next node following an admissible edge.
  97. path.append(v)
  98. u = v
  99. break
  100. try:
  101. curr_edge.move_to_next()
  102. except StopIteration:
  103. counts[height] -= 1
  104. if counts[height] == 0:
  105. # Gap heuristic: If relabeling causes a level to become
  106. # empty, a minimum cut has been identified. The algorithm
  107. # can now be terminated.
  108. R.graph["flow_value"] = flow_value
  109. return R
  110. height = relabel(u)
  111. if u == s and height >= d:
  112. if not two_phase:
  113. # t is disconnected from s in the residual network. No
  114. # more augmenting paths exist.
  115. R.graph["flow_value"] = flow_value
  116. return R
  117. else:
  118. # t is at least d steps away from s. End of phase 1.
  119. done = True
  120. break
  121. counts[height] += 1
  122. R_nodes[u]["height"] = height
  123. if u != s:
  124. # After relabeling, the last edge on the path is no longer
  125. # admissible. Retreat one step to look for an alternative.
  126. path.pop()
  127. u = path[-1]
  128. break
  129. if u == t:
  130. # t is reached. Augment flow along the path and reset it for a new
  131. # depth-first search.
  132. flow_value += augment(path)
  133. if flow_value >= cutoff:
  134. R.graph["flow_value"] = flow_value
  135. return R
  136. path = [s]
  137. u = s
  138. # Phase 2: Look for shortest augmenting paths using breadth-first search.
  139. flow_value += edmonds_karp_core(R, s, t, cutoff - flow_value)
  140. R.graph["flow_value"] = flow_value
  141. return R
  142. def shortest_augmenting_path(
  143. G,
  144. s,
  145. t,
  146. capacity="capacity",
  147. residual=None,
  148. value_only=False,
  149. two_phase=False,
  150. cutoff=None,
  151. ):
  152. r"""Find a maximum single-commodity flow using the shortest augmenting path
  153. algorithm.
  154. This function returns the residual network resulting after computing
  155. the maximum flow. See below for details about the conventions
  156. NetworkX uses for defining residual networks.
  157. This algorithm has a running time of $O(n^2 m)$ for $n$ nodes and $m$
  158. edges.
  159. Parameters
  160. ----------
  161. G : NetworkX graph
  162. Edges of the graph are expected to have an attribute called
  163. 'capacity'. If this attribute is not present, the edge is
  164. considered to have infinite capacity.
  165. s : node
  166. Source node for the flow.
  167. t : node
  168. Sink node for the flow.
  169. capacity : string
  170. Edges of the graph G are expected to have an attribute capacity
  171. that indicates how much flow the edge can support. If this
  172. attribute is not present, the edge is considered to have
  173. infinite capacity. Default value: 'capacity'.
  174. residual : NetworkX graph
  175. Residual network on which the algorithm is to be executed. If None, a
  176. new residual network is created. Default value: None.
  177. value_only : bool
  178. If True compute only the value of the maximum flow. This parameter
  179. will be ignored by this algorithm because it is not applicable.
  180. two_phase : bool
  181. If True, a two-phase variant is used. The two-phase variant improves
  182. the running time on unit-capacity networks from $O(nm)$ to
  183. $O(\min(n^{2/3}, m^{1/2}) m)$. Default value: False.
  184. cutoff : integer, float
  185. If specified, the algorithm will terminate when the flow value reaches
  186. or exceeds the cutoff. In this case, it may be unable to immediately
  187. determine a minimum cut. Default value: None.
  188. Returns
  189. -------
  190. R : NetworkX DiGraph
  191. Residual network after computing the maximum flow.
  192. Raises
  193. ------
  194. NetworkXError
  195. The algorithm does not support MultiGraph and MultiDiGraph. If
  196. the input graph is an instance of one of these two classes, a
  197. NetworkXError is raised.
  198. NetworkXUnbounded
  199. If the graph has a path of infinite capacity, the value of a
  200. feasible flow on the graph is unbounded above and the function
  201. raises a NetworkXUnbounded.
  202. See also
  203. --------
  204. :meth:`maximum_flow`
  205. :meth:`minimum_cut`
  206. :meth:`edmonds_karp`
  207. :meth:`preflow_push`
  208. Notes
  209. -----
  210. The residual network :samp:`R` from an input graph :samp:`G` has the
  211. same nodes as :samp:`G`. :samp:`R` is a DiGraph that contains a pair
  212. of edges :samp:`(u, v)` and :samp:`(v, u)` iff :samp:`(u, v)` is not a
  213. self-loop, and at least one of :samp:`(u, v)` and :samp:`(v, u)` exists
  214. in :samp:`G`.
  215. For each edge :samp:`(u, v)` in :samp:`R`, :samp:`R[u][v]['capacity']`
  216. is equal to the capacity of :samp:`(u, v)` in :samp:`G` if it exists
  217. in :samp:`G` or zero otherwise. If the capacity is infinite,
  218. :samp:`R[u][v]['capacity']` will have a high arbitrary finite value
  219. that does not affect the solution of the problem. This value is stored in
  220. :samp:`R.graph['inf']`. For each edge :samp:`(u, v)` in :samp:`R`,
  221. :samp:`R[u][v]['flow']` represents the flow function of :samp:`(u, v)` and
  222. satisfies :samp:`R[u][v]['flow'] == -R[v][u]['flow']`.
  223. The flow value, defined as the total flow into :samp:`t`, the sink, is
  224. stored in :samp:`R.graph['flow_value']`. If :samp:`cutoff` is not
  225. specified, reachability to :samp:`t` using only edges :samp:`(u, v)` such
  226. that :samp:`R[u][v]['flow'] < R[u][v]['capacity']` induces a minimum
  227. :samp:`s`-:samp:`t` cut.
  228. Examples
  229. --------
  230. >>> from networkx.algorithms.flow import shortest_augmenting_path
  231. The functions that implement flow algorithms and output a residual
  232. network, such as this one, are not imported to the base NetworkX
  233. namespace, so you have to explicitly import them from the flow package.
  234. >>> G = nx.DiGraph()
  235. >>> G.add_edge("x", "a", capacity=3.0)
  236. >>> G.add_edge("x", "b", capacity=1.0)
  237. >>> G.add_edge("a", "c", capacity=3.0)
  238. >>> G.add_edge("b", "c", capacity=5.0)
  239. >>> G.add_edge("b", "d", capacity=4.0)
  240. >>> G.add_edge("d", "e", capacity=2.0)
  241. >>> G.add_edge("c", "y", capacity=2.0)
  242. >>> G.add_edge("e", "y", capacity=3.0)
  243. >>> R = shortest_augmenting_path(G, "x", "y")
  244. >>> flow_value = nx.maximum_flow_value(G, "x", "y")
  245. >>> flow_value
  246. 3.0
  247. >>> flow_value == R.graph["flow_value"]
  248. True
  249. """
  250. R = shortest_augmenting_path_impl(G, s, t, capacity, residual, two_phase, cutoff)
  251. R.graph["algorithm"] = "shortest_augmenting_path"
  252. return R