def minimum_node_cut(G, s=None, t=None, flow_func=None): r"""Returns a set of nodes of minimum cardinality that disconnects G. If source and target nodes are provided, this function returns the set of nodes of minimum cardinality that, if removed, would destroy all paths among source and target in G. If not, it returns a set of nodes of minimum cardinality that disconnects G. Parameters ---------- G : NetworkX graph s : node Source node. Optional. Default value: None. t : node Target node. Optional. Default value: None. flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. Returns ------- cutset : set Set of nodes that, if removed, would disconnect G. If source and target nodes are provided, the set contains the nodes that if removed, would destroy all paths between source and target. Examples -------- >>> # Platonic icosahedral graph has node connectivity 5 >>> G = nx.icosahedral_graph() >>> node_cut = nx.minimum_node_cut(G) >>> len(node_cut) 5 You can use alternative flow algorithms for the underlying maximum flow computation. In dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp`, which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package. >>> from networkx.algorithms.flow import shortest_augmenting_path >>> node_cut == nx.minimum_node_cut(G, flow_func=shortest_augmenting_path) True If you specify a pair of nodes (source and target) as parameters, this function returns a local st node cut. >>> len(nx.minimum_node_cut(G, 3, 7)) 5 If you need to perform several local st cuts among different pairs of nodes on the same graph, it is recommended that you reuse the data structures used in the maximum flow computations. See :meth:`minimum_st_node_cut` for details. Notes ----- This is a flow based implementation of minimum node cut. The algorithm is based in solving a number of maximum flow computations to determine the capacity of the minimum cut on an auxiliary directed network that corresponds to the minimum node cut of G. It handles both directed and undirected graphs. This implementation is based on algorithm 11 in [1]_. See also -------- :meth:`minimum_st_node_cut` :meth:`minimum_cut` :meth:`minimum_edge_cut` :meth:`stoer_wagner` :meth:`node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf """ if (s is not None and t is None) or (s is None and t is not None): raise nx.NetworkXError('Both source and target must be specified.') # Local minimum node cut. if s is not None and t is not None: if s not in G: raise nx.NetworkXError('node %s not in graph' % s) if t not in G: raise nx.NetworkXError('node %s not in graph' % t) return minimum_st_node_cut(G, s, t, flow_func=flow_func) # Global minimum node cut. # Analog to the algorithm 11 for global node connectivity in [1]. if G.is_directed(): if not nx.is_weakly_connected(G): raise nx.NetworkXError('Input graph is not connected') iter_func = itertools.permutations def neighbors(v): return itertools.chain.from_iterable( [G.predecessors(v), G.successors(v)]) else: if not nx.is_connected(G): raise nx.NetworkXError('Input graph is not connected') iter_func = itertools.combinations neighbors = G.neighbors # Reuse the auxiliary digraph and the residual network. H = build_auxiliary_node_connectivity(G) R = build_residual_network(H, 'capacity') kwargs = dict(flow_func=flow_func, auxiliary=H, residual=R) # Choose a node with minimum degree. v = min(G, key=G.degree) # Initial node cutset is all neighbors of the node with minimum degree. min_cut = set(G[v]) # Compute st node cuts between v and all its non-neighbors nodes in G. for w in set(G) - set(neighbors(v)) - set([v]): this_cut = minimum_st_node_cut(G, v, w, **kwargs) if len(min_cut) >= len(this_cut): min_cut = this_cut # Also for non adjacent pairs of neighbors of v. for x, y in iter_func(neighbors(v), 2): if y in G[x]: continue this_cut = minimum_st_node_cut(G, x, y, **kwargs) if len(min_cut) >= len(this_cut): min_cut = this_cut return min_cut
def all_pairs_node_connectivity(G, nbunch=None, flow_func=None): """Compute node connectivity between all pairs of nodes of G. Parameters ---------- G : NetworkX graph Undirected graph nbunch: container Container of nodes. If provided node connectivity will be computed only over pairs of nodes in nbunch. flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. Returns ------- all_pairs : dict A dictionary with node connectivity between all pairs of nodes in G, or in nbunch if provided. See also -------- :meth:`local_node_connectivity` :meth:`edge_connectivity` :meth:`local_edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` """ if nbunch is None: nbunch = G else: nbunch = set(nbunch) directed = G.is_directed() if directed: iter_func = itertools.permutations else: iter_func = itertools.combinations all_pairs = dict((n, {}) for n in nbunch) # Reuse auxiliary digraph and residual network H = build_auxiliary_node_connectivity(G) mapping = H.graph['mapping'] R = build_residual_network(H, 'capacity') kwargs = dict(flow_func=flow_func, auxiliary=H, residual=R) for u, v in iter_func(nbunch, 2): K = local_node_connectivity(G, u, v, **kwargs) all_pairs[u][v] = K if not directed: all_pairs[v][u] = K return all_pairs
def minimum_st_node_cut(G, s, t, flow_func=None, auxiliary=None, residual=None): r"""Returns a set of nodes of minimum cardinality that disconnect source from target in G. This function returns the set of nodes of minimum cardinality that, if removed, would destroy all paths among source and target in G. Parameters ---------- G : NetworkX graph s : node Source node. t : node Target node. flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. auxiliary : NetworkX DiGraph Auxiliary digraph to compute flow based node connectivity. It has to have a graph attribute called mapping with a dictionary mapping node names in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default value: None. residual : NetworkX DiGraph Residual network to compute maximum flow. If provided it will be reused instead of recreated. Default value: None. Returns ------- cutset : set Set of nodes that, if removed, would destroy all paths between source and target in G. Examples -------- This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the connectivity package: >>> from networkx.algorithms.connectivity import minimum_st_node_cut We use in this example the platonic icosahedral graph, which has node connectivity 5. >>> G = nx.icosahedral_graph() >>> len(minimum_st_node_cut(G, 0, 6)) 5 If you need to compute local st cuts between several pairs of nodes in the same graph, it is recommended that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity and node cuts, and the residual network for the underlying maximum flow computation. Example of how to compute local st node cuts reusing the data structures: >>> # You also have to explicitly import the function for >>> # building the auxiliary digraph from the connectivity package >>> from networkx.algorithms.connectivity import ( ... build_auxiliary_node_connectivity) >>> H = build_auxiliary_node_connectivity(G) >>> # And the function for building the residual network from the >>> # flow package >>> from networkx.algorithms.flow import build_residual_network >>> # Note that the auxiliary digraph has an edge attribute named capacity >>> R = build_residual_network(H, 'capacity') >>> # Reuse the auxiliary digraph and the residual network by passing them >>> # as parameters >>> len(minimum_st_node_cut(G, 0, 6, auxiliary=H, residual=R)) 5 You can also use alternative flow algorithms for computing minimum st node cuts. For instance, in dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp` which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package. >>> from networkx.algorithms.flow import shortest_augmenting_path >>> len(minimum_st_node_cut(G, 0, 6, flow_func=shortest_augmenting_path)) 5 Notes ----- This is a flow based implementation of minimum node cut. The algorithm is based in solving a number of maximum flow computations to determine the capacity of the minimum cut on an auxiliary directed network that corresponds to the minimum node cut of G. It handles both directed and undirected graphs. This implementation is based on algorithm 11 in [1]_. See also -------- :meth:`minimum_node_cut` :meth:`minimum_edge_cut` :meth:`stoer_wagner` :meth:`node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf """ if auxiliary is None: H = build_auxiliary_node_connectivity(G) else: H = auxiliary mapping = H.graph.get('mapping', None) if mapping is None: raise nx.NetworkXError('Invalid auxiliary digraph.') if G.has_edge(s, t) or G.has_edge(t, s): return [] kwargs = dict(flow_func=flow_func, residual=residual, auxiliary=H) # The edge cut in the auxiliary digraph corresponds to the node cut in the # original graph. edge_cut = minimum_st_edge_cut(H, '%sB' % mapping[s], '%sA' % mapping[t], **kwargs) # Each node in the original graph maps to two nodes of the auxiliary graph node_cut = set(H.nodes[node]['id'] for edge in edge_cut for node in edge) return node_cut - set([s, t])
def average_node_connectivity(G, flow_func=None): r"""Returns the average connectivity of a graph G. The average connectivity `\bar{\kappa}` of a graph G is the average of local node connectivity over all pairs of nodes of G [1]_ . .. math:: \bar{\kappa}(G) = \frac{\sum_{u,v} \kappa_{G}(u,v)}{{n \choose 2}} Parameters ---------- G : NetworkX graph Undirected graph flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See :meth:`local_node_connectivity` for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. Returns ------- K : float Average node connectivity See also -------- :meth:`local_node_connectivity` :meth:`node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` References ---------- .. [1] Beineke, L., O. Oellermann, and R. Pippert (2002). The average connectivity of a graph. Discrete mathematics 252(1-3), 31-45. http://www.sciencedirect.com/science/article/pii/S0012365X01001807 """ if G.is_directed(): iter_func = itertools.permutations else: iter_func = itertools.combinations # Reuse the auxiliary digraph and the residual network H = build_auxiliary_node_connectivity(G) R = build_residual_network(H, 'capacity') kwargs = dict(flow_func=flow_func, auxiliary=H, residual=R) num, den = 0, 0 for u, v in iter_func(G, 2): num += local_node_connectivity(G, u, v, **kwargs) den += 1 if den == 0: # Null Graph return 0 return num / den
def local_node_connectivity(G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None): r"""Computes local node connectivity for nodes s and t. Local node connectivity for two non adjacent nodes s and t is the minimum number of nodes that must be removed (along with their incident edges) to disconnect them. This is a flow based implementation of node connectivity. We compute the maximum flow on an auxiliary digraph build from the original input graph (see below for details). Parameters ---------- G : NetworkX graph Undirected graph s : node Source node t : node Target node flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. auxiliary : NetworkX DiGraph Auxiliary digraph to compute flow based node connectivity. It has to have a graph attribute called mapping with a dictionary mapping node names in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default value: None. residual : NetworkX DiGraph Residual network to compute maximum flow. If provided it will be reused instead of recreated. Default value: None. cutoff : integer, float If specified, the maximum flow algorithm will terminate when the flow value reaches or exceeds the cutoff. This is only for the algorithms that support the cutoff parameter: :meth:`edmonds_karp` and :meth:`shortest_augmenting_path`. Other algorithms will ignore this parameter. Default value: None. Returns ------- K : integer local node connectivity for nodes s and t Examples -------- This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the connectivity package: >>> from networkx.algorithms.connectivity import local_node_connectivity We use in this example the platonic icosahedral graph, which has node connectivity 5. >>> G = nx.icosahedral_graph() >>> local_node_connectivity(G, 0, 6) 5 If you need to compute local connectivity on several pairs of nodes in the same graph, it is recommended that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity, and the residual network for the underlying maximum flow computation. Example of how to compute local node connectivity among all pairs of nodes of the platonic icosahedral graph reusing the data structures. >>> import itertools >>> # You also have to explicitly import the function for >>> # building the auxiliary digraph from the connectivity package >>> from networkx.algorithms.connectivity import ( ... build_auxiliary_node_connectivity) ... >>> H = build_auxiliary_node_connectivity(G) >>> # And the function for building the residual network from the >>> # flow package >>> from networkx.algorithms.flow import build_residual_network >>> # Note that the auxiliary digraph has an edge attribute named capacity >>> R = build_residual_network(H, 'capacity') >>> result = dict.fromkeys(G, dict()) >>> # Reuse the auxiliary digraph and the residual network by passing them >>> # as parameters >>> for u, v in itertools.combinations(G, 2): ... k = local_node_connectivity(G, u, v, auxiliary=H, residual=R) ... result[u][v] = k ... >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2)) True You can also use alternative flow algorithms for computing node connectivity. For instance, in dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp` which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package. >>> from networkx.algorithms.flow import shortest_augmenting_path >>> local_node_connectivity(G, 0, 6, flow_func=shortest_augmenting_path) 5 Notes ----- This is a flow based implementation of node connectivity. We compute the maximum flow using, by default, the :meth:`edmonds_karp` algorithm (see: :meth:`maximum_flow`) on an auxiliary digraph build from the original input graph: For an undirected graph G having `n` nodes and `m` edges we derive a directed graph H with `2n` nodes and `2m+n` arcs by replacing each original node `v` with two nodes `v_A`, `v_B` linked by an (internal) arc in H. Then for each edge (`u`, `v`) in G we add two arcs (`u_B`, `v_A`) and (`v_B`, `u_A`) in H. Finally we set the attribute capacity = 1 for each arc in H [1]_ . For a directed graph G having `n` nodes and `m` arcs we derive a directed graph H with `2n` nodes and `m+n` arcs by replacing each original node `v` with two nodes `v_A`, `v_B` linked by an (internal) arc (`v_A`, `v_B`) in H. Then for each arc (`u`, `v`) in G we add one arc (`u_B`, `v_A`) in H. Finally we set the attribute capacity = 1 for each arc in H. This is equal to the local node connectivity because the value of a maximum s-t-flow is equal to the capacity of a minimum s-t-cut. See also -------- :meth:`local_edge_connectivity` :meth:`node_connectivity` :meth:`minimum_node_cut` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` References ---------- .. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and Erlebach, 'Network Analysis: Methodological Foundations', Lecture Notes in Computer Science, Volume 3418, Springer-Verlag, 2005. http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf """ if flow_func is None: flow_func = default_flow_func if auxiliary is None: H = build_auxiliary_node_connectivity(G) else: H = auxiliary mapping = H.graph.get('mapping', None) if mapping is None: raise nx.NetworkXError('Invalid auxiliary digraph.') kwargs = dict(flow_func=flow_func, residual=residual) if flow_func is shortest_augmenting_path: kwargs['cutoff'] = cutoff kwargs['two_phase'] = True elif flow_func is edmonds_karp: kwargs['cutoff'] = cutoff elif flow_func is dinitz: kwargs['cutoff'] = cutoff elif flow_func is boykov_kolmogorov: kwargs['cutoff'] = cutoff return nx.maximum_flow_value(H, '%sB' % mapping[s], '%sA' % mapping[t], **kwargs)
def node_connectivity(G, s=None, t=None, flow_func=None): """Returns node connectivity for a graph or digraph G. Node connectivity is equal to the minimum number of nodes that must be removed to disconnect G or render it trivial. If source and target nodes are provided, this function returns the local node connectivity: the minimum number of nodes that must be removed to break all paths from source to target in G. Parameters ---------- G : NetworkX graph Undirected graph s : node Source node. Optional. Default value: None. t : node Target node. Optional. Default value: None. flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. Returns ------- K : integer Node connectivity of G, or local node connectivity if source and target are provided. Examples -------- >>> # Platonic icosahedral graph is 5-node-connected >>> G = nx.icosahedral_graph() >>> nx.node_connectivity(G) 5 You can use alternative flow algorithms for the underlying maximum flow computation. In dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp`, which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package. >>> from networkx.algorithms.flow import shortest_augmenting_path >>> nx.node_connectivity(G, flow_func=shortest_augmenting_path) 5 If you specify a pair of nodes (source and target) as parameters, this function returns the value of local node connectivity. >>> nx.node_connectivity(G, 3, 7) 5 If you need to perform several local computations among different pairs of nodes on the same graph, it is recommended that you reuse the data structures used in the maximum flow computations. See :meth:`local_node_connectivity` for details. Notes ----- This is a flow based implementation of node connectivity. The algorithm works by solving $O((n-\delta-1+\delta(\delta-1)/2))$ maximum flow problems on an auxiliary digraph. Where $\delta$ is the minimum degree of G. For details about the auxiliary digraph and the computation of local node connectivity see :meth:`local_node_connectivity`. This implementation is based on algorithm 11 in [1]_. See also -------- :meth:`local_node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf """ if (s is not None and t is None) or (s is None and t is not None): raise nx.NetworkXError('Both source and target must be specified.') # Local node connectivity if s is not None and t is not None: if s not in G: raise nx.NetworkXError('node %s not in graph' % s) if t not in G: raise nx.NetworkXError('node %s not in graph' % t) return local_node_connectivity(G, s, t, flow_func=flow_func) # Global node connectivity if G.is_directed(): if not nx.is_weakly_connected(G): return 0 iter_func = itertools.permutations # It is necessary to consider both predecessors # and successors for directed graphs def neighbors(v): return itertools.chain.from_iterable( [G.predecessors(v), G.successors(v)]) else: if not nx.is_connected(G): return 0 iter_func = itertools.combinations neighbors = G.neighbors # Reuse the auxiliary digraph and the residual network H = build_auxiliary_node_connectivity(G) R = build_residual_network(H, 'capacity') kwargs = dict(flow_func=flow_func, auxiliary=H, residual=R) # Pick a node with minimum degree # Node connectivity is bounded by degree. v, K = min(G.degree(), key=itemgetter(1)) # compute local node connectivity with all its non-neighbors nodes for w in set(G) - set(neighbors(v)) - set([v]): kwargs['cutoff'] = K K = min(K, local_node_connectivity(G, v, w, **kwargs)) # Also for non adjacent pairs of neighbors of v for x, y in iter_func(neighbors(v), 2): if y in G[x]: continue kwargs['cutoff'] = K K = min(K, local_node_connectivity(G, x, y, **kwargs)) return K
def all_node_cuts(G, k=None, flow_func=None): r"""Returns all minimum k cutsets of an undirected graph G. This implementation is based on Kanevsky's algorithm [1]_ for finding all minimum-size node cut-sets of an undirected graph G; ie the set (or sets) of nodes of cardinality equal to the node connectivity of G. Thus if removed, would break G into two or more connected components. Parameters ---------- G : NetworkX graph Undirected graph k : Integer Node connectivity of the input graph. If k is None, then it is computed. Default value: None. flow_func : function Function to perform the underlying flow computations. Default value edmonds_karp. This function performs better in sparse graphs with right tailed degree distributions. shortest_augmenting_path will perform better in denser graphs. Returns ------- cuts : a generator of node cutsets Each node cutset has cardinality equal to the node connectivity of the input graph. Examples -------- >>> # A two-dimensional grid graph has 4 cutsets of cardinality 2 >>> G = nx.grid_2d_graph(5, 5) >>> cutsets = list(nx.all_node_cuts(G)) >>> len(cutsets) 4 >>> all(2 == len(cutset) for cutset in cutsets) True >>> nx.node_connectivity(G) 2 Notes ----- This implementation is based on the sequential algorithm for finding all minimum-size separating vertex sets in a graph [1]_. The main idea is to compute minimum cuts using local maximum flow computations among a set of nodes of highest degree and all other non-adjacent nodes in the Graph. Once we find a minimum cut, we add an edge between the high degree node and the target node of the local maximum flow computation to make sure that we will not find that minimum cut again. See also -------- node_connectivity edmonds_karp shortest_augmenting_path References ---------- .. [1] Kanevsky, A. (1993). Finding all minimum-size separating vertex sets in a graph. Networks 23(6), 533--541. http://onlinelibrary.wiley.com/doi/10.1002/net.3230230604/abstract """ if not nx.is_connected(G): raise nx.NetworkXError('Input graph is disconnected.') # Address some corner cases first. # For complete Graphs if nx.density(G) == 1: for cut_set in combinations(G, len(G) - 1): yield set(cut_set) return # Initialize data structures. # Keep track of the cuts already computed so we do not repeat them. seen = [] # Even-Tarjan reduction is what we call auxiliary digraph # for node connectivity. H = build_auxiliary_node_connectivity(G) H_nodes = H.nodes # for speed mapping = H.graph['mapping'] # Keep a copy of original predecessors, H will be modified later. # Shallow copy is enough. original_H_pred = copy.copy(H._pred) R = build_residual_network(H, 'capacity') kwargs = dict(capacity='capacity', residual=R) # Define default flow function if flow_func is None: flow_func = default_flow_func if flow_func is shortest_augmenting_path: kwargs['two_phase'] = True # Begin the actual algorithm # step 1: Find node connectivity k of G if k is None: k = nx.node_connectivity(G, flow_func=flow_func) # step 2: # Find k nodes with top degree, call it X: X = set(n for n, d in sorted(G.degree(), key=itemgetter(1), reverse=True)[:k]) # Check if X is a k-node-cutset if _is_separating_set(G, X): seen.append(X) yield X for x in X: # step 3: Compute local connectivity flow of x with all other # non adjacent nodes in G non_adjacent = set(G) - X - set(G[x]) for v in non_adjacent: # step 4: compute maximum flow in an Even-Tarjan reduction H of G # and step 5: build the associated residual network R R = flow_func(H, '%sB' % mapping[x], '%sA' % mapping[v], **kwargs) flow_value = R.graph['flow_value'] if flow_value == k: # Find the nodes incident to the flow. E1 = flowed_edges = [(u, w) for (u, w, d) in R.edges(data=True) if d['flow'] != 0] VE1 = incident_nodes = set([n for edge in E1 for n in edge]) # Remove saturated edges form the residual network. # Note that reversed edges are introduced with capacity 0 # in the residual graph and they need to be removed too. saturated_edges = [(u, w, d) for (u, w, d) in R.edges(data=True) if d['capacity'] == d['flow'] or d['capacity'] == 0] R.remove_edges_from(saturated_edges) R_closure = nx.transitive_closure(R) # step 6: shrink the strongly connected components of # residual flow network R and call it L. L = nx.condensation(R) cmap = L.graph['mapping'] inv_cmap = defaultdict(list) for n, scc in cmap.items(): inv_cmap[scc].append(n) # Find the incident nodes in the condensed graph. VE1 = set([cmap[n] for n in VE1]) # step 7: Compute all antichains of L; # they map to closed sets in H. # Any edge in H that links a closed set is part of a cutset. for antichain in nx.antichains(L): # Only antichains that are subsets of incident nodes counts. # Lemma 8 in reference. if not set(antichain).issubset(VE1): continue # Nodes in an antichain of the condensation graph of # the residual network map to a closed set of nodes that # define a node partition of the auxiliary digraph H # through taking all of antichain's predecessors in the # transitive closure. S = set() for scc in antichain: S.update(inv_cmap[scc]) S_ancestors = set() for n in S: S_ancestors.update(R_closure._pred[n]) S.update(S_ancestors) if '%sB' % mapping[x] not in S or '%sA' % mapping[v] in S: continue # Find the cutset that links the node partition (S,~S) in H cutset = set() for u in S: cutset.update((u, w) for w in original_H_pred[u] if w not in S) # The edges in H that form the cutset are internal edges # (ie edges that represent a node of the original graph G) if any([H_nodes[u]['id'] != H_nodes[w]['id'] for u, w in cutset]): continue node_cut = set([H_nodes[u]['id'] for u, _ in cutset]) if len(node_cut) == k: # The cut is invalid if it includes internal edges of # end nodes. The other half of Lemma 8 in ref. if x in node_cut or v in node_cut: continue if node_cut not in seen: yield node_cut seen.append(node_cut) # Add an edge (x, v) to make sure that we do not # find this cutset again. This is equivalent # of adding the edge in the input graph # G.add_edge(x, v) and then regenerate H and R: # Add edges to the auxiliary digraph. # See build_residual_network for convention we used # in residual graphs. H.add_edge('%sB' % mapping[x], '%sA' % mapping[v], capacity=1) H.add_edge('%sB' % mapping[v], '%sA' % mapping[x], capacity=1) # Add edges to the residual network. R.add_edge('%sB' % mapping[x], '%sA' % mapping[v], capacity=1) R.add_edge('%sA' % mapping[v], '%sB' % mapping[x], capacity=0) R.add_edge('%sB' % mapping[v], '%sA' % mapping[x], capacity=1) R.add_edge('%sA' % mapping[x], '%sB' % mapping[v], capacity=0) # Add again the saturated edges to reuse the residual network R.add_edges_from(saturated_edges)
def node_disjoint_paths(G, s, t, flow_func=None, cutoff=None, auxiliary=None, residual=None): r"""Computes node disjoint paths between source and target. Node dijoint paths are paths that only share their first and last nodes. The number of node independent paths between two nodes is equal to their local node connectivity. Parameters ---------- G : NetworkX graph s : node Source node. t : node Target node. flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. cutoff : int Maximum number of paths to yield. Some of the maximum flow algorithms, such as :meth:`edmonds_karp` (the default) and :meth:`shortest_augmenting_path` support the cutoff parameter, and will terminate when the flow value reaches or exceeds the cutoff. Other algorithms will ignore this parameter. Default value: None. auxiliary : NetworkX DiGraph Auxiliary digraph to compute flow based node connectivity. It has to have a graph attribute called mapping with a dictionary mapping node names in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default value: None. residual : NetworkX DiGraph Residual network to compute maximum flow. If provided it will be reused instead of recreated. Default value: None. Returns ------- paths : generator Generator of node disjoint paths. Raises ------ NetworkXNoPath : exception If there is no path between source and target. NetworkXError : exception If source or target are not in the graph G. Examples -------- We use in this example the platonic icosahedral graph, which has node node connectivity 5, thus there are 5 node disjoint paths between any pair of non neighbor nodes. >>> G = nx.icosahedral_graph() >>> len(list(nx.node_disjoint_paths(G, 0, 6))) 5 If you need to compute node disjoint paths between several pairs of nodes in the same graph, it is recommended that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity and node cuts, and the residual network for the underlying maximum flow computation. Example of how to compute node disjoint paths reusing the data structures: >>> # You also have to explicitly import the function for >>> # building the auxiliary digraph from the connectivity package >>> from networkx.algorithms.connectivity import ( ... build_auxiliary_node_connectivity) >>> H = build_auxiliary_node_connectivity(G) >>> # And the function for building the residual network from the >>> # flow package >>> from networkx.algorithms.flow import build_residual_network >>> # Note that the auxiliary digraph has an edge attribute named capacity >>> R = build_residual_network(H, 'capacity') >>> # Reuse the auxiliary digraph and the residual network by passing them >>> # as arguments >>> len(list(nx.node_disjoint_paths(G, 0, 6, auxiliary=H, residual=R))) 5 You can also use alternative flow algorithms for computing node disjoint paths. For instance, in dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp` which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package. >>> from networkx.algorithms.flow import shortest_augmenting_path >>> len(list(nx.node_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path))) 5 Notes ----- This is a flow based implementation of node disjoint paths. We compute the maximum flow between source and target on an auxiliary directed network. The saturated edges in the residual network after running the maximum flow algorithm correspond to node disjoint paths between source and target in the original network. This function handles both directed and undirected graphs, and can use all flow algorithms from NetworkX flow package. See also -------- :meth:`edge_disjoint_paths` :meth:`node_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` """ if s not in G: raise nx.NetworkXError('node %s not in graph' % s) if t not in G: raise nx.NetworkXError('node %s not in graph' % t) if auxiliary is None: H = build_auxiliary_node_connectivity(G) else: H = auxiliary mapping = H.graph.get('mapping', None) if mapping is None: raise nx.NetworkXError('Invalid auxiliary digraph.') # Maximum possible edge disjoint paths possible = min(H.out_degree('%sB' % mapping[s]), H.in_degree('%sA' % mapping[t])) if not possible: raise NetworkXNoPath if cutoff is None: cutoff = possible else: cutoff = min(cutoff, possible) kwargs = dict(flow_func=flow_func, residual=residual, auxiliary=H, cutoff=cutoff) # The edge disjoint paths in the auxiliary digraph correspond to the node # disjoint paths in the original graph. paths_edges = edge_disjoint_paths(H, '%sB' % mapping[s], '%sA' % mapping[t], **kwargs) for path in paths_edges: # Each node in the original graph maps to two nodes in auxiliary graph yield list(_unique_everseen(H.node[node]['id'] for node in path))