Statistics
| Branch: | Revision:

iof-tools / networkxMiCe / networkx-master / networkx / algorithms / connectivity / disjoint_paths.py @ 5cef0f13

History | View | Annotate | Download (15 KB)

1
# disjoint_paths.py - Flow based node and edge disjoint paths.
2
#
3
# Copyright 2017-2019 NetworkX developers.
4
#
5
# This file is part of NetworkX.
6
#
7
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
8
# information.
9
#
10
# Author: Jordi Torrents <jordi.t21@gmail.com>
11
"""Flow based node and edge disjoint paths."""
12
import networkx as nx
13
from networkx.exception import NetworkXNoPath
14
# Define the default maximum flow function to use for the undelying
15
# maximum flow computations
16
from networkx.algorithms.flow import edmonds_karp
17
from networkx.algorithms.flow import preflow_push
18
from networkx.algorithms.flow import shortest_augmenting_path
19
default_flow_func = edmonds_karp
20
# Functions to build auxiliary data structures.
21
from networkx.algorithms.flow import build_residual_network
22
from .utils import build_auxiliary_node_connectivity
23
from .utils import build_auxiliary_edge_connectivity
24

    
25
try:
26
    from itertools import filterfalse as _filterfalse
27
except ImportError:  # Python 2
28
    def _filterfalse(predicate, iterable):
29
        # https://docs.python.org/3/library/itertools.html
30
        # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
31
        if predicate is None:
32
            predicate = bool
33
        for x in iterable:
34
            if not predicate(x):
35
                yield x
36

    
37
__all__ = [
38
    'edge_disjoint_paths',
39
    'node_disjoint_paths',
40
]
41

    
42

    
43
def edge_disjoint_paths(G, s, t, flow_func=None, cutoff=None, auxiliary=None,
44
                        residual=None):
