edgebfs.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. """
  2. =============================
  3. Breadth First Search on Edges
  4. =============================
  5. Algorithms for a breadth-first traversal of edges in a graph.
  6. """
  7. from collections import deque
  8. import networkx as nx
  9. FORWARD = "forward"
  10. REVERSE = "reverse"
  11. __all__ = ["edge_bfs"]
  12. @nx._dispatch
  13. def edge_bfs(G, source=None, orientation=None):
  14. """A directed, breadth-first-search of edges in `G`, beginning at `source`.
  15. Yield the edges of G in a breadth-first-search order continuing until
  16. all edges are generated.
  17. Parameters
  18. ----------
  19. G : graph
  20. A directed/undirected graph/multigraph.
  21. source : node, list of nodes
  22. The node from which the traversal begins. If None, then a source
  23. is chosen arbitrarily and repeatedly until all edges from each node in
  24. the graph are searched.
  25. orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
  26. For directed graphs and directed multigraphs, edge traversals need not
  27. respect the original orientation of the edges.
  28. When set to 'reverse' every edge is traversed in the reverse direction.
  29. When set to 'ignore', every edge is treated as undirected.
  30. When set to 'original', every edge is treated as directed.
  31. In all three cases, the yielded edge tuples add a last entry to
  32. indicate the direction in which that edge was traversed.
  33. If orientation is None, the yielded edge has no direction indicated.
  34. The direction is respected, but not reported.
  35. Yields
  36. ------
  37. edge : directed edge
  38. A directed edge indicating the path taken by the breadth-first-search.
  39. For graphs, `edge` is of the form `(u, v)` where `u` and `v`
  40. are the tail and head of the edge as determined by the traversal.
  41. For multigraphs, `edge` is of the form `(u, v, key)`, where `key` is
  42. the key of the edge. When the graph is directed, then `u` and `v`
  43. are always in the order of the actual directed edge.
  44. If orientation is not None then the edge tuple is extended to include
  45. the direction of traversal ('forward' or 'reverse') on that edge.
  46. Examples
  47. --------
  48. >>> nodes = [0, 1, 2, 3]
  49. >>> edges = [(0, 1), (1, 0), (1, 0), (2, 0), (2, 1), (3, 1)]
  50. >>> list(nx.edge_bfs(nx.Graph(edges), nodes))
  51. [(0, 1), (0, 2), (1, 2), (1, 3)]
  52. >>> list(nx.edge_bfs(nx.DiGraph(edges), nodes))
  53. [(0, 1), (1, 0), (2, 0), (2, 1), (3, 1)]
  54. >>> list(nx.edge_bfs(nx.MultiGraph(edges), nodes))
  55. [(0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (1, 2, 0), (1, 3, 0)]
  56. >>> list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes))
  57. [(0, 1, 0), (1, 0, 0), (1, 0, 1), (2, 0, 0), (2, 1, 0), (3, 1, 0)]
  58. >>> list(nx.edge_bfs(nx.DiGraph(edges), nodes, orientation="ignore"))
  59. [(0, 1, 'forward'), (1, 0, 'reverse'), (2, 0, 'reverse'), (2, 1, 'reverse'), (3, 1, 'reverse')]
  60. >>> list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes, orientation="ignore"))
  61. [(0, 1, 0, 'forward'), (1, 0, 0, 'reverse'), (1, 0, 1, 'reverse'), (2, 0, 0, 'reverse'), (2, 1, 0, 'reverse'), (3, 1, 0, 'reverse')]
  62. Notes
  63. -----
  64. The goal of this function is to visit edges. It differs from the more
  65. familiar breadth-first-search of nodes, as provided by
  66. :func:`networkx.algorithms.traversal.breadth_first_search.bfs_edges`, in
  67. that it does not stop once every node has been visited. In a directed graph
  68. with edges [(0, 1), (1, 2), (2, 1)], the edge (2, 1) would not be visited
  69. if not for the functionality provided by this function.
  70. The naming of this function is very similar to bfs_edges. The difference
  71. is that 'edge_bfs' yields edges even if they extend back to an already
  72. explored node while 'bfs_edges' yields the edges of the tree that results
  73. from a breadth-first-search (BFS) so no edges are reported if they extend
  74. to already explored nodes. That means 'edge_bfs' reports all edges while
  75. 'bfs_edges' only report those traversed by a node-based BFS. Yet another
  76. description is that 'bfs_edges' reports the edges traversed during BFS
  77. while 'edge_bfs' reports all edges in the order they are explored.
  78. See Also
  79. --------
  80. bfs_edges
  81. bfs_tree
  82. edge_dfs
  83. """
  84. nodes = list(G.nbunch_iter(source))
  85. if not nodes:
  86. return
  87. directed = G.is_directed()
  88. kwds = {"data": False}
  89. if G.is_multigraph() is True:
  90. kwds["keys"] = True
  91. # set up edge lookup
  92. if orientation is None:
  93. def edges_from(node):
  94. return iter(G.edges(node, **kwds))
  95. elif not directed or orientation == "original":
  96. def edges_from(node):
  97. for e in G.edges(node, **kwds):
  98. yield e + (FORWARD,)
  99. elif orientation == "reverse":
  100. def edges_from(node):
  101. for e in G.in_edges(node, **kwds):
  102. yield e + (REVERSE,)
  103. elif orientation == "ignore":
  104. def edges_from(node):
  105. for e in G.edges(node, **kwds):
  106. yield e + (FORWARD,)
  107. for e in G.in_edges(node, **kwds):
  108. yield e + (REVERSE,)
  109. else:
  110. raise nx.NetworkXError("invalid orientation argument.")
  111. if directed:
  112. neighbors = G.successors
  113. def edge_id(edge):
  114. # remove direction indicator
  115. return edge[:-1] if orientation is not None else edge
  116. else:
  117. neighbors = G.neighbors
  118. def edge_id(edge):
  119. return (frozenset(edge[:2]),) + edge[2:]
  120. check_reverse = directed and orientation in ("reverse", "ignore")
  121. # start BFS
  122. visited_nodes = set(nodes)
  123. visited_edges = set()
  124. queue = deque([(n, edges_from(n)) for n in nodes])
  125. while queue:
  126. parent, children_edges = queue.popleft()
  127. for edge in children_edges:
  128. if check_reverse and edge[-1] == REVERSE:
  129. child = edge[0]
  130. else:
  131. child = edge[1]
  132. if child not in visited_nodes:
  133. visited_nodes.add(child)
  134. queue.append((child, edges_from(child)))
  135. edgeid = edge_id(edge)
  136. if edgeid not in visited_edges:
  137. visited_edges.add(edgeid)
  138. yield edge