Statistics
| Branch: | Revision:

iof-tools / networkxMiCe / networkx-master / networkx / algorithms / traversal / edgebfs.py @ 5cef0f13

History | View | Annotate | Download (5.51 KB)

1
"""
2
=============================
3
Breadth First Search on Edges
4
=============================
5

6
Algorithms for a breadth-first traversal of edges in a graph.
7

8
"""
9
from collections import deque
10
import networkx as nx
11

    
12
FORWARD = 'forward'
13
REVERSE = 'reverse'
14

    
15
__all__ = ['edge_bfs']
16

    
17

    
18
def edge_bfs(G, source=None, orientation=None):
19
    """A directed, breadth-first-search of edges in `G`, beginning at `source`.
20

21
    Yield the edges of G in a breadth-first-search order continuing until
22
    all edges are generated.
23

24
    Parameters
25
    ----------
26
    G : graph
27
        A directed/undirected graph/multigraph.
28

29
    source : node, list of nodes
30
        The node from which the traversal begins. If None, then a source
31
        is chosen arbitrarily and repeatedly until all edges from each node in
32
        the graph are searched.
33

34
    orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
35
        For directed graphs and directed multigraphs, edge traversals need not
36
        respect the original orientation of the edges.
37
        When set to 'reverse' every edge is traversed in the reverse direction.
38
        When set to 'ignore', every edge is treated as undirected.
39
        When set to 'original', every edge is treated as directed.
40
        In all three cases, the yielded edge tuples add a last entry to
41
        indicate the direction in which that edge was traversed.
42
        If orientation is None, the yielded edge has no direction indicated.
43
        The direction is respected, but not reported.
44

45
    Yields
46
    ------
47
    edge : directed edge
48
        A directed edge indicating the path taken by the breadth-first-search.
49
        For graphs, `edge` is of the form `(u, v)` where `u` and `v`
50
        are the tail and head of the edge as determined by the traversal.
51
        For multigraphs, `edge` is of the form `(u, v, key)`, where `key` is
52
        the key of the edge. When the graph is directed, then `u` and `v`
53
        are always in the order of the actual directed edge.
54
        If orientation is not None then the edge tuple is extended to include
55
        the direction of traversal ('forward' or 'reverse') on that edge.
56

57
    Examples
58
    --------
59
    >>> import networkx as nx
60
    >>> nodes = [0, 1, 2, 3]
61
    >>> edges = [(0, 1), (1, 0), (1, 0), (2, 0), (2, 1), (3, 1)]
62

63
    >>> list(nx.edge_bfs(nx.Graph(edges), nodes))
64
    [(0, 1), (0, 2), (1, 2), (1, 3)]
65

66
    >>> list(nx.edge_bfs(nx.DiGraph(edges), nodes))
67
    [(0, 1), (1, 0), (2, 0), (2, 1), (3, 1)]
68

69
    >>> list(nx.edge_bfs(nx.MultiGraph(edges), nodes))
70
    [(0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (1, 2, 0), (1, 3, 0)]
71

72
    >>> list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes))
73
    [(0, 1, 0), (1, 0, 0), (1, 0, 1), (2, 0, 0), (2, 1, 0), (3, 1, 0)]
74

75
    >>> list(nx.edge_bfs(nx.DiGraph(edges), nodes, orientation='ignore'))
76
    [(0, 1, 'forward'), (1, 0, 'reverse'), (2, 0, 'reverse'), (2, 1, 'reverse'), (3, 1, 'reverse')]
77

78
    >>> list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes, orientation='ignore'))
79
    [(0, 1, 0, 'forward'), (1, 0, 0, 'reverse'), (1, 0, 1, 'reverse'), (2, 0, 0, 'reverse'), (2, 1, 0, 'reverse'), (3, 1, 0, 'reverse')]
80

81
    Notes
82
    -----
83
    The goal of this function is to visit edges. It differs from the more
84
    familiar breadth-first-search of nodes, as provided by
85
    :func:`networkx.algorithms.traversal.breadth_first_search.bfs_edges`, in
86
    that it does not stop once every node has been visited. In a directed graph
87
    with edges [(0, 1), (1, 2), (2, 1)], the edge (2, 1) would not be visited
88
    if not for the functionality provided by this function.
89

90
    See Also
91
    --------
92
    bfs_edges
93
    bfs_tree
94
    edge_dfs
95

96
    """
97
    nodes = list(G.nbunch_iter(source))
98
    if not nodes:
99
        return
100

    
101
    directed = G.is_directed()
102
    kwds = {'data': False}
103
    if G.is_multigraph() is True:
104
        kwds['keys'] = True
105

    
106
    # set up edge lookup
107
    if orientation is None:
108
        def edges_from(node):
109
            return iter(G.edges(node, **kwds))
110
    elif not directed or orientation == 'original':
111
        def edges_from(node):
112
            for e in G.edges(node, **kwds):
113
                yield e + (FORWARD,)
114
    elif orientation == 'reverse':
115
        def edges_from(node):
116
            for e in G.in_edges(node, **kwds):
117
                yield e + (REVERSE,)
118
    elif orientation == 'ignore':
119
        def edges_from(node):
120
            for e in G.edges(node, **kwds):
121
                yield e + (FORWARD,)
122
            for e in G.in_edges(node, **kwds):
123
                yield e + (REVERSE,)
124
    else:
125
        raise nx.NetworkXError("invalid orientation argument.")
126

    
127
    if directed:
128
        neighbors = G.successors
129
        def edge_id(edge):
130
            # remove direction indicator
131
            return edge[:-1] if orientation is not None else edge
132
    else:
133
        neighbors = G.neighbors
134
        def edge_id(edge):
135
            return (frozenset(edge[:2]),) +edge[2:]
136

    
137
    check_reverse = directed and orientation in ('reverse', 'ignore')
138

    
139
    # start BFS
140
    visited_nodes = {n for n in nodes}
141
    visited_edges = set()
142
    queue = deque([(n, edges_from(n)) for n in nodes])
143
    while queue:
144
        parent, children_edges = queue.popleft()
145
        for edge in children_edges:
146
            if check_reverse and edge[-1] == REVERSE:
147
                child = edge[0]
148
            else:
149
                child = edge[1]
150
            if child not in visited_nodes:
151
                visited_nodes.add(child)
152
                queue.append((child, edges_from(child)))
153
            edgeid = edge_id(edge)
154
            if edgeid not in visited_edges:
155
                visited_edges.add(edgeid)
156
                yield edge