45
    """Returns the edges disjoint paths between source and target.
46

47
    Edge disjoint paths are paths that do not share any edge. The
48
    number of edge disjoint paths between source and target is equal
49
    to their edge connectivity.
50

51
    Parameters
52
    ----------
53
    G : NetworkX graph
54

55
    s : node
56
        Source node for the flow.
57

58
    t : node
59
        Sink node for the flow.
60

61
    flow_func : function
62
        A function for computing the maximum flow among a pair of nodes.
63
        The function has to accept at least three parameters: a Digraph, 
64
        a source node, and a target node. And return a residual network 
65
        that follows NetworkX conventions (see :meth:`maximum_flow` for 
66
        details). If flow_func is None, the default maximum flow function 
67
        (:meth:`edmonds_karp`) is used. The choice of the default function
68
        may change from version to version and should not be relied on.
69
        Default value: None.
70

71
    cutoff : int
72
        Maximum number of paths to yield. Some of the maximum flow
73
        algorithms, such as :meth:`edmonds_karp` (the default) and 
74
        :meth:`shortest_augmenting_path` support the cutoff parameter,
75
        and will terminate when the flow value reaches or exceeds the
76
        cutoff. Other algorithms will ignore this parameter.
77
        Default value: None.
78

79
    auxiliary : NetworkX DiGraph
80
        Auxiliary digraph to compute flow based edge connectivity. It has
81
        to have a graph attribute called mapping with a dictionary mapping
82
        node names in G and in the auxiliary digraph. If provided
83
        it will be reused instead of recreated. Default value: None.
84

85
    residual : NetworkX DiGraph
86
        Residual network to compute maximum flow. If provided it will be
87
        reused instead of recreated. Default value: None.
88

89
    Returns
90
    -------
91
    paths : generator
92
        A generator of edge independent paths.
93

94
    Raises
95
    ------
96
    NetworkXNoPath : exception
97
        If there is no path between source and target.
98

99
    NetworkXError : exception
100
        If source or target are not in the graph G.
101

102
    See also
103
    --------
104
    :meth:`node_disjoint_paths`
105
    :meth:`edge_connectivity`
106
    :meth:`maximum_flow`
107
    :meth:`edmonds_karp`
108
    :meth:`preflow_push`
109
    :meth:`shortest_augmenting_path`
110

111
    Examples
112
    --------
113
    We use in this example the platonic icosahedral graph, which has node
114
    edge connectivity 5, thus there are 5 edge disjoint paths between any
115
    pair of nodes.
116

117
    >>> G = nx.icosahedral_graph()
118
    >>> len(list(nx.edge_disjoint_paths(G, 0, 6)))
119
    5
120

121

122
    If you need to compute edge disjoint paths on several pairs of
123
    nodes in the same graph, it is recommended that you reuse the
124
    data structures that NetworkX uses in the computation: the 
125
    auxiliary digraph for edge connectivity, and the residual
126
    network for the underlying maximum flow computation.
127

128
    Example of how to compute edge disjoint paths among all pairs of
129
    nodes of the platonic icosahedral graph reusing the data 
130
    structures.
131

132
    >>> import itertools
133
    >>> # You also have to explicitly import the function for 
134
    >>> # building the auxiliary digraph from the connectivity package
135
    >>> from networkx.algorithms.connectivity import (
136
    ...     build_auxiliary_edge_connectivity)
137
    >>> H = build_auxiliary_edge_connectivity(G)
138
    >>> # And the function for building the residual network from the
139
    >>> # flow package
140
    >>> from networkx.algorithms.flow import build_residual_network
141
    >>> # Note that the auxiliary digraph has an edge attribute named capacity
142
    >>> R = build_residual_network(H, 'capacity')
143
    >>> result = {n: {} for n in G}
144
    >>> # Reuse the auxiliary digraph and the residual network by passing them
145
    >>> # as arguments
146
    >>> for u, v in itertools.combinations(G, 2):
147
    ...     k = len(list(nx.edge_disjoint_paths(G, u, v, auxiliary=H, residual=R)))
148
    ...     result[u][v] = k
149
    >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
150
    True
151

152
    You can also use alternative flow algorithms for computing edge disjoint
153
    paths. For instance, in dense networks the algorithm
154
    :meth:`shortest_augmenting_path` will usually perform better than
155
    the default :meth:`edmonds_karp` which is faster for sparse
156
    networks with highly skewed degree distributions. Alternative flow
157
    functions have to be explicitly imported from the flow package.
158

159
    >>> from networkx.algorithms.flow import shortest_augmenting_path
160
    >>> len(list(nx.edge_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path)))
161
    5
162

163
    Notes
164
    -----
165
    This is a flow based implementation of edge disjoint paths. We compute
166
    the maximum flow between source and target on an auxiliary directed
167
    network. The saturated edges in the residual network after running the
168
    maximum flow algorithm correspond to edge disjoint paths between source
169
    and target in the original network. This function handles both directed
170
    and undirected graphs, and can use all flow algorithms from NetworkX flow
171
    package.
172

173
    """
174
    if s not in G:
175
        raise nx.NetworkXError('node %s not in graph' % s)
176
    if t not in G:
177
        raise nx.NetworkXError('node %s not in graph' % t)
178

    
179
    if flow_func is None:
180
        flow_func = default_flow_func
181

    
182
    if auxiliary is None:
183
        H = build_auxiliary_edge_connectivity(G)
184
    else:
185
        H = auxiliary
186

    
187
    # Maximum possible edge disjoint paths
188
    possible = min(H.out_degree(s), H.in_degree(t))
189
    if not possible:
190
        raise NetworkXNoPath
191

    
192
    if cutoff is None:
193
        cutoff = possible
194
    else:
195
        cutoff = min(cutoff, possible)
196

    
197
    # Compute maximum flow between source and target. Flow functions in
198
    # NetworkX return a residual network.
199
    kwargs = dict(capacity='capacity', residual=residual, cutoff=cutoff,
200
                  value_only=True)
201
    if flow_func is preflow_push:
202
        del kwargs['cutoff']
203
    if flow_func is shortest_augmenting_path:
204
        kwargs['two_phase'] = True
205
    R = flow_func(H, s, t, **kwargs)
