bridges.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. """Bridge-finding algorithms."""
  2. from itertools import chain
  3. import networkx as nx
  4. from networkx.utils import not_implemented_for
  5. __all__ = ["bridges", "has_bridges", "local_bridges"]
  6. @not_implemented_for("directed")
  7. def bridges(G, root=None):
  8. """Generate all bridges in a graph.
  9. A *bridge* in a graph is an edge whose removal causes the number of
  10. connected components of the graph to increase. Equivalently, a bridge is an
  11. edge that does not belong to any cycle. Bridges are also known as cut-edges,
  12. isthmuses, or cut arcs.
  13. Parameters
  14. ----------
  15. G : undirected graph
  16. root : node (optional)
  17. A node in the graph `G`. If specified, only the bridges in the
  18. connected component containing this node will be returned.
  19. Yields
  20. ------
  21. e : edge
  22. An edge in the graph whose removal disconnects the graph (or
  23. causes the number of connected components to increase).
  24. Raises
  25. ------
  26. NodeNotFound
  27. If `root` is not in the graph `G`.
  28. NetworkXNotImplemented
  29. If `G` is a directed graph.
  30. Examples
  31. --------
  32. The barbell graph with parameter zero has a single bridge:
  33. >>> G = nx.barbell_graph(10, 0)
  34. >>> list(nx.bridges(G))
  35. [(9, 10)]
  36. Notes
  37. -----
  38. This is an implementation of the algorithm described in [1]_. An edge is a
  39. bridge if and only if it is not contained in any chain. Chains are found
  40. using the :func:`networkx.chain_decomposition` function.
  41. The algorithm described in [1]_ requires a simple graph. If the provided
  42. graph is a multigraph, we convert it to a simple graph and verify that any
  43. bridges discovered by the chain decomposition algorithm are not multi-edges.
  44. Ignoring polylogarithmic factors, the worst-case time complexity is the
  45. same as the :func:`networkx.chain_decomposition` function,
  46. $O(m + n)$, where $n$ is the number of nodes in the graph and $m$ is
  47. the number of edges.
  48. References
  49. ----------
  50. .. [1] https://en.wikipedia.org/wiki/Bridge_%28graph_theory%29#Bridge-Finding_with_Chain_Decompositions
  51. """
  52. multigraph = G.is_multigraph()
  53. H = nx.Graph(G) if multigraph else G
  54. chains = nx.chain_decomposition(H, root=root)
  55. chain_edges = set(chain.from_iterable(chains))
  56. H_copy = H.copy()
  57. if root is not None:
  58. H = H.subgraph(nx.node_connected_component(H, root)).copy()
  59. for u, v in H.edges():
  60. if (u, v) not in chain_edges and (v, u) not in chain_edges:
  61. if multigraph and len(G[u][v]) > 1:
  62. continue
  63. yield u, v
  64. @not_implemented_for("directed")
  65. def has_bridges(G, root=None):
  66. """Decide whether a graph has any bridges.
  67. A *bridge* in a graph is an edge whose removal causes the number of
  68. connected components of the graph to increase.
  69. Parameters
  70. ----------
  71. G : undirected graph
  72. root : node (optional)
  73. A node in the graph `G`. If specified, only the bridges in the
  74. connected component containing this node will be considered.
  75. Returns
  76. -------
  77. bool
  78. Whether the graph (or the connected component containing `root`)
  79. has any bridges.
  80. Raises
  81. ------
  82. NodeNotFound
  83. If `root` is not in the graph `G`.
  84. NetworkXNotImplemented
  85. If `G` is a directed graph.
  86. Examples
  87. --------
  88. The barbell graph with parameter zero has a single bridge::
  89. >>> G = nx.barbell_graph(10, 0)
  90. >>> nx.has_bridges(G)
  91. True
  92. On the other hand, the cycle graph has no bridges::
  93. >>> G = nx.cycle_graph(5)
  94. >>> nx.has_bridges(G)
  95. False
  96. Notes
  97. -----
  98. This implementation uses the :func:`networkx.bridges` function, so
  99. it shares its worst-case time complexity, $O(m + n)$, ignoring
  100. polylogarithmic factors, where $n$ is the number of nodes in the
  101. graph and $m$ is the number of edges.
  102. """
  103. try:
  104. next(bridges(G, root=root))
  105. except StopIteration:
  106. return False
  107. else:
  108. return True
  109. @not_implemented_for("multigraph")
  110. @not_implemented_for("directed")
  111. def local_bridges(G, with_span=True, weight=None):
  112. """Iterate over local bridges of `G` optionally computing the span
  113. A *local bridge* is an edge whose endpoints have no common neighbors.
  114. That is, the edge is not part of a triangle in the graph.
  115. The *span* of a *local bridge* is the shortest path length between
  116. the endpoints if the local bridge is removed.
  117. Parameters
  118. ----------
  119. G : undirected graph
  120. with_span : bool
  121. If True, yield a 3-tuple `(u, v, span)`
  122. weight : function, string or None (default: None)
  123. If function, used to compute edge weights for the span.
  124. If string, the edge data attribute used in calculating span.
  125. If None, all edges have weight 1.
  126. Yields
  127. ------
  128. e : edge
  129. The local bridges as an edge 2-tuple of nodes `(u, v)` or
  130. as a 3-tuple `(u, v, span)` when `with_span is True`.
  131. Raises
  132. ------
  133. NetworkXNotImplemented
  134. If `G` is a directed graph or multigraph.
  135. Examples
  136. --------
  137. A cycle graph has every edge a local bridge with span N-1.
  138. >>> G = nx.cycle_graph(9)
  139. >>> (0, 8, 8) in set(nx.local_bridges(G))
  140. True
  141. """
  142. if with_span is not True:
  143. for u, v in G.edges:
  144. if not (set(G[u]) & set(G[v])):
  145. yield u, v
  146. else:
  147. wt = nx.weighted._weight_function(G, weight)
  148. for u, v in G.edges:
  149. if not (set(G[u]) & set(G[v])):
  150. enodes = {u, v}
  151. def hide_edge(n, nbr, d):
  152. if n not in enodes or nbr not in enodes:
  153. return wt(n, nbr, d)
  154. return None
  155. try:
  156. span = nx.shortest_path_length(G, u, v, weight=hide_edge)
  157. yield u, v, span
  158. except nx.NetworkXNoPath:
  159. yield u, v, float("inf")