edgebfs.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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._dispatchable
  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. >>> from pprint import pprint
  49. >>> nodes = [0, 1, 2, 3]
  50. >>> edges = [(0, 1), (1, 0), (1, 0), (2, 0), (2, 1), (3, 1)]
  51. >>> list(nx.edge_bfs(nx.Graph(edges), nodes))
  52. [(0, 1), (0, 2), (1, 2), (1, 3)]
  53. >>> list(nx.edge_bfs(nx.DiGraph(edges), nodes))
  54. [(0, 1), (1, 0), (2, 0), (2, 1), (3, 1)]
  55. >>> list(nx.edge_bfs(nx.MultiGraph(edges), nodes))
  56. [(0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (1, 2, 0), (1, 3, 0)]
  57. >>> list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes))
  58. [(0, 1, 0), (1, 0, 0), (1, 0, 1), (2, 0, 0), (2, 1, 0), (3, 1, 0)]
  59. >>> list(nx.edge_bfs(nx.DiGraph(edges), nodes, orientation="ignore"))
  60. [(0, 1, 'forward'), (1, 0, 'reverse'), (2, 0, 'reverse'), (2, 1, 'reverse'), (3, 1, 'reverse')]
  61. >>> elist = list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes, orientation="ignore"))
  62. >>> pprint(elist)
  63. [(0, 1, 0, 'forward'),
  64. (1, 0, 0, 'reverse'),
  65. (1, 0, 1, 'reverse'),
  66. (2, 0, 0, 'reverse'),
  67. (2, 1, 0, 'reverse'),
  68. (3, 1, 0, 'reverse')]
  69. Notes
  70. -----
  71. The goal of this function is to visit edges. It differs from the more
  72. familiar breadth-first-search of nodes, as provided by
  73. :func:`networkx.algorithms.traversal.breadth_first_search.bfs_edges`, in
  74. that it does not stop once every node has been visited. In a directed graph
  75. with edges [(0, 1), (1, 2), (2, 1)], the edge (2, 1) would not be visited
  76. if not for the functionality provided by this function.
  77. The naming of this function is very similar to bfs_edges. The difference
  78. is that 'edge_bfs' yields edges even if they extend back to an already
  79. explored node while 'bfs_edges' yields the edges of the tree that results
  80. from a breadth-first-search (BFS) so no edges are reported if they extend
  81. to already explored nodes. That means 'edge_bfs' reports all edges while
  82. 'bfs_edges' only report those traversed by a node-based BFS. Yet another
  83. description is that 'bfs_edges' reports the edges traversed during BFS
  84. while 'edge_bfs' reports all edges in the order they are explored.
  85. See Also
  86. --------
  87. bfs_edges
  88. bfs_tree
  89. edge_dfs
  90. """
  91. nodes = list(G.nbunch_iter(source))
  92. if not nodes:
  93. return
  94. directed = G.is_directed()
  95. kwds = {"data": False}
  96. if G.is_multigraph() is True:
  97. kwds["keys"] = True
  98. # set up edge lookup
  99. if orientation is None:
  100. def edges_from(node):
  101. return iter(G.edges(node, **kwds))
  102. elif not directed or orientation == "original":
  103. def edges_from(node):
  104. for e in G.edges(node, **kwds):
  105. yield e + (FORWARD,)
  106. elif orientation == "reverse":
  107. def edges_from(node):
  108. for e in G.in_edges(node, **kwds):
  109. yield e + (REVERSE,)
  110. elif orientation == "ignore":
  111. def edges_from(node):
  112. for e in G.edges(node, **kwds):
  113. yield e + (FORWARD,)
  114. for e in G.in_edges(node, **kwds):
  115. yield e + (REVERSE,)
  116. else:
  117. raise nx.NetworkXError("invalid orientation argument.")
  118. if directed:
  119. neighbors = G.successors
  120. def edge_id(edge):
  121. # remove direction indicator
  122. return edge[:-1] if orientation is not None else edge
  123. else:
  124. neighbors = G.neighbors
  125. def edge_id(edge):
  126. return (frozenset(edge[:2]),) + edge[2:]
  127. check_reverse = directed and orientation in ("reverse", "ignore")
  128. # start BFS
  129. visited_nodes = set(nodes)
  130. visited_edges = set()
  131. queue = deque([(n, edges_from(n)) for n in nodes])
  132. while queue:
  133. parent, children_edges = queue.popleft()
  134. for edge in children_edges:
  135. if check_reverse and edge[-1] == REVERSE:
  136. child = edge[0]
  137. else:
  138. child = edge[1]
  139. if child not in visited_nodes:
  140. visited_nodes.add(child)
  141. queue.append((child, edges_from(child)))
  142. edgeid = edge_id(edge)
  143. if edgeid not in visited_edges:
  144. visited_edges.add(edgeid)
  145. yield edge