206

    
207
    if R.graph['flow_value'] == 0:
208
        raise NetworkXNoPath
209

    
210
    # Saturated edges in the residual network form the edge disjoint paths
211
    # between source and target
212
    cutset = [(u, v) for u, v, d in R.edges(data=True)
213
              if d['capacity'] == d['flow'] and d['flow'] > 0]
214
    # This is equivalent of what flow.utils.build_flow_dict returns, but
215
    # only for the nodes with saturated edges and without reporting 0 flows.
216
    flow_dict = {n: {} for edge in cutset for n in edge}
217
    for u, v in cutset:
218
        flow_dict[u][v] = 1
219

    
220
    # Rebuild the edge disjoint paths from the flow dictionary.
221
    paths_found = 0
222
    for v in list(flow_dict[s]):
223
        if paths_found >= cutoff:
224
            # preflow_push does not support cutoff: we have to
225
            # keep track of the paths founds and stop at cutoff.
226
            break
227
        path = [s]
228
        if v == t:
229
            path.append(v)
230
            yield path
231
            continue
232
        u = v
233
        while u != t:
234
            path.append(u)
235
            try:
236
                u, _ = flow_dict[u].popitem()
237
            except KeyError:
238
                break
239
        else:
240
            path.append(t)
241
            yield path
242
            paths_found += 1
243

    
244

    
245
def node_disjoint_paths(G, s, t, flow_func=None, cutoff=None, auxiliary=None,
246
                        residual=None):
247
    r"""Computes node disjoint paths between source and target.
248

249
    Node dijoint paths are paths that only share their first and last
250
    nodes. The number of node independent paths between two nodes is
251
    equal to their local node connectivity.
252

253
    Parameters
254
    ----------
255
    G : NetworkX graph
256

257
    s : node
258
        Source node.
259

260
    t : node
261
        Target node.
262

263
    flow_func : function
264
        A function for computing the maximum flow among a pair of nodes.
265
        The function has to accept at least three parameters: a Digraph,
266
        a source node, and a target node. And return a residual network
267
        that follows NetworkX conventions (see :meth:`maximum_flow` for
268
        details). If flow_func is None, the default maximum flow function
269
        (:meth:`edmonds_karp`) is used. See below for details. The choice
270
        of the default function may change from version to version and
271
        should not be relied on. Default value: None.
272

273
    cutoff : int
274
        Maximum number of paths to yield. Some of the maximum flow
275
        algorithms, such as :meth:`edmonds_karp` (the default) and
276
        :meth:`shortest_augmenting_path` support the cutoff parameter,
277
        and will terminate when the flow value reaches or exceeds the
278
        cutoff. Other algorithms will ignore this parameter.
279
        Default value: None.
280

281
    auxiliary : NetworkX DiGraph
282
        Auxiliary digraph to compute flow based node connectivity. It has
283
        to have a graph attribute called mapping with a dictionary mapping
284
        node names in G and in the auxiliary digraph. If provided
285
        it will be reused instead of recreated. Default value: None.
286

287
    residual : NetworkX DiGraph
288
        Residual network to compute maximum flow. If provided it will be
289
        reused instead of recreated. Default value: None.
290

291
    Returns
292
    -------
293
    paths : generator
294
        Generator of node disjoint paths.
295

296
    Raises
297
    ------
298
    NetworkXNoPath : exception
299
        If there is no path between source and target.
300

301
    NetworkXError : exception
302
        If source or target are not in the graph G.
303

304
    Examples
305
    --------
306
    We use in this example the platonic icosahedral graph, which has node
307
    node connectivity 5, thus there are 5 node disjoint paths between any
308
    pair of non neighbor nodes.
309

310
    >>> G = nx.icosahedral_graph()
311
    >>> len(list(nx.node_disjoint_paths(G, 0, 6)))
312
    5
313

314
    If you need to compute node disjoint paths between several pairs of
315
    nodes in the same graph, it is recommended that you reuse the
316
    data structures that NetworkX uses in the computation: the
317
    auxiliary digraph for node connectivity and node cuts, and the
318
    residual network for the underlying maximum flow computation.
319

320
    Example of how to compute node disjoint paths reusing the data
321
    structures:
322

323
    >>> # You also have to explicitly import the function for 
324
    >>> # building the auxiliary digraph from the connectivity package
325
    >>> from networkx.algorithms.connectivity import (
326
    ...     build_auxiliary_node_connectivity)
327
    >>> H = build_auxiliary_node_connectivity(G)
328
    >>> # And the function for building the residual network from the
329
    >>> # flow package
330
    >>> from networkx.algorithms.flow import build_residual_network
331
    >>> # Note that the auxiliary digraph has an edge attribute named capacity
332
    >>> R = build_residual_network(H, 'capacity')
333
    >>> # Reuse the auxiliary digraph and the residual network by passing them
334
    >>> # as arguments
335
    >>> len(list(nx.node_disjoint_paths(G, 0, 6, auxiliary=H, residual=R)))
336
    5
337

338
    You can also use alternative flow algorithms for computing node disjoint
339
    paths. For instance, in dense networks the algorithm
340
    :meth:`shortest_augmenting_path` will usually perform better than
341
    the default :meth:`edmonds_karp` which is faster for sparse
342
    networks with highly skewed degree distributions. Alternative flow
343
    functions have to be explicitly imported from the flow package.
344

345
    >>> from networkx.algorithms.flow import shortest_augmenting_path
346
    >>> len(list(nx.node_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path)))
347
    5
348

349
    Notes
350
    -----
351
    This is a flow based implementation of node disjoint paths. We compute
352
    the maximum flow between source and target on an auxiliary directed
353
    network. The saturated edges in the residual network after running the
354
    maximum flow algorithm correspond to node disjoint paths between source
355
    and target in the original network. This function handles both directed
356
    and undirected graphs, and can use all flow algorithms from NetworkX flow
357
    package.
358

359
    See also
360
    --------
361
    :meth:`edge_disjoint_paths`
362
    :meth:`node_connectivity`
363
    :meth:`maximum_flow`
364
    :meth:`edmonds_karp`
365
    :meth:`preflow_push`
366
    :meth:`shortest_augmenting_path`
367

368
    """
