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