Statistics
| Branch: | Revision:

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

History | View | Annotate | Download (5.76 KB)

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

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

8
"""
9
import networkx as nx
10

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

    
14
__all__ = ['edge_dfs']
15

    
16

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

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

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

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

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

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

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

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

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

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

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

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

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

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

89
    See Also
90
    --------
91
    dfs_edges
92

93
    """
94
    nodes = list(G.nbunch_iter(source))
95
    if not nodes:
96
        return
97

    
98
    directed = G.is_directed()
99
    kwds = {'data': False}
100
    if G.is_multigraph() is True:
101
        kwds['keys'] = True
102

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

    
124
    # set up formation of edge_id to easily look up if edge already returned
125
    if directed:
126
        def edge_id(edge):
127
            # remove direction indicator
128
            return edge[:-1] if orientation is not None else edge
129
    else:
130
        def edge_id(edge):
131
            # single id for undirected requires frozenset on nodes
132
            return (frozenset(edge[:2]),) + edge[2:]
133

    
134
    # Basic setup
135
    check_reverse = directed and orientation in ('reverse', 'ignore')
136

    
137
    visited_edges = set()
138
    visited_nodes = set()
139
    edges = {}
140

    
141
    # start DFS
142
    for start_node in nodes:
143
        stack = [start_node]
144
        while stack:
145
            current_node = stack[-1]
146
            if current_node not in visited_nodes:
147
                edges[current_node] = edges_from(current_node)
148
                visited_nodes.add(current_node)
149

    
150
            try:
151
                edge = next(edges[current_node])
152
            except StopIteration:
153
                # No more edges from the current node.
154
                stack.pop()
155
            else:
156
                edgeid = edge_id(edge)
157
                if edgeid not in visited_edges:
158
                    visited_edges.add(edgeid)
159
                    # Mark the traversed "to" node as to-be-explored.
160
                    if check_reverse and edge[-1] == REVERSE:
161
                        stack.append(edge[0])
162
                    else:
163
                        stack.append(edge[1])
164
                    yield edge