369
    if s not in G:
370
        raise nx.NetworkXError('node %s not in graph' % s)
371
    if t not in G:
372
        raise nx.NetworkXError('node %s not in graph' % t)
373

    
374
    if auxiliary is None:
375
        H = build_auxiliary_node_connectivity(G)
376
    else:
377
        H = auxiliary
378

    
379
    mapping = H.graph.get('mapping', None)
380
    if mapping is None:
381
        raise nx.NetworkXError('Invalid auxiliary digraph.')
382

    
383
    # Maximum possible edge disjoint paths
384
    possible = min(H.out_degree('%sB' % mapping[s]),
385
                   H.in_degree('%sA' % mapping[t]))
386
    if not possible:
387
        raise NetworkXNoPath
388

    
389
    if cutoff is None:
390
        cutoff = possible
391
    else:
392
        cutoff = min(cutoff, possible)
393

    
394
    kwargs = dict(flow_func=flow_func, residual=residual, auxiliary=H,
395
                  cutoff=cutoff)
396

    
397
    # The edge disjoint paths in the auxiliary digraph correspond to the node
398
    # disjoint paths in the original graph.
399
    paths_edges = edge_disjoint_paths(H, '%sB' % mapping[s], '%sA' % mapping[t],
400
                                      **kwargs)
401
    for path in paths_edges:
402
        # Each node in the original graph maps to two nodes in auxiliary graph
403
        yield list(_unique_everseen(H.node[node]['id'] for node in path))
404

    
405

    
406
def _unique_everseen(iterable):
407
    # Adapted from https://docs.python.org/3/library/itertools.html examples
408
    "List unique elements, preserving order. Remember all elements ever seen."
409
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
410
    seen = set()
411
    seen_add = seen.add
412
    for element in _filterfalse(seen.__contains__, iterable):
413
        seen_add(element)
414
        yield element