Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/10.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/10.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/__init__.py +6 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/attracting.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/biconnected.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/connected.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/semiconnected.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/strongly_connected.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/weakly_connected.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/attracting.py +114 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/biconnected.py +393 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/connected.py +214 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/semiconnected.py +70 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/strongly_connected.py +430 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_attracting.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_biconnected.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_connected.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_semiconnected.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_strongly_connected.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_weakly_connected.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_attracting.py +70 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_biconnected.py +248 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_connected.py +117 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_semiconnected.py +55 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_strongly_connected.py +203 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_weakly_connected.py +96 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/components/weakly_connected.py +193 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__init__.py +11 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/connectivity.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/cuts.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/disjoint_paths.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_augmentation.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_kcomponents.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcomponents.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcutsets.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/stoerwagner.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/utils.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/connectivity.py +816 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/cuts.py +611 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/disjoint_paths.py +407 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_augmentation.py +1269 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_kcomponents.py +591 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcomponents.py +222 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcutsets.py +234 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/stoerwagner.py +151 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/utils.py +87 -0
ckpts/universal/global_step80/zero/10.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:04729a2ba6dc6371490aa348054e62bc8ce50113d5128d0ad9ec41ca048e550e
|
3 |
+
size 33555612
|
ckpts/universal/global_step80/zero/10.mlp.dense_h_to_4h_swiglu.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f3c052af163bac33c1c7feee85a6f4b5a9e419c2c2a013ef6c64e5d27703351e
|
3 |
+
size 33555533
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/__init__.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .connected import *
|
2 |
+
from .strongly_connected import *
|
3 |
+
from .weakly_connected import *
|
4 |
+
from .attracting import *
|
5 |
+
from .biconnected import *
|
6 |
+
from .semiconnected import *
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (352 Bytes). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/attracting.cpython-310.pyc
ADDED
Binary file (3.11 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/biconnected.cpython-310.pyc
ADDED
Binary file (11.4 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/connected.cpython-310.pyc
ADDED
Binary file (4.82 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/semiconnected.cpython-310.pyc
ADDED
Binary file (2.42 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/strongly_connected.cpython-310.pyc
ADDED
Binary file (11.5 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/__pycache__/weakly_connected.cpython-310.pyc
ADDED
Binary file (4.47 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/attracting.py
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Attracting components."""
|
2 |
+
import networkx as nx
|
3 |
+
from networkx.utils.decorators import not_implemented_for
|
4 |
+
|
5 |
+
__all__ = [
|
6 |
+
"number_attracting_components",
|
7 |
+
"attracting_components",
|
8 |
+
"is_attracting_component",
|
9 |
+
]
|
10 |
+
|
11 |
+
|
12 |
+
@not_implemented_for("undirected")
|
13 |
+
@nx._dispatchable
|
14 |
+
def attracting_components(G):
|
15 |
+
"""Generates the attracting components in `G`.
|
16 |
+
|
17 |
+
An attracting component in a directed graph `G` is a strongly connected
|
18 |
+
component with the property that a random walker on the graph will never
|
19 |
+
leave the component, once it enters the component.
|
20 |
+
|
21 |
+
The nodes in attracting components can also be thought of as recurrent
|
22 |
+
nodes. If a random walker enters the attractor containing the node, then
|
23 |
+
the node will be visited infinitely often.
|
24 |
+
|
25 |
+
To obtain induced subgraphs on each component use:
|
26 |
+
``(G.subgraph(c).copy() for c in attracting_components(G))``
|
27 |
+
|
28 |
+
Parameters
|
29 |
+
----------
|
30 |
+
G : DiGraph, MultiDiGraph
|
31 |
+
The graph to be analyzed.
|
32 |
+
|
33 |
+
Returns
|
34 |
+
-------
|
35 |
+
attractors : generator of sets
|
36 |
+
A generator of sets of nodes, one for each attracting component of G.
|
37 |
+
|
38 |
+
Raises
|
39 |
+
------
|
40 |
+
NetworkXNotImplemented
|
41 |
+
If the input graph is undirected.
|
42 |
+
|
43 |
+
See Also
|
44 |
+
--------
|
45 |
+
number_attracting_components
|
46 |
+
is_attracting_component
|
47 |
+
|
48 |
+
"""
|
49 |
+
scc = list(nx.strongly_connected_components(G))
|
50 |
+
cG = nx.condensation(G, scc)
|
51 |
+
for n in cG:
|
52 |
+
if cG.out_degree(n) == 0:
|
53 |
+
yield scc[n]
|
54 |
+
|
55 |
+
|
56 |
+
@not_implemented_for("undirected")
|
57 |
+
@nx._dispatchable
|
58 |
+
def number_attracting_components(G):
|
59 |
+
"""Returns the number of attracting components in `G`.
|
60 |
+
|
61 |
+
Parameters
|
62 |
+
----------
|
63 |
+
G : DiGraph, MultiDiGraph
|
64 |
+
The graph to be analyzed.
|
65 |
+
|
66 |
+
Returns
|
67 |
+
-------
|
68 |
+
n : int
|
69 |
+
The number of attracting components in G.
|
70 |
+
|
71 |
+
Raises
|
72 |
+
------
|
73 |
+
NetworkXNotImplemented
|
74 |
+
If the input graph is undirected.
|
75 |
+
|
76 |
+
See Also
|
77 |
+
--------
|
78 |
+
attracting_components
|
79 |
+
is_attracting_component
|
80 |
+
|
81 |
+
"""
|
82 |
+
return sum(1 for ac in attracting_components(G))
|
83 |
+
|
84 |
+
|
85 |
+
@not_implemented_for("undirected")
|
86 |
+
@nx._dispatchable
|
87 |
+
def is_attracting_component(G):
|
88 |
+
"""Returns True if `G` consists of a single attracting component.
|
89 |
+
|
90 |
+
Parameters
|
91 |
+
----------
|
92 |
+
G : DiGraph, MultiDiGraph
|
93 |
+
The graph to be analyzed.
|
94 |
+
|
95 |
+
Returns
|
96 |
+
-------
|
97 |
+
attracting : bool
|
98 |
+
True if `G` has a single attracting component. Otherwise, False.
|
99 |
+
|
100 |
+
Raises
|
101 |
+
------
|
102 |
+
NetworkXNotImplemented
|
103 |
+
If the input graph is undirected.
|
104 |
+
|
105 |
+
See Also
|
106 |
+
--------
|
107 |
+
attracting_components
|
108 |
+
number_attracting_components
|
109 |
+
|
110 |
+
"""
|
111 |
+
ac = list(attracting_components(G))
|
112 |
+
if len(ac) == 1:
|
113 |
+
return len(ac[0]) == len(G)
|
114 |
+
return False
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/biconnected.py
ADDED
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Biconnected components and articulation points."""
|
2 |
+
from itertools import chain
|
3 |
+
|
4 |
+
import networkx as nx
|
5 |
+
from networkx.utils.decorators import not_implemented_for
|
6 |
+
|
7 |
+
__all__ = [
|
8 |
+
"biconnected_components",
|
9 |
+
"biconnected_component_edges",
|
10 |
+
"is_biconnected",
|
11 |
+
"articulation_points",
|
12 |
+
]
|
13 |
+
|
14 |
+
|
15 |
+
@not_implemented_for("directed")
|
16 |
+
@nx._dispatchable
|
17 |
+
def is_biconnected(G):
|
18 |
+
"""Returns True if the graph is biconnected, False otherwise.
|
19 |
+
|
20 |
+
A graph is biconnected if, and only if, it cannot be disconnected by
|
21 |
+
removing only one node (and all edges incident on that node). If
|
22 |
+
removing a node increases the number of disconnected components
|
23 |
+
in the graph, that node is called an articulation point, or cut
|
24 |
+
vertex. A biconnected graph has no articulation points.
|
25 |
+
|
26 |
+
Parameters
|
27 |
+
----------
|
28 |
+
G : NetworkX Graph
|
29 |
+
An undirected graph.
|
30 |
+
|
31 |
+
Returns
|
32 |
+
-------
|
33 |
+
biconnected : bool
|
34 |
+
True if the graph is biconnected, False otherwise.
|
35 |
+
|
36 |
+
Raises
|
37 |
+
------
|
38 |
+
NetworkXNotImplemented
|
39 |
+
If the input graph is not undirected.
|
40 |
+
|
41 |
+
Examples
|
42 |
+
--------
|
43 |
+
>>> G = nx.path_graph(4)
|
44 |
+
>>> print(nx.is_biconnected(G))
|
45 |
+
False
|
46 |
+
>>> G.add_edge(0, 3)
|
47 |
+
>>> print(nx.is_biconnected(G))
|
48 |
+
True
|
49 |
+
|
50 |
+
See Also
|
51 |
+
--------
|
52 |
+
biconnected_components
|
53 |
+
articulation_points
|
54 |
+
biconnected_component_edges
|
55 |
+
is_strongly_connected
|
56 |
+
is_weakly_connected
|
57 |
+
is_connected
|
58 |
+
is_semiconnected
|
59 |
+
|
60 |
+
Notes
|
61 |
+
-----
|
62 |
+
The algorithm to find articulation points and biconnected
|
63 |
+
components is implemented using a non-recursive depth-first-search
|
64 |
+
(DFS) that keeps track of the highest level that back edges reach
|
65 |
+
in the DFS tree. A node `n` is an articulation point if, and only
|
66 |
+
if, there exists a subtree rooted at `n` such that there is no
|
67 |
+
back edge from any successor of `n` that links to a predecessor of
|
68 |
+
`n` in the DFS tree. By keeping track of all the edges traversed
|
69 |
+
by the DFS we can obtain the biconnected components because all
|
70 |
+
edges of a bicomponent will be traversed consecutively between
|
71 |
+
articulation points.
|
72 |
+
|
73 |
+
References
|
74 |
+
----------
|
75 |
+
.. [1] Hopcroft, J.; Tarjan, R. (1973).
|
76 |
+
"Efficient algorithms for graph manipulation".
|
77 |
+
Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
|
78 |
+
|
79 |
+
"""
|
80 |
+
bccs = biconnected_components(G)
|
81 |
+
try:
|
82 |
+
bcc = next(bccs)
|
83 |
+
except StopIteration:
|
84 |
+
# No bicomponents (empty graph?)
|
85 |
+
return False
|
86 |
+
try:
|
87 |
+
next(bccs)
|
88 |
+
except StopIteration:
|
89 |
+
# Only one bicomponent
|
90 |
+
return len(bcc) == len(G)
|
91 |
+
else:
|
92 |
+
# Multiple bicomponents
|
93 |
+
return False
|
94 |
+
|
95 |
+
|
96 |
+
@not_implemented_for("directed")
|
97 |
+
@nx._dispatchable
|
98 |
+
def biconnected_component_edges(G):
|
99 |
+
"""Returns a generator of lists of edges, one list for each biconnected
|
100 |
+
component of the input graph.
|
101 |
+
|
102 |
+
Biconnected components are maximal subgraphs such that the removal of a
|
103 |
+
node (and all edges incident on that node) will not disconnect the
|
104 |
+
subgraph. Note that nodes may be part of more than one biconnected
|
105 |
+
component. Those nodes are articulation points, or cut vertices.
|
106 |
+
However, each edge belongs to one, and only one, biconnected component.
|
107 |
+
|
108 |
+
Notice that by convention a dyad is considered a biconnected component.
|
109 |
+
|
110 |
+
Parameters
|
111 |
+
----------
|
112 |
+
G : NetworkX Graph
|
113 |
+
An undirected graph.
|
114 |
+
|
115 |
+
Returns
|
116 |
+
-------
|
117 |
+
edges : generator of lists
|
118 |
+
Generator of lists of edges, one list for each bicomponent.
|
119 |
+
|
120 |
+
Raises
|
121 |
+
------
|
122 |
+
NetworkXNotImplemented
|
123 |
+
If the input graph is not undirected.
|
124 |
+
|
125 |
+
Examples
|
126 |
+
--------
|
127 |
+
>>> G = nx.barbell_graph(4, 2)
|
128 |
+
>>> print(nx.is_biconnected(G))
|
129 |
+
False
|
130 |
+
>>> bicomponents_edges = list(nx.biconnected_component_edges(G))
|
131 |
+
>>> len(bicomponents_edges)
|
132 |
+
5
|
133 |
+
>>> G.add_edge(2, 8)
|
134 |
+
>>> print(nx.is_biconnected(G))
|
135 |
+
True
|
136 |
+
>>> bicomponents_edges = list(nx.biconnected_component_edges(G))
|
137 |
+
>>> len(bicomponents_edges)
|
138 |
+
1
|
139 |
+
|
140 |
+
See Also
|
141 |
+
--------
|
142 |
+
is_biconnected,
|
143 |
+
biconnected_components,
|
144 |
+
articulation_points,
|
145 |
+
|
146 |
+
Notes
|
147 |
+
-----
|
148 |
+
The algorithm to find articulation points and biconnected
|
149 |
+
components is implemented using a non-recursive depth-first-search
|
150 |
+
(DFS) that keeps track of the highest level that back edges reach
|
151 |
+
in the DFS tree. A node `n` is an articulation point if, and only
|
152 |
+
if, there exists a subtree rooted at `n` such that there is no
|
153 |
+
back edge from any successor of `n` that links to a predecessor of
|
154 |
+
`n` in the DFS tree. By keeping track of all the edges traversed
|
155 |
+
by the DFS we can obtain the biconnected components because all
|
156 |
+
edges of a bicomponent will be traversed consecutively between
|
157 |
+
articulation points.
|
158 |
+
|
159 |
+
References
|
160 |
+
----------
|
161 |
+
.. [1] Hopcroft, J.; Tarjan, R. (1973).
|
162 |
+
"Efficient algorithms for graph manipulation".
|
163 |
+
Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
|
164 |
+
|
165 |
+
"""
|
166 |
+
yield from _biconnected_dfs(G, components=True)
|
167 |
+
|
168 |
+
|
169 |
+
@not_implemented_for("directed")
|
170 |
+
@nx._dispatchable
|
171 |
+
def biconnected_components(G):
|
172 |
+
"""Returns a generator of sets of nodes, one set for each biconnected
|
173 |
+
component of the graph
|
174 |
+
|
175 |
+
Biconnected components are maximal subgraphs such that the removal of a
|
176 |
+
node (and all edges incident on that node) will not disconnect the
|
177 |
+
subgraph. Note that nodes may be part of more than one biconnected
|
178 |
+
component. Those nodes are articulation points, or cut vertices. The
|
179 |
+
removal of articulation points will increase the number of connected
|
180 |
+
components of the graph.
|
181 |
+
|
182 |
+
Notice that by convention a dyad is considered a biconnected component.
|
183 |
+
|
184 |
+
Parameters
|
185 |
+
----------
|
186 |
+
G : NetworkX Graph
|
187 |
+
An undirected graph.
|
188 |
+
|
189 |
+
Returns
|
190 |
+
-------
|
191 |
+
nodes : generator
|
192 |
+
Generator of sets of nodes, one set for each biconnected component.
|
193 |
+
|
194 |
+
Raises
|
195 |
+
------
|
196 |
+
NetworkXNotImplemented
|
197 |
+
If the input graph is not undirected.
|
198 |
+
|
199 |
+
Examples
|
200 |
+
--------
|
201 |
+
>>> G = nx.lollipop_graph(5, 1)
|
202 |
+
>>> print(nx.is_biconnected(G))
|
203 |
+
False
|
204 |
+
>>> bicomponents = list(nx.biconnected_components(G))
|
205 |
+
>>> len(bicomponents)
|
206 |
+
2
|
207 |
+
>>> G.add_edge(0, 5)
|
208 |
+
>>> print(nx.is_biconnected(G))
|
209 |
+
True
|
210 |
+
>>> bicomponents = list(nx.biconnected_components(G))
|
211 |
+
>>> len(bicomponents)
|
212 |
+
1
|
213 |
+
|
214 |
+
You can generate a sorted list of biconnected components, largest
|
215 |
+
first, using sort.
|
216 |
+
|
217 |
+
>>> G.remove_edge(0, 5)
|
218 |
+
>>> [len(c) for c in sorted(nx.biconnected_components(G), key=len, reverse=True)]
|
219 |
+
[5, 2]
|
220 |
+
|
221 |
+
If you only want the largest connected component, it's more
|
222 |
+
efficient to use max instead of sort.
|
223 |
+
|
224 |
+
>>> Gc = max(nx.biconnected_components(G), key=len)
|
225 |
+
|
226 |
+
To create the components as subgraphs use:
|
227 |
+
``(G.subgraph(c).copy() for c in biconnected_components(G))``
|
228 |
+
|
229 |
+
See Also
|
230 |
+
--------
|
231 |
+
is_biconnected
|
232 |
+
articulation_points
|
233 |
+
biconnected_component_edges
|
234 |
+
k_components : this function is a special case where k=2
|
235 |
+
bridge_components : similar to this function, but is defined using
|
236 |
+
2-edge-connectivity instead of 2-node-connectivity.
|
237 |
+
|
238 |
+
Notes
|
239 |
+
-----
|
240 |
+
The algorithm to find articulation points and biconnected
|
241 |
+
components is implemented using a non-recursive depth-first-search
|
242 |
+
(DFS) that keeps track of the highest level that back edges reach
|
243 |
+
in the DFS tree. A node `n` is an articulation point if, and only
|
244 |
+
if, there exists a subtree rooted at `n` such that there is no
|
245 |
+
back edge from any successor of `n` that links to a predecessor of
|
246 |
+
`n` in the DFS tree. By keeping track of all the edges traversed
|
247 |
+
by the DFS we can obtain the biconnected components because all
|
248 |
+
edges of a bicomponent will be traversed consecutively between
|
249 |
+
articulation points.
|
250 |
+
|
251 |
+
References
|
252 |
+
----------
|
253 |
+
.. [1] Hopcroft, J.; Tarjan, R. (1973).
|
254 |
+
"Efficient algorithms for graph manipulation".
|
255 |
+
Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
|
256 |
+
|
257 |
+
"""
|
258 |
+
for comp in _biconnected_dfs(G, components=True):
|
259 |
+
yield set(chain.from_iterable(comp))
|
260 |
+
|
261 |
+
|
262 |
+
@not_implemented_for("directed")
|
263 |
+
@nx._dispatchable
|
264 |
+
def articulation_points(G):
|
265 |
+
"""Yield the articulation points, or cut vertices, of a graph.
|
266 |
+
|
267 |
+
An articulation point or cut vertex is any node whose removal (along with
|
268 |
+
all its incident edges) increases the number of connected components of
|
269 |
+
a graph. An undirected connected graph without articulation points is
|
270 |
+
biconnected. Articulation points belong to more than one biconnected
|
271 |
+
component of a graph.
|
272 |
+
|
273 |
+
Notice that by convention a dyad is considered a biconnected component.
|
274 |
+
|
275 |
+
Parameters
|
276 |
+
----------
|
277 |
+
G : NetworkX Graph
|
278 |
+
An undirected graph.
|
279 |
+
|
280 |
+
Yields
|
281 |
+
------
|
282 |
+
node
|
283 |
+
An articulation point in the graph.
|
284 |
+
|
285 |
+
Raises
|
286 |
+
------
|
287 |
+
NetworkXNotImplemented
|
288 |
+
If the input graph is not undirected.
|
289 |
+
|
290 |
+
Examples
|
291 |
+
--------
|
292 |
+
|
293 |
+
>>> G = nx.barbell_graph(4, 2)
|
294 |
+
>>> print(nx.is_biconnected(G))
|
295 |
+
False
|
296 |
+
>>> len(list(nx.articulation_points(G)))
|
297 |
+
4
|
298 |
+
>>> G.add_edge(2, 8)
|
299 |
+
>>> print(nx.is_biconnected(G))
|
300 |
+
True
|
301 |
+
>>> len(list(nx.articulation_points(G)))
|
302 |
+
0
|
303 |
+
|
304 |
+
See Also
|
305 |
+
--------
|
306 |
+
is_biconnected
|
307 |
+
biconnected_components
|
308 |
+
biconnected_component_edges
|
309 |
+
|
310 |
+
Notes
|
311 |
+
-----
|
312 |
+
The algorithm to find articulation points and biconnected
|
313 |
+
components is implemented using a non-recursive depth-first-search
|
314 |
+
(DFS) that keeps track of the highest level that back edges reach
|
315 |
+
in the DFS tree. A node `n` is an articulation point if, and only
|
316 |
+
if, there exists a subtree rooted at `n` such that there is no
|
317 |
+
back edge from any successor of `n` that links to a predecessor of
|
318 |
+
`n` in the DFS tree. By keeping track of all the edges traversed
|
319 |
+
by the DFS we can obtain the biconnected components because all
|
320 |
+
edges of a bicomponent will be traversed consecutively between
|
321 |
+
articulation points.
|
322 |
+
|
323 |
+
References
|
324 |
+
----------
|
325 |
+
.. [1] Hopcroft, J.; Tarjan, R. (1973).
|
326 |
+
"Efficient algorithms for graph manipulation".
|
327 |
+
Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
|
328 |
+
|
329 |
+
"""
|
330 |
+
seen = set()
|
331 |
+
for articulation in _biconnected_dfs(G, components=False):
|
332 |
+
if articulation not in seen:
|
333 |
+
seen.add(articulation)
|
334 |
+
yield articulation
|
335 |
+
|
336 |
+
|
337 |
+
@not_implemented_for("directed")
|
338 |
+
def _biconnected_dfs(G, components=True):
|
339 |
+
# depth-first search algorithm to generate articulation points
|
340 |
+
# and biconnected components
|
341 |
+
visited = set()
|
342 |
+
for start in G:
|
343 |
+
if start in visited:
|
344 |
+
continue
|
345 |
+
discovery = {start: 0} # time of first discovery of node during search
|
346 |
+
low = {start: 0}
|
347 |
+
root_children = 0
|
348 |
+
visited.add(start)
|
349 |
+
edge_stack = []
|
350 |
+
stack = [(start, start, iter(G[start]))]
|
351 |
+
edge_index = {}
|
352 |
+
while stack:
|
353 |
+
grandparent, parent, children = stack[-1]
|
354 |
+
try:
|
355 |
+
child = next(children)
|
356 |
+
if grandparent == child:
|
357 |
+
continue
|
358 |
+
if child in visited:
|
359 |
+
if discovery[child] <= discovery[parent]: # back edge
|
360 |
+
low[parent] = min(low[parent], discovery[child])
|
361 |
+
if components:
|
362 |
+
edge_index[parent, child] = len(edge_stack)
|
363 |
+
edge_stack.append((parent, child))
|
364 |
+
else:
|
365 |
+
low[child] = discovery[child] = len(discovery)
|
366 |
+
visited.add(child)
|
367 |
+
stack.append((parent, child, iter(G[child])))
|
368 |
+
if components:
|
369 |
+
edge_index[parent, child] = len(edge_stack)
|
370 |
+
edge_stack.append((parent, child))
|
371 |
+
|
372 |
+
except StopIteration:
|
373 |
+
stack.pop()
|
374 |
+
if len(stack) > 1:
|
375 |
+
if low[parent] >= discovery[grandparent]:
|
376 |
+
if components:
|
377 |
+
ind = edge_index[grandparent, parent]
|
378 |
+
yield edge_stack[ind:]
|
379 |
+
del edge_stack[ind:]
|
380 |
+
|
381 |
+
else:
|
382 |
+
yield grandparent
|
383 |
+
low[grandparent] = min(low[parent], low[grandparent])
|
384 |
+
elif stack: # length 1 so grandparent is root
|
385 |
+
root_children += 1
|
386 |
+
if components:
|
387 |
+
ind = edge_index[grandparent, parent]
|
388 |
+
yield edge_stack[ind:]
|
389 |
+
del edge_stack[ind:]
|
390 |
+
if not components:
|
391 |
+
# root node is articulation point if it has more than 1 child
|
392 |
+
if root_children > 1:
|
393 |
+
yield start
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/connected.py
ADDED
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Connected components."""
|
2 |
+
import networkx as nx
|
3 |
+
from networkx.utils.decorators import not_implemented_for
|
4 |
+
|
5 |
+
from ...utils import arbitrary_element
|
6 |
+
|
7 |
+
__all__ = [
|
8 |
+
"number_connected_components",
|
9 |
+
"connected_components",
|
10 |
+
"is_connected",
|
11 |
+
"node_connected_component",
|
12 |
+
]
|
13 |
+
|
14 |
+
|
15 |
+
@not_implemented_for("directed")
|
16 |
+
@nx._dispatchable
|
17 |
+
def connected_components(G):
|
18 |
+
"""Generate connected components.
|
19 |
+
|
20 |
+
Parameters
|
21 |
+
----------
|
22 |
+
G : NetworkX graph
|
23 |
+
An undirected graph
|
24 |
+
|
25 |
+
Returns
|
26 |
+
-------
|
27 |
+
comp : generator of sets
|
28 |
+
A generator of sets of nodes, one for each component of G.
|
29 |
+
|
30 |
+
Raises
|
31 |
+
------
|
32 |
+
NetworkXNotImplemented
|
33 |
+
If G is directed.
|
34 |
+
|
35 |
+
Examples
|
36 |
+
--------
|
37 |
+
Generate a sorted list of connected components, largest first.
|
38 |
+
|
39 |
+
>>> G = nx.path_graph(4)
|
40 |
+
>>> nx.add_path(G, [10, 11, 12])
|
41 |
+
>>> [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)]
|
42 |
+
[4, 3]
|
43 |
+
|
44 |
+
If you only want the largest connected component, it's more
|
45 |
+
efficient to use max instead of sort.
|
46 |
+
|
47 |
+
>>> largest_cc = max(nx.connected_components(G), key=len)
|
48 |
+
|
49 |
+
To create the induced subgraph of each component use:
|
50 |
+
|
51 |
+
>>> S = [G.subgraph(c).copy() for c in nx.connected_components(G)]
|
52 |
+
|
53 |
+
See Also
|
54 |
+
--------
|
55 |
+
strongly_connected_components
|
56 |
+
weakly_connected_components
|
57 |
+
|
58 |
+
Notes
|
59 |
+
-----
|
60 |
+
For undirected graphs only.
|
61 |
+
|
62 |
+
"""
|
63 |
+
seen = set()
|
64 |
+
for v in G:
|
65 |
+
if v not in seen:
|
66 |
+
c = _plain_bfs(G, v)
|
67 |
+
seen.update(c)
|
68 |
+
yield c
|
69 |
+
|
70 |
+
|
71 |
+
@not_implemented_for("directed")
|
72 |
+
@nx._dispatchable
|
73 |
+
def number_connected_components(G):
|
74 |
+
"""Returns the number of connected components.
|
75 |
+
|
76 |
+
Parameters
|
77 |
+
----------
|
78 |
+
G : NetworkX graph
|
79 |
+
An undirected graph.
|
80 |
+
|
81 |
+
Returns
|
82 |
+
-------
|
83 |
+
n : integer
|
84 |
+
Number of connected components
|
85 |
+
|
86 |
+
Raises
|
87 |
+
------
|
88 |
+
NetworkXNotImplemented
|
89 |
+
If G is directed.
|
90 |
+
|
91 |
+
Examples
|
92 |
+
--------
|
93 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (5, 6), (3, 4)])
|
94 |
+
>>> nx.number_connected_components(G)
|
95 |
+
3
|
96 |
+
|
97 |
+
See Also
|
98 |
+
--------
|
99 |
+
connected_components
|
100 |
+
number_weakly_connected_components
|
101 |
+
number_strongly_connected_components
|
102 |
+
|
103 |
+
Notes
|
104 |
+
-----
|
105 |
+
For undirected graphs only.
|
106 |
+
|
107 |
+
"""
|
108 |
+
return sum(1 for cc in connected_components(G))
|
109 |
+
|
110 |
+
|
111 |
+
@not_implemented_for("directed")
|
112 |
+
@nx._dispatchable
|
113 |
+
def is_connected(G):
|
114 |
+
"""Returns True if the graph is connected, False otherwise.
|
115 |
+
|
116 |
+
Parameters
|
117 |
+
----------
|
118 |
+
G : NetworkX Graph
|
119 |
+
An undirected graph.
|
120 |
+
|
121 |
+
Returns
|
122 |
+
-------
|
123 |
+
connected : bool
|
124 |
+
True if the graph is connected, false otherwise.
|
125 |
+
|
126 |
+
Raises
|
127 |
+
------
|
128 |
+
NetworkXNotImplemented
|
129 |
+
If G is directed.
|
130 |
+
|
131 |
+
Examples
|
132 |
+
--------
|
133 |
+
>>> G = nx.path_graph(4)
|
134 |
+
>>> print(nx.is_connected(G))
|
135 |
+
True
|
136 |
+
|
137 |
+
See Also
|
138 |
+
--------
|
139 |
+
is_strongly_connected
|
140 |
+
is_weakly_connected
|
141 |
+
is_semiconnected
|
142 |
+
is_biconnected
|
143 |
+
connected_components
|
144 |
+
|
145 |
+
Notes
|
146 |
+
-----
|
147 |
+
For undirected graphs only.
|
148 |
+
|
149 |
+
"""
|
150 |
+
if len(G) == 0:
|
151 |
+
raise nx.NetworkXPointlessConcept(
|
152 |
+
"Connectivity is undefined for the null graph."
|
153 |
+
)
|
154 |
+
return sum(1 for node in _plain_bfs(G, arbitrary_element(G))) == len(G)
|
155 |
+
|
156 |
+
|
157 |
+
@not_implemented_for("directed")
|
158 |
+
@nx._dispatchable
|
159 |
+
def node_connected_component(G, n):
|
160 |
+
"""Returns the set of nodes in the component of graph containing node n.
|
161 |
+
|
162 |
+
Parameters
|
163 |
+
----------
|
164 |
+
G : NetworkX Graph
|
165 |
+
An undirected graph.
|
166 |
+
|
167 |
+
n : node label
|
168 |
+
A node in G
|
169 |
+
|
170 |
+
Returns
|
171 |
+
-------
|
172 |
+
comp : set
|
173 |
+
A set of nodes in the component of G containing node n.
|
174 |
+
|
175 |
+
Raises
|
176 |
+
------
|
177 |
+
NetworkXNotImplemented
|
178 |
+
If G is directed.
|
179 |
+
|
180 |
+
Examples
|
181 |
+
--------
|
182 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (5, 6), (3, 4)])
|
183 |
+
>>> nx.node_connected_component(G, 0) # nodes of component that contains node 0
|
184 |
+
{0, 1, 2}
|
185 |
+
|
186 |
+
See Also
|
187 |
+
--------
|
188 |
+
connected_components
|
189 |
+
|
190 |
+
Notes
|
191 |
+
-----
|
192 |
+
For undirected graphs only.
|
193 |
+
|
194 |
+
"""
|
195 |
+
return _plain_bfs(G, n)
|
196 |
+
|
197 |
+
|
198 |
+
def _plain_bfs(G, source):
|
199 |
+
"""A fast BFS node generator"""
|
200 |
+
adj = G._adj
|
201 |
+
n = len(adj)
|
202 |
+
seen = {source}
|
203 |
+
nextlevel = [source]
|
204 |
+
while nextlevel:
|
205 |
+
thislevel = nextlevel
|
206 |
+
nextlevel = []
|
207 |
+
for v in thislevel:
|
208 |
+
for w in adj[v]:
|
209 |
+
if w not in seen:
|
210 |
+
seen.add(w)
|
211 |
+
nextlevel.append(w)
|
212 |
+
if len(seen) == n:
|
213 |
+
return seen
|
214 |
+
return seen
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/semiconnected.py
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Semiconnectedness."""
|
2 |
+
import networkx as nx
|
3 |
+
from networkx.utils import not_implemented_for, pairwise
|
4 |
+
|
5 |
+
__all__ = ["is_semiconnected"]
|
6 |
+
|
7 |
+
|
8 |
+
@not_implemented_for("undirected")
|
9 |
+
@nx._dispatchable
|
10 |
+
def is_semiconnected(G):
|
11 |
+
r"""Returns True if the graph is semiconnected, False otherwise.
|
12 |
+
|
13 |
+
A graph is semiconnected if and only if for any pair of nodes, either one
|
14 |
+
is reachable from the other, or they are mutually reachable.
|
15 |
+
|
16 |
+
This function uses a theorem that states that a DAG is semiconnected
|
17 |
+
if for any topological sort, for node $v_n$ in that sort, there is an
|
18 |
+
edge $(v_i, v_{i+1})$. That allows us to check if a non-DAG `G` is
|
19 |
+
semiconnected by condensing the graph: i.e. constructing a new graph `H`
|
20 |
+
with nodes being the strongly connected components of `G`, and edges
|
21 |
+
(scc_1, scc_2) if there is a edge $(v_1, v_2)$ in `G` for some
|
22 |
+
$v_1 \in scc_1$ and $v_2 \in scc_2$. That results in a DAG, so we compute
|
23 |
+
the topological sort of `H` and check if for every $n$ there is an edge
|
24 |
+
$(scc_n, scc_{n+1})$.
|
25 |
+
|
26 |
+
Parameters
|
27 |
+
----------
|
28 |
+
G : NetworkX graph
|
29 |
+
A directed graph.
|
30 |
+
|
31 |
+
Returns
|
32 |
+
-------
|
33 |
+
semiconnected : bool
|
34 |
+
True if the graph is semiconnected, False otherwise.
|
35 |
+
|
36 |
+
Raises
|
37 |
+
------
|
38 |
+
NetworkXNotImplemented
|
39 |
+
If the input graph is undirected.
|
40 |
+
|
41 |
+
NetworkXPointlessConcept
|
42 |
+
If the graph is empty.
|
43 |
+
|
44 |
+
Examples
|
45 |
+
--------
|
46 |
+
>>> G = nx.path_graph(4, create_using=nx.DiGraph())
|
47 |
+
>>> print(nx.is_semiconnected(G))
|
48 |
+
True
|
49 |
+
>>> G = nx.DiGraph([(1, 2), (3, 2)])
|
50 |
+
>>> print(nx.is_semiconnected(G))
|
51 |
+
False
|
52 |
+
|
53 |
+
See Also
|
54 |
+
--------
|
55 |
+
is_strongly_connected
|
56 |
+
is_weakly_connected
|
57 |
+
is_connected
|
58 |
+
is_biconnected
|
59 |
+
"""
|
60 |
+
if len(G) == 0:
|
61 |
+
raise nx.NetworkXPointlessConcept(
|
62 |
+
"Connectivity is undefined for the null graph."
|
63 |
+
)
|
64 |
+
|
65 |
+
if not nx.is_weakly_connected(G):
|
66 |
+
return False
|
67 |
+
|
68 |
+
H = nx.condensation(G)
|
69 |
+
|
70 |
+
return all(H.has_edge(u, v) for u, v in pairwise(nx.topological_sort(H)))
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/strongly_connected.py
ADDED
@@ -0,0 +1,430 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Strongly connected components."""
|
2 |
+
import networkx as nx
|
3 |
+
from networkx.utils.decorators import not_implemented_for
|
4 |
+
|
5 |
+
__all__ = [
|
6 |
+
"number_strongly_connected_components",
|
7 |
+
"strongly_connected_components",
|
8 |
+
"is_strongly_connected",
|
9 |
+
"strongly_connected_components_recursive",
|
10 |
+
"kosaraju_strongly_connected_components",
|
11 |
+
"condensation",
|
12 |
+
]
|
13 |
+
|
14 |
+
|
15 |
+
@not_implemented_for("undirected")
|
16 |
+
@nx._dispatchable
|
17 |
+
def strongly_connected_components(G):
|
18 |
+
"""Generate nodes in strongly connected components of graph.
|
19 |
+
|
20 |
+
Parameters
|
21 |
+
----------
|
22 |
+
G : NetworkX Graph
|
23 |
+
A directed graph.
|
24 |
+
|
25 |
+
Returns
|
26 |
+
-------
|
27 |
+
comp : generator of sets
|
28 |
+
A generator of sets of nodes, one for each strongly connected
|
29 |
+
component of G.
|
30 |
+
|
31 |
+
Raises
|
32 |
+
------
|
33 |
+
NetworkXNotImplemented
|
34 |
+
If G is undirected.
|
35 |
+
|
36 |
+
Examples
|
37 |
+
--------
|
38 |
+
Generate a sorted list of strongly connected components, largest first.
|
39 |
+
|
40 |
+
>>> G = nx.cycle_graph(4, create_using=nx.DiGraph())
|
41 |
+
>>> nx.add_cycle(G, [10, 11, 12])
|
42 |
+
>>> [len(c) for c in sorted(nx.strongly_connected_components(G), key=len, reverse=True)]
|
43 |
+
[4, 3]
|
44 |
+
|
45 |
+
If you only want the largest component, it's more efficient to
|
46 |
+
use max instead of sort.
|
47 |
+
|
48 |
+
>>> largest = max(nx.strongly_connected_components(G), key=len)
|
49 |
+
|
50 |
+
See Also
|
51 |
+
--------
|
52 |
+
connected_components
|
53 |
+
weakly_connected_components
|
54 |
+
kosaraju_strongly_connected_components
|
55 |
+
|
56 |
+
Notes
|
57 |
+
-----
|
58 |
+
Uses Tarjan's algorithm[1]_ with Nuutila's modifications[2]_.
|
59 |
+
Nonrecursive version of algorithm.
|
60 |
+
|
61 |
+
References
|
62 |
+
----------
|
63 |
+
.. [1] Depth-first search and linear graph algorithms, R. Tarjan
|
64 |
+
SIAM Journal of Computing 1(2):146-160, (1972).
|
65 |
+
|
66 |
+
.. [2] On finding the strongly connected components in a directed graph.
|
67 |
+
E. Nuutila and E. Soisalon-Soinen
|
68 |
+
Information Processing Letters 49(1): 9-14, (1994)..
|
69 |
+
|
70 |
+
"""
|
71 |
+
preorder = {}
|
72 |
+
lowlink = {}
|
73 |
+
scc_found = set()
|
74 |
+
scc_queue = []
|
75 |
+
i = 0 # Preorder counter
|
76 |
+
neighbors = {v: iter(G[v]) for v in G}
|
77 |
+
for source in G:
|
78 |
+
if source not in scc_found:
|
79 |
+
queue = [source]
|
80 |
+
while queue:
|
81 |
+
v = queue[-1]
|
82 |
+
if v not in preorder:
|
83 |
+
i = i + 1
|
84 |
+
preorder[v] = i
|
85 |
+
done = True
|
86 |
+
for w in neighbors[v]:
|
87 |
+
if w not in preorder:
|
88 |
+
queue.append(w)
|
89 |
+
done = False
|
90 |
+
break
|
91 |
+
if done:
|
92 |
+
lowlink[v] = preorder[v]
|
93 |
+
for w in G[v]:
|
94 |
+
if w not in scc_found:
|
95 |
+
if preorder[w] > preorder[v]:
|
96 |
+
lowlink[v] = min([lowlink[v], lowlink[w]])
|
97 |
+
else:
|
98 |
+
lowlink[v] = min([lowlink[v], preorder[w]])
|
99 |
+
queue.pop()
|
100 |
+
if lowlink[v] == preorder[v]:
|
101 |
+
scc = {v}
|
102 |
+
while scc_queue and preorder[scc_queue[-1]] > preorder[v]:
|
103 |
+
k = scc_queue.pop()
|
104 |
+
scc.add(k)
|
105 |
+
scc_found.update(scc)
|
106 |
+
yield scc
|
107 |
+
else:
|
108 |
+
scc_queue.append(v)
|
109 |
+
|
110 |
+
|
111 |
+
@not_implemented_for("undirected")
|
112 |
+
@nx._dispatchable
|
113 |
+
def kosaraju_strongly_connected_components(G, source=None):
|
114 |
+
"""Generate nodes in strongly connected components of graph.
|
115 |
+
|
116 |
+
Parameters
|
117 |
+
----------
|
118 |
+
G : NetworkX Graph
|
119 |
+
A directed graph.
|
120 |
+
|
121 |
+
Returns
|
122 |
+
-------
|
123 |
+
comp : generator of sets
|
124 |
+
A generator of sets of nodes, one for each strongly connected
|
125 |
+
component of G.
|
126 |
+
|
127 |
+
Raises
|
128 |
+
------
|
129 |
+
NetworkXNotImplemented
|
130 |
+
If G is undirected.
|
131 |
+
|
132 |
+
Examples
|
133 |
+
--------
|
134 |
+
Generate a sorted list of strongly connected components, largest first.
|
135 |
+
|
136 |
+
>>> G = nx.cycle_graph(4, create_using=nx.DiGraph())
|
137 |
+
>>> nx.add_cycle(G, [10, 11, 12])
|
138 |
+
>>> [
|
139 |
+
... len(c)
|
140 |
+
... for c in sorted(
|
141 |
+
... nx.kosaraju_strongly_connected_components(G), key=len, reverse=True
|
142 |
+
... )
|
143 |
+
... ]
|
144 |
+
[4, 3]
|
145 |
+
|
146 |
+
If you only want the largest component, it's more efficient to
|
147 |
+
use max instead of sort.
|
148 |
+
|
149 |
+
>>> largest = max(nx.kosaraju_strongly_connected_components(G), key=len)
|
150 |
+
|
151 |
+
See Also
|
152 |
+
--------
|
153 |
+
strongly_connected_components
|
154 |
+
|
155 |
+
Notes
|
156 |
+
-----
|
157 |
+
Uses Kosaraju's algorithm.
|
158 |
+
|
159 |
+
"""
|
160 |
+
post = list(nx.dfs_postorder_nodes(G.reverse(copy=False), source=source))
|
161 |
+
|
162 |
+
seen = set()
|
163 |
+
while post:
|
164 |
+
r = post.pop()
|
165 |
+
if r in seen:
|
166 |
+
continue
|
167 |
+
c = nx.dfs_preorder_nodes(G, r)
|
168 |
+
new = {v for v in c if v not in seen}
|
169 |
+
seen.update(new)
|
170 |
+
yield new
|
171 |
+
|
172 |
+
|
173 |
+
@not_implemented_for("undirected")
|
174 |
+
@nx._dispatchable
|
175 |
+
def strongly_connected_components_recursive(G):
|
176 |
+
"""Generate nodes in strongly connected components of graph.
|
177 |
+
|
178 |
+
.. deprecated:: 3.2
|
179 |
+
|
180 |
+
This function is deprecated and will be removed in a future version of
|
181 |
+
NetworkX. Use `strongly_connected_components` instead.
|
182 |
+
|
183 |
+
Recursive version of algorithm.
|
184 |
+
|
185 |
+
Parameters
|
186 |
+
----------
|
187 |
+
G : NetworkX Graph
|
188 |
+
A directed graph.
|
189 |
+
|
190 |
+
Returns
|
191 |
+
-------
|
192 |
+
comp : generator of sets
|
193 |
+
A generator of sets of nodes, one for each strongly connected
|
194 |
+
component of G.
|
195 |
+
|
196 |
+
Raises
|
197 |
+
------
|
198 |
+
NetworkXNotImplemented
|
199 |
+
If G is undirected.
|
200 |
+
|
201 |
+
Examples
|
202 |
+
--------
|
203 |
+
Generate a sorted list of strongly connected components, largest first.
|
204 |
+
|
205 |
+
>>> G = nx.cycle_graph(4, create_using=nx.DiGraph())
|
206 |
+
>>> nx.add_cycle(G, [10, 11, 12])
|
207 |
+
>>> [
|
208 |
+
... len(c)
|
209 |
+
... for c in sorted(
|
210 |
+
... nx.strongly_connected_components_recursive(G), key=len, reverse=True
|
211 |
+
... )
|
212 |
+
... ]
|
213 |
+
[4, 3]
|
214 |
+
|
215 |
+
If you only want the largest component, it's more efficient to
|
216 |
+
use max instead of sort.
|
217 |
+
|
218 |
+
>>> largest = max(nx.strongly_connected_components_recursive(G), key=len)
|
219 |
+
|
220 |
+
To create the induced subgraph of the components use:
|
221 |
+
>>> S = [G.subgraph(c).copy() for c in nx.weakly_connected_components(G)]
|
222 |
+
|
223 |
+
See Also
|
224 |
+
--------
|
225 |
+
connected_components
|
226 |
+
|
227 |
+
Notes
|
228 |
+
-----
|
229 |
+
Uses Tarjan's algorithm[1]_ with Nuutila's modifications[2]_.
|
230 |
+
|
231 |
+
References
|
232 |
+
----------
|
233 |
+
.. [1] Depth-first search and linear graph algorithms, R. Tarjan
|
234 |
+
SIAM Journal of Computing 1(2):146-160, (1972).
|
235 |
+
|
236 |
+
.. [2] On finding the strongly connected components in a directed graph.
|
237 |
+
E. Nuutila and E. Soisalon-Soinen
|
238 |
+
Information Processing Letters 49(1): 9-14, (1994)..
|
239 |
+
|
240 |
+
"""
|
241 |
+
import warnings
|
242 |
+
|
243 |
+
warnings.warn(
|
244 |
+
(
|
245 |
+
"\n\nstrongly_connected_components_recursive is deprecated and will be\n"
|
246 |
+
"removed in the future. Use strongly_connected_components instead."
|
247 |
+
),
|
248 |
+
category=DeprecationWarning,
|
249 |
+
stacklevel=2,
|
250 |
+
)
|
251 |
+
|
252 |
+
yield from strongly_connected_components(G)
|
253 |
+
|
254 |
+
|
255 |
+
@not_implemented_for("undirected")
|
256 |
+
@nx._dispatchable
|
257 |
+
def number_strongly_connected_components(G):
|
258 |
+
"""Returns number of strongly connected components in graph.
|
259 |
+
|
260 |
+
Parameters
|
261 |
+
----------
|
262 |
+
G : NetworkX graph
|
263 |
+
A directed graph.
|
264 |
+
|
265 |
+
Returns
|
266 |
+
-------
|
267 |
+
n : integer
|
268 |
+
Number of strongly connected components
|
269 |
+
|
270 |
+
Raises
|
271 |
+
------
|
272 |
+
NetworkXNotImplemented
|
273 |
+
If G is undirected.
|
274 |
+
|
275 |
+
Examples
|
276 |
+
--------
|
277 |
+
>>> G = nx.DiGraph(
|
278 |
+
... [(0, 1), (1, 2), (2, 0), (2, 3), (4, 5), (3, 4), (5, 6), (6, 3), (6, 7)]
|
279 |
+
... )
|
280 |
+
>>> nx.number_strongly_connected_components(G)
|
281 |
+
3
|
282 |
+
|
283 |
+
See Also
|
284 |
+
--------
|
285 |
+
strongly_connected_components
|
286 |
+
number_connected_components
|
287 |
+
number_weakly_connected_components
|
288 |
+
|
289 |
+
Notes
|
290 |
+
-----
|
291 |
+
For directed graphs only.
|
292 |
+
"""
|
293 |
+
return sum(1 for scc in strongly_connected_components(G))
|
294 |
+
|
295 |
+
|
296 |
+
@not_implemented_for("undirected")
|
297 |
+
@nx._dispatchable
|
298 |
+
def is_strongly_connected(G):
|
299 |
+
"""Test directed graph for strong connectivity.
|
300 |
+
|
301 |
+
A directed graph is strongly connected if and only if every vertex in
|
302 |
+
the graph is reachable from every other vertex.
|
303 |
+
|
304 |
+
Parameters
|
305 |
+
----------
|
306 |
+
G : NetworkX Graph
|
307 |
+
A directed graph.
|
308 |
+
|
309 |
+
Returns
|
310 |
+
-------
|
311 |
+
connected : bool
|
312 |
+
True if the graph is strongly connected, False otherwise.
|
313 |
+
|
314 |
+
Examples
|
315 |
+
--------
|
316 |
+
>>> G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 0), (2, 4), (4, 2)])
|
317 |
+
>>> nx.is_strongly_connected(G)
|
318 |
+
True
|
319 |
+
>>> G.remove_edge(2, 3)
|
320 |
+
>>> nx.is_strongly_connected(G)
|
321 |
+
False
|
322 |
+
|
323 |
+
Raises
|
324 |
+
------
|
325 |
+
NetworkXNotImplemented
|
326 |
+
If G is undirected.
|
327 |
+
|
328 |
+
See Also
|
329 |
+
--------
|
330 |
+
is_weakly_connected
|
331 |
+
is_semiconnected
|
332 |
+
is_connected
|
333 |
+
is_biconnected
|
334 |
+
strongly_connected_components
|
335 |
+
|
336 |
+
Notes
|
337 |
+
-----
|
338 |
+
For directed graphs only.
|
339 |
+
"""
|
340 |
+
if len(G) == 0:
|
341 |
+
raise nx.NetworkXPointlessConcept(
|
342 |
+
"""Connectivity is undefined for the null graph."""
|
343 |
+
)
|
344 |
+
|
345 |
+
return len(next(strongly_connected_components(G))) == len(G)
|
346 |
+
|
347 |
+
|
348 |
+
@not_implemented_for("undirected")
|
349 |
+
@nx._dispatchable(returns_graph=True)
|
350 |
+
def condensation(G, scc=None):
|
351 |
+
"""Returns the condensation of G.
|
352 |
+
|
353 |
+
The condensation of G is the graph with each of the strongly connected
|
354 |
+
components contracted into a single node.
|
355 |
+
|
356 |
+
Parameters
|
357 |
+
----------
|
358 |
+
G : NetworkX DiGraph
|
359 |
+
A directed graph.
|
360 |
+
|
361 |
+
scc: list or generator (optional, default=None)
|
362 |
+
Strongly connected components. If provided, the elements in
|
363 |
+
`scc` must partition the nodes in `G`. If not provided, it will be
|
364 |
+
calculated as scc=nx.strongly_connected_components(G).
|
365 |
+
|
366 |
+
Returns
|
367 |
+
-------
|
368 |
+
C : NetworkX DiGraph
|
369 |
+
The condensation graph C of G. The node labels are integers
|
370 |
+
corresponding to the index of the component in the list of
|
371 |
+
strongly connected components of G. C has a graph attribute named
|
372 |
+
'mapping' with a dictionary mapping the original nodes to the
|
373 |
+
nodes in C to which they belong. Each node in C also has a node
|
374 |
+
attribute 'members' with the set of original nodes in G that
|
375 |
+
form the SCC that the node in C represents.
|
376 |
+
|
377 |
+
Raises
|
378 |
+
------
|
379 |
+
NetworkXNotImplemented
|
380 |
+
If G is undirected.
|
381 |
+
|
382 |
+
Examples
|
383 |
+
--------
|
384 |
+
Contracting two sets of strongly connected nodes into two distinct SCC
|
385 |
+
using the barbell graph.
|
386 |
+
|
387 |
+
>>> G = nx.barbell_graph(4, 0)
|
388 |
+
>>> G.remove_edge(3, 4)
|
389 |
+
>>> G = nx.DiGraph(G)
|
390 |
+
>>> H = nx.condensation(G)
|
391 |
+
>>> H.nodes.data()
|
392 |
+
NodeDataView({0: {'members': {0, 1, 2, 3}}, 1: {'members': {4, 5, 6, 7}}})
|
393 |
+
>>> H.graph["mapping"]
|
394 |
+
{0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1}
|
395 |
+
|
396 |
+
Contracting a complete graph into one single SCC.
|
397 |
+
|
398 |
+
>>> G = nx.complete_graph(7, create_using=nx.DiGraph)
|
399 |
+
>>> H = nx.condensation(G)
|
400 |
+
>>> H.nodes
|
401 |
+
NodeView((0,))
|
402 |
+
>>> H.nodes.data()
|
403 |
+
NodeDataView({0: {'members': {0, 1, 2, 3, 4, 5, 6}}})
|
404 |
+
|
405 |
+
Notes
|
406 |
+
-----
|
407 |
+
After contracting all strongly connected components to a single node,
|
408 |
+
the resulting graph is a directed acyclic graph.
|
409 |
+
|
410 |
+
"""
|
411 |
+
if scc is None:
|
412 |
+
scc = nx.strongly_connected_components(G)
|
413 |
+
mapping = {}
|
414 |
+
members = {}
|
415 |
+
C = nx.DiGraph()
|
416 |
+
# Add mapping dict as graph attribute
|
417 |
+
C.graph["mapping"] = mapping
|
418 |
+
if len(G) == 0:
|
419 |
+
return C
|
420 |
+
for i, component in enumerate(scc):
|
421 |
+
members[i] = component
|
422 |
+
mapping.update((n, i) for n in component)
|
423 |
+
number_of_components = i + 1
|
424 |
+
C.add_nodes_from(range(number_of_components))
|
425 |
+
C.add_edges_from(
|
426 |
+
(mapping[u], mapping[v]) for u, v in G.edges() if mapping[u] != mapping[v]
|
427 |
+
)
|
428 |
+
# Add a list of members (ie original nodes) to each node (ie scc) in C.
|
429 |
+
nx.set_node_attributes(C, members, "members")
|
430 |
+
return C
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (204 Bytes). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_attracting.cpython-310.pyc
ADDED
Binary file (2.76 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_biconnected.cpython-310.pyc
ADDED
Binary file (6.72 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_connected.cpython-310.pyc
ADDED
Binary file (4.8 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_semiconnected.cpython-310.pyc
ADDED
Binary file (3.01 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_strongly_connected.cpython-310.pyc
ADDED
Binary file (7.21 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/__pycache__/test_weakly_connected.cpython-310.pyc
ADDED
Binary file (4 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_attracting.py
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx import NetworkXNotImplemented
|
5 |
+
|
6 |
+
|
7 |
+
class TestAttractingComponents:
|
8 |
+
@classmethod
|
9 |
+
def setup_class(cls):
|
10 |
+
cls.G1 = nx.DiGraph()
|
11 |
+
cls.G1.add_edges_from(
|
12 |
+
[
|
13 |
+
(5, 11),
|
14 |
+
(11, 2),
|
15 |
+
(11, 9),
|
16 |
+
(11, 10),
|
17 |
+
(7, 11),
|
18 |
+
(7, 8),
|
19 |
+
(8, 9),
|
20 |
+
(3, 8),
|
21 |
+
(3, 10),
|
22 |
+
]
|
23 |
+
)
|
24 |
+
cls.G2 = nx.DiGraph()
|
25 |
+
cls.G2.add_edges_from([(0, 1), (0, 2), (1, 1), (1, 2), (2, 1)])
|
26 |
+
|
27 |
+
cls.G3 = nx.DiGraph()
|
28 |
+
cls.G3.add_edges_from([(0, 1), (1, 2), (2, 1), (0, 3), (3, 4), (4, 3)])
|
29 |
+
|
30 |
+
cls.G4 = nx.DiGraph()
|
31 |
+
|
32 |
+
def test_attracting_components(self):
|
33 |
+
ac = list(nx.attracting_components(self.G1))
|
34 |
+
assert {2} in ac
|
35 |
+
assert {9} in ac
|
36 |
+
assert {10} in ac
|
37 |
+
|
38 |
+
ac = list(nx.attracting_components(self.G2))
|
39 |
+
ac = [tuple(sorted(x)) for x in ac]
|
40 |
+
assert ac == [(1, 2)]
|
41 |
+
|
42 |
+
ac = list(nx.attracting_components(self.G3))
|
43 |
+
ac = [tuple(sorted(x)) for x in ac]
|
44 |
+
assert (1, 2) in ac
|
45 |
+
assert (3, 4) in ac
|
46 |
+
assert len(ac) == 2
|
47 |
+
|
48 |
+
ac = list(nx.attracting_components(self.G4))
|
49 |
+
assert ac == []
|
50 |
+
|
51 |
+
def test_number_attacting_components(self):
|
52 |
+
assert nx.number_attracting_components(self.G1) == 3
|
53 |
+
assert nx.number_attracting_components(self.G2) == 1
|
54 |
+
assert nx.number_attracting_components(self.G3) == 2
|
55 |
+
assert nx.number_attracting_components(self.G4) == 0
|
56 |
+
|
57 |
+
def test_is_attracting_component(self):
|
58 |
+
assert not nx.is_attracting_component(self.G1)
|
59 |
+
assert not nx.is_attracting_component(self.G2)
|
60 |
+
assert not nx.is_attracting_component(self.G3)
|
61 |
+
g2 = self.G3.subgraph([1, 2])
|
62 |
+
assert nx.is_attracting_component(g2)
|
63 |
+
assert not nx.is_attracting_component(self.G4)
|
64 |
+
|
65 |
+
def test_connected_raise(self):
|
66 |
+
G = nx.Graph()
|
67 |
+
with pytest.raises(NetworkXNotImplemented):
|
68 |
+
next(nx.attracting_components(G))
|
69 |
+
pytest.raises(NetworkXNotImplemented, nx.number_attracting_components, G)
|
70 |
+
pytest.raises(NetworkXNotImplemented, nx.is_attracting_component, G)
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_biconnected.py
ADDED
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx import NetworkXNotImplemented
|
5 |
+
|
6 |
+
|
7 |
+
def assert_components_edges_equal(x, y):
|
8 |
+
sx = {frozenset(frozenset(e) for e in c) for c in x}
|
9 |
+
sy = {frozenset(frozenset(e) for e in c) for c in y}
|
10 |
+
assert sx == sy
|
11 |
+
|
12 |
+
|
13 |
+
def assert_components_equal(x, y):
|
14 |
+
sx = {frozenset(c) for c in x}
|
15 |
+
sy = {frozenset(c) for c in y}
|
16 |
+
assert sx == sy
|
17 |
+
|
18 |
+
|
19 |
+
def test_barbell():
|
20 |
+
G = nx.barbell_graph(8, 4)
|
21 |
+
nx.add_path(G, [7, 20, 21, 22])
|
22 |
+
nx.add_cycle(G, [22, 23, 24, 25])
|
23 |
+
pts = set(nx.articulation_points(G))
|
24 |
+
assert pts == {7, 8, 9, 10, 11, 12, 20, 21, 22}
|
25 |
+
|
26 |
+
answer = [
|
27 |
+
{12, 13, 14, 15, 16, 17, 18, 19},
|
28 |
+
{0, 1, 2, 3, 4, 5, 6, 7},
|
29 |
+
{22, 23, 24, 25},
|
30 |
+
{11, 12},
|
31 |
+
{10, 11},
|
32 |
+
{9, 10},
|
33 |
+
{8, 9},
|
34 |
+
{7, 8},
|
35 |
+
{21, 22},
|
36 |
+
{20, 21},
|
37 |
+
{7, 20},
|
38 |
+
]
|
39 |
+
assert_components_equal(list(nx.biconnected_components(G)), answer)
|
40 |
+
|
41 |
+
G.add_edge(2, 17)
|
42 |
+
pts = set(nx.articulation_points(G))
|
43 |
+
assert pts == {7, 20, 21, 22}
|
44 |
+
|
45 |
+
|
46 |
+
def test_articulation_points_repetitions():
|
47 |
+
G = nx.Graph()
|
48 |
+
G.add_edges_from([(0, 1), (1, 2), (1, 3)])
|
49 |
+
assert list(nx.articulation_points(G)) == [1]
|
50 |
+
|
51 |
+
|
52 |
+
def test_articulation_points_cycle():
|
53 |
+
G = nx.cycle_graph(3)
|
54 |
+
nx.add_cycle(G, [1, 3, 4])
|
55 |
+
pts = set(nx.articulation_points(G))
|
56 |
+
assert pts == {1}
|
57 |
+
|
58 |
+
|
59 |
+
def test_is_biconnected():
|
60 |
+
G = nx.cycle_graph(3)
|
61 |
+
assert nx.is_biconnected(G)
|
62 |
+
nx.add_cycle(G, [1, 3, 4])
|
63 |
+
assert not nx.is_biconnected(G)
|
64 |
+
|
65 |
+
|
66 |
+
def test_empty_is_biconnected():
|
67 |
+
G = nx.empty_graph(5)
|
68 |
+
assert not nx.is_biconnected(G)
|
69 |
+
G.add_edge(0, 1)
|
70 |
+
assert not nx.is_biconnected(G)
|
71 |
+
|
72 |
+
|
73 |
+
def test_biconnected_components_cycle():
|
74 |
+
G = nx.cycle_graph(3)
|
75 |
+
nx.add_cycle(G, [1, 3, 4])
|
76 |
+
answer = [{0, 1, 2}, {1, 3, 4}]
|
77 |
+
assert_components_equal(list(nx.biconnected_components(G)), answer)
|
78 |
+
|
79 |
+
|
80 |
+
def test_biconnected_components1():
|
81 |
+
# graph example from
|
82 |
+
# https://web.archive.org/web/20121229123447/http://www.ibluemojo.com/school/articul_algorithm.html
|
83 |
+
edges = [
|
84 |
+
(0, 1),
|
85 |
+
(0, 5),
|
86 |
+
(0, 6),
|
87 |
+
(0, 14),
|
88 |
+
(1, 5),
|
89 |
+
(1, 6),
|
90 |
+
(1, 14),
|
91 |
+
(2, 4),
|
92 |
+
(2, 10),
|
93 |
+
(3, 4),
|
94 |
+
(3, 15),
|
95 |
+
(4, 6),
|
96 |
+
(4, 7),
|
97 |
+
(4, 10),
|
98 |
+
(5, 14),
|
99 |
+
(6, 14),
|
100 |
+
(7, 9),
|
101 |
+
(8, 9),
|
102 |
+
(8, 12),
|
103 |
+
(8, 13),
|
104 |
+
(10, 15),
|
105 |
+
(11, 12),
|
106 |
+
(11, 13),
|
107 |
+
(12, 13),
|
108 |
+
]
|
109 |
+
G = nx.Graph(edges)
|
110 |
+
pts = set(nx.articulation_points(G))
|
111 |
+
assert pts == {4, 6, 7, 8, 9}
|
112 |
+
comps = list(nx.biconnected_component_edges(G))
|
113 |
+
answer = [
|
114 |
+
[(3, 4), (15, 3), (10, 15), (10, 4), (2, 10), (4, 2)],
|
115 |
+
[(13, 12), (13, 8), (11, 13), (12, 11), (8, 12)],
|
116 |
+
[(9, 8)],
|
117 |
+
[(7, 9)],
|
118 |
+
[(4, 7)],
|
119 |
+
[(6, 4)],
|
120 |
+
[(14, 0), (5, 1), (5, 0), (14, 5), (14, 1), (6, 14), (6, 0), (1, 6), (0, 1)],
|
121 |
+
]
|
122 |
+
assert_components_edges_equal(comps, answer)
|
123 |
+
|
124 |
+
|
125 |
+
def test_biconnected_components2():
|
126 |
+
G = nx.Graph()
|
127 |
+
nx.add_cycle(G, "ABC")
|
128 |
+
nx.add_cycle(G, "CDE")
|
129 |
+
nx.add_cycle(G, "FIJHG")
|
130 |
+
nx.add_cycle(G, "GIJ")
|
131 |
+
G.add_edge("E", "G")
|
132 |
+
comps = list(nx.biconnected_component_edges(G))
|
133 |
+
answer = [
|
134 |
+
[
|
135 |
+
tuple("GF"),
|
136 |
+
tuple("FI"),
|
137 |
+
tuple("IG"),
|
138 |
+
tuple("IJ"),
|
139 |
+
tuple("JG"),
|
140 |
+
tuple("JH"),
|
141 |
+
tuple("HG"),
|
142 |
+
],
|
143 |
+
[tuple("EG")],
|
144 |
+
[tuple("CD"), tuple("DE"), tuple("CE")],
|
145 |
+
[tuple("AB"), tuple("BC"), tuple("AC")],
|
146 |
+
]
|
147 |
+
assert_components_edges_equal(comps, answer)
|
148 |
+
|
149 |
+
|
150 |
+
def test_biconnected_davis():
|
151 |
+
D = nx.davis_southern_women_graph()
|
152 |
+
bcc = list(nx.biconnected_components(D))[0]
|
153 |
+
assert set(D) == bcc # All nodes in a giant bicomponent
|
154 |
+
# So no articulation points
|
155 |
+
assert len(list(nx.articulation_points(D))) == 0
|
156 |
+
|
157 |
+
|
158 |
+
def test_biconnected_karate():
|
159 |
+
K = nx.karate_club_graph()
|
160 |
+
answer = [
|
161 |
+
{
|
162 |
+
0,
|
163 |
+
1,
|
164 |
+
2,
|
165 |
+
3,
|
166 |
+
7,
|
167 |
+
8,
|
168 |
+
9,
|
169 |
+
12,
|
170 |
+
13,
|
171 |
+
14,
|
172 |
+
15,
|
173 |
+
17,
|
174 |
+
18,
|
175 |
+
19,
|
176 |
+
20,
|
177 |
+
21,
|
178 |
+
22,
|
179 |
+
23,
|
180 |
+
24,
|
181 |
+
25,
|
182 |
+
26,
|
183 |
+
27,
|
184 |
+
28,
|
185 |
+
29,
|
186 |
+
30,
|
187 |
+
31,
|
188 |
+
32,
|
189 |
+
33,
|
190 |
+
},
|
191 |
+
{0, 4, 5, 6, 10, 16},
|
192 |
+
{0, 11},
|
193 |
+
]
|
194 |
+
bcc = list(nx.biconnected_components(K))
|
195 |
+
assert_components_equal(bcc, answer)
|
196 |
+
assert set(nx.articulation_points(K)) == {0}
|
197 |
+
|
198 |
+
|
199 |
+
def test_biconnected_eppstein():
|
200 |
+
# tests from http://www.ics.uci.edu/~eppstein/PADS/Biconnectivity.py
|
201 |
+
G1 = nx.Graph(
|
202 |
+
{
|
203 |
+
0: [1, 2, 5],
|
204 |
+
1: [0, 5],
|
205 |
+
2: [0, 3, 4],
|
206 |
+
3: [2, 4, 5, 6],
|
207 |
+
4: [2, 3, 5, 6],
|
208 |
+
5: [0, 1, 3, 4],
|
209 |
+
6: [3, 4],
|
210 |
+
}
|
211 |
+
)
|
212 |
+
G2 = nx.Graph(
|
213 |
+
{
|
214 |
+
0: [2, 5],
|
215 |
+
1: [3, 8],
|
216 |
+
2: [0, 3, 5],
|
217 |
+
3: [1, 2, 6, 8],
|
218 |
+
4: [7],
|
219 |
+
5: [0, 2],
|
220 |
+
6: [3, 8],
|
221 |
+
7: [4],
|
222 |
+
8: [1, 3, 6],
|
223 |
+
}
|
224 |
+
)
|
225 |
+
assert nx.is_biconnected(G1)
|
226 |
+
assert not nx.is_biconnected(G2)
|
227 |
+
answer_G2 = [{1, 3, 6, 8}, {0, 2, 5}, {2, 3}, {4, 7}]
|
228 |
+
bcc = list(nx.biconnected_components(G2))
|
229 |
+
assert_components_equal(bcc, answer_G2)
|
230 |
+
|
231 |
+
|
232 |
+
def test_null_graph():
|
233 |
+
G = nx.Graph()
|
234 |
+
assert not nx.is_biconnected(G)
|
235 |
+
assert list(nx.biconnected_components(G)) == []
|
236 |
+
assert list(nx.biconnected_component_edges(G)) == []
|
237 |
+
assert list(nx.articulation_points(G)) == []
|
238 |
+
|
239 |
+
|
240 |
+
def test_connected_raise():
|
241 |
+
DG = nx.DiGraph()
|
242 |
+
with pytest.raises(NetworkXNotImplemented):
|
243 |
+
next(nx.biconnected_components(DG))
|
244 |
+
with pytest.raises(NetworkXNotImplemented):
|
245 |
+
next(nx.biconnected_component_edges(DG))
|
246 |
+
with pytest.raises(NetworkXNotImplemented):
|
247 |
+
next(nx.articulation_points(DG))
|
248 |
+
pytest.raises(NetworkXNotImplemented, nx.is_biconnected, DG)
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_connected.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx import NetworkXNotImplemented
|
5 |
+
from networkx import convert_node_labels_to_integers as cnlti
|
6 |
+
from networkx.classes.tests import dispatch_interface
|
7 |
+
|
8 |
+
|
9 |
+
class TestConnected:
|
10 |
+
@classmethod
|
11 |
+
def setup_class(cls):
|
12 |
+
G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted")
|
13 |
+
G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted")
|
14 |
+
G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted")
|
15 |
+
cls.G = nx.union(G1, G2)
|
16 |
+
cls.G = nx.union(cls.G, G3)
|
17 |
+
cls.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
|
18 |
+
cls.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1)
|
19 |
+
|
20 |
+
cls.gc = []
|
21 |
+
G = nx.DiGraph()
|
22 |
+
G.add_edges_from(
|
23 |
+
[
|
24 |
+
(1, 2),
|
25 |
+
(2, 3),
|
26 |
+
(2, 8),
|
27 |
+
(3, 4),
|
28 |
+
(3, 7),
|
29 |
+
(4, 5),
|
30 |
+
(5, 3),
|
31 |
+
(5, 6),
|
32 |
+
(7, 4),
|
33 |
+
(7, 6),
|
34 |
+
(8, 1),
|
35 |
+
(8, 7),
|
36 |
+
]
|
37 |
+
)
|
38 |
+
C = [[3, 4, 5, 7], [1, 2, 8], [6]]
|
39 |
+
cls.gc.append((G, C))
|
40 |
+
|
41 |
+
G = nx.DiGraph()
|
42 |
+
G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
|
43 |
+
C = [[2, 3, 4], [1]]
|
44 |
+
cls.gc.append((G, C))
|
45 |
+
|
46 |
+
G = nx.DiGraph()
|
47 |
+
G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
|
48 |
+
C = [[1, 2, 3]]
|
49 |
+
cls.gc.append((G, C))
|
50 |
+
|
51 |
+
# Eppstein's tests
|
52 |
+
G = nx.DiGraph({0: [1], 1: [2, 3], 2: [4, 5], 3: [4, 5], 4: [6], 5: [], 6: []})
|
53 |
+
C = [[0], [1], [2], [3], [4], [5], [6]]
|
54 |
+
cls.gc.append((G, C))
|
55 |
+
|
56 |
+
G = nx.DiGraph({0: [1], 1: [2, 3, 4], 2: [0, 3], 3: [4], 4: [3]})
|
57 |
+
C = [[0, 1, 2], [3, 4]]
|
58 |
+
cls.gc.append((G, C))
|
59 |
+
|
60 |
+
G = nx.DiGraph()
|
61 |
+
C = []
|
62 |
+
cls.gc.append((G, C))
|
63 |
+
|
64 |
+
# This additionally tests the @nx._dispatchable mechanism, treating
|
65 |
+
# nx.connected_components as if it were a re-implementation from another package
|
66 |
+
@pytest.mark.parametrize("wrapper", [lambda x: x, dispatch_interface.convert])
|
67 |
+
def test_connected_components(self, wrapper):
|
68 |
+
cc = nx.connected_components
|
69 |
+
G = wrapper(self.G)
|
70 |
+
C = {
|
71 |
+
frozenset([0, 1, 2, 3]),
|
72 |
+
frozenset([4, 5, 6, 7, 8, 9]),
|
73 |
+
frozenset([10, 11, 12, 13, 14]),
|
74 |
+
}
|
75 |
+
assert {frozenset(g) for g in cc(G)} == C
|
76 |
+
|
77 |
+
def test_number_connected_components(self):
|
78 |
+
ncc = nx.number_connected_components
|
79 |
+
assert ncc(self.G) == 3
|
80 |
+
|
81 |
+
def test_number_connected_components2(self):
|
82 |
+
ncc = nx.number_connected_components
|
83 |
+
assert ncc(self.grid) == 1
|
84 |
+
|
85 |
+
def test_connected_components2(self):
|
86 |
+
cc = nx.connected_components
|
87 |
+
G = self.grid
|
88 |
+
C = {frozenset([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])}
|
89 |
+
assert {frozenset(g) for g in cc(G)} == C
|
90 |
+
|
91 |
+
def test_node_connected_components(self):
|
92 |
+
ncc = nx.node_connected_component
|
93 |
+
G = self.grid
|
94 |
+
C = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
|
95 |
+
assert ncc(G, 1) == C
|
96 |
+
|
97 |
+
def test_is_connected(self):
|
98 |
+
assert nx.is_connected(self.grid)
|
99 |
+
G = nx.Graph()
|
100 |
+
G.add_nodes_from([1, 2])
|
101 |
+
assert not nx.is_connected(G)
|
102 |
+
|
103 |
+
def test_connected_raise(self):
|
104 |
+
with pytest.raises(NetworkXNotImplemented):
|
105 |
+
next(nx.connected_components(self.DG))
|
106 |
+
pytest.raises(NetworkXNotImplemented, nx.number_connected_components, self.DG)
|
107 |
+
pytest.raises(NetworkXNotImplemented, nx.node_connected_component, self.DG, 1)
|
108 |
+
pytest.raises(NetworkXNotImplemented, nx.is_connected, self.DG)
|
109 |
+
pytest.raises(nx.NetworkXPointlessConcept, nx.is_connected, nx.Graph())
|
110 |
+
|
111 |
+
def test_connected_mutability(self):
|
112 |
+
G = self.grid
|
113 |
+
seen = set()
|
114 |
+
for component in nx.connected_components(G):
|
115 |
+
assert len(seen & component) == 0
|
116 |
+
seen.update(component)
|
117 |
+
component.clear()
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_semiconnected.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import chain
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
|
7 |
+
|
8 |
+
class TestIsSemiconnected:
|
9 |
+
def test_undirected(self):
|
10 |
+
pytest.raises(nx.NetworkXNotImplemented, nx.is_semiconnected, nx.Graph())
|
11 |
+
pytest.raises(nx.NetworkXNotImplemented, nx.is_semiconnected, nx.MultiGraph())
|
12 |
+
|
13 |
+
def test_empty(self):
|
14 |
+
pytest.raises(nx.NetworkXPointlessConcept, nx.is_semiconnected, nx.DiGraph())
|
15 |
+
pytest.raises(
|
16 |
+
nx.NetworkXPointlessConcept, nx.is_semiconnected, nx.MultiDiGraph()
|
17 |
+
)
|
18 |
+
|
19 |
+
def test_single_node_graph(self):
|
20 |
+
G = nx.DiGraph()
|
21 |
+
G.add_node(0)
|
22 |
+
assert nx.is_semiconnected(G)
|
23 |
+
|
24 |
+
def test_path(self):
|
25 |
+
G = nx.path_graph(100, create_using=nx.DiGraph())
|
26 |
+
assert nx.is_semiconnected(G)
|
27 |
+
G.add_edge(100, 99)
|
28 |
+
assert not nx.is_semiconnected(G)
|
29 |
+
|
30 |
+
def test_cycle(self):
|
31 |
+
G = nx.cycle_graph(100, create_using=nx.DiGraph())
|
32 |
+
assert nx.is_semiconnected(G)
|
33 |
+
G = nx.path_graph(100, create_using=nx.DiGraph())
|
34 |
+
G.add_edge(0, 99)
|
35 |
+
assert nx.is_semiconnected(G)
|
36 |
+
|
37 |
+
def test_tree(self):
|
38 |
+
G = nx.DiGraph()
|
39 |
+
G.add_edges_from(
|
40 |
+
chain.from_iterable([(i, 2 * i + 1), (i, 2 * i + 2)] for i in range(100))
|
41 |
+
)
|
42 |
+
assert not nx.is_semiconnected(G)
|
43 |
+
|
44 |
+
def test_dumbbell(self):
|
45 |
+
G = nx.cycle_graph(100, create_using=nx.DiGraph())
|
46 |
+
G.add_edges_from((i + 100, (i + 1) % 100 + 100) for i in range(100))
|
47 |
+
assert not nx.is_semiconnected(G) # G is disconnected.
|
48 |
+
G.add_edge(100, 99)
|
49 |
+
assert nx.is_semiconnected(G)
|
50 |
+
|
51 |
+
def test_alternating_path(self):
|
52 |
+
G = nx.DiGraph(
|
53 |
+
chain.from_iterable([(i, i - 1), (i, i + 1)] for i in range(0, 100, 2))
|
54 |
+
)
|
55 |
+
assert not nx.is_semiconnected(G)
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_strongly_connected.py
ADDED
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx import NetworkXNotImplemented
|
5 |
+
|
6 |
+
|
7 |
+
class TestStronglyConnected:
|
8 |
+
@classmethod
|
9 |
+
def setup_class(cls):
|
10 |
+
cls.gc = []
|
11 |
+
G = nx.DiGraph()
|
12 |
+
G.add_edges_from(
|
13 |
+
[
|
14 |
+
(1, 2),
|
15 |
+
(2, 3),
|
16 |
+
(2, 8),
|
17 |
+
(3, 4),
|
18 |
+
(3, 7),
|
19 |
+
(4, 5),
|
20 |
+
(5, 3),
|
21 |
+
(5, 6),
|
22 |
+
(7, 4),
|
23 |
+
(7, 6),
|
24 |
+
(8, 1),
|
25 |
+
(8, 7),
|
26 |
+
]
|
27 |
+
)
|
28 |
+
C = {frozenset([3, 4, 5, 7]), frozenset([1, 2, 8]), frozenset([6])}
|
29 |
+
cls.gc.append((G, C))
|
30 |
+
|
31 |
+
G = nx.DiGraph()
|
32 |
+
G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
|
33 |
+
C = {frozenset([2, 3, 4]), frozenset([1])}
|
34 |
+
cls.gc.append((G, C))
|
35 |
+
|
36 |
+
G = nx.DiGraph()
|
37 |
+
G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
|
38 |
+
C = {frozenset([1, 2, 3])}
|
39 |
+
cls.gc.append((G, C))
|
40 |
+
|
41 |
+
# Eppstein's tests
|
42 |
+
G = nx.DiGraph({0: [1], 1: [2, 3], 2: [4, 5], 3: [4, 5], 4: [6], 5: [], 6: []})
|
43 |
+
C = {
|
44 |
+
frozenset([0]),
|
45 |
+
frozenset([1]),
|
46 |
+
frozenset([2]),
|
47 |
+
frozenset([3]),
|
48 |
+
frozenset([4]),
|
49 |
+
frozenset([5]),
|
50 |
+
frozenset([6]),
|
51 |
+
}
|
52 |
+
cls.gc.append((G, C))
|
53 |
+
|
54 |
+
G = nx.DiGraph({0: [1], 1: [2, 3, 4], 2: [0, 3], 3: [4], 4: [3]})
|
55 |
+
C = {frozenset([0, 1, 2]), frozenset([3, 4])}
|
56 |
+
cls.gc.append((G, C))
|
57 |
+
|
58 |
+
def test_tarjan(self):
|
59 |
+
scc = nx.strongly_connected_components
|
60 |
+
for G, C in self.gc:
|
61 |
+
assert {frozenset(g) for g in scc(G)} == C
|
62 |
+
|
63 |
+
def test_tarjan_recursive(self):
|
64 |
+
scc = nx.strongly_connected_components_recursive
|
65 |
+
for G, C in self.gc:
|
66 |
+
with pytest.deprecated_call():
|
67 |
+
assert {frozenset(g) for g in scc(G)} == C
|
68 |
+
|
69 |
+
def test_kosaraju(self):
|
70 |
+
scc = nx.kosaraju_strongly_connected_components
|
71 |
+
for G, C in self.gc:
|
72 |
+
assert {frozenset(g) for g in scc(G)} == C
|
73 |
+
|
74 |
+
def test_number_strongly_connected_components(self):
|
75 |
+
ncc = nx.number_strongly_connected_components
|
76 |
+
for G, C in self.gc:
|
77 |
+
assert ncc(G) == len(C)
|
78 |
+
|
79 |
+
def test_is_strongly_connected(self):
|
80 |
+
for G, C in self.gc:
|
81 |
+
if len(C) == 1:
|
82 |
+
assert nx.is_strongly_connected(G)
|
83 |
+
else:
|
84 |
+
assert not nx.is_strongly_connected(G)
|
85 |
+
|
86 |
+
def test_contract_scc1(self):
|
87 |
+
G = nx.DiGraph()
|
88 |
+
G.add_edges_from(
|
89 |
+
[
|
90 |
+
(1, 2),
|
91 |
+
(2, 3),
|
92 |
+
(2, 11),
|
93 |
+
(2, 12),
|
94 |
+
(3, 4),
|
95 |
+
(4, 3),
|
96 |
+
(4, 5),
|
97 |
+
(5, 6),
|
98 |
+
(6, 5),
|
99 |
+
(6, 7),
|
100 |
+
(7, 8),
|
101 |
+
(7, 9),
|
102 |
+
(7, 10),
|
103 |
+
(8, 9),
|
104 |
+
(9, 7),
|
105 |
+
(10, 6),
|
106 |
+
(11, 2),
|
107 |
+
(11, 4),
|
108 |
+
(11, 6),
|
109 |
+
(12, 6),
|
110 |
+
(12, 11),
|
111 |
+
]
|
112 |
+
)
|
113 |
+
scc = list(nx.strongly_connected_components(G))
|
114 |
+
cG = nx.condensation(G, scc)
|
115 |
+
# DAG
|
116 |
+
assert nx.is_directed_acyclic_graph(cG)
|
117 |
+
# nodes
|
118 |
+
assert sorted(cG.nodes()) == [0, 1, 2, 3]
|
119 |
+
# edges
|
120 |
+
mapping = {}
|
121 |
+
for i, component in enumerate(scc):
|
122 |
+
for n in component:
|
123 |
+
mapping[n] = i
|
124 |
+
edge = (mapping[2], mapping[3])
|
125 |
+
assert cG.has_edge(*edge)
|
126 |
+
edge = (mapping[2], mapping[5])
|
127 |
+
assert cG.has_edge(*edge)
|
128 |
+
edge = (mapping[3], mapping[5])
|
129 |
+
assert cG.has_edge(*edge)
|
130 |
+
|
131 |
+
def test_contract_scc_isolate(self):
|
132 |
+
# Bug found and fixed in [1687].
|
133 |
+
G = nx.DiGraph()
|
134 |
+
G.add_edge(1, 2)
|
135 |
+
G.add_edge(2, 1)
|
136 |
+
scc = list(nx.strongly_connected_components(G))
|
137 |
+
cG = nx.condensation(G, scc)
|
138 |
+
assert list(cG.nodes()) == [0]
|
139 |
+
assert list(cG.edges()) == []
|
140 |
+
|
141 |
+
def test_contract_scc_edge(self):
|
142 |
+
G = nx.DiGraph()
|
143 |
+
G.add_edge(1, 2)
|
144 |
+
G.add_edge(2, 1)
|
145 |
+
G.add_edge(2, 3)
|
146 |
+
G.add_edge(3, 4)
|
147 |
+
G.add_edge(4, 3)
|
148 |
+
scc = list(nx.strongly_connected_components(G))
|
149 |
+
cG = nx.condensation(G, scc)
|
150 |
+
assert sorted(cG.nodes()) == [0, 1]
|
151 |
+
if 1 in scc[0]:
|
152 |
+
edge = (0, 1)
|
153 |
+
else:
|
154 |
+
edge = (1, 0)
|
155 |
+
assert list(cG.edges()) == [edge]
|
156 |
+
|
157 |
+
def test_condensation_mapping_and_members(self):
|
158 |
+
G, C = self.gc[1]
|
159 |
+
C = sorted(C, key=len, reverse=True)
|
160 |
+
cG = nx.condensation(G)
|
161 |
+
mapping = cG.graph["mapping"]
|
162 |
+
assert all(n in G for n in mapping)
|
163 |
+
assert all(0 == cN for n, cN in mapping.items() if n in C[0])
|
164 |
+
assert all(1 == cN for n, cN in mapping.items() if n in C[1])
|
165 |
+
for n, d in cG.nodes(data=True):
|
166 |
+
assert set(C[n]) == cG.nodes[n]["members"]
|
167 |
+
|
168 |
+
def test_null_graph(self):
|
169 |
+
G = nx.DiGraph()
|
170 |
+
assert list(nx.strongly_connected_components(G)) == []
|
171 |
+
assert list(nx.kosaraju_strongly_connected_components(G)) == []
|
172 |
+
with pytest.deprecated_call():
|
173 |
+
assert list(nx.strongly_connected_components_recursive(G)) == []
|
174 |
+
assert len(nx.condensation(G)) == 0
|
175 |
+
pytest.raises(
|
176 |
+
nx.NetworkXPointlessConcept, nx.is_strongly_connected, nx.DiGraph()
|
177 |
+
)
|
178 |
+
|
179 |
+
def test_connected_raise(self):
|
180 |
+
G = nx.Graph()
|
181 |
+
with pytest.raises(NetworkXNotImplemented):
|
182 |
+
next(nx.strongly_connected_components(G))
|
183 |
+
with pytest.raises(NetworkXNotImplemented):
|
184 |
+
next(nx.kosaraju_strongly_connected_components(G))
|
185 |
+
with pytest.raises(NetworkXNotImplemented):
|
186 |
+
next(nx.strongly_connected_components_recursive(G))
|
187 |
+
pytest.raises(NetworkXNotImplemented, nx.is_strongly_connected, G)
|
188 |
+
pytest.raises(NetworkXNotImplemented, nx.condensation, G)
|
189 |
+
|
190 |
+
strong_cc_methods = (
|
191 |
+
nx.strongly_connected_components,
|
192 |
+
nx.kosaraju_strongly_connected_components,
|
193 |
+
)
|
194 |
+
|
195 |
+
@pytest.mark.parametrize("get_components", strong_cc_methods)
|
196 |
+
def test_connected_mutability(self, get_components):
|
197 |
+
DG = nx.path_graph(5, create_using=nx.DiGraph)
|
198 |
+
G = nx.disjoint_union(DG, DG)
|
199 |
+
seen = set()
|
200 |
+
for component in get_components(G):
|
201 |
+
assert len(seen & component) == 0
|
202 |
+
seen.update(component)
|
203 |
+
component.clear()
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/tests/test_weakly_connected.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx import NetworkXNotImplemented
|
5 |
+
|
6 |
+
|
7 |
+
class TestWeaklyConnected:
|
8 |
+
@classmethod
|
9 |
+
def setup_class(cls):
|
10 |
+
cls.gc = []
|
11 |
+
G = nx.DiGraph()
|
12 |
+
G.add_edges_from(
|
13 |
+
[
|
14 |
+
(1, 2),
|
15 |
+
(2, 3),
|
16 |
+
(2, 8),
|
17 |
+
(3, 4),
|
18 |
+
(3, 7),
|
19 |
+
(4, 5),
|
20 |
+
(5, 3),
|
21 |
+
(5, 6),
|
22 |
+
(7, 4),
|
23 |
+
(7, 6),
|
24 |
+
(8, 1),
|
25 |
+
(8, 7),
|
26 |
+
]
|
27 |
+
)
|
28 |
+
C = [[3, 4, 5, 7], [1, 2, 8], [6]]
|
29 |
+
cls.gc.append((G, C))
|
30 |
+
|
31 |
+
G = nx.DiGraph()
|
32 |
+
G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
|
33 |
+
C = [[2, 3, 4], [1]]
|
34 |
+
cls.gc.append((G, C))
|
35 |
+
|
36 |
+
G = nx.DiGraph()
|
37 |
+
G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
|
38 |
+
C = [[1, 2, 3]]
|
39 |
+
cls.gc.append((G, C))
|
40 |
+
|
41 |
+
# Eppstein's tests
|
42 |
+
G = nx.DiGraph({0: [1], 1: [2, 3], 2: [4, 5], 3: [4, 5], 4: [6], 5: [], 6: []})
|
43 |
+
C = [[0], [1], [2], [3], [4], [5], [6]]
|
44 |
+
cls.gc.append((G, C))
|
45 |
+
|
46 |
+
G = nx.DiGraph({0: [1], 1: [2, 3, 4], 2: [0, 3], 3: [4], 4: [3]})
|
47 |
+
C = [[0, 1, 2], [3, 4]]
|
48 |
+
cls.gc.append((G, C))
|
49 |
+
|
50 |
+
def test_weakly_connected_components(self):
|
51 |
+
for G, C in self.gc:
|
52 |
+
U = G.to_undirected()
|
53 |
+
w = {frozenset(g) for g in nx.weakly_connected_components(G)}
|
54 |
+
c = {frozenset(g) for g in nx.connected_components(U)}
|
55 |
+
assert w == c
|
56 |
+
|
57 |
+
def test_number_weakly_connected_components(self):
|
58 |
+
for G, C in self.gc:
|
59 |
+
U = G.to_undirected()
|
60 |
+
w = nx.number_weakly_connected_components(G)
|
61 |
+
c = nx.number_connected_components(U)
|
62 |
+
assert w == c
|
63 |
+
|
64 |
+
def test_is_weakly_connected(self):
|
65 |
+
for G, C in self.gc:
|
66 |
+
U = G.to_undirected()
|
67 |
+
assert nx.is_weakly_connected(G) == nx.is_connected(U)
|
68 |
+
|
69 |
+
def test_null_graph(self):
|
70 |
+
G = nx.DiGraph()
|
71 |
+
assert list(nx.weakly_connected_components(G)) == []
|
72 |
+
assert nx.number_weakly_connected_components(G) == 0
|
73 |
+
with pytest.raises(nx.NetworkXPointlessConcept):
|
74 |
+
next(nx.is_weakly_connected(G))
|
75 |
+
|
76 |
+
def test_connected_raise(self):
|
77 |
+
G = nx.Graph()
|
78 |
+
with pytest.raises(NetworkXNotImplemented):
|
79 |
+
next(nx.weakly_connected_components(G))
|
80 |
+
pytest.raises(NetworkXNotImplemented, nx.number_weakly_connected_components, G)
|
81 |
+
pytest.raises(NetworkXNotImplemented, nx.is_weakly_connected, G)
|
82 |
+
|
83 |
+
def test_connected_mutability(self):
|
84 |
+
DG = nx.path_graph(5, create_using=nx.DiGraph)
|
85 |
+
G = nx.disjoint_union(DG, DG)
|
86 |
+
seen = set()
|
87 |
+
for component in nx.weakly_connected_components(G):
|
88 |
+
assert len(seen & component) == 0
|
89 |
+
seen.update(component)
|
90 |
+
component.clear()
|
91 |
+
|
92 |
+
|
93 |
+
def test_is_weakly_connected_empty_graph_raises():
|
94 |
+
G = nx.DiGraph()
|
95 |
+
with pytest.raises(nx.NetworkXPointlessConcept, match="Connectivity is undefined"):
|
96 |
+
nx.is_weakly_connected(G)
|
venv/lib/python3.10/site-packages/networkx/algorithms/components/weakly_connected.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Weakly connected components."""
|
2 |
+
import networkx as nx
|
3 |
+
from networkx.utils.decorators import not_implemented_for
|
4 |
+
|
5 |
+
__all__ = [
|
6 |
+
"number_weakly_connected_components",
|
7 |
+
"weakly_connected_components",
|
8 |
+
"is_weakly_connected",
|
9 |
+
]
|
10 |
+
|
11 |
+
|
12 |
+
@not_implemented_for("undirected")
|
13 |
+
@nx._dispatchable
|
14 |
+
def weakly_connected_components(G):
|
15 |
+
"""Generate weakly connected components of G.
|
16 |
+
|
17 |
+
Parameters
|
18 |
+
----------
|
19 |
+
G : NetworkX graph
|
20 |
+
A directed graph
|
21 |
+
|
22 |
+
Returns
|
23 |
+
-------
|
24 |
+
comp : generator of sets
|
25 |
+
A generator of sets of nodes, one for each weakly connected
|
26 |
+
component of G.
|
27 |
+
|
28 |
+
Raises
|
29 |
+
------
|
30 |
+
NetworkXNotImplemented
|
31 |
+
If G is undirected.
|
32 |
+
|
33 |
+
Examples
|
34 |
+
--------
|
35 |
+
Generate a sorted list of weakly connected components, largest first.
|
36 |
+
|
37 |
+
>>> G = nx.path_graph(4, create_using=nx.DiGraph())
|
38 |
+
>>> nx.add_path(G, [10, 11, 12])
|
39 |
+
>>> [len(c) for c in sorted(nx.weakly_connected_components(G), key=len, reverse=True)]
|
40 |
+
[4, 3]
|
41 |
+
|
42 |
+
If you only want the largest component, it's more efficient to
|
43 |
+
use max instead of sort:
|
44 |
+
|
45 |
+
>>> largest_cc = max(nx.weakly_connected_components(G), key=len)
|
46 |
+
|
47 |
+
See Also
|
48 |
+
--------
|
49 |
+
connected_components
|
50 |
+
strongly_connected_components
|
51 |
+
|
52 |
+
Notes
|
53 |
+
-----
|
54 |
+
For directed graphs only.
|
55 |
+
|
56 |
+
"""
|
57 |
+
seen = set()
|
58 |
+
for v in G:
|
59 |
+
if v not in seen:
|
60 |
+
c = set(_plain_bfs(G, v))
|
61 |
+
seen.update(c)
|
62 |
+
yield c
|
63 |
+
|
64 |
+
|
65 |
+
@not_implemented_for("undirected")
|
66 |
+
@nx._dispatchable
|
67 |
+
def number_weakly_connected_components(G):
|
68 |
+
"""Returns the number of weakly connected components in G.
|
69 |
+
|
70 |
+
Parameters
|
71 |
+
----------
|
72 |
+
G : NetworkX graph
|
73 |
+
A directed graph.
|
74 |
+
|
75 |
+
Returns
|
76 |
+
-------
|
77 |
+
n : integer
|
78 |
+
Number of weakly connected components
|
79 |
+
|
80 |
+
Raises
|
81 |
+
------
|
82 |
+
NetworkXNotImplemented
|
83 |
+
If G is undirected.
|
84 |
+
|
85 |
+
Examples
|
86 |
+
--------
|
87 |
+
>>> G = nx.DiGraph([(0, 1), (2, 1), (3, 4)])
|
88 |
+
>>> nx.number_weakly_connected_components(G)
|
89 |
+
2
|
90 |
+
|
91 |
+
See Also
|
92 |
+
--------
|
93 |
+
weakly_connected_components
|
94 |
+
number_connected_components
|
95 |
+
number_strongly_connected_components
|
96 |
+
|
97 |
+
Notes
|
98 |
+
-----
|
99 |
+
For directed graphs only.
|
100 |
+
|
101 |
+
"""
|
102 |
+
return sum(1 for wcc in weakly_connected_components(G))
|
103 |
+
|
104 |
+
|
105 |
+
@not_implemented_for("undirected")
|
106 |
+
@nx._dispatchable
|
107 |
+
def is_weakly_connected(G):
|
108 |
+
"""Test directed graph for weak connectivity.
|
109 |
+
|
110 |
+
A directed graph is weakly connected if and only if the graph
|
111 |
+
is connected when the direction of the edge between nodes is ignored.
|
112 |
+
|
113 |
+
Note that if a graph is strongly connected (i.e. the graph is connected
|
114 |
+
even when we account for directionality), it is by definition weakly
|
115 |
+
connected as well.
|
116 |
+
|
117 |
+
Parameters
|
118 |
+
----------
|
119 |
+
G : NetworkX Graph
|
120 |
+
A directed graph.
|
121 |
+
|
122 |
+
Returns
|
123 |
+
-------
|
124 |
+
connected : bool
|
125 |
+
True if the graph is weakly connected, False otherwise.
|
126 |
+
|
127 |
+
Raises
|
128 |
+
------
|
129 |
+
NetworkXNotImplemented
|
130 |
+
If G is undirected.
|
131 |
+
|
132 |
+
Examples
|
133 |
+
--------
|
134 |
+
>>> G = nx.DiGraph([(0, 1), (2, 1)])
|
135 |
+
>>> G.add_node(3)
|
136 |
+
>>> nx.is_weakly_connected(G) # node 3 is not connected to the graph
|
137 |
+
False
|
138 |
+
>>> G.add_edge(2, 3)
|
139 |
+
>>> nx.is_weakly_connected(G)
|
140 |
+
True
|
141 |
+
|
142 |
+
See Also
|
143 |
+
--------
|
144 |
+
is_strongly_connected
|
145 |
+
is_semiconnected
|
146 |
+
is_connected
|
147 |
+
is_biconnected
|
148 |
+
weakly_connected_components
|
149 |
+
|
150 |
+
Notes
|
151 |
+
-----
|
152 |
+
For directed graphs only.
|
153 |
+
|
154 |
+
"""
|
155 |
+
if len(G) == 0:
|
156 |
+
raise nx.NetworkXPointlessConcept(
|
157 |
+
"""Connectivity is undefined for the null graph."""
|
158 |
+
)
|
159 |
+
|
160 |
+
return len(next(weakly_connected_components(G))) == len(G)
|
161 |
+
|
162 |
+
|
163 |
+
def _plain_bfs(G, source):
|
164 |
+
"""A fast BFS node generator
|
165 |
+
|
166 |
+
The direction of the edge between nodes is ignored.
|
167 |
+
|
168 |
+
For directed graphs only.
|
169 |
+
|
170 |
+
"""
|
171 |
+
n = len(G)
|
172 |
+
Gsucc = G._succ
|
173 |
+
Gpred = G._pred
|
174 |
+
seen = {source}
|
175 |
+
nextlevel = [source]
|
176 |
+
|
177 |
+
yield source
|
178 |
+
while nextlevel:
|
179 |
+
thislevel = nextlevel
|
180 |
+
nextlevel = []
|
181 |
+
for v in thislevel:
|
182 |
+
for w in Gsucc[v]:
|
183 |
+
if w not in seen:
|
184 |
+
seen.add(w)
|
185 |
+
nextlevel.append(w)
|
186 |
+
yield w
|
187 |
+
for w in Gpred[v]:
|
188 |
+
if w not in seen:
|
189 |
+
seen.add(w)
|
190 |
+
nextlevel.append(w)
|
191 |
+
yield w
|
192 |
+
if len(seen) == n:
|
193 |
+
return
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__init__.py
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Connectivity and cut algorithms
|
2 |
+
"""
|
3 |
+
from .connectivity import *
|
4 |
+
from .cuts import *
|
5 |
+
from .edge_augmentation import *
|
6 |
+
from .edge_kcomponents import *
|
7 |
+
from .disjoint_paths import *
|
8 |
+
from .kcomponents import *
|
9 |
+
from .kcutsets import *
|
10 |
+
from .stoerwagner import *
|
11 |
+
from .utils import *
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (460 Bytes). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/connectivity.cpython-310.pyc
ADDED
Binary file (26.8 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/cuts.cpython-310.pyc
ADDED
Binary file (20.3 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/disjoint_paths.cpython-310.pyc
ADDED
Binary file (13.2 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_augmentation.cpython-310.pyc
ADDED
Binary file (37.9 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_kcomponents.cpython-310.pyc
ADDED
Binary file (18.1 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcomponents.cpython-310.pyc
ADDED
Binary file (7.93 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcutsets.cpython-310.pyc
ADDED
Binary file (6.32 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/stoerwagner.cpython-310.pyc
ADDED
Binary file (4.51 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (3.19 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/connectivity.py
ADDED
@@ -0,0 +1,816 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Flow based connectivity algorithms
|
3 |
+
"""
|
4 |
+
|
5 |
+
import itertools
|
6 |
+
from operator import itemgetter
|
7 |
+
|
8 |
+
import networkx as nx
|
9 |
+
|
10 |
+
# Define the default maximum flow function to use in all flow based
|
11 |
+
# connectivity algorithms.
|
12 |
+
from networkx.algorithms.flow import (
|
13 |
+
boykov_kolmogorov,
|
14 |
+
build_residual_network,
|
15 |
+
dinitz,
|
16 |
+
edmonds_karp,
|
17 |
+
shortest_augmenting_path,
|
18 |
+
)
|
19 |
+
|
20 |
+
default_flow_func = edmonds_karp
|
21 |
+
|
22 |
+
from .utils import build_auxiliary_edge_connectivity, build_auxiliary_node_connectivity
|
23 |
+
|
24 |
+
__all__ = [
|
25 |
+
"average_node_connectivity",
|
26 |
+
"local_node_connectivity",
|
27 |
+
"node_connectivity",
|
28 |
+
"local_edge_connectivity",
|
29 |
+
"edge_connectivity",
|
30 |
+
"all_pairs_node_connectivity",
|
31 |
+
]
|
32 |
+
|
33 |
+
|
34 |
+
@nx._dispatchable(graphs={"G": 0, "auxiliary?": 4}, preserve_graph_attrs={"auxiliary"})
|
35 |
+
def local_node_connectivity(
|
36 |
+
G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None
|
37 |
+
):
|
38 |
+
r"""Computes local node connectivity for nodes s and t.
|
39 |
+
|
40 |
+
Local node connectivity for two non adjacent nodes s and t is the
|
41 |
+
minimum number of nodes that must be removed (along with their incident
|
42 |
+
edges) to disconnect them.
|
43 |
+
|
44 |
+
This is a flow based implementation of node connectivity. We compute the
|
45 |
+
maximum flow on an auxiliary digraph build from the original input
|
46 |
+
graph (see below for details).
|
47 |
+
|
48 |
+
Parameters
|
49 |
+
----------
|
50 |
+
G : NetworkX graph
|
51 |
+
Undirected graph
|
52 |
+
|
53 |
+
s : node
|
54 |
+
Source node
|
55 |
+
|
56 |
+
t : node
|
57 |
+
Target node
|
58 |
+
|
59 |
+
flow_func : function
|
60 |
+
A function for computing the maximum flow among a pair of nodes.
|
61 |
+
The function has to accept at least three parameters: a Digraph,
|
62 |
+
a source node, and a target node. And return a residual network
|
63 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
64 |
+
details). If flow_func is None, the default maximum flow function
|
65 |
+
(:meth:`edmonds_karp`) is used. See below for details. The choice
|
66 |
+
of the default function may change from version to version and
|
67 |
+
should not be relied on. Default value: None.
|
68 |
+
|
69 |
+
auxiliary : NetworkX DiGraph
|
70 |
+
Auxiliary digraph to compute flow based node connectivity. It has
|
71 |
+
to have a graph attribute called mapping with a dictionary mapping
|
72 |
+
node names in G and in the auxiliary digraph. If provided
|
73 |
+
it will be reused instead of recreated. Default value: None.
|
74 |
+
|
75 |
+
residual : NetworkX DiGraph
|
76 |
+
Residual network to compute maximum flow. If provided it will be
|
77 |
+
reused instead of recreated. Default value: None.
|
78 |
+
|
79 |
+
cutoff : integer, float, or None (default: None)
|
80 |
+
If specified, the maximum flow algorithm will terminate when the
|
81 |
+
flow value reaches or exceeds the cutoff. This only works for flows
|
82 |
+
that support the cutoff parameter (most do) and is ignored otherwise.
|
83 |
+
|
84 |
+
Returns
|
85 |
+
-------
|
86 |
+
K : integer
|
87 |
+
local node connectivity for nodes s and t
|
88 |
+
|
89 |
+
Examples
|
90 |
+
--------
|
91 |
+
This function is not imported in the base NetworkX namespace, so you
|
92 |
+
have to explicitly import it from the connectivity package:
|
93 |
+
|
94 |
+
>>> from networkx.algorithms.connectivity import local_node_connectivity
|
95 |
+
|
96 |
+
We use in this example the platonic icosahedral graph, which has node
|
97 |
+
connectivity 5.
|
98 |
+
|
99 |
+
>>> G = nx.icosahedral_graph()
|
100 |
+
>>> local_node_connectivity(G, 0, 6)
|
101 |
+
5
|
102 |
+
|
103 |
+
If you need to compute local connectivity on several pairs of
|
104 |
+
nodes in the same graph, it is recommended that you reuse the
|
105 |
+
data structures that NetworkX uses in the computation: the
|
106 |
+
auxiliary digraph for node connectivity, and the residual
|
107 |
+
network for the underlying maximum flow computation.
|
108 |
+
|
109 |
+
Example of how to compute local node connectivity among
|
110 |
+
all pairs of nodes of the platonic icosahedral graph reusing
|
111 |
+
the data structures.
|
112 |
+
|
113 |
+
>>> import itertools
|
114 |
+
>>> # You also have to explicitly import the function for
|
115 |
+
>>> # building the auxiliary digraph from the connectivity package
|
116 |
+
>>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity
|
117 |
+
>>> H = build_auxiliary_node_connectivity(G)
|
118 |
+
>>> # And the function for building the residual network from the
|
119 |
+
>>> # flow package
|
120 |
+
>>> from networkx.algorithms.flow import build_residual_network
|
121 |
+
>>> # Note that the auxiliary digraph has an edge attribute named capacity
|
122 |
+
>>> R = build_residual_network(H, "capacity")
|
123 |
+
>>> result = dict.fromkeys(G, dict())
|
124 |
+
>>> # Reuse the auxiliary digraph and the residual network by passing them
|
125 |
+
>>> # as parameters
|
126 |
+
>>> for u, v in itertools.combinations(G, 2):
|
127 |
+
... k = local_node_connectivity(G, u, v, auxiliary=H, residual=R)
|
128 |
+
... result[u][v] = k
|
129 |
+
>>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
|
130 |
+
True
|
131 |
+
|
132 |
+
You can also use alternative flow algorithms for computing node
|
133 |
+
connectivity. For instance, in dense networks the algorithm
|
134 |
+
:meth:`shortest_augmenting_path` will usually perform better than
|
135 |
+
the default :meth:`edmonds_karp` which is faster for sparse
|
136 |
+
networks with highly skewed degree distributions. Alternative flow
|
137 |
+
functions have to be explicitly imported from the flow package.
|
138 |
+
|
139 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
140 |
+
>>> local_node_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
|
141 |
+
5
|
142 |
+
|
143 |
+
Notes
|
144 |
+
-----
|
145 |
+
This is a flow based implementation of node connectivity. We compute the
|
146 |
+
maximum flow using, by default, the :meth:`edmonds_karp` algorithm (see:
|
147 |
+
:meth:`maximum_flow`) on an auxiliary digraph build from the original
|
148 |
+
input graph:
|
149 |
+
|
150 |
+
For an undirected graph G having `n` nodes and `m` edges we derive a
|
151 |
+
directed graph H with `2n` nodes and `2m+n` arcs by replacing each
|
152 |
+
original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
|
153 |
+
arc in H. Then for each edge (`u`, `v`) in G we add two arcs
|
154 |
+
(`u_B`, `v_A`) and (`v_B`, `u_A`) in H. Finally we set the attribute
|
155 |
+
capacity = 1 for each arc in H [1]_ .
|
156 |
+
|
157 |
+
For a directed graph G having `n` nodes and `m` arcs we derive a
|
158 |
+
directed graph H with `2n` nodes and `m+n` arcs by replacing each
|
159 |
+
original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
|
160 |
+
arc (`v_A`, `v_B`) in H. Then for each arc (`u`, `v`) in G we add one arc
|
161 |
+
(`u_B`, `v_A`) in H. Finally we set the attribute capacity = 1 for
|
162 |
+
each arc in H.
|
163 |
+
|
164 |
+
This is equal to the local node connectivity because the value of
|
165 |
+
a maximum s-t-flow is equal to the capacity of a minimum s-t-cut.
|
166 |
+
|
167 |
+
See also
|
168 |
+
--------
|
169 |
+
:meth:`local_edge_connectivity`
|
170 |
+
:meth:`node_connectivity`
|
171 |
+
:meth:`minimum_node_cut`
|
172 |
+
:meth:`maximum_flow`
|
173 |
+
:meth:`edmonds_karp`
|
174 |
+
:meth:`preflow_push`
|
175 |
+
:meth:`shortest_augmenting_path`
|
176 |
+
|
177 |
+
References
|
178 |
+
----------
|
179 |
+
.. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and
|
180 |
+
Erlebach, 'Network Analysis: Methodological Foundations', Lecture
|
181 |
+
Notes in Computer Science, Volume 3418, Springer-Verlag, 2005.
|
182 |
+
http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
|
183 |
+
|
184 |
+
"""
|
185 |
+
if flow_func is None:
|
186 |
+
flow_func = default_flow_func
|
187 |
+
|
188 |
+
if auxiliary is None:
|
189 |
+
H = build_auxiliary_node_connectivity(G)
|
190 |
+
else:
|
191 |
+
H = auxiliary
|
192 |
+
|
193 |
+
mapping = H.graph.get("mapping", None)
|
194 |
+
if mapping is None:
|
195 |
+
raise nx.NetworkXError("Invalid auxiliary digraph.")
|
196 |
+
|
197 |
+
kwargs = {"flow_func": flow_func, "residual": residual}
|
198 |
+
if flow_func is shortest_augmenting_path:
|
199 |
+
kwargs["cutoff"] = cutoff
|
200 |
+
kwargs["two_phase"] = True
|
201 |
+
elif flow_func is edmonds_karp:
|
202 |
+
kwargs["cutoff"] = cutoff
|
203 |
+
elif flow_func is dinitz:
|
204 |
+
kwargs["cutoff"] = cutoff
|
205 |
+
elif flow_func is boykov_kolmogorov:
|
206 |
+
kwargs["cutoff"] = cutoff
|
207 |
+
|
208 |
+
return nx.maximum_flow_value(H, f"{mapping[s]}B", f"{mapping[t]}A", **kwargs)
|
209 |
+
|
210 |
+
|
211 |
+
@nx._dispatchable
|
212 |
+
def node_connectivity(G, s=None, t=None, flow_func=None):
|
213 |
+
r"""Returns node connectivity for a graph or digraph G.
|
214 |
+
|
215 |
+
Node connectivity is equal to the minimum number of nodes that
|
216 |
+
must be removed to disconnect G or render it trivial. If source
|
217 |
+
and target nodes are provided, this function returns the local node
|
218 |
+
connectivity: the minimum number of nodes that must be removed to break
|
219 |
+
all paths from source to target in G.
|
220 |
+
|
221 |
+
Parameters
|
222 |
+
----------
|
223 |
+
G : NetworkX graph
|
224 |
+
Undirected graph
|
225 |
+
|
226 |
+
s : node
|
227 |
+
Source node. Optional. Default value: None.
|
228 |
+
|
229 |
+
t : node
|
230 |
+
Target node. Optional. Default value: None.
|
231 |
+
|
232 |
+
flow_func : function
|
233 |
+
A function for computing the maximum flow among a pair of nodes.
|
234 |
+
The function has to accept at least three parameters: a Digraph,
|
235 |
+
a source node, and a target node. And return a residual network
|
236 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
237 |
+
details). If flow_func is None, the default maximum flow function
|
238 |
+
(:meth:`edmonds_karp`) is used. See below for details. The
|
239 |
+
choice of the default function may change from version
|
240 |
+
to version and should not be relied on. Default value: None.
|
241 |
+
|
242 |
+
Returns
|
243 |
+
-------
|
244 |
+
K : integer
|
245 |
+
Node connectivity of G, or local node connectivity if source
|
246 |
+
and target are provided.
|
247 |
+
|
248 |
+
Examples
|
249 |
+
--------
|
250 |
+
>>> # Platonic icosahedral graph is 5-node-connected
|
251 |
+
>>> G = nx.icosahedral_graph()
|
252 |
+
>>> nx.node_connectivity(G)
|
253 |
+
5
|
254 |
+
|
255 |
+
You can use alternative flow algorithms for the underlying maximum
|
256 |
+
flow computation. In dense networks the algorithm
|
257 |
+
:meth:`shortest_augmenting_path` will usually perform better
|
258 |
+
than the default :meth:`edmonds_karp`, which is faster for
|
259 |
+
sparse networks with highly skewed degree distributions. Alternative
|
260 |
+
flow functions have to be explicitly imported from the flow package.
|
261 |
+
|
262 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
263 |
+
>>> nx.node_connectivity(G, flow_func=shortest_augmenting_path)
|
264 |
+
5
|
265 |
+
|
266 |
+
If you specify a pair of nodes (source and target) as parameters,
|
267 |
+
this function returns the value of local node connectivity.
|
268 |
+
|
269 |
+
>>> nx.node_connectivity(G, 3, 7)
|
270 |
+
5
|
271 |
+
|
272 |
+
If you need to perform several local computations among different
|
273 |
+
pairs of nodes on the same graph, it is recommended that you reuse
|
274 |
+
the data structures used in the maximum flow computations. See
|
275 |
+
:meth:`local_node_connectivity` for details.
|
276 |
+
|
277 |
+
Notes
|
278 |
+
-----
|
279 |
+
This is a flow based implementation of node connectivity. The
|
280 |
+
algorithm works by solving $O((n-\delta-1+\delta(\delta-1)/2))$
|
281 |
+
maximum flow problems on an auxiliary digraph. Where $\delta$
|
282 |
+
is the minimum degree of G. For details about the auxiliary
|
283 |
+
digraph and the computation of local node connectivity see
|
284 |
+
:meth:`local_node_connectivity`. This implementation is based
|
285 |
+
on algorithm 11 in [1]_.
|
286 |
+
|
287 |
+
See also
|
288 |
+
--------
|
289 |
+
:meth:`local_node_connectivity`
|
290 |
+
:meth:`edge_connectivity`
|
291 |
+
:meth:`maximum_flow`
|
292 |
+
:meth:`edmonds_karp`
|
293 |
+
:meth:`preflow_push`
|
294 |
+
:meth:`shortest_augmenting_path`
|
295 |
+
|
296 |
+
References
|
297 |
+
----------
|
298 |
+
.. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
|
299 |
+
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
|
300 |
+
|
301 |
+
"""
|
302 |
+
if (s is not None and t is None) or (s is None and t is not None):
|
303 |
+
raise nx.NetworkXError("Both source and target must be specified.")
|
304 |
+
|
305 |
+
# Local node connectivity
|
306 |
+
if s is not None and t is not None:
|
307 |
+
if s not in G:
|
308 |
+
raise nx.NetworkXError(f"node {s} not in graph")
|
309 |
+
if t not in G:
|
310 |
+
raise nx.NetworkXError(f"node {t} not in graph")
|
311 |
+
return local_node_connectivity(G, s, t, flow_func=flow_func)
|
312 |
+
|
313 |
+
# Global node connectivity
|
314 |
+
if G.is_directed():
|
315 |
+
if not nx.is_weakly_connected(G):
|
316 |
+
return 0
|
317 |
+
iter_func = itertools.permutations
|
318 |
+
# It is necessary to consider both predecessors
|
319 |
+
# and successors for directed graphs
|
320 |
+
|
321 |
+
def neighbors(v):
|
322 |
+
return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
|
323 |
+
|
324 |
+
else:
|
325 |
+
if not nx.is_connected(G):
|
326 |
+
return 0
|
327 |
+
iter_func = itertools.combinations
|
328 |
+
neighbors = G.neighbors
|
329 |
+
|
330 |
+
# Reuse the auxiliary digraph and the residual network
|
331 |
+
H = build_auxiliary_node_connectivity(G)
|
332 |
+
R = build_residual_network(H, "capacity")
|
333 |
+
kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
|
334 |
+
|
335 |
+
# Pick a node with minimum degree
|
336 |
+
# Node connectivity is bounded by degree.
|
337 |
+
v, K = min(G.degree(), key=itemgetter(1))
|
338 |
+
# compute local node connectivity with all its non-neighbors nodes
|
339 |
+
for w in set(G) - set(neighbors(v)) - {v}:
|
340 |
+
kwargs["cutoff"] = K
|
341 |
+
K = min(K, local_node_connectivity(G, v, w, **kwargs))
|
342 |
+
# Also for non adjacent pairs of neighbors of v
|
343 |
+
for x, y in iter_func(neighbors(v), 2):
|
344 |
+
if y in G[x]:
|
345 |
+
continue
|
346 |
+
kwargs["cutoff"] = K
|
347 |
+
K = min(K, local_node_connectivity(G, x, y, **kwargs))
|
348 |
+
|
349 |
+
return K
|
350 |
+
|
351 |
+
|
352 |
+
@nx._dispatchable
|
353 |
+
def average_node_connectivity(G, flow_func=None):
|
354 |
+
r"""Returns the average connectivity of a graph G.
|
355 |
+
|
356 |
+
The average connectivity `\bar{\kappa}` of a graph G is the average
|
357 |
+
of local node connectivity over all pairs of nodes of G [1]_ .
|
358 |
+
|
359 |
+
.. math::
|
360 |
+
|
361 |
+
\bar{\kappa}(G) = \frac{\sum_{u,v} \kappa_{G}(u,v)}{{n \choose 2}}
|
362 |
+
|
363 |
+
Parameters
|
364 |
+
----------
|
365 |
+
|
366 |
+
G : NetworkX graph
|
367 |
+
Undirected graph
|
368 |
+
|
369 |
+
flow_func : function
|
370 |
+
A function for computing the maximum flow among a pair of nodes.
|
371 |
+
The function has to accept at least three parameters: a Digraph,
|
372 |
+
a source node, and a target node. And return a residual network
|
373 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
374 |
+
details). If flow_func is None, the default maximum flow function
|
375 |
+
(:meth:`edmonds_karp`) is used. See :meth:`local_node_connectivity`
|
376 |
+
for details. The choice of the default function may change from
|
377 |
+
version to version and should not be relied on. Default value: None.
|
378 |
+
|
379 |
+
Returns
|
380 |
+
-------
|
381 |
+
K : float
|
382 |
+
Average node connectivity
|
383 |
+
|
384 |
+
See also
|
385 |
+
--------
|
386 |
+
:meth:`local_node_connectivity`
|
387 |
+
:meth:`node_connectivity`
|
388 |
+
:meth:`edge_connectivity`
|
389 |
+
:meth:`maximum_flow`
|
390 |
+
:meth:`edmonds_karp`
|
391 |
+
:meth:`preflow_push`
|
392 |
+
:meth:`shortest_augmenting_path`
|
393 |
+
|
394 |
+
References
|
395 |
+
----------
|
396 |
+
.. [1] Beineke, L., O. Oellermann, and R. Pippert (2002). The average
|
397 |
+
connectivity of a graph. Discrete mathematics 252(1-3), 31-45.
|
398 |
+
http://www.sciencedirect.com/science/article/pii/S0012365X01001807
|
399 |
+
|
400 |
+
"""
|
401 |
+
if G.is_directed():
|
402 |
+
iter_func = itertools.permutations
|
403 |
+
else:
|
404 |
+
iter_func = itertools.combinations
|
405 |
+
|
406 |
+
# Reuse the auxiliary digraph and the residual network
|
407 |
+
H = build_auxiliary_node_connectivity(G)
|
408 |
+
R = build_residual_network(H, "capacity")
|
409 |
+
kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
|
410 |
+
|
411 |
+
num, den = 0, 0
|
412 |
+
for u, v in iter_func(G, 2):
|
413 |
+
num += local_node_connectivity(G, u, v, **kwargs)
|
414 |
+
den += 1
|
415 |
+
|
416 |
+
if den == 0: # Null Graph
|
417 |
+
return 0
|
418 |
+
return num / den
|
419 |
+
|
420 |
+
|
421 |
+
@nx._dispatchable
|
422 |
+
def all_pairs_node_connectivity(G, nbunch=None, flow_func=None):
|
423 |
+
"""Compute node connectivity between all pairs of nodes of G.
|
424 |
+
|
425 |
+
Parameters
|
426 |
+
----------
|
427 |
+
G : NetworkX graph
|
428 |
+
Undirected graph
|
429 |
+
|
430 |
+
nbunch: container
|
431 |
+
Container of nodes. If provided node connectivity will be computed
|
432 |
+
only over pairs of nodes in nbunch.
|
433 |
+
|
434 |
+
flow_func : function
|
435 |
+
A function for computing the maximum flow among a pair of nodes.
|
436 |
+
The function has to accept at least three parameters: a Digraph,
|
437 |
+
a source node, and a target node. And return a residual network
|
438 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
439 |
+
details). If flow_func is None, the default maximum flow function
|
440 |
+
(:meth:`edmonds_karp`) is used. See below for details. The
|
441 |
+
choice of the default function may change from version
|
442 |
+
to version and should not be relied on. Default value: None.
|
443 |
+
|
444 |
+
Returns
|
445 |
+
-------
|
446 |
+
all_pairs : dict
|
447 |
+
A dictionary with node connectivity between all pairs of nodes
|
448 |
+
in G, or in nbunch if provided.
|
449 |
+
|
450 |
+
See also
|
451 |
+
--------
|
452 |
+
:meth:`local_node_connectivity`
|
453 |
+
:meth:`edge_connectivity`
|
454 |
+
:meth:`local_edge_connectivity`
|
455 |
+
:meth:`maximum_flow`
|
456 |
+
:meth:`edmonds_karp`
|
457 |
+
:meth:`preflow_push`
|
458 |
+
:meth:`shortest_augmenting_path`
|
459 |
+
|
460 |
+
"""
|
461 |
+
if nbunch is None:
|
462 |
+
nbunch = G
|
463 |
+
else:
|
464 |
+
nbunch = set(nbunch)
|
465 |
+
|
466 |
+
directed = G.is_directed()
|
467 |
+
if directed:
|
468 |
+
iter_func = itertools.permutations
|
469 |
+
else:
|
470 |
+
iter_func = itertools.combinations
|
471 |
+
|
472 |
+
all_pairs = {n: {} for n in nbunch}
|
473 |
+
|
474 |
+
# Reuse auxiliary digraph and residual network
|
475 |
+
H = build_auxiliary_node_connectivity(G)
|
476 |
+
mapping = H.graph["mapping"]
|
477 |
+
R = build_residual_network(H, "capacity")
|
478 |
+
kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
|
479 |
+
|
480 |
+
for u, v in iter_func(nbunch, 2):
|
481 |
+
K = local_node_connectivity(G, u, v, **kwargs)
|
482 |
+
all_pairs[u][v] = K
|
483 |
+
if not directed:
|
484 |
+
all_pairs[v][u] = K
|
485 |
+
|
486 |
+
return all_pairs
|
487 |
+
|
488 |
+
|
489 |
+
@nx._dispatchable(graphs={"G": 0, "auxiliary?": 4})
|
490 |
+
def local_edge_connectivity(
|
491 |
+
G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None
|
492 |
+
):
|
493 |
+
r"""Returns local edge connectivity for nodes s and t in G.
|
494 |
+
|
495 |
+
Local edge connectivity for two nodes s and t is the minimum number
|
496 |
+
of edges that must be removed to disconnect them.
|
497 |
+
|
498 |
+
This is a flow based implementation of edge connectivity. We compute the
|
499 |
+
maximum flow on an auxiliary digraph build from the original
|
500 |
+
network (see below for details). This is equal to the local edge
|
501 |
+
connectivity because the value of a maximum s-t-flow is equal to the
|
502 |
+
capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ .
|
503 |
+
|
504 |
+
Parameters
|
505 |
+
----------
|
506 |
+
G : NetworkX graph
|
507 |
+
Undirected or directed graph
|
508 |
+
|
509 |
+
s : node
|
510 |
+
Source node
|
511 |
+
|
512 |
+
t : node
|
513 |
+
Target node
|
514 |
+
|
515 |
+
flow_func : function
|
516 |
+
A function for computing the maximum flow among a pair of nodes.
|
517 |
+
The function has to accept at least three parameters: a Digraph,
|
518 |
+
a source node, and a target node. And return a residual network
|
519 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
520 |
+
details). If flow_func is None, the default maximum flow function
|
521 |
+
(:meth:`edmonds_karp`) is used. See below for details. The
|
522 |
+
choice of the default function may change from version
|
523 |
+
to version and should not be relied on. Default value: None.
|
524 |
+
|
525 |
+
auxiliary : NetworkX DiGraph
|
526 |
+
Auxiliary digraph for computing flow based edge connectivity. If
|
527 |
+
provided it will be reused instead of recreated. Default value: None.
|
528 |
+
|
529 |
+
residual : NetworkX DiGraph
|
530 |
+
Residual network to compute maximum flow. If provided it will be
|
531 |
+
reused instead of recreated. Default value: None.
|
532 |
+
|
533 |
+
cutoff : integer, float, or None (default: None)
|
534 |
+
If specified, the maximum flow algorithm will terminate when the
|
535 |
+
flow value reaches or exceeds the cutoff. This only works for flows
|
536 |
+
that support the cutoff parameter (most do) and is ignored otherwise.
|
537 |
+
|
538 |
+
Returns
|
539 |
+
-------
|
540 |
+
K : integer
|
541 |
+
local edge connectivity for nodes s and t.
|
542 |
+
|
543 |
+
Examples
|
544 |
+
--------
|
545 |
+
This function is not imported in the base NetworkX namespace, so you
|
546 |
+
have to explicitly import it from the connectivity package:
|
547 |
+
|
548 |
+
>>> from networkx.algorithms.connectivity import local_edge_connectivity
|
549 |
+
|
550 |
+
We use in this example the platonic icosahedral graph, which has edge
|
551 |
+
connectivity 5.
|
552 |
+
|
553 |
+
>>> G = nx.icosahedral_graph()
|
554 |
+
>>> local_edge_connectivity(G, 0, 6)
|
555 |
+
5
|
556 |
+
|
557 |
+
If you need to compute local connectivity on several pairs of
|
558 |
+
nodes in the same graph, it is recommended that you reuse the
|
559 |
+
data structures that NetworkX uses in the computation: the
|
560 |
+
auxiliary digraph for edge connectivity, and the residual
|
561 |
+
network for the underlying maximum flow computation.
|
562 |
+
|
563 |
+
Example of how to compute local edge connectivity among
|
564 |
+
all pairs of nodes of the platonic icosahedral graph reusing
|
565 |
+
the data structures.
|
566 |
+
|
567 |
+
>>> import itertools
|
568 |
+
>>> # You also have to explicitly import the function for
|
569 |
+
>>> # building the auxiliary digraph from the connectivity package
|
570 |
+
>>> from networkx.algorithms.connectivity import build_auxiliary_edge_connectivity
|
571 |
+
>>> H = build_auxiliary_edge_connectivity(G)
|
572 |
+
>>> # And the function for building the residual network from the
|
573 |
+
>>> # flow package
|
574 |
+
>>> from networkx.algorithms.flow import build_residual_network
|
575 |
+
>>> # Note that the auxiliary digraph has an edge attribute named capacity
|
576 |
+
>>> R = build_residual_network(H, "capacity")
|
577 |
+
>>> result = dict.fromkeys(G, dict())
|
578 |
+
>>> # Reuse the auxiliary digraph and the residual network by passing them
|
579 |
+
>>> # as parameters
|
580 |
+
>>> for u, v in itertools.combinations(G, 2):
|
581 |
+
... k = local_edge_connectivity(G, u, v, auxiliary=H, residual=R)
|
582 |
+
... result[u][v] = k
|
583 |
+
>>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
|
584 |
+
True
|
585 |
+
|
586 |
+
You can also use alternative flow algorithms for computing edge
|
587 |
+
connectivity. For instance, in dense networks the algorithm
|
588 |
+
:meth:`shortest_augmenting_path` will usually perform better than
|
589 |
+
the default :meth:`edmonds_karp` which is faster for sparse
|
590 |
+
networks with highly skewed degree distributions. Alternative flow
|
591 |
+
functions have to be explicitly imported from the flow package.
|
592 |
+
|
593 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
594 |
+
>>> local_edge_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
|
595 |
+
5
|
596 |
+
|
597 |
+
Notes
|
598 |
+
-----
|
599 |
+
This is a flow based implementation of edge connectivity. We compute the
|
600 |
+
maximum flow using, by default, the :meth:`edmonds_karp` algorithm on an
|
601 |
+
auxiliary digraph build from the original input graph:
|
602 |
+
|
603 |
+
If the input graph is undirected, we replace each edge (`u`,`v`) with
|
604 |
+
two reciprocal arcs (`u`, `v`) and (`v`, `u`) and then we set the attribute
|
605 |
+
'capacity' for each arc to 1. If the input graph is directed we simply
|
606 |
+
add the 'capacity' attribute. This is an implementation of algorithm 1
|
607 |
+
in [1]_.
|
608 |
+
|
609 |
+
The maximum flow in the auxiliary network is equal to the local edge
|
610 |
+
connectivity because the value of a maximum s-t-flow is equal to the
|
611 |
+
capacity of a minimum s-t-cut (Ford and Fulkerson theorem).
|
612 |
+
|
613 |
+
See also
|
614 |
+
--------
|
615 |
+
:meth:`edge_connectivity`
|
616 |
+
:meth:`local_node_connectivity`
|
617 |
+
:meth:`node_connectivity`
|
618 |
+
:meth:`maximum_flow`
|
619 |
+
:meth:`edmonds_karp`
|
620 |
+
:meth:`preflow_push`
|
621 |
+
:meth:`shortest_augmenting_path`
|
622 |
+
|
623 |
+
References
|
624 |
+
----------
|
625 |
+
.. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
|
626 |
+
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
|
627 |
+
|
628 |
+
"""
|
629 |
+
if flow_func is None:
|
630 |
+
flow_func = default_flow_func
|
631 |
+
|
632 |
+
if auxiliary is None:
|
633 |
+
H = build_auxiliary_edge_connectivity(G)
|
634 |
+
else:
|
635 |
+
H = auxiliary
|
636 |
+
|
637 |
+
kwargs = {"flow_func": flow_func, "residual": residual}
|
638 |
+
if flow_func is shortest_augmenting_path:
|
639 |
+
kwargs["cutoff"] = cutoff
|
640 |
+
kwargs["two_phase"] = True
|
641 |
+
elif flow_func is edmonds_karp:
|
642 |
+
kwargs["cutoff"] = cutoff
|
643 |
+
elif flow_func is dinitz:
|
644 |
+
kwargs["cutoff"] = cutoff
|
645 |
+
elif flow_func is boykov_kolmogorov:
|
646 |
+
kwargs["cutoff"] = cutoff
|
647 |
+
|
648 |
+
return nx.maximum_flow_value(H, s, t, **kwargs)
|
649 |
+
|
650 |
+
|
651 |
+
@nx._dispatchable
|
652 |
+
def edge_connectivity(G, s=None, t=None, flow_func=None, cutoff=None):
|
653 |
+
r"""Returns the edge connectivity of the graph or digraph G.
|
654 |
+
|
655 |
+
The edge connectivity is equal to the minimum number of edges that
|
656 |
+
must be removed to disconnect G or render it trivial. If source
|
657 |
+
and target nodes are provided, this function returns the local edge
|
658 |
+
connectivity: the minimum number of edges that must be removed to
|
659 |
+
break all paths from source to target in G.
|
660 |
+
|
661 |
+
Parameters
|
662 |
+
----------
|
663 |
+
G : NetworkX graph
|
664 |
+
Undirected or directed graph
|
665 |
+
|
666 |
+
s : node
|
667 |
+
Source node. Optional. Default value: None.
|
668 |
+
|
669 |
+
t : node
|
670 |
+
Target node. Optional. Default value: None.
|
671 |
+
|
672 |
+
flow_func : function
|
673 |
+
A function for computing the maximum flow among a pair of nodes.
|
674 |
+
The function has to accept at least three parameters: a Digraph,
|
675 |
+
a source node, and a target node. And return a residual network
|
676 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
677 |
+
details). If flow_func is None, the default maximum flow function
|
678 |
+
(:meth:`edmonds_karp`) is used. See below for details. The
|
679 |
+
choice of the default function may change from version
|
680 |
+
to version and should not be relied on. Default value: None.
|
681 |
+
|
682 |
+
cutoff : integer, float, or None (default: None)
|
683 |
+
If specified, the maximum flow algorithm will terminate when the
|
684 |
+
flow value reaches or exceeds the cutoff. This only works for flows
|
685 |
+
that support the cutoff parameter (most do) and is ignored otherwise.
|
686 |
+
|
687 |
+
Returns
|
688 |
+
-------
|
689 |
+
K : integer
|
690 |
+
Edge connectivity for G, or local edge connectivity if source
|
691 |
+
and target were provided
|
692 |
+
|
693 |
+
Examples
|
694 |
+
--------
|
695 |
+
>>> # Platonic icosahedral graph is 5-edge-connected
|
696 |
+
>>> G = nx.icosahedral_graph()
|
697 |
+
>>> nx.edge_connectivity(G)
|
698 |
+
5
|
699 |
+
|
700 |
+
You can use alternative flow algorithms for the underlying
|
701 |
+
maximum flow computation. In dense networks the algorithm
|
702 |
+
:meth:`shortest_augmenting_path` will usually perform better
|
703 |
+
than the default :meth:`edmonds_karp`, which is faster for
|
704 |
+
sparse networks with highly skewed degree distributions.
|
705 |
+
Alternative flow functions have to be explicitly imported
|
706 |
+
from the flow package.
|
707 |
+
|
708 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
709 |
+
>>> nx.edge_connectivity(G, flow_func=shortest_augmenting_path)
|
710 |
+
5
|
711 |
+
|
712 |
+
If you specify a pair of nodes (source and target) as parameters,
|
713 |
+
this function returns the value of local edge connectivity.
|
714 |
+
|
715 |
+
>>> nx.edge_connectivity(G, 3, 7)
|
716 |
+
5
|
717 |
+
|
718 |
+
If you need to perform several local computations among different
|
719 |
+
pairs of nodes on the same graph, it is recommended that you reuse
|
720 |
+
the data structures used in the maximum flow computations. See
|
721 |
+
:meth:`local_edge_connectivity` for details.
|
722 |
+
|
723 |
+
Notes
|
724 |
+
-----
|
725 |
+
This is a flow based implementation of global edge connectivity.
|
726 |
+
For undirected graphs the algorithm works by finding a 'small'
|
727 |
+
dominating set of nodes of G (see algorithm 7 in [1]_ ) and
|
728 |
+
computing local maximum flow (see :meth:`local_edge_connectivity`)
|
729 |
+
between an arbitrary node in the dominating set and the rest of
|
730 |
+
nodes in it. This is an implementation of algorithm 6 in [1]_ .
|
731 |
+
For directed graphs, the algorithm does n calls to the maximum
|
732 |
+
flow function. This is an implementation of algorithm 8 in [1]_ .
|
733 |
+
|
734 |
+
See also
|
735 |
+
--------
|
736 |
+
:meth:`local_edge_connectivity`
|
737 |
+
:meth:`local_node_connectivity`
|
738 |
+
:meth:`node_connectivity`
|
739 |
+
:meth:`maximum_flow`
|
740 |
+
:meth:`edmonds_karp`
|
741 |
+
:meth:`preflow_push`
|
742 |
+
:meth:`shortest_augmenting_path`
|
743 |
+
:meth:`k_edge_components`
|
744 |
+
:meth:`k_edge_subgraphs`
|
745 |
+
|
746 |
+
References
|
747 |
+
----------
|
748 |
+
.. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
|
749 |
+
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
|
750 |
+
|
751 |
+
"""
|
752 |
+
if (s is not None and t is None) or (s is None and t is not None):
|
753 |
+
raise nx.NetworkXError("Both source and target must be specified.")
|
754 |
+
|
755 |
+
# Local edge connectivity
|
756 |
+
if s is not None and t is not None:
|
757 |
+
if s not in G:
|
758 |
+
raise nx.NetworkXError(f"node {s} not in graph")
|
759 |
+
if t not in G:
|
760 |
+
raise nx.NetworkXError(f"node {t} not in graph")
|
761 |
+
return local_edge_connectivity(G, s, t, flow_func=flow_func, cutoff=cutoff)
|
762 |
+
|
763 |
+
# Global edge connectivity
|
764 |
+
# reuse auxiliary digraph and residual network
|
765 |
+
H = build_auxiliary_edge_connectivity(G)
|
766 |
+
R = build_residual_network(H, "capacity")
|
767 |
+
kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
|
768 |
+
|
769 |
+
if G.is_directed():
|
770 |
+
# Algorithm 8 in [1]
|
771 |
+
if not nx.is_weakly_connected(G):
|
772 |
+
return 0
|
773 |
+
|
774 |
+
# initial value for \lambda is minimum degree
|
775 |
+
L = min(d for n, d in G.degree())
|
776 |
+
nodes = list(G)
|
777 |
+
n = len(nodes)
|
778 |
+
|
779 |
+
if cutoff is not None:
|
780 |
+
L = min(cutoff, L)
|
781 |
+
|
782 |
+
for i in range(n):
|
783 |
+
kwargs["cutoff"] = L
|
784 |
+
try:
|
785 |
+
L = min(L, local_edge_connectivity(G, nodes[i], nodes[i + 1], **kwargs))
|
786 |
+
except IndexError: # last node!
|
787 |
+
L = min(L, local_edge_connectivity(G, nodes[i], nodes[0], **kwargs))
|
788 |
+
return L
|
789 |
+
else: # undirected
|
790 |
+
# Algorithm 6 in [1]
|
791 |
+
if not nx.is_connected(G):
|
792 |
+
return 0
|
793 |
+
|
794 |
+
# initial value for \lambda is minimum degree
|
795 |
+
L = min(d for n, d in G.degree())
|
796 |
+
|
797 |
+
if cutoff is not None:
|
798 |
+
L = min(cutoff, L)
|
799 |
+
|
800 |
+
# A dominating set is \lambda-covering
|
801 |
+
# We need a dominating set with at least two nodes
|
802 |
+
for node in G:
|
803 |
+
D = nx.dominating_set(G, start_with=node)
|
804 |
+
v = D.pop()
|
805 |
+
if D:
|
806 |
+
break
|
807 |
+
else:
|
808 |
+
# in complete graphs the dominating sets will always be of one node
|
809 |
+
# thus we return min degree
|
810 |
+
return L
|
811 |
+
|
812 |
+
for w in D:
|
813 |
+
kwargs["cutoff"] = L
|
814 |
+
L = min(L, local_edge_connectivity(G, v, w, **kwargs))
|
815 |
+
|
816 |
+
return L
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/cuts.py
ADDED
@@ -0,0 +1,611 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Flow based cut algorithms
|
3 |
+
"""
|
4 |
+
import itertools
|
5 |
+
|
6 |
+
import networkx as nx
|
7 |
+
|
8 |
+
# Define the default maximum flow function to use in all flow based
|
9 |
+
# cut algorithms.
|
10 |
+
from networkx.algorithms.flow import build_residual_network, edmonds_karp
|
11 |
+
|
12 |
+
default_flow_func = edmonds_karp
|
13 |
+
|
14 |
+
from .utils import build_auxiliary_edge_connectivity, build_auxiliary_node_connectivity
|
15 |
+
|
16 |
+
__all__ = [
|
17 |
+
"minimum_st_node_cut",
|
18 |
+
"minimum_node_cut",
|
19 |
+
"minimum_st_edge_cut",
|
20 |
+
"minimum_edge_cut",
|
21 |
+
]
|
22 |
+
|
23 |
+
|
24 |
+
@nx._dispatchable(
|
25 |
+
graphs={"G": 0, "auxiliary?": 4},
|
26 |
+
preserve_edge_attrs={"auxiliary": {"capacity": float("inf")}},
|
27 |
+
preserve_graph_attrs={"auxiliary"},
|
28 |
+
)
|
29 |
+
def minimum_st_edge_cut(G, s, t, flow_func=None, auxiliary=None, residual=None):
|
30 |
+
"""Returns the edges of the cut-set of a minimum (s, t)-cut.
|
31 |
+
|
32 |
+
This function returns the set of edges of minimum cardinality that,
|
33 |
+
if removed, would destroy all paths among source and target in G.
|
34 |
+
Edge weights are not considered. See :meth:`minimum_cut` for
|
35 |
+
computing minimum cuts considering edge weights.
|
36 |
+
|
37 |
+
Parameters
|
38 |
+
----------
|
39 |
+
G : NetworkX graph
|
40 |
+
|
41 |
+
s : node
|
42 |
+
Source node for the flow.
|
43 |
+
|
44 |
+
t : node
|
45 |
+
Sink node for the flow.
|
46 |
+
|
47 |
+
auxiliary : NetworkX DiGraph
|
48 |
+
Auxiliary digraph to compute flow based node connectivity. It has
|
49 |
+
to have a graph attribute called mapping with a dictionary mapping
|
50 |
+
node names in G and in the auxiliary digraph. If provided
|
51 |
+
it will be reused instead of recreated. Default value: None.
|
52 |
+
|
53 |
+
flow_func : function
|
54 |
+
A function for computing the maximum flow among a pair of nodes.
|
55 |
+
The function has to accept at least three parameters: a Digraph,
|
56 |
+
a source node, and a target node. And return a residual network
|
57 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
58 |
+
details). If flow_func is None, the default maximum flow function
|
59 |
+
(:meth:`edmonds_karp`) is used. See :meth:`node_connectivity` for
|
60 |
+
details. The choice of the default function may change from version
|
61 |
+
to version and should not be relied on. Default value: None.
|
62 |
+
|
63 |
+
residual : NetworkX DiGraph
|
64 |
+
Residual network to compute maximum flow. If provided it will be
|
65 |
+
reused instead of recreated. Default value: None.
|
66 |
+
|
67 |
+
Returns
|
68 |
+
-------
|
69 |
+
cutset : set
|
70 |
+
Set of edges that, if removed from the graph, will disconnect it.
|
71 |
+
|
72 |
+
See also
|
73 |
+
--------
|
74 |
+
:meth:`minimum_cut`
|
75 |
+
:meth:`minimum_node_cut`
|
76 |
+
:meth:`minimum_edge_cut`
|
77 |
+
:meth:`stoer_wagner`
|
78 |
+
:meth:`node_connectivity`
|
79 |
+
:meth:`edge_connectivity`
|
80 |
+
:meth:`maximum_flow`
|
81 |
+
:meth:`edmonds_karp`
|
82 |
+
:meth:`preflow_push`
|
83 |
+
:meth:`shortest_augmenting_path`
|
84 |
+
|
85 |
+
Examples
|
86 |
+
--------
|
87 |
+
This function is not imported in the base NetworkX namespace, so you
|
88 |
+
have to explicitly import it from the connectivity package:
|
89 |
+
|
90 |
+
>>> from networkx.algorithms.connectivity import minimum_st_edge_cut
|
91 |
+
|
92 |
+
We use in this example the platonic icosahedral graph, which has edge
|
93 |
+
connectivity 5.
|
94 |
+
|
95 |
+
>>> G = nx.icosahedral_graph()
|
96 |
+
>>> len(minimum_st_edge_cut(G, 0, 6))
|
97 |
+
5
|
98 |
+
|
99 |
+
If you need to compute local edge cuts on several pairs of
|
100 |
+
nodes in the same graph, it is recommended that you reuse the
|
101 |
+
data structures that NetworkX uses in the computation: the
|
102 |
+
auxiliary digraph for edge connectivity, and the residual
|
103 |
+
network for the underlying maximum flow computation.
|
104 |
+
|
105 |
+
Example of how to compute local edge cuts among all pairs of
|
106 |
+
nodes of the platonic icosahedral graph reusing the data
|
107 |
+
structures.
|
108 |
+
|
109 |
+
>>> import itertools
|
110 |
+
>>> # You also have to explicitly import the function for
|
111 |
+
>>> # building the auxiliary digraph from the connectivity package
|
112 |
+
>>> from networkx.algorithms.connectivity import build_auxiliary_edge_connectivity
|
113 |
+
>>> H = build_auxiliary_edge_connectivity(G)
|
114 |
+
>>> # And the function for building the residual network from the
|
115 |
+
>>> # flow package
|
116 |
+
>>> from networkx.algorithms.flow import build_residual_network
|
117 |
+
>>> # Note that the auxiliary digraph has an edge attribute named capacity
|
118 |
+
>>> R = build_residual_network(H, "capacity")
|
119 |
+
>>> result = dict.fromkeys(G, dict())
|
120 |
+
>>> # Reuse the auxiliary digraph and the residual network by passing them
|
121 |
+
>>> # as parameters
|
122 |
+
>>> for u, v in itertools.combinations(G, 2):
|
123 |
+
... k = len(minimum_st_edge_cut(G, u, v, auxiliary=H, residual=R))
|
124 |
+
... result[u][v] = k
|
125 |
+
>>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
|
126 |
+
True
|
127 |
+
|
128 |
+
You can also use alternative flow algorithms for computing edge
|
129 |
+
cuts. For instance, in dense networks the algorithm
|
130 |
+
:meth:`shortest_augmenting_path` will usually perform better than
|
131 |
+
the default :meth:`edmonds_karp` which is faster for sparse
|
132 |
+
networks with highly skewed degree distributions. Alternative flow
|
133 |
+
functions have to be explicitly imported from the flow package.
|
134 |
+
|
135 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
136 |
+
>>> len(minimum_st_edge_cut(G, 0, 6, flow_func=shortest_augmenting_path))
|
137 |
+
5
|
138 |
+
|
139 |
+
"""
|
140 |
+
if flow_func is None:
|
141 |
+
flow_func = default_flow_func
|
142 |
+
|
143 |
+
if auxiliary is None:
|
144 |
+
H = build_auxiliary_edge_connectivity(G)
|
145 |
+
else:
|
146 |
+
H = auxiliary
|
147 |
+
|
148 |
+
kwargs = {"capacity": "capacity", "flow_func": flow_func, "residual": residual}
|
149 |
+
|
150 |
+
cut_value, partition = nx.minimum_cut(H, s, t, **kwargs)
|
151 |
+
reachable, non_reachable = partition
|
152 |
+
# Any edge in the original graph linking the two sets in the
|
153 |
+
# partition is part of the edge cutset
|
154 |
+
cutset = set()
|
155 |
+
for u, nbrs in ((n, G[n]) for n in reachable):
|
156 |
+
cutset.update((u, v) for v in nbrs if v in non_reachable)
|
157 |
+
|
158 |
+
return cutset
|
159 |
+
|
160 |
+
|
161 |
+
@nx._dispatchable(
|
162 |
+
graphs={"G": 0, "auxiliary?": 4},
|
163 |
+
preserve_node_attrs={"auxiliary": {"id": None}},
|
164 |
+
preserve_graph_attrs={"auxiliary"},
|
165 |
+
)
|
166 |
+
def minimum_st_node_cut(G, s, t, flow_func=None, auxiliary=None, residual=None):
|
167 |
+
r"""Returns a set of nodes of minimum cardinality that disconnect source
|
168 |
+
from target in G.
|
169 |
+
|
170 |
+
This function returns the set of nodes of minimum cardinality that,
|
171 |
+
if removed, would destroy all paths among source and target in G.
|
172 |
+
|
173 |
+
Parameters
|
174 |
+
----------
|
175 |
+
G : NetworkX graph
|
176 |
+
|
177 |
+
s : node
|
178 |
+
Source node.
|
179 |
+
|
180 |
+
t : node
|
181 |
+
Target node.
|
182 |
+
|
183 |
+
flow_func : function
|
184 |
+
A function for computing the maximum flow among a pair of nodes.
|
185 |
+
The function has to accept at least three parameters: a Digraph,
|
186 |
+
a source node, and a target node. And return a residual network
|
187 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
188 |
+
details). If flow_func is None, the default maximum flow function
|
189 |
+
(:meth:`edmonds_karp`) is used. See below for details. The choice
|
190 |
+
of the default function may change from version to version and
|
191 |
+
should not be relied on. Default value: None.
|
192 |
+
|
193 |
+
auxiliary : NetworkX DiGraph
|
194 |
+
Auxiliary digraph to compute flow based node connectivity. It has
|
195 |
+
to have a graph attribute called mapping with a dictionary mapping
|
196 |
+
node names in G and in the auxiliary digraph. If provided
|
197 |
+
it will be reused instead of recreated. Default value: None.
|
198 |
+
|
199 |
+
residual : NetworkX DiGraph
|
200 |
+
Residual network to compute maximum flow. If provided it will be
|
201 |
+
reused instead of recreated. Default value: None.
|
202 |
+
|
203 |
+
Returns
|
204 |
+
-------
|
205 |
+
cutset : set
|
206 |
+
Set of nodes that, if removed, would destroy all paths between
|
207 |
+
source and target in G.
|
208 |
+
|
209 |
+
Examples
|
210 |
+
--------
|
211 |
+
This function is not imported in the base NetworkX namespace, so you
|
212 |
+
have to explicitly import it from the connectivity package:
|
213 |
+
|
214 |
+
>>> from networkx.algorithms.connectivity import minimum_st_node_cut
|
215 |
+
|
216 |
+
We use in this example the platonic icosahedral graph, which has node
|
217 |
+
connectivity 5.
|
218 |
+
|
219 |
+
>>> G = nx.icosahedral_graph()
|
220 |
+
>>> len(minimum_st_node_cut(G, 0, 6))
|
221 |
+
5
|
222 |
+
|
223 |
+
If you need to compute local st cuts between several pairs of
|
224 |
+
nodes in the same graph, it is recommended that you reuse the
|
225 |
+
data structures that NetworkX uses in the computation: the
|
226 |
+
auxiliary digraph for node connectivity and node cuts, and the
|
227 |
+
residual network for the underlying maximum flow computation.
|
228 |
+
|
229 |
+
Example of how to compute local st node cuts reusing the data
|
230 |
+
structures:
|
231 |
+
|
232 |
+
>>> # You also have to explicitly import the function for
|
233 |
+
>>> # building the auxiliary digraph from the connectivity package
|
234 |
+
>>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity
|
235 |
+
>>> H = build_auxiliary_node_connectivity(G)
|
236 |
+
>>> # And the function for building the residual network from the
|
237 |
+
>>> # flow package
|
238 |
+
>>> from networkx.algorithms.flow import build_residual_network
|
239 |
+
>>> # Note that the auxiliary digraph has an edge attribute named capacity
|
240 |
+
>>> R = build_residual_network(H, "capacity")
|
241 |
+
>>> # Reuse the auxiliary digraph and the residual network by passing them
|
242 |
+
>>> # as parameters
|
243 |
+
>>> len(minimum_st_node_cut(G, 0, 6, auxiliary=H, residual=R))
|
244 |
+
5
|
245 |
+
|
246 |
+
You can also use alternative flow algorithms for computing minimum st
|
247 |
+
node cuts. For instance, in dense networks the algorithm
|
248 |
+
:meth:`shortest_augmenting_path` will usually perform better than
|
249 |
+
the default :meth:`edmonds_karp` which is faster for sparse
|
250 |
+
networks with highly skewed degree distributions. Alternative flow
|
251 |
+
functions have to be explicitly imported from the flow package.
|
252 |
+
|
253 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
254 |
+
>>> len(minimum_st_node_cut(G, 0, 6, flow_func=shortest_augmenting_path))
|
255 |
+
5
|
256 |
+
|
257 |
+
Notes
|
258 |
+
-----
|
259 |
+
This is a flow based implementation of minimum node cut. The algorithm
|
260 |
+
is based in solving a number of maximum flow computations to determine
|
261 |
+
the capacity of the minimum cut on an auxiliary directed network that
|
262 |
+
corresponds to the minimum node cut of G. It handles both directed
|
263 |
+
and undirected graphs. This implementation is based on algorithm 11
|
264 |
+
in [1]_.
|
265 |
+
|
266 |
+
See also
|
267 |
+
--------
|
268 |
+
:meth:`minimum_node_cut`
|
269 |
+
:meth:`minimum_edge_cut`
|
270 |
+
:meth:`stoer_wagner`
|
271 |
+
:meth:`node_connectivity`
|
272 |
+
:meth:`edge_connectivity`
|
273 |
+
:meth:`maximum_flow`
|
274 |
+
:meth:`edmonds_karp`
|
275 |
+
:meth:`preflow_push`
|
276 |
+
:meth:`shortest_augmenting_path`
|
277 |
+
|
278 |
+
References
|
279 |
+
----------
|
280 |
+
.. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
|
281 |
+
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
|
282 |
+
|
283 |
+
"""
|
284 |
+
if auxiliary is None:
|
285 |
+
H = build_auxiliary_node_connectivity(G)
|
286 |
+
else:
|
287 |
+
H = auxiliary
|
288 |
+
|
289 |
+
mapping = H.graph.get("mapping", None)
|
290 |
+
if mapping is None:
|
291 |
+
raise nx.NetworkXError("Invalid auxiliary digraph.")
|
292 |
+
if G.has_edge(s, t) or G.has_edge(t, s):
|
293 |
+
return {}
|
294 |
+
kwargs = {"flow_func": flow_func, "residual": residual, "auxiliary": H}
|
295 |
+
|
296 |
+
# The edge cut in the auxiliary digraph corresponds to the node cut in the
|
297 |
+
# original graph.
|
298 |
+
edge_cut = minimum_st_edge_cut(H, f"{mapping[s]}B", f"{mapping[t]}A", **kwargs)
|
299 |
+
# Each node in the original graph maps to two nodes of the auxiliary graph
|
300 |
+
node_cut = {H.nodes[node]["id"] for edge in edge_cut for node in edge}
|
301 |
+
return node_cut - {s, t}
|
302 |
+
|
303 |
+
|
304 |
+
@nx._dispatchable
|
305 |
+
def minimum_node_cut(G, s=None, t=None, flow_func=None):
|
306 |
+
r"""Returns a set of nodes of minimum cardinality that disconnects G.
|
307 |
+
|
308 |
+
If source and target nodes are provided, this function returns the
|
309 |
+
set of nodes of minimum cardinality that, if removed, would destroy
|
310 |
+
all paths among source and target in G. If not, it returns a set
|
311 |
+
of nodes of minimum cardinality that disconnects G.
|
312 |
+
|
313 |
+
Parameters
|
314 |
+
----------
|
315 |
+
G : NetworkX graph
|
316 |
+
|
317 |
+
s : node
|
318 |
+
Source node. Optional. Default value: None.
|
319 |
+
|
320 |
+
t : node
|
321 |
+
Target node. Optional. Default value: None.
|
322 |
+
|
323 |
+
flow_func : function
|
324 |
+
A function for computing the maximum flow among a pair of nodes.
|
325 |
+
The function has to accept at least three parameters: a Digraph,
|
326 |
+
a source node, and a target node. And return a residual network
|
327 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
328 |
+
details). If flow_func is None, the default maximum flow function
|
329 |
+
(:meth:`edmonds_karp`) is used. See below for details. The
|
330 |
+
choice of the default function may change from version
|
331 |
+
to version and should not be relied on. Default value: None.
|
332 |
+
|
333 |
+
Returns
|
334 |
+
-------
|
335 |
+
cutset : set
|
336 |
+
Set of nodes that, if removed, would disconnect G. If source
|
337 |
+
and target nodes are provided, the set contains the nodes that
|
338 |
+
if removed, would destroy all paths between source and target.
|
339 |
+
|
340 |
+
Examples
|
341 |
+
--------
|
342 |
+
>>> # Platonic icosahedral graph has node connectivity 5
|
343 |
+
>>> G = nx.icosahedral_graph()
|
344 |
+
>>> node_cut = nx.minimum_node_cut(G)
|
345 |
+
>>> len(node_cut)
|
346 |
+
5
|
347 |
+
|
348 |
+
You can use alternative flow algorithms for the underlying maximum
|
349 |
+
flow computation. In dense networks the algorithm
|
350 |
+
:meth:`shortest_augmenting_path` will usually perform better
|
351 |
+
than the default :meth:`edmonds_karp`, which is faster for
|
352 |
+
sparse networks with highly skewed degree distributions. Alternative
|
353 |
+
flow functions have to be explicitly imported from the flow package.
|
354 |
+
|
355 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
356 |
+
>>> node_cut == nx.minimum_node_cut(G, flow_func=shortest_augmenting_path)
|
357 |
+
True
|
358 |
+
|
359 |
+
If you specify a pair of nodes (source and target) as parameters,
|
360 |
+
this function returns a local st node cut.
|
361 |
+
|
362 |
+
>>> len(nx.minimum_node_cut(G, 3, 7))
|
363 |
+
5
|
364 |
+
|
365 |
+
If you need to perform several local st cuts among different
|
366 |
+
pairs of nodes on the same graph, it is recommended that you reuse
|
367 |
+
the data structures used in the maximum flow computations. See
|
368 |
+
:meth:`minimum_st_node_cut` for details.
|
369 |
+
|
370 |
+
Notes
|
371 |
+
-----
|
372 |
+
This is a flow based implementation of minimum node cut. The algorithm
|
373 |
+
is based in solving a number of maximum flow computations to determine
|
374 |
+
the capacity of the minimum cut on an auxiliary directed network that
|
375 |
+
corresponds to the minimum node cut of G. It handles both directed
|
376 |
+
and undirected graphs. This implementation is based on algorithm 11
|
377 |
+
in [1]_.
|
378 |
+
|
379 |
+
See also
|
380 |
+
--------
|
381 |
+
:meth:`minimum_st_node_cut`
|
382 |
+
:meth:`minimum_cut`
|
383 |
+
:meth:`minimum_edge_cut`
|
384 |
+
:meth:`stoer_wagner`
|
385 |
+
:meth:`node_connectivity`
|
386 |
+
:meth:`edge_connectivity`
|
387 |
+
:meth:`maximum_flow`
|
388 |
+
:meth:`edmonds_karp`
|
389 |
+
:meth:`preflow_push`
|
390 |
+
:meth:`shortest_augmenting_path`
|
391 |
+
|
392 |
+
References
|
393 |
+
----------
|
394 |
+
.. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
|
395 |
+
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
|
396 |
+
|
397 |
+
"""
|
398 |
+
if (s is not None and t is None) or (s is None and t is not None):
|
399 |
+
raise nx.NetworkXError("Both source and target must be specified.")
|
400 |
+
|
401 |
+
# Local minimum node cut.
|
402 |
+
if s is not None and t is not None:
|
403 |
+
if s not in G:
|
404 |
+
raise nx.NetworkXError(f"node {s} not in graph")
|
405 |
+
if t not in G:
|
406 |
+
raise nx.NetworkXError(f"node {t} not in graph")
|
407 |
+
return minimum_st_node_cut(G, s, t, flow_func=flow_func)
|
408 |
+
|
409 |
+
# Global minimum node cut.
|
410 |
+
# Analog to the algorithm 11 for global node connectivity in [1].
|
411 |
+
if G.is_directed():
|
412 |
+
if not nx.is_weakly_connected(G):
|
413 |
+
raise nx.NetworkXError("Input graph is not connected")
|
414 |
+
iter_func = itertools.permutations
|
415 |
+
|
416 |
+
def neighbors(v):
|
417 |
+
return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
|
418 |
+
|
419 |
+
else:
|
420 |
+
if not nx.is_connected(G):
|
421 |
+
raise nx.NetworkXError("Input graph is not connected")
|
422 |
+
iter_func = itertools.combinations
|
423 |
+
neighbors = G.neighbors
|
424 |
+
|
425 |
+
# Reuse the auxiliary digraph and the residual network.
|
426 |
+
H = build_auxiliary_node_connectivity(G)
|
427 |
+
R = build_residual_network(H, "capacity")
|
428 |
+
kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
|
429 |
+
|
430 |
+
# Choose a node with minimum degree.
|
431 |
+
v = min(G, key=G.degree)
|
432 |
+
# Initial node cutset is all neighbors of the node with minimum degree.
|
433 |
+
min_cut = set(G[v])
|
434 |
+
# Compute st node cuts between v and all its non-neighbors nodes in G.
|
435 |
+
for w in set(G) - set(neighbors(v)) - {v}:
|
436 |
+
this_cut = minimum_st_node_cut(G, v, w, **kwargs)
|
437 |
+
if len(min_cut) >= len(this_cut):
|
438 |
+
min_cut = this_cut
|
439 |
+
# Also for non adjacent pairs of neighbors of v.
|
440 |
+
for x, y in iter_func(neighbors(v), 2):
|
441 |
+
if y in G[x]:
|
442 |
+
continue
|
443 |
+
this_cut = minimum_st_node_cut(G, x, y, **kwargs)
|
444 |
+
if len(min_cut) >= len(this_cut):
|
445 |
+
min_cut = this_cut
|
446 |
+
|
447 |
+
return min_cut
|
448 |
+
|
449 |
+
|
450 |
+
@nx._dispatchable
|
451 |
+
def minimum_edge_cut(G, s=None, t=None, flow_func=None):
|
452 |
+
r"""Returns a set of edges of minimum cardinality that disconnects G.
|
453 |
+
|
454 |
+
If source and target nodes are provided, this function returns the
|
455 |
+
set of edges of minimum cardinality that, if removed, would break
|
456 |
+
all paths among source and target in G. If not, it returns a set of
|
457 |
+
edges of minimum cardinality that disconnects G.
|
458 |
+
|
459 |
+
Parameters
|
460 |
+
----------
|
461 |
+
G : NetworkX graph
|
462 |
+
|
463 |
+
s : node
|
464 |
+
Source node. Optional. Default value: None.
|
465 |
+
|
466 |
+
t : node
|
467 |
+
Target node. Optional. Default value: None.
|
468 |
+
|
469 |
+
flow_func : function
|
470 |
+
A function for computing the maximum flow among a pair of nodes.
|
471 |
+
The function has to accept at least three parameters: a Digraph,
|
472 |
+
a source node, and a target node. And return a residual network
|
473 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
474 |
+
details). If flow_func is None, the default maximum flow function
|
475 |
+
(:meth:`edmonds_karp`) is used. See below for details. The
|
476 |
+
choice of the default function may change from version
|
477 |
+
to version and should not be relied on. Default value: None.
|
478 |
+
|
479 |
+
Returns
|
480 |
+
-------
|
481 |
+
cutset : set
|
482 |
+
Set of edges that, if removed, would disconnect G. If source
|
483 |
+
and target nodes are provided, the set contains the edges that
|
484 |
+
if removed, would destroy all paths between source and target.
|
485 |
+
|
486 |
+
Examples
|
487 |
+
--------
|
488 |
+
>>> # Platonic icosahedral graph has edge connectivity 5
|
489 |
+
>>> G = nx.icosahedral_graph()
|
490 |
+
>>> len(nx.minimum_edge_cut(G))
|
491 |
+
5
|
492 |
+
|
493 |
+
You can use alternative flow algorithms for the underlying
|
494 |
+
maximum flow computation. In dense networks the algorithm
|
495 |
+
:meth:`shortest_augmenting_path` will usually perform better
|
496 |
+
than the default :meth:`edmonds_karp`, which is faster for
|
497 |
+
sparse networks with highly skewed degree distributions.
|
498 |
+
Alternative flow functions have to be explicitly imported
|
499 |
+
from the flow package.
|
500 |
+
|
501 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
502 |
+
>>> len(nx.minimum_edge_cut(G, flow_func=shortest_augmenting_path))
|
503 |
+
5
|
504 |
+
|
505 |
+
If you specify a pair of nodes (source and target) as parameters,
|
506 |
+
this function returns the value of local edge connectivity.
|
507 |
+
|
508 |
+
>>> nx.edge_connectivity(G, 3, 7)
|
509 |
+
5
|
510 |
+
|
511 |
+
If you need to perform several local computations among different
|
512 |
+
pairs of nodes on the same graph, it is recommended that you reuse
|
513 |
+
the data structures used in the maximum flow computations. See
|
514 |
+
:meth:`local_edge_connectivity` for details.
|
515 |
+
|
516 |
+
Notes
|
517 |
+
-----
|
518 |
+
This is a flow based implementation of minimum edge cut. For
|
519 |
+
undirected graphs the algorithm works by finding a 'small' dominating
|
520 |
+
set of nodes of G (see algorithm 7 in [1]_) and computing the maximum
|
521 |
+
flow between an arbitrary node in the dominating set and the rest of
|
522 |
+
nodes in it. This is an implementation of algorithm 6 in [1]_. For
|
523 |
+
directed graphs, the algorithm does n calls to the max flow function.
|
524 |
+
The function raises an error if the directed graph is not weakly
|
525 |
+
connected and returns an empty set if it is weakly connected.
|
526 |
+
It is an implementation of algorithm 8 in [1]_.
|
527 |
+
|
528 |
+
See also
|
529 |
+
--------
|
530 |
+
:meth:`minimum_st_edge_cut`
|
531 |
+
:meth:`minimum_node_cut`
|
532 |
+
:meth:`stoer_wagner`
|
533 |
+
:meth:`node_connectivity`
|
534 |
+
:meth:`edge_connectivity`
|
535 |
+
:meth:`maximum_flow`
|
536 |
+
:meth:`edmonds_karp`
|
537 |
+
:meth:`preflow_push`
|
538 |
+
:meth:`shortest_augmenting_path`
|
539 |
+
|
540 |
+
References
|
541 |
+
----------
|
542 |
+
.. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
|
543 |
+
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
|
544 |
+
|
545 |
+
"""
|
546 |
+
if (s is not None and t is None) or (s is None and t is not None):
|
547 |
+
raise nx.NetworkXError("Both source and target must be specified.")
|
548 |
+
|
549 |
+
# reuse auxiliary digraph and residual network
|
550 |
+
H = build_auxiliary_edge_connectivity(G)
|
551 |
+
R = build_residual_network(H, "capacity")
|
552 |
+
kwargs = {"flow_func": flow_func, "residual": R, "auxiliary": H}
|
553 |
+
|
554 |
+
# Local minimum edge cut if s and t are not None
|
555 |
+
if s is not None and t is not None:
|
556 |
+
if s not in G:
|
557 |
+
raise nx.NetworkXError(f"node {s} not in graph")
|
558 |
+
if t not in G:
|
559 |
+
raise nx.NetworkXError(f"node {t} not in graph")
|
560 |
+
return minimum_st_edge_cut(H, s, t, **kwargs)
|
561 |
+
|
562 |
+
# Global minimum edge cut
|
563 |
+
# Analog to the algorithm for global edge connectivity
|
564 |
+
if G.is_directed():
|
565 |
+
# Based on algorithm 8 in [1]
|
566 |
+
if not nx.is_weakly_connected(G):
|
567 |
+
raise nx.NetworkXError("Input graph is not connected")
|
568 |
+
|
569 |
+
# Initial cutset is all edges of a node with minimum degree
|
570 |
+
node = min(G, key=G.degree)
|
571 |
+
min_cut = set(G.edges(node))
|
572 |
+
nodes = list(G)
|
573 |
+
n = len(nodes)
|
574 |
+
for i in range(n):
|
575 |
+
try:
|
576 |
+
this_cut = minimum_st_edge_cut(H, nodes[i], nodes[i + 1], **kwargs)
|
577 |
+
if len(this_cut) <= len(min_cut):
|
578 |
+
min_cut = this_cut
|
579 |
+
except IndexError: # Last node!
|
580 |
+
this_cut = minimum_st_edge_cut(H, nodes[i], nodes[0], **kwargs)
|
581 |
+
if len(this_cut) <= len(min_cut):
|
582 |
+
min_cut = this_cut
|
583 |
+
|
584 |
+
return min_cut
|
585 |
+
|
586 |
+
else: # undirected
|
587 |
+
# Based on algorithm 6 in [1]
|
588 |
+
if not nx.is_connected(G):
|
589 |
+
raise nx.NetworkXError("Input graph is not connected")
|
590 |
+
|
591 |
+
# Initial cutset is all edges of a node with minimum degree
|
592 |
+
node = min(G, key=G.degree)
|
593 |
+
min_cut = set(G.edges(node))
|
594 |
+
# A dominating set is \lambda-covering
|
595 |
+
# We need a dominating set with at least two nodes
|
596 |
+
for node in G:
|
597 |
+
D = nx.dominating_set(G, start_with=node)
|
598 |
+
v = D.pop()
|
599 |
+
if D:
|
600 |
+
break
|
601 |
+
else:
|
602 |
+
# in complete graphs the dominating set will always be of one node
|
603 |
+
# thus we return min_cut, which now contains the edges of a node
|
604 |
+
# with minimum degree
|
605 |
+
return min_cut
|
606 |
+
for w in D:
|
607 |
+
this_cut = minimum_st_edge_cut(H, v, w, **kwargs)
|
608 |
+
if len(this_cut) <= len(min_cut):
|
609 |
+
min_cut = this_cut
|
610 |
+
|
611 |
+
return min_cut
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/disjoint_paths.py
ADDED
@@ -0,0 +1,407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Flow based node and edge disjoint paths."""
|
2 |
+
import networkx as nx
|
3 |
+
|
4 |
+
# Define the default maximum flow function to use for the underlying
|
5 |
+
# maximum flow computations
|
6 |
+
from networkx.algorithms.flow import (
|
7 |
+
edmonds_karp,
|
8 |
+
preflow_push,
|
9 |
+
shortest_augmenting_path,
|
10 |
+
)
|
11 |
+
from networkx.exception import NetworkXNoPath
|
12 |
+
|
13 |
+
default_flow_func = edmonds_karp
|
14 |
+
from itertools import filterfalse as _filterfalse
|
15 |
+
|
16 |
+
# Functions to build auxiliary data structures.
|
17 |
+
from .utils import build_auxiliary_edge_connectivity, build_auxiliary_node_connectivity
|
18 |
+
|
19 |
+
__all__ = ["edge_disjoint_paths", "node_disjoint_paths"]
|
20 |
+
|
21 |
+
|
22 |
+
@nx._dispatchable(
|
23 |
+
graphs={"G": 0, "auxiliary?": 5},
|
24 |
+
preserve_edge_attrs={"auxiliary": {"capacity": float("inf")}},
|
25 |
+
)
|
26 |
+
def edge_disjoint_paths(
|
27 |
+
G, s, t, flow_func=None, cutoff=None, auxiliary=None, residual=None
|
28 |
+
):
|
29 |
+
"""Returns the edges disjoint paths between source and target.
|
30 |
+
|
31 |
+
Edge disjoint paths are paths that do not share any edge. The
|
32 |
+
number of edge disjoint paths between source and target is equal
|
33 |
+
to their edge connectivity.
|
34 |
+
|
35 |
+
Parameters
|
36 |
+
----------
|
37 |
+
G : NetworkX graph
|
38 |
+
|
39 |
+
s : node
|
40 |
+
Source node for the flow.
|
41 |
+
|
42 |
+
t : node
|
43 |
+
Sink node for the flow.
|
44 |
+
|
45 |
+
flow_func : function
|
46 |
+
A function for computing the maximum flow among a pair of nodes.
|
47 |
+
The function has to accept at least three parameters: a Digraph,
|
48 |
+
a source node, and a target node. And return a residual network
|
49 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
50 |
+
details). If flow_func is None, the default maximum flow function
|
51 |
+
(:meth:`edmonds_karp`) is used. The choice of the default function
|
52 |
+
may change from version to version and should not be relied on.
|
53 |
+
Default value: None.
|
54 |
+
|
55 |
+
cutoff : integer or None (default: None)
|
56 |
+
Maximum number of paths to yield. If specified, the maximum flow
|
57 |
+
algorithm will terminate when the flow value reaches or exceeds the
|
58 |
+
cutoff. This only works for flows that support the cutoff parameter
|
59 |
+
(most do) and is ignored otherwise.
|
60 |
+
|
61 |
+
auxiliary : NetworkX DiGraph
|
62 |
+
Auxiliary digraph to compute flow based edge connectivity. It has
|
63 |
+
to have a graph attribute called mapping with a dictionary mapping
|
64 |
+
node names in G and in the auxiliary digraph. If provided
|
65 |
+
it will be reused instead of recreated. Default value: None.
|
66 |
+
|
67 |
+
residual : NetworkX DiGraph
|
68 |
+
Residual network to compute maximum flow. If provided it will be
|
69 |
+
reused instead of recreated. Default value: None.
|
70 |
+
|
71 |
+
Returns
|
72 |
+
-------
|
73 |
+
paths : generator
|
74 |
+
A generator of edge independent paths.
|
75 |
+
|
76 |
+
Raises
|
77 |
+
------
|
78 |
+
NetworkXNoPath
|
79 |
+
If there is no path between source and target.
|
80 |
+
|
81 |
+
NetworkXError
|
82 |
+
If source or target are not in the graph G.
|
83 |
+
|
84 |
+
See also
|
85 |
+
--------
|
86 |
+
:meth:`node_disjoint_paths`
|
87 |
+
:meth:`edge_connectivity`
|
88 |
+
:meth:`maximum_flow`
|
89 |
+
:meth:`edmonds_karp`
|
90 |
+
:meth:`preflow_push`
|
91 |
+
:meth:`shortest_augmenting_path`
|
92 |
+
|
93 |
+
Examples
|
94 |
+
--------
|
95 |
+
We use in this example the platonic icosahedral graph, which has node
|
96 |
+
edge connectivity 5, thus there are 5 edge disjoint paths between any
|
97 |
+
pair of nodes.
|
98 |
+
|
99 |
+
>>> G = nx.icosahedral_graph()
|
100 |
+
>>> len(list(nx.edge_disjoint_paths(G, 0, 6)))
|
101 |
+
5
|
102 |
+
|
103 |
+
|
104 |
+
If you need to compute edge disjoint paths on several pairs of
|
105 |
+
nodes in the same graph, it is recommended that you reuse the
|
106 |
+
data structures that NetworkX uses in the computation: the
|
107 |
+
auxiliary digraph for edge connectivity, and the residual
|
108 |
+
network for the underlying maximum flow computation.
|
109 |
+
|
110 |
+
Example of how to compute edge disjoint paths among all pairs of
|
111 |
+
nodes of the platonic icosahedral graph reusing the data
|
112 |
+
structures.
|
113 |
+
|
114 |
+
>>> import itertools
|
115 |
+
>>> # You also have to explicitly import the function for
|
116 |
+
>>> # building the auxiliary digraph from the connectivity package
|
117 |
+
>>> from networkx.algorithms.connectivity import build_auxiliary_edge_connectivity
|
118 |
+
>>> H = build_auxiliary_edge_connectivity(G)
|
119 |
+
>>> # And the function for building the residual network from the
|
120 |
+
>>> # flow package
|
121 |
+
>>> from networkx.algorithms.flow import build_residual_network
|
122 |
+
>>> # Note that the auxiliary digraph has an edge attribute named capacity
|
123 |
+
>>> R = build_residual_network(H, "capacity")
|
124 |
+
>>> result = {n: {} for n in G}
|
125 |
+
>>> # Reuse the auxiliary digraph and the residual network by passing them
|
126 |
+
>>> # as arguments
|
127 |
+
>>> for u, v in itertools.combinations(G, 2):
|
128 |
+
... k = len(list(nx.edge_disjoint_paths(G, u, v, auxiliary=H, residual=R)))
|
129 |
+
... result[u][v] = k
|
130 |
+
>>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
|
131 |
+
True
|
132 |
+
|
133 |
+
You can also use alternative flow algorithms for computing edge disjoint
|
134 |
+
paths. For instance, in dense networks the algorithm
|
135 |
+
:meth:`shortest_augmenting_path` will usually perform better than
|
136 |
+
the default :meth:`edmonds_karp` which is faster for sparse
|
137 |
+
networks with highly skewed degree distributions. Alternative flow
|
138 |
+
functions have to be explicitly imported from the flow package.
|
139 |
+
|
140 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
141 |
+
>>> len(list(nx.edge_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path)))
|
142 |
+
5
|
143 |
+
|
144 |
+
Notes
|
145 |
+
-----
|
146 |
+
This is a flow based implementation of edge disjoint paths. We compute
|
147 |
+
the maximum flow between source and target on an auxiliary directed
|
148 |
+
network. The saturated edges in the residual network after running the
|
149 |
+
maximum flow algorithm correspond to edge disjoint paths between source
|
150 |
+
and target in the original network. This function handles both directed
|
151 |
+
and undirected graphs, and can use all flow algorithms from NetworkX flow
|
152 |
+
package.
|
153 |
+
|
154 |
+
"""
|
155 |
+
if s not in G:
|
156 |
+
raise nx.NetworkXError(f"node {s} not in graph")
|
157 |
+
if t not in G:
|
158 |
+
raise nx.NetworkXError(f"node {t} not in graph")
|
159 |
+
|
160 |
+
if flow_func is None:
|
161 |
+
flow_func = default_flow_func
|
162 |
+
|
163 |
+
if auxiliary is None:
|
164 |
+
H = build_auxiliary_edge_connectivity(G)
|
165 |
+
else:
|
166 |
+
H = auxiliary
|
167 |
+
|
168 |
+
# Maximum possible edge disjoint paths
|
169 |
+
possible = min(H.out_degree(s), H.in_degree(t))
|
170 |
+
if not possible:
|
171 |
+
raise NetworkXNoPath
|
172 |
+
|
173 |
+
if cutoff is None:
|
174 |
+
cutoff = possible
|
175 |
+
else:
|
176 |
+
cutoff = min(cutoff, possible)
|
177 |
+
|
178 |
+
# Compute maximum flow between source and target. Flow functions in
|
179 |
+
# NetworkX return a residual network.
|
180 |
+
kwargs = {
|
181 |
+
"capacity": "capacity",
|
182 |
+
"residual": residual,
|
183 |
+
"cutoff": cutoff,
|
184 |
+
"value_only": True,
|
185 |
+
}
|
186 |
+
if flow_func is preflow_push:
|
187 |
+
del kwargs["cutoff"]
|
188 |
+
if flow_func is shortest_augmenting_path:
|
189 |
+
kwargs["two_phase"] = True
|
190 |
+
R = flow_func(H, s, t, **kwargs)
|
191 |
+
|
192 |
+
if R.graph["flow_value"] == 0:
|
193 |
+
raise NetworkXNoPath
|
194 |
+
|
195 |
+
# Saturated edges in the residual network form the edge disjoint paths
|
196 |
+
# between source and target
|
197 |
+
cutset = [
|
198 |
+
(u, v)
|
199 |
+
for u, v, d in R.edges(data=True)
|
200 |
+
if d["capacity"] == d["flow"] and d["flow"] > 0
|
201 |
+
]
|
202 |
+
# This is equivalent of what flow.utils.build_flow_dict returns, but
|
203 |
+
# only for the nodes with saturated edges and without reporting 0 flows.
|
204 |
+
flow_dict = {n: {} for edge in cutset for n in edge}
|
205 |
+
for u, v in cutset:
|
206 |
+
flow_dict[u][v] = 1
|
207 |
+
|
208 |
+
# Rebuild the edge disjoint paths from the flow dictionary.
|
209 |
+
paths_found = 0
|
210 |
+
for v in list(flow_dict[s]):
|
211 |
+
if paths_found >= cutoff:
|
212 |
+
# preflow_push does not support cutoff: we have to
|
213 |
+
# keep track of the paths founds and stop at cutoff.
|
214 |
+
break
|
215 |
+
path = [s]
|
216 |
+
if v == t:
|
217 |
+
path.append(v)
|
218 |
+
yield path
|
219 |
+
continue
|
220 |
+
u = v
|
221 |
+
while u != t:
|
222 |
+
path.append(u)
|
223 |
+
try:
|
224 |
+
u, _ = flow_dict[u].popitem()
|
225 |
+
except KeyError:
|
226 |
+
break
|
227 |
+
else:
|
228 |
+
path.append(t)
|
229 |
+
yield path
|
230 |
+
paths_found += 1
|
231 |
+
|
232 |
+
|
233 |
+
@nx._dispatchable(
|
234 |
+
graphs={"G": 0, "auxiliary?": 5},
|
235 |
+
preserve_node_attrs={"auxiliary": {"id": None}},
|
236 |
+
preserve_graph_attrs={"auxiliary"},
|
237 |
+
)
|
238 |
+
def node_disjoint_paths(
|
239 |
+
G, s, t, flow_func=None, cutoff=None, auxiliary=None, residual=None
|
240 |
+
):
|
241 |
+
r"""Computes node disjoint paths between source and target.
|
242 |
+
|
243 |
+
Node disjoint paths are paths that only share their first and last
|
244 |
+
nodes. The number of node independent paths between two nodes is
|
245 |
+
equal to their local node connectivity.
|
246 |
+
|
247 |
+
Parameters
|
248 |
+
----------
|
249 |
+
G : NetworkX graph
|
250 |
+
|
251 |
+
s : node
|
252 |
+
Source node.
|
253 |
+
|
254 |
+
t : node
|
255 |
+
Target node.
|
256 |
+
|
257 |
+
flow_func : function
|
258 |
+
A function for computing the maximum flow among a pair of nodes.
|
259 |
+
The function has to accept at least three parameters: a Digraph,
|
260 |
+
a source node, and a target node. And return a residual network
|
261 |
+
that follows NetworkX conventions (see :meth:`maximum_flow` for
|
262 |
+
details). If flow_func is None, the default maximum flow function
|
263 |
+
(:meth:`edmonds_karp`) is used. See below for details. The choice
|
264 |
+
of the default function may change from version to version and
|
265 |
+
should not be relied on. Default value: None.
|
266 |
+
|
267 |
+
cutoff : integer or None (default: None)
|
268 |
+
Maximum number of paths to yield. If specified, the maximum flow
|
269 |
+
algorithm will terminate when the flow value reaches or exceeds the
|
270 |
+
cutoff. This only works for flows that support the cutoff parameter
|
271 |
+
(most do) and is ignored otherwise.
|
272 |
+
|
273 |
+
auxiliary : NetworkX DiGraph
|
274 |
+
Auxiliary digraph to compute flow based node connectivity. It has
|
275 |
+
to have a graph attribute called mapping with a dictionary mapping
|
276 |
+
node names in G and in the auxiliary digraph. If provided
|
277 |
+
it will be reused instead of recreated. Default value: None.
|
278 |
+
|
279 |
+
residual : NetworkX DiGraph
|
280 |
+
Residual network to compute maximum flow. If provided it will be
|
281 |
+
reused instead of recreated. Default value: None.
|
282 |
+
|
283 |
+
Returns
|
284 |
+
-------
|
285 |
+
paths : generator
|
286 |
+
Generator of node disjoint paths.
|
287 |
+
|
288 |
+
Raises
|
289 |
+
------
|
290 |
+
NetworkXNoPath
|
291 |
+
If there is no path between source and target.
|
292 |
+
|
293 |
+
NetworkXError
|
294 |
+
If source or target are not in the graph G.
|
295 |
+
|
296 |
+
Examples
|
297 |
+
--------
|
298 |
+
We use in this example the platonic icosahedral graph, which has node
|
299 |
+
connectivity 5, thus there are 5 node disjoint paths between any pair
|
300 |
+
of non neighbor nodes.
|
301 |
+
|
302 |
+
>>> G = nx.icosahedral_graph()
|
303 |
+
>>> len(list(nx.node_disjoint_paths(G, 0, 6)))
|
304 |
+
5
|
305 |
+
|
306 |
+
If you need to compute node disjoint paths between several pairs of
|
307 |
+
nodes in the same graph, it is recommended that you reuse the
|
308 |
+
data structures that NetworkX uses in the computation: the
|
309 |
+
auxiliary digraph for node connectivity and node cuts, and the
|
310 |
+
residual network for the underlying maximum flow computation.
|
311 |
+
|
312 |
+
Example of how to compute node disjoint paths reusing the data
|
313 |
+
structures:
|
314 |
+
|
315 |
+
>>> # You also have to explicitly import the function for
|
316 |
+
>>> # building the auxiliary digraph from the connectivity package
|
317 |
+
>>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity
|
318 |
+
>>> H = build_auxiliary_node_connectivity(G)
|
319 |
+
>>> # And the function for building the residual network from the
|
320 |
+
>>> # flow package
|
321 |
+
>>> from networkx.algorithms.flow import build_residual_network
|
322 |
+
>>> # Note that the auxiliary digraph has an edge attribute named capacity
|
323 |
+
>>> R = build_residual_network(H, "capacity")
|
324 |
+
>>> # Reuse the auxiliary digraph and the residual network by passing them
|
325 |
+
>>> # as arguments
|
326 |
+
>>> len(list(nx.node_disjoint_paths(G, 0, 6, auxiliary=H, residual=R)))
|
327 |
+
5
|
328 |
+
|
329 |
+
You can also use alternative flow algorithms for computing node disjoint
|
330 |
+
paths. For instance, in dense networks the algorithm
|
331 |
+
:meth:`shortest_augmenting_path` will usually perform better than
|
332 |
+
the default :meth:`edmonds_karp` which is faster for sparse
|
333 |
+
networks with highly skewed degree distributions. Alternative flow
|
334 |
+
functions have to be explicitly imported from the flow package.
|
335 |
+
|
336 |
+
>>> from networkx.algorithms.flow import shortest_augmenting_path
|
337 |
+
>>> len(list(nx.node_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path)))
|
338 |
+
5
|
339 |
+
|
340 |
+
Notes
|
341 |
+
-----
|
342 |
+
This is a flow based implementation of node disjoint paths. We compute
|
343 |
+
the maximum flow between source and target on an auxiliary directed
|
344 |
+
network. The saturated edges in the residual network after running the
|
345 |
+
maximum flow algorithm correspond to node disjoint paths between source
|
346 |
+
and target in the original network. This function handles both directed
|
347 |
+
and undirected graphs, and can use all flow algorithms from NetworkX flow
|
348 |
+
package.
|
349 |
+
|
350 |
+
See also
|
351 |
+
--------
|
352 |
+
:meth:`edge_disjoint_paths`
|
353 |
+
:meth:`node_connectivity`
|
354 |
+
:meth:`maximum_flow`
|
355 |
+
:meth:`edmonds_karp`
|
356 |
+
:meth:`preflow_push`
|
357 |
+
:meth:`shortest_augmenting_path`
|
358 |
+
|
359 |
+
"""
|
360 |
+
if s not in G:
|
361 |
+
raise nx.NetworkXError(f"node {s} not in graph")
|
362 |
+
if t not in G:
|
363 |
+
raise nx.NetworkXError(f"node {t} not in graph")
|
364 |
+
|
365 |
+
if auxiliary is None:
|
366 |
+
H = build_auxiliary_node_connectivity(G)
|
367 |
+
else:
|
368 |
+
H = auxiliary
|
369 |
+
|
370 |
+
mapping = H.graph.get("mapping", None)
|
371 |
+
if mapping is None:
|
372 |
+
raise nx.NetworkXError("Invalid auxiliary digraph.")
|
373 |
+
|
374 |
+
# Maximum possible edge disjoint paths
|
375 |
+
possible = min(H.out_degree(f"{mapping[s]}B"), H.in_degree(f"{mapping[t]}A"))
|
376 |
+
if not possible:
|
377 |
+
raise NetworkXNoPath
|
378 |
+
|
379 |
+
if cutoff is None:
|
380 |
+
cutoff = possible
|
381 |
+
else:
|
382 |
+
cutoff = min(cutoff, possible)
|
383 |
+
|
384 |
+
kwargs = {
|
385 |
+
"flow_func": flow_func,
|
386 |
+
"residual": residual,
|
387 |
+
"auxiliary": H,
|
388 |
+
"cutoff": cutoff,
|
389 |
+
}
|
390 |
+
|
391 |
+
# The edge disjoint paths in the auxiliary digraph correspond to the node
|
392 |
+
# disjoint paths in the original graph.
|
393 |
+
paths_edges = edge_disjoint_paths(H, f"{mapping[s]}B", f"{mapping[t]}A", **kwargs)
|
394 |
+
for path in paths_edges:
|
395 |
+
# Each node in the original graph maps to two nodes in auxiliary graph
|
396 |
+
yield list(_unique_everseen(H.nodes[node]["id"] for node in path))
|
397 |
+
|
398 |
+
|
399 |
+
def _unique_everseen(iterable):
|
400 |
+
# Adapted from https://docs.python.org/3/library/itertools.html examples
|
401 |
+
"List unique elements, preserving order. Remember all elements ever seen."
|
402 |
+
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
|
403 |
+
seen = set()
|
404 |
+
seen_add = seen.add
|
405 |
+
for element in _filterfalse(seen.__contains__, iterable):
|
406 |
+
seen_add(element)
|
407 |
+
yield element
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_augmentation.py
ADDED
@@ -0,0 +1,1269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Algorithms for finding k-edge-augmentations
|
3 |
+
|
4 |
+
A k-edge-augmentation is a set of edges, that once added to a graph, ensures
|
5 |
+
that the graph is k-edge-connected; i.e. the graph cannot be disconnected
|
6 |
+
unless k or more edges are removed. Typically, the goal is to find the
|
7 |
+
augmentation with minimum weight. In general, it is not guaranteed that a
|
8 |
+
k-edge-augmentation exists.
|
9 |
+
|
10 |
+
See Also
|
11 |
+
--------
|
12 |
+
:mod:`edge_kcomponents` : algorithms for finding k-edge-connected components
|
13 |
+
:mod:`connectivity` : algorithms for determining edge connectivity.
|
14 |
+
"""
|
15 |
+
import itertools as it
|
16 |
+
import math
|
17 |
+
from collections import defaultdict, namedtuple
|
18 |
+
|
19 |
+
import networkx as nx
|
20 |
+
from networkx.utils import not_implemented_for, py_random_state
|
21 |
+
|
22 |
+
__all__ = ["k_edge_augmentation", "is_k_edge_connected", "is_locally_k_edge_connected"]
|
23 |
+
|
24 |
+
|
25 |
+
@not_implemented_for("directed")
|
26 |
+
@not_implemented_for("multigraph")
|
27 |
+
@nx._dispatchable
|
28 |
+
def is_k_edge_connected(G, k):
|
29 |
+
"""Tests to see if a graph is k-edge-connected.
|
30 |
+
|
31 |
+
Is it impossible to disconnect the graph by removing fewer than k edges?
|
32 |
+
If so, then G is k-edge-connected.
|
33 |
+
|
34 |
+
Parameters
|
35 |
+
----------
|
36 |
+
G : NetworkX graph
|
37 |
+
An undirected graph.
|
38 |
+
|
39 |
+
k : integer
|
40 |
+
edge connectivity to test for
|
41 |
+
|
42 |
+
Returns
|
43 |
+
-------
|
44 |
+
boolean
|
45 |
+
True if G is k-edge-connected.
|
46 |
+
|
47 |
+
See Also
|
48 |
+
--------
|
49 |
+
:func:`is_locally_k_edge_connected`
|
50 |
+
|
51 |
+
Examples
|
52 |
+
--------
|
53 |
+
>>> G = nx.barbell_graph(10, 0)
|
54 |
+
>>> nx.is_k_edge_connected(G, k=1)
|
55 |
+
True
|
56 |
+
>>> nx.is_k_edge_connected(G, k=2)
|
57 |
+
False
|
58 |
+
"""
|
59 |
+
if k < 1:
|
60 |
+
raise ValueError(f"k must be positive, not {k}")
|
61 |
+
# First try to quickly determine if G is not k-edge-connected
|
62 |
+
if G.number_of_nodes() < k + 1:
|
63 |
+
return False
|
64 |
+
elif any(d < k for n, d in G.degree()):
|
65 |
+
return False
|
66 |
+
else:
|
67 |
+
# Otherwise perform the full check
|
68 |
+
if k == 1:
|
69 |
+
return nx.is_connected(G)
|
70 |
+
elif k == 2:
|
71 |
+
return nx.is_connected(G) and not nx.has_bridges(G)
|
72 |
+
else:
|
73 |
+
return nx.edge_connectivity(G, cutoff=k) >= k
|
74 |
+
|
75 |
+
|
76 |
+
@not_implemented_for("directed")
|
77 |
+
@not_implemented_for("multigraph")
|
78 |
+
@nx._dispatchable
|
79 |
+
def is_locally_k_edge_connected(G, s, t, k):
|
80 |
+
"""Tests to see if an edge in a graph is locally k-edge-connected.
|
81 |
+
|
82 |
+
Is it impossible to disconnect s and t by removing fewer than k edges?
|
83 |
+
If so, then s and t are locally k-edge-connected in G.
|
84 |
+
|
85 |
+
Parameters
|
86 |
+
----------
|
87 |
+
G : NetworkX graph
|
88 |
+
An undirected graph.
|
89 |
+
|
90 |
+
s : node
|
91 |
+
Source node
|
92 |
+
|
93 |
+
t : node
|
94 |
+
Target node
|
95 |
+
|
96 |
+
k : integer
|
97 |
+
local edge connectivity for nodes s and t
|
98 |
+
|
99 |
+
Returns
|
100 |
+
-------
|
101 |
+
boolean
|
102 |
+
True if s and t are locally k-edge-connected in G.
|
103 |
+
|
104 |
+
See Also
|
105 |
+
--------
|
106 |
+
:func:`is_k_edge_connected`
|
107 |
+
|
108 |
+
Examples
|
109 |
+
--------
|
110 |
+
>>> from networkx.algorithms.connectivity import is_locally_k_edge_connected
|
111 |
+
>>> G = nx.barbell_graph(10, 0)
|
112 |
+
>>> is_locally_k_edge_connected(G, 5, 15, k=1)
|
113 |
+
True
|
114 |
+
>>> is_locally_k_edge_connected(G, 5, 15, k=2)
|
115 |
+
False
|
116 |
+
>>> is_locally_k_edge_connected(G, 1, 5, k=2)
|
117 |
+
True
|
118 |
+
"""
|
119 |
+
if k < 1:
|
120 |
+
raise ValueError(f"k must be positive, not {k}")
|
121 |
+
|
122 |
+
# First try to quickly determine s, t is not k-locally-edge-connected in G
|
123 |
+
if G.degree(s) < k or G.degree(t) < k:
|
124 |
+
return False
|
125 |
+
else:
|
126 |
+
# Otherwise perform the full check
|
127 |
+
if k == 1:
|
128 |
+
return nx.has_path(G, s, t)
|
129 |
+
else:
|
130 |
+
localk = nx.connectivity.local_edge_connectivity(G, s, t, cutoff=k)
|
131 |
+
return localk >= k
|
132 |
+
|
133 |
+
|
134 |
+
@not_implemented_for("directed")
|
135 |
+
@not_implemented_for("multigraph")
|
136 |
+
@nx._dispatchable
|
137 |
+
def k_edge_augmentation(G, k, avail=None, weight=None, partial=False):
|
138 |
+
"""Finds set of edges to k-edge-connect G.
|
139 |
+
|
140 |
+
Adding edges from the augmentation to G make it impossible to disconnect G
|
141 |
+
unless k or more edges are removed. This function uses the most efficient
|
142 |
+
function available (depending on the value of k and if the problem is
|
143 |
+
weighted or unweighted) to search for a minimum weight subset of available
|
144 |
+
edges that k-edge-connects G. In general, finding a k-edge-augmentation is
|
145 |
+
NP-hard, so solutions are not guaranteed to be minimal. Furthermore, a
|
146 |
+
k-edge-augmentation may not exist.
|
147 |
+
|
148 |
+
Parameters
|
149 |
+
----------
|
150 |
+
G : NetworkX graph
|
151 |
+
An undirected graph.
|
152 |
+
|
153 |
+
k : integer
|
154 |
+
Desired edge connectivity
|
155 |
+
|
156 |
+
avail : dict or a set of 2 or 3 tuples
|
157 |
+
The available edges that can be used in the augmentation.
|
158 |
+
|
159 |
+
If unspecified, then all edges in the complement of G are available.
|
160 |
+
Otherwise, each item is an available edge (with an optional weight).
|
161 |
+
|
162 |
+
In the unweighted case, each item is an edge ``(u, v)``.
|
163 |
+
|
164 |
+
In the weighted case, each item is a 3-tuple ``(u, v, d)`` or a dict
|
165 |
+
with items ``(u, v): d``. The third item, ``d``, can be a dictionary
|
166 |
+
or a real number. If ``d`` is a dictionary ``d[weight]``
|
167 |
+
correspondings to the weight.
|
168 |
+
|
169 |
+
weight : string
|
170 |
+
key to use to find weights if ``avail`` is a set of 3-tuples where the
|
171 |
+
third item in each tuple is a dictionary.
|
172 |
+
|
173 |
+
partial : boolean
|
174 |
+
If partial is True and no feasible k-edge-augmentation exists, then all
|
175 |
+
a partial k-edge-augmentation is generated. Adding the edges in a
|
176 |
+
partial augmentation to G, minimizes the number of k-edge-connected
|
177 |
+
components and maximizes the edge connectivity between those
|
178 |
+
components. For details, see :func:`partial_k_edge_augmentation`.
|
179 |
+
|
180 |
+
Yields
|
181 |
+
------
|
182 |
+
edge : tuple
|
183 |
+
Edges that, once added to G, would cause G to become k-edge-connected.
|
184 |
+
If partial is False, an error is raised if this is not possible.
|
185 |
+
Otherwise, generated edges form a partial augmentation, which
|
186 |
+
k-edge-connects any part of G where it is possible, and maximally
|
187 |
+
connects the remaining parts.
|
188 |
+
|
189 |
+
Raises
|
190 |
+
------
|
191 |
+
NetworkXUnfeasible
|
192 |
+
If partial is False and no k-edge-augmentation exists.
|
193 |
+
|
194 |
+
NetworkXNotImplemented
|
195 |
+
If the input graph is directed or a multigraph.
|
196 |
+
|
197 |
+
ValueError:
|
198 |
+
If k is less than 1
|
199 |
+
|
200 |
+
Notes
|
201 |
+
-----
|
202 |
+
When k=1 this returns an optimal solution.
|
203 |
+
|
204 |
+
When k=2 and ``avail`` is None, this returns an optimal solution.
|
205 |
+
Otherwise when k=2, this returns a 2-approximation of the optimal solution.
|
206 |
+
|
207 |
+
For k>3, this problem is NP-hard and this uses a randomized algorithm that
|
208 |
+
produces a feasible solution, but provides no guarantees on the
|
209 |
+
solution weight.
|
210 |
+
|
211 |
+
Examples
|
212 |
+
--------
|
213 |
+
>>> # Unweighted cases
|
214 |
+
>>> G = nx.path_graph((1, 2, 3, 4))
|
215 |
+
>>> G.add_node(5)
|
216 |
+
>>> sorted(nx.k_edge_augmentation(G, k=1))
|
217 |
+
[(1, 5)]
|
218 |
+
>>> sorted(nx.k_edge_augmentation(G, k=2))
|
219 |
+
[(1, 5), (5, 4)]
|
220 |
+
>>> sorted(nx.k_edge_augmentation(G, k=3))
|
221 |
+
[(1, 4), (1, 5), (2, 5), (3, 5), (4, 5)]
|
222 |
+
>>> complement = list(nx.k_edge_augmentation(G, k=5, partial=True))
|
223 |
+
>>> G.add_edges_from(complement)
|
224 |
+
>>> nx.edge_connectivity(G)
|
225 |
+
4
|
226 |
+
|
227 |
+
>>> # Weighted cases
|
228 |
+
>>> G = nx.path_graph((1, 2, 3, 4))
|
229 |
+
>>> G.add_node(5)
|
230 |
+
>>> # avail can be a tuple with a dict
|
231 |
+
>>> avail = [(1, 5, {"weight": 11}), (2, 5, {"weight": 10})]
|
232 |
+
>>> sorted(nx.k_edge_augmentation(G, k=1, avail=avail, weight="weight"))
|
233 |
+
[(2, 5)]
|
234 |
+
>>> # or avail can be a 3-tuple with a real number
|
235 |
+
>>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 51)]
|
236 |
+
>>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
|
237 |
+
[(1, 5), (2, 5), (4, 5)]
|
238 |
+
>>> # or avail can be a dict
|
239 |
+
>>> avail = {(1, 5): 11, (2, 5): 10, (4, 3): 1, (4, 5): 51}
|
240 |
+
>>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
|
241 |
+
[(1, 5), (2, 5), (4, 5)]
|
242 |
+
>>> # If augmentation is infeasible, then a partial solution can be found
|
243 |
+
>>> avail = {(1, 5): 11}
|
244 |
+
>>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail, partial=True))
|
245 |
+
[(1, 5)]
|
246 |
+
"""
|
247 |
+
try:
|
248 |
+
if k <= 0:
|
249 |
+
raise ValueError(f"k must be a positive integer, not {k}")
|
250 |
+
elif G.number_of_nodes() < k + 1:
|
251 |
+
msg = f"impossible to {k} connect in graph with less than {k + 1} nodes"
|
252 |
+
raise nx.NetworkXUnfeasible(msg)
|
253 |
+
elif avail is not None and len(avail) == 0:
|
254 |
+
if not nx.is_k_edge_connected(G, k):
|
255 |
+
raise nx.NetworkXUnfeasible("no available edges")
|
256 |
+
aug_edges = []
|
257 |
+
elif k == 1:
|
258 |
+
aug_edges = one_edge_augmentation(
|
259 |
+
G, avail=avail, weight=weight, partial=partial
|
260 |
+
)
|
261 |
+
elif k == 2:
|
262 |
+
aug_edges = bridge_augmentation(G, avail=avail, weight=weight)
|
263 |
+
else:
|
264 |
+
# raise NotImplementedError(f'not implemented for k>2. k={k}')
|
265 |
+
aug_edges = greedy_k_edge_augmentation(
|
266 |
+
G, k=k, avail=avail, weight=weight, seed=0
|
267 |
+
)
|
268 |
+
# Do eager evaluation so we can catch any exceptions
|
269 |
+
# Before executing partial code.
|
270 |
+
yield from list(aug_edges)
|
271 |
+
except nx.NetworkXUnfeasible:
|
272 |
+
if partial:
|
273 |
+
# Return all available edges
|
274 |
+
if avail is None:
|
275 |
+
aug_edges = complement_edges(G)
|
276 |
+
else:
|
277 |
+
# If we can't k-edge-connect the entire graph, try to
|
278 |
+
# k-edge-connect as much as possible
|
279 |
+
aug_edges = partial_k_edge_augmentation(
|
280 |
+
G, k=k, avail=avail, weight=weight
|
281 |
+
)
|
282 |
+
yield from aug_edges
|
283 |
+
else:
|
284 |
+
raise
|
285 |
+
|
286 |
+
|
287 |
+
@nx._dispatchable
|
288 |
+
def partial_k_edge_augmentation(G, k, avail, weight=None):
|
289 |
+
"""Finds augmentation that k-edge-connects as much of the graph as possible.
|
290 |
+
|
291 |
+
When a k-edge-augmentation is not possible, we can still try to find a
|
292 |
+
small set of edges that partially k-edge-connects as much of the graph as
|
293 |
+
possible. All possible edges are generated between remaining parts.
|
294 |
+
This minimizes the number of k-edge-connected subgraphs in the resulting
|
295 |
+
graph and maximizes the edge connectivity between those subgraphs.
|
296 |
+
|
297 |
+
Parameters
|
298 |
+
----------
|
299 |
+
G : NetworkX graph
|
300 |
+
An undirected graph.
|
301 |
+
|
302 |
+
k : integer
|
303 |
+
Desired edge connectivity
|
304 |
+
|
305 |
+
avail : dict or a set of 2 or 3 tuples
|
306 |
+
For more details, see :func:`k_edge_augmentation`.
|
307 |
+
|
308 |
+
weight : string
|
309 |
+
key to use to find weights if ``avail`` is a set of 3-tuples.
|
310 |
+
For more details, see :func:`k_edge_augmentation`.
|
311 |
+
|
312 |
+
Yields
|
313 |
+
------
|
314 |
+
edge : tuple
|
315 |
+
Edges in the partial augmentation of G. These edges k-edge-connect any
|
316 |
+
part of G where it is possible, and maximally connects the remaining
|
317 |
+
parts. In other words, all edges from avail are generated except for
|
318 |
+
those within subgraphs that have already become k-edge-connected.
|
319 |
+
|
320 |
+
Notes
|
321 |
+
-----
|
322 |
+
Construct H that augments G with all edges in avail.
|
323 |
+
Find the k-edge-subgraphs of H.
|
324 |
+
For each k-edge-subgraph, if the number of nodes is more than k, then find
|
325 |
+
the k-edge-augmentation of that graph and add it to the solution. Then add
|
326 |
+
all edges in avail between k-edge subgraphs to the solution.
|
327 |
+
|
328 |
+
See Also
|
329 |
+
--------
|
330 |
+
:func:`k_edge_augmentation`
|
331 |
+
|
332 |
+
Examples
|
333 |
+
--------
|
334 |
+
>>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
|
335 |
+
>>> G.add_node(8)
|
336 |
+
>>> avail = [(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5), (1, 8)]
|
337 |
+
>>> sorted(partial_k_edge_augmentation(G, k=2, avail=avail))
|
338 |
+
[(1, 5), (1, 8)]
|
339 |
+
"""
|
340 |
+
|
341 |
+
def _edges_between_disjoint(H, only1, only2):
|
342 |
+
"""finds edges between disjoint nodes"""
|
343 |
+
only1_adj = {u: set(H.adj[u]) for u in only1}
|
344 |
+
for u, neighbs in only1_adj.items():
|
345 |
+
# Find the neighbors of u in only1 that are also in only2
|
346 |
+
neighbs12 = neighbs.intersection(only2)
|
347 |
+
for v in neighbs12:
|
348 |
+
yield (u, v)
|
349 |
+
|
350 |
+
avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
|
351 |
+
|
352 |
+
# Find which parts of the graph can be k-edge-connected
|
353 |
+
H = G.copy()
|
354 |
+
H.add_edges_from(
|
355 |
+
(
|
356 |
+
(u, v, {"weight": w, "generator": (u, v)})
|
357 |
+
for (u, v), w in zip(avail, avail_w)
|
358 |
+
)
|
359 |
+
)
|
360 |
+
k_edge_subgraphs = list(nx.k_edge_subgraphs(H, k=k))
|
361 |
+
|
362 |
+
# Generate edges to k-edge-connect internal subgraphs
|
363 |
+
for nodes in k_edge_subgraphs:
|
364 |
+
if len(nodes) > 1:
|
365 |
+
# Get the k-edge-connected subgraph
|
366 |
+
C = H.subgraph(nodes).copy()
|
367 |
+
# Find the internal edges that were available
|
368 |
+
sub_avail = {
|
369 |
+
d["generator"]: d["weight"]
|
370 |
+
for (u, v, d) in C.edges(data=True)
|
371 |
+
if "generator" in d
|
372 |
+
}
|
373 |
+
# Remove potential augmenting edges
|
374 |
+
C.remove_edges_from(sub_avail.keys())
|
375 |
+
# Find a subset of these edges that makes the component
|
376 |
+
# k-edge-connected and ignore the rest
|
377 |
+
yield from nx.k_edge_augmentation(C, k=k, avail=sub_avail)
|
378 |
+
|
379 |
+
# Generate all edges between CCs that could not be k-edge-connected
|
380 |
+
for cc1, cc2 in it.combinations(k_edge_subgraphs, 2):
|
381 |
+
for u, v in _edges_between_disjoint(H, cc1, cc2):
|
382 |
+
d = H.get_edge_data(u, v)
|
383 |
+
edge = d.get("generator", None)
|
384 |
+
if edge is not None:
|
385 |
+
yield edge
|
386 |
+
|
387 |
+
|
388 |
+
@not_implemented_for("multigraph")
|
389 |
+
@not_implemented_for("directed")
|
390 |
+
@nx._dispatchable
|
391 |
+
def one_edge_augmentation(G, avail=None, weight=None, partial=False):
|
392 |
+
"""Finds minimum weight set of edges to connect G.
|
393 |
+
|
394 |
+
Equivalent to :func:`k_edge_augmentation` when k=1. Adding the resulting
|
395 |
+
edges to G will make it 1-edge-connected. The solution is optimal for both
|
396 |
+
weighted and non-weighted variants.
|
397 |
+
|
398 |
+
Parameters
|
399 |
+
----------
|
400 |
+
G : NetworkX graph
|
401 |
+
An undirected graph.
|
402 |
+
|
403 |
+
avail : dict or a set of 2 or 3 tuples
|
404 |
+
For more details, see :func:`k_edge_augmentation`.
|
405 |
+
|
406 |
+
weight : string
|
407 |
+
key to use to find weights if ``avail`` is a set of 3-tuples.
|
408 |
+
For more details, see :func:`k_edge_augmentation`.
|
409 |
+
|
410 |
+
partial : boolean
|
411 |
+
If partial is True and no feasible k-edge-augmentation exists, then the
|
412 |
+
augmenting edges minimize the number of connected components.
|
413 |
+
|
414 |
+
Yields
|
415 |
+
------
|
416 |
+
edge : tuple
|
417 |
+
Edges in the one-augmentation of G
|
418 |
+
|
419 |
+
Raises
|
420 |
+
------
|
421 |
+
NetworkXUnfeasible
|
422 |
+
If partial is False and no one-edge-augmentation exists.
|
423 |
+
|
424 |
+
Notes
|
425 |
+
-----
|
426 |
+
Uses either :func:`unconstrained_one_edge_augmentation` or
|
427 |
+
:func:`weighted_one_edge_augmentation` depending on whether ``avail`` is
|
428 |
+
specified. Both algorithms are based on finding a minimum spanning tree.
|
429 |
+
As such both algorithms find optimal solutions and run in linear time.
|
430 |
+
|
431 |
+
See Also
|
432 |
+
--------
|
433 |
+
:func:`k_edge_augmentation`
|
434 |
+
"""
|
435 |
+
if avail is None:
|
436 |
+
return unconstrained_one_edge_augmentation(G)
|
437 |
+
else:
|
438 |
+
return weighted_one_edge_augmentation(
|
439 |
+
G, avail=avail, weight=weight, partial=partial
|
440 |
+
)
|
441 |
+
|
442 |
+
|
443 |
+
@not_implemented_for("multigraph")
|
444 |
+
@not_implemented_for("directed")
|
445 |
+
@nx._dispatchable
|
446 |
+
def bridge_augmentation(G, avail=None, weight=None):
|
447 |
+
"""Finds the a set of edges that bridge connects G.
|
448 |
+
|
449 |
+
Equivalent to :func:`k_edge_augmentation` when k=2, and partial=False.
|
450 |
+
Adding the resulting edges to G will make it 2-edge-connected. If no
|
451 |
+
constraints are specified the returned set of edges is minimum an optimal,
|
452 |
+
otherwise the solution is approximated.
|
453 |
+
|
454 |
+
Parameters
|
455 |
+
----------
|
456 |
+
G : NetworkX graph
|
457 |
+
An undirected graph.
|
458 |
+
|
459 |
+
avail : dict or a set of 2 or 3 tuples
|
460 |
+
For more details, see :func:`k_edge_augmentation`.
|
461 |
+
|
462 |
+
weight : string
|
463 |
+
key to use to find weights if ``avail`` is a set of 3-tuples.
|
464 |
+
For more details, see :func:`k_edge_augmentation`.
|
465 |
+
|
466 |
+
Yields
|
467 |
+
------
|
468 |
+
edge : tuple
|
469 |
+
Edges in the bridge-augmentation of G
|
470 |
+
|
471 |
+
Raises
|
472 |
+
------
|
473 |
+
NetworkXUnfeasible
|
474 |
+
If no bridge-augmentation exists.
|
475 |
+
|
476 |
+
Notes
|
477 |
+
-----
|
478 |
+
If there are no constraints the solution can be computed in linear time
|
479 |
+
using :func:`unconstrained_bridge_augmentation`. Otherwise, the problem
|
480 |
+
becomes NP-hard and is the solution is approximated by
|
481 |
+
:func:`weighted_bridge_augmentation`.
|
482 |
+
|
483 |
+
See Also
|
484 |
+
--------
|
485 |
+
:func:`k_edge_augmentation`
|
486 |
+
"""
|
487 |
+
if G.number_of_nodes() < 3:
|
488 |
+
raise nx.NetworkXUnfeasible("impossible to bridge connect less than 3 nodes")
|
489 |
+
if avail is None:
|
490 |
+
return unconstrained_bridge_augmentation(G)
|
491 |
+
else:
|
492 |
+
return weighted_bridge_augmentation(G, avail, weight=weight)
|
493 |
+
|
494 |
+
|
495 |
+
# --- Algorithms and Helpers ---
|
496 |
+
|
497 |
+
|
498 |
+
def _ordered(u, v):
|
499 |
+
"""Returns the nodes in an undirected edge in lower-triangular order"""
|
500 |
+
return (u, v) if u < v else (v, u)
|
501 |
+
|
502 |
+
|
503 |
+
def _unpack_available_edges(avail, weight=None, G=None):
|
504 |
+
"""Helper to separate avail into edges and corresponding weights"""
|
505 |
+
if weight is None:
|
506 |
+
weight = "weight"
|
507 |
+
if isinstance(avail, dict):
|
508 |
+
avail_uv = list(avail.keys())
|
509 |
+
avail_w = list(avail.values())
|
510 |
+
else:
|
511 |
+
|
512 |
+
def _try_getitem(d):
|
513 |
+
try:
|
514 |
+
return d[weight]
|
515 |
+
except TypeError:
|
516 |
+
return d
|
517 |
+
|
518 |
+
avail_uv = [tup[0:2] for tup in avail]
|
519 |
+
avail_w = [1 if len(tup) == 2 else _try_getitem(tup[-1]) for tup in avail]
|
520 |
+
|
521 |
+
if G is not None:
|
522 |
+
# Edges already in the graph are filtered
|
523 |
+
flags = [not G.has_edge(u, v) for u, v in avail_uv]
|
524 |
+
avail_uv = list(it.compress(avail_uv, flags))
|
525 |
+
avail_w = list(it.compress(avail_w, flags))
|
526 |
+
return avail_uv, avail_w
|
527 |
+
|
528 |
+
|
529 |
+
MetaEdge = namedtuple("MetaEdge", ("meta_uv", "uv", "w"))
|
530 |
+
|
531 |
+
|
532 |
+
def _lightest_meta_edges(mapping, avail_uv, avail_w):
|
533 |
+
"""Maps available edges in the original graph to edges in the metagraph.
|
534 |
+
|
535 |
+
Parameters
|
536 |
+
----------
|
537 |
+
mapping : dict
|
538 |
+
mapping produced by :func:`collapse`, that maps each node in the
|
539 |
+
original graph to a node in the meta graph
|
540 |
+
|
541 |
+
avail_uv : list
|
542 |
+
list of edges
|
543 |
+
|
544 |
+
avail_w : list
|
545 |
+
list of edge weights
|
546 |
+
|
547 |
+
Notes
|
548 |
+
-----
|
549 |
+
Each node in the metagraph is a k-edge-connected component in the original
|
550 |
+
graph. We don't care about any edge within the same k-edge-connected
|
551 |
+
component, so we ignore self edges. We also are only interested in the
|
552 |
+
minimum weight edge bridging each k-edge-connected component so, we group
|
553 |
+
the edges by meta-edge and take the lightest in each group.
|
554 |
+
|
555 |
+
Examples
|
556 |
+
--------
|
557 |
+
>>> # Each group represents a meta-node
|
558 |
+
>>> groups = ([1, 2, 3], [4, 5], [6])
|
559 |
+
>>> mapping = {n: meta_n for meta_n, ns in enumerate(groups) for n in ns}
|
560 |
+
>>> avail_uv = [(1, 2), (3, 6), (1, 4), (5, 2), (6, 1), (2, 6), (3, 1)]
|
561 |
+
>>> avail_w = [20, 99, 20, 15, 50, 99, 20]
|
562 |
+
>>> sorted(_lightest_meta_edges(mapping, avail_uv, avail_w))
|
563 |
+
[MetaEdge(meta_uv=(0, 1), uv=(5, 2), w=15), MetaEdge(meta_uv=(0, 2), uv=(6, 1), w=50)]
|
564 |
+
"""
|
565 |
+
grouped_wuv = defaultdict(list)
|
566 |
+
for w, (u, v) in zip(avail_w, avail_uv):
|
567 |
+
# Order the meta-edge so it can be used as a dict key
|
568 |
+
meta_uv = _ordered(mapping[u], mapping[v])
|
569 |
+
# Group each available edge using the meta-edge as a key
|
570 |
+
grouped_wuv[meta_uv].append((w, u, v))
|
571 |
+
|
572 |
+
# Now that all available edges are grouped, choose one per group
|
573 |
+
for (mu, mv), choices_wuv in grouped_wuv.items():
|
574 |
+
# Ignore available edges within the same meta-node
|
575 |
+
if mu != mv:
|
576 |
+
# Choose the lightest available edge belonging to each meta-edge
|
577 |
+
w, u, v = min(choices_wuv)
|
578 |
+
yield MetaEdge((mu, mv), (u, v), w)
|
579 |
+
|
580 |
+
|
581 |
+
@nx._dispatchable
|
582 |
+
def unconstrained_one_edge_augmentation(G):
|
583 |
+
"""Finds the smallest set of edges to connect G.
|
584 |
+
|
585 |
+
This is a variant of the unweighted MST problem.
|
586 |
+
If G is not empty, a feasible solution always exists.
|
587 |
+
|
588 |
+
Parameters
|
589 |
+
----------
|
590 |
+
G : NetworkX graph
|
591 |
+
An undirected graph.
|
592 |
+
|
593 |
+
Yields
|
594 |
+
------
|
595 |
+
edge : tuple
|
596 |
+
Edges in the one-edge-augmentation of G
|
597 |
+
|
598 |
+
See Also
|
599 |
+
--------
|
600 |
+
:func:`one_edge_augmentation`
|
601 |
+
:func:`k_edge_augmentation`
|
602 |
+
|
603 |
+
Examples
|
604 |
+
--------
|
605 |
+
>>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
|
606 |
+
>>> G.add_nodes_from([6, 7, 8])
|
607 |
+
>>> sorted(unconstrained_one_edge_augmentation(G))
|
608 |
+
[(1, 4), (4, 6), (6, 7), (7, 8)]
|
609 |
+
"""
|
610 |
+
ccs1 = list(nx.connected_components(G))
|
611 |
+
C = collapse(G, ccs1)
|
612 |
+
# When we are not constrained, we can just make a meta graph tree.
|
613 |
+
meta_nodes = list(C.nodes())
|
614 |
+
# build a path in the metagraph
|
615 |
+
meta_aug = list(zip(meta_nodes, meta_nodes[1:]))
|
616 |
+
# map that path to the original graph
|
617 |
+
inverse = defaultdict(list)
|
618 |
+
for k, v in C.graph["mapping"].items():
|
619 |
+
inverse[v].append(k)
|
620 |
+
for mu, mv in meta_aug:
|
621 |
+
yield (inverse[mu][0], inverse[mv][0])
|
622 |
+
|
623 |
+
|
624 |
+
@nx._dispatchable
|
625 |
+
def weighted_one_edge_augmentation(G, avail, weight=None, partial=False):
|
626 |
+
"""Finds the minimum weight set of edges to connect G if one exists.
|
627 |
+
|
628 |
+
This is a variant of the weighted MST problem.
|
629 |
+
|
630 |
+
Parameters
|
631 |
+
----------
|
632 |
+
G : NetworkX graph
|
633 |
+
An undirected graph.
|
634 |
+
|
635 |
+
avail : dict or a set of 2 or 3 tuples
|
636 |
+
For more details, see :func:`k_edge_augmentation`.
|
637 |
+
|
638 |
+
weight : string
|
639 |
+
key to use to find weights if ``avail`` is a set of 3-tuples.
|
640 |
+
For more details, see :func:`k_edge_augmentation`.
|
641 |
+
|
642 |
+
partial : boolean
|
643 |
+
If partial is True and no feasible k-edge-augmentation exists, then the
|
644 |
+
augmenting edges minimize the number of connected components.
|
645 |
+
|
646 |
+
Yields
|
647 |
+
------
|
648 |
+
edge : tuple
|
649 |
+
Edges in the subset of avail chosen to connect G.
|
650 |
+
|
651 |
+
See Also
|
652 |
+
--------
|
653 |
+
:func:`one_edge_augmentation`
|
654 |
+
:func:`k_edge_augmentation`
|
655 |
+
|
656 |
+
Examples
|
657 |
+
--------
|
658 |
+
>>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
|
659 |
+
>>> G.add_nodes_from([6, 7, 8])
|
660 |
+
>>> # any edge not in avail has an implicit weight of infinity
|
661 |
+
>>> avail = [(1, 3), (1, 5), (4, 7), (4, 8), (6, 1), (8, 1), (8, 2)]
|
662 |
+
>>> sorted(weighted_one_edge_augmentation(G, avail))
|
663 |
+
[(1, 5), (4, 7), (6, 1), (8, 1)]
|
664 |
+
>>> # find another solution by giving large weights to edges in the
|
665 |
+
>>> # previous solution (note some of the old edges must be used)
|
666 |
+
>>> avail = [(1, 3), (1, 5, 99), (4, 7, 9), (6, 1, 99), (8, 1, 99), (8, 2)]
|
667 |
+
>>> sorted(weighted_one_edge_augmentation(G, avail))
|
668 |
+
[(1, 5), (4, 7), (6, 1), (8, 2)]
|
669 |
+
"""
|
670 |
+
avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
|
671 |
+
# Collapse CCs in the original graph into nodes in a metagraph
|
672 |
+
# Then find an MST of the metagraph instead of the original graph
|
673 |
+
C = collapse(G, nx.connected_components(G))
|
674 |
+
mapping = C.graph["mapping"]
|
675 |
+
# Assign each available edge to an edge in the metagraph
|
676 |
+
candidate_mapping = _lightest_meta_edges(mapping, avail_uv, avail_w)
|
677 |
+
# nx.set_edge_attributes(C, name='weight', values=0)
|
678 |
+
C.add_edges_from(
|
679 |
+
(mu, mv, {"weight": w, "generator": uv})
|
680 |
+
for (mu, mv), uv, w in candidate_mapping
|
681 |
+
)
|
682 |
+
# Find MST of the meta graph
|
683 |
+
meta_mst = nx.minimum_spanning_tree(C)
|
684 |
+
if not partial and not nx.is_connected(meta_mst):
|
685 |
+
raise nx.NetworkXUnfeasible("Not possible to connect G with available edges")
|
686 |
+
# Yield the edge that generated the meta-edge
|
687 |
+
for mu, mv, d in meta_mst.edges(data=True):
|
688 |
+
if "generator" in d:
|
689 |
+
edge = d["generator"]
|
690 |
+
yield edge
|
691 |
+
|
692 |
+
|
693 |
+
@nx._dispatchable
|
694 |
+
def unconstrained_bridge_augmentation(G):
|
695 |
+
"""Finds an optimal 2-edge-augmentation of G using the fewest edges.
|
696 |
+
|
697 |
+
This is an implementation of the algorithm detailed in [1]_.
|
698 |
+
The basic idea is to construct a meta-graph of bridge-ccs, connect leaf
|
699 |
+
nodes of the trees to connect the entire graph, and finally connect the
|
700 |
+
leafs of the tree in dfs-preorder to bridge connect the entire graph.
|
701 |
+
|
702 |
+
Parameters
|
703 |
+
----------
|
704 |
+
G : NetworkX graph
|
705 |
+
An undirected graph.
|
706 |
+
|
707 |
+
Yields
|
708 |
+
------
|
709 |
+
edge : tuple
|
710 |
+
Edges in the bridge augmentation of G
|
711 |
+
|
712 |
+
Notes
|
713 |
+
-----
|
714 |
+
Input: a graph G.
|
715 |
+
First find the bridge components of G and collapse each bridge-cc into a
|
716 |
+
node of a metagraph graph C, which is guaranteed to be a forest of trees.
|
717 |
+
|
718 |
+
C contains p "leafs" --- nodes with exactly one incident edge.
|
719 |
+
C contains q "isolated nodes" --- nodes with no incident edges.
|
720 |
+
|
721 |
+
Theorem: If p + q > 1, then at least :math:`ceil(p / 2) + q` edges are
|
722 |
+
needed to bridge connect C. This algorithm achieves this min number.
|
723 |
+
|
724 |
+
The method first adds enough edges to make G into a tree and then pairs
|
725 |
+
leafs in a simple fashion.
|
726 |
+
|
727 |
+
Let n be the number of trees in C. Let v(i) be an isolated vertex in the
|
728 |
+
i-th tree if one exists, otherwise it is a pair of distinct leafs nodes
|
729 |
+
in the i-th tree. Alternating edges from these sets (i.e. adding edges
|
730 |
+
A1 = [(v(i)[0], v(i + 1)[1]), v(i + 1)[0], v(i + 2)[1])...]) connects C
|
731 |
+
into a tree T. This tree has p' = p + 2q - 2(n -1) leafs and no isolated
|
732 |
+
vertices. A1 has n - 1 edges. The next step finds ceil(p' / 2) edges to
|
733 |
+
biconnect any tree with p' leafs.
|
734 |
+
|
735 |
+
Convert T into an arborescence T' by picking an arbitrary root node with
|
736 |
+
degree >= 2 and directing all edges away from the root. Note the
|
737 |
+
implementation implicitly constructs T'.
|
738 |
+
|
739 |
+
The leafs of T are the nodes with no existing edges in T'.
|
740 |
+
Order the leafs of T' by DFS preorder. Then break this list in half
|
741 |
+
and add the zipped pairs to A2.
|
742 |
+
|
743 |
+
The set A = A1 + A2 is the minimum augmentation in the metagraph.
|
744 |
+
|
745 |
+
To convert this to edges in the original graph
|
746 |
+
|
747 |
+
References
|
748 |
+
----------
|
749 |
+
.. [1] Eswaran, Kapali P., and R. Endre Tarjan. (1975) Augmentation problems.
|
750 |
+
http://epubs.siam.org/doi/abs/10.1137/0205044
|
751 |
+
|
752 |
+
See Also
|
753 |
+
--------
|
754 |
+
:func:`bridge_augmentation`
|
755 |
+
:func:`k_edge_augmentation`
|
756 |
+
|
757 |
+
Examples
|
758 |
+
--------
|
759 |
+
>>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
|
760 |
+
>>> sorted(unconstrained_bridge_augmentation(G))
|
761 |
+
[(1, 7)]
|
762 |
+
>>> G = nx.path_graph((1, 2, 3, 2, 4, 5, 6, 7))
|
763 |
+
>>> sorted(unconstrained_bridge_augmentation(G))
|
764 |
+
[(1, 3), (3, 7)]
|
765 |
+
>>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
|
766 |
+
>>> G.add_node(4)
|
767 |
+
>>> sorted(unconstrained_bridge_augmentation(G))
|
768 |
+
[(1, 4), (4, 0)]
|
769 |
+
"""
|
770 |
+
# -----
|
771 |
+
# Mapping of terms from (Eswaran and Tarjan):
|
772 |
+
# G = G_0 - the input graph
|
773 |
+
# C = G_0' - the bridge condensation of G. (This is a forest of trees)
|
774 |
+
# A1 = A_1 - the edges to connect the forest into a tree
|
775 |
+
# leaf = pendant - a node with degree of 1
|
776 |
+
|
777 |
+
# alpha(v) = maps the node v in G to its meta-node in C
|
778 |
+
# beta(x) = maps the meta-node x in C to any node in the bridge
|
779 |
+
# component of G corresponding to x.
|
780 |
+
|
781 |
+
# find the 2-edge-connected components of G
|
782 |
+
bridge_ccs = list(nx.connectivity.bridge_components(G))
|
783 |
+
# condense G into an forest C
|
784 |
+
C = collapse(G, bridge_ccs)
|
785 |
+
|
786 |
+
# Choose pairs of distinct leaf nodes in each tree. If this is not
|
787 |
+
# possible then make a pair using the single isolated node in the tree.
|
788 |
+
vset1 = [
|
789 |
+
tuple(cc) * 2 # case1: an isolated node
|
790 |
+
if len(cc) == 1
|
791 |
+
else sorted(cc, key=C.degree)[0:2] # case2: pair of leaf nodes
|
792 |
+
for cc in nx.connected_components(C)
|
793 |
+
]
|
794 |
+
if len(vset1) > 1:
|
795 |
+
# Use this set to construct edges that connect C into a tree.
|
796 |
+
nodes1 = [vs[0] for vs in vset1]
|
797 |
+
nodes2 = [vs[1] for vs in vset1]
|
798 |
+
A1 = list(zip(nodes1[1:], nodes2))
|
799 |
+
else:
|
800 |
+
A1 = []
|
801 |
+
# Connect each tree in the forest to construct an arborescence
|
802 |
+
T = C.copy()
|
803 |
+
T.add_edges_from(A1)
|
804 |
+
|
805 |
+
# If there are only two leaf nodes, we simply connect them.
|
806 |
+
leafs = [n for n, d in T.degree() if d == 1]
|
807 |
+
if len(leafs) == 1:
|
808 |
+
A2 = []
|
809 |
+
if len(leafs) == 2:
|
810 |
+
A2 = [tuple(leafs)]
|
811 |
+
else:
|
812 |
+
# Choose an arbitrary non-leaf root
|
813 |
+
try:
|
814 |
+
root = next(n for n, d in T.degree() if d > 1)
|
815 |
+
except StopIteration: # no nodes found with degree > 1
|
816 |
+
return
|
817 |
+
# order the leaves of C by (induced directed) preorder
|
818 |
+
v2 = [n for n in nx.dfs_preorder_nodes(T, root) if T.degree(n) == 1]
|
819 |
+
# connecting first half of the leafs in pre-order to the second
|
820 |
+
# half will bridge connect the tree with the fewest edges.
|
821 |
+
half = math.ceil(len(v2) / 2)
|
822 |
+
A2 = list(zip(v2[:half], v2[-half:]))
|
823 |
+
|
824 |
+
# collect the edges used to augment the original forest
|
825 |
+
aug_tree_edges = A1 + A2
|
826 |
+
|
827 |
+
# Construct the mapping (beta) from meta-nodes to regular nodes
|
828 |
+
inverse = defaultdict(list)
|
829 |
+
for k, v in C.graph["mapping"].items():
|
830 |
+
inverse[v].append(k)
|
831 |
+
# sort so we choose minimum degree nodes first
|
832 |
+
inverse = {
|
833 |
+
mu: sorted(mapped, key=lambda u: (G.degree(u), u))
|
834 |
+
for mu, mapped in inverse.items()
|
835 |
+
}
|
836 |
+
|
837 |
+
# For each meta-edge, map back to an arbitrary pair in the original graph
|
838 |
+
G2 = G.copy()
|
839 |
+
for mu, mv in aug_tree_edges:
|
840 |
+
# Find the first available edge that doesn't exist and return it
|
841 |
+
for u, v in it.product(inverse[mu], inverse[mv]):
|
842 |
+
if not G2.has_edge(u, v):
|
843 |
+
G2.add_edge(u, v)
|
844 |
+
yield u, v
|
845 |
+
break
|
846 |
+
|
847 |
+
|
848 |
+
@nx._dispatchable
|
849 |
+
def weighted_bridge_augmentation(G, avail, weight=None):
|
850 |
+
"""Finds an approximate min-weight 2-edge-augmentation of G.
|
851 |
+
|
852 |
+
This is an implementation of the approximation algorithm detailed in [1]_.
|
853 |
+
It chooses a set of edges from avail to add to G that renders it
|
854 |
+
2-edge-connected if such a subset exists. This is done by finding a
|
855 |
+
minimum spanning arborescence of a specially constructed metagraph.
|
856 |
+
|
857 |
+
Parameters
|
858 |
+
----------
|
859 |
+
G : NetworkX graph
|
860 |
+
An undirected graph.
|
861 |
+
|
862 |
+
avail : set of 2 or 3 tuples.
|
863 |
+
candidate edges (with optional weights) to choose from
|
864 |
+
|
865 |
+
weight : string
|
866 |
+
key to use to find weights if avail is a set of 3-tuples where the
|
867 |
+
third item in each tuple is a dictionary.
|
868 |
+
|
869 |
+
Yields
|
870 |
+
------
|
871 |
+
edge : tuple
|
872 |
+
Edges in the subset of avail chosen to bridge augment G.
|
873 |
+
|
874 |
+
Notes
|
875 |
+
-----
|
876 |
+
Finding a weighted 2-edge-augmentation is NP-hard.
|
877 |
+
Any edge not in ``avail`` is considered to have a weight of infinity.
|
878 |
+
The approximation factor is 2 if ``G`` is connected and 3 if it is not.
|
879 |
+
Runs in :math:`O(m + n log(n))` time
|
880 |
+
|
881 |
+
References
|
882 |
+
----------
|
883 |
+
.. [1] Khuller, Samir, and Ramakrishna Thurimella. (1993) Approximation
|
884 |
+
algorithms for graph augmentation.
|
885 |
+
http://www.sciencedirect.com/science/article/pii/S0196677483710102
|
886 |
+
|
887 |
+
See Also
|
888 |
+
--------
|
889 |
+
:func:`bridge_augmentation`
|
890 |
+
:func:`k_edge_augmentation`
|
891 |
+
|
892 |
+
Examples
|
893 |
+
--------
|
894 |
+
>>> G = nx.path_graph((1, 2, 3, 4))
|
895 |
+
>>> # When the weights are equal, (1, 4) is the best
|
896 |
+
>>> avail = [(1, 4, 1), (1, 3, 1), (2, 4, 1)]
|
897 |
+
>>> sorted(weighted_bridge_augmentation(G, avail))
|
898 |
+
[(1, 4)]
|
899 |
+
>>> # Giving (1, 4) a high weight makes the two edge solution the best.
|
900 |
+
>>> avail = [(1, 4, 1000), (1, 3, 1), (2, 4, 1)]
|
901 |
+
>>> sorted(weighted_bridge_augmentation(G, avail))
|
902 |
+
[(1, 3), (2, 4)]
|
903 |
+
>>> # ------
|
904 |
+
>>> G = nx.path_graph((1, 2, 3, 4))
|
905 |
+
>>> G.add_node(5)
|
906 |
+
>>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 1)]
|
907 |
+
>>> sorted(weighted_bridge_augmentation(G, avail=avail))
|
908 |
+
[(1, 5), (4, 5)]
|
909 |
+
>>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 51)]
|
910 |
+
>>> sorted(weighted_bridge_augmentation(G, avail=avail))
|
911 |
+
[(1, 5), (2, 5), (4, 5)]
|
912 |
+
"""
|
913 |
+
|
914 |
+
if weight is None:
|
915 |
+
weight = "weight"
|
916 |
+
|
917 |
+
# If input G is not connected the approximation factor increases to 3
|
918 |
+
if not nx.is_connected(G):
|
919 |
+
H = G.copy()
|
920 |
+
connectors = list(one_edge_augmentation(H, avail=avail, weight=weight))
|
921 |
+
H.add_edges_from(connectors)
|
922 |
+
|
923 |
+
yield from connectors
|
924 |
+
else:
|
925 |
+
connectors = []
|
926 |
+
H = G
|
927 |
+
|
928 |
+
if len(avail) == 0:
|
929 |
+
if nx.has_bridges(H):
|
930 |
+
raise nx.NetworkXUnfeasible("no augmentation possible")
|
931 |
+
|
932 |
+
avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=H)
|
933 |
+
|
934 |
+
# Collapse input into a metagraph. Meta nodes are bridge-ccs
|
935 |
+
bridge_ccs = nx.connectivity.bridge_components(H)
|
936 |
+
C = collapse(H, bridge_ccs)
|
937 |
+
|
938 |
+
# Use the meta graph to shrink avail to a small feasible subset
|
939 |
+
mapping = C.graph["mapping"]
|
940 |
+
# Choose the minimum weight feasible edge in each group
|
941 |
+
meta_to_wuv = {
|
942 |
+
(mu, mv): (w, uv)
|
943 |
+
for (mu, mv), uv, w in _lightest_meta_edges(mapping, avail_uv, avail_w)
|
944 |
+
}
|
945 |
+
|
946 |
+
# Mapping of terms from (Khuller and Thurimella):
|
947 |
+
# C : G_0 = (V, E^0)
|
948 |
+
# This is the metagraph where each node is a 2-edge-cc in G.
|
949 |
+
# The edges in C represent bridges in the original graph.
|
950 |
+
# (mu, mv) : E - E^0 # they group both avail and given edges in E
|
951 |
+
# T : \Gamma
|
952 |
+
# D : G^D = (V, E_D)
|
953 |
+
|
954 |
+
# The paper uses ancestor because children point to parents, which is
|
955 |
+
# contrary to networkx standards. So, we actually need to run
|
956 |
+
# nx.least_common_ancestor on the reversed Tree.
|
957 |
+
|
958 |
+
# Pick an arbitrary leaf from C as the root
|
959 |
+
try:
|
960 |
+
root = next(n for n, d in C.degree() if d == 1)
|
961 |
+
except StopIteration: # no nodes found with degree == 1
|
962 |
+
return
|
963 |
+
# Root C into a tree TR by directing all edges away from the root
|
964 |
+
# Note in their paper T directs edges towards the root
|
965 |
+
TR = nx.dfs_tree(C, root)
|
966 |
+
|
967 |
+
# Add to D the directed edges of T and set their weight to zero
|
968 |
+
# This indicates that it costs nothing to use edges that were given.
|
969 |
+
D = nx.reverse(TR).copy()
|
970 |
+
|
971 |
+
nx.set_edge_attributes(D, name="weight", values=0)
|
972 |
+
|
973 |
+
# The LCA of mu and mv in T is the shared ancestor of mu and mv that is
|
974 |
+
# located farthest from the root.
|
975 |
+
lca_gen = nx.tree_all_pairs_lowest_common_ancestor(
|
976 |
+
TR, root=root, pairs=meta_to_wuv.keys()
|
977 |
+
)
|
978 |
+
|
979 |
+
for (mu, mv), lca in lca_gen:
|
980 |
+
w, uv = meta_to_wuv[(mu, mv)]
|
981 |
+
if lca == mu:
|
982 |
+
# If u is an ancestor of v in TR, then add edge u->v to D
|
983 |
+
D.add_edge(lca, mv, weight=w, generator=uv)
|
984 |
+
elif lca == mv:
|
985 |
+
# If v is an ancestor of u in TR, then add edge v->u to D
|
986 |
+
D.add_edge(lca, mu, weight=w, generator=uv)
|
987 |
+
else:
|
988 |
+
# If neither u nor v is a ancestor of the other in TR
|
989 |
+
# let t = lca(TR, u, v) and add edges t->u and t->v
|
990 |
+
# Track the original edge that GENERATED these edges.
|
991 |
+
D.add_edge(lca, mu, weight=w, generator=uv)
|
992 |
+
D.add_edge(lca, mv, weight=w, generator=uv)
|
993 |
+
|
994 |
+
# Then compute a minimum rooted branching
|
995 |
+
try:
|
996 |
+
# Note the original edges must be directed towards to root for the
|
997 |
+
# branching to give us a bridge-augmentation.
|
998 |
+
A = _minimum_rooted_branching(D, root)
|
999 |
+
except nx.NetworkXException as err:
|
1000 |
+
# If there is no branching then augmentation is not possible
|
1001 |
+
raise nx.NetworkXUnfeasible("no 2-edge-augmentation possible") from err
|
1002 |
+
|
1003 |
+
# For each edge e, in the branching that did not belong to the directed
|
1004 |
+
# tree T, add the corresponding edge that **GENERATED** it (this is not
|
1005 |
+
# necessarily e itself!)
|
1006 |
+
|
1007 |
+
# ensure the third case does not generate edges twice
|
1008 |
+
bridge_connectors = set()
|
1009 |
+
for mu, mv in A.edges():
|
1010 |
+
data = D.get_edge_data(mu, mv)
|
1011 |
+
if "generator" in data:
|
1012 |
+
# Add the avail edge that generated the branching edge.
|
1013 |
+
edge = data["generator"]
|
1014 |
+
bridge_connectors.add(edge)
|
1015 |
+
|
1016 |
+
yield from bridge_connectors
|
1017 |
+
|
1018 |
+
|
1019 |
+
def _minimum_rooted_branching(D, root):
|
1020 |
+
"""Helper function to compute a minimum rooted branching (aka rooted
|
1021 |
+
arborescence)
|
1022 |
+
|
1023 |
+
Before the branching can be computed, the directed graph must be rooted by
|
1024 |
+
removing the predecessors of root.
|
1025 |
+
|
1026 |
+
A branching / arborescence of rooted graph G is a subgraph that contains a
|
1027 |
+
directed path from the root to every other vertex. It is the directed
|
1028 |
+
analog of the minimum spanning tree problem.
|
1029 |
+
|
1030 |
+
References
|
1031 |
+
----------
|
1032 |
+
[1] Khuller, Samir (2002) Advanced Algorithms Lecture 24 Notes.
|
1033 |
+
https://web.archive.org/web/20121030033722/https://www.cs.umd.edu/class/spring2011/cmsc651/lec07.pdf
|
1034 |
+
"""
|
1035 |
+
rooted = D.copy()
|
1036 |
+
# root the graph by removing all predecessors to `root`.
|
1037 |
+
rooted.remove_edges_from([(u, root) for u in D.predecessors(root)])
|
1038 |
+
# Then compute the branching / arborescence.
|
1039 |
+
A = nx.minimum_spanning_arborescence(rooted)
|
1040 |
+
return A
|
1041 |
+
|
1042 |
+
|
1043 |
+
@nx._dispatchable(returns_graph=True)
|
1044 |
+
def collapse(G, grouped_nodes):
|
1045 |
+
"""Collapses each group of nodes into a single node.
|
1046 |
+
|
1047 |
+
This is similar to condensation, but works on undirected graphs.
|
1048 |
+
|
1049 |
+
Parameters
|
1050 |
+
----------
|
1051 |
+
G : NetworkX Graph
|
1052 |
+
|
1053 |
+
grouped_nodes: list or generator
|
1054 |
+
Grouping of nodes to collapse. The grouping must be disjoint.
|
1055 |
+
If grouped_nodes are strongly_connected_components then this is
|
1056 |
+
equivalent to :func:`condensation`.
|
1057 |
+
|
1058 |
+
Returns
|
1059 |
+
-------
|
1060 |
+
C : NetworkX Graph
|
1061 |
+
The collapsed graph C of G with respect to the node grouping. The node
|
1062 |
+
labels are integers corresponding to the index of the component in the
|
1063 |
+
list of grouped_nodes. C has a graph attribute named 'mapping' with a
|
1064 |
+
dictionary mapping the original nodes to the nodes in C to which they
|
1065 |
+
belong. Each node in C also has a node attribute 'members' with the set
|
1066 |
+
of original nodes in G that form the group that the node in C
|
1067 |
+
represents.
|
1068 |
+
|
1069 |
+
Examples
|
1070 |
+
--------
|
1071 |
+
>>> # Collapses a graph using disjoint groups, but not necessarily connected
|
1072 |
+
>>> G = nx.Graph([(1, 0), (2, 3), (3, 1), (3, 4), (4, 5), (5, 6), (5, 7)])
|
1073 |
+
>>> G.add_node("A")
|
1074 |
+
>>> grouped_nodes = [{0, 1, 2, 3}, {5, 6, 7}]
|
1075 |
+
>>> C = collapse(G, grouped_nodes)
|
1076 |
+
>>> members = nx.get_node_attributes(C, "members")
|
1077 |
+
>>> sorted(members.keys())
|
1078 |
+
[0, 1, 2, 3]
|
1079 |
+
>>> member_values = set(map(frozenset, members.values()))
|
1080 |
+
>>> assert {0, 1, 2, 3} in member_values
|
1081 |
+
>>> assert {4} in member_values
|
1082 |
+
>>> assert {5, 6, 7} in member_values
|
1083 |
+
>>> assert {"A"} in member_values
|
1084 |
+
"""
|
1085 |
+
mapping = {}
|
1086 |
+
members = {}
|
1087 |
+
C = G.__class__()
|
1088 |
+
i = 0 # required if G is empty
|
1089 |
+
remaining = set(G.nodes())
|
1090 |
+
for i, group in enumerate(grouped_nodes):
|
1091 |
+
group = set(group)
|
1092 |
+
assert remaining.issuperset(
|
1093 |
+
group
|
1094 |
+
), "grouped nodes must exist in G and be disjoint"
|
1095 |
+
remaining.difference_update(group)
|
1096 |
+
members[i] = group
|
1097 |
+
mapping.update((n, i) for n in group)
|
1098 |
+
# remaining nodes are in their own group
|
1099 |
+
for i, node in enumerate(remaining, start=i + 1):
|
1100 |
+
group = {node}
|
1101 |
+
members[i] = group
|
1102 |
+
mapping.update((n, i) for n in group)
|
1103 |
+
number_of_groups = i + 1
|
1104 |
+
C.add_nodes_from(range(number_of_groups))
|
1105 |
+
C.add_edges_from(
|
1106 |
+
(mapping[u], mapping[v]) for u, v in G.edges() if mapping[u] != mapping[v]
|
1107 |
+
)
|
1108 |
+
# Add a list of members (ie original nodes) to each node (ie scc) in C.
|
1109 |
+
nx.set_node_attributes(C, name="members", values=members)
|
1110 |
+
# Add mapping dict as graph attribute
|
1111 |
+
C.graph["mapping"] = mapping
|
1112 |
+
return C
|
1113 |
+
|
1114 |
+
|
1115 |
+
@nx._dispatchable
|
1116 |
+
def complement_edges(G):
|
1117 |
+
"""Returns only the edges in the complement of G
|
1118 |
+
|
1119 |
+
Parameters
|
1120 |
+
----------
|
1121 |
+
G : NetworkX Graph
|
1122 |
+
|
1123 |
+
Yields
|
1124 |
+
------
|
1125 |
+
edge : tuple
|
1126 |
+
Edges in the complement of G
|
1127 |
+
|
1128 |
+
Examples
|
1129 |
+
--------
|
1130 |
+
>>> G = nx.path_graph((1, 2, 3, 4))
|
1131 |
+
>>> sorted(complement_edges(G))
|
1132 |
+
[(1, 3), (1, 4), (2, 4)]
|
1133 |
+
>>> G = nx.path_graph((1, 2, 3, 4), nx.DiGraph())
|
1134 |
+
>>> sorted(complement_edges(G))
|
1135 |
+
[(1, 3), (1, 4), (2, 1), (2, 4), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3)]
|
1136 |
+
>>> G = nx.complete_graph(1000)
|
1137 |
+
>>> sorted(complement_edges(G))
|
1138 |
+
[]
|
1139 |
+
"""
|
1140 |
+
G_adj = G._adj # Store as a variable to eliminate attribute lookup
|
1141 |
+
if G.is_directed():
|
1142 |
+
for u, v in it.combinations(G.nodes(), 2):
|
1143 |
+
if v not in G_adj[u]:
|
1144 |
+
yield (u, v)
|
1145 |
+
if u not in G_adj[v]:
|
1146 |
+
yield (v, u)
|
1147 |
+
else:
|
1148 |
+
for u, v in it.combinations(G.nodes(), 2):
|
1149 |
+
if v not in G_adj[u]:
|
1150 |
+
yield (u, v)
|
1151 |
+
|
1152 |
+
|
1153 |
+
def _compat_shuffle(rng, input):
|
1154 |
+
"""wrapper around rng.shuffle for python 2 compatibility reasons"""
|
1155 |
+
rng.shuffle(input)
|
1156 |
+
|
1157 |
+
|
1158 |
+
@not_implemented_for("multigraph")
|
1159 |
+
@not_implemented_for("directed")
|
1160 |
+
@py_random_state(4)
|
1161 |
+
@nx._dispatchable
|
1162 |
+
def greedy_k_edge_augmentation(G, k, avail=None, weight=None, seed=None):
|
1163 |
+
"""Greedy algorithm for finding a k-edge-augmentation
|
1164 |
+
|
1165 |
+
Parameters
|
1166 |
+
----------
|
1167 |
+
G : NetworkX graph
|
1168 |
+
An undirected graph.
|
1169 |
+
|
1170 |
+
k : integer
|
1171 |
+
Desired edge connectivity
|
1172 |
+
|
1173 |
+
avail : dict or a set of 2 or 3 tuples
|
1174 |
+
For more details, see :func:`k_edge_augmentation`.
|
1175 |
+
|
1176 |
+
weight : string
|
1177 |
+
key to use to find weights if ``avail`` is a set of 3-tuples.
|
1178 |
+
For more details, see :func:`k_edge_augmentation`.
|
1179 |
+
|
1180 |
+
seed : integer, random_state, or None (default)
|
1181 |
+
Indicator of random number generation state.
|
1182 |
+
See :ref:`Randomness<randomness>`.
|
1183 |
+
|
1184 |
+
Yields
|
1185 |
+
------
|
1186 |
+
edge : tuple
|
1187 |
+
Edges in the greedy augmentation of G
|
1188 |
+
|
1189 |
+
Notes
|
1190 |
+
-----
|
1191 |
+
The algorithm is simple. Edges are incrementally added between parts of the
|
1192 |
+
graph that are not yet locally k-edge-connected. Then edges are from the
|
1193 |
+
augmenting set are pruned as long as local-edge-connectivity is not broken.
|
1194 |
+
|
1195 |
+
This algorithm is greedy and does not provide optimality guarantees. It
|
1196 |
+
exists only to provide :func:`k_edge_augmentation` with the ability to
|
1197 |
+
generate a feasible solution for arbitrary k.
|
1198 |
+
|
1199 |
+
See Also
|
1200 |
+
--------
|
1201 |
+
:func:`k_edge_augmentation`
|
1202 |
+
|
1203 |
+
Examples
|
1204 |
+
--------
|
1205 |
+
>>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
|
1206 |
+
>>> sorted(greedy_k_edge_augmentation(G, k=2))
|
1207 |
+
[(1, 7)]
|
1208 |
+
>>> sorted(greedy_k_edge_augmentation(G, k=1, avail=[]))
|
1209 |
+
[]
|
1210 |
+
>>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
|
1211 |
+
>>> avail = {(u, v): 1 for (u, v) in complement_edges(G)}
|
1212 |
+
>>> # randomized pruning process can produce different solutions
|
1213 |
+
>>> sorted(greedy_k_edge_augmentation(G, k=4, avail=avail, seed=2))
|
1214 |
+
[(1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (2, 4), (2, 6), (3, 7), (5, 7)]
|
1215 |
+
>>> sorted(greedy_k_edge_augmentation(G, k=4, avail=avail, seed=3))
|
1216 |
+
[(1, 3), (1, 5), (1, 6), (2, 4), (2, 6), (3, 7), (4, 7), (5, 7)]
|
1217 |
+
"""
|
1218 |
+
# Result set
|
1219 |
+
aug_edges = []
|
1220 |
+
|
1221 |
+
done = is_k_edge_connected(G, k)
|
1222 |
+
if done:
|
1223 |
+
return
|
1224 |
+
if avail is None:
|
1225 |
+
# all edges are available
|
1226 |
+
avail_uv = list(complement_edges(G))
|
1227 |
+
avail_w = [1] * len(avail_uv)
|
1228 |
+
else:
|
1229 |
+
# Get the unique set of unweighted edges
|
1230 |
+
avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
|
1231 |
+
|
1232 |
+
# Greedy: order lightest edges. Use degree sum to tie-break
|
1233 |
+
tiebreaker = [sum(map(G.degree, uv)) for uv in avail_uv]
|
1234 |
+
avail_wduv = sorted(zip(avail_w, tiebreaker, avail_uv))
|
1235 |
+
avail_uv = [uv for w, d, uv in avail_wduv]
|
1236 |
+
|
1237 |
+
# Incrementally add edges in until we are k-connected
|
1238 |
+
H = G.copy()
|
1239 |
+
for u, v in avail_uv:
|
1240 |
+
done = False
|
1241 |
+
if not is_locally_k_edge_connected(H, u, v, k=k):
|
1242 |
+
# Only add edges in parts that are not yet locally k-edge-connected
|
1243 |
+
aug_edges.append((u, v))
|
1244 |
+
H.add_edge(u, v)
|
1245 |
+
# Did adding this edge help?
|
1246 |
+
if H.degree(u) >= k and H.degree(v) >= k:
|
1247 |
+
done = is_k_edge_connected(H, k)
|
1248 |
+
if done:
|
1249 |
+
break
|
1250 |
+
|
1251 |
+
# Check for feasibility
|
1252 |
+
if not done:
|
1253 |
+
raise nx.NetworkXUnfeasible("not able to k-edge-connect with available edges")
|
1254 |
+
|
1255 |
+
# Randomized attempt to reduce the size of the solution
|
1256 |
+
_compat_shuffle(seed, aug_edges)
|
1257 |
+
for u, v in list(aug_edges):
|
1258 |
+
# Don't remove if we know it would break connectivity
|
1259 |
+
if H.degree(u) <= k or H.degree(v) <= k:
|
1260 |
+
continue
|
1261 |
+
H.remove_edge(u, v)
|
1262 |
+
aug_edges.remove((u, v))
|
1263 |
+
if not is_k_edge_connected(H, k=k):
|
1264 |
+
# If removing this edge breaks feasibility, undo
|
1265 |
+
H.add_edge(u, v)
|
1266 |
+
aug_edges.append((u, v))
|
1267 |
+
|
1268 |
+
# Generate results
|
1269 |
+
yield from aug_edges
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/edge_kcomponents.py
ADDED
@@ -0,0 +1,591 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Algorithms for finding k-edge-connected components and subgraphs.
|
3 |
+
|
4 |
+
A k-edge-connected component (k-edge-cc) is a maximal set of nodes in G, such
|
5 |
+
that all pairs of node have an edge-connectivity of at least k.
|
6 |
+
|
7 |
+
A k-edge-connected subgraph (k-edge-subgraph) is a maximal set of nodes in G,
|
8 |
+
such that the subgraph of G defined by the nodes has an edge-connectivity at
|
9 |
+
least k.
|
10 |
+
"""
|
11 |
+
import itertools as it
|
12 |
+
from functools import partial
|
13 |
+
|
14 |
+
import networkx as nx
|
15 |
+
from networkx.utils import arbitrary_element, not_implemented_for
|
16 |
+
|
17 |
+
__all__ = [
|
18 |
+
"k_edge_components",
|
19 |
+
"k_edge_subgraphs",
|
20 |
+
"bridge_components",
|
21 |
+
"EdgeComponentAuxGraph",
|
22 |
+
]
|
23 |
+
|
24 |
+
|
25 |
+
@not_implemented_for("multigraph")
|
26 |
+
@nx._dispatchable
|
27 |
+
def k_edge_components(G, k):
|
28 |
+
"""Generates nodes in each maximal k-edge-connected component in G.
|
29 |
+
|
30 |
+
Parameters
|
31 |
+
----------
|
32 |
+
G : NetworkX graph
|
33 |
+
|
34 |
+
k : Integer
|
35 |
+
Desired edge connectivity
|
36 |
+
|
37 |
+
Returns
|
38 |
+
-------
|
39 |
+
k_edge_components : a generator of k-edge-ccs. Each set of returned nodes
|
40 |
+
will have k-edge-connectivity in the graph G.
|
41 |
+
|
42 |
+
See Also
|
43 |
+
--------
|
44 |
+
:func:`local_edge_connectivity`
|
45 |
+
:func:`k_edge_subgraphs` : similar to this function, but the subgraph
|
46 |
+
defined by the nodes must also have k-edge-connectivity.
|
47 |
+
:func:`k_components` : similar to this function, but uses node-connectivity
|
48 |
+
instead of edge-connectivity
|
49 |
+
|
50 |
+
Raises
|
51 |
+
------
|
52 |
+
NetworkXNotImplemented
|
53 |
+
If the input graph is a multigraph.
|
54 |
+
|
55 |
+
ValueError:
|
56 |
+
If k is less than 1
|
57 |
+
|
58 |
+
Notes
|
59 |
+
-----
|
60 |
+
Attempts to use the most efficient implementation available based on k.
|
61 |
+
If k=1, this is simply connected components for directed graphs and
|
62 |
+
connected components for undirected graphs.
|
63 |
+
If k=2 on an efficient bridge connected component algorithm from _[1] is
|
64 |
+
run based on the chain decomposition.
|
65 |
+
Otherwise, the algorithm from _[2] is used.
|
66 |
+
|
67 |
+
Examples
|
68 |
+
--------
|
69 |
+
>>> import itertools as it
|
70 |
+
>>> from networkx.utils import pairwise
|
71 |
+
>>> paths = [
|
72 |
+
... (1, 2, 4, 3, 1, 4),
|
73 |
+
... (5, 6, 7, 8, 5, 7, 8, 6),
|
74 |
+
... ]
|
75 |
+
>>> G = nx.Graph()
|
76 |
+
>>> G.add_nodes_from(it.chain(*paths))
|
77 |
+
>>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
|
78 |
+
>>> # note this returns {1, 4} unlike k_edge_subgraphs
|
79 |
+
>>> sorted(map(sorted, nx.k_edge_components(G, k=3)))
|
80 |
+
[[1, 4], [2], [3], [5, 6, 7, 8]]
|
81 |
+
|
82 |
+
References
|
83 |
+
----------
|
84 |
+
.. [1] https://en.wikipedia.org/wiki/Bridge_%28graph_theory%29
|
85 |
+
.. [2] Wang, Tianhao, et al. (2015) A simple algorithm for finding all
|
86 |
+
k-edge-connected components.
|
87 |
+
http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0136264
|
88 |
+
"""
|
89 |
+
# Compute k-edge-ccs using the most efficient algorithms available.
|
90 |
+
if k < 1:
|
91 |
+
raise ValueError("k cannot be less than 1")
|
92 |
+
if G.is_directed():
|
93 |
+
if k == 1:
|
94 |
+
return nx.strongly_connected_components(G)
|
95 |
+
else:
|
96 |
+
# TODO: investigate https://arxiv.org/abs/1412.6466 for k=2
|
97 |
+
aux_graph = EdgeComponentAuxGraph.construct(G)
|
98 |
+
return aux_graph.k_edge_components(k)
|
99 |
+
else:
|
100 |
+
if k == 1:
|
101 |
+
return nx.connected_components(G)
|
102 |
+
elif k == 2:
|
103 |
+
return bridge_components(G)
|
104 |
+
else:
|
105 |
+
aux_graph = EdgeComponentAuxGraph.construct(G)
|
106 |
+
return aux_graph.k_edge_components(k)
|
107 |
+
|
108 |
+
|
109 |
+
@not_implemented_for("multigraph")
|
110 |
+
@nx._dispatchable
|
111 |
+
def k_edge_subgraphs(G, k):
|
112 |
+
"""Generates nodes in each maximal k-edge-connected subgraph in G.
|
113 |
+
|
114 |
+
Parameters
|
115 |
+
----------
|
116 |
+
G : NetworkX graph
|
117 |
+
|
118 |
+
k : Integer
|
119 |
+
Desired edge connectivity
|
120 |
+
|
121 |
+
Returns
|
122 |
+
-------
|
123 |
+
k_edge_subgraphs : a generator of k-edge-subgraphs
|
124 |
+
Each k-edge-subgraph is a maximal set of nodes that defines a subgraph
|
125 |
+
of G that is k-edge-connected.
|
126 |
+
|
127 |
+
See Also
|
128 |
+
--------
|
129 |
+
:func:`edge_connectivity`
|
130 |
+
:func:`k_edge_components` : similar to this function, but nodes only
|
131 |
+
need to have k-edge-connectivity within the graph G and the subgraphs
|
132 |
+
might not be k-edge-connected.
|
133 |
+
|
134 |
+
Raises
|
135 |
+
------
|
136 |
+
NetworkXNotImplemented
|
137 |
+
If the input graph is a multigraph.
|
138 |
+
|
139 |
+
ValueError:
|
140 |
+
If k is less than 1
|
141 |
+
|
142 |
+
Notes
|
143 |
+
-----
|
144 |
+
Attempts to use the most efficient implementation available based on k.
|
145 |
+
If k=1, or k=2 and the graph is undirected, then this simply calls
|
146 |
+
`k_edge_components`. Otherwise the algorithm from _[1] is used.
|
147 |
+
|
148 |
+
Examples
|
149 |
+
--------
|
150 |
+
>>> import itertools as it
|
151 |
+
>>> from networkx.utils import pairwise
|
152 |
+
>>> paths = [
|
153 |
+
... (1, 2, 4, 3, 1, 4),
|
154 |
+
... (5, 6, 7, 8, 5, 7, 8, 6),
|
155 |
+
... ]
|
156 |
+
>>> G = nx.Graph()
|
157 |
+
>>> G.add_nodes_from(it.chain(*paths))
|
158 |
+
>>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
|
159 |
+
>>> # note this does not return {1, 4} unlike k_edge_components
|
160 |
+
>>> sorted(map(sorted, nx.k_edge_subgraphs(G, k=3)))
|
161 |
+
[[1], [2], [3], [4], [5, 6, 7, 8]]
|
162 |
+
|
163 |
+
References
|
164 |
+
----------
|
165 |
+
.. [1] Zhou, Liu, et al. (2012) Finding maximal k-edge-connected subgraphs
|
166 |
+
from a large graph. ACM International Conference on Extending Database
|
167 |
+
Technology 2012 480-–491.
|
168 |
+
https://openproceedings.org/2012/conf/edbt/ZhouLYLCL12.pdf
|
169 |
+
"""
|
170 |
+
if k < 1:
|
171 |
+
raise ValueError("k cannot be less than 1")
|
172 |
+
if G.is_directed():
|
173 |
+
if k <= 1:
|
174 |
+
# For directed graphs ,
|
175 |
+
# When k == 1, k-edge-ccs and k-edge-subgraphs are the same
|
176 |
+
return k_edge_components(G, k)
|
177 |
+
else:
|
178 |
+
return _k_edge_subgraphs_nodes(G, k)
|
179 |
+
else:
|
180 |
+
if k <= 2:
|
181 |
+
# For undirected graphs,
|
182 |
+
# when k <= 2, k-edge-ccs and k-edge-subgraphs are the same
|
183 |
+
return k_edge_components(G, k)
|
184 |
+
else:
|
185 |
+
return _k_edge_subgraphs_nodes(G, k)
|
186 |
+
|
187 |
+
|
188 |
+
def _k_edge_subgraphs_nodes(G, k):
|
189 |
+
"""Helper to get the nodes from the subgraphs.
|
190 |
+
|
191 |
+
This allows k_edge_subgraphs to return a generator.
|
192 |
+
"""
|
193 |
+
for C in general_k_edge_subgraphs(G, k):
|
194 |
+
yield set(C.nodes())
|
195 |
+
|
196 |
+
|
197 |
+
@not_implemented_for("directed")
|
198 |
+
@not_implemented_for("multigraph")
|
199 |
+
@nx._dispatchable
|
200 |
+
def bridge_components(G):
|
201 |
+
"""Finds all bridge-connected components G.
|
202 |
+
|
203 |
+
Parameters
|
204 |
+
----------
|
205 |
+
G : NetworkX undirected graph
|
206 |
+
|
207 |
+
Returns
|
208 |
+
-------
|
209 |
+
bridge_components : a generator of 2-edge-connected components
|
210 |
+
|
211 |
+
|
212 |
+
See Also
|
213 |
+
--------
|
214 |
+
:func:`k_edge_subgraphs` : this function is a special case for an
|
215 |
+
undirected graph where k=2.
|
216 |
+
:func:`biconnected_components` : similar to this function, but is defined
|
217 |
+
using 2-node-connectivity instead of 2-edge-connectivity.
|
218 |
+
|
219 |
+
Raises
|
220 |
+
------
|
221 |
+
NetworkXNotImplemented
|
222 |
+
If the input graph is directed or a multigraph.
|
223 |
+
|
224 |
+
Notes
|
225 |
+
-----
|
226 |
+
Bridge-connected components are also known as 2-edge-connected components.
|
227 |
+
|
228 |
+
Examples
|
229 |
+
--------
|
230 |
+
>>> # The barbell graph with parameter zero has a single bridge
|
231 |
+
>>> G = nx.barbell_graph(5, 0)
|
232 |
+
>>> from networkx.algorithms.connectivity.edge_kcomponents import bridge_components
|
233 |
+
>>> sorted(map(sorted, bridge_components(G)))
|
234 |
+
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
|
235 |
+
"""
|
236 |
+
H = G.copy()
|
237 |
+
H.remove_edges_from(nx.bridges(G))
|
238 |
+
yield from nx.connected_components(H)
|
239 |
+
|
240 |
+
|
241 |
+
class EdgeComponentAuxGraph:
|
242 |
+
r"""A simple algorithm to find all k-edge-connected components in a graph.
|
243 |
+
|
244 |
+
Constructing the auxiliary graph (which may take some time) allows for the
|
245 |
+
k-edge-ccs to be found in linear time for arbitrary k.
|
246 |
+
|
247 |
+
Notes
|
248 |
+
-----
|
249 |
+
This implementation is based on [1]_. The idea is to construct an auxiliary
|
250 |
+
graph from which the k-edge-ccs can be extracted in linear time. The
|
251 |
+
auxiliary graph is constructed in $O(|V|\cdot F)$ operations, where F is the
|
252 |
+
complexity of max flow. Querying the components takes an additional $O(|V|)$
|
253 |
+
operations. This algorithm can be slow for large graphs, but it handles an
|
254 |
+
arbitrary k and works for both directed and undirected inputs.
|
255 |
+
|
256 |
+
The undirected case for k=1 is exactly connected components.
|
257 |
+
The undirected case for k=2 is exactly bridge connected components.
|
258 |
+
The directed case for k=1 is exactly strongly connected components.
|
259 |
+
|
260 |
+
References
|
261 |
+
----------
|
262 |
+
.. [1] Wang, Tianhao, et al. (2015) A simple algorithm for finding all
|
263 |
+
k-edge-connected components.
|
264 |
+
http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0136264
|
265 |
+
|
266 |
+
Examples
|
267 |
+
--------
|
268 |
+
>>> import itertools as it
|
269 |
+
>>> from networkx.utils import pairwise
|
270 |
+
>>> from networkx.algorithms.connectivity import EdgeComponentAuxGraph
|
271 |
+
>>> # Build an interesting graph with multiple levels of k-edge-ccs
|
272 |
+
>>> paths = [
|
273 |
+
... (1, 2, 3, 4, 1, 3, 4, 2), # a 3-edge-cc (a 4 clique)
|
274 |
+
... (5, 6, 7, 5), # a 2-edge-cc (a 3 clique)
|
275 |
+
... (1, 5), # combine first two ccs into a 1-edge-cc
|
276 |
+
... (0,), # add an additional disconnected 1-edge-cc
|
277 |
+
... ]
|
278 |
+
>>> G = nx.Graph()
|
279 |
+
>>> G.add_nodes_from(it.chain(*paths))
|
280 |
+
>>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
|
281 |
+
>>> # Constructing the AuxGraph takes about O(n ** 4)
|
282 |
+
>>> aux_graph = EdgeComponentAuxGraph.construct(G)
|
283 |
+
>>> # Once constructed, querying takes O(n)
|
284 |
+
>>> sorted(map(sorted, aux_graph.k_edge_components(k=1)))
|
285 |
+
[[0], [1, 2, 3, 4, 5, 6, 7]]
|
286 |
+
>>> sorted(map(sorted, aux_graph.k_edge_components(k=2)))
|
287 |
+
[[0], [1, 2, 3, 4], [5, 6, 7]]
|
288 |
+
>>> sorted(map(sorted, aux_graph.k_edge_components(k=3)))
|
289 |
+
[[0], [1, 2, 3, 4], [5], [6], [7]]
|
290 |
+
>>> sorted(map(sorted, aux_graph.k_edge_components(k=4)))
|
291 |
+
[[0], [1], [2], [3], [4], [5], [6], [7]]
|
292 |
+
|
293 |
+
The auxiliary graph is primarily used for k-edge-ccs but it
|
294 |
+
can also speed up the queries of k-edge-subgraphs by refining the
|
295 |
+
search space.
|
296 |
+
|
297 |
+
>>> import itertools as it
|
298 |
+
>>> from networkx.utils import pairwise
|
299 |
+
>>> from networkx.algorithms.connectivity import EdgeComponentAuxGraph
|
300 |
+
>>> paths = [
|
301 |
+
... (1, 2, 4, 3, 1, 4),
|
302 |
+
... ]
|
303 |
+
>>> G = nx.Graph()
|
304 |
+
>>> G.add_nodes_from(it.chain(*paths))
|
305 |
+
>>> G.add_edges_from(it.chain(*[pairwise(path) for path in paths]))
|
306 |
+
>>> aux_graph = EdgeComponentAuxGraph.construct(G)
|
307 |
+
>>> sorted(map(sorted, aux_graph.k_edge_subgraphs(k=3)))
|
308 |
+
[[1], [2], [3], [4]]
|
309 |
+
>>> sorted(map(sorted, aux_graph.k_edge_components(k=3)))
|
310 |
+
[[1, 4], [2], [3]]
|
311 |
+
"""
|
312 |
+
|
313 |
+
# @not_implemented_for('multigraph') # TODO: fix decor for classmethods
|
314 |
+
@classmethod
|
315 |
+
def construct(EdgeComponentAuxGraph, G):
|
316 |
+
"""Builds an auxiliary graph encoding edge-connectivity between nodes.
|
317 |
+
|
318 |
+
Notes
|
319 |
+
-----
|
320 |
+
Given G=(V, E), initialize an empty auxiliary graph A.
|
321 |
+
Choose an arbitrary source node s. Initialize a set N of available
|
322 |
+
nodes (that can be used as the sink). The algorithm picks an
|
323 |
+
arbitrary node t from N - {s}, and then computes the minimum st-cut
|
324 |
+
(S, T) with value w. If G is directed the minimum of the st-cut or
|
325 |
+
the ts-cut is used instead. Then, the edge (s, t) is added to the
|
326 |
+
auxiliary graph with weight w. The algorithm is called recursively
|
327 |
+
first using S as the available nodes and s as the source, and then
|
328 |
+
using T and t. Recursion stops when the source is the only available
|
329 |
+
node.
|
330 |
+
|
331 |
+
Parameters
|
332 |
+
----------
|
333 |
+
G : NetworkX graph
|
334 |
+
"""
|
335 |
+
# workaround for classmethod decorator
|
336 |
+
not_implemented_for("multigraph")(lambda G: G)(G)
|
337 |
+
|
338 |
+
def _recursive_build(H, A, source, avail):
|
339 |
+
# Terminate once the flow has been compute to every node.
|
340 |
+
if {source} == avail:
|
341 |
+
return
|
342 |
+
# pick an arbitrary node as the sink
|
343 |
+
sink = arbitrary_element(avail - {source})
|
344 |
+
# find the minimum cut and its weight
|
345 |
+
value, (S, T) = nx.minimum_cut(H, source, sink)
|
346 |
+
if H.is_directed():
|
347 |
+
# check if the reverse direction has a smaller cut
|
348 |
+
value_, (T_, S_) = nx.minimum_cut(H, sink, source)
|
349 |
+
if value_ < value:
|
350 |
+
value, S, T = value_, S_, T_
|
351 |
+
# add edge with weight of cut to the aux graph
|
352 |
+
A.add_edge(source, sink, weight=value)
|
353 |
+
# recursively call until all but one node is used
|
354 |
+
_recursive_build(H, A, source, avail.intersection(S))
|
355 |
+
_recursive_build(H, A, sink, avail.intersection(T))
|
356 |
+
|
357 |
+
# Copy input to ensure all edges have unit capacity
|
358 |
+
H = G.__class__()
|
359 |
+
H.add_nodes_from(G.nodes())
|
360 |
+
H.add_edges_from(G.edges(), capacity=1)
|
361 |
+
|
362 |
+
# A is the auxiliary graph to be constructed
|
363 |
+
# It is a weighted undirected tree
|
364 |
+
A = nx.Graph()
|
365 |
+
|
366 |
+
# Pick an arbitrary node as the source
|
367 |
+
if H.number_of_nodes() > 0:
|
368 |
+
source = arbitrary_element(H.nodes())
|
369 |
+
# Initialize a set of elements that can be chosen as the sink
|
370 |
+
avail = set(H.nodes())
|
371 |
+
|
372 |
+
# This constructs A
|
373 |
+
_recursive_build(H, A, source, avail)
|
374 |
+
|
375 |
+
# This class is a container the holds the auxiliary graph A and
|
376 |
+
# provides access the k_edge_components function.
|
377 |
+
self = EdgeComponentAuxGraph()
|
378 |
+
self.A = A
|
379 |
+
self.H = H
|
380 |
+
return self
|
381 |
+
|
382 |
+
def k_edge_components(self, k):
|
383 |
+
"""Queries the auxiliary graph for k-edge-connected components.
|
384 |
+
|
385 |
+
Parameters
|
386 |
+
----------
|
387 |
+
k : Integer
|
388 |
+
Desired edge connectivity
|
389 |
+
|
390 |
+
Returns
|
391 |
+
-------
|
392 |
+
k_edge_components : a generator of k-edge-ccs
|
393 |
+
|
394 |
+
Notes
|
395 |
+
-----
|
396 |
+
Given the auxiliary graph, the k-edge-connected components can be
|
397 |
+
determined in linear time by removing all edges with weights less than
|
398 |
+
k from the auxiliary graph. The resulting connected components are the
|
399 |
+
k-edge-ccs in the original graph.
|
400 |
+
"""
|
401 |
+
if k < 1:
|
402 |
+
raise ValueError("k cannot be less than 1")
|
403 |
+
A = self.A
|
404 |
+
# "traverse the auxiliary graph A and delete all edges with weights less
|
405 |
+
# than k"
|
406 |
+
aux_weights = nx.get_edge_attributes(A, "weight")
|
407 |
+
# Create a relevant graph with the auxiliary edges with weights >= k
|
408 |
+
R = nx.Graph()
|
409 |
+
R.add_nodes_from(A.nodes())
|
410 |
+
R.add_edges_from(e for e, w in aux_weights.items() if w >= k)
|
411 |
+
|
412 |
+
# Return the nodes that are k-edge-connected in the original graph
|
413 |
+
yield from nx.connected_components(R)
|
414 |
+
|
415 |
+
def k_edge_subgraphs(self, k):
|
416 |
+
"""Queries the auxiliary graph for k-edge-connected subgraphs.
|
417 |
+
|
418 |
+
Parameters
|
419 |
+
----------
|
420 |
+
k : Integer
|
421 |
+
Desired edge connectivity
|
422 |
+
|
423 |
+
Returns
|
424 |
+
-------
|
425 |
+
k_edge_subgraphs : a generator of k-edge-subgraphs
|
426 |
+
|
427 |
+
Notes
|
428 |
+
-----
|
429 |
+
Refines the k-edge-ccs into k-edge-subgraphs. The running time is more
|
430 |
+
than $O(|V|)$.
|
431 |
+
|
432 |
+
For single values of k it is faster to use `nx.k_edge_subgraphs`.
|
433 |
+
But for multiple values of k, it can be faster to build AuxGraph and
|
434 |
+
then use this method.
|
435 |
+
"""
|
436 |
+
if k < 1:
|
437 |
+
raise ValueError("k cannot be less than 1")
|
438 |
+
H = self.H
|
439 |
+
A = self.A
|
440 |
+
# "traverse the auxiliary graph A and delete all edges with weights less
|
441 |
+
# than k"
|
442 |
+
aux_weights = nx.get_edge_attributes(A, "weight")
|
443 |
+
# Create a relevant graph with the auxiliary edges with weights >= k
|
444 |
+
R = nx.Graph()
|
445 |
+
R.add_nodes_from(A.nodes())
|
446 |
+
R.add_edges_from(e for e, w in aux_weights.items() if w >= k)
|
447 |
+
|
448 |
+
# Return the components whose subgraphs are k-edge-connected
|
449 |
+
for cc in nx.connected_components(R):
|
450 |
+
if len(cc) < k:
|
451 |
+
# Early return optimization
|
452 |
+
for node in cc:
|
453 |
+
yield {node}
|
454 |
+
else:
|
455 |
+
# Call subgraph solution to refine the results
|
456 |
+
C = H.subgraph(cc)
|
457 |
+
yield from k_edge_subgraphs(C, k)
|
458 |
+
|
459 |
+
|
460 |
+
def _low_degree_nodes(G, k, nbunch=None):
|
461 |
+
"""Helper for finding nodes with degree less than k."""
|
462 |
+
# Nodes with degree less than k cannot be k-edge-connected.
|
463 |
+
if G.is_directed():
|
464 |
+
# Consider both in and out degree in the directed case
|
465 |
+
seen = set()
|
466 |
+
for node, degree in G.out_degree(nbunch):
|
467 |
+
if degree < k:
|
468 |
+
seen.add(node)
|
469 |
+
yield node
|
470 |
+
for node, degree in G.in_degree(nbunch):
|
471 |
+
if node not in seen and degree < k:
|
472 |
+
seen.add(node)
|
473 |
+
yield node
|
474 |
+
else:
|
475 |
+
# Only the degree matters in the undirected case
|
476 |
+
for node, degree in G.degree(nbunch):
|
477 |
+
if degree < k:
|
478 |
+
yield node
|
479 |
+
|
480 |
+
|
481 |
+
def _high_degree_components(G, k):
|
482 |
+
"""Helper for filtering components that can't be k-edge-connected.
|
483 |
+
|
484 |
+
Removes and generates each node with degree less than k. Then generates
|
485 |
+
remaining components where all nodes have degree at least k.
|
486 |
+
"""
|
487 |
+
# Iteratively remove parts of the graph that are not k-edge-connected
|
488 |
+
H = G.copy()
|
489 |
+
singletons = set(_low_degree_nodes(H, k))
|
490 |
+
while singletons:
|
491 |
+
# Only search neighbors of removed nodes
|
492 |
+
nbunch = set(it.chain.from_iterable(map(H.neighbors, singletons)))
|
493 |
+
nbunch.difference_update(singletons)
|
494 |
+
H.remove_nodes_from(singletons)
|
495 |
+
for node in singletons:
|
496 |
+
yield {node}
|
497 |
+
singletons = set(_low_degree_nodes(H, k, nbunch))
|
498 |
+
|
499 |
+
# Note: remaining connected components may not be k-edge-connected
|
500 |
+
if G.is_directed():
|
501 |
+
yield from nx.strongly_connected_components(H)
|
502 |
+
else:
|
503 |
+
yield from nx.connected_components(H)
|
504 |
+
|
505 |
+
|
506 |
+
@nx._dispatchable(returns_graph=True)
|
507 |
+
def general_k_edge_subgraphs(G, k):
|
508 |
+
"""General algorithm to find all maximal k-edge-connected subgraphs in `G`.
|
509 |
+
|
510 |
+
Parameters
|
511 |
+
----------
|
512 |
+
G : nx.Graph
|
513 |
+
Graph in which all maximal k-edge-connected subgraphs will be found.
|
514 |
+
|
515 |
+
k : int
|
516 |
+
|
517 |
+
Yields
|
518 |
+
------
|
519 |
+
k_edge_subgraphs : Graph instances that are k-edge-subgraphs
|
520 |
+
Each k-edge-subgraph contains a maximal set of nodes that defines a
|
521 |
+
subgraph of `G` that is k-edge-connected.
|
522 |
+
|
523 |
+
Notes
|
524 |
+
-----
|
525 |
+
Implementation of the basic algorithm from [1]_. The basic idea is to find
|
526 |
+
a global minimum cut of the graph. If the cut value is at least k, then the
|
527 |
+
graph is a k-edge-connected subgraph and can be added to the results.
|
528 |
+
Otherwise, the cut is used to split the graph in two and the procedure is
|
529 |
+
applied recursively. If the graph is just a single node, then it is also
|
530 |
+
added to the results. At the end, each result is either guaranteed to be
|
531 |
+
a single node or a subgraph of G that is k-edge-connected.
|
532 |
+
|
533 |
+
This implementation contains optimizations for reducing the number of calls
|
534 |
+
to max-flow, but there are other optimizations in [1]_ that could be
|
535 |
+
implemented.
|
536 |
+
|
537 |
+
References
|
538 |
+
----------
|
539 |
+
.. [1] Zhou, Liu, et al. (2012) Finding maximal k-edge-connected subgraphs
|
540 |
+
from a large graph. ACM International Conference on Extending Database
|
541 |
+
Technology 2012 480-–491.
|
542 |
+
https://openproceedings.org/2012/conf/edbt/ZhouLYLCL12.pdf
|
543 |
+
|
544 |
+
Examples
|
545 |
+
--------
|
546 |
+
>>> from networkx.utils import pairwise
|
547 |
+
>>> paths = [
|
548 |
+
... (11, 12, 13, 14, 11, 13, 14, 12), # a 4-clique
|
549 |
+
... (21, 22, 23, 24, 21, 23, 24, 22), # another 4-clique
|
550 |
+
... # connect the cliques with high degree but low connectivity
|
551 |
+
... (50, 13),
|
552 |
+
... (12, 50, 22),
|
553 |
+
... (13, 102, 23),
|
554 |
+
... (14, 101, 24),
|
555 |
+
... ]
|
556 |
+
>>> G = nx.Graph(it.chain(*[pairwise(path) for path in paths]))
|
557 |
+
>>> sorted(len(k_sg) for k_sg in k_edge_subgraphs(G, k=3))
|
558 |
+
[1, 1, 1, 4, 4]
|
559 |
+
"""
|
560 |
+
if k < 1:
|
561 |
+
raise ValueError("k cannot be less than 1")
|
562 |
+
|
563 |
+
# Node pruning optimization (incorporates early return)
|
564 |
+
# find_ccs is either connected_components/strongly_connected_components
|
565 |
+
find_ccs = partial(_high_degree_components, k=k)
|
566 |
+
|
567 |
+
# Quick return optimization
|
568 |
+
if G.number_of_nodes() < k:
|
569 |
+
for node in G.nodes():
|
570 |
+
yield G.subgraph([node]).copy()
|
571 |
+
return
|
572 |
+
|
573 |
+
# Intermediate results
|
574 |
+
R0 = {G.subgraph(cc).copy() for cc in find_ccs(G)}
|
575 |
+
# Subdivide CCs in the intermediate results until they are k-conn
|
576 |
+
while R0:
|
577 |
+
G1 = R0.pop()
|
578 |
+
if G1.number_of_nodes() == 1:
|
579 |
+
yield G1
|
580 |
+
else:
|
581 |
+
# Find a global minimum cut
|
582 |
+
cut_edges = nx.minimum_edge_cut(G1)
|
583 |
+
cut_value = len(cut_edges)
|
584 |
+
if cut_value < k:
|
585 |
+
# G1 is not k-edge-connected, so subdivide it
|
586 |
+
G1.remove_edges_from(cut_edges)
|
587 |
+
for cc in find_ccs(G1):
|
588 |
+
R0.add(G1.subgraph(cc).copy())
|
589 |
+
else:
|
590 |
+
# Otherwise we found a k-edge-connected subgraph
|
591 |
+
yield G1
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcomponents.py
ADDED
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Moody and White algorithm for k-components
|
3 |
+
"""
|
4 |
+
from collections import defaultdict
|
5 |
+
from itertools import combinations
|
6 |
+
from operator import itemgetter
|
7 |
+
|
8 |
+
import networkx as nx
|
9 |
+
|
10 |
+
# Define the default maximum flow function.
|
11 |
+
from networkx.algorithms.flow import edmonds_karp
|
12 |
+
from networkx.utils import not_implemented_for
|
13 |
+
|
14 |
+
default_flow_func = edmonds_karp
|
15 |
+
|
16 |
+
__all__ = ["k_components"]
|
17 |
+
|
18 |
+
|
19 |
+
@not_implemented_for("directed")
|
20 |
+
@nx._dispatchable
|
21 |
+
def k_components(G, flow_func=None):
|
22 |
+
r"""Returns the k-component structure of a graph G.
|
23 |
+
|
24 |
+
A `k`-component is a maximal subgraph of a graph G that has, at least,
|
25 |
+
node connectivity `k`: we need to remove at least `k` nodes to break it
|
26 |
+
into more components. `k`-components have an inherent hierarchical
|
27 |
+
structure because they are nested in terms of connectivity: a connected
|
28 |
+
graph can contain several 2-components, each of which can contain
|
29 |
+
one or more 3-components, and so forth.
|
30 |
+
|
31 |
+
Parameters
|
32 |
+
----------
|
33 |
+
G : NetworkX graph
|
34 |
+
|
35 |
+
flow_func : function
|
36 |
+
Function to perform the underlying flow computations. Default value
|
37 |
+
:meth:`edmonds_karp`. This function performs better in sparse graphs with
|
38 |
+
right tailed degree distributions. :meth:`shortest_augmenting_path` will
|
39 |
+
perform better in denser graphs.
|
40 |
+
|
41 |
+
Returns
|
42 |
+
-------
|
43 |
+
k_components : dict
|
44 |
+
Dictionary with all connectivity levels `k` in the input Graph as keys
|
45 |
+
and a list of sets of nodes that form a k-component of level `k` as
|
46 |
+
values.
|
47 |
+
|
48 |
+
Raises
|
49 |
+
------
|
50 |
+
NetworkXNotImplemented
|
51 |
+
If the input graph is directed.
|
52 |
+
|
53 |
+
Examples
|
54 |
+
--------
|
55 |
+
>>> # Petersen graph has 10 nodes and it is triconnected, thus all
|
56 |
+
>>> # nodes are in a single component on all three connectivity levels
|
57 |
+
>>> G = nx.petersen_graph()
|
58 |
+
>>> k_components = nx.k_components(G)
|
59 |
+
|
60 |
+
Notes
|
61 |
+
-----
|
62 |
+
Moody and White [1]_ (appendix A) provide an algorithm for identifying
|
63 |
+
k-components in a graph, which is based on Kanevsky's algorithm [2]_
|
64 |
+
for finding all minimum-size node cut-sets of a graph (implemented in
|
65 |
+
:meth:`all_node_cuts` function):
|
66 |
+
|
67 |
+
1. Compute node connectivity, k, of the input graph G.
|
68 |
+
|
69 |
+
2. Identify all k-cutsets at the current level of connectivity using
|
70 |
+
Kanevsky's algorithm.
|
71 |
+
|
72 |
+
3. Generate new graph components based on the removal of
|
73 |
+
these cutsets. Nodes in a cutset belong to both sides
|
74 |
+
of the induced cut.
|
75 |
+
|
76 |
+
4. If the graph is neither complete nor trivial, return to 1;
|
77 |
+
else end.
|
78 |
+
|
79 |
+
This implementation also uses some heuristics (see [3]_ for details)
|
80 |
+
to speed up the computation.
|
81 |
+
|
82 |
+
See also
|
83 |
+
--------
|
84 |
+
node_connectivity
|
85 |
+
all_node_cuts
|
86 |
+
biconnected_components : special case of this function when k=2
|
87 |
+
k_edge_components : similar to this function, but uses edge-connectivity
|
88 |
+
instead of node-connectivity
|
89 |
+
|
90 |
+
References
|
91 |
+
----------
|
92 |
+
.. [1] Moody, J. and D. White (2003). Social cohesion and embeddedness:
|
93 |
+
A hierarchical conception of social groups.
|
94 |
+
American Sociological Review 68(1), 103--28.
|
95 |
+
http://www2.asanet.org/journals/ASRFeb03MoodyWhite.pdf
|
96 |
+
|
97 |
+
.. [2] Kanevsky, A. (1993). Finding all minimum-size separating vertex
|
98 |
+
sets in a graph. Networks 23(6), 533--541.
|
99 |
+
http://onlinelibrary.wiley.com/doi/10.1002/net.3230230604/abstract
|
100 |
+
|
101 |
+
.. [3] Torrents, J. and F. Ferraro (2015). Structural Cohesion:
|
102 |
+
Visualization and Heuristics for Fast Computation.
|
103 |
+
https://arxiv.org/pdf/1503.04476v1
|
104 |
+
|
105 |
+
"""
|
106 |
+
# Dictionary with connectivity level (k) as keys and a list of
|
107 |
+
# sets of nodes that form a k-component as values. Note that
|
108 |
+
# k-components can overlap (but only k - 1 nodes).
|
109 |
+
k_components = defaultdict(list)
|
110 |
+
# Define default flow function
|
111 |
+
if flow_func is None:
|
112 |
+
flow_func = default_flow_func
|
113 |
+
# Bicomponents as a base to check for higher order k-components
|
114 |
+
for component in nx.connected_components(G):
|
115 |
+
# isolated nodes have connectivity 0
|
116 |
+
comp = set(component)
|
117 |
+
if len(comp) > 1:
|
118 |
+
k_components[1].append(comp)
|
119 |
+
bicomponents = [G.subgraph(c) for c in nx.biconnected_components(G)]
|
120 |
+
for bicomponent in bicomponents:
|
121 |
+
bicomp = set(bicomponent)
|
122 |
+
# avoid considering dyads as bicomponents
|
123 |
+
if len(bicomp) > 2:
|
124 |
+
k_components[2].append(bicomp)
|
125 |
+
for B in bicomponents:
|
126 |
+
if len(B) <= 2:
|
127 |
+
continue
|
128 |
+
k = nx.node_connectivity(B, flow_func=flow_func)
|
129 |
+
if k > 2:
|
130 |
+
k_components[k].append(set(B))
|
131 |
+
# Perform cuts in a DFS like order.
|
132 |
+
cuts = list(nx.all_node_cuts(B, k=k, flow_func=flow_func))
|
133 |
+
stack = [(k, _generate_partition(B, cuts, k))]
|
134 |
+
while stack:
|
135 |
+
(parent_k, partition) = stack[-1]
|
136 |
+
try:
|
137 |
+
nodes = next(partition)
|
138 |
+
C = B.subgraph(nodes)
|
139 |
+
this_k = nx.node_connectivity(C, flow_func=flow_func)
|
140 |
+
if this_k > parent_k and this_k > 2:
|
141 |
+
k_components[this_k].append(set(C))
|
142 |
+
cuts = list(nx.all_node_cuts(C, k=this_k, flow_func=flow_func))
|
143 |
+
if cuts:
|
144 |
+
stack.append((this_k, _generate_partition(C, cuts, this_k)))
|
145 |
+
except StopIteration:
|
146 |
+
stack.pop()
|
147 |
+
|
148 |
+
# This is necessary because k-components may only be reported at their
|
149 |
+
# maximum k level. But we want to return a dictionary in which keys are
|
150 |
+
# connectivity levels and values list of sets of components, without
|
151 |
+
# skipping any connectivity level. Also, it's possible that subsets of
|
152 |
+
# an already detected k-component appear at a level k. Checking for this
|
153 |
+
# in the while loop above penalizes the common case. Thus we also have to
|
154 |
+
# _consolidate all connectivity levels in _reconstruct_k_components.
|
155 |
+
return _reconstruct_k_components(k_components)
|
156 |
+
|
157 |
+
|
158 |
+
def _consolidate(sets, k):
|
159 |
+
"""Merge sets that share k or more elements.
|
160 |
+
|
161 |
+
See: http://rosettacode.org/wiki/Set_consolidation
|
162 |
+
|
163 |
+
The iterative python implementation posted there is
|
164 |
+
faster than this because of the overhead of building a
|
165 |
+
Graph and calling nx.connected_components, but it's not
|
166 |
+
clear for us if we can use it in NetworkX because there
|
167 |
+
is no licence for the code.
|
168 |
+
|
169 |
+
"""
|
170 |
+
G = nx.Graph()
|
171 |
+
nodes = dict(enumerate(sets))
|
172 |
+
G.add_nodes_from(nodes)
|
173 |
+
G.add_edges_from(
|
174 |
+
(u, v) for u, v in combinations(nodes, 2) if len(nodes[u] & nodes[v]) >= k
|
175 |
+
)
|
176 |
+
for component in nx.connected_components(G):
|
177 |
+
yield set.union(*[nodes[n] for n in component])
|
178 |
+
|
179 |
+
|
180 |
+
def _generate_partition(G, cuts, k):
|
181 |
+
def has_nbrs_in_partition(G, node, partition):
|
182 |
+
return any(n in partition for n in G[node])
|
183 |
+
|
184 |
+
components = []
|
185 |
+
nodes = {n for n, d in G.degree() if d > k} - {n for cut in cuts for n in cut}
|
186 |
+
H = G.subgraph(nodes)
|
187 |
+
for cc in nx.connected_components(H):
|
188 |
+
component = set(cc)
|
189 |
+
for cut in cuts:
|
190 |
+
for node in cut:
|
191 |
+
if has_nbrs_in_partition(G, node, cc):
|
192 |
+
component.add(node)
|
193 |
+
if len(component) < G.order():
|
194 |
+
components.append(component)
|
195 |
+
yield from _consolidate(components, k + 1)
|
196 |
+
|
197 |
+
|
198 |
+
def _reconstruct_k_components(k_comps):
|
199 |
+
result = {}
|
200 |
+
max_k = max(k_comps)
|
201 |
+
for k in reversed(range(1, max_k + 1)):
|
202 |
+
if k == max_k:
|
203 |
+
result[k] = list(_consolidate(k_comps[k], k))
|
204 |
+
elif k not in k_comps:
|
205 |
+
result[k] = list(_consolidate(result[k + 1], k))
|
206 |
+
else:
|
207 |
+
nodes_at_k = set.union(*k_comps[k])
|
208 |
+
to_add = [c for c in result[k + 1] if any(n not in nodes_at_k for n in c)]
|
209 |
+
if to_add:
|
210 |
+
result[k] = list(_consolidate(k_comps[k] + to_add, k))
|
211 |
+
else:
|
212 |
+
result[k] = list(_consolidate(k_comps[k], k))
|
213 |
+
return result
|
214 |
+
|
215 |
+
|
216 |
+
def build_k_number_dict(kcomps):
|
217 |
+
result = {}
|
218 |
+
for k, comps in sorted(kcomps.items(), key=itemgetter(0)):
|
219 |
+
for comp in comps:
|
220 |
+
for node in comp:
|
221 |
+
result[node] = k
|
222 |
+
return result
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/kcutsets.py
ADDED
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Kanevsky all minimum node k cutsets algorithm.
|
3 |
+
"""
|
4 |
+
import copy
|
5 |
+
from collections import defaultdict
|
6 |
+
from itertools import combinations
|
7 |
+
from operator import itemgetter
|
8 |
+
|
9 |
+
import networkx as nx
|
10 |
+
from networkx.algorithms.flow import (
|
11 |
+
build_residual_network,
|
12 |
+
edmonds_karp,
|
13 |
+
shortest_augmenting_path,
|
14 |
+
)
|
15 |
+
|
16 |
+
from .utils import build_auxiliary_node_connectivity
|
17 |
+
|
18 |
+
default_flow_func = edmonds_karp
|
19 |
+
|
20 |
+
|
21 |
+
__all__ = ["all_node_cuts"]
|
22 |
+
|
23 |
+
|
24 |
+
@nx._dispatchable
|
25 |
+
def all_node_cuts(G, k=None, flow_func=None):
|
26 |
+
r"""Returns all minimum k cutsets of an undirected graph G.
|
27 |
+
|
28 |
+
This implementation is based on Kanevsky's algorithm [1]_ for finding all
|
29 |
+
minimum-size node cut-sets of an undirected graph G; ie the set (or sets)
|
30 |
+
of nodes of cardinality equal to the node connectivity of G. Thus if
|
31 |
+
removed, would break G into two or more connected components.
|
32 |
+
|
33 |
+
Parameters
|
34 |
+
----------
|
35 |
+
G : NetworkX graph
|
36 |
+
Undirected graph
|
37 |
+
|
38 |
+
k : Integer
|
39 |
+
Node connectivity of the input graph. If k is None, then it is
|
40 |
+
computed. Default value: None.
|
41 |
+
|
42 |
+
flow_func : function
|
43 |
+
Function to perform the underlying flow computations. Default value is
|
44 |
+
:func:`~networkx.algorithms.flow.edmonds_karp`. This function performs
|
45 |
+
better in sparse graphs with right tailed degree distributions.
|
46 |
+
:func:`~networkx.algorithms.flow.shortest_augmenting_path` will
|
47 |
+
perform better in denser graphs.
|
48 |
+
|
49 |
+
|
50 |
+
Returns
|
51 |
+
-------
|
52 |
+
cuts : a generator of node cutsets
|
53 |
+
Each node cutset has cardinality equal to the node connectivity of
|
54 |
+
the input graph.
|
55 |
+
|
56 |
+
Examples
|
57 |
+
--------
|
58 |
+
>>> # A two-dimensional grid graph has 4 cutsets of cardinality 2
|
59 |
+
>>> G = nx.grid_2d_graph(5, 5)
|
60 |
+
>>> cutsets = list(nx.all_node_cuts(G))
|
61 |
+
>>> len(cutsets)
|
62 |
+
4
|
63 |
+
>>> all(2 == len(cutset) for cutset in cutsets)
|
64 |
+
True
|
65 |
+
>>> nx.node_connectivity(G)
|
66 |
+
2
|
67 |
+
|
68 |
+
Notes
|
69 |
+
-----
|
70 |
+
This implementation is based on the sequential algorithm for finding all
|
71 |
+
minimum-size separating vertex sets in a graph [1]_. The main idea is to
|
72 |
+
compute minimum cuts using local maximum flow computations among a set
|
73 |
+
of nodes of highest degree and all other non-adjacent nodes in the Graph.
|
74 |
+
Once we find a minimum cut, we add an edge between the high degree
|
75 |
+
node and the target node of the local maximum flow computation to make
|
76 |
+
sure that we will not find that minimum cut again.
|
77 |
+
|
78 |
+
See also
|
79 |
+
--------
|
80 |
+
node_connectivity
|
81 |
+
edmonds_karp
|
82 |
+
shortest_augmenting_path
|
83 |
+
|
84 |
+
References
|
85 |
+
----------
|
86 |
+
.. [1] Kanevsky, A. (1993). Finding all minimum-size separating vertex
|
87 |
+
sets in a graph. Networks 23(6), 533--541.
|
88 |
+
http://onlinelibrary.wiley.com/doi/10.1002/net.3230230604/abstract
|
89 |
+
|
90 |
+
"""
|
91 |
+
if not nx.is_connected(G):
|
92 |
+
raise nx.NetworkXError("Input graph is disconnected.")
|
93 |
+
|
94 |
+
# Address some corner cases first.
|
95 |
+
# For complete Graphs
|
96 |
+
|
97 |
+
if nx.density(G) == 1:
|
98 |
+
yield from ()
|
99 |
+
return
|
100 |
+
|
101 |
+
# Initialize data structures.
|
102 |
+
# Keep track of the cuts already computed so we do not repeat them.
|
103 |
+
seen = []
|
104 |
+
# Even-Tarjan reduction is what we call auxiliary digraph
|
105 |
+
# for node connectivity.
|
106 |
+
H = build_auxiliary_node_connectivity(G)
|
107 |
+
H_nodes = H.nodes # for speed
|
108 |
+
mapping = H.graph["mapping"]
|
109 |
+
# Keep a copy of original predecessors, H will be modified later.
|
110 |
+
# Shallow copy is enough.
|
111 |
+
original_H_pred = copy.copy(H._pred)
|
112 |
+
R = build_residual_network(H, "capacity")
|
113 |
+
kwargs = {"capacity": "capacity", "residual": R}
|
114 |
+
# Define default flow function
|
115 |
+
if flow_func is None:
|
116 |
+
flow_func = default_flow_func
|
117 |
+
if flow_func is shortest_augmenting_path:
|
118 |
+
kwargs["two_phase"] = True
|
119 |
+
# Begin the actual algorithm
|
120 |
+
# step 1: Find node connectivity k of G
|
121 |
+
if k is None:
|
122 |
+
k = nx.node_connectivity(G, flow_func=flow_func)
|
123 |
+
# step 2:
|
124 |
+
# Find k nodes with top degree, call it X:
|
125 |
+
X = {n for n, d in sorted(G.degree(), key=itemgetter(1), reverse=True)[:k]}
|
126 |
+
# Check if X is a k-node-cutset
|
127 |
+
if _is_separating_set(G, X):
|
128 |
+
seen.append(X)
|
129 |
+
yield X
|
130 |
+
|
131 |
+
for x in X:
|
132 |
+
# step 3: Compute local connectivity flow of x with all other
|
133 |
+
# non adjacent nodes in G
|
134 |
+
non_adjacent = set(G) - {x} - set(G[x])
|
135 |
+
for v in non_adjacent:
|
136 |
+
# step 4: compute maximum flow in an Even-Tarjan reduction H of G
|
137 |
+
# and step 5: build the associated residual network R
|
138 |
+
R = flow_func(H, f"{mapping[x]}B", f"{mapping[v]}A", **kwargs)
|
139 |
+
flow_value = R.graph["flow_value"]
|
140 |
+
|
141 |
+
if flow_value == k:
|
142 |
+
# Find the nodes incident to the flow.
|
143 |
+
E1 = flowed_edges = [
|
144 |
+
(u, w) for (u, w, d) in R.edges(data=True) if d["flow"] != 0
|
145 |
+
]
|
146 |
+
VE1 = incident_nodes = {n for edge in E1 for n in edge}
|
147 |
+
# Remove saturated edges form the residual network.
|
148 |
+
# Note that reversed edges are introduced with capacity 0
|
149 |
+
# in the residual graph and they need to be removed too.
|
150 |
+
saturated_edges = [
|
151 |
+
(u, w, d)
|
152 |
+
for (u, w, d) in R.edges(data=True)
|
153 |
+
if d["capacity"] == d["flow"] or d["capacity"] == 0
|
154 |
+
]
|
155 |
+
R.remove_edges_from(saturated_edges)
|
156 |
+
R_closure = nx.transitive_closure(R)
|
157 |
+
# step 6: shrink the strongly connected components of
|
158 |
+
# residual flow network R and call it L.
|
159 |
+
L = nx.condensation(R)
|
160 |
+
cmap = L.graph["mapping"]
|
161 |
+
inv_cmap = defaultdict(list)
|
162 |
+
for n, scc in cmap.items():
|
163 |
+
inv_cmap[scc].append(n)
|
164 |
+
# Find the incident nodes in the condensed graph.
|
165 |
+
VE1 = {cmap[n] for n in VE1}
|
166 |
+
# step 7: Compute all antichains of L;
|
167 |
+
# they map to closed sets in H.
|
168 |
+
# Any edge in H that links a closed set is part of a cutset.
|
169 |
+
for antichain in nx.antichains(L):
|
170 |
+
# Only antichains that are subsets of incident nodes counts.
|
171 |
+
# Lemma 8 in reference.
|
172 |
+
if not set(antichain).issubset(VE1):
|
173 |
+
continue
|
174 |
+
# Nodes in an antichain of the condensation graph of
|
175 |
+
# the residual network map to a closed set of nodes that
|
176 |
+
# define a node partition of the auxiliary digraph H
|
177 |
+
# through taking all of antichain's predecessors in the
|
178 |
+
# transitive closure.
|
179 |
+
S = set()
|
180 |
+
for scc in antichain:
|
181 |
+
S.update(inv_cmap[scc])
|
182 |
+
S_ancestors = set()
|
183 |
+
for n in S:
|
184 |
+
S_ancestors.update(R_closure._pred[n])
|
185 |
+
S.update(S_ancestors)
|
186 |
+
if f"{mapping[x]}B" not in S or f"{mapping[v]}A" in S:
|
187 |
+
continue
|
188 |
+
# Find the cutset that links the node partition (S,~S) in H
|
189 |
+
cutset = set()
|
190 |
+
for u in S:
|
191 |
+
cutset.update((u, w) for w in original_H_pred[u] if w not in S)
|
192 |
+
# The edges in H that form the cutset are internal edges
|
193 |
+
# (ie edges that represent a node of the original graph G)
|
194 |
+
if any(H_nodes[u]["id"] != H_nodes[w]["id"] for u, w in cutset):
|
195 |
+
continue
|
196 |
+
node_cut = {H_nodes[u]["id"] for u, _ in cutset}
|
197 |
+
|
198 |
+
if len(node_cut) == k:
|
199 |
+
# The cut is invalid if it includes internal edges of
|
200 |
+
# end nodes. The other half of Lemma 8 in ref.
|
201 |
+
if x in node_cut or v in node_cut:
|
202 |
+
continue
|
203 |
+
if node_cut not in seen:
|
204 |
+
yield node_cut
|
205 |
+
seen.append(node_cut)
|
206 |
+
|
207 |
+
# Add an edge (x, v) to make sure that we do not
|
208 |
+
# find this cutset again. This is equivalent
|
209 |
+
# of adding the edge in the input graph
|
210 |
+
# G.add_edge(x, v) and then regenerate H and R:
|
211 |
+
# Add edges to the auxiliary digraph.
|
212 |
+
# See build_residual_network for convention we used
|
213 |
+
# in residual graphs.
|
214 |
+
H.add_edge(f"{mapping[x]}B", f"{mapping[v]}A", capacity=1)
|
215 |
+
H.add_edge(f"{mapping[v]}B", f"{mapping[x]}A", capacity=1)
|
216 |
+
# Add edges to the residual network.
|
217 |
+
R.add_edge(f"{mapping[x]}B", f"{mapping[v]}A", capacity=1)
|
218 |
+
R.add_edge(f"{mapping[v]}A", f"{mapping[x]}B", capacity=0)
|
219 |
+
R.add_edge(f"{mapping[v]}B", f"{mapping[x]}A", capacity=1)
|
220 |
+
R.add_edge(f"{mapping[x]}A", f"{mapping[v]}B", capacity=0)
|
221 |
+
|
222 |
+
# Add again the saturated edges to reuse the residual network
|
223 |
+
R.add_edges_from(saturated_edges)
|
224 |
+
|
225 |
+
|
226 |
+
def _is_separating_set(G, cut):
|
227 |
+
"""Assumes that the input graph is connected"""
|
228 |
+
if len(cut) == len(G) - 1:
|
229 |
+
return True
|
230 |
+
|
231 |
+
H = nx.restricted_view(G, cut, [])
|
232 |
+
if nx.is_connected(H):
|
233 |
+
return False
|
234 |
+
return True
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/stoerwagner.py
ADDED
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Stoer-Wagner minimum cut algorithm.
|
3 |
+
"""
|
4 |
+
from itertools import islice
|
5 |
+
|
6 |
+
import networkx as nx
|
7 |
+
|
8 |
+
from ...utils import BinaryHeap, arbitrary_element, not_implemented_for
|
9 |
+
|
10 |
+
__all__ = ["stoer_wagner"]
|
11 |
+
|
12 |
+
|
13 |
+
@not_implemented_for("directed")
|
14 |
+
@not_implemented_for("multigraph")
|
15 |
+
@nx._dispatchable(edge_attrs="weight")
|
16 |
+
def stoer_wagner(G, weight="weight", heap=BinaryHeap):
|
17 |
+
r"""Returns the weighted minimum edge cut using the Stoer-Wagner algorithm.
|
18 |
+
|
19 |
+
Determine the minimum edge cut of a connected graph using the
|
20 |
+
Stoer-Wagner algorithm. In weighted cases, all weights must be
|
21 |
+
nonnegative.
|
22 |
+
|
23 |
+
The running time of the algorithm depends on the type of heaps used:
|
24 |
+
|
25 |
+
============== =============================================
|
26 |
+
Type of heap Running time
|
27 |
+
============== =============================================
|
28 |
+
Binary heap $O(n (m + n) \log n)$
|
29 |
+
Fibonacci heap $O(nm + n^2 \log n)$
|
30 |
+
Pairing heap $O(2^{2 \sqrt{\log \log n}} nm + n^2 \log n)$
|
31 |
+
============== =============================================
|
32 |
+
|
33 |
+
Parameters
|
34 |
+
----------
|
35 |
+
G : NetworkX graph
|
36 |
+
Edges of the graph are expected to have an attribute named by the
|
37 |
+
weight parameter below. If this attribute is not present, the edge is
|
38 |
+
considered to have unit weight.
|
39 |
+
|
40 |
+
weight : string
|
41 |
+
Name of the weight attribute of the edges. If the attribute is not
|
42 |
+
present, unit weight is assumed. Default value: 'weight'.
|
43 |
+
|
44 |
+
heap : class
|
45 |
+
Type of heap to be used in the algorithm. It should be a subclass of
|
46 |
+
:class:`MinHeap` or implement a compatible interface.
|
47 |
+
|
48 |
+
If a stock heap implementation is to be used, :class:`BinaryHeap` is
|
49 |
+
recommended over :class:`PairingHeap` for Python implementations without
|
50 |
+
optimized attribute accesses (e.g., CPython) despite a slower
|
51 |
+
asymptotic running time. For Python implementations with optimized
|
52 |
+
attribute accesses (e.g., PyPy), :class:`PairingHeap` provides better
|
53 |
+
performance. Default value: :class:`BinaryHeap`.
|
54 |
+
|
55 |
+
Returns
|
56 |
+
-------
|
57 |
+
cut_value : integer or float
|
58 |
+
The sum of weights of edges in a minimum cut.
|
59 |
+
|
60 |
+
partition : pair of node lists
|
61 |
+
A partitioning of the nodes that defines a minimum cut.
|
62 |
+
|
63 |
+
Raises
|
64 |
+
------
|
65 |
+
NetworkXNotImplemented
|
66 |
+
If the graph is directed or a multigraph.
|
67 |
+
|
68 |
+
NetworkXError
|
69 |
+
If the graph has less than two nodes, is not connected or has a
|
70 |
+
negative-weighted edge.
|
71 |
+
|
72 |
+
Examples
|
73 |
+
--------
|
74 |
+
>>> G = nx.Graph()
|
75 |
+
>>> G.add_edge("x", "a", weight=3)
|
76 |
+
>>> G.add_edge("x", "b", weight=1)
|
77 |
+
>>> G.add_edge("a", "c", weight=3)
|
78 |
+
>>> G.add_edge("b", "c", weight=5)
|
79 |
+
>>> G.add_edge("b", "d", weight=4)
|
80 |
+
>>> G.add_edge("d", "e", weight=2)
|
81 |
+
>>> G.add_edge("c", "y", weight=2)
|
82 |
+
>>> G.add_edge("e", "y", weight=3)
|
83 |
+
>>> cut_value, partition = nx.stoer_wagner(G)
|
84 |
+
>>> cut_value
|
85 |
+
4
|
86 |
+
"""
|
87 |
+
n = len(G)
|
88 |
+
if n < 2:
|
89 |
+
raise nx.NetworkXError("graph has less than two nodes.")
|
90 |
+
if not nx.is_connected(G):
|
91 |
+
raise nx.NetworkXError("graph is not connected.")
|
92 |
+
|
93 |
+
# Make a copy of the graph for internal use.
|
94 |
+
G = nx.Graph(
|
95 |
+
(u, v, {"weight": e.get(weight, 1)}) for u, v, e in G.edges(data=True) if u != v
|
96 |
+
)
|
97 |
+
G.__networkx_cache__ = None # Disable caching
|
98 |
+
|
99 |
+
for u, v, e in G.edges(data=True):
|
100 |
+
if e["weight"] < 0:
|
101 |
+
raise nx.NetworkXError("graph has a negative-weighted edge.")
|
102 |
+
|
103 |
+
cut_value = float("inf")
|
104 |
+
nodes = set(G)
|
105 |
+
contractions = [] # contracted node pairs
|
106 |
+
|
107 |
+
# Repeatedly pick a pair of nodes to contract until only one node is left.
|
108 |
+
for i in range(n - 1):
|
109 |
+
# Pick an arbitrary node u and create a set A = {u}.
|
110 |
+
u = arbitrary_element(G)
|
111 |
+
A = {u}
|
112 |
+
# Repeatedly pick the node "most tightly connected" to A and add it to
|
113 |
+
# A. The tightness of connectivity of a node not in A is defined by the
|
114 |
+
# of edges connecting it to nodes in A.
|
115 |
+
h = heap() # min-heap emulating a max-heap
|
116 |
+
for v, e in G[u].items():
|
117 |
+
h.insert(v, -e["weight"])
|
118 |
+
# Repeat until all but one node has been added to A.
|
119 |
+
for j in range(n - i - 2):
|
120 |
+
u = h.pop()[0]
|
121 |
+
A.add(u)
|
122 |
+
for v, e in G[u].items():
|
123 |
+
if v not in A:
|
124 |
+
h.insert(v, h.get(v, 0) - e["weight"])
|
125 |
+
# A and the remaining node v define a "cut of the phase". There is a
|
126 |
+
# minimum cut of the original graph that is also a cut of the phase.
|
127 |
+
# Due to contractions in earlier phases, v may in fact represent
|
128 |
+
# multiple nodes in the original graph.
|
129 |
+
v, w = h.min()
|
130 |
+
w = -w
|
131 |
+
if w < cut_value:
|
132 |
+
cut_value = w
|
133 |
+
best_phase = i
|
134 |
+
# Contract v and the last node added to A.
|
135 |
+
contractions.append((u, v))
|
136 |
+
for w, e in G[v].items():
|
137 |
+
if w != u:
|
138 |
+
if w not in G[u]:
|
139 |
+
G.add_edge(u, w, weight=e["weight"])
|
140 |
+
else:
|
141 |
+
G[u][w]["weight"] += e["weight"]
|
142 |
+
G.remove_node(v)
|
143 |
+
|
144 |
+
# Recover the optimal partitioning from the contractions.
|
145 |
+
G = nx.Graph(islice(contractions, best_phase))
|
146 |
+
v = contractions[best_phase][1]
|
147 |
+
G.add_node(v)
|
148 |
+
reachable = set(nx.single_source_shortest_path_length(G, v))
|
149 |
+
partition = (list(reachable), list(nodes - reachable))
|
150 |
+
|
151 |
+
return cut_value, partition
|
venv/lib/python3.10/site-packages/networkx/algorithms/connectivity/utils.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Utilities for connectivity package
|
3 |
+
"""
|
4 |
+
import networkx as nx
|
5 |
+
|
6 |
+
__all__ = ["build_auxiliary_node_connectivity", "build_auxiliary_edge_connectivity"]
|
7 |
+
|
8 |
+
|
9 |
+
@nx._dispatchable(returns_graph=True)
|
10 |
+
def build_auxiliary_node_connectivity(G):
|
11 |
+
r"""Creates a directed graph D from an undirected graph G to compute flow
|
12 |
+
based node connectivity.
|
13 |
+
|
14 |
+
For an undirected graph G having `n` nodes and `m` edges we derive a
|
15 |
+
directed graph D with `2n` nodes and `2m+n` arcs by replacing each
|
16 |
+
original node `v` with two nodes `vA`, `vB` linked by an (internal)
|
17 |
+
arc in D. Then for each edge (`u`, `v`) in G we add two arcs (`uB`, `vA`)
|
18 |
+
and (`vB`, `uA`) in D. Finally we set the attribute capacity = 1 for each
|
19 |
+
arc in D [1]_.
|
20 |
+
|
21 |
+
For a directed graph having `n` nodes and `m` arcs we derive a
|
22 |
+
directed graph D with `2n` nodes and `m+n` arcs by replacing each
|
23 |
+
original node `v` with two nodes `vA`, `vB` linked by an (internal)
|
24 |
+
arc (`vA`, `vB`) in D. Then for each arc (`u`, `v`) in G we add one
|
25 |
+
arc (`uB`, `vA`) in D. Finally we set the attribute capacity = 1 for
|
26 |
+
each arc in D.
|
27 |
+
|
28 |
+
A dictionary with a mapping between nodes in the original graph and the
|
29 |
+
auxiliary digraph is stored as a graph attribute: D.graph['mapping'].
|
30 |
+
|
31 |
+
References
|
32 |
+
----------
|
33 |
+
.. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and
|
34 |
+
Erlebach, 'Network Analysis: Methodological Foundations', Lecture
|
35 |
+
Notes in Computer Science, Volume 3418, Springer-Verlag, 2005.
|
36 |
+
https://doi.org/10.1007/978-3-540-31955-9_7
|
37 |
+
|
38 |
+
"""
|
39 |
+
directed = G.is_directed()
|
40 |
+
|
41 |
+
mapping = {}
|
42 |
+
H = nx.DiGraph()
|
43 |
+
|
44 |
+
for i, node in enumerate(G):
|
45 |
+
mapping[node] = i
|
46 |
+
H.add_node(f"{i}A", id=node)
|
47 |
+
H.add_node(f"{i}B", id=node)
|
48 |
+
H.add_edge(f"{i}A", f"{i}B", capacity=1)
|
49 |
+
|
50 |
+
edges = []
|
51 |
+
for source, target in G.edges():
|
52 |
+
edges.append((f"{mapping[source]}B", f"{mapping[target]}A"))
|
53 |
+
if not directed:
|
54 |
+
edges.append((f"{mapping[target]}B", f"{mapping[source]}A"))
|
55 |
+
H.add_edges_from(edges, capacity=1)
|
56 |
+
|
57 |
+
# Store mapping as graph attribute
|
58 |
+
H.graph["mapping"] = mapping
|
59 |
+
return H
|
60 |
+
|
61 |
+
|
62 |
+
@nx._dispatchable(returns_graph=True)
|
63 |
+
def build_auxiliary_edge_connectivity(G):
|
64 |
+
"""Auxiliary digraph for computing flow based edge connectivity
|
65 |
+
|
66 |
+
If the input graph is undirected, we replace each edge (`u`,`v`) with
|
67 |
+
two reciprocal arcs (`u`, `v`) and (`v`, `u`) and then we set the attribute
|
68 |
+
'capacity' for each arc to 1. If the input graph is directed we simply
|
69 |
+
add the 'capacity' attribute. Part of algorithm 1 in [1]_ .
|
70 |
+
|
71 |
+
References
|
72 |
+
----------
|
73 |
+
.. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. (this is a
|
74 |
+
chapter, look for the reference of the book).
|
75 |
+
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
|
76 |
+
"""
|
77 |
+
if G.is_directed():
|
78 |
+
H = nx.DiGraph()
|
79 |
+
H.add_nodes_from(G.nodes())
|
80 |
+
H.add_edges_from(G.edges(), capacity=1)
|
81 |
+
return H
|
82 |
+
else:
|
83 |
+
H = nx.DiGraph()
|
84 |
+
H.add_nodes_from(G.nodes())
|
85 |
+
for source, target in G.edges():
|
86 |
+
H.add_edges_from([(source, target), (target, source)], capacity=1)
|
87 |
+
return H
|