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/1.word_embeddings.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/18.input_layernorm.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/18.input_layernorm.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/18.input_layernorm.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/5.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/6.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/6.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/6.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__init__.py +87 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/basic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/centrality.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/cluster.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/covering.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/edgelist.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/extendability.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/generators.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/matching.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/matrix.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/projection.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/redundancy.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/spectral.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/basic.py +321 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/centrality.py +290 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/cluster.py +280 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/covering.py +57 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/edgelist.py +359 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/extendability.py +106 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/generators.py +603 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/matching.py +589 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/matrix.py +167 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/projection.py +521 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/redundancy.py +111 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/spectral.py +68 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_basic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_centrality.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_cluster.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_covering.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_edgelist.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_extendability.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_generators.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_matching.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_matrix.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_project.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_redundancy.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_spectral_bipartivity.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/test_basic.py +125 -0
- venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/test_centrality.py +192 -0
ckpts/universal/global_step80/zero/1.word_embeddings.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:68491fcbf42bfbf625bc221306ebd91801701f0241ec3411ec593fbee1cca9bb
|
3 |
+
size 415237325
|
ckpts/universal/global_step80/zero/18.input_layernorm.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:38b46b36b73ee9742442287631f94814ddd87b138e170f5f5bf634f2ecd94043
|
3 |
+
size 9372
|
ckpts/universal/global_step80/zero/18.input_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7969f2295b97ac6e3bd9b83bd3081513bb16b68a686d9fdc41059531dd99a683
|
3 |
+
size 9387
|
ckpts/universal/global_step80/zero/18.input_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:aa5ad192c0e954b27b27b86d0052141f15fe9d8319f9909fbd96cd38dc28f15f
|
3 |
+
size 9293
|
ckpts/universal/global_step80/zero/5.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b739d1a82df9c4b1fc226a359c7e28f8a6641733146ff983d23c46cca9796216
|
3 |
+
size 33555627
|
ckpts/universal/global_step80/zero/6.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:615244d63b375c85c8c7f56e42809c7ebe07454f8fc134a67a6b8220014341e8
|
3 |
+
size 33555612
|
ckpts/universal/global_step80/zero/6.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:35be3ce4136ac8b8aa9320c963ace045f1a8eea53c118aee2ea459ddf8b90191
|
3 |
+
size 33555627
|
ckpts/universal/global_step80/zero/6.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:ccb8dc5d14afdb3f3b1725d0d5b4f4a679a4d326023cb56b917dfc9ea4383071
|
3 |
+
size 33555533
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__init__.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
r""" This module provides functions and operations for bipartite
|
2 |
+
graphs. Bipartite graphs `B = (U, V, E)` have two node sets `U,V` and edges in
|
3 |
+
`E` that only connect nodes from opposite sets. It is common in the literature
|
4 |
+
to use an spatial analogy referring to the two node sets as top and bottom nodes.
|
5 |
+
|
6 |
+
The bipartite algorithms are not imported into the networkx namespace
|
7 |
+
at the top level so the easiest way to use them is with:
|
8 |
+
|
9 |
+
>>> from networkx.algorithms import bipartite
|
10 |
+
|
11 |
+
NetworkX does not have a custom bipartite graph class but the Graph()
|
12 |
+
or DiGraph() classes can be used to represent bipartite graphs. However,
|
13 |
+
you have to keep track of which set each node belongs to, and make
|
14 |
+
sure that there is no edge between nodes of the same set. The convention used
|
15 |
+
in NetworkX is to use a node attribute named `bipartite` with values 0 or 1 to
|
16 |
+
identify the sets each node belongs to. This convention is not enforced in
|
17 |
+
the source code of bipartite functions, it's only a recommendation.
|
18 |
+
|
19 |
+
For example:
|
20 |
+
|
21 |
+
>>> B = nx.Graph()
|
22 |
+
>>> # Add nodes with the node attribute "bipartite"
|
23 |
+
>>> B.add_nodes_from([1, 2, 3, 4], bipartite=0)
|
24 |
+
>>> B.add_nodes_from(["a", "b", "c"], bipartite=1)
|
25 |
+
>>> # Add edges only between nodes of opposite node sets
|
26 |
+
>>> B.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
|
27 |
+
|
28 |
+
Many algorithms of the bipartite module of NetworkX require, as an argument, a
|
29 |
+
container with all the nodes that belong to one set, in addition to the bipartite
|
30 |
+
graph `B`. The functions in the bipartite package do not check that the node set
|
31 |
+
is actually correct nor that the input graph is actually bipartite.
|
32 |
+
If `B` is connected, you can find the two node sets using a two-coloring
|
33 |
+
algorithm:
|
34 |
+
|
35 |
+
>>> nx.is_connected(B)
|
36 |
+
True
|
37 |
+
>>> bottom_nodes, top_nodes = bipartite.sets(B)
|
38 |
+
|
39 |
+
However, if the input graph is not connected, there are more than one possible
|
40 |
+
colorations. This is the reason why we require the user to pass a container
|
41 |
+
with all nodes of one bipartite node set as an argument to most bipartite
|
42 |
+
functions. In the face of ambiguity, we refuse the temptation to guess and
|
43 |
+
raise an :exc:`AmbiguousSolution <networkx.AmbiguousSolution>`
|
44 |
+
Exception if the input graph for
|
45 |
+
:func:`bipartite.sets <networkx.algorithms.bipartite.basic.sets>`
|
46 |
+
is disconnected.
|
47 |
+
|
48 |
+
Using the `bipartite` node attribute, you can easily get the two node sets:
|
49 |
+
|
50 |
+
>>> top_nodes = {n for n, d in B.nodes(data=True) if d["bipartite"] == 0}
|
51 |
+
>>> bottom_nodes = set(B) - top_nodes
|
52 |
+
|
53 |
+
So you can easily use the bipartite algorithms that require, as an argument, a
|
54 |
+
container with all nodes that belong to one node set:
|
55 |
+
|
56 |
+
>>> print(round(bipartite.density(B, bottom_nodes), 2))
|
57 |
+
0.5
|
58 |
+
>>> G = bipartite.projected_graph(B, top_nodes)
|
59 |
+
|
60 |
+
All bipartite graph generators in NetworkX build bipartite graphs with the
|
61 |
+
`bipartite` node attribute. Thus, you can use the same approach:
|
62 |
+
|
63 |
+
>>> RB = bipartite.random_graph(5, 7, 0.2)
|
64 |
+
>>> RB_top = {n for n, d in RB.nodes(data=True) if d["bipartite"] == 0}
|
65 |
+
>>> RB_bottom = set(RB) - RB_top
|
66 |
+
>>> list(RB_top)
|
67 |
+
[0, 1, 2, 3, 4]
|
68 |
+
>>> list(RB_bottom)
|
69 |
+
[5, 6, 7, 8, 9, 10, 11]
|
70 |
+
|
71 |
+
For other bipartite graph generators see
|
72 |
+
:mod:`Generators <networkx.algorithms.bipartite.generators>`.
|
73 |
+
|
74 |
+
"""
|
75 |
+
|
76 |
+
from networkx.algorithms.bipartite.basic import *
|
77 |
+
from networkx.algorithms.bipartite.centrality import *
|
78 |
+
from networkx.algorithms.bipartite.cluster import *
|
79 |
+
from networkx.algorithms.bipartite.covering import *
|
80 |
+
from networkx.algorithms.bipartite.edgelist import *
|
81 |
+
from networkx.algorithms.bipartite.matching import *
|
82 |
+
from networkx.algorithms.bipartite.matrix import *
|
83 |
+
from networkx.algorithms.bipartite.projection import *
|
84 |
+
from networkx.algorithms.bipartite.redundancy import *
|
85 |
+
from networkx.algorithms.bipartite.spectral import *
|
86 |
+
from networkx.algorithms.bipartite.generators import *
|
87 |
+
from networkx.algorithms.bipartite.extendability import *
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (4 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/basic.cpython-310.pyc
ADDED
Binary file (8.48 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/centrality.cpython-310.pyc
ADDED
Binary file (9.15 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/cluster.cpython-310.pyc
ADDED
Binary file (7.51 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/covering.cpython-310.pyc
ADDED
Binary file (2.28 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/edgelist.cpython-310.pyc
ADDED
Binary file (10.8 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/extendability.cpython-310.pyc
ADDED
Binary file (4.07 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/generators.cpython-310.pyc
ADDED
Binary file (18.9 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/matching.cpython-310.pyc
ADDED
Binary file (16.2 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/matrix.cpython-310.pyc
ADDED
Binary file (6.05 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/projection.cpython-310.pyc
ADDED
Binary file (17.9 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/redundancy.cpython-310.pyc
ADDED
Binary file (4.04 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/__pycache__/spectral.cpython-310.pyc
ADDED
Binary file (1.94 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/basic.py
ADDED
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
==========================
|
3 |
+
Bipartite Graph Algorithms
|
4 |
+
==========================
|
5 |
+
"""
|
6 |
+
import networkx as nx
|
7 |
+
from networkx.algorithms.components import connected_components
|
8 |
+
from networkx.exception import AmbiguousSolution
|
9 |
+
|
10 |
+
__all__ = [
|
11 |
+
"is_bipartite",
|
12 |
+
"is_bipartite_node_set",
|
13 |
+
"color",
|
14 |
+
"sets",
|
15 |
+
"density",
|
16 |
+
"degrees",
|
17 |
+
]
|
18 |
+
|
19 |
+
|
20 |
+
@nx._dispatchable
|
21 |
+
def color(G):
|
22 |
+
"""Returns a two-coloring of the graph.
|
23 |
+
|
24 |
+
Raises an exception if the graph is not bipartite.
|
25 |
+
|
26 |
+
Parameters
|
27 |
+
----------
|
28 |
+
G : NetworkX graph
|
29 |
+
|
30 |
+
Returns
|
31 |
+
-------
|
32 |
+
color : dictionary
|
33 |
+
A dictionary keyed by node with a 1 or 0 as data for each node color.
|
34 |
+
|
35 |
+
Raises
|
36 |
+
------
|
37 |
+
NetworkXError
|
38 |
+
If the graph is not two-colorable.
|
39 |
+
|
40 |
+
Examples
|
41 |
+
--------
|
42 |
+
>>> from networkx.algorithms import bipartite
|
43 |
+
>>> G = nx.path_graph(4)
|
44 |
+
>>> c = bipartite.color(G)
|
45 |
+
>>> print(c)
|
46 |
+
{0: 1, 1: 0, 2: 1, 3: 0}
|
47 |
+
|
48 |
+
You can use this to set a node attribute indicating the bipartite set:
|
49 |
+
|
50 |
+
>>> nx.set_node_attributes(G, c, "bipartite")
|
51 |
+
>>> print(G.nodes[0]["bipartite"])
|
52 |
+
1
|
53 |
+
>>> print(G.nodes[1]["bipartite"])
|
54 |
+
0
|
55 |
+
"""
|
56 |
+
if G.is_directed():
|
57 |
+
import itertools
|
58 |
+
|
59 |
+
def neighbors(v):
|
60 |
+
return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
|
61 |
+
|
62 |
+
else:
|
63 |
+
neighbors = G.neighbors
|
64 |
+
|
65 |
+
color = {}
|
66 |
+
for n in G: # handle disconnected graphs
|
67 |
+
if n in color or len(G[n]) == 0: # skip isolates
|
68 |
+
continue
|
69 |
+
queue = [n]
|
70 |
+
color[n] = 1 # nodes seen with color (1 or 0)
|
71 |
+
while queue:
|
72 |
+
v = queue.pop()
|
73 |
+
c = 1 - color[v] # opposite color of node v
|
74 |
+
for w in neighbors(v):
|
75 |
+
if w in color:
|
76 |
+
if color[w] == color[v]:
|
77 |
+
raise nx.NetworkXError("Graph is not bipartite.")
|
78 |
+
else:
|
79 |
+
color[w] = c
|
80 |
+
queue.append(w)
|
81 |
+
# color isolates with 0
|
82 |
+
color.update(dict.fromkeys(nx.isolates(G), 0))
|
83 |
+
return color
|
84 |
+
|
85 |
+
|
86 |
+
@nx._dispatchable
|
87 |
+
def is_bipartite(G):
|
88 |
+
"""Returns True if graph G is bipartite, False if not.
|
89 |
+
|
90 |
+
Parameters
|
91 |
+
----------
|
92 |
+
G : NetworkX graph
|
93 |
+
|
94 |
+
Examples
|
95 |
+
--------
|
96 |
+
>>> from networkx.algorithms import bipartite
|
97 |
+
>>> G = nx.path_graph(4)
|
98 |
+
>>> print(bipartite.is_bipartite(G))
|
99 |
+
True
|
100 |
+
|
101 |
+
See Also
|
102 |
+
--------
|
103 |
+
color, is_bipartite_node_set
|
104 |
+
"""
|
105 |
+
try:
|
106 |
+
color(G)
|
107 |
+
return True
|
108 |
+
except nx.NetworkXError:
|
109 |
+
return False
|
110 |
+
|
111 |
+
|
112 |
+
@nx._dispatchable
|
113 |
+
def is_bipartite_node_set(G, nodes):
|
114 |
+
"""Returns True if nodes and G/nodes are a bipartition of G.
|
115 |
+
|
116 |
+
Parameters
|
117 |
+
----------
|
118 |
+
G : NetworkX graph
|
119 |
+
|
120 |
+
nodes: list or container
|
121 |
+
Check if nodes are a one of a bipartite set.
|
122 |
+
|
123 |
+
Examples
|
124 |
+
--------
|
125 |
+
>>> from networkx.algorithms import bipartite
|
126 |
+
>>> G = nx.path_graph(4)
|
127 |
+
>>> X = set([1, 3])
|
128 |
+
>>> bipartite.is_bipartite_node_set(G, X)
|
129 |
+
True
|
130 |
+
|
131 |
+
Notes
|
132 |
+
-----
|
133 |
+
An exception is raised if the input nodes are not distinct, because in this
|
134 |
+
case some bipartite algorithms will yield incorrect results.
|
135 |
+
For connected graphs the bipartite sets are unique. This function handles
|
136 |
+
disconnected graphs.
|
137 |
+
"""
|
138 |
+
S = set(nodes)
|
139 |
+
|
140 |
+
if len(S) < len(nodes):
|
141 |
+
# this should maybe just return False?
|
142 |
+
raise AmbiguousSolution(
|
143 |
+
"The input node set contains duplicates.\n"
|
144 |
+
"This may lead to incorrect results when using it in bipartite algorithms.\n"
|
145 |
+
"Consider using set(nodes) as the input"
|
146 |
+
)
|
147 |
+
|
148 |
+
for CC in (G.subgraph(c).copy() for c in connected_components(G)):
|
149 |
+
X, Y = sets(CC)
|
150 |
+
if not (
|
151 |
+
(X.issubset(S) and Y.isdisjoint(S)) or (Y.issubset(S) and X.isdisjoint(S))
|
152 |
+
):
|
153 |
+
return False
|
154 |
+
return True
|
155 |
+
|
156 |
+
|
157 |
+
@nx._dispatchable
|
158 |
+
def sets(G, top_nodes=None):
|
159 |
+
"""Returns bipartite node sets of graph G.
|
160 |
+
|
161 |
+
Raises an exception if the graph is not bipartite or if the input
|
162 |
+
graph is disconnected and thus more than one valid solution exists.
|
163 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
164 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
165 |
+
|
166 |
+
Parameters
|
167 |
+
----------
|
168 |
+
G : NetworkX graph
|
169 |
+
|
170 |
+
top_nodes : container, optional
|
171 |
+
Container with all nodes in one bipartite node set. If not supplied
|
172 |
+
it will be computed. But if more than one solution exists an exception
|
173 |
+
will be raised.
|
174 |
+
|
175 |
+
Returns
|
176 |
+
-------
|
177 |
+
X : set
|
178 |
+
Nodes from one side of the bipartite graph.
|
179 |
+
Y : set
|
180 |
+
Nodes from the other side.
|
181 |
+
|
182 |
+
Raises
|
183 |
+
------
|
184 |
+
AmbiguousSolution
|
185 |
+
Raised if the input bipartite graph is disconnected and no container
|
186 |
+
with all nodes in one bipartite set is provided. When determining
|
187 |
+
the nodes in each bipartite set more than one valid solution is
|
188 |
+
possible if the input graph is disconnected.
|
189 |
+
NetworkXError
|
190 |
+
Raised if the input graph is not bipartite.
|
191 |
+
|
192 |
+
Examples
|
193 |
+
--------
|
194 |
+
>>> from networkx.algorithms import bipartite
|
195 |
+
>>> G = nx.path_graph(4)
|
196 |
+
>>> X, Y = bipartite.sets(G)
|
197 |
+
>>> list(X)
|
198 |
+
[0, 2]
|
199 |
+
>>> list(Y)
|
200 |
+
[1, 3]
|
201 |
+
|
202 |
+
See Also
|
203 |
+
--------
|
204 |
+
color
|
205 |
+
|
206 |
+
"""
|
207 |
+
if G.is_directed():
|
208 |
+
is_connected = nx.is_weakly_connected
|
209 |
+
else:
|
210 |
+
is_connected = nx.is_connected
|
211 |
+
if top_nodes is not None:
|
212 |
+
X = set(top_nodes)
|
213 |
+
Y = set(G) - X
|
214 |
+
else:
|
215 |
+
if not is_connected(G):
|
216 |
+
msg = "Disconnected graph: Ambiguous solution for bipartite sets."
|
217 |
+
raise nx.AmbiguousSolution(msg)
|
218 |
+
c = color(G)
|
219 |
+
X = {n for n, is_top in c.items() if is_top}
|
220 |
+
Y = {n for n, is_top in c.items() if not is_top}
|
221 |
+
return (X, Y)
|
222 |
+
|
223 |
+
|
224 |
+
@nx._dispatchable(graphs="B")
|
225 |
+
def density(B, nodes):
|
226 |
+
"""Returns density of bipartite graph B.
|
227 |
+
|
228 |
+
Parameters
|
229 |
+
----------
|
230 |
+
B : NetworkX graph
|
231 |
+
|
232 |
+
nodes: list or container
|
233 |
+
Nodes in one node set of the bipartite graph.
|
234 |
+
|
235 |
+
Returns
|
236 |
+
-------
|
237 |
+
d : float
|
238 |
+
The bipartite density
|
239 |
+
|
240 |
+
Examples
|
241 |
+
--------
|
242 |
+
>>> from networkx.algorithms import bipartite
|
243 |
+
>>> G = nx.complete_bipartite_graph(3, 2)
|
244 |
+
>>> X = set([0, 1, 2])
|
245 |
+
>>> bipartite.density(G, X)
|
246 |
+
1.0
|
247 |
+
>>> Y = set([3, 4])
|
248 |
+
>>> bipartite.density(G, Y)
|
249 |
+
1.0
|
250 |
+
|
251 |
+
Notes
|
252 |
+
-----
|
253 |
+
The container of nodes passed as argument must contain all nodes
|
254 |
+
in one of the two bipartite node sets to avoid ambiguity in the
|
255 |
+
case of disconnected graphs.
|
256 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
257 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
258 |
+
|
259 |
+
See Also
|
260 |
+
--------
|
261 |
+
color
|
262 |
+
"""
|
263 |
+
n = len(B)
|
264 |
+
m = nx.number_of_edges(B)
|
265 |
+
nb = len(nodes)
|
266 |
+
nt = n - nb
|
267 |
+
if m == 0: # includes cases n==0 and n==1
|
268 |
+
d = 0.0
|
269 |
+
else:
|
270 |
+
if B.is_directed():
|
271 |
+
d = m / (2 * nb * nt)
|
272 |
+
else:
|
273 |
+
d = m / (nb * nt)
|
274 |
+
return d
|
275 |
+
|
276 |
+
|
277 |
+
@nx._dispatchable(graphs="B", edge_attrs="weight")
|
278 |
+
def degrees(B, nodes, weight=None):
|
279 |
+
"""Returns the degrees of the two node sets in the bipartite graph B.
|
280 |
+
|
281 |
+
Parameters
|
282 |
+
----------
|
283 |
+
B : NetworkX graph
|
284 |
+
|
285 |
+
nodes: list or container
|
286 |
+
Nodes in one node set of the bipartite graph.
|
287 |
+
|
288 |
+
weight : string or None, optional (default=None)
|
289 |
+
The edge attribute that holds the numerical value used as a weight.
|
290 |
+
If None, then each edge has weight 1.
|
291 |
+
The degree is the sum of the edge weights adjacent to the node.
|
292 |
+
|
293 |
+
Returns
|
294 |
+
-------
|
295 |
+
(degX,degY) : tuple of dictionaries
|
296 |
+
The degrees of the two bipartite sets as dictionaries keyed by node.
|
297 |
+
|
298 |
+
Examples
|
299 |
+
--------
|
300 |
+
>>> from networkx.algorithms import bipartite
|
301 |
+
>>> G = nx.complete_bipartite_graph(3, 2)
|
302 |
+
>>> Y = set([3, 4])
|
303 |
+
>>> degX, degY = bipartite.degrees(G, Y)
|
304 |
+
>>> dict(degX)
|
305 |
+
{0: 2, 1: 2, 2: 2}
|
306 |
+
|
307 |
+
Notes
|
308 |
+
-----
|
309 |
+
The container of nodes passed as argument must contain all nodes
|
310 |
+
in one of the two bipartite node sets to avoid ambiguity in the
|
311 |
+
case of disconnected graphs.
|
312 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
313 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
314 |
+
|
315 |
+
See Also
|
316 |
+
--------
|
317 |
+
color, density
|
318 |
+
"""
|
319 |
+
bottom = set(nodes)
|
320 |
+
top = set(B) - bottom
|
321 |
+
return (B.degree(top, weight), B.degree(bottom, weight))
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/centrality.py
ADDED
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
|
3 |
+
__all__ = ["degree_centrality", "betweenness_centrality", "closeness_centrality"]
|
4 |
+
|
5 |
+
|
6 |
+
@nx._dispatchable(name="bipartite_degree_centrality")
|
7 |
+
def degree_centrality(G, nodes):
|
8 |
+
r"""Compute the degree centrality for nodes in a bipartite network.
|
9 |
+
|
10 |
+
The degree centrality for a node `v` is the fraction of nodes
|
11 |
+
connected to it.
|
12 |
+
|
13 |
+
Parameters
|
14 |
+
----------
|
15 |
+
G : graph
|
16 |
+
A bipartite network
|
17 |
+
|
18 |
+
nodes : list or container
|
19 |
+
Container with all nodes in one bipartite node set.
|
20 |
+
|
21 |
+
Returns
|
22 |
+
-------
|
23 |
+
centrality : dictionary
|
24 |
+
Dictionary keyed by node with bipartite degree centrality as the value.
|
25 |
+
|
26 |
+
Examples
|
27 |
+
--------
|
28 |
+
>>> G = nx.wheel_graph(5)
|
29 |
+
>>> top_nodes = {0, 1, 2}
|
30 |
+
>>> nx.bipartite.degree_centrality(G, nodes=top_nodes)
|
31 |
+
{0: 2.0, 1: 1.5, 2: 1.5, 3: 1.0, 4: 1.0}
|
32 |
+
|
33 |
+
See Also
|
34 |
+
--------
|
35 |
+
betweenness_centrality
|
36 |
+
closeness_centrality
|
37 |
+
:func:`~networkx.algorithms.bipartite.basic.sets`
|
38 |
+
:func:`~networkx.algorithms.bipartite.basic.is_bipartite`
|
39 |
+
|
40 |
+
Notes
|
41 |
+
-----
|
42 |
+
The nodes input parameter must contain all nodes in one bipartite node set,
|
43 |
+
but the dictionary returned contains all nodes from both bipartite node
|
44 |
+
sets. See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
45 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
46 |
+
|
47 |
+
For unipartite networks, the degree centrality values are
|
48 |
+
normalized by dividing by the maximum possible degree (which is
|
49 |
+
`n-1` where `n` is the number of nodes in G).
|
50 |
+
|
51 |
+
In the bipartite case, the maximum possible degree of a node in a
|
52 |
+
bipartite node set is the number of nodes in the opposite node set
|
53 |
+
[1]_. The degree centrality for a node `v` in the bipartite
|
54 |
+
sets `U` with `n` nodes and `V` with `m` nodes is
|
55 |
+
|
56 |
+
.. math::
|
57 |
+
|
58 |
+
d_{v} = \frac{deg(v)}{m}, \mbox{for} v \in U ,
|
59 |
+
|
60 |
+
d_{v} = \frac{deg(v)}{n}, \mbox{for} v \in V ,
|
61 |
+
|
62 |
+
|
63 |
+
where `deg(v)` is the degree of node `v`.
|
64 |
+
|
65 |
+
References
|
66 |
+
----------
|
67 |
+
.. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
|
68 |
+
Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
|
69 |
+
of Social Network Analysis. Sage Publications.
|
70 |
+
https://dx.doi.org/10.4135/9781446294413.n28
|
71 |
+
"""
|
72 |
+
top = set(nodes)
|
73 |
+
bottom = set(G) - top
|
74 |
+
s = 1.0 / len(bottom)
|
75 |
+
centrality = {n: d * s for n, d in G.degree(top)}
|
76 |
+
s = 1.0 / len(top)
|
77 |
+
centrality.update({n: d * s for n, d in G.degree(bottom)})
|
78 |
+
return centrality
|
79 |
+
|
80 |
+
|
81 |
+
@nx._dispatchable(name="bipartite_betweenness_centrality")
|
82 |
+
def betweenness_centrality(G, nodes):
|
83 |
+
r"""Compute betweenness centrality for nodes in a bipartite network.
|
84 |
+
|
85 |
+
Betweenness centrality of a node `v` is the sum of the
|
86 |
+
fraction of all-pairs shortest paths that pass through `v`.
|
87 |
+
|
88 |
+
Values of betweenness are normalized by the maximum possible
|
89 |
+
value which for bipartite graphs is limited by the relative size
|
90 |
+
of the two node sets [1]_.
|
91 |
+
|
92 |
+
Let `n` be the number of nodes in the node set `U` and
|
93 |
+
`m` be the number of nodes in the node set `V`, then
|
94 |
+
nodes in `U` are normalized by dividing by
|
95 |
+
|
96 |
+
.. math::
|
97 |
+
|
98 |
+
\frac{1}{2} [m^2 (s + 1)^2 + m (s + 1)(2t - s - 1) - t (2s - t + 3)] ,
|
99 |
+
|
100 |
+
where
|
101 |
+
|
102 |
+
.. math::
|
103 |
+
|
104 |
+
s = (n - 1) \div m , t = (n - 1) \mod m ,
|
105 |
+
|
106 |
+
and nodes in `V` are normalized by dividing by
|
107 |
+
|
108 |
+
.. math::
|
109 |
+
|
110 |
+
\frac{1}{2} [n^2 (p + 1)^2 + n (p + 1)(2r - p - 1) - r (2p - r + 3)] ,
|
111 |
+
|
112 |
+
where,
|
113 |
+
|
114 |
+
.. math::
|
115 |
+
|
116 |
+
p = (m - 1) \div n , r = (m - 1) \mod n .
|
117 |
+
|
118 |
+
Parameters
|
119 |
+
----------
|
120 |
+
G : graph
|
121 |
+
A bipartite graph
|
122 |
+
|
123 |
+
nodes : list or container
|
124 |
+
Container with all nodes in one bipartite node set.
|
125 |
+
|
126 |
+
Returns
|
127 |
+
-------
|
128 |
+
betweenness : dictionary
|
129 |
+
Dictionary keyed by node with bipartite betweenness centrality
|
130 |
+
as the value.
|
131 |
+
|
132 |
+
Examples
|
133 |
+
--------
|
134 |
+
>>> G = nx.cycle_graph(4)
|
135 |
+
>>> top_nodes = {1, 2}
|
136 |
+
>>> nx.bipartite.betweenness_centrality(G, nodes=top_nodes)
|
137 |
+
{0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
|
138 |
+
|
139 |
+
See Also
|
140 |
+
--------
|
141 |
+
degree_centrality
|
142 |
+
closeness_centrality
|
143 |
+
:func:`~networkx.algorithms.bipartite.basic.sets`
|
144 |
+
:func:`~networkx.algorithms.bipartite.basic.is_bipartite`
|
145 |
+
|
146 |
+
Notes
|
147 |
+
-----
|
148 |
+
The nodes input parameter must contain all nodes in one bipartite node set,
|
149 |
+
but the dictionary returned contains all nodes from both node sets.
|
150 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
151 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
152 |
+
|
153 |
+
|
154 |
+
References
|
155 |
+
----------
|
156 |
+
.. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
|
157 |
+
Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
|
158 |
+
of Social Network Analysis. Sage Publications.
|
159 |
+
https://dx.doi.org/10.4135/9781446294413.n28
|
160 |
+
"""
|
161 |
+
top = set(nodes)
|
162 |
+
bottom = set(G) - top
|
163 |
+
n = len(top)
|
164 |
+
m = len(bottom)
|
165 |
+
s, t = divmod(n - 1, m)
|
166 |
+
bet_max_top = (
|
167 |
+
((m**2) * ((s + 1) ** 2))
|
168 |
+
+ (m * (s + 1) * (2 * t - s - 1))
|
169 |
+
- (t * ((2 * s) - t + 3))
|
170 |
+
) / 2.0
|
171 |
+
p, r = divmod(m - 1, n)
|
172 |
+
bet_max_bot = (
|
173 |
+
((n**2) * ((p + 1) ** 2))
|
174 |
+
+ (n * (p + 1) * (2 * r - p - 1))
|
175 |
+
- (r * ((2 * p) - r + 3))
|
176 |
+
) / 2.0
|
177 |
+
betweenness = nx.betweenness_centrality(G, normalized=False, weight=None)
|
178 |
+
for node in top:
|
179 |
+
betweenness[node] /= bet_max_top
|
180 |
+
for node in bottom:
|
181 |
+
betweenness[node] /= bet_max_bot
|
182 |
+
return betweenness
|
183 |
+
|
184 |
+
|
185 |
+
@nx._dispatchable(name="bipartite_closeness_centrality")
|
186 |
+
def closeness_centrality(G, nodes, normalized=True):
|
187 |
+
r"""Compute the closeness centrality for nodes in a bipartite network.
|
188 |
+
|
189 |
+
The closeness of a node is the distance to all other nodes in the
|
190 |
+
graph or in the case that the graph is not connected to all other nodes
|
191 |
+
in the connected component containing that node.
|
192 |
+
|
193 |
+
Parameters
|
194 |
+
----------
|
195 |
+
G : graph
|
196 |
+
A bipartite network
|
197 |
+
|
198 |
+
nodes : list or container
|
199 |
+
Container with all nodes in one bipartite node set.
|
200 |
+
|
201 |
+
normalized : bool, optional
|
202 |
+
If True (default) normalize by connected component size.
|
203 |
+
|
204 |
+
Returns
|
205 |
+
-------
|
206 |
+
closeness : dictionary
|
207 |
+
Dictionary keyed by node with bipartite closeness centrality
|
208 |
+
as the value.
|
209 |
+
|
210 |
+
Examples
|
211 |
+
--------
|
212 |
+
>>> G = nx.wheel_graph(5)
|
213 |
+
>>> top_nodes = {0, 1, 2}
|
214 |
+
>>> nx.bipartite.closeness_centrality(G, nodes=top_nodes)
|
215 |
+
{0: 1.5, 1: 1.2, 2: 1.2, 3: 1.0, 4: 1.0}
|
216 |
+
|
217 |
+
See Also
|
218 |
+
--------
|
219 |
+
betweenness_centrality
|
220 |
+
degree_centrality
|
221 |
+
:func:`~networkx.algorithms.bipartite.basic.sets`
|
222 |
+
:func:`~networkx.algorithms.bipartite.basic.is_bipartite`
|
223 |
+
|
224 |
+
Notes
|
225 |
+
-----
|
226 |
+
The nodes input parameter must contain all nodes in one bipartite node set,
|
227 |
+
but the dictionary returned contains all nodes from both node sets.
|
228 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
229 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
230 |
+
|
231 |
+
|
232 |
+
Closeness centrality is normalized by the minimum distance possible.
|
233 |
+
In the bipartite case the minimum distance for a node in one bipartite
|
234 |
+
node set is 1 from all nodes in the other node set and 2 from all
|
235 |
+
other nodes in its own set [1]_. Thus the closeness centrality
|
236 |
+
for node `v` in the two bipartite sets `U` with
|
237 |
+
`n` nodes and `V` with `m` nodes is
|
238 |
+
|
239 |
+
.. math::
|
240 |
+
|
241 |
+
c_{v} = \frac{m + 2(n - 1)}{d}, \mbox{for} v \in U,
|
242 |
+
|
243 |
+
c_{v} = \frac{n + 2(m - 1)}{d}, \mbox{for} v \in V,
|
244 |
+
|
245 |
+
where `d` is the sum of the distances from `v` to all
|
246 |
+
other nodes.
|
247 |
+
|
248 |
+
Higher values of closeness indicate higher centrality.
|
249 |
+
|
250 |
+
As in the unipartite case, setting normalized=True causes the
|
251 |
+
values to normalized further to n-1 / size(G)-1 where n is the
|
252 |
+
number of nodes in the connected part of graph containing the
|
253 |
+
node. If the graph is not completely connected, this algorithm
|
254 |
+
computes the closeness centrality for each connected part
|
255 |
+
separately.
|
256 |
+
|
257 |
+
References
|
258 |
+
----------
|
259 |
+
.. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
|
260 |
+
Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
|
261 |
+
of Social Network Analysis. Sage Publications.
|
262 |
+
https://dx.doi.org/10.4135/9781446294413.n28
|
263 |
+
"""
|
264 |
+
closeness = {}
|
265 |
+
path_length = nx.single_source_shortest_path_length
|
266 |
+
top = set(nodes)
|
267 |
+
bottom = set(G) - top
|
268 |
+
n = len(top)
|
269 |
+
m = len(bottom)
|
270 |
+
for node in top:
|
271 |
+
sp = dict(path_length(G, node))
|
272 |
+
totsp = sum(sp.values())
|
273 |
+
if totsp > 0.0 and len(G) > 1:
|
274 |
+
closeness[node] = (m + 2 * (n - 1)) / totsp
|
275 |
+
if normalized:
|
276 |
+
s = (len(sp) - 1) / (len(G) - 1)
|
277 |
+
closeness[node] *= s
|
278 |
+
else:
|
279 |
+
closeness[node] = 0.0
|
280 |
+
for node in bottom:
|
281 |
+
sp = dict(path_length(G, node))
|
282 |
+
totsp = sum(sp.values())
|
283 |
+
if totsp > 0.0 and len(G) > 1:
|
284 |
+
closeness[node] = (n + 2 * (m - 1)) / totsp
|
285 |
+
if normalized:
|
286 |
+
s = (len(sp) - 1) / (len(G) - 1)
|
287 |
+
closeness[node] *= s
|
288 |
+
else:
|
289 |
+
closeness[node] = 0.0
|
290 |
+
return closeness
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/cluster.py
ADDED
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Functions for computing clustering of pairs
|
2 |
+
|
3 |
+
"""
|
4 |
+
|
5 |
+
import itertools
|
6 |
+
|
7 |
+
import networkx as nx
|
8 |
+
|
9 |
+
__all__ = [
|
10 |
+
"clustering",
|
11 |
+
"average_clustering",
|
12 |
+
"latapy_clustering",
|
13 |
+
"robins_alexander_clustering",
|
14 |
+
]
|
15 |
+
|
16 |
+
|
17 |
+
def cc_dot(nu, nv):
|
18 |
+
return len(nu & nv) / len(nu | nv)
|
19 |
+
|
20 |
+
|
21 |
+
def cc_max(nu, nv):
|
22 |
+
return len(nu & nv) / max(len(nu), len(nv))
|
23 |
+
|
24 |
+
|
25 |
+
def cc_min(nu, nv):
|
26 |
+
return len(nu & nv) / min(len(nu), len(nv))
|
27 |
+
|
28 |
+
|
29 |
+
modes = {"dot": cc_dot, "min": cc_min, "max": cc_max}
|
30 |
+
|
31 |
+
|
32 |
+
@nx._dispatchable
|
33 |
+
def latapy_clustering(G, nodes=None, mode="dot"):
|
34 |
+
r"""Compute a bipartite clustering coefficient for nodes.
|
35 |
+
|
36 |
+
The bipartite clustering coefficient is a measure of local density
|
37 |
+
of connections defined as [1]_:
|
38 |
+
|
39 |
+
.. math::
|
40 |
+
|
41 |
+
c_u = \frac{\sum_{v \in N(N(u))} c_{uv} }{|N(N(u))|}
|
42 |
+
|
43 |
+
where `N(N(u))` are the second order neighbors of `u` in `G` excluding `u`,
|
44 |
+
and `c_{uv}` is the pairwise clustering coefficient between nodes
|
45 |
+
`u` and `v`.
|
46 |
+
|
47 |
+
The mode selects the function for `c_{uv}` which can be:
|
48 |
+
|
49 |
+
`dot`:
|
50 |
+
|
51 |
+
.. math::
|
52 |
+
|
53 |
+
c_{uv}=\frac{|N(u)\cap N(v)|}{|N(u) \cup N(v)|}
|
54 |
+
|
55 |
+
`min`:
|
56 |
+
|
57 |
+
.. math::
|
58 |
+
|
59 |
+
c_{uv}=\frac{|N(u)\cap N(v)|}{min(|N(u)|,|N(v)|)}
|
60 |
+
|
61 |
+
`max`:
|
62 |
+
|
63 |
+
.. math::
|
64 |
+
|
65 |
+
c_{uv}=\frac{|N(u)\cap N(v)|}{max(|N(u)|,|N(v)|)}
|
66 |
+
|
67 |
+
|
68 |
+
Parameters
|
69 |
+
----------
|
70 |
+
G : graph
|
71 |
+
A bipartite graph
|
72 |
+
|
73 |
+
nodes : list or iterable (optional)
|
74 |
+
Compute bipartite clustering for these nodes. The default
|
75 |
+
is all nodes in G.
|
76 |
+
|
77 |
+
mode : string
|
78 |
+
The pairwise bipartite clustering method to be used in the computation.
|
79 |
+
It must be "dot", "max", or "min".
|
80 |
+
|
81 |
+
Returns
|
82 |
+
-------
|
83 |
+
clustering : dictionary
|
84 |
+
A dictionary keyed by node with the clustering coefficient value.
|
85 |
+
|
86 |
+
|
87 |
+
Examples
|
88 |
+
--------
|
89 |
+
>>> from networkx.algorithms import bipartite
|
90 |
+
>>> G = nx.path_graph(4) # path graphs are bipartite
|
91 |
+
>>> c = bipartite.clustering(G)
|
92 |
+
>>> c[0]
|
93 |
+
0.5
|
94 |
+
>>> c = bipartite.clustering(G, mode="min")
|
95 |
+
>>> c[0]
|
96 |
+
1.0
|
97 |
+
|
98 |
+
See Also
|
99 |
+
--------
|
100 |
+
robins_alexander_clustering
|
101 |
+
average_clustering
|
102 |
+
networkx.algorithms.cluster.square_clustering
|
103 |
+
|
104 |
+
References
|
105 |
+
----------
|
106 |
+
.. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
|
107 |
+
Basic notions for the analysis of large two-mode networks.
|
108 |
+
Social Networks 30(1), 31--48.
|
109 |
+
"""
|
110 |
+
if not nx.algorithms.bipartite.is_bipartite(G):
|
111 |
+
raise nx.NetworkXError("Graph is not bipartite")
|
112 |
+
|
113 |
+
try:
|
114 |
+
cc_func = modes[mode]
|
115 |
+
except KeyError as err:
|
116 |
+
raise nx.NetworkXError(
|
117 |
+
"Mode for bipartite clustering must be: dot, min or max"
|
118 |
+
) from err
|
119 |
+
|
120 |
+
if nodes is None:
|
121 |
+
nodes = G
|
122 |
+
ccs = {}
|
123 |
+
for v in nodes:
|
124 |
+
cc = 0.0
|
125 |
+
nbrs2 = {u for nbr in G[v] for u in G[nbr]} - {v}
|
126 |
+
for u in nbrs2:
|
127 |
+
cc += cc_func(set(G[u]), set(G[v]))
|
128 |
+
if cc > 0.0: # len(nbrs2)>0
|
129 |
+
cc /= len(nbrs2)
|
130 |
+
ccs[v] = cc
|
131 |
+
return ccs
|
132 |
+
|
133 |
+
|
134 |
+
clustering = latapy_clustering
|
135 |
+
|
136 |
+
|
137 |
+
@nx._dispatchable(name="bipartite_average_clustering")
|
138 |
+
def average_clustering(G, nodes=None, mode="dot"):
|
139 |
+
r"""Compute the average bipartite clustering coefficient.
|
140 |
+
|
141 |
+
A clustering coefficient for the whole graph is the average,
|
142 |
+
|
143 |
+
.. math::
|
144 |
+
|
145 |
+
C = \frac{1}{n}\sum_{v \in G} c_v,
|
146 |
+
|
147 |
+
where `n` is the number of nodes in `G`.
|
148 |
+
|
149 |
+
Similar measures for the two bipartite sets can be defined [1]_
|
150 |
+
|
151 |
+
.. math::
|
152 |
+
|
153 |
+
C_X = \frac{1}{|X|}\sum_{v \in X} c_v,
|
154 |
+
|
155 |
+
where `X` is a bipartite set of `G`.
|
156 |
+
|
157 |
+
Parameters
|
158 |
+
----------
|
159 |
+
G : graph
|
160 |
+
a bipartite graph
|
161 |
+
|
162 |
+
nodes : list or iterable, optional
|
163 |
+
A container of nodes to use in computing the average.
|
164 |
+
The nodes should be either the entire graph (the default) or one of the
|
165 |
+
bipartite sets.
|
166 |
+
|
167 |
+
mode : string
|
168 |
+
The pairwise bipartite clustering method.
|
169 |
+
It must be "dot", "max", or "min"
|
170 |
+
|
171 |
+
Returns
|
172 |
+
-------
|
173 |
+
clustering : float
|
174 |
+
The average bipartite clustering for the given set of nodes or the
|
175 |
+
entire graph if no nodes are specified.
|
176 |
+
|
177 |
+
Examples
|
178 |
+
--------
|
179 |
+
>>> from networkx.algorithms import bipartite
|
180 |
+
>>> G = nx.star_graph(3) # star graphs are bipartite
|
181 |
+
>>> bipartite.average_clustering(G)
|
182 |
+
0.75
|
183 |
+
>>> X, Y = bipartite.sets(G)
|
184 |
+
>>> bipartite.average_clustering(G, X)
|
185 |
+
0.0
|
186 |
+
>>> bipartite.average_clustering(G, Y)
|
187 |
+
1.0
|
188 |
+
|
189 |
+
See Also
|
190 |
+
--------
|
191 |
+
clustering
|
192 |
+
|
193 |
+
Notes
|
194 |
+
-----
|
195 |
+
The container of nodes passed to this function must contain all of the nodes
|
196 |
+
in one of the bipartite sets ("top" or "bottom") in order to compute
|
197 |
+
the correct average bipartite clustering coefficients.
|
198 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
199 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
200 |
+
|
201 |
+
|
202 |
+
References
|
203 |
+
----------
|
204 |
+
.. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
|
205 |
+
Basic notions for the analysis of large two-mode networks.
|
206 |
+
Social Networks 30(1), 31--48.
|
207 |
+
"""
|
208 |
+
if nodes is None:
|
209 |
+
nodes = G
|
210 |
+
ccs = latapy_clustering(G, nodes=nodes, mode=mode)
|
211 |
+
return sum(ccs[v] for v in nodes) / len(nodes)
|
212 |
+
|
213 |
+
|
214 |
+
@nx._dispatchable
|
215 |
+
def robins_alexander_clustering(G):
|
216 |
+
r"""Compute the bipartite clustering of G.
|
217 |
+
|
218 |
+
Robins and Alexander [1]_ defined bipartite clustering coefficient as
|
219 |
+
four times the number of four cycles `C_4` divided by the number of
|
220 |
+
three paths `L_3` in a bipartite graph:
|
221 |
+
|
222 |
+
.. math::
|
223 |
+
|
224 |
+
CC_4 = \frac{4 * C_4}{L_3}
|
225 |
+
|
226 |
+
Parameters
|
227 |
+
----------
|
228 |
+
G : graph
|
229 |
+
a bipartite graph
|
230 |
+
|
231 |
+
Returns
|
232 |
+
-------
|
233 |
+
clustering : float
|
234 |
+
The Robins and Alexander bipartite clustering for the input graph.
|
235 |
+
|
236 |
+
Examples
|
237 |
+
--------
|
238 |
+
>>> from networkx.algorithms import bipartite
|
239 |
+
>>> G = nx.davis_southern_women_graph()
|
240 |
+
>>> print(round(bipartite.robins_alexander_clustering(G), 3))
|
241 |
+
0.468
|
242 |
+
|
243 |
+
See Also
|
244 |
+
--------
|
245 |
+
latapy_clustering
|
246 |
+
networkx.algorithms.cluster.square_clustering
|
247 |
+
|
248 |
+
References
|
249 |
+
----------
|
250 |
+
.. [1] Robins, G. and M. Alexander (2004). Small worlds among interlocking
|
251 |
+
directors: Network structure and distance in bipartite graphs.
|
252 |
+
Computational & Mathematical Organization Theory 10(1), 69–94.
|
253 |
+
|
254 |
+
"""
|
255 |
+
if G.order() < 4 or G.size() < 3:
|
256 |
+
return 0
|
257 |
+
L_3 = _threepaths(G)
|
258 |
+
if L_3 == 0:
|
259 |
+
return 0
|
260 |
+
C_4 = _four_cycles(G)
|
261 |
+
return (4.0 * C_4) / L_3
|
262 |
+
|
263 |
+
|
264 |
+
def _four_cycles(G):
|
265 |
+
cycles = 0
|
266 |
+
for v in G:
|
267 |
+
for u, w in itertools.combinations(G[v], 2):
|
268 |
+
cycles += len((set(G[u]) & set(G[w])) - {v})
|
269 |
+
return cycles / 4
|
270 |
+
|
271 |
+
|
272 |
+
def _threepaths(G):
|
273 |
+
paths = 0
|
274 |
+
for v in G:
|
275 |
+
for u in G[v]:
|
276 |
+
for w in set(G[u]) - {v}:
|
277 |
+
paths += len(set(G[w]) - {v, u})
|
278 |
+
# Divide by two because we count each three path twice
|
279 |
+
# one for each possible starting point
|
280 |
+
return paths / 2
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/covering.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" Functions related to graph covers."""
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.algorithms.bipartite.matching import hopcroft_karp_matching
|
5 |
+
from networkx.algorithms.covering import min_edge_cover as _min_edge_cover
|
6 |
+
from networkx.utils import not_implemented_for
|
7 |
+
|
8 |
+
__all__ = ["min_edge_cover"]
|
9 |
+
|
10 |
+
|
11 |
+
@not_implemented_for("directed")
|
12 |
+
@not_implemented_for("multigraph")
|
13 |
+
@nx._dispatchable(name="bipartite_min_edge_cover")
|
14 |
+
def min_edge_cover(G, matching_algorithm=None):
|
15 |
+
"""Returns a set of edges which constitutes
|
16 |
+
the minimum edge cover of the graph.
|
17 |
+
|
18 |
+
The smallest edge cover can be found in polynomial time by finding
|
19 |
+
a maximum matching and extending it greedily so that all nodes
|
20 |
+
are covered.
|
21 |
+
|
22 |
+
Parameters
|
23 |
+
----------
|
24 |
+
G : NetworkX graph
|
25 |
+
An undirected bipartite graph.
|
26 |
+
|
27 |
+
matching_algorithm : function
|
28 |
+
A function that returns a maximum cardinality matching in a
|
29 |
+
given bipartite graph. The function must take one input, the
|
30 |
+
graph ``G``, and return a dictionary mapping each node to its
|
31 |
+
mate. If not specified,
|
32 |
+
:func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching`
|
33 |
+
will be used. Other possibilities include
|
34 |
+
:func:`~networkx.algorithms.bipartite.matching.eppstein_matching`,
|
35 |
+
|
36 |
+
Returns
|
37 |
+
-------
|
38 |
+
set
|
39 |
+
A set of the edges in a minimum edge cover of the graph, given as
|
40 |
+
pairs of nodes. It contains both the edges `(u, v)` and `(v, u)`
|
41 |
+
for given nodes `u` and `v` among the edges of minimum edge cover.
|
42 |
+
|
43 |
+
Notes
|
44 |
+
-----
|
45 |
+
An edge cover of a graph is a set of edges such that every node of
|
46 |
+
the graph is incident to at least one edge of the set.
|
47 |
+
A minimum edge cover is an edge covering of smallest cardinality.
|
48 |
+
|
49 |
+
Due to its implementation, the worst-case running time of this algorithm
|
50 |
+
is bounded by the worst-case running time of the function
|
51 |
+
``matching_algorithm``.
|
52 |
+
"""
|
53 |
+
if G.order() == 0: # Special case for the empty graph
|
54 |
+
return set()
|
55 |
+
if matching_algorithm is None:
|
56 |
+
matching_algorithm = hopcroft_karp_matching
|
57 |
+
return _min_edge_cover(G, matching_algorithm=matching_algorithm)
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/edgelist.py
ADDED
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
********************
|
3 |
+
Bipartite Edge Lists
|
4 |
+
********************
|
5 |
+
Read and write NetworkX graphs as bipartite edge lists.
|
6 |
+
|
7 |
+
Format
|
8 |
+
------
|
9 |
+
You can read or write three formats of edge lists with these functions.
|
10 |
+
|
11 |
+
Node pairs with no data::
|
12 |
+
|
13 |
+
1 2
|
14 |
+
|
15 |
+
Python dictionary as data::
|
16 |
+
|
17 |
+
1 2 {'weight':7, 'color':'green'}
|
18 |
+
|
19 |
+
Arbitrary data::
|
20 |
+
|
21 |
+
1 2 7 green
|
22 |
+
|
23 |
+
For each edge (u, v) the node u is assigned to part 0 and the node v to part 1.
|
24 |
+
"""
|
25 |
+
__all__ = ["generate_edgelist", "write_edgelist", "parse_edgelist", "read_edgelist"]
|
26 |
+
|
27 |
+
import networkx as nx
|
28 |
+
from networkx.utils import not_implemented_for, open_file
|
29 |
+
|
30 |
+
|
31 |
+
@open_file(1, mode="wb")
|
32 |
+
def write_edgelist(G, path, comments="#", delimiter=" ", data=True, encoding="utf-8"):
|
33 |
+
"""Write a bipartite graph as a list of edges.
|
34 |
+
|
35 |
+
Parameters
|
36 |
+
----------
|
37 |
+
G : Graph
|
38 |
+
A NetworkX bipartite graph
|
39 |
+
path : file or string
|
40 |
+
File or filename to write. If a file is provided, it must be
|
41 |
+
opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed.
|
42 |
+
comments : string, optional
|
43 |
+
The character used to indicate the start of a comment
|
44 |
+
delimiter : string, optional
|
45 |
+
The string used to separate values. The default is whitespace.
|
46 |
+
data : bool or list, optional
|
47 |
+
If False write no edge data.
|
48 |
+
If True write a string representation of the edge data dictionary..
|
49 |
+
If a list (or other iterable) is provided, write the keys specified
|
50 |
+
in the list.
|
51 |
+
encoding: string, optional
|
52 |
+
Specify which encoding to use when writing file.
|
53 |
+
|
54 |
+
Examples
|
55 |
+
--------
|
56 |
+
>>> G = nx.path_graph(4)
|
57 |
+
>>> G.add_nodes_from([0, 2], bipartite=0)
|
58 |
+
>>> G.add_nodes_from([1, 3], bipartite=1)
|
59 |
+
>>> nx.write_edgelist(G, "test.edgelist")
|
60 |
+
>>> fh = open("test.edgelist", "wb")
|
61 |
+
>>> nx.write_edgelist(G, fh)
|
62 |
+
>>> nx.write_edgelist(G, "test.edgelist.gz")
|
63 |
+
>>> nx.write_edgelist(G, "test.edgelist.gz", data=False)
|
64 |
+
|
65 |
+
>>> G = nx.Graph()
|
66 |
+
>>> G.add_edge(1, 2, weight=7, color="red")
|
67 |
+
>>> nx.write_edgelist(G, "test.edgelist", data=False)
|
68 |
+
>>> nx.write_edgelist(G, "test.edgelist", data=["color"])
|
69 |
+
>>> nx.write_edgelist(G, "test.edgelist", data=["color", "weight"])
|
70 |
+
|
71 |
+
See Also
|
72 |
+
--------
|
73 |
+
write_edgelist
|
74 |
+
generate_edgelist
|
75 |
+
"""
|
76 |
+
for line in generate_edgelist(G, delimiter, data):
|
77 |
+
line += "\n"
|
78 |
+
path.write(line.encode(encoding))
|
79 |
+
|
80 |
+
|
81 |
+
@not_implemented_for("directed")
|
82 |
+
def generate_edgelist(G, delimiter=" ", data=True):
|
83 |
+
"""Generate a single line of the bipartite graph G in edge list format.
|
84 |
+
|
85 |
+
Parameters
|
86 |
+
----------
|
87 |
+
G : NetworkX graph
|
88 |
+
The graph is assumed to have node attribute `part` set to 0,1 representing
|
89 |
+
the two graph parts
|
90 |
+
|
91 |
+
delimiter : string, optional
|
92 |
+
Separator for node labels
|
93 |
+
|
94 |
+
data : bool or list of keys
|
95 |
+
If False generate no edge data. If True use a dictionary
|
96 |
+
representation of edge data. If a list of keys use a list of data
|
97 |
+
values corresponding to the keys.
|
98 |
+
|
99 |
+
Returns
|
100 |
+
-------
|
101 |
+
lines : string
|
102 |
+
Lines of data in adjlist format.
|
103 |
+
|
104 |
+
Examples
|
105 |
+
--------
|
106 |
+
>>> from networkx.algorithms import bipartite
|
107 |
+
>>> G = nx.path_graph(4)
|
108 |
+
>>> G.add_nodes_from([0, 2], bipartite=0)
|
109 |
+
>>> G.add_nodes_from([1, 3], bipartite=1)
|
110 |
+
>>> G[1][2]["weight"] = 3
|
111 |
+
>>> G[2][3]["capacity"] = 12
|
112 |
+
>>> for line in bipartite.generate_edgelist(G, data=False):
|
113 |
+
... print(line)
|
114 |
+
0 1
|
115 |
+
2 1
|
116 |
+
2 3
|
117 |
+
|
118 |
+
>>> for line in bipartite.generate_edgelist(G):
|
119 |
+
... print(line)
|
120 |
+
0 1 {}
|
121 |
+
2 1 {'weight': 3}
|
122 |
+
2 3 {'capacity': 12}
|
123 |
+
|
124 |
+
>>> for line in bipartite.generate_edgelist(G, data=["weight"]):
|
125 |
+
... print(line)
|
126 |
+
0 1
|
127 |
+
2 1 3
|
128 |
+
2 3
|
129 |
+
"""
|
130 |
+
try:
|
131 |
+
part0 = [n for n, d in G.nodes.items() if d["bipartite"] == 0]
|
132 |
+
except BaseException as err:
|
133 |
+
raise AttributeError("Missing node attribute `bipartite`") from err
|
134 |
+
if data is True or data is False:
|
135 |
+
for n in part0:
|
136 |
+
for edge in G.edges(n, data=data):
|
137 |
+
yield delimiter.join(map(str, edge))
|
138 |
+
else:
|
139 |
+
for n in part0:
|
140 |
+
for u, v, d in G.edges(n, data=True):
|
141 |
+
edge = [u, v]
|
142 |
+
try:
|
143 |
+
edge.extend(d[k] for k in data)
|
144 |
+
except KeyError:
|
145 |
+
pass # missing data for this edge, should warn?
|
146 |
+
yield delimiter.join(map(str, edge))
|
147 |
+
|
148 |
+
|
149 |
+
@nx._dispatchable(name="bipartite_parse_edgelist", graphs=None, returns_graph=True)
|
150 |
+
def parse_edgelist(
|
151 |
+
lines, comments="#", delimiter=None, create_using=None, nodetype=None, data=True
|
152 |
+
):
|
153 |
+
"""Parse lines of an edge list representation of a bipartite graph.
|
154 |
+
|
155 |
+
Parameters
|
156 |
+
----------
|
157 |
+
lines : list or iterator of strings
|
158 |
+
Input data in edgelist format
|
159 |
+
comments : string, optional
|
160 |
+
Marker for comment lines
|
161 |
+
delimiter : string, optional
|
162 |
+
Separator for node labels
|
163 |
+
create_using: NetworkX graph container, optional
|
164 |
+
Use given NetworkX graph for holding nodes or edges.
|
165 |
+
nodetype : Python type, optional
|
166 |
+
Convert nodes to this type.
|
167 |
+
data : bool or list of (label,type) tuples
|
168 |
+
If False generate no edge data or if True use a dictionary
|
169 |
+
representation of edge data or a list tuples specifying dictionary
|
170 |
+
key names and types for edge data.
|
171 |
+
|
172 |
+
Returns
|
173 |
+
-------
|
174 |
+
G: NetworkX Graph
|
175 |
+
The bipartite graph corresponding to lines
|
176 |
+
|
177 |
+
Examples
|
178 |
+
--------
|
179 |
+
Edgelist with no data:
|
180 |
+
|
181 |
+
>>> from networkx.algorithms import bipartite
|
182 |
+
>>> lines = ["1 2", "2 3", "3 4"]
|
183 |
+
>>> G = bipartite.parse_edgelist(lines, nodetype=int)
|
184 |
+
>>> sorted(G.nodes())
|
185 |
+
[1, 2, 3, 4]
|
186 |
+
>>> sorted(G.nodes(data=True))
|
187 |
+
[(1, {'bipartite': 0}), (2, {'bipartite': 0}), (3, {'bipartite': 0}), (4, {'bipartite': 1})]
|
188 |
+
>>> sorted(G.edges())
|
189 |
+
[(1, 2), (2, 3), (3, 4)]
|
190 |
+
|
191 |
+
Edgelist with data in Python dictionary representation:
|
192 |
+
|
193 |
+
>>> lines = ["1 2 {'weight':3}", "2 3 {'weight':27}", "3 4 {'weight':3.0}"]
|
194 |
+
>>> G = bipartite.parse_edgelist(lines, nodetype=int)
|
195 |
+
>>> sorted(G.nodes())
|
196 |
+
[1, 2, 3, 4]
|
197 |
+
>>> sorted(G.edges(data=True))
|
198 |
+
[(1, 2, {'weight': 3}), (2, 3, {'weight': 27}), (3, 4, {'weight': 3.0})]
|
199 |
+
|
200 |
+
Edgelist with data in a list:
|
201 |
+
|
202 |
+
>>> lines = ["1 2 3", "2 3 27", "3 4 3.0"]
|
203 |
+
>>> G = bipartite.parse_edgelist(lines, nodetype=int, data=(("weight", float),))
|
204 |
+
>>> sorted(G.nodes())
|
205 |
+
[1, 2, 3, 4]
|
206 |
+
>>> sorted(G.edges(data=True))
|
207 |
+
[(1, 2, {'weight': 3.0}), (2, 3, {'weight': 27.0}), (3, 4, {'weight': 3.0})]
|
208 |
+
|
209 |
+
See Also
|
210 |
+
--------
|
211 |
+
"""
|
212 |
+
from ast import literal_eval
|
213 |
+
|
214 |
+
G = nx.empty_graph(0, create_using)
|
215 |
+
for line in lines:
|
216 |
+
p = line.find(comments)
|
217 |
+
if p >= 0:
|
218 |
+
line = line[:p]
|
219 |
+
if not len(line):
|
220 |
+
continue
|
221 |
+
# split line, should have 2 or more
|
222 |
+
s = line.strip().split(delimiter)
|
223 |
+
if len(s) < 2:
|
224 |
+
continue
|
225 |
+
u = s.pop(0)
|
226 |
+
v = s.pop(0)
|
227 |
+
d = s
|
228 |
+
if nodetype is not None:
|
229 |
+
try:
|
230 |
+
u = nodetype(u)
|
231 |
+
v = nodetype(v)
|
232 |
+
except BaseException as err:
|
233 |
+
raise TypeError(
|
234 |
+
f"Failed to convert nodes {u},{v} to type {nodetype}."
|
235 |
+
) from err
|
236 |
+
|
237 |
+
if len(d) == 0 or data is False:
|
238 |
+
# no data or data type specified
|
239 |
+
edgedata = {}
|
240 |
+
elif data is True:
|
241 |
+
# no edge types specified
|
242 |
+
try: # try to evaluate as dictionary
|
243 |
+
edgedata = dict(literal_eval(" ".join(d)))
|
244 |
+
except BaseException as err:
|
245 |
+
raise TypeError(
|
246 |
+
f"Failed to convert edge data ({d}) to dictionary."
|
247 |
+
) from err
|
248 |
+
else:
|
249 |
+
# convert edge data to dictionary with specified keys and type
|
250 |
+
if len(d) != len(data):
|
251 |
+
raise IndexError(
|
252 |
+
f"Edge data {d} and data_keys {data} are not the same length"
|
253 |
+
)
|
254 |
+
edgedata = {}
|
255 |
+
for (edge_key, edge_type), edge_value in zip(data, d):
|
256 |
+
try:
|
257 |
+
edge_value = edge_type(edge_value)
|
258 |
+
except BaseException as err:
|
259 |
+
raise TypeError(
|
260 |
+
f"Failed to convert {edge_key} data "
|
261 |
+
f"{edge_value} to type {edge_type}."
|
262 |
+
) from err
|
263 |
+
edgedata.update({edge_key: edge_value})
|
264 |
+
G.add_node(u, bipartite=0)
|
265 |
+
G.add_node(v, bipartite=1)
|
266 |
+
G.add_edge(u, v, **edgedata)
|
267 |
+
return G
|
268 |
+
|
269 |
+
|
270 |
+
@open_file(0, mode="rb")
|
271 |
+
@nx._dispatchable(name="bipartite_read_edgelist", graphs=None, returns_graph=True)
|
272 |
+
def read_edgelist(
|
273 |
+
path,
|
274 |
+
comments="#",
|
275 |
+
delimiter=None,
|
276 |
+
create_using=None,
|
277 |
+
nodetype=None,
|
278 |
+
data=True,
|
279 |
+
edgetype=None,
|
280 |
+
encoding="utf-8",
|
281 |
+
):
|
282 |
+
"""Read a bipartite graph from a list of edges.
|
283 |
+
|
284 |
+
Parameters
|
285 |
+
----------
|
286 |
+
path : file or string
|
287 |
+
File or filename to read. If a file is provided, it must be
|
288 |
+
opened in 'rb' mode.
|
289 |
+
Filenames ending in .gz or .bz2 will be uncompressed.
|
290 |
+
comments : string, optional
|
291 |
+
The character used to indicate the start of a comment.
|
292 |
+
delimiter : string, optional
|
293 |
+
The string used to separate values. The default is whitespace.
|
294 |
+
create_using : Graph container, optional,
|
295 |
+
Use specified container to build graph. The default is networkx.Graph,
|
296 |
+
an undirected graph.
|
297 |
+
nodetype : int, float, str, Python type, optional
|
298 |
+
Convert node data from strings to specified type
|
299 |
+
data : bool or list of (label,type) tuples
|
300 |
+
Tuples specifying dictionary key names and types for edge data
|
301 |
+
edgetype : int, float, str, Python type, optional OBSOLETE
|
302 |
+
Convert edge data from strings to specified type and use as 'weight'
|
303 |
+
encoding: string, optional
|
304 |
+
Specify which encoding to use when reading file.
|
305 |
+
|
306 |
+
Returns
|
307 |
+
-------
|
308 |
+
G : graph
|
309 |
+
A networkx Graph or other type specified with create_using
|
310 |
+
|
311 |
+
Examples
|
312 |
+
--------
|
313 |
+
>>> from networkx.algorithms import bipartite
|
314 |
+
>>> G = nx.path_graph(4)
|
315 |
+
>>> G.add_nodes_from([0, 2], bipartite=0)
|
316 |
+
>>> G.add_nodes_from([1, 3], bipartite=1)
|
317 |
+
>>> bipartite.write_edgelist(G, "test.edgelist")
|
318 |
+
>>> G = bipartite.read_edgelist("test.edgelist")
|
319 |
+
|
320 |
+
>>> fh = open("test.edgelist", "rb")
|
321 |
+
>>> G = bipartite.read_edgelist(fh)
|
322 |
+
>>> fh.close()
|
323 |
+
|
324 |
+
>>> G = bipartite.read_edgelist("test.edgelist", nodetype=int)
|
325 |
+
|
326 |
+
Edgelist with data in a list:
|
327 |
+
|
328 |
+
>>> textline = "1 2 3"
|
329 |
+
>>> fh = open("test.edgelist", "w")
|
330 |
+
>>> d = fh.write(textline)
|
331 |
+
>>> fh.close()
|
332 |
+
>>> G = bipartite.read_edgelist(
|
333 |
+
... "test.edgelist", nodetype=int, data=(("weight", float),)
|
334 |
+
... )
|
335 |
+
>>> list(G)
|
336 |
+
[1, 2]
|
337 |
+
>>> list(G.edges(data=True))
|
338 |
+
[(1, 2, {'weight': 3.0})]
|
339 |
+
|
340 |
+
See parse_edgelist() for more examples of formatting.
|
341 |
+
|
342 |
+
See Also
|
343 |
+
--------
|
344 |
+
parse_edgelist
|
345 |
+
|
346 |
+
Notes
|
347 |
+
-----
|
348 |
+
Since nodes must be hashable, the function nodetype must return hashable
|
349 |
+
types (e.g. int, float, str, frozenset - or tuples of those, etc.)
|
350 |
+
"""
|
351 |
+
lines = (line.decode(encoding) for line in path)
|
352 |
+
return parse_edgelist(
|
353 |
+
lines,
|
354 |
+
comments=comments,
|
355 |
+
delimiter=delimiter,
|
356 |
+
create_using=create_using,
|
357 |
+
nodetype=nodetype,
|
358 |
+
data=data,
|
359 |
+
)
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/extendability.py
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" Provides a function for computing the extendability of a graph which is
|
2 |
+
undirected, simple, connected and bipartite and contains at least one perfect matching."""
|
3 |
+
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
from networkx.utils import not_implemented_for
|
7 |
+
|
8 |
+
__all__ = ["maximal_extendability"]
|
9 |
+
|
10 |
+
|
11 |
+
@not_implemented_for("directed")
|
12 |
+
@not_implemented_for("multigraph")
|
13 |
+
@nx._dispatchable
|
14 |
+
def maximal_extendability(G):
|
15 |
+
"""Computes the extendability of a graph.
|
16 |
+
|
17 |
+
The extendability of a graph is defined as the maximum $k$ for which `G`
|
18 |
+
is $k$-extendable. Graph `G` is $k$-extendable if and only if `G` has a
|
19 |
+
perfect matching and every set of $k$ independent edges can be extended
|
20 |
+
to a perfect matching in `G`.
|
21 |
+
|
22 |
+
Parameters
|
23 |
+
----------
|
24 |
+
G : NetworkX Graph
|
25 |
+
A fully-connected bipartite graph without self-loops
|
26 |
+
|
27 |
+
Returns
|
28 |
+
-------
|
29 |
+
extendability : int
|
30 |
+
|
31 |
+
Raises
|
32 |
+
------
|
33 |
+
NetworkXError
|
34 |
+
If the graph `G` is disconnected.
|
35 |
+
If the graph `G` is not bipartite.
|
36 |
+
If the graph `G` does not contain a perfect matching.
|
37 |
+
If the residual graph of `G` is not strongly connected.
|
38 |
+
|
39 |
+
Notes
|
40 |
+
-----
|
41 |
+
Definition:
|
42 |
+
Let `G` be a simple, connected, undirected and bipartite graph with a perfect
|
43 |
+
matching M and bipartition (U,V). The residual graph of `G`, denoted by $G_M$,
|
44 |
+
is the graph obtained from G by directing the edges of M from V to U and the
|
45 |
+
edges that do not belong to M from U to V.
|
46 |
+
|
47 |
+
Lemma [1]_ :
|
48 |
+
Let M be a perfect matching of `G`. `G` is $k$-extendable if and only if its residual
|
49 |
+
graph $G_M$ is strongly connected and there are $k$ vertex-disjoint directed
|
50 |
+
paths between every vertex of U and every vertex of V.
|
51 |
+
|
52 |
+
Assuming that input graph `G` is undirected, simple, connected, bipartite and contains
|
53 |
+
a perfect matching M, this function constructs the residual graph $G_M$ of G and
|
54 |
+
returns the minimum value among the maximum vertex-disjoint directed paths between
|
55 |
+
every vertex of U and every vertex of V in $G_M$. By combining the definitions
|
56 |
+
and the lemma, this value represents the extendability of the graph `G`.
|
57 |
+
|
58 |
+
Time complexity O($n^3$ $m^2$)) where $n$ is the number of vertices
|
59 |
+
and $m$ is the number of edges.
|
60 |
+
|
61 |
+
References
|
62 |
+
----------
|
63 |
+
.. [1] "A polynomial algorithm for the extendability problem in bipartite graphs",
|
64 |
+
J. Lakhal, L. Litzler, Information Processing Letters, 1998.
|
65 |
+
.. [2] "On n-extendible graphs", M. D. Plummer, Discrete Mathematics, 31:201–210, 1980
|
66 |
+
https://doi.org/10.1016/0012-365X(80)90037-0
|
67 |
+
|
68 |
+
"""
|
69 |
+
if not nx.is_connected(G):
|
70 |
+
raise nx.NetworkXError("Graph G is not connected")
|
71 |
+
|
72 |
+
if not nx.bipartite.is_bipartite(G):
|
73 |
+
raise nx.NetworkXError("Graph G is not bipartite")
|
74 |
+
|
75 |
+
U, V = nx.bipartite.sets(G)
|
76 |
+
|
77 |
+
maximum_matching = nx.bipartite.hopcroft_karp_matching(G)
|
78 |
+
|
79 |
+
if not nx.is_perfect_matching(G, maximum_matching):
|
80 |
+
raise nx.NetworkXError("Graph G does not contain a perfect matching")
|
81 |
+
|
82 |
+
# list of edges in perfect matching, directed from V to U
|
83 |
+
pm = [(node, maximum_matching[node]) for node in V & maximum_matching.keys()]
|
84 |
+
|
85 |
+
# Direct all the edges of G, from V to U if in matching, else from U to V
|
86 |
+
directed_edges = [
|
87 |
+
(x, y) if (x in V and (x, y) in pm) or (x in U and (y, x) not in pm) else (y, x)
|
88 |
+
for x, y in G.edges
|
89 |
+
]
|
90 |
+
|
91 |
+
# Construct the residual graph of G
|
92 |
+
residual_G = nx.DiGraph()
|
93 |
+
residual_G.add_nodes_from(G)
|
94 |
+
residual_G.add_edges_from(directed_edges)
|
95 |
+
|
96 |
+
if not nx.is_strongly_connected(residual_G):
|
97 |
+
raise nx.NetworkXError("The residual graph of G is not strongly connected")
|
98 |
+
|
99 |
+
# For node-pairs between V & U, keep min of max number of node-disjoint paths
|
100 |
+
# Variable $k$ stands for the extendability of graph G
|
101 |
+
k = float("inf")
|
102 |
+
for u in U:
|
103 |
+
for v in V:
|
104 |
+
num_paths = sum(1 for _ in nx.node_disjoint_paths(residual_G, u, v))
|
105 |
+
k = k if k < num_paths else num_paths
|
106 |
+
return k
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/generators.py
ADDED
@@ -0,0 +1,603 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Generators and functions for bipartite graphs.
|
3 |
+
"""
|
4 |
+
import math
|
5 |
+
import numbers
|
6 |
+
from functools import reduce
|
7 |
+
|
8 |
+
import networkx as nx
|
9 |
+
from networkx.utils import nodes_or_number, py_random_state
|
10 |
+
|
11 |
+
__all__ = [
|
12 |
+
"configuration_model",
|
13 |
+
"havel_hakimi_graph",
|
14 |
+
"reverse_havel_hakimi_graph",
|
15 |
+
"alternating_havel_hakimi_graph",
|
16 |
+
"preferential_attachment_graph",
|
17 |
+
"random_graph",
|
18 |
+
"gnmk_random_graph",
|
19 |
+
"complete_bipartite_graph",
|
20 |
+
]
|
21 |
+
|
22 |
+
|
23 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
24 |
+
@nodes_or_number([0, 1])
|
25 |
+
def complete_bipartite_graph(n1, n2, create_using=None):
|
26 |
+
"""Returns the complete bipartite graph `K_{n_1,n_2}`.
|
27 |
+
|
28 |
+
The graph is composed of two partitions with nodes 0 to (n1 - 1)
|
29 |
+
in the first and nodes n1 to (n1 + n2 - 1) in the second.
|
30 |
+
Each node in the first is connected to each node in the second.
|
31 |
+
|
32 |
+
Parameters
|
33 |
+
----------
|
34 |
+
n1, n2 : integer or iterable container of nodes
|
35 |
+
If integers, nodes are from `range(n1)` and `range(n1, n1 + n2)`.
|
36 |
+
If a container, the elements are the nodes.
|
37 |
+
create_using : NetworkX graph instance, (default: nx.Graph)
|
38 |
+
Return graph of this type.
|
39 |
+
|
40 |
+
Notes
|
41 |
+
-----
|
42 |
+
Nodes are the integers 0 to `n1 + n2 - 1` unless either n1 or n2 are
|
43 |
+
containers of nodes. If only one of n1 or n2 are integers, that
|
44 |
+
integer is replaced by `range` of that integer.
|
45 |
+
|
46 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
47 |
+
to indicate which bipartite set the node belongs to.
|
48 |
+
|
49 |
+
This function is not imported in the main namespace.
|
50 |
+
To use it use nx.bipartite.complete_bipartite_graph
|
51 |
+
"""
|
52 |
+
G = nx.empty_graph(0, create_using)
|
53 |
+
if G.is_directed():
|
54 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
55 |
+
|
56 |
+
n1, top = n1
|
57 |
+
n2, bottom = n2
|
58 |
+
if isinstance(n1, numbers.Integral) and isinstance(n2, numbers.Integral):
|
59 |
+
bottom = [n1 + i for i in bottom]
|
60 |
+
G.add_nodes_from(top, bipartite=0)
|
61 |
+
G.add_nodes_from(bottom, bipartite=1)
|
62 |
+
if len(G) != len(top) + len(bottom):
|
63 |
+
raise nx.NetworkXError("Inputs n1 and n2 must contain distinct nodes")
|
64 |
+
G.add_edges_from((u, v) for u in top for v in bottom)
|
65 |
+
G.graph["name"] = f"complete_bipartite_graph({n1}, {n2})"
|
66 |
+
return G
|
67 |
+
|
68 |
+
|
69 |
+
@py_random_state(3)
|
70 |
+
@nx._dispatchable(name="bipartite_configuration_model", graphs=None, returns_graph=True)
|
71 |
+
def configuration_model(aseq, bseq, create_using=None, seed=None):
|
72 |
+
"""Returns a random bipartite graph from two given degree sequences.
|
73 |
+
|
74 |
+
Parameters
|
75 |
+
----------
|
76 |
+
aseq : list
|
77 |
+
Degree sequence for node set A.
|
78 |
+
bseq : list
|
79 |
+
Degree sequence for node set B.
|
80 |
+
create_using : NetworkX graph instance, optional
|
81 |
+
Return graph of this type.
|
82 |
+
seed : integer, random_state, or None (default)
|
83 |
+
Indicator of random number generation state.
|
84 |
+
See :ref:`Randomness<randomness>`.
|
85 |
+
|
86 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
87 |
+
(len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
|
88 |
+
Nodes from set A are connected to nodes in set B by choosing
|
89 |
+
randomly from the possible free stubs, one in A and one in B.
|
90 |
+
|
91 |
+
Notes
|
92 |
+
-----
|
93 |
+
The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
|
94 |
+
If no graph type is specified use MultiGraph with parallel edges.
|
95 |
+
If you want a graph with no parallel edges use create_using=Graph()
|
96 |
+
but then the resulting degree sequences might not be exact.
|
97 |
+
|
98 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
99 |
+
to indicate which bipartite set the node belongs to.
|
100 |
+
|
101 |
+
This function is not imported in the main namespace.
|
102 |
+
To use it use nx.bipartite.configuration_model
|
103 |
+
"""
|
104 |
+
G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
|
105 |
+
if G.is_directed():
|
106 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
107 |
+
|
108 |
+
# length and sum of each sequence
|
109 |
+
lena = len(aseq)
|
110 |
+
lenb = len(bseq)
|
111 |
+
suma = sum(aseq)
|
112 |
+
sumb = sum(bseq)
|
113 |
+
|
114 |
+
if not suma == sumb:
|
115 |
+
raise nx.NetworkXError(
|
116 |
+
f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
|
117 |
+
)
|
118 |
+
|
119 |
+
G = _add_nodes_with_bipartite_label(G, lena, lenb)
|
120 |
+
|
121 |
+
if len(aseq) == 0 or max(aseq) == 0:
|
122 |
+
return G # done if no edges
|
123 |
+
|
124 |
+
# build lists of degree-repeated vertex numbers
|
125 |
+
stubs = [[v] * aseq[v] for v in range(lena)]
|
126 |
+
astubs = [x for subseq in stubs for x in subseq]
|
127 |
+
|
128 |
+
stubs = [[v] * bseq[v - lena] for v in range(lena, lena + lenb)]
|
129 |
+
bstubs = [x for subseq in stubs for x in subseq]
|
130 |
+
|
131 |
+
# shuffle lists
|
132 |
+
seed.shuffle(astubs)
|
133 |
+
seed.shuffle(bstubs)
|
134 |
+
|
135 |
+
G.add_edges_from([astubs[i], bstubs[i]] for i in range(suma))
|
136 |
+
|
137 |
+
G.name = "bipartite_configuration_model"
|
138 |
+
return G
|
139 |
+
|
140 |
+
|
141 |
+
@nx._dispatchable(name="bipartite_havel_hakimi_graph", graphs=None, returns_graph=True)
|
142 |
+
def havel_hakimi_graph(aseq, bseq, create_using=None):
|
143 |
+
"""Returns a bipartite graph from two given degree sequences using a
|
144 |
+
Havel-Hakimi style construction.
|
145 |
+
|
146 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
147 |
+
(len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
|
148 |
+
Nodes from the set A are connected to nodes in the set B by
|
149 |
+
connecting the highest degree nodes in set A to the highest degree
|
150 |
+
nodes in set B until all stubs are connected.
|
151 |
+
|
152 |
+
Parameters
|
153 |
+
----------
|
154 |
+
aseq : list
|
155 |
+
Degree sequence for node set A.
|
156 |
+
bseq : list
|
157 |
+
Degree sequence for node set B.
|
158 |
+
create_using : NetworkX graph instance, optional
|
159 |
+
Return graph of this type.
|
160 |
+
|
161 |
+
Notes
|
162 |
+
-----
|
163 |
+
The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
|
164 |
+
If no graph type is specified use MultiGraph with parallel edges.
|
165 |
+
If you want a graph with no parallel edges use create_using=Graph()
|
166 |
+
but then the resulting degree sequences might not be exact.
|
167 |
+
|
168 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
169 |
+
to indicate which bipartite set the node belongs to.
|
170 |
+
|
171 |
+
This function is not imported in the main namespace.
|
172 |
+
To use it use nx.bipartite.havel_hakimi_graph
|
173 |
+
"""
|
174 |
+
G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
|
175 |
+
if G.is_directed():
|
176 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
177 |
+
|
178 |
+
# length of the each sequence
|
179 |
+
naseq = len(aseq)
|
180 |
+
nbseq = len(bseq)
|
181 |
+
|
182 |
+
suma = sum(aseq)
|
183 |
+
sumb = sum(bseq)
|
184 |
+
|
185 |
+
if not suma == sumb:
|
186 |
+
raise nx.NetworkXError(
|
187 |
+
f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
|
188 |
+
)
|
189 |
+
|
190 |
+
G = _add_nodes_with_bipartite_label(G, naseq, nbseq)
|
191 |
+
|
192 |
+
if len(aseq) == 0 or max(aseq) == 0:
|
193 |
+
return G # done if no edges
|
194 |
+
|
195 |
+
# build list of degree-repeated vertex numbers
|
196 |
+
astubs = [[aseq[v], v] for v in range(naseq)]
|
197 |
+
bstubs = [[bseq[v - naseq], v] for v in range(naseq, naseq + nbseq)]
|
198 |
+
astubs.sort()
|
199 |
+
while astubs:
|
200 |
+
(degree, u) = astubs.pop() # take of largest degree node in the a set
|
201 |
+
if degree == 0:
|
202 |
+
break # done, all are zero
|
203 |
+
# connect the source to largest degree nodes in the b set
|
204 |
+
bstubs.sort()
|
205 |
+
for target in bstubs[-degree:]:
|
206 |
+
v = target[1]
|
207 |
+
G.add_edge(u, v)
|
208 |
+
target[0] -= 1 # note this updates bstubs too.
|
209 |
+
if target[0] == 0:
|
210 |
+
bstubs.remove(target)
|
211 |
+
|
212 |
+
G.name = "bipartite_havel_hakimi_graph"
|
213 |
+
return G
|
214 |
+
|
215 |
+
|
216 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
217 |
+
def reverse_havel_hakimi_graph(aseq, bseq, create_using=None):
|
218 |
+
"""Returns a bipartite graph from two given degree sequences using a
|
219 |
+
Havel-Hakimi style construction.
|
220 |
+
|
221 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
222 |
+
(len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
|
223 |
+
Nodes from set A are connected to nodes in the set B by connecting
|
224 |
+
the highest degree nodes in set A to the lowest degree nodes in
|
225 |
+
set B until all stubs are connected.
|
226 |
+
|
227 |
+
Parameters
|
228 |
+
----------
|
229 |
+
aseq : list
|
230 |
+
Degree sequence for node set A.
|
231 |
+
bseq : list
|
232 |
+
Degree sequence for node set B.
|
233 |
+
create_using : NetworkX graph instance, optional
|
234 |
+
Return graph of this type.
|
235 |
+
|
236 |
+
Notes
|
237 |
+
-----
|
238 |
+
The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
|
239 |
+
If no graph type is specified use MultiGraph with parallel edges.
|
240 |
+
If you want a graph with no parallel edges use create_using=Graph()
|
241 |
+
but then the resulting degree sequences might not be exact.
|
242 |
+
|
243 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
244 |
+
to indicate which bipartite set the node belongs to.
|
245 |
+
|
246 |
+
This function is not imported in the main namespace.
|
247 |
+
To use it use nx.bipartite.reverse_havel_hakimi_graph
|
248 |
+
"""
|
249 |
+
G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
|
250 |
+
if G.is_directed():
|
251 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
252 |
+
|
253 |
+
# length of the each sequence
|
254 |
+
lena = len(aseq)
|
255 |
+
lenb = len(bseq)
|
256 |
+
suma = sum(aseq)
|
257 |
+
sumb = sum(bseq)
|
258 |
+
|
259 |
+
if not suma == sumb:
|
260 |
+
raise nx.NetworkXError(
|
261 |
+
f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
|
262 |
+
)
|
263 |
+
|
264 |
+
G = _add_nodes_with_bipartite_label(G, lena, lenb)
|
265 |
+
|
266 |
+
if len(aseq) == 0 or max(aseq) == 0:
|
267 |
+
return G # done if no edges
|
268 |
+
|
269 |
+
# build list of degree-repeated vertex numbers
|
270 |
+
astubs = [[aseq[v], v] for v in range(lena)]
|
271 |
+
bstubs = [[bseq[v - lena], v] for v in range(lena, lena + lenb)]
|
272 |
+
astubs.sort()
|
273 |
+
bstubs.sort()
|
274 |
+
while astubs:
|
275 |
+
(degree, u) = astubs.pop() # take of largest degree node in the a set
|
276 |
+
if degree == 0:
|
277 |
+
break # done, all are zero
|
278 |
+
# connect the source to the smallest degree nodes in the b set
|
279 |
+
for target in bstubs[0:degree]:
|
280 |
+
v = target[1]
|
281 |
+
G.add_edge(u, v)
|
282 |
+
target[0] -= 1 # note this updates bstubs too.
|
283 |
+
if target[0] == 0:
|
284 |
+
bstubs.remove(target)
|
285 |
+
|
286 |
+
G.name = "bipartite_reverse_havel_hakimi_graph"
|
287 |
+
return G
|
288 |
+
|
289 |
+
|
290 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
291 |
+
def alternating_havel_hakimi_graph(aseq, bseq, create_using=None):
|
292 |
+
"""Returns a bipartite graph from two given degree sequences using
|
293 |
+
an alternating Havel-Hakimi style construction.
|
294 |
+
|
295 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
296 |
+
(len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
|
297 |
+
Nodes from the set A are connected to nodes in the set B by
|
298 |
+
connecting the highest degree nodes in set A to alternatively the
|
299 |
+
highest and the lowest degree nodes in set B until all stubs are
|
300 |
+
connected.
|
301 |
+
|
302 |
+
Parameters
|
303 |
+
----------
|
304 |
+
aseq : list
|
305 |
+
Degree sequence for node set A.
|
306 |
+
bseq : list
|
307 |
+
Degree sequence for node set B.
|
308 |
+
create_using : NetworkX graph instance, optional
|
309 |
+
Return graph of this type.
|
310 |
+
|
311 |
+
Notes
|
312 |
+
-----
|
313 |
+
The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
|
314 |
+
If no graph type is specified use MultiGraph with parallel edges.
|
315 |
+
If you want a graph with no parallel edges use create_using=Graph()
|
316 |
+
but then the resulting degree sequences might not be exact.
|
317 |
+
|
318 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
319 |
+
to indicate which bipartite set the node belongs to.
|
320 |
+
|
321 |
+
This function is not imported in the main namespace.
|
322 |
+
To use it use nx.bipartite.alternating_havel_hakimi_graph
|
323 |
+
"""
|
324 |
+
G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
|
325 |
+
if G.is_directed():
|
326 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
327 |
+
|
328 |
+
# length of the each sequence
|
329 |
+
naseq = len(aseq)
|
330 |
+
nbseq = len(bseq)
|
331 |
+
suma = sum(aseq)
|
332 |
+
sumb = sum(bseq)
|
333 |
+
|
334 |
+
if not suma == sumb:
|
335 |
+
raise nx.NetworkXError(
|
336 |
+
f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
|
337 |
+
)
|
338 |
+
|
339 |
+
G = _add_nodes_with_bipartite_label(G, naseq, nbseq)
|
340 |
+
|
341 |
+
if len(aseq) == 0 or max(aseq) == 0:
|
342 |
+
return G # done if no edges
|
343 |
+
# build list of degree-repeated vertex numbers
|
344 |
+
astubs = [[aseq[v], v] for v in range(naseq)]
|
345 |
+
bstubs = [[bseq[v - naseq], v] for v in range(naseq, naseq + nbseq)]
|
346 |
+
while astubs:
|
347 |
+
astubs.sort()
|
348 |
+
(degree, u) = astubs.pop() # take of largest degree node in the a set
|
349 |
+
if degree == 0:
|
350 |
+
break # done, all are zero
|
351 |
+
bstubs.sort()
|
352 |
+
small = bstubs[0 : degree // 2] # add these low degree targets
|
353 |
+
large = bstubs[(-degree + degree // 2) :] # now high degree targets
|
354 |
+
stubs = [x for z in zip(large, small) for x in z] # combine, sorry
|
355 |
+
if len(stubs) < len(small) + len(large): # check for zip truncation
|
356 |
+
stubs.append(large.pop())
|
357 |
+
for target in stubs:
|
358 |
+
v = target[1]
|
359 |
+
G.add_edge(u, v)
|
360 |
+
target[0] -= 1 # note this updates bstubs too.
|
361 |
+
if target[0] == 0:
|
362 |
+
bstubs.remove(target)
|
363 |
+
|
364 |
+
G.name = "bipartite_alternating_havel_hakimi_graph"
|
365 |
+
return G
|
366 |
+
|
367 |
+
|
368 |
+
@py_random_state(3)
|
369 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
370 |
+
def preferential_attachment_graph(aseq, p, create_using=None, seed=None):
|
371 |
+
"""Create a bipartite graph with a preferential attachment model from
|
372 |
+
a given single degree sequence.
|
373 |
+
|
374 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
375 |
+
(len(aseq) - 1) and set B has nodes starting with node len(aseq).
|
376 |
+
The number of nodes in set B is random.
|
377 |
+
|
378 |
+
Parameters
|
379 |
+
----------
|
380 |
+
aseq : list
|
381 |
+
Degree sequence for node set A.
|
382 |
+
p : float
|
383 |
+
Probability that a new bottom node is added.
|
384 |
+
create_using : NetworkX graph instance, optional
|
385 |
+
Return graph of this type.
|
386 |
+
seed : integer, random_state, or None (default)
|
387 |
+
Indicator of random number generation state.
|
388 |
+
See :ref:`Randomness<randomness>`.
|
389 |
+
|
390 |
+
References
|
391 |
+
----------
|
392 |
+
.. [1] Guillaume, J.L. and Latapy, M.,
|
393 |
+
Bipartite graphs as models of complex networks.
|
394 |
+
Physica A: Statistical Mechanics and its Applications,
|
395 |
+
2006, 371(2), pp.795-813.
|
396 |
+
.. [2] Jean-Loup Guillaume and Matthieu Latapy,
|
397 |
+
Bipartite structure of all complex networks,
|
398 |
+
Inf. Process. Lett. 90, 2004, pg. 215-221
|
399 |
+
https://doi.org/10.1016/j.ipl.2004.03.007
|
400 |
+
|
401 |
+
Notes
|
402 |
+
-----
|
403 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
404 |
+
to indicate which bipartite set the node belongs to.
|
405 |
+
|
406 |
+
This function is not imported in the main namespace.
|
407 |
+
To use it use nx.bipartite.preferential_attachment_graph
|
408 |
+
"""
|
409 |
+
G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
|
410 |
+
if G.is_directed():
|
411 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
412 |
+
|
413 |
+
if p > 1:
|
414 |
+
raise nx.NetworkXError(f"probability {p} > 1")
|
415 |
+
|
416 |
+
naseq = len(aseq)
|
417 |
+
G = _add_nodes_with_bipartite_label(G, naseq, 0)
|
418 |
+
vv = [[v] * aseq[v] for v in range(naseq)]
|
419 |
+
while vv:
|
420 |
+
while vv[0]:
|
421 |
+
source = vv[0][0]
|
422 |
+
vv[0].remove(source)
|
423 |
+
if seed.random() < p or len(G) == naseq:
|
424 |
+
target = len(G)
|
425 |
+
G.add_node(target, bipartite=1)
|
426 |
+
G.add_edge(source, target)
|
427 |
+
else:
|
428 |
+
bb = [[b] * G.degree(b) for b in range(naseq, len(G))]
|
429 |
+
# flatten the list of lists into a list.
|
430 |
+
bbstubs = reduce(lambda x, y: x + y, bb)
|
431 |
+
# choose preferentially a bottom node.
|
432 |
+
target = seed.choice(bbstubs)
|
433 |
+
G.add_node(target, bipartite=1)
|
434 |
+
G.add_edge(source, target)
|
435 |
+
vv.remove(vv[0])
|
436 |
+
G.name = "bipartite_preferential_attachment_model"
|
437 |
+
return G
|
438 |
+
|
439 |
+
|
440 |
+
@py_random_state(3)
|
441 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
442 |
+
def random_graph(n, m, p, seed=None, directed=False):
|
443 |
+
"""Returns a bipartite random graph.
|
444 |
+
|
445 |
+
This is a bipartite version of the binomial (Erdős-Rényi) graph.
|
446 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
447 |
+
(n - 1) and set B has nodes n to (n + m - 1).
|
448 |
+
|
449 |
+
Parameters
|
450 |
+
----------
|
451 |
+
n : int
|
452 |
+
The number of nodes in the first bipartite set.
|
453 |
+
m : int
|
454 |
+
The number of nodes in the second bipartite set.
|
455 |
+
p : float
|
456 |
+
Probability for edge creation.
|
457 |
+
seed : integer, random_state, or None (default)
|
458 |
+
Indicator of random number generation state.
|
459 |
+
See :ref:`Randomness<randomness>`.
|
460 |
+
directed : bool, optional (default=False)
|
461 |
+
If True return a directed graph
|
462 |
+
|
463 |
+
Notes
|
464 |
+
-----
|
465 |
+
The bipartite random graph algorithm chooses each of the n*m (undirected)
|
466 |
+
or 2*nm (directed) possible edges with probability p.
|
467 |
+
|
468 |
+
This algorithm is $O(n+m)$ where $m$ is the expected number of edges.
|
469 |
+
|
470 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
471 |
+
to indicate which bipartite set the node belongs to.
|
472 |
+
|
473 |
+
This function is not imported in the main namespace.
|
474 |
+
To use it use nx.bipartite.random_graph
|
475 |
+
|
476 |
+
See Also
|
477 |
+
--------
|
478 |
+
gnp_random_graph, configuration_model
|
479 |
+
|
480 |
+
References
|
481 |
+
----------
|
482 |
+
.. [1] Vladimir Batagelj and Ulrik Brandes,
|
483 |
+
"Efficient generation of large random networks",
|
484 |
+
Phys. Rev. E, 71, 036113, 2005.
|
485 |
+
"""
|
486 |
+
G = nx.Graph()
|
487 |
+
G = _add_nodes_with_bipartite_label(G, n, m)
|
488 |
+
if directed:
|
489 |
+
G = nx.DiGraph(G)
|
490 |
+
G.name = f"fast_gnp_random_graph({n},{m},{p})"
|
491 |
+
|
492 |
+
if p <= 0:
|
493 |
+
return G
|
494 |
+
if p >= 1:
|
495 |
+
return nx.complete_bipartite_graph(n, m)
|
496 |
+
|
497 |
+
lp = math.log(1.0 - p)
|
498 |
+
|
499 |
+
v = 0
|
500 |
+
w = -1
|
501 |
+
while v < n:
|
502 |
+
lr = math.log(1.0 - seed.random())
|
503 |
+
w = w + 1 + int(lr / lp)
|
504 |
+
while w >= m and v < n:
|
505 |
+
w = w - m
|
506 |
+
v = v + 1
|
507 |
+
if v < n:
|
508 |
+
G.add_edge(v, n + w)
|
509 |
+
|
510 |
+
if directed:
|
511 |
+
# use the same algorithm to
|
512 |
+
# add edges from the "m" to "n" set
|
513 |
+
v = 0
|
514 |
+
w = -1
|
515 |
+
while v < n:
|
516 |
+
lr = math.log(1.0 - seed.random())
|
517 |
+
w = w + 1 + int(lr / lp)
|
518 |
+
while w >= m and v < n:
|
519 |
+
w = w - m
|
520 |
+
v = v + 1
|
521 |
+
if v < n:
|
522 |
+
G.add_edge(n + w, v)
|
523 |
+
|
524 |
+
return G
|
525 |
+
|
526 |
+
|
527 |
+
@py_random_state(3)
|
528 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
529 |
+
def gnmk_random_graph(n, m, k, seed=None, directed=False):
|
530 |
+
"""Returns a random bipartite graph G_{n,m,k}.
|
531 |
+
|
532 |
+
Produces a bipartite graph chosen randomly out of the set of all graphs
|
533 |
+
with n top nodes, m bottom nodes, and k edges.
|
534 |
+
The graph is composed of two sets of nodes.
|
535 |
+
Set A has nodes 0 to (n - 1) and set B has nodes n to (n + m - 1).
|
536 |
+
|
537 |
+
Parameters
|
538 |
+
----------
|
539 |
+
n : int
|
540 |
+
The number of nodes in the first bipartite set.
|
541 |
+
m : int
|
542 |
+
The number of nodes in the second bipartite set.
|
543 |
+
k : int
|
544 |
+
The number of edges
|
545 |
+
seed : integer, random_state, or None (default)
|
546 |
+
Indicator of random number generation state.
|
547 |
+
See :ref:`Randomness<randomness>`.
|
548 |
+
directed : bool, optional (default=False)
|
549 |
+
If True return a directed graph
|
550 |
+
|
551 |
+
Examples
|
552 |
+
--------
|
553 |
+
from nx.algorithms import bipartite
|
554 |
+
G = bipartite.gnmk_random_graph(10,20,50)
|
555 |
+
|
556 |
+
See Also
|
557 |
+
--------
|
558 |
+
gnm_random_graph
|
559 |
+
|
560 |
+
Notes
|
561 |
+
-----
|
562 |
+
If k > m * n then a complete bipartite graph is returned.
|
563 |
+
|
564 |
+
This graph is a bipartite version of the `G_{nm}` random graph model.
|
565 |
+
|
566 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
567 |
+
to indicate which bipartite set the node belongs to.
|
568 |
+
|
569 |
+
This function is not imported in the main namespace.
|
570 |
+
To use it use nx.bipartite.gnmk_random_graph
|
571 |
+
"""
|
572 |
+
G = nx.Graph()
|
573 |
+
G = _add_nodes_with_bipartite_label(G, n, m)
|
574 |
+
if directed:
|
575 |
+
G = nx.DiGraph(G)
|
576 |
+
G.name = f"bipartite_gnm_random_graph({n},{m},{k})"
|
577 |
+
if n == 1 or m == 1:
|
578 |
+
return G
|
579 |
+
max_edges = n * m # max_edges for bipartite networks
|
580 |
+
if k >= max_edges: # Maybe we should raise an exception here
|
581 |
+
return nx.complete_bipartite_graph(n, m, create_using=G)
|
582 |
+
|
583 |
+
top = [n for n, d in G.nodes(data=True) if d["bipartite"] == 0]
|
584 |
+
bottom = list(set(G) - set(top))
|
585 |
+
edge_count = 0
|
586 |
+
while edge_count < k:
|
587 |
+
# generate random edge,u,v
|
588 |
+
u = seed.choice(top)
|
589 |
+
v = seed.choice(bottom)
|
590 |
+
if v in G[u]:
|
591 |
+
continue
|
592 |
+
else:
|
593 |
+
G.add_edge(u, v)
|
594 |
+
edge_count += 1
|
595 |
+
return G
|
596 |
+
|
597 |
+
|
598 |
+
def _add_nodes_with_bipartite_label(G, lena, lenb):
|
599 |
+
G.add_nodes_from(range(lena + lenb))
|
600 |
+
b = dict(zip(range(lena), [0] * lena))
|
601 |
+
b.update(dict(zip(range(lena, lena + lenb), [1] * lenb)))
|
602 |
+
nx.set_node_attributes(G, b, "bipartite")
|
603 |
+
return G
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/matching.py
ADDED
@@ -0,0 +1,589 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This module uses material from the Wikipedia article Hopcroft--Karp algorithm
|
2 |
+
# <https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm>, accessed on
|
3 |
+
# January 3, 2015, which is released under the Creative Commons
|
4 |
+
# Attribution-Share-Alike License 3.0
|
5 |
+
# <http://creativecommons.org/licenses/by-sa/3.0/>. That article includes
|
6 |
+
# pseudocode, which has been translated into the corresponding Python code.
|
7 |
+
#
|
8 |
+
# Portions of this module use code from David Eppstein's Python Algorithms and
|
9 |
+
# Data Structures (PADS) library, which is dedicated to the public domain (for
|
10 |
+
# proof, see <http://www.ics.uci.edu/~eppstein/PADS/ABOUT-PADS.txt>).
|
11 |
+
"""Provides functions for computing maximum cardinality matchings and minimum
|
12 |
+
weight full matchings in a bipartite graph.
|
13 |
+
|
14 |
+
If you don't care about the particular implementation of the maximum matching
|
15 |
+
algorithm, simply use the :func:`maximum_matching`. If you do care, you can
|
16 |
+
import one of the named maximum matching algorithms directly.
|
17 |
+
|
18 |
+
For example, to find a maximum matching in the complete bipartite graph with
|
19 |
+
two vertices on the left and three vertices on the right:
|
20 |
+
|
21 |
+
>>> G = nx.complete_bipartite_graph(2, 3)
|
22 |
+
>>> left, right = nx.bipartite.sets(G)
|
23 |
+
>>> list(left)
|
24 |
+
[0, 1]
|
25 |
+
>>> list(right)
|
26 |
+
[2, 3, 4]
|
27 |
+
>>> nx.bipartite.maximum_matching(G)
|
28 |
+
{0: 2, 1: 3, 2: 0, 3: 1}
|
29 |
+
|
30 |
+
The dictionary returned by :func:`maximum_matching` includes a mapping for
|
31 |
+
vertices in both the left and right vertex sets.
|
32 |
+
|
33 |
+
Similarly, :func:`minimum_weight_full_matching` produces, for a complete
|
34 |
+
weighted bipartite graph, a matching whose cardinality is the cardinality of
|
35 |
+
the smaller of the two partitions, and for which the sum of the weights of the
|
36 |
+
edges included in the matching is minimal.
|
37 |
+
|
38 |
+
"""
|
39 |
+
import collections
|
40 |
+
import itertools
|
41 |
+
|
42 |
+
import networkx as nx
|
43 |
+
from networkx.algorithms.bipartite import sets as bipartite_sets
|
44 |
+
from networkx.algorithms.bipartite.matrix import biadjacency_matrix
|
45 |
+
|
46 |
+
__all__ = [
|
47 |
+
"maximum_matching",
|
48 |
+
"hopcroft_karp_matching",
|
49 |
+
"eppstein_matching",
|
50 |
+
"to_vertex_cover",
|
51 |
+
"minimum_weight_full_matching",
|
52 |
+
]
|
53 |
+
|
54 |
+
INFINITY = float("inf")
|
55 |
+
|
56 |
+
|
57 |
+
@nx._dispatchable
|
58 |
+
def hopcroft_karp_matching(G, top_nodes=None):
|
59 |
+
"""Returns the maximum cardinality matching of the bipartite graph `G`.
|
60 |
+
|
61 |
+
A matching is a set of edges that do not share any nodes. A maximum
|
62 |
+
cardinality matching is a matching with the most edges possible. It
|
63 |
+
is not always unique. Finding a matching in a bipartite graph can be
|
64 |
+
treated as a networkx flow problem.
|
65 |
+
|
66 |
+
The functions ``hopcroft_karp_matching`` and ``maximum_matching``
|
67 |
+
are aliases of the same function.
|
68 |
+
|
69 |
+
Parameters
|
70 |
+
----------
|
71 |
+
G : NetworkX graph
|
72 |
+
|
73 |
+
Undirected bipartite graph
|
74 |
+
|
75 |
+
top_nodes : container of nodes
|
76 |
+
|
77 |
+
Container with all nodes in one bipartite node set. If not supplied
|
78 |
+
it will be computed. But if more than one solution exists an exception
|
79 |
+
will be raised.
|
80 |
+
|
81 |
+
Returns
|
82 |
+
-------
|
83 |
+
matches : dictionary
|
84 |
+
|
85 |
+
The matching is returned as a dictionary, `matches`, such that
|
86 |
+
``matches[v] == w`` if node `v` is matched to node `w`. Unmatched
|
87 |
+
nodes do not occur as a key in `matches`.
|
88 |
+
|
89 |
+
Raises
|
90 |
+
------
|
91 |
+
AmbiguousSolution
|
92 |
+
Raised if the input bipartite graph is disconnected and no container
|
93 |
+
with all nodes in one bipartite set is provided. When determining
|
94 |
+
the nodes in each bipartite set more than one valid solution is
|
95 |
+
possible if the input graph is disconnected.
|
96 |
+
|
97 |
+
Notes
|
98 |
+
-----
|
99 |
+
This function is implemented with the `Hopcroft--Karp matching algorithm
|
100 |
+
<https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm>`_ for
|
101 |
+
bipartite graphs.
|
102 |
+
|
103 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
104 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
105 |
+
|
106 |
+
See Also
|
107 |
+
--------
|
108 |
+
maximum_matching
|
109 |
+
hopcroft_karp_matching
|
110 |
+
eppstein_matching
|
111 |
+
|
112 |
+
References
|
113 |
+
----------
|
114 |
+
.. [1] John E. Hopcroft and Richard M. Karp. "An n^{5 / 2} Algorithm for
|
115 |
+
Maximum Matchings in Bipartite Graphs" In: **SIAM Journal of Computing**
|
116 |
+
2.4 (1973), pp. 225--231. <https://doi.org/10.1137/0202019>.
|
117 |
+
|
118 |
+
"""
|
119 |
+
|
120 |
+
# First we define some auxiliary search functions.
|
121 |
+
#
|
122 |
+
# If you are a human reading these auxiliary search functions, the "global"
|
123 |
+
# variables `leftmatches`, `rightmatches`, `distances`, etc. are defined
|
124 |
+
# below the functions, so that they are initialized close to the initial
|
125 |
+
# invocation of the search functions.
|
126 |
+
def breadth_first_search():
|
127 |
+
for v in left:
|
128 |
+
if leftmatches[v] is None:
|
129 |
+
distances[v] = 0
|
130 |
+
queue.append(v)
|
131 |
+
else:
|
132 |
+
distances[v] = INFINITY
|
133 |
+
distances[None] = INFINITY
|
134 |
+
while queue:
|
135 |
+
v = queue.popleft()
|
136 |
+
if distances[v] < distances[None]:
|
137 |
+
for u in G[v]:
|
138 |
+
if distances[rightmatches[u]] is INFINITY:
|
139 |
+
distances[rightmatches[u]] = distances[v] + 1
|
140 |
+
queue.append(rightmatches[u])
|
141 |
+
return distances[None] is not INFINITY
|
142 |
+
|
143 |
+
def depth_first_search(v):
|
144 |
+
if v is not None:
|
145 |
+
for u in G[v]:
|
146 |
+
if distances[rightmatches[u]] == distances[v] + 1:
|
147 |
+
if depth_first_search(rightmatches[u]):
|
148 |
+
rightmatches[u] = v
|
149 |
+
leftmatches[v] = u
|
150 |
+
return True
|
151 |
+
distances[v] = INFINITY
|
152 |
+
return False
|
153 |
+
return True
|
154 |
+
|
155 |
+
# Initialize the "global" variables that maintain state during the search.
|
156 |
+
left, right = bipartite_sets(G, top_nodes)
|
157 |
+
leftmatches = {v: None for v in left}
|
158 |
+
rightmatches = {v: None for v in right}
|
159 |
+
distances = {}
|
160 |
+
queue = collections.deque()
|
161 |
+
|
162 |
+
# Implementation note: this counter is incremented as pairs are matched but
|
163 |
+
# it is currently not used elsewhere in the computation.
|
164 |
+
num_matched_pairs = 0
|
165 |
+
while breadth_first_search():
|
166 |
+
for v in left:
|
167 |
+
if leftmatches[v] is None:
|
168 |
+
if depth_first_search(v):
|
169 |
+
num_matched_pairs += 1
|
170 |
+
|
171 |
+
# Strip the entries matched to `None`.
|
172 |
+
leftmatches = {k: v for k, v in leftmatches.items() if v is not None}
|
173 |
+
rightmatches = {k: v for k, v in rightmatches.items() if v is not None}
|
174 |
+
|
175 |
+
# At this point, the left matches and the right matches are inverses of one
|
176 |
+
# another. In other words,
|
177 |
+
#
|
178 |
+
# leftmatches == {v, k for k, v in rightmatches.items()}
|
179 |
+
#
|
180 |
+
# Finally, we combine both the left matches and right matches.
|
181 |
+
return dict(itertools.chain(leftmatches.items(), rightmatches.items()))
|
182 |
+
|
183 |
+
|
184 |
+
@nx._dispatchable
|
185 |
+
def eppstein_matching(G, top_nodes=None):
|
186 |
+
"""Returns the maximum cardinality matching of the bipartite graph `G`.
|
187 |
+
|
188 |
+
Parameters
|
189 |
+
----------
|
190 |
+
G : NetworkX graph
|
191 |
+
|
192 |
+
Undirected bipartite graph
|
193 |
+
|
194 |
+
top_nodes : container
|
195 |
+
|
196 |
+
Container with all nodes in one bipartite node set. If not supplied
|
197 |
+
it will be computed. But if more than one solution exists an exception
|
198 |
+
will be raised.
|
199 |
+
|
200 |
+
Returns
|
201 |
+
-------
|
202 |
+
matches : dictionary
|
203 |
+
|
204 |
+
The matching is returned as a dictionary, `matching`, such that
|
205 |
+
``matching[v] == w`` if node `v` is matched to node `w`. Unmatched
|
206 |
+
nodes do not occur as a key in `matching`.
|
207 |
+
|
208 |
+
Raises
|
209 |
+
------
|
210 |
+
AmbiguousSolution
|
211 |
+
Raised if the input bipartite graph is disconnected and no container
|
212 |
+
with all nodes in one bipartite set is provided. When determining
|
213 |
+
the nodes in each bipartite set more than one valid solution is
|
214 |
+
possible if the input graph is disconnected.
|
215 |
+
|
216 |
+
Notes
|
217 |
+
-----
|
218 |
+
This function is implemented with David Eppstein's version of the algorithm
|
219 |
+
Hopcroft--Karp algorithm (see :func:`hopcroft_karp_matching`), which
|
220 |
+
originally appeared in the `Python Algorithms and Data Structures library
|
221 |
+
(PADS) <http://www.ics.uci.edu/~eppstein/PADS/ABOUT-PADS.txt>`_.
|
222 |
+
|
223 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
224 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
225 |
+
|
226 |
+
See Also
|
227 |
+
--------
|
228 |
+
|
229 |
+
hopcroft_karp_matching
|
230 |
+
|
231 |
+
"""
|
232 |
+
# Due to its original implementation, a directed graph is needed
|
233 |
+
# so that the two sets of bipartite nodes can be distinguished
|
234 |
+
left, right = bipartite_sets(G, top_nodes)
|
235 |
+
G = nx.DiGraph(G.edges(left))
|
236 |
+
# initialize greedy matching (redundant, but faster than full search)
|
237 |
+
matching = {}
|
238 |
+
for u in G:
|
239 |
+
for v in G[u]:
|
240 |
+
if v not in matching:
|
241 |
+
matching[v] = u
|
242 |
+
break
|
243 |
+
while True:
|
244 |
+
# structure residual graph into layers
|
245 |
+
# pred[u] gives the neighbor in the previous layer for u in U
|
246 |
+
# preds[v] gives a list of neighbors in the previous layer for v in V
|
247 |
+
# unmatched gives a list of unmatched vertices in final layer of V,
|
248 |
+
# and is also used as a flag value for pred[u] when u is in the first
|
249 |
+
# layer
|
250 |
+
preds = {}
|
251 |
+
unmatched = []
|
252 |
+
pred = {u: unmatched for u in G}
|
253 |
+
for v in matching:
|
254 |
+
del pred[matching[v]]
|
255 |
+
layer = list(pred)
|
256 |
+
|
257 |
+
# repeatedly extend layering structure by another pair of layers
|
258 |
+
while layer and not unmatched:
|
259 |
+
newLayer = {}
|
260 |
+
for u in layer:
|
261 |
+
for v in G[u]:
|
262 |
+
if v not in preds:
|
263 |
+
newLayer.setdefault(v, []).append(u)
|
264 |
+
layer = []
|
265 |
+
for v in newLayer:
|
266 |
+
preds[v] = newLayer[v]
|
267 |
+
if v in matching:
|
268 |
+
layer.append(matching[v])
|
269 |
+
pred[matching[v]] = v
|
270 |
+
else:
|
271 |
+
unmatched.append(v)
|
272 |
+
|
273 |
+
# did we finish layering without finding any alternating paths?
|
274 |
+
if not unmatched:
|
275 |
+
# TODO - The lines between --- were unused and were thus commented
|
276 |
+
# out. This whole commented chunk should be reviewed to determine
|
277 |
+
# whether it should be built upon or completely removed.
|
278 |
+
# ---
|
279 |
+
# unlayered = {}
|
280 |
+
# for u in G:
|
281 |
+
# # TODO Why is extra inner loop necessary?
|
282 |
+
# for v in G[u]:
|
283 |
+
# if v not in preds:
|
284 |
+
# unlayered[v] = None
|
285 |
+
# ---
|
286 |
+
# TODO Originally, this function returned a three-tuple:
|
287 |
+
#
|
288 |
+
# return (matching, list(pred), list(unlayered))
|
289 |
+
#
|
290 |
+
# For some reason, the documentation for this function
|
291 |
+
# indicated that the second and third elements of the returned
|
292 |
+
# three-tuple would be the vertices in the left and right vertex
|
293 |
+
# sets, respectively, that are also in the maximum independent set.
|
294 |
+
# However, what I think the author meant was that the second
|
295 |
+
# element is the list of vertices that were unmatched and the third
|
296 |
+
# element was the list of vertices that were matched. Since that
|
297 |
+
# seems to be the case, they don't really need to be returned,
|
298 |
+
# since that information can be inferred from the matching
|
299 |
+
# dictionary.
|
300 |
+
|
301 |
+
# All the matched nodes must be a key in the dictionary
|
302 |
+
for key in matching.copy():
|
303 |
+
matching[matching[key]] = key
|
304 |
+
return matching
|
305 |
+
|
306 |
+
# recursively search backward through layers to find alternating paths
|
307 |
+
# recursion returns true if found path, false otherwise
|
308 |
+
def recurse(v):
|
309 |
+
if v in preds:
|
310 |
+
L = preds.pop(v)
|
311 |
+
for u in L:
|
312 |
+
if u in pred:
|
313 |
+
pu = pred.pop(u)
|
314 |
+
if pu is unmatched or recurse(pu):
|
315 |
+
matching[v] = u
|
316 |
+
return True
|
317 |
+
return False
|
318 |
+
|
319 |
+
for v in unmatched:
|
320 |
+
recurse(v)
|
321 |
+
|
322 |
+
|
323 |
+
def _is_connected_by_alternating_path(G, v, matched_edges, unmatched_edges, targets):
|
324 |
+
"""Returns True if and only if the vertex `v` is connected to one of
|
325 |
+
the target vertices by an alternating path in `G`.
|
326 |
+
|
327 |
+
An *alternating path* is a path in which every other edge is in the
|
328 |
+
specified maximum matching (and the remaining edges in the path are not in
|
329 |
+
the matching). An alternating path may have matched edges in the even
|
330 |
+
positions or in the odd positions, as long as the edges alternate between
|
331 |
+
'matched' and 'unmatched'.
|
332 |
+
|
333 |
+
`G` is an undirected bipartite NetworkX graph.
|
334 |
+
|
335 |
+
`v` is a vertex in `G`.
|
336 |
+
|
337 |
+
`matched_edges` is a set of edges present in a maximum matching in `G`.
|
338 |
+
|
339 |
+
`unmatched_edges` is a set of edges not present in a maximum
|
340 |
+
matching in `G`.
|
341 |
+
|
342 |
+
`targets` is a set of vertices.
|
343 |
+
|
344 |
+
"""
|
345 |
+
|
346 |
+
def _alternating_dfs(u, along_matched=True):
|
347 |
+
"""Returns True if and only if `u` is connected to one of the
|
348 |
+
targets by an alternating path.
|
349 |
+
|
350 |
+
`u` is a vertex in the graph `G`.
|
351 |
+
|
352 |
+
If `along_matched` is True, this step of the depth-first search
|
353 |
+
will continue only through edges in the given matching. Otherwise, it
|
354 |
+
will continue only through edges *not* in the given matching.
|
355 |
+
|
356 |
+
"""
|
357 |
+
visited = set()
|
358 |
+
# Follow matched edges when depth is even,
|
359 |
+
# and follow unmatched edges when depth is odd.
|
360 |
+
initial_depth = 0 if along_matched else 1
|
361 |
+
stack = [(u, iter(G[u]), initial_depth)]
|
362 |
+
while stack:
|
363 |
+
parent, children, depth = stack[-1]
|
364 |
+
valid_edges = matched_edges if depth % 2 else unmatched_edges
|
365 |
+
try:
|
366 |
+
child = next(children)
|
367 |
+
if child not in visited:
|
368 |
+
if (parent, child) in valid_edges or (child, parent) in valid_edges:
|
369 |
+
if child in targets:
|
370 |
+
return True
|
371 |
+
visited.add(child)
|
372 |
+
stack.append((child, iter(G[child]), depth + 1))
|
373 |
+
except StopIteration:
|
374 |
+
stack.pop()
|
375 |
+
return False
|
376 |
+
|
377 |
+
# Check for alternating paths starting with edges in the matching, then
|
378 |
+
# check for alternating paths starting with edges not in the
|
379 |
+
# matching.
|
380 |
+
return _alternating_dfs(v, along_matched=True) or _alternating_dfs(
|
381 |
+
v, along_matched=False
|
382 |
+
)
|
383 |
+
|
384 |
+
|
385 |
+
def _connected_by_alternating_paths(G, matching, targets):
|
386 |
+
"""Returns the set of vertices that are connected to one of the target
|
387 |
+
vertices by an alternating path in `G` or are themselves a target.
|
388 |
+
|
389 |
+
An *alternating path* is a path in which every other edge is in the
|
390 |
+
specified maximum matching (and the remaining edges in the path are not in
|
391 |
+
the matching). An alternating path may have matched edges in the even
|
392 |
+
positions or in the odd positions, as long as the edges alternate between
|
393 |
+
'matched' and 'unmatched'.
|
394 |
+
|
395 |
+
`G` is an undirected bipartite NetworkX graph.
|
396 |
+
|
397 |
+
`matching` is a dictionary representing a maximum matching in `G`, as
|
398 |
+
returned by, for example, :func:`maximum_matching`.
|
399 |
+
|
400 |
+
`targets` is a set of vertices.
|
401 |
+
|
402 |
+
"""
|
403 |
+
# Get the set of matched edges and the set of unmatched edges. Only include
|
404 |
+
# one version of each undirected edge (for example, include edge (1, 2) but
|
405 |
+
# not edge (2, 1)). Using frozensets as an intermediary step we do not
|
406 |
+
# require nodes to be orderable.
|
407 |
+
edge_sets = {frozenset((u, v)) for u, v in matching.items()}
|
408 |
+
matched_edges = {tuple(edge) for edge in edge_sets}
|
409 |
+
unmatched_edges = {
|
410 |
+
(u, v) for (u, v) in G.edges() if frozenset((u, v)) not in edge_sets
|
411 |
+
}
|
412 |
+
|
413 |
+
return {
|
414 |
+
v
|
415 |
+
for v in G
|
416 |
+
if v in targets
|
417 |
+
or _is_connected_by_alternating_path(
|
418 |
+
G, v, matched_edges, unmatched_edges, targets
|
419 |
+
)
|
420 |
+
}
|
421 |
+
|
422 |
+
|
423 |
+
@nx._dispatchable
|
424 |
+
def to_vertex_cover(G, matching, top_nodes=None):
|
425 |
+
"""Returns the minimum vertex cover corresponding to the given maximum
|
426 |
+
matching of the bipartite graph `G`.
|
427 |
+
|
428 |
+
Parameters
|
429 |
+
----------
|
430 |
+
G : NetworkX graph
|
431 |
+
|
432 |
+
Undirected bipartite graph
|
433 |
+
|
434 |
+
matching : dictionary
|
435 |
+
|
436 |
+
A dictionary whose keys are vertices in `G` and whose values are the
|
437 |
+
distinct neighbors comprising the maximum matching for `G`, as returned
|
438 |
+
by, for example, :func:`maximum_matching`. The dictionary *must*
|
439 |
+
represent the maximum matching.
|
440 |
+
|
441 |
+
top_nodes : container
|
442 |
+
|
443 |
+
Container with all nodes in one bipartite node set. If not supplied
|
444 |
+
it will be computed. But if more than one solution exists an exception
|
445 |
+
will be raised.
|
446 |
+
|
447 |
+
Returns
|
448 |
+
-------
|
449 |
+
vertex_cover : :class:`set`
|
450 |
+
|
451 |
+
The minimum vertex cover in `G`.
|
452 |
+
|
453 |
+
Raises
|
454 |
+
------
|
455 |
+
AmbiguousSolution
|
456 |
+
Raised if the input bipartite graph is disconnected and no container
|
457 |
+
with all nodes in one bipartite set is provided. When determining
|
458 |
+
the nodes in each bipartite set more than one valid solution is
|
459 |
+
possible if the input graph is disconnected.
|
460 |
+
|
461 |
+
Notes
|
462 |
+
-----
|
463 |
+
This function is implemented using the procedure guaranteed by `Konig's
|
464 |
+
theorem
|
465 |
+
<https://en.wikipedia.org/wiki/K%C3%B6nig%27s_theorem_%28graph_theory%29>`_,
|
466 |
+
which proves an equivalence between a maximum matching and a minimum vertex
|
467 |
+
cover in bipartite graphs.
|
468 |
+
|
469 |
+
Since a minimum vertex cover is the complement of a maximum independent set
|
470 |
+
for any graph, one can compute the maximum independent set of a bipartite
|
471 |
+
graph this way:
|
472 |
+
|
473 |
+
>>> G = nx.complete_bipartite_graph(2, 3)
|
474 |
+
>>> matching = nx.bipartite.maximum_matching(G)
|
475 |
+
>>> vertex_cover = nx.bipartite.to_vertex_cover(G, matching)
|
476 |
+
>>> independent_set = set(G) - vertex_cover
|
477 |
+
>>> print(list(independent_set))
|
478 |
+
[2, 3, 4]
|
479 |
+
|
480 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
481 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
482 |
+
|
483 |
+
"""
|
484 |
+
# This is a Python implementation of the algorithm described at
|
485 |
+
# <https://en.wikipedia.org/wiki/K%C3%B6nig%27s_theorem_%28graph_theory%29#Proof>.
|
486 |
+
L, R = bipartite_sets(G, top_nodes)
|
487 |
+
# Let U be the set of unmatched vertices in the left vertex set.
|
488 |
+
unmatched_vertices = set(G) - set(matching)
|
489 |
+
U = unmatched_vertices & L
|
490 |
+
# Let Z be the set of vertices that are either in U or are connected to U
|
491 |
+
# by alternating paths.
|
492 |
+
Z = _connected_by_alternating_paths(G, matching, U)
|
493 |
+
# At this point, every edge either has a right endpoint in Z or a left
|
494 |
+
# endpoint not in Z. This gives us the vertex cover.
|
495 |
+
return (L - Z) | (R & Z)
|
496 |
+
|
497 |
+
|
498 |
+
#: Returns the maximum cardinality matching in the given bipartite graph.
|
499 |
+
#:
|
500 |
+
#: This function is simply an alias for :func:`hopcroft_karp_matching`.
|
501 |
+
maximum_matching = hopcroft_karp_matching
|
502 |
+
|
503 |
+
|
504 |
+
@nx._dispatchable(edge_attrs="weight")
|
505 |
+
def minimum_weight_full_matching(G, top_nodes=None, weight="weight"):
|
506 |
+
r"""Returns a minimum weight full matching of the bipartite graph `G`.
|
507 |
+
|
508 |
+
Let :math:`G = ((U, V), E)` be a weighted bipartite graph with real weights
|
509 |
+
:math:`w : E \to \mathbb{R}`. This function then produces a matching
|
510 |
+
:math:`M \subseteq E` with cardinality
|
511 |
+
|
512 |
+
.. math::
|
513 |
+
\lvert M \rvert = \min(\lvert U \rvert, \lvert V \rvert),
|
514 |
+
|
515 |
+
which minimizes the sum of the weights of the edges included in the
|
516 |
+
matching, :math:`\sum_{e \in M} w(e)`, or raises an error if no such
|
517 |
+
matching exists.
|
518 |
+
|
519 |
+
When :math:`\lvert U \rvert = \lvert V \rvert`, this is commonly
|
520 |
+
referred to as a perfect matching; here, since we allow
|
521 |
+
:math:`\lvert U \rvert` and :math:`\lvert V \rvert` to differ, we
|
522 |
+
follow Karp [1]_ and refer to the matching as *full*.
|
523 |
+
|
524 |
+
Parameters
|
525 |
+
----------
|
526 |
+
G : NetworkX graph
|
527 |
+
|
528 |
+
Undirected bipartite graph
|
529 |
+
|
530 |
+
top_nodes : container
|
531 |
+
|
532 |
+
Container with all nodes in one bipartite node set. If not supplied
|
533 |
+
it will be computed.
|
534 |
+
|
535 |
+
weight : string, optional (default='weight')
|
536 |
+
|
537 |
+
The edge data key used to provide each value in the matrix.
|
538 |
+
If None, then each edge has weight 1.
|
539 |
+
|
540 |
+
Returns
|
541 |
+
-------
|
542 |
+
matches : dictionary
|
543 |
+
|
544 |
+
The matching is returned as a dictionary, `matches`, such that
|
545 |
+
``matches[v] == w`` if node `v` is matched to node `w`. Unmatched
|
546 |
+
nodes do not occur as a key in `matches`.
|
547 |
+
|
548 |
+
Raises
|
549 |
+
------
|
550 |
+
ValueError
|
551 |
+
Raised if no full matching exists.
|
552 |
+
|
553 |
+
ImportError
|
554 |
+
Raised if SciPy is not available.
|
555 |
+
|
556 |
+
Notes
|
557 |
+
-----
|
558 |
+
The problem of determining a minimum weight full matching is also known as
|
559 |
+
the rectangular linear assignment problem. This implementation defers the
|
560 |
+
calculation of the assignment to SciPy.
|
561 |
+
|
562 |
+
References
|
563 |
+
----------
|
564 |
+
.. [1] Richard Manning Karp:
|
565 |
+
An algorithm to Solve the m x n Assignment Problem in Expected Time
|
566 |
+
O(mn log n).
|
567 |
+
Networks, 10(2):143–152, 1980.
|
568 |
+
|
569 |
+
"""
|
570 |
+
import numpy as np
|
571 |
+
import scipy as sp
|
572 |
+
|
573 |
+
left, right = nx.bipartite.sets(G, top_nodes)
|
574 |
+
U = list(left)
|
575 |
+
V = list(right)
|
576 |
+
# We explicitly create the biadjacency matrix having infinities
|
577 |
+
# where edges are missing (as opposed to zeros, which is what one would
|
578 |
+
# get by using toarray on the sparse matrix).
|
579 |
+
weights_sparse = biadjacency_matrix(
|
580 |
+
G, row_order=U, column_order=V, weight=weight, format="coo"
|
581 |
+
)
|
582 |
+
weights = np.full(weights_sparse.shape, np.inf)
|
583 |
+
weights[weights_sparse.row, weights_sparse.col] = weights_sparse.data
|
584 |
+
left_matches = sp.optimize.linear_sum_assignment(weights)
|
585 |
+
d = {U[u]: V[v] for u, v in zip(*left_matches)}
|
586 |
+
# d will contain the matching from edges in left to right; we need to
|
587 |
+
# add the ones from right to left as well.
|
588 |
+
d.update({v: u for u, v in d.items()})
|
589 |
+
return d
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/matrix.py
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
====================
|
3 |
+
Biadjacency matrices
|
4 |
+
====================
|
5 |
+
"""
|
6 |
+
import itertools
|
7 |
+
|
8 |
+
import networkx as nx
|
9 |
+
from networkx.convert_matrix import _generate_weighted_edges
|
10 |
+
|
11 |
+
__all__ = ["biadjacency_matrix", "from_biadjacency_matrix"]
|
12 |
+
|
13 |
+
|
14 |
+
@nx._dispatchable(edge_attrs="weight")
|
15 |
+
def biadjacency_matrix(
|
16 |
+
G, row_order, column_order=None, dtype=None, weight="weight", format="csr"
|
17 |
+
):
|
18 |
+
r"""Returns the biadjacency matrix of the bipartite graph G.
|
19 |
+
|
20 |
+
Let `G = (U, V, E)` be a bipartite graph with node sets
|
21 |
+
`U = u_{1},...,u_{r}` and `V = v_{1},...,v_{s}`. The biadjacency
|
22 |
+
matrix [1]_ is the `r` x `s` matrix `B` in which `b_{i,j} = 1`
|
23 |
+
if, and only if, `(u_i, v_j) \in E`. If the parameter `weight` is
|
24 |
+
not `None` and matches the name of an edge attribute, its value is
|
25 |
+
used instead of 1.
|
26 |
+
|
27 |
+
Parameters
|
28 |
+
----------
|
29 |
+
G : graph
|
30 |
+
A NetworkX graph
|
31 |
+
|
32 |
+
row_order : list of nodes
|
33 |
+
The rows of the matrix are ordered according to the list of nodes.
|
34 |
+
|
35 |
+
column_order : list, optional
|
36 |
+
The columns of the matrix are ordered according to the list of nodes.
|
37 |
+
If column_order is None, then the ordering of columns is arbitrary.
|
38 |
+
|
39 |
+
dtype : NumPy data-type, optional
|
40 |
+
A valid NumPy dtype used to initialize the array. If None, then the
|
41 |
+
NumPy default is used.
|
42 |
+
|
43 |
+
weight : string or None, optional (default='weight')
|
44 |
+
The edge data key used to provide each value in the matrix.
|
45 |
+
If None, then each edge has weight 1.
|
46 |
+
|
47 |
+
format : str in {'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'}
|
48 |
+
The type of the matrix to be returned (default 'csr'). For
|
49 |
+
some algorithms different implementations of sparse matrices
|
50 |
+
can perform better. See [2]_ for details.
|
51 |
+
|
52 |
+
Returns
|
53 |
+
-------
|
54 |
+
M : SciPy sparse array
|
55 |
+
Biadjacency matrix representation of the bipartite graph G.
|
56 |
+
|
57 |
+
Notes
|
58 |
+
-----
|
59 |
+
No attempt is made to check that the input graph is bipartite.
|
60 |
+
|
61 |
+
For directed bipartite graphs only successors are considered as neighbors.
|
62 |
+
To obtain an adjacency matrix with ones (or weight values) for both
|
63 |
+
predecessors and successors you have to generate two biadjacency matrices
|
64 |
+
where the rows of one of them are the columns of the other, and then add
|
65 |
+
one to the transpose of the other.
|
66 |
+
|
67 |
+
See Also
|
68 |
+
--------
|
69 |
+
adjacency_matrix
|
70 |
+
from_biadjacency_matrix
|
71 |
+
|
72 |
+
References
|
73 |
+
----------
|
74 |
+
.. [1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
|
75 |
+
.. [2] Scipy Dev. References, "Sparse Matrices",
|
76 |
+
https://docs.scipy.org/doc/scipy/reference/sparse.html
|
77 |
+
"""
|
78 |
+
import scipy as sp
|
79 |
+
|
80 |
+
nlen = len(row_order)
|
81 |
+
if nlen == 0:
|
82 |
+
raise nx.NetworkXError("row_order is empty list")
|
83 |
+
if len(row_order) != len(set(row_order)):
|
84 |
+
msg = "Ambiguous ordering: `row_order` contained duplicates."
|
85 |
+
raise nx.NetworkXError(msg)
|
86 |
+
if column_order is None:
|
87 |
+
column_order = list(set(G) - set(row_order))
|
88 |
+
mlen = len(column_order)
|
89 |
+
if len(column_order) != len(set(column_order)):
|
90 |
+
msg = "Ambiguous ordering: `column_order` contained duplicates."
|
91 |
+
raise nx.NetworkXError(msg)
|
92 |
+
|
93 |
+
row_index = dict(zip(row_order, itertools.count()))
|
94 |
+
col_index = dict(zip(column_order, itertools.count()))
|
95 |
+
|
96 |
+
if G.number_of_edges() == 0:
|
97 |
+
row, col, data = [], [], []
|
98 |
+
else:
|
99 |
+
row, col, data = zip(
|
100 |
+
*(
|
101 |
+
(row_index[u], col_index[v], d.get(weight, 1))
|
102 |
+
for u, v, d in G.edges(row_order, data=True)
|
103 |
+
if u in row_index and v in col_index
|
104 |
+
)
|
105 |
+
)
|
106 |
+
A = sp.sparse.coo_array((data, (row, col)), shape=(nlen, mlen), dtype=dtype)
|
107 |
+
try:
|
108 |
+
return A.asformat(format)
|
109 |
+
except ValueError as err:
|
110 |
+
raise nx.NetworkXError(f"Unknown sparse array format: {format}") from err
|
111 |
+
|
112 |
+
|
113 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
114 |
+
def from_biadjacency_matrix(A, create_using=None, edge_attribute="weight"):
|
115 |
+
r"""Creates a new bipartite graph from a biadjacency matrix given as a
|
116 |
+
SciPy sparse array.
|
117 |
+
|
118 |
+
Parameters
|
119 |
+
----------
|
120 |
+
A: scipy sparse array
|
121 |
+
A biadjacency matrix representation of a graph
|
122 |
+
|
123 |
+
create_using: NetworkX graph
|
124 |
+
Use specified graph for result. The default is Graph()
|
125 |
+
|
126 |
+
edge_attribute: string
|
127 |
+
Name of edge attribute to store matrix numeric value. The data will
|
128 |
+
have the same type as the matrix entry (int, float, (real,imag)).
|
129 |
+
|
130 |
+
Notes
|
131 |
+
-----
|
132 |
+
The nodes are labeled with the attribute `bipartite` set to an integer
|
133 |
+
0 or 1 representing membership in part 0 or part 1 of the bipartite graph.
|
134 |
+
|
135 |
+
If `create_using` is an instance of :class:`networkx.MultiGraph` or
|
136 |
+
:class:`networkx.MultiDiGraph` and the entries of `A` are of
|
137 |
+
type :class:`int`, then this function returns a multigraph (of the same
|
138 |
+
type as `create_using`) with parallel edges. In this case, `edge_attribute`
|
139 |
+
will be ignored.
|
140 |
+
|
141 |
+
See Also
|
142 |
+
--------
|
143 |
+
biadjacency_matrix
|
144 |
+
from_numpy_array
|
145 |
+
|
146 |
+
References
|
147 |
+
----------
|
148 |
+
[1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
|
149 |
+
"""
|
150 |
+
G = nx.empty_graph(0, create_using)
|
151 |
+
n, m = A.shape
|
152 |
+
# Make sure we get even the isolated nodes of the graph.
|
153 |
+
G.add_nodes_from(range(n), bipartite=0)
|
154 |
+
G.add_nodes_from(range(n, n + m), bipartite=1)
|
155 |
+
# Create an iterable over (u, v, w) triples and for each triple, add an
|
156 |
+
# edge from u to v with weight w.
|
157 |
+
triples = ((u, n + v, d) for (u, v, d) in _generate_weighted_edges(A))
|
158 |
+
# If the entries in the adjacency matrix are integers and the graph is a
|
159 |
+
# multigraph, then create parallel edges, each with weight 1, for each
|
160 |
+
# entry in the adjacency matrix. Otherwise, create one edge for each
|
161 |
+
# positive entry in the adjacency matrix and set the weight of that edge to
|
162 |
+
# be the entry in the matrix.
|
163 |
+
if A.dtype.kind in ("i", "u") and G.is_multigraph():
|
164 |
+
chain = itertools.chain.from_iterable
|
165 |
+
triples = chain(((u, v, 1) for d in range(w)) for (u, v, w) in triples)
|
166 |
+
G.add_weighted_edges_from(triples, weight=edge_attribute)
|
167 |
+
return G
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/projection.py
ADDED
@@ -0,0 +1,521 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""One-mode (unipartite) projections of bipartite graphs."""
|
2 |
+
import networkx as nx
|
3 |
+
from networkx.exception import NetworkXAlgorithmError
|
4 |
+
from networkx.utils import not_implemented_for
|
5 |
+
|
6 |
+
__all__ = [
|
7 |
+
"projected_graph",
|
8 |
+
"weighted_projected_graph",
|
9 |
+
"collaboration_weighted_projected_graph",
|
10 |
+
"overlap_weighted_projected_graph",
|
11 |
+
"generic_weighted_projected_graph",
|
12 |
+
]
|
13 |
+
|
14 |
+
|
15 |
+
@nx._dispatchable(
|
16 |
+
graphs="B", preserve_node_attrs=True, preserve_graph_attrs=True, returns_graph=True
|
17 |
+
)
|
18 |
+
def projected_graph(B, nodes, multigraph=False):
|
19 |
+
r"""Returns the projection of B onto one of its node sets.
|
20 |
+
|
21 |
+
Returns the graph G that is the projection of the bipartite graph B
|
22 |
+
onto the specified nodes. They retain their attributes and are connected
|
23 |
+
in G if they have a common neighbor in B.
|
24 |
+
|
25 |
+
Parameters
|
26 |
+
----------
|
27 |
+
B : NetworkX graph
|
28 |
+
The input graph should be bipartite.
|
29 |
+
|
30 |
+
nodes : list or iterable
|
31 |
+
Nodes to project onto (the "bottom" nodes).
|
32 |
+
|
33 |
+
multigraph: bool (default=False)
|
34 |
+
If True return a multigraph where the multiple edges represent multiple
|
35 |
+
shared neighbors. They edge key in the multigraph is assigned to the
|
36 |
+
label of the neighbor.
|
37 |
+
|
38 |
+
Returns
|
39 |
+
-------
|
40 |
+
Graph : NetworkX graph or multigraph
|
41 |
+
A graph that is the projection onto the given nodes.
|
42 |
+
|
43 |
+
Examples
|
44 |
+
--------
|
45 |
+
>>> from networkx.algorithms import bipartite
|
46 |
+
>>> B = nx.path_graph(4)
|
47 |
+
>>> G = bipartite.projected_graph(B, [1, 3])
|
48 |
+
>>> list(G)
|
49 |
+
[1, 3]
|
50 |
+
>>> list(G.edges())
|
51 |
+
[(1, 3)]
|
52 |
+
|
53 |
+
If nodes `a`, and `b` are connected through both nodes 1 and 2 then
|
54 |
+
building a multigraph results in two edges in the projection onto
|
55 |
+
[`a`, `b`]:
|
56 |
+
|
57 |
+
>>> B = nx.Graph()
|
58 |
+
>>> B.add_edges_from([("a", 1), ("b", 1), ("a", 2), ("b", 2)])
|
59 |
+
>>> G = bipartite.projected_graph(B, ["a", "b"], multigraph=True)
|
60 |
+
>>> print([sorted((u, v)) for u, v in G.edges()])
|
61 |
+
[['a', 'b'], ['a', 'b']]
|
62 |
+
|
63 |
+
Notes
|
64 |
+
-----
|
65 |
+
No attempt is made to verify that the input graph B is bipartite.
|
66 |
+
Returns a simple graph that is the projection of the bipartite graph B
|
67 |
+
onto the set of nodes given in list nodes. If multigraph=True then
|
68 |
+
a multigraph is returned with an edge for every shared neighbor.
|
69 |
+
|
70 |
+
Directed graphs are allowed as input. The output will also then
|
71 |
+
be a directed graph with edges if there is a directed path between
|
72 |
+
the nodes.
|
73 |
+
|
74 |
+
The graph and node properties are (shallow) copied to the projected graph.
|
75 |
+
|
76 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
77 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
78 |
+
|
79 |
+
See Also
|
80 |
+
--------
|
81 |
+
is_bipartite,
|
82 |
+
is_bipartite_node_set,
|
83 |
+
sets,
|
84 |
+
weighted_projected_graph,
|
85 |
+
collaboration_weighted_projected_graph,
|
86 |
+
overlap_weighted_projected_graph,
|
87 |
+
generic_weighted_projected_graph
|
88 |
+
"""
|
89 |
+
if B.is_multigraph():
|
90 |
+
raise nx.NetworkXError("not defined for multigraphs")
|
91 |
+
if B.is_directed():
|
92 |
+
directed = True
|
93 |
+
if multigraph:
|
94 |
+
G = nx.MultiDiGraph()
|
95 |
+
else:
|
96 |
+
G = nx.DiGraph()
|
97 |
+
else:
|
98 |
+
directed = False
|
99 |
+
if multigraph:
|
100 |
+
G = nx.MultiGraph()
|
101 |
+
else:
|
102 |
+
G = nx.Graph()
|
103 |
+
G.graph.update(B.graph)
|
104 |
+
G.add_nodes_from((n, B.nodes[n]) for n in nodes)
|
105 |
+
for u in nodes:
|
106 |
+
nbrs2 = {v for nbr in B[u] for v in B[nbr] if v != u}
|
107 |
+
if multigraph:
|
108 |
+
for n in nbrs2:
|
109 |
+
if directed:
|
110 |
+
links = set(B[u]) & set(B.pred[n])
|
111 |
+
else:
|
112 |
+
links = set(B[u]) & set(B[n])
|
113 |
+
for l in links:
|
114 |
+
if not G.has_edge(u, n, l):
|
115 |
+
G.add_edge(u, n, key=l)
|
116 |
+
else:
|
117 |
+
G.add_edges_from((u, n) for n in nbrs2)
|
118 |
+
return G
|
119 |
+
|
120 |
+
|
121 |
+
@not_implemented_for("multigraph")
|
122 |
+
@nx._dispatchable(graphs="B", returns_graph=True)
|
123 |
+
def weighted_projected_graph(B, nodes, ratio=False):
|
124 |
+
r"""Returns a weighted projection of B onto one of its node sets.
|
125 |
+
|
126 |
+
The weighted projected graph is the projection of the bipartite
|
127 |
+
network B onto the specified nodes with weights representing the
|
128 |
+
number of shared neighbors or the ratio between actual shared
|
129 |
+
neighbors and possible shared neighbors if ``ratio is True`` [1]_.
|
130 |
+
The nodes retain their attributes and are connected in the resulting
|
131 |
+
graph if they have an edge to a common node in the original graph.
|
132 |
+
|
133 |
+
Parameters
|
134 |
+
----------
|
135 |
+
B : NetworkX graph
|
136 |
+
The input graph should be bipartite.
|
137 |
+
|
138 |
+
nodes : list or iterable
|
139 |
+
Distinct nodes to project onto (the "bottom" nodes).
|
140 |
+
|
141 |
+
ratio: Bool (default=False)
|
142 |
+
If True, edge weight is the ratio between actual shared neighbors
|
143 |
+
and maximum possible shared neighbors (i.e., the size of the other
|
144 |
+
node set). If False, edges weight is the number of shared neighbors.
|
145 |
+
|
146 |
+
Returns
|
147 |
+
-------
|
148 |
+
Graph : NetworkX graph
|
149 |
+
A graph that is the projection onto the given nodes.
|
150 |
+
|
151 |
+
Examples
|
152 |
+
--------
|
153 |
+
>>> from networkx.algorithms import bipartite
|
154 |
+
>>> B = nx.path_graph(4)
|
155 |
+
>>> G = bipartite.weighted_projected_graph(B, [1, 3])
|
156 |
+
>>> list(G)
|
157 |
+
[1, 3]
|
158 |
+
>>> list(G.edges(data=True))
|
159 |
+
[(1, 3, {'weight': 1})]
|
160 |
+
>>> G = bipartite.weighted_projected_graph(B, [1, 3], ratio=True)
|
161 |
+
>>> list(G.edges(data=True))
|
162 |
+
[(1, 3, {'weight': 0.5})]
|
163 |
+
|
164 |
+
Notes
|
165 |
+
-----
|
166 |
+
No attempt is made to verify that the input graph B is bipartite, or that
|
167 |
+
the input nodes are distinct. However, if the length of the input nodes is
|
168 |
+
greater than or equal to the nodes in the graph B, an exception is raised.
|
169 |
+
If the nodes are not distinct but don't raise this error, the output weights
|
170 |
+
will be incorrect.
|
171 |
+
The graph and node properties are (shallow) copied to the projected graph.
|
172 |
+
|
173 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
174 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
175 |
+
|
176 |
+
See Also
|
177 |
+
--------
|
178 |
+
is_bipartite,
|
179 |
+
is_bipartite_node_set,
|
180 |
+
sets,
|
181 |
+
collaboration_weighted_projected_graph,
|
182 |
+
overlap_weighted_projected_graph,
|
183 |
+
generic_weighted_projected_graph
|
184 |
+
projected_graph
|
185 |
+
|
186 |
+
References
|
187 |
+
----------
|
188 |
+
.. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
|
189 |
+
Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
|
190 |
+
of Social Network Analysis. Sage Publications.
|
191 |
+
"""
|
192 |
+
if B.is_directed():
|
193 |
+
pred = B.pred
|
194 |
+
G = nx.DiGraph()
|
195 |
+
else:
|
196 |
+
pred = B.adj
|
197 |
+
G = nx.Graph()
|
198 |
+
G.graph.update(B.graph)
|
199 |
+
G.add_nodes_from((n, B.nodes[n]) for n in nodes)
|
200 |
+
n_top = len(B) - len(nodes)
|
201 |
+
|
202 |
+
if n_top < 1:
|
203 |
+
raise NetworkXAlgorithmError(
|
204 |
+
f"the size of the nodes to project onto ({len(nodes)}) is >= the graph size ({len(B)}).\n"
|
205 |
+
"They are either not a valid bipartite partition or contain duplicates"
|
206 |
+
)
|
207 |
+
|
208 |
+
for u in nodes:
|
209 |
+
unbrs = set(B[u])
|
210 |
+
nbrs2 = {n for nbr in unbrs for n in B[nbr]} - {u}
|
211 |
+
for v in nbrs2:
|
212 |
+
vnbrs = set(pred[v])
|
213 |
+
common = unbrs & vnbrs
|
214 |
+
if not ratio:
|
215 |
+
weight = len(common)
|
216 |
+
else:
|
217 |
+
weight = len(common) / n_top
|
218 |
+
G.add_edge(u, v, weight=weight)
|
219 |
+
return G
|
220 |
+
|
221 |
+
|
222 |
+
@not_implemented_for("multigraph")
|
223 |
+
@nx._dispatchable(graphs="B", returns_graph=True)
|
224 |
+
def collaboration_weighted_projected_graph(B, nodes):
|
225 |
+
r"""Newman's weighted projection of B onto one of its node sets.
|
226 |
+
|
227 |
+
The collaboration weighted projection is the projection of the
|
228 |
+
bipartite network B onto the specified nodes with weights assigned
|
229 |
+
using Newman's collaboration model [1]_:
|
230 |
+
|
231 |
+
.. math::
|
232 |
+
|
233 |
+
w_{u, v} = \sum_k \frac{\delta_{u}^{k} \delta_{v}^{k}}{d_k - 1}
|
234 |
+
|
235 |
+
where `u` and `v` are nodes from the bottom bipartite node set,
|
236 |
+
and `k` is a node of the top node set.
|
237 |
+
The value `d_k` is the degree of node `k` in the bipartite
|
238 |
+
network and `\delta_{u}^{k}` is 1 if node `u` is
|
239 |
+
linked to node `k` in the original bipartite graph or 0 otherwise.
|
240 |
+
|
241 |
+
The nodes retain their attributes and are connected in the resulting
|
242 |
+
graph if have an edge to a common node in the original bipartite
|
243 |
+
graph.
|
244 |
+
|
245 |
+
Parameters
|
246 |
+
----------
|
247 |
+
B : NetworkX graph
|
248 |
+
The input graph should be bipartite.
|
249 |
+
|
250 |
+
nodes : list or iterable
|
251 |
+
Nodes to project onto (the "bottom" nodes).
|
252 |
+
|
253 |
+
Returns
|
254 |
+
-------
|
255 |
+
Graph : NetworkX graph
|
256 |
+
A graph that is the projection onto the given nodes.
|
257 |
+
|
258 |
+
Examples
|
259 |
+
--------
|
260 |
+
>>> from networkx.algorithms import bipartite
|
261 |
+
>>> B = nx.path_graph(5)
|
262 |
+
>>> B.add_edge(1, 5)
|
263 |
+
>>> G = bipartite.collaboration_weighted_projected_graph(B, [0, 2, 4, 5])
|
264 |
+
>>> list(G)
|
265 |
+
[0, 2, 4, 5]
|
266 |
+
>>> for edge in sorted(G.edges(data=True)):
|
267 |
+
... print(edge)
|
268 |
+
(0, 2, {'weight': 0.5})
|
269 |
+
(0, 5, {'weight': 0.5})
|
270 |
+
(2, 4, {'weight': 1.0})
|
271 |
+
(2, 5, {'weight': 0.5})
|
272 |
+
|
273 |
+
Notes
|
274 |
+
-----
|
275 |
+
No attempt is made to verify that the input graph B is bipartite.
|
276 |
+
The graph and node properties are (shallow) copied to the projected graph.
|
277 |
+
|
278 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
279 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
280 |
+
|
281 |
+
See Also
|
282 |
+
--------
|
283 |
+
is_bipartite,
|
284 |
+
is_bipartite_node_set,
|
285 |
+
sets,
|
286 |
+
weighted_projected_graph,
|
287 |
+
overlap_weighted_projected_graph,
|
288 |
+
generic_weighted_projected_graph,
|
289 |
+
projected_graph
|
290 |
+
|
291 |
+
References
|
292 |
+
----------
|
293 |
+
.. [1] Scientific collaboration networks: II.
|
294 |
+
Shortest paths, weighted networks, and centrality,
|
295 |
+
M. E. J. Newman, Phys. Rev. E 64, 016132 (2001).
|
296 |
+
"""
|
297 |
+
if B.is_directed():
|
298 |
+
pred = B.pred
|
299 |
+
G = nx.DiGraph()
|
300 |
+
else:
|
301 |
+
pred = B.adj
|
302 |
+
G = nx.Graph()
|
303 |
+
G.graph.update(B.graph)
|
304 |
+
G.add_nodes_from((n, B.nodes[n]) for n in nodes)
|
305 |
+
for u in nodes:
|
306 |
+
unbrs = set(B[u])
|
307 |
+
nbrs2 = {n for nbr in unbrs for n in B[nbr] if n != u}
|
308 |
+
for v in nbrs2:
|
309 |
+
vnbrs = set(pred[v])
|
310 |
+
common_degree = (len(B[n]) for n in unbrs & vnbrs)
|
311 |
+
weight = sum(1.0 / (deg - 1) for deg in common_degree if deg > 1)
|
312 |
+
G.add_edge(u, v, weight=weight)
|
313 |
+
return G
|
314 |
+
|
315 |
+
|
316 |
+
@not_implemented_for("multigraph")
|
317 |
+
@nx._dispatchable(graphs="B", returns_graph=True)
|
318 |
+
def overlap_weighted_projected_graph(B, nodes, jaccard=True):
|
319 |
+
r"""Overlap weighted projection of B onto one of its node sets.
|
320 |
+
|
321 |
+
The overlap weighted projection is the projection of the bipartite
|
322 |
+
network B onto the specified nodes with weights representing
|
323 |
+
the Jaccard index between the neighborhoods of the two nodes in the
|
324 |
+
original bipartite network [1]_:
|
325 |
+
|
326 |
+
.. math::
|
327 |
+
|
328 |
+
w_{v, u} = \frac{|N(u) \cap N(v)|}{|N(u) \cup N(v)|}
|
329 |
+
|
330 |
+
or if the parameter 'jaccard' is False, the fraction of common
|
331 |
+
neighbors by minimum of both nodes degree in the original
|
332 |
+
bipartite graph [1]_:
|
333 |
+
|
334 |
+
.. math::
|
335 |
+
|
336 |
+
w_{v, u} = \frac{|N(u) \cap N(v)|}{min(|N(u)|, |N(v)|)}
|
337 |
+
|
338 |
+
The nodes retain their attributes and are connected in the resulting
|
339 |
+
graph if have an edge to a common node in the original bipartite graph.
|
340 |
+
|
341 |
+
Parameters
|
342 |
+
----------
|
343 |
+
B : NetworkX graph
|
344 |
+
The input graph should be bipartite.
|
345 |
+
|
346 |
+
nodes : list or iterable
|
347 |
+
Nodes to project onto (the "bottom" nodes).
|
348 |
+
|
349 |
+
jaccard: Bool (default=True)
|
350 |
+
|
351 |
+
Returns
|
352 |
+
-------
|
353 |
+
Graph : NetworkX graph
|
354 |
+
A graph that is the projection onto the given nodes.
|
355 |
+
|
356 |
+
Examples
|
357 |
+
--------
|
358 |
+
>>> from networkx.algorithms import bipartite
|
359 |
+
>>> B = nx.path_graph(5)
|
360 |
+
>>> nodes = [0, 2, 4]
|
361 |
+
>>> G = bipartite.overlap_weighted_projected_graph(B, nodes)
|
362 |
+
>>> list(G)
|
363 |
+
[0, 2, 4]
|
364 |
+
>>> list(G.edges(data=True))
|
365 |
+
[(0, 2, {'weight': 0.5}), (2, 4, {'weight': 0.5})]
|
366 |
+
>>> G = bipartite.overlap_weighted_projected_graph(B, nodes, jaccard=False)
|
367 |
+
>>> list(G.edges(data=True))
|
368 |
+
[(0, 2, {'weight': 1.0}), (2, 4, {'weight': 1.0})]
|
369 |
+
|
370 |
+
Notes
|
371 |
+
-----
|
372 |
+
No attempt is made to verify that the input graph B is bipartite.
|
373 |
+
The graph and node properties are (shallow) copied to the projected graph.
|
374 |
+
|
375 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
376 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
377 |
+
|
378 |
+
See Also
|
379 |
+
--------
|
380 |
+
is_bipartite,
|
381 |
+
is_bipartite_node_set,
|
382 |
+
sets,
|
383 |
+
weighted_projected_graph,
|
384 |
+
collaboration_weighted_projected_graph,
|
385 |
+
generic_weighted_projected_graph,
|
386 |
+
projected_graph
|
387 |
+
|
388 |
+
References
|
389 |
+
----------
|
390 |
+
.. [1] Borgatti, S.P. and Halgin, D. In press. Analyzing Affiliation
|
391 |
+
Networks. In Carrington, P. and Scott, J. (eds) The Sage Handbook
|
392 |
+
of Social Network Analysis. Sage Publications.
|
393 |
+
|
394 |
+
"""
|
395 |
+
if B.is_directed():
|
396 |
+
pred = B.pred
|
397 |
+
G = nx.DiGraph()
|
398 |
+
else:
|
399 |
+
pred = B.adj
|
400 |
+
G = nx.Graph()
|
401 |
+
G.graph.update(B.graph)
|
402 |
+
G.add_nodes_from((n, B.nodes[n]) for n in nodes)
|
403 |
+
for u in nodes:
|
404 |
+
unbrs = set(B[u])
|
405 |
+
nbrs2 = {n for nbr in unbrs for n in B[nbr]} - {u}
|
406 |
+
for v in nbrs2:
|
407 |
+
vnbrs = set(pred[v])
|
408 |
+
if jaccard:
|
409 |
+
wt = len(unbrs & vnbrs) / len(unbrs | vnbrs)
|
410 |
+
else:
|
411 |
+
wt = len(unbrs & vnbrs) / min(len(unbrs), len(vnbrs))
|
412 |
+
G.add_edge(u, v, weight=wt)
|
413 |
+
return G
|
414 |
+
|
415 |
+
|
416 |
+
@not_implemented_for("multigraph")
|
417 |
+
@nx._dispatchable(graphs="B", preserve_all_attrs=True, returns_graph=True)
|
418 |
+
def generic_weighted_projected_graph(B, nodes, weight_function=None):
|
419 |
+
r"""Weighted projection of B with a user-specified weight function.
|
420 |
+
|
421 |
+
The bipartite network B is projected on to the specified nodes
|
422 |
+
with weights computed by a user-specified function. This function
|
423 |
+
must accept as a parameter the neighborhood sets of two nodes and
|
424 |
+
return an integer or a float.
|
425 |
+
|
426 |
+
The nodes retain their attributes and are connected in the resulting graph
|
427 |
+
if they have an edge to a common node in the original graph.
|
428 |
+
|
429 |
+
Parameters
|
430 |
+
----------
|
431 |
+
B : NetworkX graph
|
432 |
+
The input graph should be bipartite.
|
433 |
+
|
434 |
+
nodes : list or iterable
|
435 |
+
Nodes to project onto (the "bottom" nodes).
|
436 |
+
|
437 |
+
weight_function : function
|
438 |
+
This function must accept as parameters the same input graph
|
439 |
+
that this function, and two nodes; and return an integer or a float.
|
440 |
+
The default function computes the number of shared neighbors.
|
441 |
+
|
442 |
+
Returns
|
443 |
+
-------
|
444 |
+
Graph : NetworkX graph
|
445 |
+
A graph that is the projection onto the given nodes.
|
446 |
+
|
447 |
+
Examples
|
448 |
+
--------
|
449 |
+
>>> from networkx.algorithms import bipartite
|
450 |
+
>>> # Define some custom weight functions
|
451 |
+
>>> def jaccard(G, u, v):
|
452 |
+
... unbrs = set(G[u])
|
453 |
+
... vnbrs = set(G[v])
|
454 |
+
... return float(len(unbrs & vnbrs)) / len(unbrs | vnbrs)
|
455 |
+
>>> def my_weight(G, u, v, weight="weight"):
|
456 |
+
... w = 0
|
457 |
+
... for nbr in set(G[u]) & set(G[v]):
|
458 |
+
... w += G[u][nbr].get(weight, 1) + G[v][nbr].get(weight, 1)
|
459 |
+
... return w
|
460 |
+
>>> # A complete bipartite graph with 4 nodes and 4 edges
|
461 |
+
>>> B = nx.complete_bipartite_graph(2, 2)
|
462 |
+
>>> # Add some arbitrary weight to the edges
|
463 |
+
>>> for i, (u, v) in enumerate(B.edges()):
|
464 |
+
... B.edges[u, v]["weight"] = i + 1
|
465 |
+
>>> for edge in B.edges(data=True):
|
466 |
+
... print(edge)
|
467 |
+
(0, 2, {'weight': 1})
|
468 |
+
(0, 3, {'weight': 2})
|
469 |
+
(1, 2, {'weight': 3})
|
470 |
+
(1, 3, {'weight': 4})
|
471 |
+
>>> # By default, the weight is the number of shared neighbors
|
472 |
+
>>> G = bipartite.generic_weighted_projected_graph(B, [0, 1])
|
473 |
+
>>> print(list(G.edges(data=True)))
|
474 |
+
[(0, 1, {'weight': 2})]
|
475 |
+
>>> # To specify a custom weight function use the weight_function parameter
|
476 |
+
>>> G = bipartite.generic_weighted_projected_graph(B, [0, 1], weight_function=jaccard)
|
477 |
+
>>> print(list(G.edges(data=True)))
|
478 |
+
[(0, 1, {'weight': 1.0})]
|
479 |
+
>>> G = bipartite.generic_weighted_projected_graph(B, [0, 1], weight_function=my_weight)
|
480 |
+
>>> print(list(G.edges(data=True)))
|
481 |
+
[(0, 1, {'weight': 10})]
|
482 |
+
|
483 |
+
Notes
|
484 |
+
-----
|
485 |
+
No attempt is made to verify that the input graph B is bipartite.
|
486 |
+
The graph and node properties are (shallow) copied to the projected graph.
|
487 |
+
|
488 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
489 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
490 |
+
|
491 |
+
See Also
|
492 |
+
--------
|
493 |
+
is_bipartite,
|
494 |
+
is_bipartite_node_set,
|
495 |
+
sets,
|
496 |
+
weighted_projected_graph,
|
497 |
+
collaboration_weighted_projected_graph,
|
498 |
+
overlap_weighted_projected_graph,
|
499 |
+
projected_graph
|
500 |
+
|
501 |
+
"""
|
502 |
+
if B.is_directed():
|
503 |
+
pred = B.pred
|
504 |
+
G = nx.DiGraph()
|
505 |
+
else:
|
506 |
+
pred = B.adj
|
507 |
+
G = nx.Graph()
|
508 |
+
if weight_function is None:
|
509 |
+
|
510 |
+
def weight_function(G, u, v):
|
511 |
+
# Notice that we use set(pred[v]) for handling the directed case.
|
512 |
+
return len(set(G[u]) & set(pred[v]))
|
513 |
+
|
514 |
+
G.graph.update(B.graph)
|
515 |
+
G.add_nodes_from((n, B.nodes[n]) for n in nodes)
|
516 |
+
for u in nodes:
|
517 |
+
nbrs2 = {n for nbr in set(B[u]) for n in B[nbr]} - {u}
|
518 |
+
for v in nbrs2:
|
519 |
+
weight = weight_function(B, u, v)
|
520 |
+
G.add_edge(u, v, weight=weight)
|
521 |
+
return G
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/redundancy.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Node redundancy for bipartite graphs."""
|
2 |
+
from itertools import combinations
|
3 |
+
|
4 |
+
import networkx as nx
|
5 |
+
from networkx import NetworkXError
|
6 |
+
|
7 |
+
__all__ = ["node_redundancy"]
|
8 |
+
|
9 |
+
|
10 |
+
@nx._dispatchable
|
11 |
+
def node_redundancy(G, nodes=None):
|
12 |
+
r"""Computes the node redundancy coefficients for the nodes in the bipartite
|
13 |
+
graph `G`.
|
14 |
+
|
15 |
+
The redundancy coefficient of a node `v` is the fraction of pairs of
|
16 |
+
neighbors of `v` that are both linked to other nodes. In a one-mode
|
17 |
+
projection these nodes would be linked together even if `v` were
|
18 |
+
not there.
|
19 |
+
|
20 |
+
More formally, for any vertex `v`, the *redundancy coefficient of `v`* is
|
21 |
+
defined by
|
22 |
+
|
23 |
+
.. math::
|
24 |
+
|
25 |
+
rc(v) = \frac{|\{\{u, w\} \subseteq N(v),
|
26 |
+
\: \exists v' \neq v,\: (v',u) \in E\:
|
27 |
+
\mathrm{and}\: (v',w) \in E\}|}{ \frac{|N(v)|(|N(v)|-1)}{2}},
|
28 |
+
|
29 |
+
where `N(v)` is the set of neighbors of `v` in `G`.
|
30 |
+
|
31 |
+
Parameters
|
32 |
+
----------
|
33 |
+
G : graph
|
34 |
+
A bipartite graph
|
35 |
+
|
36 |
+
nodes : list or iterable (optional)
|
37 |
+
Compute redundancy for these nodes. The default is all nodes in G.
|
38 |
+
|
39 |
+
Returns
|
40 |
+
-------
|
41 |
+
redundancy : dictionary
|
42 |
+
A dictionary keyed by node with the node redundancy value.
|
43 |
+
|
44 |
+
Examples
|
45 |
+
--------
|
46 |
+
Compute the redundancy coefficient of each node in a graph::
|
47 |
+
|
48 |
+
>>> from networkx.algorithms import bipartite
|
49 |
+
>>> G = nx.cycle_graph(4)
|
50 |
+
>>> rc = bipartite.node_redundancy(G)
|
51 |
+
>>> rc[0]
|
52 |
+
1.0
|
53 |
+
|
54 |
+
Compute the average redundancy for the graph::
|
55 |
+
|
56 |
+
>>> from networkx.algorithms import bipartite
|
57 |
+
>>> G = nx.cycle_graph(4)
|
58 |
+
>>> rc = bipartite.node_redundancy(G)
|
59 |
+
>>> sum(rc.values()) / len(G)
|
60 |
+
1.0
|
61 |
+
|
62 |
+
Compute the average redundancy for a set of nodes::
|
63 |
+
|
64 |
+
>>> from networkx.algorithms import bipartite
|
65 |
+
>>> G = nx.cycle_graph(4)
|
66 |
+
>>> rc = bipartite.node_redundancy(G)
|
67 |
+
>>> nodes = [0, 2]
|
68 |
+
>>> sum(rc[n] for n in nodes) / len(nodes)
|
69 |
+
1.0
|
70 |
+
|
71 |
+
Raises
|
72 |
+
------
|
73 |
+
NetworkXError
|
74 |
+
If any of the nodes in the graph (or in `nodes`, if specified) has
|
75 |
+
(out-)degree less than two (which would result in division by zero,
|
76 |
+
according to the definition of the redundancy coefficient).
|
77 |
+
|
78 |
+
References
|
79 |
+
----------
|
80 |
+
.. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
|
81 |
+
Basic notions for the analysis of large two-mode networks.
|
82 |
+
Social Networks 30(1), 31--48.
|
83 |
+
|
84 |
+
"""
|
85 |
+
if nodes is None:
|
86 |
+
nodes = G
|
87 |
+
if any(len(G[v]) < 2 for v in nodes):
|
88 |
+
raise NetworkXError(
|
89 |
+
"Cannot compute redundancy coefficient for a node"
|
90 |
+
" that has fewer than two neighbors."
|
91 |
+
)
|
92 |
+
# TODO This can be trivially parallelized.
|
93 |
+
return {v: _node_redundancy(G, v) for v in nodes}
|
94 |
+
|
95 |
+
|
96 |
+
def _node_redundancy(G, v):
|
97 |
+
"""Returns the redundancy of the node `v` in the bipartite graph `G`.
|
98 |
+
|
99 |
+
If `G` is a graph with `n` nodes, the redundancy of a node is the ratio
|
100 |
+
of the "overlap" of `v` to the maximum possible overlap of `v`
|
101 |
+
according to its degree. The overlap of `v` is the number of pairs of
|
102 |
+
neighbors that have mutual neighbors themselves, other than `v`.
|
103 |
+
|
104 |
+
`v` must have at least two neighbors in `G`.
|
105 |
+
|
106 |
+
"""
|
107 |
+
n = len(G[v])
|
108 |
+
overlap = sum(
|
109 |
+
1 for (u, w) in combinations(G[v], 2) if (set(G[u]) & set(G[w])) - {v}
|
110 |
+
)
|
111 |
+
return (2 * overlap) / (n * (n - 1))
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/spectral.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Spectral bipartivity measure.
|
3 |
+
"""
|
4 |
+
import networkx as nx
|
5 |
+
|
6 |
+
__all__ = ["spectral_bipartivity"]
|
7 |
+
|
8 |
+
|
9 |
+
@nx._dispatchable(edge_attrs="weight")
|
10 |
+
def spectral_bipartivity(G, nodes=None, weight="weight"):
|
11 |
+
"""Returns the spectral bipartivity.
|
12 |
+
|
13 |
+
Parameters
|
14 |
+
----------
|
15 |
+
G : NetworkX graph
|
16 |
+
|
17 |
+
nodes : list or container optional(default is all nodes)
|
18 |
+
Nodes to return value of spectral bipartivity contribution.
|
19 |
+
|
20 |
+
weight : string or None optional (default = 'weight')
|
21 |
+
Edge data key to use for edge weights. If None, weights set to 1.
|
22 |
+
|
23 |
+
Returns
|
24 |
+
-------
|
25 |
+
sb : float or dict
|
26 |
+
A single number if the keyword nodes is not specified, or
|
27 |
+
a dictionary keyed by node with the spectral bipartivity contribution
|
28 |
+
of that node as the value.
|
29 |
+
|
30 |
+
Examples
|
31 |
+
--------
|
32 |
+
>>> from networkx.algorithms import bipartite
|
33 |
+
>>> G = nx.path_graph(4)
|
34 |
+
>>> bipartite.spectral_bipartivity(G)
|
35 |
+
1.0
|
36 |
+
|
37 |
+
Notes
|
38 |
+
-----
|
39 |
+
This implementation uses Numpy (dense) matrices which are not efficient
|
40 |
+
for storing large sparse graphs.
|
41 |
+
|
42 |
+
See Also
|
43 |
+
--------
|
44 |
+
color
|
45 |
+
|
46 |
+
References
|
47 |
+
----------
|
48 |
+
.. [1] E. Estrada and J. A. Rodríguez-Velázquez, "Spectral measures of
|
49 |
+
bipartivity in complex networks", PhysRev E 72, 046105 (2005)
|
50 |
+
"""
|
51 |
+
import scipy as sp
|
52 |
+
|
53 |
+
nodelist = list(G) # ordering of nodes in matrix
|
54 |
+
A = nx.to_numpy_array(G, nodelist, weight=weight)
|
55 |
+
expA = sp.linalg.expm(A)
|
56 |
+
expmA = sp.linalg.expm(-A)
|
57 |
+
coshA = 0.5 * (expA + expmA)
|
58 |
+
if nodes is None:
|
59 |
+
# return single number for entire graph
|
60 |
+
return float(coshA.diagonal().sum() / expA.diagonal().sum())
|
61 |
+
else:
|
62 |
+
# contribution for individual nodes
|
63 |
+
index = dict(zip(nodelist, range(len(nodelist))))
|
64 |
+
sb = {}
|
65 |
+
for n in nodes:
|
66 |
+
i = index[n]
|
67 |
+
sb[n] = coshA.item(i, i) / expA.item(i, i)
|
68 |
+
return sb
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (203 Bytes). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_basic.cpython-310.pyc
ADDED
Binary file (6.07 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_centrality.cpython-310.pyc
ADDED
Binary file (5.34 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_cluster.cpython-310.pyc
ADDED
Binary file (3.36 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_covering.cpython-310.pyc
ADDED
Binary file (1.81 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_edgelist.cpython-310.pyc
ADDED
Binary file (7.36 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_extendability.cpython-310.pyc
ADDED
Binary file (5.24 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_generators.cpython-310.pyc
ADDED
Binary file (9.4 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_matching.cpython-310.pyc
ADDED
Binary file (12.4 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_matrix.cpython-310.pyc
ADDED
Binary file (4.71 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_project.cpython-310.pyc
ADDED
Binary file (11.7 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_redundancy.cpython-310.pyc
ADDED
Binary file (1.43 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/__pycache__/test_spectral_bipartivity.cpython-310.pyc
ADDED
Binary file (2.2 kB). View file
|
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/test_basic.py
ADDED
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.algorithms import bipartite
|
5 |
+
|
6 |
+
|
7 |
+
class TestBipartiteBasic:
|
8 |
+
def test_is_bipartite(self):
|
9 |
+
assert bipartite.is_bipartite(nx.path_graph(4))
|
10 |
+
assert bipartite.is_bipartite(nx.DiGraph([(1, 0)]))
|
11 |
+
assert not bipartite.is_bipartite(nx.complete_graph(3))
|
12 |
+
|
13 |
+
def test_bipartite_color(self):
|
14 |
+
G = nx.path_graph(4)
|
15 |
+
c = bipartite.color(G)
|
16 |
+
assert c == {0: 1, 1: 0, 2: 1, 3: 0}
|
17 |
+
|
18 |
+
def test_not_bipartite_color(self):
|
19 |
+
with pytest.raises(nx.NetworkXError):
|
20 |
+
c = bipartite.color(nx.complete_graph(4))
|
21 |
+
|
22 |
+
def test_bipartite_directed(self):
|
23 |
+
G = bipartite.random_graph(10, 10, 0.1, directed=True)
|
24 |
+
assert bipartite.is_bipartite(G)
|
25 |
+
|
26 |
+
def test_bipartite_sets(self):
|
27 |
+
G = nx.path_graph(4)
|
28 |
+
X, Y = bipartite.sets(G)
|
29 |
+
assert X == {0, 2}
|
30 |
+
assert Y == {1, 3}
|
31 |
+
|
32 |
+
def test_bipartite_sets_directed(self):
|
33 |
+
G = nx.path_graph(4)
|
34 |
+
D = G.to_directed()
|
35 |
+
X, Y = bipartite.sets(D)
|
36 |
+
assert X == {0, 2}
|
37 |
+
assert Y == {1, 3}
|
38 |
+
|
39 |
+
def test_bipartite_sets_given_top_nodes(self):
|
40 |
+
G = nx.path_graph(4)
|
41 |
+
top_nodes = [0, 2]
|
42 |
+
X, Y = bipartite.sets(G, top_nodes)
|
43 |
+
assert X == {0, 2}
|
44 |
+
assert Y == {1, 3}
|
45 |
+
|
46 |
+
def test_bipartite_sets_disconnected(self):
|
47 |
+
with pytest.raises(nx.AmbiguousSolution):
|
48 |
+
G = nx.path_graph(4)
|
49 |
+
G.add_edges_from([(5, 6), (6, 7)])
|
50 |
+
X, Y = bipartite.sets(G)
|
51 |
+
|
52 |
+
def test_is_bipartite_node_set(self):
|
53 |
+
G = nx.path_graph(4)
|
54 |
+
|
55 |
+
with pytest.raises(nx.AmbiguousSolution):
|
56 |
+
bipartite.is_bipartite_node_set(G, [1, 1, 2, 3])
|
57 |
+
|
58 |
+
assert bipartite.is_bipartite_node_set(G, [0, 2])
|
59 |
+
assert bipartite.is_bipartite_node_set(G, [1, 3])
|
60 |
+
assert not bipartite.is_bipartite_node_set(G, [1, 2])
|
61 |
+
G.add_edge(10, 20)
|
62 |
+
assert bipartite.is_bipartite_node_set(G, [0, 2, 10])
|
63 |
+
assert bipartite.is_bipartite_node_set(G, [0, 2, 20])
|
64 |
+
assert bipartite.is_bipartite_node_set(G, [1, 3, 10])
|
65 |
+
assert bipartite.is_bipartite_node_set(G, [1, 3, 20])
|
66 |
+
|
67 |
+
def test_bipartite_density(self):
|
68 |
+
G = nx.path_graph(5)
|
69 |
+
X, Y = bipartite.sets(G)
|
70 |
+
density = len(list(G.edges())) / (len(X) * len(Y))
|
71 |
+
assert bipartite.density(G, X) == density
|
72 |
+
D = nx.DiGraph(G.edges())
|
73 |
+
assert bipartite.density(D, X) == density / 2.0
|
74 |
+
assert bipartite.density(nx.Graph(), {}) == 0.0
|
75 |
+
|
76 |
+
def test_bipartite_degrees(self):
|
77 |
+
G = nx.path_graph(5)
|
78 |
+
X = {1, 3}
|
79 |
+
Y = {0, 2, 4}
|
80 |
+
u, d = bipartite.degrees(G, Y)
|
81 |
+
assert dict(u) == {1: 2, 3: 2}
|
82 |
+
assert dict(d) == {0: 1, 2: 2, 4: 1}
|
83 |
+
|
84 |
+
def test_bipartite_weighted_degrees(self):
|
85 |
+
G = nx.path_graph(5)
|
86 |
+
G.add_edge(0, 1, weight=0.1, other=0.2)
|
87 |
+
X = {1, 3}
|
88 |
+
Y = {0, 2, 4}
|
89 |
+
u, d = bipartite.degrees(G, Y, weight="weight")
|
90 |
+
assert dict(u) == {1: 1.1, 3: 2}
|
91 |
+
assert dict(d) == {0: 0.1, 2: 2, 4: 1}
|
92 |
+
u, d = bipartite.degrees(G, Y, weight="other")
|
93 |
+
assert dict(u) == {1: 1.2, 3: 2}
|
94 |
+
assert dict(d) == {0: 0.2, 2: 2, 4: 1}
|
95 |
+
|
96 |
+
def test_biadjacency_matrix_weight(self):
|
97 |
+
pytest.importorskip("scipy")
|
98 |
+
G = nx.path_graph(5)
|
99 |
+
G.add_edge(0, 1, weight=2, other=4)
|
100 |
+
X = [1, 3]
|
101 |
+
Y = [0, 2, 4]
|
102 |
+
M = bipartite.biadjacency_matrix(G, X, weight="weight")
|
103 |
+
assert M[0, 0] == 2
|
104 |
+
M = bipartite.biadjacency_matrix(G, X, weight="other")
|
105 |
+
assert M[0, 0] == 4
|
106 |
+
|
107 |
+
def test_biadjacency_matrix(self):
|
108 |
+
pytest.importorskip("scipy")
|
109 |
+
tops = [2, 5, 10]
|
110 |
+
bots = [5, 10, 15]
|
111 |
+
for i in range(len(tops)):
|
112 |
+
G = bipartite.random_graph(tops[i], bots[i], 0.2)
|
113 |
+
top = [n for n, d in G.nodes(data=True) if d["bipartite"] == 0]
|
114 |
+
M = bipartite.biadjacency_matrix(G, top)
|
115 |
+
assert M.shape[0] == tops[i]
|
116 |
+
assert M.shape[1] == bots[i]
|
117 |
+
|
118 |
+
def test_biadjacency_matrix_order(self):
|
119 |
+
pytest.importorskip("scipy")
|
120 |
+
G = nx.path_graph(5)
|
121 |
+
G.add_edge(0, 1, weight=2)
|
122 |
+
X = [3, 1]
|
123 |
+
Y = [4, 2, 0]
|
124 |
+
M = bipartite.biadjacency_matrix(G, X, Y, weight="weight")
|
125 |
+
assert M[1, 2] == 2
|
venv/lib/python3.10/site-packages/networkx/algorithms/bipartite/tests/test_centrality.py
ADDED
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.algorithms import bipartite
|
5 |
+
|
6 |
+
|
7 |
+
class TestBipartiteCentrality:
|
8 |
+
@classmethod
|
9 |
+
def setup_class(cls):
|
10 |
+
cls.P4 = nx.path_graph(4)
|
11 |
+
cls.K3 = nx.complete_bipartite_graph(3, 3)
|
12 |
+
cls.C4 = nx.cycle_graph(4)
|
13 |
+
cls.davis = nx.davis_southern_women_graph()
|
14 |
+
cls.top_nodes = [
|
15 |
+
n for n, d in cls.davis.nodes(data=True) if d["bipartite"] == 0
|
16 |
+
]
|
17 |
+
|
18 |
+
def test_degree_centrality(self):
|
19 |
+
d = bipartite.degree_centrality(self.P4, [1, 3])
|
20 |
+
answer = {0: 0.5, 1: 1.0, 2: 1.0, 3: 0.5}
|
21 |
+
assert d == answer
|
22 |
+
d = bipartite.degree_centrality(self.K3, [0, 1, 2])
|
23 |
+
answer = {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0, 5: 1.0}
|
24 |
+
assert d == answer
|
25 |
+
d = bipartite.degree_centrality(self.C4, [0, 2])
|
26 |
+
answer = {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0}
|
27 |
+
assert d == answer
|
28 |
+
|
29 |
+
def test_betweenness_centrality(self):
|
30 |
+
c = bipartite.betweenness_centrality(self.P4, [1, 3])
|
31 |
+
answer = {0: 0.0, 1: 1.0, 2: 1.0, 3: 0.0}
|
32 |
+
assert c == answer
|
33 |
+
c = bipartite.betweenness_centrality(self.K3, [0, 1, 2])
|
34 |
+
answer = {0: 0.125, 1: 0.125, 2: 0.125, 3: 0.125, 4: 0.125, 5: 0.125}
|
35 |
+
assert c == answer
|
36 |
+
c = bipartite.betweenness_centrality(self.C4, [0, 2])
|
37 |
+
answer = {0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
|
38 |
+
assert c == answer
|
39 |
+
|
40 |
+
def test_closeness_centrality(self):
|
41 |
+
c = bipartite.closeness_centrality(self.P4, [1, 3])
|
42 |
+
answer = {0: 2.0 / 3, 1: 1.0, 2: 1.0, 3: 2.0 / 3}
|
43 |
+
assert c == answer
|
44 |
+
c = bipartite.closeness_centrality(self.K3, [0, 1, 2])
|
45 |
+
answer = {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0, 5: 1.0}
|
46 |
+
assert c == answer
|
47 |
+
c = bipartite.closeness_centrality(self.C4, [0, 2])
|
48 |
+
answer = {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0}
|
49 |
+
assert c == answer
|
50 |
+
G = nx.Graph()
|
51 |
+
G.add_node(0)
|
52 |
+
G.add_node(1)
|
53 |
+
c = bipartite.closeness_centrality(G, [0])
|
54 |
+
assert c == {0: 0.0, 1: 0.0}
|
55 |
+
c = bipartite.closeness_centrality(G, [1])
|
56 |
+
assert c == {0: 0.0, 1: 0.0}
|
57 |
+
|
58 |
+
def test_bipartite_closeness_centrality_unconnected(self):
|
59 |
+
G = nx.complete_bipartite_graph(3, 3)
|
60 |
+
G.add_edge(6, 7)
|
61 |
+
c = bipartite.closeness_centrality(G, [0, 2, 4, 6], normalized=False)
|
62 |
+
answer = {
|
63 |
+
0: 10.0 / 7,
|
64 |
+
2: 10.0 / 7,
|
65 |
+
4: 10.0 / 7,
|
66 |
+
6: 10.0,
|
67 |
+
1: 10.0 / 7,
|
68 |
+
3: 10.0 / 7,
|
69 |
+
5: 10.0 / 7,
|
70 |
+
7: 10.0,
|
71 |
+
}
|
72 |
+
assert c == answer
|
73 |
+
|
74 |
+
def test_davis_degree_centrality(self):
|
75 |
+
G = self.davis
|
76 |
+
deg = bipartite.degree_centrality(G, self.top_nodes)
|
77 |
+
answer = {
|
78 |
+
"E8": 0.78,
|
79 |
+
"E9": 0.67,
|
80 |
+
"E7": 0.56,
|
81 |
+
"Nora Fayette": 0.57,
|
82 |
+
"Evelyn Jefferson": 0.57,
|
83 |
+
"Theresa Anderson": 0.57,
|
84 |
+
"E6": 0.44,
|
85 |
+
"Sylvia Avondale": 0.50,
|
86 |
+
"Laura Mandeville": 0.50,
|
87 |
+
"Brenda Rogers": 0.50,
|
88 |
+
"Katherina Rogers": 0.43,
|
89 |
+
"E5": 0.44,
|
90 |
+
"Helen Lloyd": 0.36,
|
91 |
+
"E3": 0.33,
|
92 |
+
"Ruth DeSand": 0.29,
|
93 |
+
"Verne Sanderson": 0.29,
|
94 |
+
"E12": 0.33,
|
95 |
+
"Myra Liddel": 0.29,
|
96 |
+
"E11": 0.22,
|
97 |
+
"Eleanor Nye": 0.29,
|
98 |
+
"Frances Anderson": 0.29,
|
99 |
+
"Pearl Oglethorpe": 0.21,
|
100 |
+
"E4": 0.22,
|
101 |
+
"Charlotte McDowd": 0.29,
|
102 |
+
"E10": 0.28,
|
103 |
+
"Olivia Carleton": 0.14,
|
104 |
+
"Flora Price": 0.14,
|
105 |
+
"E2": 0.17,
|
106 |
+
"E1": 0.17,
|
107 |
+
"Dorothy Murchison": 0.14,
|
108 |
+
"E13": 0.17,
|
109 |
+
"E14": 0.17,
|
110 |
+
}
|
111 |
+
for node, value in answer.items():
|
112 |
+
assert value == pytest.approx(deg[node], abs=1e-2)
|
113 |
+
|
114 |
+
def test_davis_betweenness_centrality(self):
|
115 |
+
G = self.davis
|
116 |
+
bet = bipartite.betweenness_centrality(G, self.top_nodes)
|
117 |
+
answer = {
|
118 |
+
"E8": 0.24,
|
119 |
+
"E9": 0.23,
|
120 |
+
"E7": 0.13,
|
121 |
+
"Nora Fayette": 0.11,
|
122 |
+
"Evelyn Jefferson": 0.10,
|
123 |
+
"Theresa Anderson": 0.09,
|
124 |
+
"E6": 0.07,
|
125 |
+
"Sylvia Avondale": 0.07,
|
126 |
+
"Laura Mandeville": 0.05,
|
127 |
+
"Brenda Rogers": 0.05,
|
128 |
+
"Katherina Rogers": 0.05,
|
129 |
+
"E5": 0.04,
|
130 |
+
"Helen Lloyd": 0.04,
|
131 |
+
"E3": 0.02,
|
132 |
+
"Ruth DeSand": 0.02,
|
133 |
+
"Verne Sanderson": 0.02,
|
134 |
+
"E12": 0.02,
|
135 |
+
"Myra Liddel": 0.02,
|
136 |
+
"E11": 0.02,
|
137 |
+
"Eleanor Nye": 0.01,
|
138 |
+
"Frances Anderson": 0.01,
|
139 |
+
"Pearl Oglethorpe": 0.01,
|
140 |
+
"E4": 0.01,
|
141 |
+
"Charlotte McDowd": 0.01,
|
142 |
+
"E10": 0.01,
|
143 |
+
"Olivia Carleton": 0.01,
|
144 |
+
"Flora Price": 0.01,
|
145 |
+
"E2": 0.00,
|
146 |
+
"E1": 0.00,
|
147 |
+
"Dorothy Murchison": 0.00,
|
148 |
+
"E13": 0.00,
|
149 |
+
"E14": 0.00,
|
150 |
+
}
|
151 |
+
for node, value in answer.items():
|
152 |
+
assert value == pytest.approx(bet[node], abs=1e-2)
|
153 |
+
|
154 |
+
def test_davis_closeness_centrality(self):
|
155 |
+
G = self.davis
|
156 |
+
clos = bipartite.closeness_centrality(G, self.top_nodes)
|
157 |
+
answer = {
|
158 |
+
"E8": 0.85,
|
159 |
+
"E9": 0.79,
|
160 |
+
"E7": 0.73,
|
161 |
+
"Nora Fayette": 0.80,
|
162 |
+
"Evelyn Jefferson": 0.80,
|
163 |
+
"Theresa Anderson": 0.80,
|
164 |
+
"E6": 0.69,
|
165 |
+
"Sylvia Avondale": 0.77,
|
166 |
+
"Laura Mandeville": 0.73,
|
167 |
+
"Brenda Rogers": 0.73,
|
168 |
+
"Katherina Rogers": 0.73,
|
169 |
+
"E5": 0.59,
|
170 |
+
"Helen Lloyd": 0.73,
|
171 |
+
"E3": 0.56,
|
172 |
+
"Ruth DeSand": 0.71,
|
173 |
+
"Verne Sanderson": 0.71,
|
174 |
+
"E12": 0.56,
|
175 |
+
"Myra Liddel": 0.69,
|
176 |
+
"E11": 0.54,
|
177 |
+
"Eleanor Nye": 0.67,
|
178 |
+
"Frances Anderson": 0.67,
|
179 |
+
"Pearl Oglethorpe": 0.67,
|
180 |
+
"E4": 0.54,
|
181 |
+
"Charlotte McDowd": 0.60,
|
182 |
+
"E10": 0.55,
|
183 |
+
"Olivia Carleton": 0.59,
|
184 |
+
"Flora Price": 0.59,
|
185 |
+
"E2": 0.52,
|
186 |
+
"E1": 0.52,
|
187 |
+
"Dorothy Murchison": 0.65,
|
188 |
+
"E13": 0.52,
|
189 |
+
"E14": 0.52,
|
190 |
+
}
|
191 |
+
for node, value in answer.items():
|
192 |
+
assert value == pytest.approx(clos[node], abs=1e-2)
|