edgedfs.py 5.9 KB

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