Upload folder using huggingface_hub (part 8)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +8 -0
- .venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/INSTALLER +1 -0
- .venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/METADATA +177 -0
- .venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/RECORD +603 -0
- .venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/REQUESTED +0 -0
- .venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/WHEEL +5 -0
- .venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/entry_points.txt +2 -0
- .venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txt +37 -0
- .venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/top_level.txt +1 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_load_centrality.py +344 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_percolation_centrality.py +87 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_reaching.py +140 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_second_order_centrality.py +82 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_subgraph.py +110 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_trophic.py +302 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_voterank.py +64 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/centrality/trophic.py +181 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/centrality/voterank_alg.py +95 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/chains.py +172 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/chordal.py +443 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/clique.py +818 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/cluster.py +732 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/coloring/__init__.py +4 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/coloring/equitable_coloring.py +505 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/coloring/greedy_coloring.py +565 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/coloring/tests/__init__.py +0 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/coloring/tests/test_coloring.py +863 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/communicability_alg.py +163 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/__init__.py +28 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/asyn_fluid.py +153 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/bipartitions.py +354 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/centrality.py +171 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/community_utils.py +30 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/divisive.py +216 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/kclique.py +79 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/label_propagation.py +338 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/leiden.py +162 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/local.py +220 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/louvain.py +384 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/lukes.py +227 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/modularity_max.py +452 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/quality.py +347 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/__init__.py +0 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_asyn_fluid.py +147 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_bipartitions.py +157 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_centrality.py +85 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_divisive.py +106 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_kclique.py +91 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_label_propagation.py +241 -0
- .venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_leiden.py +138 -0
.gitattributes
CHANGED
|
@@ -106,3 +106,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 106 |
.venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBol.ttf filter=lfs diff=lfs merge=lfs -text
|
| 107 |
.venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf filter=lfs diff=lfs merge=lfs -text
|
| 108 |
.venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralItalic.ttf filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
.venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBol.ttf filter=lfs diff=lfs merge=lfs -text
|
| 107 |
.venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf filter=lfs diff=lfs merge=lfs -text
|
| 108 |
.venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralItalic.ttf filter=lfs diff=lfs merge=lfs -text
|
| 109 |
+
.venv/lib/python3.11/site-packages/networkx/drawing/tests/baseline/test_display_complex.png filter=lfs diff=lfs merge=lfs -text
|
| 110 |
+
.venv/lib/python3.11/site-packages/numba/_dispatcher.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 111 |
+
.venv/lib/python3.11/site-packages/numba/_helperlib.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 112 |
+
.venv/lib/python3.11/site-packages/numba/core/runtime/_nrt_python.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 113 |
+
.venv/lib/python3.11/site-packages/numba/core/typeconv/_typeconv.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 114 |
+
.venv/lib/python3.11/site-packages/numba/np/ufunc/omppool.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 115 |
+
.venv/lib/python3.11/site-packages/numba/np/ufunc/tbbpool.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 116 |
+
.venv/lib/python3.11/site-packages/numba/np/ufunc/workqueue.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
uv
|
.venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: networkx
|
| 3 |
+
Version: 3.6.1
|
| 4 |
+
Summary: Python package for creating and manipulating graphs and networks
|
| 5 |
+
Author-email: Aric Hagberg <hagberg@lanl.gov>
|
| 6 |
+
Maintainer-email: NetworkX Developers <networkx-discuss@googlegroups.com>
|
| 7 |
+
License-Expression: BSD-3-Clause
|
| 8 |
+
Project-URL: Homepage, https://networkx.org/
|
| 9 |
+
Project-URL: Bug Tracker, https://github.com/networkx/networkx/issues
|
| 10 |
+
Project-URL: Documentation, https://networkx.org/documentation/stable/
|
| 11 |
+
Project-URL: Source Code, https://github.com/networkx/networkx
|
| 12 |
+
Keywords: Networks,Graph Theory,Mathematics,network,graph,discrete mathematics,math
|
| 13 |
+
Platform: Linux
|
| 14 |
+
Platform: Mac OSX
|
| 15 |
+
Platform: Windows
|
| 16 |
+
Platform: Unix
|
| 17 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 18 |
+
Classifier: Intended Audience :: Developers
|
| 19 |
+
Classifier: Intended Audience :: Science/Research
|
| 20 |
+
Classifier: Operating System :: OS Independent
|
| 21 |
+
Classifier: Programming Language :: Python :: 3
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 26 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 27 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 28 |
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
| 29 |
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
| 30 |
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
| 31 |
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
| 32 |
+
Requires-Python: !=3.14.1,>=3.11
|
| 33 |
+
Description-Content-Type: text/x-rst
|
| 34 |
+
License-File: LICENSE.txt
|
| 35 |
+
Provides-Extra: benchmarking
|
| 36 |
+
Requires-Dist: asv; extra == "benchmarking"
|
| 37 |
+
Requires-Dist: virtualenv; extra == "benchmarking"
|
| 38 |
+
Provides-Extra: default
|
| 39 |
+
Requires-Dist: numpy>=1.25; extra == "default"
|
| 40 |
+
Requires-Dist: scipy>=1.11.2; extra == "default"
|
| 41 |
+
Requires-Dist: matplotlib>=3.8; extra == "default"
|
| 42 |
+
Requires-Dist: pandas>=2.0; extra == "default"
|
| 43 |
+
Provides-Extra: developer
|
| 44 |
+
Requires-Dist: pre-commit>=4.1; extra == "developer"
|
| 45 |
+
Requires-Dist: mypy>=1.15; extra == "developer"
|
| 46 |
+
Provides-Extra: doc
|
| 47 |
+
Requires-Dist: sphinx>=8.0; extra == "doc"
|
| 48 |
+
Requires-Dist: pydata-sphinx-theme>=0.16; extra == "doc"
|
| 49 |
+
Requires-Dist: sphinx-gallery>=0.18; extra == "doc"
|
| 50 |
+
Requires-Dist: numpydoc>=1.8.0; extra == "doc"
|
| 51 |
+
Requires-Dist: pillow>=10; extra == "doc"
|
| 52 |
+
Requires-Dist: texext>=0.6.7; extra == "doc"
|
| 53 |
+
Requires-Dist: myst-nb>=1.1; extra == "doc"
|
| 54 |
+
Requires-Dist: intersphinx-registry; extra == "doc"
|
| 55 |
+
Provides-Extra: example
|
| 56 |
+
Requires-Dist: osmnx>=2.0.0; extra == "example"
|
| 57 |
+
Requires-Dist: momepy>=0.7.2; extra == "example"
|
| 58 |
+
Requires-Dist: contextily>=1.6; extra == "example"
|
| 59 |
+
Requires-Dist: seaborn>=0.13; extra == "example"
|
| 60 |
+
Requires-Dist: cairocffi>=1.7; extra == "example"
|
| 61 |
+
Requires-Dist: igraph>=0.11; extra == "example"
|
| 62 |
+
Requires-Dist: scikit-learn>=1.5; extra == "example"
|
| 63 |
+
Requires-Dist: iplotx>=0.9.0; extra == "example"
|
| 64 |
+
Provides-Extra: extra
|
| 65 |
+
Requires-Dist: lxml>=4.6; extra == "extra"
|
| 66 |
+
Requires-Dist: pygraphviz>=1.14; extra == "extra"
|
| 67 |
+
Requires-Dist: pydot>=3.0.1; extra == "extra"
|
| 68 |
+
Requires-Dist: sympy>=1.10; extra == "extra"
|
| 69 |
+
Provides-Extra: release
|
| 70 |
+
Requires-Dist: build>=0.10; extra == "release"
|
| 71 |
+
Requires-Dist: twine>=4.0; extra == "release"
|
| 72 |
+
Requires-Dist: wheel>=0.40; extra == "release"
|
| 73 |
+
Requires-Dist: changelist==0.5; extra == "release"
|
| 74 |
+
Provides-Extra: test
|
| 75 |
+
Requires-Dist: pytest>=7.2; extra == "test"
|
| 76 |
+
Requires-Dist: pytest-cov>=4.0; extra == "test"
|
| 77 |
+
Requires-Dist: pytest-xdist>=3.0; extra == "test"
|
| 78 |
+
Provides-Extra: test-extras
|
| 79 |
+
Requires-Dist: pytest-mpl; extra == "test-extras"
|
| 80 |
+
Requires-Dist: pytest-randomly; extra == "test-extras"
|
| 81 |
+
Dynamic: license-file
|
| 82 |
+
|
| 83 |
+
NetworkX
|
| 84 |
+
========
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
.. image::
|
| 88 |
+
https://github.com/networkx/networkx/actions/workflows/test.yml/badge.svg?branch=main
|
| 89 |
+
:target: https://github.com/networkx/networkx/actions/workflows/test.yml
|
| 90 |
+
|
| 91 |
+
.. image::
|
| 92 |
+
https://img.shields.io/pypi/v/networkx.svg?
|
| 93 |
+
:target: https://pypi.python.org/pypi/networkx
|
| 94 |
+
|
| 95 |
+
.. image::
|
| 96 |
+
https://img.shields.io/pypi/l/networkx.svg?
|
| 97 |
+
:target: https://github.com/networkx/networkx/blob/main/LICENSE.txt
|
| 98 |
+
|
| 99 |
+
.. image::
|
| 100 |
+
https://img.shields.io/pypi/pyversions/networkx.svg?
|
| 101 |
+
:target: https://pypi.python.org/pypi/networkx
|
| 102 |
+
|
| 103 |
+
.. image::
|
| 104 |
+
https://img.shields.io/github/labels/networkx/networkx/good%20first%20issue?color=green&label=contribute
|
| 105 |
+
:target: https://github.com/networkx/networkx/contribute
|
| 106 |
+
|
| 107 |
+
.. image::
|
| 108 |
+
https://insights.linuxfoundation.org/api/badge/health-score?project=networkx
|
| 109 |
+
:target: https://insights.linuxfoundation.org/project/networkx
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
NetworkX is a Python package for the creation, manipulation,
|
| 113 |
+
and study of the structure, dynamics, and functions
|
| 114 |
+
of complex networks.
|
| 115 |
+
|
| 116 |
+
- **Website (including documentation):** https://networkx.org
|
| 117 |
+
- **Mailing list:** https://groups.google.com/forum/#!forum/networkx-discuss
|
| 118 |
+
- **Source:** https://github.com/networkx/networkx
|
| 119 |
+
- **Bug reports:** https://github.com/networkx/networkx/issues
|
| 120 |
+
- **Report a security vulnerability:** https://tidelift.com/security
|
| 121 |
+
- **Tutorial:** https://networkx.org/documentation/latest/tutorial.html
|
| 122 |
+
- **GitHub Discussions:** https://github.com/networkx/networkx/discussions
|
| 123 |
+
- **Discord (Scientific Python) invite link:** https://discord.com/invite/vur45CbwMz
|
| 124 |
+
- **NetworkX meetings calendar (open to all):** https://scientific-python.org/calendars/networkx.ics
|
| 125 |
+
|
| 126 |
+
Simple example
|
| 127 |
+
--------------
|
| 128 |
+
|
| 129 |
+
Find the shortest path between two nodes in an undirected graph:
|
| 130 |
+
|
| 131 |
+
.. code:: pycon
|
| 132 |
+
|
| 133 |
+
>>> import networkx as nx
|
| 134 |
+
>>> G = nx.Graph()
|
| 135 |
+
>>> G.add_edge("A", "B", weight=4)
|
| 136 |
+
>>> G.add_edge("B", "D", weight=2)
|
| 137 |
+
>>> G.add_edge("A", "C", weight=3)
|
| 138 |
+
>>> G.add_edge("C", "D", weight=4)
|
| 139 |
+
>>> nx.shortest_path(G, "A", "D", weight="weight")
|
| 140 |
+
['A', 'B', 'D']
|
| 141 |
+
|
| 142 |
+
Install
|
| 143 |
+
-------
|
| 144 |
+
|
| 145 |
+
Install the latest released version of NetworkX:
|
| 146 |
+
|
| 147 |
+
.. code:: shell
|
| 148 |
+
|
| 149 |
+
$ pip install networkx
|
| 150 |
+
|
| 151 |
+
Install with all optional dependencies:
|
| 152 |
+
|
| 153 |
+
.. code:: shell
|
| 154 |
+
|
| 155 |
+
$ pip install networkx[default]
|
| 156 |
+
|
| 157 |
+
For additional details,
|
| 158 |
+
please see the `installation guide <https://networkx.org/documentation/stable/install.html>`_.
|
| 159 |
+
|
| 160 |
+
Bugs
|
| 161 |
+
----
|
| 162 |
+
|
| 163 |
+
Please report any bugs that you find `here <https://github.com/networkx/networkx/issues>`_.
|
| 164 |
+
Or, even better, fork the repository on `GitHub <https://github.com/networkx/networkx>`_
|
| 165 |
+
and create a pull request (PR). We welcome all changes, big or small, and we
|
| 166 |
+
will help you make the PR if you are new to `git` (just ask on the issue and/or
|
| 167 |
+
see the `contributor guide <https://networkx.org/documentation/latest/developer/contribute.html>`_).
|
| 168 |
+
|
| 169 |
+
License
|
| 170 |
+
-------
|
| 171 |
+
|
| 172 |
+
Released under the `3-clause BSD license <https://github.com/networkx/networkx/blob/main/LICENSE.txt>`_::
|
| 173 |
+
|
| 174 |
+
Copyright (c) 2004-2025, NetworkX Developers
|
| 175 |
+
Aric Hagberg <hagberg@lanl.gov>
|
| 176 |
+
Dan Schult <dschult@colgate.edu>
|
| 177 |
+
Pieter Swart <swart@lanl.gov>
|
.venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/RECORD
ADDED
|
@@ -0,0 +1,603 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
networkx-3.6.1.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
|
| 2 |
+
networkx-3.6.1.dist-info/METADATA,sha256=rKXZSpfR9w8wHQM63bY19uZr6Jc6AKukEnY37tLvMWo,6783
|
| 3 |
+
networkx-3.6.1.dist-info/RECORD,,
|
| 4 |
+
networkx-3.6.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
networkx-3.6.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
| 6 |
+
networkx-3.6.1.dist-info/entry_points.txt,sha256=H2jZaDsDJ_i9H2SwWpwuFel8BrZ9xHKuvh-DQAWW9lQ,94
|
| 7 |
+
networkx-3.6.1.dist-info/licenses/LICENSE.txt,sha256=PPfDoXnYF7I7i4VoIRdp_v35N5fSB9mEuLL6JNAiCzM,1763
|
| 8 |
+
networkx-3.6.1.dist-info/top_level.txt,sha256=s3Mk-7KOlu-kD39w8Xg_KXoP5Z_MVvgB-upkyuOE4Hk,9
|
| 9 |
+
networkx/__init__.py,sha256=OVN8C-x44LgeJWKcb77v-WwfMV7EYqieafkoQdlAl5E,1625
|
| 10 |
+
networkx/algorithms/__init__.py,sha256=sXdgBEDG0qlsOAymWl9zyT-c_luwOQOhWuus6quro0A,6607
|
| 11 |
+
networkx/algorithms/approximation/__init__.py,sha256=1W0c3YlSfVQtNI4-WiQdzMfPqmcrCar5hJQmrwcsVoI,1234
|
| 12 |
+
networkx/algorithms/approximation/clique.py,sha256=b4cnWMJXmmgCyjMI8A_doHZeKS_RQbGqm2L01OpT_Jg,7691
|
| 13 |
+
networkx/algorithms/approximation/clustering_coefficient.py,sha256=SWpSLEhW3DJc1n2fHlSbJSGg3wdoJkN5Y4_tnntn0Ws,2164
|
| 14 |
+
networkx/algorithms/approximation/connectivity.py,sha256=aVXSfUiWEG4gUL0R1u6WZ-h-wheuLP1_suO_pRFB8M4,13118
|
| 15 |
+
networkx/algorithms/approximation/density.py,sha256=_JU9nIH4wneHG6PtEAF_q1oLwy5UUKk--FkTVkkMAMg,15258
|
| 16 |
+
networkx/algorithms/approximation/distance_measures.py,sha256=UEkmKagNw9sj8kiUDdbAeYuzvZ31pgLMXqzliqMkG84,5805
|
| 17 |
+
networkx/algorithms/approximation/dominating_set.py,sha256=5fC90w1CgYR4Xkpqact8iukKY0i57bMmyJW-A9CToUQ,4710
|
| 18 |
+
networkx/algorithms/approximation/kcomponents.py,sha256=MDkoyQbk0gSAm3ZZK35VOsiLJDv7wiDsxfzH5O-ObFs,13285
|
| 19 |
+
networkx/algorithms/approximation/matching.py,sha256=PFof5m9AIq9Xr5Kaa_-mYxI1IBBP7HEkjf-R9wVE3bo,1175
|
| 20 |
+
networkx/algorithms/approximation/maxcut.py,sha256=eTQZqsDQAAUaufni-aDJAY2UzIcajDhRMdj-AcqVkPs,4333
|
| 21 |
+
networkx/algorithms/approximation/ramsey.py,sha256=W5tX7BOQJIM_qNsBeUhCXVWMD8DFdeTycYyk08k4Sqk,1358
|
| 22 |
+
networkx/algorithms/approximation/steinertree.py,sha256=2t58cQQt9OAMRWP1q0RV9QrdNzgasZtPNp6PbA0LFDU,9363
|
| 23 |
+
networkx/algorithms/approximation/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 24 |
+
networkx/algorithms/approximation/tests/test_approx_clust_coeff.py,sha256=PGOVEKf2BcJu1vvjZrgTlBBpwM8V6t7yCANjyS9nWF0,1171
|
| 25 |
+
networkx/algorithms/approximation/tests/test_clique.py,sha256=s6HQB-lK3RAu_ftpe2NvIiMu0Ol8tpAdbGvWzucNL6k,3021
|
| 26 |
+
networkx/algorithms/approximation/tests/test_connectivity.py,sha256=gDG6tsgP3ux7Dgu0x7r0nso7_yknIxicV42Gq0It5pc,5952
|
| 27 |
+
networkx/algorithms/approximation/tests/test_density.py,sha256=EgJsX9z2lxWJCpF5NPbYEbE0GIATazCmgj7wFYeObDM,5298
|
| 28 |
+
networkx/algorithms/approximation/tests/test_distance_measures.py,sha256=axgOojplJIgXdopgkjxjAgvzGTQ1FV1oJ5NG-7ICalo,2023
|
| 29 |
+
networkx/algorithms/approximation/tests/test_dominating_set.py,sha256=l4pBDY7pK7Fxw-S4tOlNcxf-j2j5GpHPJ9f4TrMs1sI,2686
|
| 30 |
+
networkx/algorithms/approximation/tests/test_kcomponents.py,sha256=tTljP1FHzXrUwi-oBz5AQcibRw1NgR4N5UE0a2OrOUA,9346
|
| 31 |
+
networkx/algorithms/approximation/tests/test_matching.py,sha256=nitZncaM0605kaIu1NO6_5TFV2--nohUCO46XTD_lnM,186
|
| 32 |
+
networkx/algorithms/approximation/tests/test_maxcut.py,sha256=U6CDZFSLfYDII-1nX9XB7avSz10kTx88vNazJFoLQ1k,2804
|
| 33 |
+
networkx/algorithms/approximation/tests/test_ramsey.py,sha256=h36Ol39csHbIoTDBxbxMgn4371iVUGZ3a2N6l7d56lI,1143
|
| 34 |
+
networkx/algorithms/approximation/tests/test_steinertree.py,sha256=ifBKzrKjRzfMg2g9BKSXVYLvuEbygQPp9rXR4cK99Q8,10727
|
| 35 |
+
networkx/algorithms/approximation/tests/test_traveling_salesman.py,sha256=odnyk7CgLbMGI2QuHxj3BPRX4cCfWHK5N65rj0jMLW8,32048
|
| 36 |
+
networkx/algorithms/approximation/tests/test_treewidth.py,sha256=b_79ZKiW0XX24-GYaeQJ9Zaq7ZFYQT0DcDTkACII3EY,8868
|
| 37 |
+
networkx/algorithms/approximation/tests/test_vertex_cover.py,sha256=FobHNhG9CAMeB_AOEprUs-7XQdPoc1YvfmXhozDZ8pM,1942
|
| 38 |
+
networkx/algorithms/approximation/traveling_salesman.py,sha256=HZU6dbPo3Hiz2-Z3QHLFm5kdGBQwkXPefkVUuW-IC2A,56210
|
| 39 |
+
networkx/algorithms/approximation/treewidth.py,sha256=hfLiPlheQMN7MG6CGR5w7AscKbLu3pTLNYRS13SO0Xo,8389
|
| 40 |
+
networkx/algorithms/approximation/vertex_cover.py,sha256=oIi_yg5O-IisnfmrSof1P4HD-fsZpW69RpvkR_SM5Og,2803
|
| 41 |
+
networkx/algorithms/assortativity/__init__.py,sha256=ov3HRRbeYB_6Qezvxp1OTl77GBpw-EWkWGUzgfT8G9c,294
|
| 42 |
+
networkx/algorithms/assortativity/connectivity.py,sha256=-V0C5MTqtErl86N-gyrZ487MUyiG5x1QFEZKurOpIJA,4220
|
| 43 |
+
networkx/algorithms/assortativity/correlation.py,sha256=0rc4FDi-e8eQRia7gpFrTqjIy-J7V2GtSwOb4QN6WZk,8689
|
| 44 |
+
networkx/algorithms/assortativity/mixing.py,sha256=RRqqkuVwo71LosJLDbeVCVBikqC7I_XZORdsonQsf9Y,7586
|
| 45 |
+
networkx/algorithms/assortativity/neighbor_degree.py,sha256=UMaQWKBkOZ0ZgC8xGt5fXEz8OL1rgwYjt2zKbKEqofI,5282
|
| 46 |
+
networkx/algorithms/assortativity/pairs.py,sha256=w7xnaWxDDteluHoCsqunLlcM6nlcBenO_5Nz87oOEnE,3841
|
| 47 |
+
networkx/algorithms/assortativity/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 48 |
+
networkx/algorithms/assortativity/tests/base_test.py,sha256=MNeQMLA3oBUCM8TSyNbBQ_uW0nDc1GEZYdNdUwePAm4,2651
|
| 49 |
+
networkx/algorithms/assortativity/tests/test_connectivity.py,sha256=Js841GQLYTLWvc6xZhnyqj-JtyrnS0ska1TFYntxyXA,4978
|
| 50 |
+
networkx/algorithms/assortativity/tests/test_correlation.py,sha256=ddx-yqnVcOfx1dKVNUF695hS3Q-zCmFmCGzK64B7YSE,5068
|
| 51 |
+
networkx/algorithms/assortativity/tests/test_mixing.py,sha256=1kkiMoQXslY-VnT1j00mFbRdj75A4d1b6OPTUOJVgaY,6802
|
| 52 |
+
networkx/algorithms/assortativity/tests/test_neighbor_degree.py,sha256=wphbir1e-h-BAq5rjvWBi4WlgWdseyQbh_KLGQvy5Pc,3934
|
| 53 |
+
networkx/algorithms/assortativity/tests/test_pairs.py,sha256=t05qP_-gfkbiR6aTLtE1owYl9otBSsuJcRkuZsa63UQ,3008
|
| 54 |
+
networkx/algorithms/asteroidal.py,sha256=hIGg9zI4vylRXkrY5wHverTSOeK6dt1Gn2T_JYvGNnU,5500
|
| 55 |
+
networkx/algorithms/bipartite/__init__.py,sha256=FZug-pg0FUDgAdysnKXxDpi1ly8ezxf4UxBPRklqjys,3883
|
| 56 |
+
networkx/algorithms/bipartite/basic.py,sha256=JPC2gGuPvFA6q2CuI5mqLX_9QUGxrsQ8cIwcS0e9P4U,8375
|
| 57 |
+
networkx/algorithms/bipartite/centrality.py,sha256=G280bAqeyXyCmes5NpRqUv2Tc-EHWrMshJ3_f4uqV9U,9156
|
| 58 |
+
networkx/algorithms/bipartite/cluster.py,sha256=8aZRmlQ3g0XtzHyF1kUBBwnzMSjtduquHDH8MxKNSEI,7346
|
| 59 |
+
networkx/algorithms/bipartite/covering.py,sha256=B3ITc016Kk70NBv-1lb30emXnfjlMIQJ7M-FIPCZip0,2163
|
| 60 |
+
networkx/algorithms/bipartite/edgelist.py,sha256=mmiM2Bvh9CxRKCsspbs-90GZedpt7Gj5AGzvJ-aYDSM,11409
|
| 61 |
+
networkx/algorithms/bipartite/extendability.py,sha256=OrYHlS4ruQST-dlQOuleiqHFKpVVNOvrG5aDNFgfckg,3989
|
| 62 |
+
networkx/algorithms/bipartite/generators.py,sha256=p0xgyuJ5hp52NYPu2ryPEKZ0MEktP5VSW2HMK2VdBCo,20408
|
| 63 |
+
networkx/algorithms/bipartite/link_analysis.py,sha256=eVRRQgwzMcUPPu6ccskPk72yc_lmnF5EGqNIdXe-MxA,12772
|
| 64 |
+
networkx/algorithms/bipartite/matching.py,sha256=xsT048Ok_uM0Zhpdc34qswV1zaCGOlJQnsbGTDsm5oo,21637
|
| 65 |
+
networkx/algorithms/bipartite/matrix.py,sha256=rxmjBNHts4hQ-EIlHLE3vIAeGHaMz8Kg_FJ8je5zFyQ,8320
|
| 66 |
+
networkx/algorithms/bipartite/projection.py,sha256=YIUlreqQQ6IPE37OXF32zNIdzEGeyR8aY-7iUENZYVA,17252
|
| 67 |
+
networkx/algorithms/bipartite/redundancy.py,sha256=eGNVo0qW-3unhGhY5VTs2vbc8QmOGve70UDY3ykjhNo,3340
|
| 68 |
+
networkx/algorithms/bipartite/spectral.py,sha256=fu2grV1the_e_G-e_lUdhk8Y9XFe6_p2tPmx3RKntFw,1902
|
| 69 |
+
networkx/algorithms/bipartite/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 70 |
+
networkx/algorithms/bipartite/tests/test_basic.py,sha256=gzbtsQqPi85BznX5REdGBBJVyr9aH4nO06c3eEI4634,4291
|
| 71 |
+
networkx/algorithms/bipartite/tests/test_centrality.py,sha256=PABPbrIyoAziEEQKXsZLl2jT36N8DZpNRzEO-jeu89Y,6362
|
| 72 |
+
networkx/algorithms/bipartite/tests/test_cluster.py,sha256=O0VsPVt8vcY_E1FjjLJX2xaUbhVViI5MP6_gLTbEpos,2801
|
| 73 |
+
networkx/algorithms/bipartite/tests/test_covering.py,sha256=EGVxYQsyLXE5yY5N5u6D4wZq2NcZe9OwlYpEuY6DF3o,1221
|
| 74 |
+
networkx/algorithms/bipartite/tests/test_edgelist.py,sha256=fK35tSekG_-9Ewr5Bhl1bRdwAy247Z9zZ4dQFFDQ9xw,8471
|
| 75 |
+
networkx/algorithms/bipartite/tests/test_extendability.py,sha256=XgPmg6bWiHAF1iQ75_r2NqUxExOQNZRUeYUPzlCa5-E,7043
|
| 76 |
+
networkx/algorithms/bipartite/tests/test_generators.py,sha256=BehRU6SQnWzKsAFoshrN2vpxcPByLAViofGeq38v23E,13203
|
| 77 |
+
networkx/algorithms/bipartite/tests/test_link_analysis.py,sha256=vJMOtYG0vxYQCif_ztnYTUm_13gApfzFiNxChRefONg,6914
|
| 78 |
+
networkx/algorithms/bipartite/tests/test_matching.py,sha256=3-2DMl3tF-g4_xNHvEuY4fZW7S5cqMTO_GUpcz1gkeQ,11973
|
| 79 |
+
networkx/algorithms/bipartite/tests/test_matrix.py,sha256=TlZRVHCTKO2sqhycKFsefvdqP-Se47b_8iZwjtPpQYs,5063
|
| 80 |
+
networkx/algorithms/bipartite/tests/test_project.py,sha256=WhX_yteTrXOdTZLMXpkW2A5ZFIBkw0WsnJRsNITyYtQ,15294
|
| 81 |
+
networkx/algorithms/bipartite/tests/test_redundancy.py,sha256=utxcrQaTrkcEN3kqtObgKNpLZai8B5sMAqLyXatOuUo,917
|
| 82 |
+
networkx/algorithms/bipartite/tests/test_spectral_bipartivity.py,sha256=1jGDgrIx3-TWOCNMSC4zxmZa7LHyMU69DXh3h12Bjag,2358
|
| 83 |
+
networkx/algorithms/boundary.py,sha256=q3JtWssmn9yCB2mBdkjKZjkaxmBhkG9_dJOzmuJiQos,5339
|
| 84 |
+
networkx/algorithms/bridges.py,sha256=CsxueHDOB9aFM5D8GP83u1ZKGzxF193XBpvmMReAcQk,6066
|
| 85 |
+
networkx/algorithms/broadcasting.py,sha256=Amw1oRpr8pdS67aC_9wjJOQomP1IqPvqtE7c0Mf9L70,4974
|
| 86 |
+
networkx/algorithms/centrality/__init__.py,sha256=Er3YoYoj76UfY4P6I0L-0fCQkO7mMU0b3NLsTT2RGWI,558
|
| 87 |
+
networkx/algorithms/centrality/betweenness.py,sha256=8829b5ep0pilM2Muqk5U0rPVQ02kwwedXaVGuQ_hY_U,22814
|
| 88 |
+
networkx/algorithms/centrality/betweenness_subset.py,sha256=CUX0c96gYIORsdjOxVtif2796gOAcMitYoqEnbXDi5c,8114
|
| 89 |
+
networkx/algorithms/centrality/closeness.py,sha256=ehkntG-gApT9uhWJjGaEZQ-tEQ-hdxDT7luf-uVPNAE,10281
|
| 90 |
+
networkx/algorithms/centrality/current_flow_betweenness.py,sha256=kbq9XsZQvrCOdCAYvF67hRni1aqA1sT93WU2i0WfKKI,12717
|
| 91 |
+
networkx/algorithms/centrality/current_flow_betweenness_subset.py,sha256=2qtLgf_3ft5qdDvHFrfYUt6zeQi42Nw7XBpSZRboJIA,8107
|
| 92 |
+
networkx/algorithms/centrality/current_flow_closeness.py,sha256=IvecI8BZE4SgKayEXhKowIJw7S2fD_dN__N-f9TW-ME,3327
|
| 93 |
+
networkx/algorithms/centrality/degree_alg.py,sha256=EFTA1b_GWUbmBy5R9beRQp7yh1X_NwZtk5L6is-mFGk,3894
|
| 94 |
+
networkx/algorithms/centrality/dispersion.py,sha256=M12L2KiVPrC2-SyCXMF0kvxLelgcmvXJkLT_cBHoCTw,3631
|
| 95 |
+
networkx/algorithms/centrality/eigenvector.py,sha256=LAxVqaT3LmuQw20__t1KrgLKPF1Cz-PkTaiSrgPC1FU,13623
|
| 96 |
+
networkx/algorithms/centrality/flow_matrix.py,sha256=Y65m6VbWyYjNK0CInE_lufyEkKy9-TyPmBeXb-Gkz70,3834
|
| 97 |
+
networkx/algorithms/centrality/group.py,sha256=TLlK2eWlcMX7Lvbe2wAcZrmZ9LLTvbRCz-3RbXF0Zug,27960
|
| 98 |
+
networkx/algorithms/centrality/harmonic.py,sha256=OfrDikASbb0Xejjbd1kJ-lQuGT3Gv-rg3pmTtncAbho,2832
|
| 99 |
+
networkx/algorithms/centrality/katz.py,sha256=uVGHAyjqndSd4y4idHjkv0mUhmKmHU5vaEfNWfiKlzc,11042
|
| 100 |
+
networkx/algorithms/centrality/laplacian.py,sha256=qjyW2WnxMFo_mZqiQ4d8PVHLpXi3xNEX148Yikvk_ls,5554
|
| 101 |
+
networkx/algorithms/centrality/load.py,sha256=M2EdPX4gJEYGjMBIJMFKRWGI9uYHbFOWYxsILeaJuOE,6859
|
| 102 |
+
networkx/algorithms/centrality/percolation.py,sha256=YJB8iYgbpjJ3EYK8pl26iSnjgfFsK31ufytRHnUTYYE,4419
|
| 103 |
+
networkx/algorithms/centrality/reaching.py,sha256=Q9rda_dqXBfVaHOi8FgZSYNHKpJ0SHfCbX_myMsIe2I,7255
|
| 104 |
+
networkx/algorithms/centrality/second_order.py,sha256=4CTboP95B6gUtAtSKLfeeE4s9oq0_3hXsXczxL6c_g8,5012
|
| 105 |
+
networkx/algorithms/centrality/subgraph_alg.py,sha256=YXkuyhhhZHmobNFpKDUpfeqSPyBvk97MlcJy5ESWh1s,10520
|
| 106 |
+
networkx/algorithms/centrality/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 107 |
+
networkx/algorithms/centrality/tests/test_betweenness_centrality.py,sha256=LmHNSaqExAT8kE-eOb_67Z6ckSGD_XqO56OHXhNkbFc,33669
|
| 108 |
+
networkx/algorithms/centrality/tests/test_betweenness_centrality_subset.py,sha256=Y7qigLxQwFJqClJiCrKWGkcOHD467W0b6C5gBb0rFUg,13085
|
| 109 |
+
networkx/algorithms/centrality/tests/test_closeness_centrality.py,sha256=-LtG4ex192Xjgy4JCTfdjdJ3Cd9Op-3XnVvG2GA3FWQ,8728
|
| 110 |
+
networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality.py,sha256=1sipOadh8bsuzHZ0_7haapKU6Vrn0rbZL5HXvbsto5w,10072
|
| 111 |
+
networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py,sha256=JfRGgPuiF-vJu5fc2_pcJYREEboxcK_dmy-np39c4Aw,5839
|
| 112 |
+
networkx/algorithms/centrality/tests/test_current_flow_closeness.py,sha256=vflQeoNKngrGUiRb3XNlm2X9wR4vKgMSW_sCyMUCQi8,1379
|
| 113 |
+
networkx/algorithms/centrality/tests/test_degree_centrality.py,sha256=Jn_p5lThA3__ZBTDAORwo_EchjXKKkK1NwU_73HHI6M,4101
|
| 114 |
+
networkx/algorithms/centrality/tests/test_dispersion.py,sha256=ROgl_5bGhcNXonNW3ylsvUcA0NCwynsQu_scic371Gw,1959
|
| 115 |
+
networkx/algorithms/centrality/tests/test_eigenvector_centrality.py,sha256=AfUa7GTve0UX6QOdBF6YMipmo-gKhyCu6aT8OCSf8wc,5254
|
| 116 |
+
networkx/algorithms/centrality/tests/test_group.py,sha256=833ME4tGlOGQZz8YANw4MSyeVPpjbyCdYh5X88GOprw,8685
|
| 117 |
+
networkx/algorithms/centrality/tests/test_harmonic_centrality.py,sha256=wI7nStX_kIFJoZQY_i8DXXlZBOJzVnQfOP8yidX0PAU,3867
|
| 118 |
+
networkx/algorithms/centrality/tests/test_katz_centrality.py,sha256=JL0bZZsJe2MQFL6urXgY82wCAwucUvhjaShYZPxpL6U,11240
|
| 119 |
+
networkx/algorithms/centrality/tests/test_laplacian_centrality.py,sha256=9Nd9CfiCn2908BgRZ-cQiMQjpOFDu4Bftod1didWyCE,5898
|
| 120 |
+
networkx/algorithms/centrality/tests/test_load_centrality.py,sha256=Vv3zSW89iELN-8KNbUclmkhOe1LzKdF7U_w34nYovIo,11343
|
| 121 |
+
networkx/algorithms/centrality/tests/test_percolation_centrality.py,sha256=ycQ1fvEZZcWAfqL11urT7yHiEP77usJDSG25OQiDM2s,2591
|
| 122 |
+
networkx/algorithms/centrality/tests/test_reaching.py,sha256=_JVeO1Ri-KybdnGCJ_yNPtJQmT_g77z0DAkU0JYFVGQ,5090
|
| 123 |
+
networkx/algorithms/centrality/tests/test_second_order_centrality.py,sha256=ce0wQ4T33lu23wskzGUnBS7X4BSODlvAX1S5KxlLzOA,1999
|
| 124 |
+
networkx/algorithms/centrality/tests/test_subgraph.py,sha256=vhE9Uh-_Hlk49k-ny6ORHCgqk7LWH8OHIYOEYM96uz0,3729
|
| 125 |
+
networkx/algorithms/centrality/tests/test_trophic.py,sha256=mt--0AUc_8qez2SjauEHVnetC3DMwMAlLME6kgb8Lc0,8796
|
| 126 |
+
networkx/algorithms/centrality/tests/test_voterank.py,sha256=tN5u7pKAnJ_4AiwhPW6EuJZz7FLIG2jYqLKcXFi2urk,1687
|
| 127 |
+
networkx/algorithms/centrality/trophic.py,sha256=7mpFrpgQhwP3Ad1plpJu1WzTGR1YWrIp_SUhM0D8Zww,5328
|
| 128 |
+
networkx/algorithms/centrality/voterank_alg.py,sha256=z_1eq8rSDadEO5W5BbAg1zuOJj2di4FUCkmOwiuK12I,3231
|
| 129 |
+
networkx/algorithms/chains.py,sha256=PPiSq5-GsT1Lsf8fwtGwGDVf1hhv5ZLariWtfzkBbAw,6968
|
| 130 |
+
networkx/algorithms/chordal.py,sha256=L-ILWdVLWE44OkWmEO_4bSo4z6Ro-_zLglfLfTrwdqQ,13411
|
| 131 |
+
networkx/algorithms/clique.py,sha256=SAvORAbZrZ-IpTVuEcarETQihNes-glpNiqoZ7hEgnM,27522
|
| 132 |
+
networkx/algorithms/cluster.py,sha256=sKexvbvRnjuHSAkoJ9_dzCuOWDUDQkT_KjzmkKSoAhE,24851
|
| 133 |
+
networkx/algorithms/coloring/__init__.py,sha256=P1cmqrAjcaCdObkNZ1e6Hp__ZpxBAhQx0iIipOVW8jg,182
|
| 134 |
+
networkx/algorithms/coloring/equitable_coloring.py,sha256=uDcza6PD9qbvwVPUX1MBZbopQdrAEKNk6DpCFkc02tU,16315
|
| 135 |
+
networkx/algorithms/coloring/greedy_coloring.py,sha256=GLXbwSvitsQgmxtOsbgUt4DTkURnb2k0X-7-SNsDW9I,20043
|
| 136 |
+
networkx/algorithms/coloring/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 137 |
+
networkx/algorithms/coloring/tests/test_coloring.py,sha256=7v_d1xanjYMZCa3dq2hE2hCcyexwWBTEFV5SoLgQDv4,23697
|
| 138 |
+
networkx/algorithms/communicability_alg.py,sha256=0tZvZKY-_GUUB7GsRILxabS2jEpI51Udg5ADI9ADGZw,4545
|
| 139 |
+
networkx/algorithms/community/__init__.py,sha256=vfw5aY7eoL7UDk42e0JPoVzRViCzk5cQf83zbls5p90,1279
|
| 140 |
+
networkx/algorithms/community/asyn_fluid.py,sha256=bsY14UgR5FKLFqhFhHKmPP4-RJsVzH6K8ogsImLnCE8,6010
|
| 141 |
+
networkx/algorithms/community/bipartitions.py,sha256=jqgJyMKOCs8TwI8YM9DO8qzuVZFe4XCnYRGeVAx5P4c,12238
|
| 142 |
+
networkx/algorithms/community/centrality.py,sha256=Yyv5kyf1hf_L7iQ_ZbG8_FAkP638Sc_3N4tCSoB6J1w,6635
|
| 143 |
+
networkx/algorithms/community/community_utils.py,sha256=sUi-AcPYyGrYhnjI9ztt-vrSHLl28lKXxTJPfi5N0c8,908
|
| 144 |
+
networkx/algorithms/community/divisive.py,sha256=yFcKfKkiI6FqEVlBVxLa1fbqI1Yeiqe_A5fpPnYvlAE,6655
|
| 145 |
+
networkx/algorithms/community/kclique.py,sha256=DTr9iUT_XWv0S3Y79KQl6OXefjztNMc9SAHWhdFOxcU,2460
|
| 146 |
+
networkx/algorithms/community/label_propagation.py,sha256=LhzAXSHFCPQ2kG_rPgXb06YKdppO7buApksCC4GI4w8,11878
|
| 147 |
+
networkx/algorithms/community/leiden.py,sha256=dx1N_KEsy30mfJ4729rJ28qaLsnkxoqDnv3UOXV2hWQ,6964
|
| 148 |
+
networkx/algorithms/community/local.py,sha256=w-LK7qlMsQ2YHbZRQP95JvqM2gHGSe4yYZi7CXNkj_M,7316
|
| 149 |
+
networkx/algorithms/community/louvain.py,sha256=jscGGTF6uUnC7yGEZTcE9UFmKsLDFwlZa4ecQyVQrOU,15424
|
| 150 |
+
networkx/algorithms/community/lukes.py,sha256=gzqnup95RR2UzUiPpIt8qkepzZ9dCWqHGQSVPIJDMx8,8115
|
| 151 |
+
networkx/algorithms/community/modularity_max.py,sha256=Qzidmvk2QOIb-S2o4erJvLSeQWcPbLq5TVMrxw15Wc4,18093
|
| 152 |
+
networkx/algorithms/community/quality.py,sha256=oEw-RZBe62janFTTs-ak62APBiF2FpQoBiHv11_4YQY,11943
|
| 153 |
+
networkx/algorithms/community/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 154 |
+
networkx/algorithms/community/tests/test_asyn_fluid.py,sha256=XziMTOiEhzX6cvJdLeODUC1zjOLWchhHf9Z_9Eb3TME,3738
|
| 155 |
+
networkx/algorithms/community/tests/test_bipartitions.py,sha256=w7kxfw5WjKzIosCdq3eHsvuYhUoElaO9Q3lK0kVyNg4,4639
|
| 156 |
+
networkx/algorithms/community/tests/test_centrality.py,sha256=s8q4k5aThR0OgO9CDQk_PXMxfllmf5uC1GlvyUc_8EY,2932
|
| 157 |
+
networkx/algorithms/community/tests/test_divisive.py,sha256=-Ee40OR-mPDReTngTEhbpx4_uLtNI7cqFkt8cZT9t5Y,3441
|
| 158 |
+
networkx/algorithms/community/tests/test_kclique.py,sha256=iA0SBqwbDfaD2u7KM6ccs6LfgAQY_xxrnW05UIT_tFA,2413
|
| 159 |
+
networkx/algorithms/community/tests/test_label_propagation.py,sha256=IHidFEv7MI781zsdk7XT848rLvLwDk2wBK1FjL-CRv4,7985
|
| 160 |
+
networkx/algorithms/community/tests/test_leiden.py,sha256=bl4jr-Z0m59AISIAl-OLsnATz1lDacNssc-ICKn72Nw,4803
|
| 161 |
+
networkx/algorithms/community/tests/test_local.py,sha256=c-dy1rs1L0ahhDTQwNZP1zNbffjzRgw5IBFTCBV-fas,1809
|
| 162 |
+
networkx/algorithms/community/tests/test_louvain.py,sha256=TwW1nlSKWGJeIKr9QOJ8xGehSY6R0Nz01xsnFqzt0Oo,8071
|
| 163 |
+
networkx/algorithms/community/tests/test_lukes.py,sha256=f_JU-EzY6PwXEkPN8kk5_3NVg6phlX0nrj1f57M49lk,3961
|
| 164 |
+
networkx/algorithms/community/tests/test_modularity_max.py,sha256=XYyPuDkxL4CYFwnpTdU_qD4GydpqgiRAIJO3CHQN_m4,10617
|
| 165 |
+
networkx/algorithms/community/tests/test_quality.py,sha256=sZEy10hh3zlelUmww5r2pk5LxpZAht06PC5zCHxV1bs,5275
|
| 166 |
+
networkx/algorithms/community/tests/test_utils.py,sha256=gomD6rFgAaywxT1Yjdi4ozY-1rC0ina4jgfvWeCvwGE,704
|
| 167 |
+
networkx/algorithms/components/__init__.py,sha256=Dt74KZWp_cJ_j0lL5hd_S50_hia5DKcC2SjuRnubr6M,173
|
| 168 |
+
networkx/algorithms/components/attracting.py,sha256=6az3lgqWhHTXaWUUuOPZfW9t7okliAhooFRotQY5JoM,2712
|
| 169 |
+
networkx/algorithms/components/biconnected.py,sha256=_9GJdPZgqusGKZLzqT9tUSj1XZr2DgohiT6hcHVyil4,12782
|
| 170 |
+
networkx/algorithms/components/connected.py,sha256=s-uvEdHkY8dNxNPS5G8jnk-qTCum-bet_yKAx8_qTXc,7904
|
| 171 |
+
networkx/algorithms/components/semiconnected.py,sha256=BaBMFlQ208vuHOo5y1xeV0PDEI3yDUfH6zFb_jkcVhQ,2030
|
| 172 |
+
networkx/algorithms/components/strongly_connected.py,sha256=oZGBBDzhsrCBQjIfqYlkzvXkE3sF-WTRtYEa5UYy6-k,9911
|
| 173 |
+
networkx/algorithms/components/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 174 |
+
networkx/algorithms/components/tests/test_attracting.py,sha256=b3N3ZR9E5gLSQWGgaqhcRfRs4KBW6GnnkVYeAjdxC_o,2243
|
| 175 |
+
networkx/algorithms/components/tests/test_biconnected.py,sha256=N-J-dgBgI77ytYUUrXjduLxtDydH7jS-af98fyPBkYc,6036
|
| 176 |
+
networkx/algorithms/components/tests/test_connected.py,sha256=KMYm55BpbFdGXk_B2WozS9rIagQROd7_k0LT3HFQmr4,4815
|
| 177 |
+
networkx/algorithms/components/tests/test_semiconnected.py,sha256=q860lIxZF5M2JmDwwdzy-SGSXnrillOefMx23GcJpw0,1792
|
| 178 |
+
networkx/algorithms/components/tests/test_strongly_connected.py,sha256=Zm7MgUIZbuPPJu66xZH1zfMZQ_3X1YBl2fLCOjph7NQ,6021
|
| 179 |
+
networkx/algorithms/components/tests/test_weakly_connected.py,sha256=_eUx7226dxme_K2WNmvSIwZXQlKNoCuglWOOC3kFUW4,3083
|
| 180 |
+
networkx/algorithms/components/weakly_connected.py,sha256=q5siwSHQYtbKDcVc4dUDzfKh-DClETmuy3jLQN2_K4o,4413
|
| 181 |
+
networkx/algorithms/connectivity/__init__.py,sha256=EvYKw8LJn7wyZECHAsuEkIaSl-cV-LhymR6tqcn90p8,281
|
| 182 |
+
networkx/algorithms/connectivity/connectivity.py,sha256=xck9yth1asWFAM9Hp7UP6vdUh-Kr0IOmq046plOAXPQ,29367
|
| 183 |
+
networkx/algorithms/connectivity/cuts.py,sha256=o-5GRQotOVXsNq7Kx_w7yBBVuGLa57whS2YF5DVb1KQ,23199
|
| 184 |
+
networkx/algorithms/connectivity/disjoint_paths.py,sha256=57ZerbGqn30B8cwomcsS0GScectvP-mgCMb0GH-RYb8,14649
|
| 185 |
+
networkx/algorithms/connectivity/edge_augmentation.py,sha256=cK9S6pRnsKLyb_57guKfrAbLiXL6sMALHCf7pR4tzFM,44063
|
| 186 |
+
networkx/algorithms/connectivity/edge_kcomponents.py,sha256=hqABcfCqZ-rb45I0qYE-X4NtstsKJbxl37FZzzmoXA4,20894
|
| 187 |
+
networkx/algorithms/connectivity/kcomponents.py,sha256=qDDeMqPb5rWbi6EKZwetBft5Qmv6PSUngQTVunJxyy0,8086
|
| 188 |
+
networkx/algorithms/connectivity/kcutsets.py,sha256=zYohzgkR2FODi_Ew2M9uMLb_a9ZP5fNqcXJwMYy6P7o,9371
|
| 189 |
+
networkx/algorithms/connectivity/stoerwagner.py,sha256=WodsJEqKgsmTTcyUBk2u3wV_CXeon-cAzveWgIGgFmA,5431
|
| 190 |
+
networkx/algorithms/connectivity/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 191 |
+
networkx/algorithms/connectivity/tests/test_connectivity.py,sha256=eSmsi8uQk6MI591JgtSu2elIusb08bmSZS0h9gxb76I,15027
|
| 192 |
+
networkx/algorithms/connectivity/tests/test_cuts.py,sha256=q8dxYBAnsGtIBBPZCjIvMszZvXOYST2cVVsCJvXbIhw,10356
|
| 193 |
+
networkx/algorithms/connectivity/tests/test_disjoint_paths.py,sha256=NLHReLoXSKoA6KPBNRbjF84ktg5PEaaktIj2AII3SDY,8392
|
| 194 |
+
networkx/algorithms/connectivity/tests/test_edge_augmentation.py,sha256=gIu58oxk_uSexawlr3H1ds2HGqkTHHGhhVYUCNmfrb4,15737
|
| 195 |
+
networkx/algorithms/connectivity/tests/test_edge_kcomponents.py,sha256=Bzo77zG79Lv_-OzdI1ZZKO_c13wrnFmfv60FrkDyXI0,16453
|
| 196 |
+
networkx/algorithms/connectivity/tests/test_kcomponents.py,sha256=vLwQOLRevXeeid3e7SSKVpd_OyAJE8PxiAU8GYX0Tf0,9276
|
| 197 |
+
networkx/algorithms/connectivity/tests/test_kcutsets.py,sha256=w5DyrjndNqyT3qxQH6WTBCuBR0ljYXatZCtcT1WeiYM,8974
|
| 198 |
+
networkx/algorithms/connectivity/tests/test_stoer_wagner.py,sha256=A291C30_t2CI1erPCqN1W0DoAj3zqNA8fThPIj4Rku0,3011
|
| 199 |
+
networkx/algorithms/connectivity/utils.py,sha256=gL8LmZnK4GKAZQcIPEhVNYmVi18Mqsqwg4O4j_et56s,3217
|
| 200 |
+
networkx/algorithms/core.py,sha256=6SO5Wz-LSkx6t2DSq0GPmOvFALGe0gVsXdsvno9Fljs,17479
|
| 201 |
+
networkx/algorithms/covering.py,sha256=I_on4DUgmwbtbo-qlBq4YWhOsNjuSHCfVGZNAL-Sefs,5278
|
| 202 |
+
networkx/algorithms/cuts.py,sha256=eqwi5bhCMchItKlRAUw4wGVRtHUK0JzTkaXJFUyxXEw,10419
|
| 203 |
+
networkx/algorithms/cycles.py,sha256=AGpANFoLZ2td8YkGn0cHypASJuRllAwj_-g2Vve7QW8,43302
|
| 204 |
+
networkx/algorithms/d_separation.py,sha256=DpOl1YaI-72_fgUJ2NI3Piuj7EQRQ8xmyAQCRdLgjTw,26089
|
| 205 |
+
networkx/algorithms/dag.py,sha256=OPgrOtnKJVMwxu2AxBGWPZyO7ti6qXa6pn57SsO8FAQ,44673
|
| 206 |
+
networkx/algorithms/distance_measures.py,sha256=cQIRYjP4FtpbA3SP_dOPM6hvwpM1z77oMfmuZ4w8suI,37618
|
| 207 |
+
networkx/algorithms/distance_regular.py,sha256=M9m6qitAtCXYbv2k9hDjF0CpxdeEXPu2_KOI8CCGc_I,8391
|
| 208 |
+
networkx/algorithms/dominance.py,sha256=00Ng1SMzAvxodLTfAeLnXexpPb13IlB_S_mDEuT8JhY,3897
|
| 209 |
+
networkx/algorithms/dominating.py,sha256=yoRB4WCe0wMvJpkbKtNo2fpd0jTVq6b09JsCYcaeR_Y,8145
|
| 210 |
+
networkx/algorithms/efficiency_measures.py,sha256=VKbLKJgdIbno-YnJaLaCZt7TNXXnQPdz8N99uJCo748,4741
|
| 211 |
+
networkx/algorithms/euler.py,sha256=yCqKaGchFSRPTRDXq7u1fH2IXZF94wWf9S10K9-Cd6U,14205
|
| 212 |
+
networkx/algorithms/flow/__init__.py,sha256=rVtMUy6dViPLewjDRntmn15QF0bQwiDdQbZZx9j7Drc,341
|
| 213 |
+
networkx/algorithms/flow/boykovkolmogorov.py,sha256=qFcppmiXz4VKKFd4RbDsiWOqJODtDTHbNr9_UFTjQaU,13334
|
| 214 |
+
networkx/algorithms/flow/capacityscaling.py,sha256=8rng2qO5kawNSxq2S8BNlUMmdvNSoC6R8ekiBGU8LxU,14469
|
| 215 |
+
networkx/algorithms/flow/dinitz_alg.py,sha256=I5nnZVsj0aU8-9Cje0umey407epFzpd7BDJpkI6ESK4,8341
|
| 216 |
+
networkx/algorithms/flow/edmondskarp.py,sha256=PEIwLftevS2VYHaTzzZMSOLPy7QSBPsWPedjx1lR6Cs,8056
|
| 217 |
+
networkx/algorithms/flow/gomory_hu.py,sha256=EuibaxPl65shGM9Jxvaa9WMwMmoczDvXXc2b0E81cqM,6345
|
| 218 |
+
networkx/algorithms/flow/maxflow.py,sha256=GuVA4MlPwdOeCdPRXW2QVW1OdJqgzSpPhEyASr302u4,22975
|
| 219 |
+
networkx/algorithms/flow/mincost.py,sha256=GzMYInS4QcNe0yImGrVXJ0bRd7t5TSSMa9jSeenIoOk,12853
|
| 220 |
+
networkx/algorithms/flow/networksimplex.py,sha256=6F1JNT1pMEMt-C27H3PsdZYF-53SrJMrHaakQ8pD7Ng,25098
|
| 221 |
+
networkx/algorithms/flow/preflowpush.py,sha256=CUKZ0-7X9l7P7qH_2n2Immbf8mFm8vocH2SY0tIwjGo,15721
|
| 222 |
+
networkx/algorithms/flow/shortestaugmentingpath.py,sha256=gXXdkY3nH4d0hXVn0P2-kzfC3DHcuCdrudFdxetflKI,10372
|
| 223 |
+
networkx/algorithms/flow/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 224 |
+
networkx/algorithms/flow/tests/gl1.gpickle.bz2,sha256=z4-BzrXqruFiGqYLiS2D5ZamFz9vZRc1m2ef89qhsPg,44623
|
| 225 |
+
networkx/algorithms/flow/tests/gw1.gpickle.bz2,sha256=b3nw6Q-kxR7HkWXxWWPh7YlHdXbga8qmeuYiwmBBGTE,42248
|
| 226 |
+
networkx/algorithms/flow/tests/netgen-2.gpickle.bz2,sha256=OxfmbN7ajtuNHexyYmx38fZd1GdeP3bcL8T9hKoDjjA,18972
|
| 227 |
+
networkx/algorithms/flow/tests/test_gomory_hu.py,sha256=aWtbI3AHofIK6LDJnmj9UH1QOfulXsi5NyB7bNyV2Vw,4471
|
| 228 |
+
networkx/algorithms/flow/tests/test_maxflow.py,sha256=4CtGOqeyloAxFSajaxPfGuyVhE0R3IdJf2SuIg4kHKQ,18940
|
| 229 |
+
networkx/algorithms/flow/tests/test_maxflow_large_graph.py,sha256=P2e7G8TKN17zrMeOEbSIkLwK08MjfOtNhPva3nLM-B0,4612
|
| 230 |
+
networkx/algorithms/flow/tests/test_mincost.py,sha256=vI61ZCLoWAzwYU4hU0AJS8Ori8vAWEPzFDCUoiloVRk,17806
|
| 231 |
+
networkx/algorithms/flow/tests/test_networksimplex.py,sha256=tCw5C1hLEwbUbt_ySWgkvRyLKj-1T2wfXV9HT4Fx77Q,14162
|
| 232 |
+
networkx/algorithms/flow/tests/wlm3.gpickle.bz2,sha256=zKy6Hg-_swvsNh8OSOyIyZnTR0_Npd35O9RErOF8-g4,88132
|
| 233 |
+
networkx/algorithms/flow/utils.py,sha256=jexiKM-_BQfSAy15f4iZ_Km7DvRrcdOKqi6hxu9X0MM,6246
|
| 234 |
+
networkx/algorithms/graph_hashing.py,sha256=kS881g6vUvMZms856A_tblq3ljB6BanUbt5az37fSlo,16918
|
| 235 |
+
networkx/algorithms/graphical.py,sha256=1NdlhXuGEgUkHPo47EoNTWUMfdeTpiv7BBVM9ty2ivw,15831
|
| 236 |
+
networkx/algorithms/hierarchy.py,sha256=_KFhCF1Afr2TrkPhqx-1PXUXEtfYLhbRShC58ZKbDGE,1786
|
| 237 |
+
networkx/algorithms/hybrid.py,sha256=z3sIFMOpja1wlj-lI8YI6OIbSLZWHr66uSqyVESZWXY,6209
|
| 238 |
+
networkx/algorithms/isolate.py,sha256=8F4GCBHZIW21CZresBlHuZhvq85ruPH_pnlxYetbHuQ,2251
|
| 239 |
+
networkx/algorithms/isomorphism/__init__.py,sha256=gPRQ-_X6xN2lJZPQNw86IVj4NemGmbQYTejf5yJ32N4,406
|
| 240 |
+
networkx/algorithms/isomorphism/ismags.py,sha256=AwJKq94d5e_RU0PZs5Gm7D73v-eOBBP8QDkpPxUocd0,60177
|
| 241 |
+
networkx/algorithms/isomorphism/isomorph.py,sha256=O2TZtUPe89CsZxoNchv6FyYsGU79kWrwywGFBeonksE,10561
|
| 242 |
+
networkx/algorithms/isomorphism/isomorphvf2.py,sha256=NTc9uCm2RnR9RxuKsAS_70RWD1zJYCJNPhefcJZUi5U,47637
|
| 243 |
+
networkx/algorithms/isomorphism/matchhelpers.py,sha256=PaZ7PjmNNsJO9KoeRrf9JgcDHIcFr1tZckQc_ol4e9I,10884
|
| 244 |
+
networkx/algorithms/isomorphism/temporalisomorphvf2.py,sha256=-1NW81l8kM9orQ2ni9tcNizQzEhOUE9BaBJXjUWqhiI,10948
|
| 245 |
+
networkx/algorithms/isomorphism/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 246 |
+
networkx/algorithms/isomorphism/tests/iso_r01_s80.A99,sha256=hKzMtYLUR8Oqp9pmJR6RwG7qo31aNPZcnXy4KHDGhqU,1442
|
| 247 |
+
networkx/algorithms/isomorphism/tests/iso_r01_s80.B99,sha256=AHx_W2xG4JEcz1xKoN5TwCHVE6-UO2PiMByynkd4TPE,1442
|
| 248 |
+
networkx/algorithms/isomorphism/tests/si2_b06_m200.A99,sha256=NVnPFA52amNl3qM55G1V9eL9ZlP9NwugBlPf-zekTFU,310
|
| 249 |
+
networkx/algorithms/isomorphism/tests/si2_b06_m200.B99,sha256=-clIDp05LFNRHA2BghhGTeyuXDqBBqA9XpEzpB7Ku7M,1602
|
| 250 |
+
networkx/algorithms/isomorphism/tests/test_ismags.py,sha256=YIrF8xSbnY8zsxiqjSZkzMFXF9TKwZ91m9araTfxJwE,24323
|
| 251 |
+
networkx/algorithms/isomorphism/tests/test_isomorphism.py,sha256=e92l9AcYLKISmXB3hOdKanrvgKlUKuQ0TuXz7xuCD1Q,4576
|
| 252 |
+
networkx/algorithms/isomorphism/tests/test_isomorphvf2.py,sha256=fVZZQgTU_L_kgp6KsiVwy5iLBewVFzXGDl72VQ0CgS0,15303
|
| 253 |
+
networkx/algorithms/isomorphism/tests/test_match_helpers.py,sha256=uuTcvjgf2LPqSQzzECPIh0dezw8-a1IN0u42u8TxwAw,2483
|
| 254 |
+
networkx/algorithms/isomorphism/tests/test_temporalisomorphvf2.py,sha256=k8032J4ItZ4aFHeOraOpiF8y4aPm2O1g44UvUfrQJgg,7343
|
| 255 |
+
networkx/algorithms/isomorphism/tests/test_tree_isomorphism.py,sha256=mZPWRv2sSVJ9PbpGi5MEj5GaFbrp_ha2bL1wre1-Jqo,5681
|
| 256 |
+
networkx/algorithms/isomorphism/tests/test_vf2pp.py,sha256=u_baOdKDdp34CQWwPob8henY90k8_hdK82SQDGesaO0,51386
|
| 257 |
+
networkx/algorithms/isomorphism/tests/test_vf2pp_helpers.py,sha256=A8Y-FcGsLPWvmci5oHHDowSeh-Fhl_y88TrvboPZwdw,90251
|
| 258 |
+
networkx/algorithms/isomorphism/tests/test_vf2userfunc.py,sha256=TrXs7E3Ynva18dBmaJDO4QGsySteCwK32cUKw-WkZ0I,6309
|
| 259 |
+
networkx/algorithms/isomorphism/tree_isomorphism.py,sha256=J4RfMpO5LfL5z_wI3xP2wcbK2vMFEsxAQqBddPdw3YA,9033
|
| 260 |
+
networkx/algorithms/isomorphism/vf2pp.py,sha256=jM3mzJNC0EutWHDmDkKIh1JfsB9XbpTkzEC6qXD0Lpo,36681
|
| 261 |
+
networkx/algorithms/isomorphism/vf2userfunc.py,sha256=HiPwyr7nJF1QS9w69MzKf6wGvO8cgjvdS5vW59iwCew,7371
|
| 262 |
+
networkx/algorithms/link_analysis/__init__.py,sha256=UkcgTDdzsIu-jsJ4jBwP8sF2CsRPC1YcZZT-q5Wlj3I,118
|
| 263 |
+
networkx/algorithms/link_analysis/hits_alg.py,sha256=ot5sEhIvQ-JruYgcqCoi_EvNk89UWx_skG4KayIuO9I,10439
|
| 264 |
+
networkx/algorithms/link_analysis/pagerank_alg.py,sha256=e7HuXXXVCG79YG0iuIOr1wqA_zC60hKoXGlMfvh9k1o,17202
|
| 265 |
+
networkx/algorithms/link_analysis/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 266 |
+
networkx/algorithms/link_analysis/tests/test_hits.py,sha256=BQ7QHXvJDkXtK-_VDFagtdp_-VXxVerwPymjGjzFWA0,2546
|
| 267 |
+
networkx/algorithms/link_analysis/tests/test_pagerank.py,sha256=rUJNa_2nKDSk75Fg1yygMPAqg_Bdk0gGWMDRKY8g1lk,7282
|
| 268 |
+
networkx/algorithms/link_prediction.py,sha256=UYo_LJgoVXcM1iLMXswM2g4jvUJmvxln3e5bVfXxQ10,22253
|
| 269 |
+
networkx/algorithms/lowest_common_ancestors.py,sha256=D1LgoX_ibv2hR-viKEx6l_qp3mWVCkW6YAlGGdoWgXQ,9286
|
| 270 |
+
networkx/algorithms/matching.py,sha256=Xgi-zy9C2pNvGwTixTFV7ut7W-l8s7zUgJha9v8D0s8,44325
|
| 271 |
+
networkx/algorithms/minors/__init__.py,sha256=ceeKdsZ6U1H40ED-KmtVGkbADxeWMTVG07Ja8P7N_Pg,587
|
| 272 |
+
networkx/algorithms/minors/contraction.py,sha256=o5i1UfWpI1KhD4-pVx4yuFJvwi00yJx58Te6GYpys7Y,27606
|
| 273 |
+
networkx/algorithms/minors/tests/test_contraction.py,sha256=31FgiENkElrScHzJrQ3DcKG8W2ieow6zI7PZ9wgVJKE,17674
|
| 274 |
+
networkx/algorithms/mis.py,sha256=BEMv_dW8R6CjMMXJQGIhS4HpS8A8AkLJJWnz3GstuS4,2344
|
| 275 |
+
networkx/algorithms/moral.py,sha256=z5lp42k4kqYk7t_FfszVj5KAC7BxXe6Adik3T2qvA6o,1535
|
| 276 |
+
networkx/algorithms/node_classification.py,sha256=s2yjsHk4mj_6llCuawgGvJ59HyswbcW6ufGQC4UBmG0,6465
|
| 277 |
+
networkx/algorithms/non_randomness.py,sha256=rjIoT7-aqKwGSBNoYxgKniDFgqSDwV8Hh21lkWRYGVE,5787
|
| 278 |
+
networkx/algorithms/operators/__init__.py,sha256=dJ3xOXvHxSzzM3-YcfvjGTJ_ndxULF1TybkIRzUS87Y,201
|
| 279 |
+
networkx/algorithms/operators/all.py,sha256=v_W9ZT3u4STNvT4YI9zYn1Z2PDMhqfh4vfhtO4glaIA,9718
|
| 280 |
+
networkx/algorithms/operators/binary.py,sha256=hziSCLDIVIoTWPV56fED5gI1pErOdyLOQ3Z_E_Nz9As,13150
|
| 281 |
+
networkx/algorithms/operators/product.py,sha256=FQkSIduOv-z1ktVzid2T40759S-BmAfTlya88VytuZc,19632
|
| 282 |
+
networkx/algorithms/operators/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 283 |
+
networkx/algorithms/operators/tests/test_all.py,sha256=Jn8IfNZ1P4Aa51C0gU58S2A-DPksQUFersWco0kG0Yw,8280
|
| 284 |
+
networkx/algorithms/operators/tests/test_binary.py,sha256=BdZQS-qsWbEbRXuWANvH2eXEv7myAKyuldtQzHj6n4Y,12190
|
| 285 |
+
networkx/algorithms/operators/tests/test_product.py,sha256=i4pBb5A4NmaCsllR1XizyhUToaQFMuLZ-JrywkQFdbU,15155
|
| 286 |
+
networkx/algorithms/operators/tests/test_unary.py,sha256=UZdzbt5GI9hnflEizUWXihGqBWmSFJDkzjwVv6wziQE,1415
|
| 287 |
+
networkx/algorithms/operators/unary.py,sha256=Eo2yeTg-F5uODGWSWR_im5VaKZQ97LyATIuKZcAFQR8,1795
|
| 288 |
+
networkx/algorithms/perfect_graph.py,sha256=aMdQkfcXEySVutIOwngHkvDEy1qinO_92uZFJx6Ydnk,2597
|
| 289 |
+
networkx/algorithms/planar_drawing.py,sha256=AXuoT3aFgEtCeMnAaUsRqjxCABdNYZ8Oo9sGOKBQto0,16254
|
| 290 |
+
networkx/algorithms/planarity.py,sha256=nN6QCMz9PJYRqnAa06qEDANdd9bxsbO64PQdbVEGwk4,49887
|
| 291 |
+
networkx/algorithms/polynomials.py,sha256=iP30_mcOlj81Vrzt4iB_ZZxYiRokubs-O1i9RW4pgTw,11278
|
| 292 |
+
networkx/algorithms/reciprocity.py,sha256=1WMhLbSMkVPxRPlfUvbgO5FgVvJHn1doXQF4WuqSLQk,2855
|
| 293 |
+
networkx/algorithms/regular.py,sha256=fEHD4VBREbJwSlR48okVZBuwgvD76GXdT28NitJI8qQ,4877
|
| 294 |
+
networkx/algorithms/richclub.py,sha256=kARzso3M6wnUcAJo2g8ga_ZtigL2czDNzeUDzBtRfqo,4892
|
| 295 |
+
networkx/algorithms/shortest_paths/__init__.py,sha256=Rmxtsje-mPdQyeYhE8TP2NId-iZEOu4eAsWhVRm2Xqk,285
|
| 296 |
+
networkx/algorithms/shortest_paths/astar.py,sha256=0pEnYNzG7Z86zWqyFe0OL8HTlQO9PwjDABy_ypC30_A,8937
|
| 297 |
+
networkx/algorithms/shortest_paths/dense.py,sha256=5Y8ziU-RsWZRTzxEEzg5gB7f4j9yxbNhplTbLaMliG8,8261
|
| 298 |
+
networkx/algorithms/shortest_paths/generic.py,sha256=-7wIqqDWeScy8brYFkdt68nuxkSgXVs1iXcwGWoBZAU,25337
|
| 299 |
+
networkx/algorithms/shortest_paths/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 300 |
+
networkx/algorithms/shortest_paths/tests/test_astar.py,sha256=F0zXZ7R0eXP8Et4F3mrCtdtfE1-tQTGB2ATcFveDUHI,8989
|
| 301 |
+
networkx/algorithms/shortest_paths/tests/test_dense.py,sha256=ievl4gu3Exl_31hp4OKcsAGPb3g3_xFUM4t3NnvrG_A,6747
|
| 302 |
+
networkx/algorithms/shortest_paths/tests/test_dense_numpy.py,sha256=IEwhjPNTlc2H1on-B3WhFoyLkDkJVdAFBjn675XALHA,2299
|
| 303 |
+
networkx/algorithms/shortest_paths/tests/test_generic.py,sha256=CQJxa5by1xE1a2E8iZm8GAtiPy_DILcrB4dIyWVM_qM,20609
|
| 304 |
+
networkx/algorithms/shortest_paths/tests/test_unweighted.py,sha256=r1F5qVEDZnzPn5yJ71Rp-Z7pq33CzJFfZmDhVBekR9Y,5879
|
| 305 |
+
networkx/algorithms/shortest_paths/tests/test_weighted.py,sha256=dzMts7Y1mMUuz4zEz4adEqYUNoXi9BMf-oyzQ0BMG3s,35502
|
| 306 |
+
networkx/algorithms/shortest_paths/unweighted.py,sha256=iuJAO3WzB1p-fwpDyGM4snuFB5k57KIsVGcAJUhCpi0,17825
|
| 307 |
+
networkx/algorithms/shortest_paths/weighted.py,sha256=PphAp7PmN9qpWzkLudePIVgvySh_SGDi5GhdQN5iufk,84155
|
| 308 |
+
networkx/algorithms/similarity.py,sha256=E8P8vWqCR-r2SFVSqW9Y-Bb4I4R7BzUc_jzhiCYx7tU,72679
|
| 309 |
+
networkx/algorithms/simple_paths.py,sha256=8oG_bRDVRrBKVCDEjZLHW3Qyzrv5KVynp-Hl0m5SNmA,31091
|
| 310 |
+
networkx/algorithms/smallworld.py,sha256=3xT-z2_CVdp5-Ap8vF6fsd3DiavDYtspFNZrcwcpXG0,13565
|
| 311 |
+
networkx/algorithms/smetric.py,sha256=_Aj4BIMnafiXbJtLkvAfAnIEMdI9OcVvMy6kk9KKTns,770
|
| 312 |
+
networkx/algorithms/sparsifiers.py,sha256=4T8pMlh-usEHA2-rZFh-CmZbBY9dcXIHjoqR-oJ2hSw,10048
|
| 313 |
+
networkx/algorithms/structuralholes.py,sha256=rYaVkndSJ3kFxbjkhfQd6uMBpYO7NNlcsOPR0Xbiy7Y,12626
|
| 314 |
+
networkx/algorithms/summarization.py,sha256=CygTsSthyCKHs0ZTZsCgWnyaT8annQbLpUtahmfY9Sw,23251
|
| 315 |
+
networkx/algorithms/swap.py,sha256=NVZMmlnkdxgwwNw5GDrc8waNERcdCu52ydHcBdOA_hw,14744
|
| 316 |
+
networkx/algorithms/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 317 |
+
networkx/algorithms/tests/test_asteroidal.py,sha256=DnWI5_jnaaZMxtG44XD0K690HZs8ez7HU_9dSR-p6eA,502
|
| 318 |
+
networkx/algorithms/tests/test_boundary.py,sha256=1OSJh32FYFhAVYB5zqxhZGEXZLS0HPp9kvfHZvWmD3o,6227
|
| 319 |
+
networkx/algorithms/tests/test_bridges.py,sha256=jSCguECho0GNHnu0vpRh1twyfGP6tWFcaYL1rgvc8mU,4026
|
| 320 |
+
networkx/algorithms/tests/test_broadcasting.py,sha256=GqjkpHC5Z7ogZZdf1qsz5B1lmX-Pd5pFMD5e3QRPAkI,3034
|
| 321 |
+
networkx/algorithms/tests/test_chains.py,sha256=4fR5Uh2NMrTZGT1yR6sAsQEP3uy1U3UnwjcXLFk9d1Y,4196
|
| 322 |
+
networkx/algorithms/tests/test_chordal.py,sha256=DPdNPY7KtqCsCwYVb4xQfnIm-z35dUJIWxNHtAiQLAQ,4438
|
| 323 |
+
networkx/algorithms/tests/test_clique.py,sha256=RX1Q38DRDmclLLJ04pfE5RIFAy86EuTZ2QAERrtkjS4,9772
|
| 324 |
+
networkx/algorithms/tests/test_cluster.py,sha256=b0OXtKvUYGzDxBrnIbPh8A3vo3jmRYOFzW02MVSWYgo,19320
|
| 325 |
+
networkx/algorithms/tests/test_communicability.py,sha256=4KK9wU9gAUqHAAAyHwAKpq2dV9g415s_X0qd7Tt83gU,2938
|
| 326 |
+
networkx/algorithms/tests/test_core.py,sha256=Q3bi_c0LpxZ-0VopHU6Lyzkb_JKseVT16H45qDuax9A,9619
|
| 327 |
+
networkx/algorithms/tests/test_covering.py,sha256=EeBjQ5mxcVctgavqXZ255T8ryFocuxjxdVpIxVUNFvw,2718
|
| 328 |
+
networkx/algorithms/tests/test_cuts.py,sha256=gKm9VDtnmwFli6kgwV1ktEFI_rw84p2Sg02Em6SoW5Q,5376
|
| 329 |
+
networkx/algorithms/tests/test_cycles.py,sha256=CBEQ_kNlHg5PHb9vKMS9ot-lqUuvs_cAgaPtnEQn76g,34851
|
| 330 |
+
networkx/algorithms/tests/test_d_separation.py,sha256=cxoAOA_EahXQHFsFaRopz6cp3h5sMnD7D_isq4_EuWI,10714
|
| 331 |
+
networkx/algorithms/tests/test_dag.py,sha256=sd6OlsrK57rY7x6vMfWSf11tEiKH5BakNp7747KvCnA,29407
|
| 332 |
+
networkx/algorithms/tests/test_distance_measures.py,sha256=kF-pR5WbVBs1d_IO-U6Dr-sf8MaRHfxc_D286sBN62E,28793
|
| 333 |
+
networkx/algorithms/tests/test_distance_regular.py,sha256=w27OTUtAI0VQv7cikkOdJg4bo4q7xTNIVE8nbU_x7b8,2915
|
| 334 |
+
networkx/algorithms/tests/test_dominance.py,sha256=rD-m7LVQpqrOTCUJrli43lYpezYxajfkcNd3xvGhTj8,9811
|
| 335 |
+
networkx/algorithms/tests/test_dominating.py,sha256=5WwPlrQ6_pFaVx_-K4D5cHNbCZL23qp-PytgsXDuS4Q,3112
|
| 336 |
+
networkx/algorithms/tests/test_efficiency.py,sha256=QKWMvyjCG1Byt-oNp7Rz_qxnVeT77Zk27lrzI1qH0mA,1894
|
| 337 |
+
networkx/algorithms/tests/test_euler.py,sha256=L4L1ljHVxQxjQQludO2r6k3UZU7WAY_N6WYUjFx1fEk,11209
|
| 338 |
+
networkx/algorithms/tests/test_graph_hashing.py,sha256=ribxC8ZkNxkkBDyjSZ8P2f8J6y5y4g-Ik-k5hBgZcx4,31567
|
| 339 |
+
networkx/algorithms/tests/test_graphical.py,sha256=uhFjvs04odxABToY4IRig_CaUTpAC3SfZRu1p1T7FwY,5366
|
| 340 |
+
networkx/algorithms/tests/test_hierarchy.py,sha256=uW8DqCdXiAeypkNPKcAYX7aW86CawYH84Q0bW4cDTXo,1184
|
| 341 |
+
networkx/algorithms/tests/test_hybrid.py,sha256=kQLzaMoqZcKFaJ3D7PKbY2O-FX59XDZ1pN5un8My-tk,720
|
| 342 |
+
networkx/algorithms/tests/test_isolate.py,sha256=LyR0YYHJDH5vppQzGzGiJK-aaIV17_Jmla8dMf93olg,555
|
| 343 |
+
networkx/algorithms/tests/test_link_prediction.py,sha256=lP6slSHwXdzdJzNSeMTUsP88ypSqe6EeVy-bUP2d-48,20451
|
| 344 |
+
networkx/algorithms/tests/test_lowest_common_ancestors.py,sha256=5ZT_17q-5ipw7NNgNisaVcxIxrY6XeQQaUlBXHx9k9g,14160
|
| 345 |
+
networkx/algorithms/tests/test_matching.py,sha256=1IKeUi49HR8aAOm2V4cmBL2NGXvF9cb8mqW9jnkNGuY,18319
|
| 346 |
+
networkx/algorithms/tests/test_max_weight_clique.py,sha256=M1eoy8OtuQVZkEvNMauV9vqR6hHtOCrtq6INv2qzMyA,6739
|
| 347 |
+
networkx/algorithms/tests/test_mis.py,sha256=Z2tKoqbs-AFPzEBDYO7S8U-F7usLfZJ2l6j2DpZUts4,1865
|
| 348 |
+
networkx/algorithms/tests/test_moral.py,sha256=15PZgkx7O9aXQB1npQ2JNqBBkEqPPP2RfeZzKqY-GNU,452
|
| 349 |
+
networkx/algorithms/tests/test_node_classification.py,sha256=NgJJKUHH1GoD1GE3F4QRYBLM3fUo_En3RNtZvhqCjlg,4663
|
| 350 |
+
networkx/algorithms/tests/test_non_randomness.py,sha256=iDHCFzFvxGXCi_vWnv-DkXHcmO9uU6KVpYGMCpHKQG8,1678
|
| 351 |
+
networkx/algorithms/tests/test_perfect_graph.py,sha256=Y2mpreh5TNCkqn4PDO57MFkgYozt-tlZFScKH3TZJRg,609
|
| 352 |
+
networkx/algorithms/tests/test_planar_drawing.py,sha256=fBTd9JzDkTqNQz7GBQCS9lShU1P3lWRQ7L-E5WhSdlA,8765
|
| 353 |
+
networkx/algorithms/tests/test_planarity.py,sha256=2iy22H4APB2K0DiPcoWmiQV9BTQlJ9JSOexubN14sU0,17312
|
| 354 |
+
networkx/algorithms/tests/test_polynomials.py,sha256=baI0Kua1pRngRC6Scm5gRRwi1bl0iET5_Xxo3AZTP3A,1983
|
| 355 |
+
networkx/algorithms/tests/test_reciprocity.py,sha256=X_PXWFOTzuEcyMWpRdwEJfm8lJOfNE_1rb9AAybf4is,1296
|
| 356 |
+
networkx/algorithms/tests/test_regular.py,sha256=ppXES6zvpsppoZmzXPFim-S4ZMWPG2Zhhmlgc67y_GA,2951
|
| 357 |
+
networkx/algorithms/tests/test_richclub.py,sha256=Wl8aE0CSswaXJiHCQ42IkyRvjWaJQZ2OQcbC7LpIgfo,3962
|
| 358 |
+
networkx/algorithms/tests/test_similarity.py,sha256=l02q6PMnweng8EfUm6Z0yor-Uy-zd6WN0Tm28lh3pBU,41248
|
| 359 |
+
networkx/algorithms/tests/test_simple_paths.py,sha256=7U9wCXz4SHK0XeYrs1k2KjYgrYVQDnts2ggQLzU18p0,25181
|
| 360 |
+
networkx/algorithms/tests/test_smallworld.py,sha256=bmoNDxIuhV0bBKWh2hgFw0XYTPCc2rgg1y77uMg6rE8,2390
|
| 361 |
+
networkx/algorithms/tests/test_smetric.py,sha256=VM14L4X1AABvINDL9qKXzlech_Q2g4Aee-ozWM2Qrr4,144
|
| 362 |
+
networkx/algorithms/tests/test_sparsifiers.py,sha256=1GRbQy1vfmwv6eUhP4Io0aykH2VyTJfFWmncrXmTqi4,4044
|
| 363 |
+
networkx/algorithms/tests/test_structuralholes.py,sha256=F0xZ1nlKJLGmQDebDiExju4fMffu79qThnyF7ZGA53A,7592
|
| 364 |
+
networkx/algorithms/tests/test_summarization.py,sha256=uNyaUstobIEu6M_Hexik-3YiYTRSy_XO6LUqoE4wazw,21312
|
| 365 |
+
networkx/algorithms/tests/test_swap.py,sha256=WJtGMkSbAd1Cv06VaUeDVHosNOtdigsqEspyux0ExCs,6144
|
| 366 |
+
networkx/algorithms/tests/test_threshold.py,sha256=x0hqqbH65nbDNEUV0vYz0J2TSmmBbJ0daEgLIR7CRm0,9733
|
| 367 |
+
networkx/algorithms/tests/test_time_dependent.py,sha256=NmuV2kDo4nh2MeN0hwcJf0QSDtqMD0dfSeeKSsYBtQ8,13342
|
| 368 |
+
networkx/algorithms/tests/test_tournament.py,sha256=tfOPwN7YHnw0oxl9d7-ErPBFKz6KBfSc5S3tbGrGHs8,4107
|
| 369 |
+
networkx/algorithms/tests/test_triads.py,sha256=CbnFABCMDU0X1mzu3tzW4-WL2qn5ptaDTOShNaTjIwk,8219
|
| 370 |
+
networkx/algorithms/tests/test_vitality.py,sha256=p5lPWCtVMtbvxDw6TJUaf8vpb0zKPoz5pND722xiypQ,1380
|
| 371 |
+
networkx/algorithms/tests/test_voronoi.py,sha256=M4B6JtkJUw56ULEWRs1kyVEUsroNrnb5FBq9OioAyHM,3477
|
| 372 |
+
networkx/algorithms/tests/test_walks.py,sha256=X8cb-YvGHiiqbMEXuKMSdTAb9WtVtbHjIESNSqpJTmU,1499
|
| 373 |
+
networkx/algorithms/tests/test_wiener.py,sha256=uT6Es_OFbJqxnVY7lImzlJSRTQS4eJnMaKotKbObMd8,4186
|
| 374 |
+
networkx/algorithms/threshold.py,sha256=maOMixTxDibvBL2BkVcaYz1Co_09jg8d7DpAW2blNnY,30776
|
| 375 |
+
networkx/algorithms/time_dependent.py,sha256=PAeJ7Yt8kUqbDgvBaz_ZfUFZg-w-vf1gPC0HO6go_TI,5762
|
| 376 |
+
networkx/algorithms/tournament.py,sha256=TyWD0P-8JYXsckulbyr-bkKOoc0gLUHK59R1RQm2We4,11613
|
| 377 |
+
networkx/algorithms/traversal/__init__.py,sha256=YtFrfNjciqTOI6jGePQaJ01tRSEQXTHqTGGNhDEDb_8,142
|
| 378 |
+
networkx/algorithms/traversal/beamsearch.py,sha256=Vn0U4Wck8ICShIAGggv3tVtQWVW0ABEz_hcBsGrql6o,3473
|
| 379 |
+
networkx/algorithms/traversal/breadth_first_search.py,sha256=KGpFnXuCQrDwcQg27Irtrqu7hcIWlFSlVWGpA26XbHA,18259
|
| 380 |
+
networkx/algorithms/traversal/depth_first_search.py,sha256=2V4T3tGujcAtV3W6WcTQUjGAAe3b1rqinONowUhLsa8,16795
|
| 381 |
+
networkx/algorithms/traversal/edgebfs.py,sha256=JJ1mQCmv8WydqQtIVQC1HqkqEFDMeKVzJ_hexwU8sXA,6333
|
| 382 |
+
networkx/algorithms/traversal/edgedfs.py,sha256=T1xHGr8p_eC1pEUyCP-kpaYlIY_la_ms-J0-50c4EDk,6041
|
| 383 |
+
networkx/algorithms/traversal/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 384 |
+
networkx/algorithms/traversal/tests/test_beamsearch.py,sha256=bzUcswZ1qo0ecDZYSER_4enbsW6SjTpb_3Nb3fqmkAo,900
|
| 385 |
+
networkx/algorithms/traversal/tests/test_bfs.py,sha256=tGQSiYhc6BxaZEuw-G3ZxVfYLN7q0zrP_BeKl6EfxkU,6447
|
| 386 |
+
networkx/algorithms/traversal/tests/test_dfs.py,sha256=rQMq7GToM6CVU3WwIZfmqa-HrqlmvIT1DryRU7NbU_U,10580
|
| 387 |
+
networkx/algorithms/traversal/tests/test_edgebfs.py,sha256=8oplCu0fct3QipT0JB0-292EA2aOm8zWlMkPedfe6iY,4702
|
| 388 |
+
networkx/algorithms/traversal/tests/test_edgedfs.py,sha256=HGmC3GUYSn9XLMHQpdefdE6g-Uh3KqbmgEEXBcckdYc,4775
|
| 389 |
+
networkx/algorithms/tree/__init__.py,sha256=wOh_v70XEdFHL2qUMje7qkJI5RcjFNrDremJYl4zzkg,182
|
| 390 |
+
networkx/algorithms/tree/branchings.py,sha256=B0c_uKpcnV2SwJMZJRK0BMEz8LkvIcOhv1y0AI0gTnY,34339
|
| 391 |
+
networkx/algorithms/tree/coding.py,sha256=l9P4jhmhg_9uYBVMNSmLYW8btHJH07-Sl2SIKJtO1LA,13466
|
| 392 |
+
networkx/algorithms/tree/decomposition.py,sha256=lY_rqx9JxnLEkp1wiAv0mX62PGPwGQ6SW4Jp48o8aiw,3071
|
| 393 |
+
networkx/algorithms/tree/distance_measures.py,sha256=Dwtk2BRTXmEGjFFtpiAbk02HrX2Hb5kjXusfwn6nm9M,6981
|
| 394 |
+
networkx/algorithms/tree/mst.py,sha256=UMeSnnpKrPeq7a_w_tR415w9TOLltmzuXyIy_HfqbAU,46145
|
| 395 |
+
networkx/algorithms/tree/operations.py,sha256=TjfLQpxwlaLgdOnhLkdzHfZ68yFCYz6BMzzh_d_2mJc,4048
|
| 396 |
+
networkx/algorithms/tree/recognition.py,sha256=bYnaDN0ZaIWTgq0tbPEHAcdxQBWZpDvWypZarBbA334,7569
|
| 397 |
+
networkx/algorithms/tree/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 398 |
+
networkx/algorithms/tree/tests/test_branchings.py,sha256=euky-3tFOV5CVV5v_yFawuVGCaqTuTrKtBIkCygwhiA,17731
|
| 399 |
+
networkx/algorithms/tree/tests/test_coding.py,sha256=XC6SbfA2zVGH4FyJJyv6o8eOnBu7FNzNot3SKs7QmEo,3955
|
| 400 |
+
networkx/algorithms/tree/tests/test_decomposition.py,sha256=vnl_xoQzi1LnlZL25vXOZWwvaWmon3-x222OKt4eDqE,1871
|
| 401 |
+
networkx/algorithms/tree/tests/test_distance_measures.py,sha256=WNzqjgDuFLUt_NgjD4R8gGhbYhQ3F5a4HZfBBipunv0,3389
|
| 402 |
+
networkx/algorithms/tree/tests/test_mst.py,sha256=D3o217cjuUtf0TxZ9ks1wqQ4cpwVySoOBYfg0Jmr1AU,32376
|
| 403 |
+
networkx/algorithms/tree/tests/test_operations.py,sha256=ybU96kROTVJRTyjLG7JSJjYlPxaWmYjUVJqbXV5VGGI,1961
|
| 404 |
+
networkx/algorithms/tree/tests/test_recognition.py,sha256=qeMEIvg-j2MqaU-TNIQhCcXxao8vTBy0wjpU7jr2iw8,4521
|
| 405 |
+
networkx/algorithms/triads.py,sha256=FqOtB5fi40k4EoA_-bV1TBwimsRihAqrVdFyNnq0hns,14233
|
| 406 |
+
networkx/algorithms/vitality.py,sha256=8M1cubIydO49El2kwVCURHZ2UwCtfGVFeGS8-JYt1ko,2289
|
| 407 |
+
networkx/algorithms/voronoi.py,sha256=07SnSpxLDz4k6K59Jo-VTNA-Qy5knaHfBC-y_5vAOLQ,3183
|
| 408 |
+
networkx/algorithms/walks.py,sha256=5A611YwX9D8IZYbFcQ4aT3cuKZWHq1QOzCpy4mAM6XE,2312
|
| 409 |
+
networkx/algorithms/wiener.py,sha256=88sTSCXt6gakAmxP4BD_ir1R-_0NOUxXlyZKeElzzvs,9221
|
| 410 |
+
networkx/classes/__init__.py,sha256=Q9oONJrnTFs874SGpwcbV_kyJTDcrLI69GFt99MiE6I,364
|
| 411 |
+
networkx/classes/coreviews.py,sha256=5Dgi8PjMZJz_Uun2SXL5a6mxtAfdbm3kPIdbgzSTXgM,13251
|
| 412 |
+
networkx/classes/digraph.py,sha256=ys8hmrqUjto00TDwBNCwiaNAahFbizNvKkkx84BxS30,48781
|
| 413 |
+
networkx/classes/filters.py,sha256=PCy7BsoIby8VcamqDjZQiNAe_5egI0WKUq-y5nc9unQ,2817
|
| 414 |
+
networkx/classes/function.py,sha256=pPpy-TgC33yNX3nPMZoSjfVmaiiSTbfwYJJMFGa35hQ,43794
|
| 415 |
+
networkx/classes/graph.py,sha256=bY5x7WQHoQxSZow95OUAmU8UZaYV0ZWQvhrEFjSAt0Y,72337
|
| 416 |
+
networkx/classes/graphviews.py,sha256=ulUTLozEK_hj_4TGHdgvxveR2-rb92Q14jjxH4oH4Go,8520
|
| 417 |
+
networkx/classes/multidigraph.py,sha256=qBhb2eoiMejz5fkv-ihLsqwQKKYnUjUANHnrWZKYQfI,37036
|
| 418 |
+
networkx/classes/multigraph.py,sha256=7SD8_ZT7yE1EfIotDzIgITSj4HkKLxZfj6ZnWjQ7hIA,47931
|
| 419 |
+
networkx/classes/reportviews.py,sha256=u0hNZqaWXCfLMP_lq835XCIVStkZQJ9HaQPeDPPoo88,46132
|
| 420 |
+
networkx/classes/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 421 |
+
networkx/classes/tests/dispatch_interface.py,sha256=gffiIwS4OZWKIgRkfvghixQds5hY0tPBi86p0lpV7eY,6823
|
| 422 |
+
networkx/classes/tests/historical_tests.py,sha256=oUJSS-QhvInhad9AJCXCCk0x7OzAclIF9RjBSZ6gB58,16291
|
| 423 |
+
networkx/classes/tests/test_coreviews.py,sha256=qzdozzWK8vLag-CAUqrXAM2CZZwMFN5vMu6Tdrwdf-E,12128
|
| 424 |
+
networkx/classes/tests/test_digraph.py,sha256=uw0FuEu3y_YI-PSGuQCRytFpXLF7Eye2fqLJaKbXkBc,12283
|
| 425 |
+
networkx/classes/tests/test_digraph_historical.py,sha256=8TbDcvmLgfllfGomTRStSpT5WIQiTHLt-rS3GyJEItU,3668
|
| 426 |
+
networkx/classes/tests/test_filters.py,sha256=fBLig8z548gsBBlQw6VJdGZb4IcqJj7_0mi2Fd2ncEM,5851
|
| 427 |
+
networkx/classes/tests/test_function.py,sha256=PDtKrB31Ix1-abPc8NzuP-h7HOOIRtkL5bvcOE8mshU,35481
|
| 428 |
+
networkx/classes/tests/test_graph.py,sha256=ST12bvoj72uzUDpnyVz-Zx0mlXV2CegcEg3txT5qS6k,31798
|
| 429 |
+
networkx/classes/tests/test_graph_historical.py,sha256=EVAndjelyyZ9laQCTrj6KR6lhdmG8Y1raP2IrxkZxdA,258
|
| 430 |
+
networkx/classes/tests/test_graphviews.py,sha256=JoTS_ZY7u4dBHEttD55WT1pD47FcvELBEzw-uJQiqv4,11496
|
| 431 |
+
networkx/classes/tests/test_multidigraph.py,sha256=ryTKegCoYixXbAqOn3mIt9vSMb5666Dv-pfMkXEjoUE,16342
|
| 432 |
+
networkx/classes/tests/test_multigraph.py,sha256=0vFQO3RCJaBpzXvnQzdWa_qYLHNo_I9DICYhPZJNUMk,18777
|
| 433 |
+
networkx/classes/tests/test_reportviews.py,sha256=MgP9_cKlw4aTU5m1XbsNTM3ZjmO7roOOf-7x-Hn9xKs,41332
|
| 434 |
+
networkx/classes/tests/test_special.py,sha256=wl-Idzdc55eOQ4Tn5SNqOG21AjwLb2TTp9x102Qx3Ms,4053
|
| 435 |
+
networkx/classes/tests/test_subgraphviews.py,sha256=iIMkbHdtJsgDlcdphhE_uUTJ0VGTGFzKIVvMd7oamoU,13669
|
| 436 |
+
networkx/conftest.py,sha256=5-BwqVMgfaZyRZICFpG1plLMJ2G1IchSQVEuRjoBtyc,8041
|
| 437 |
+
networkx/convert.py,sha256=Xmkhacuyw9CDviBTZPlH6nmD-JabSk0aPcVmGgp4LeY,16143
|
| 438 |
+
networkx/convert_matrix.py,sha256=9BXSEXzCEIte1nx8f35cWhXo-EVYjOkuW4H3Jutq-oE,45342
|
| 439 |
+
networkx/drawing/__init__.py,sha256=rnTFNzLc4fis1hTAEpnWTC80neAR88-llVQ-LObN-i4,160
|
| 440 |
+
networkx/drawing/layout.py,sha256=5MUr2NTp4L3IbOShTb_m7fD4SH1HPZKJPJ4G1mJC3Js,66346
|
| 441 |
+
networkx/drawing/nx_agraph.py,sha256=4Vd8JQH4BQ7BaRO8TmYlqBKmFPm8e2XcDDJiqFkNMxM,14248
|
| 442 |
+
networkx/drawing/nx_latex.py,sha256=PySHixo2YhGV0xbKLroaX-_XcI1L5u8IF8nP6xdV2NU,24846
|
| 443 |
+
networkx/drawing/nx_pydot.py,sha256=9KbNVrVcU5gFmo1GPpB_UMBXcD1tnBYDBzxHvgg6mOs,9992
|
| 444 |
+
networkx/drawing/nx_pylab.py,sha256=MHoDvYE4FO9kJRogqeB1FfqrStyLcjQTq3fr67vAjOE,103488
|
| 445 |
+
networkx/drawing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 446 |
+
networkx/drawing/tests/baseline/test_display_complex.png,sha256=3YPN6JEuyq1KEpRgSnH-2yECI81frU_5fw0VxHlwo9A,142315
|
| 447 |
+
networkx/drawing/tests/baseline/test_display_empty_graph.png,sha256=XsOkBCZlt-55c40ElwEapBENVfmdc4TZKIF1ufs5Dzk,3257
|
| 448 |
+
networkx/drawing/tests/baseline/test_display_house_with_colors.png,sha256=uiEx6_2RddHG-516OsRVM0AG7M5CGiAo4tpDgbgPKIU,26002
|
| 449 |
+
networkx/drawing/tests/baseline/test_display_labels_and_colors.png,sha256=RfA1OtWYKttP5_LDScIcx8MFbC-_5wljXeDsZAqAqDU,62571
|
| 450 |
+
networkx/drawing/tests/baseline/test_display_shortest_path.png,sha256=6W7EMitF8jojJ8epmaYEWpjhYRlzBlL7QV98MStxvvQ,35264
|
| 451 |
+
networkx/drawing/tests/baseline/test_house_with_colors.png,sha256=FQi9pIRFwjq4gvgB8cDdBHL5euQUJFw6sQlABf2kRVo,21918
|
| 452 |
+
networkx/drawing/tests/test_agraph.py,sha256=5cbqLGEgJmAocWOMSikv_9ykRWfBymjGfalvKbR1_KE,8725
|
| 453 |
+
networkx/drawing/tests/test_image_comparison_pylab_mpl.py,sha256=2UtGMJFpcWiG0sQtXIYT0j03Q2LhGqWM2G-pfKY3Sw0,6340
|
| 454 |
+
networkx/drawing/tests/test_latex.py,sha256=YQjLxsZnx7_CX2sJ3nN0cUiJzC7p6UhyFN6ufbox5G0,8621
|
| 455 |
+
networkx/drawing/tests/test_layout.py,sha256=2_wJfBcCcHwBm1JRrQiLMcnNWoaURX6F4LFcn5OPul4,23709
|
| 456 |
+
networkx/drawing/tests/test_pydot.py,sha256=X9b66gWqMgdTEyRJ7Zmy5kL9cr22waI688K9BJUf4Bk,4973
|
| 457 |
+
networkx/drawing/tests/test_pylab.py,sha256=TMGpM6IKm5vTSu9Dbfm8mvyhMqz2aAu1gafGbLiOU1k,54825
|
| 458 |
+
networkx/exception.py,sha256=hC8efPfIzOFo0jiWiQbTPaNKuNTuUwhp9RPw--pdv4U,3787
|
| 459 |
+
networkx/generators/__init__.py,sha256=EoYB5c5ZE4rsNKZvl1TRQy2Vo2D3T2H-YunyD2i6sa0,1366
|
| 460 |
+
networkx/generators/atlas.dat.gz,sha256=c_xBbfAWSSNgd1HLdZ9K6B3rX2VQvyW-Wcht47dH5B0,8887
|
| 461 |
+
networkx/generators/atlas.py,sha256=cbki_oYDi_7vniSesqJZ-PCEM3BvnzEdjSc3TA3s1xc,6955
|
| 462 |
+
networkx/generators/classic.py,sha256=Wzey-Pl6Rm-ELYyg2lIb0lFZAxywRr5iQxv7zo3d9Bk,32658
|
| 463 |
+
networkx/generators/cographs.py,sha256=-WR4_yrNk_X5nj7egb7A22eKPVymOdIYM-IftSRH4WA,1891
|
| 464 |
+
networkx/generators/community.py,sha256=_p_4OfItbg8nS0b3EvojCXZ8cESdC-0Gj67V5w2veuM,34911
|
| 465 |
+
networkx/generators/degree_seq.py,sha256=Hxv1rjY2NS8qmnvSWh4rcvublDZzor3D3IiB2OAFXoE,30493
|
| 466 |
+
networkx/generators/directed.py,sha256=rtgf2Imf34SogrWA0BNgDltlA5kUv_l2NkxKPcJgGtQ,18149
|
| 467 |
+
networkx/generators/duplication.py,sha256=hmYAHJBez7WlfdVGGa288JFUBHoIUdVqEGCodApKOr4,5831
|
| 468 |
+
networkx/generators/ego.py,sha256=ylW-UMvg9C8cqygw9vrBNLGAVZJT4U5EWbU4gaT_H1g,1894
|
| 469 |
+
networkx/generators/expanders.py,sha256=gJioNdyhBOnNcjh0qC-kfbFs1SEMU5_o9GHy85pdJXk,15184
|
| 470 |
+
networkx/generators/geometric.py,sha256=6slgS0vraxql67AOP9lWzBrpNbx_OBZCoBwYuSkQQXg,39461
|
| 471 |
+
networkx/generators/harary_graph.py,sha256=N2_b49xrET0bjZ4C7sgcG2xLv64ia9xjvJ2NB75CAz8,4950
|
| 472 |
+
networkx/generators/internet_as_graphs.py,sha256=RuhEW9rQ8f5VzeIyZe6GqSWgxKtMVuwqnzv0llW3FeY,14226
|
| 473 |
+
networkx/generators/intersection.py,sha256=EFm0AOjnqyp8KcT7kGWqANq-_vq9kQ0d_0DzVyQyP-o,4101
|
| 474 |
+
networkx/generators/interval_graph.py,sha256=ZTmdgQbBx3M6sysGWXbGyngYYOC1TAXD3Ozkw4deQFw,2204
|
| 475 |
+
networkx/generators/joint_degree_seq.py,sha256=nyp86NC_4XvzvwpwwzKrrCSz1i_4bESSDtVjWvpkWFg,24773
|
| 476 |
+
networkx/generators/lattice.py,sha256=5iujIY5pF_VhbWEE2osM5i7uuYqs5Hv1wS33WGPMn_o,14740
|
| 477 |
+
networkx/generators/line.py,sha256=DDQZvD2Y2c-4kc_xTuUWpmmViLftTSGKFukgqSiyI_c,17540
|
| 478 |
+
networkx/generators/mycielski.py,sha256=xBX2m77sCzumoH5cAGitksvEEW-ocbCnbdaN7fKUtVk,3314
|
| 479 |
+
networkx/generators/nonisomorphic_trees.py,sha256=62FIt4Qx-giwDflNKP5BrDoCv1HbQmlp6oVGjqGeRlE,6993
|
| 480 |
+
networkx/generators/random_clustered.py,sha256=i_NdvvchHvsvbwgQtoWSY_pLwvhO9Lh02MSZXzgGb7c,4183
|
| 481 |
+
networkx/generators/random_graphs.py,sha256=WIJ4v8PSNpHePclSCQ3IcLWwcipZJ2Cn9pNx6XenBEo,51669
|
| 482 |
+
networkx/generators/small.py,sha256=duBVJgz4f2TByU4SdyRGHw7YyLHrlrr0UFw6spVTCbo,30967
|
| 483 |
+
networkx/generators/social.py,sha256=brzAScpAxWGRExE9J7FuiJ29QZxBm8bXpRgCc0IoHP0,23416
|
| 484 |
+
networkx/generators/spectral_graph_forge.py,sha256=9r6d9f5Y03KPX138sQTKWG3_RjeiYQVUJJWwCHqG4MA,4282
|
| 485 |
+
networkx/generators/stochastic.py,sha256=Qg9vWm9EOug2OQVIHL_dZ5HrXc16lxnWyzX52KWNEPI,1981
|
| 486 |
+
networkx/generators/sudoku.py,sha256=kLM2AP0H4966uYiNO1oAFEmv5qBftU_bOfYucRxexM0,4288
|
| 487 |
+
networkx/generators/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 488 |
+
networkx/generators/tests/test_atlas.py,sha256=nwXJL4O5jUqhTwqhkPxHY8s3KXHQTDEdsfbg4MsSzVQ,2530
|
| 489 |
+
networkx/generators/tests/test_classic.py,sha256=eRtftt3fcr5kYJI8PffuY3tWOnn4u0yJZwKav1bZACU,24400
|
| 490 |
+
networkx/generators/tests/test_cographs.py,sha256=v2fYoolmfwfCpJZRKRtH9YKyWcuJkaPOQUpDK9DMsn0,553
|
| 491 |
+
networkx/generators/tests/test_community.py,sha256=FGcDo3Ajb-yYc5kUkFbVfOJVMG-YppbAtjgBPcVzjLc,11311
|
| 492 |
+
networkx/generators/tests/test_degree_seq.py,sha256=V_X-Mc0H2sqEy7OTJb4yY9khsi-9HD-DIA_fvngW-VE,7284
|
| 493 |
+
networkx/generators/tests/test_directed.py,sha256=e8C7AF2whjaqdxga7WSvCrtIx7ByBG_JyJ9gYqJ6HBA,6020
|
| 494 |
+
networkx/generators/tests/test_duplication.py,sha256=UdIGDF_fishanWid1xO_aH4NDfie8xpIqd26qndhOqI,3155
|
| 495 |
+
networkx/generators/tests/test_ego.py,sha256=8v1Qjmkli9wIhhUuqzgqCzysr0C1Z2C3oJMCUoNvgY4,1327
|
| 496 |
+
networkx/generators/tests/test_expanders.py,sha256=Cf0cCJOplngPlN23OVqDcrny2QZlrYMrrWHeIi0APaA,6363
|
| 497 |
+
networkx/generators/tests/test_geometric.py,sha256=gnVm4dam_Er88YwaNpNZC6mjJjfgwMYhyLOtU9oPn1o,18087
|
| 498 |
+
networkx/generators/tests/test_harary_graph.py,sha256=GiX5LXXJaNxzjvd-Nyw_QuARzbFGkA6zE1R1eX8mclw,4936
|
| 499 |
+
networkx/generators/tests/test_internet_as_graphs.py,sha256=3et6aawAPZ9bPNWqADJ3bQN_2KhyqPf8VFgrBAkgABQ,8514
|
| 500 |
+
networkx/generators/tests/test_intersection.py,sha256=hcIit5fKfOn3VjMhz9KqovZK9tzxZfmC6ezvA7gZAvM,819
|
| 501 |
+
networkx/generators/tests/test_interval_graph.py,sha256=JYMi-QMkJQdBU9uOdfm0Xr6MEYqIbhU5oSDa6D3tSb0,4277
|
| 502 |
+
networkx/generators/tests/test_joint_degree_seq.py,sha256=8TXTZI3Um2gBXtP-4yhGKf9vCi78-NVmWZw9r9WG3F8,4270
|
| 503 |
+
networkx/generators/tests/test_lattice.py,sha256=iYB2F7j1Qt3QAHkhGnGKcgiRNB1Gq9MxtE3152XdS_A,10102
|
| 504 |
+
networkx/generators/tests/test_line.py,sha256=Dt1R1Hnm47aq_8FX9gRFdby0sV3Oxyap1R5Z4eK0A5o,10516
|
| 505 |
+
networkx/generators/tests/test_mycielski.py,sha256=fwZLO1ybcltRy6TzCel8tPBil1oZWv9QSXs779H6Xt0,946
|
| 506 |
+
networkx/generators/tests/test_nonisomorphic_trees.py,sha256=KFRwMfx-x_a9oGvPlhtMlWGk__rKgm77Gk4LtbxFrZE,2945
|
| 507 |
+
networkx/generators/tests/test_random_clustered.py,sha256=SalHqWvpnXA3QrDRMjLx15dk2c4Us8Ck52clUERoUI8,1297
|
| 508 |
+
networkx/generators/tests/test_random_graphs.py,sha256=R5dHYuzAbcIBduoP7PUdoV-6CFauqk5r1Ak1Slwlsho,19565
|
| 509 |
+
networkx/generators/tests/test_small.py,sha256=y9rZHpwQG4Bjp-sHJp18rM3A0uEGOUkbklqlJec11ao,8074
|
| 510 |
+
networkx/generators/tests/test_spectral_graph_forge.py,sha256=x4jyTiQiydaUPWYaGsNFsIB47PAzSSwQYCNXGa2B4SU,1594
|
| 511 |
+
networkx/generators/tests/test_stochastic.py,sha256=f-5KD3RpoQf369gXHH7KGebE19g5lCkXR_alcwmFm_s,2179
|
| 512 |
+
networkx/generators/tests/test_sudoku.py,sha256=dgOmk-B7MxCVkbHdZzsLZppQ61FAArVy4McSVL8Afzo,1968
|
| 513 |
+
networkx/generators/tests/test_time_series.py,sha256=rgmFcitlKa_kF6TzJ2ze91lSmNJlqjhvgrYet0AUZx8,2230
|
| 514 |
+
networkx/generators/tests/test_trees.py,sha256=Pvh0MvTKaRuZuwWL-wpJIC0zlBAcnTirpSLJi-9c7qc,7006
|
| 515 |
+
networkx/generators/tests/test_triads.py,sha256=K8anVEP8R90Y172IrKIOrYRWRJBGeqxNqU9isX7Ybxs,333
|
| 516 |
+
networkx/generators/time_series.py,sha256=_DMiY9X95O_9sK2BSeeTb2yMWfStBwKFWwn6FUOXN4Q,2439
|
| 517 |
+
networkx/generators/trees.py,sha256=KvKYhZwwSl1KKMyKBe_6G_UTpLwLLeqdWwRkWJ2Xxz4,36517
|
| 518 |
+
networkx/generators/triads.py,sha256=7kScTf3ITDi3qsSa-IvGMpa9diEaFwQnRuIf3Tv4UBI,2452
|
| 519 |
+
networkx/lazy_imports.py,sha256=pZWn3f6NCY-lGtViKQh11NJ5Cn-cXBKhvacMycg3844,5764
|
| 520 |
+
networkx/linalg/__init__.py,sha256=7iyNZ_YYBnlsW8zSfhUgvEkywOrUWfpIuyS86ZOKlG8,568
|
| 521 |
+
networkx/linalg/algebraicconnectivity.py,sha256=qAjHk8Ew2av9HM-Sevf99alKHWkeo4R76U-1SFn2so8,20790
|
| 522 |
+
networkx/linalg/attrmatrix.py,sha256=gG2cZZm4N7PQhXuq5nxZq1S_OmW61641rdRnrDiX_ws,15900
|
| 523 |
+
networkx/linalg/bethehessianmatrix.py,sha256=Q5dJZOMopwWnvpSdebfo9QSQABEmLy-z1_hGCWsopDo,2513
|
| 524 |
+
networkx/linalg/graphmatrix.py,sha256=NIs2uWGS_8lJJ5IQ8Og9aIWHawghtlCDWifqOIKV2-c,5623
|
| 525 |
+
networkx/linalg/laplacianmatrix.py,sha256=YrzwLTLoGIisJVS2NLaD9g4fA3VDKzlYo1u3yOCVrF4,16722
|
| 526 |
+
networkx/linalg/modularitymatrix.py,sha256=R_VITtgIkGenxlsCLN4u6CYxj3_HiPXfeU29yarntRo,4706
|
| 527 |
+
networkx/linalg/spectrum.py,sha256=aRY7ApYv5HxrO_4O8brxpZRw3SJU3fYzlgMwhEIXcrc,4215
|
| 528 |
+
networkx/linalg/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 529 |
+
networkx/linalg/tests/test_algebraic_connectivity.py,sha256=uXq7h1fCmvcUyJhh3DujyZvJH2SGlgo-JRdLbff3bKI,13735
|
| 530 |
+
networkx/linalg/tests/test_attrmatrix.py,sha256=I8p_ME5Cq__SZJoxla1y5ynGaa_b4UruZRcuzPOh_wE,2833
|
| 531 |
+
networkx/linalg/tests/test_bethehessian.py,sha256=WQM3H_y1GWrtM2B659HYQ2vvYGs-4H9V1qeo3Bx75B4,1268
|
| 532 |
+
networkx/linalg/tests/test_graphmatrix.py,sha256=6y-DSezX5slSms8LtEJcoggI4wP_duBqodNYWKKvM4w,8655
|
| 533 |
+
networkx/linalg/tests/test_laplacian.py,sha256=sIJ64KVVCUcK3b4ohF-443222vR64myIlV6addwwfWs,13953
|
| 534 |
+
networkx/linalg/tests/test_modularity.py,sha256=Xs7iaUr_QqcxG0t0xHx54iYbM2VyQNmFeANovTMJomE,3056
|
| 535 |
+
networkx/linalg/tests/test_spectrum.py,sha256=Hrl3FE0Z0u4urwY5eNMx0VcH4IRTYgudT04EmfhkosA,2769
|
| 536 |
+
networkx/readwrite/__init__.py,sha256=TvSbnGEHQ5F9CY2tkpjWYOyrUj6BeW3sc6P4_IczbKA,561
|
| 537 |
+
networkx/readwrite/adjlist.py,sha256=XkmtOO-aP-BGLoIjMoSXEOhCIEQz1TJcSrhMHGPCJTc,9050
|
| 538 |
+
networkx/readwrite/edgelist.py,sha256=XwemCOs-xNet3mVIGpxol3RgFVJVa1iXsgBonAHDmug,14292
|
| 539 |
+
networkx/readwrite/gexf.py,sha256=B5rj7Ra1XHSZR4qO5DRJMAEgWwQfiL0IKlE85fzQZ5Q,40438
|
| 540 |
+
networkx/readwrite/gml.py,sha256=JcP0hsDKwpZOPzZeXdoEiKBBNd94Ox8y7_cjT5AVBT4,31193
|
| 541 |
+
networkx/readwrite/graph6.py,sha256=dED6yWelHARFvyKniX8xSTtqj1-asDs1vUBWuZOG9cA,11684
|
| 542 |
+
networkx/readwrite/graphml.py,sha256=sb-D5I5gmqyNj_TSNUvLn-96NBXtOAPFMEKvT3mkdTw,39326
|
| 543 |
+
networkx/readwrite/json_graph/__init__.py,sha256=37XJPMmilcwwo8KqouLWUly7Yv5tZ7IKraMHbBRx3fI,677
|
| 544 |
+
networkx/readwrite/json_graph/adjacency.py,sha256=WM6fdncV87WDLPOfF-IbOlOOBMX0utUjJ09UsxtwRAo,4716
|
| 545 |
+
networkx/readwrite/json_graph/cytoscape.py,sha256=NaHGbwLuQCx_GB5R7Uag2ACKSmrpCFQKsRk3y9hE6Io,5841
|
| 546 |
+
networkx/readwrite/json_graph/node_link.py,sha256=9hr4sk2fIHYDPuwSyyGNLNKDhahf6aFAEsIRhd5V890,7850
|
| 547 |
+
networkx/readwrite/json_graph/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 548 |
+
networkx/readwrite/json_graph/tests/test_adjacency.py,sha256=jueQE3Z_W5BZuCjr0hEsOWSfoQ2fP51p0o0m7IcXUuE,2456
|
| 549 |
+
networkx/readwrite/json_graph/tests/test_cytoscape.py,sha256=vFoDzcSRI9THlmp4Fu2HHhIF9AUmECWs5mftVWjaWWs,2044
|
| 550 |
+
networkx/readwrite/json_graph/tests/test_node_link.py,sha256=3RbMNRlLBLN86EG4YyCvNmA3ISzmECqr17EqTcov3kI,3364
|
| 551 |
+
networkx/readwrite/json_graph/tests/test_tree.py,sha256=zBXv3_db2XGxFs3XQ35btNf_ku52aLXXiHZmmX4ixAs,1352
|
| 552 |
+
networkx/readwrite/json_graph/tree.py,sha256=K4rF4Kds4g0JhgcPTrrR_I3Pswpze8yCVH4M-WF9nn0,3851
|
| 553 |
+
networkx/readwrite/leda.py,sha256=mtuIRKecfykiInePt-oIw91JB1vIgNXuUEbuBInO7Hs,2852
|
| 554 |
+
networkx/readwrite/multiline_adjlist.py,sha256=TyvVZih3DIYaCQ6MC7XF8GuGBfcYIX-q-ccYu2Qs05M,11384
|
| 555 |
+
networkx/readwrite/p2g.py,sha256=wDPg_3u42rlsv8pFtVLbZIjo-BN6dd95jCxFAoEC_6E,3253
|
| 556 |
+
networkx/readwrite/pajek.py,sha256=0Xli27YbjyW5Ny6-qqVOtBmhZkPj4i3cJPvwjU3mMjM,8746
|
| 557 |
+
networkx/readwrite/sparse6.py,sha256=kGEbDmnK1qcR5I6LZnPKYXLe7Qp6esT6gftkwSt1xcs,10442
|
| 558 |
+
networkx/readwrite/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 559 |
+
networkx/readwrite/tests/test_adjlist.py,sha256=aCDyLpv8cekWwEZgv5rB4gtwUvor7_YDArTYvL2ngPs,12756
|
| 560 |
+
networkx/readwrite/tests/test_edgelist.py,sha256=5_rZ5rI_o8VDJr-R4besR-XcPwKY8-dHn4VmrrlBorc,10190
|
| 561 |
+
networkx/readwrite/tests/test_gexf.py,sha256=TJLCj0ULSewUt5PlqEuoD8yhZoc6jFPqElIyQYhoKz0,21327
|
| 562 |
+
networkx/readwrite/tests/test_gml.py,sha256=SIuCCSoH9psZdjKkrJfdGHbMROhUsfms70B71rnozUU,21399
|
| 563 |
+
networkx/readwrite/tests/test_graph6.py,sha256=WMQmTgrI_VDcli1Gl5cjM17EFKc8_AkwoR14FLS1sXQ,6559
|
| 564 |
+
networkx/readwrite/tests/test_graphml.py,sha256=RHZqs_-0Vw_NboMK1Sq65Nmk_XPAjfvnsgiPCptnpnI,67633
|
| 565 |
+
networkx/readwrite/tests/test_leda.py,sha256=_5F4nLLQ1oAZQMZtTQoFncZL0Oc-IsztFBglEdQeH3k,1392
|
| 566 |
+
networkx/readwrite/tests/test_p2g.py,sha256=0kvtohQuM2zjw88ogoDMhVbFcm85R3Sk2_yFdQ7TcWg,1319
|
| 567 |
+
networkx/readwrite/tests/test_pajek.py,sha256=VxMk_TXQE1R-2t2B2OTSkwvPepKNYwExDbdlTDb0SOM,4696
|
| 568 |
+
networkx/readwrite/tests/test_sparse6.py,sha256=zpd0hUPtOqwAJiuke4FXWFaQVa6Fa47dgIdHpCWXQ6U,5288
|
| 569 |
+
networkx/readwrite/tests/test_text.py,sha256=x1N97hD31HPkj9Wn2PYti5-gcwaFNnStkaN_38HKnIg,55319
|
| 570 |
+
networkx/readwrite/text.py,sha256=u62a-zG_7NpJD4Bh6kBZbUntORVM4XZId9zGX9wJBGQ,29140
|
| 571 |
+
networkx/relabel.py,sha256=0HptAQOBToKhLZzxscd6FQpzVCNMlYmiHjHul69ct8o,10300
|
| 572 |
+
networkx/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 573 |
+
networkx/tests/test_all_random_functions.py,sha256=T6bYvfqCmBfqOHAAJAqCv95VceTqdT32cN740HZTWH0,8549
|
| 574 |
+
networkx/tests/test_convert.py,sha256=SoIVrqJFF9Gu9Jff_apfbpqg8QhkfC6QW4qzoSM-ukM,12731
|
| 575 |
+
networkx/tests/test_convert_numpy.py,sha256=wivMBF5pmDd2FdrHX72J4Xt26IxTIfb12G-t-TWch40,19032
|
| 576 |
+
networkx/tests/test_convert_pandas.py,sha256=VXumRYNIV2jdr4dfDsRidqpUDXHlgbhAFhaiqWlcx6s,13361
|
| 577 |
+
networkx/tests/test_convert_scipy.py,sha256=IO9Xfke5Vk0SC4c7UR4YbQMjVZBuADQBt_wlMaOxTSQ,10381
|
| 578 |
+
networkx/tests/test_exceptions.py,sha256=XYkpPzqMepSw3MPRUJN5LcFsUsy3YT_fiRDhm0OeAeQ,927
|
| 579 |
+
networkx/tests/test_import.py,sha256=Gm4ujfH9JkQtDrSjOlwXXXUuubI057wskKLCkF6Z92k,220
|
| 580 |
+
networkx/tests/test_lazy_imports.py,sha256=PylxEvRtD8ekwH-1M1sjnV_4uyhCYQl4WvlyF6ah0wo,2675
|
| 581 |
+
networkx/tests/test_relabel.py,sha256=2qua3Z45m9mXkBQYmD82h17-pK6fYHJLpntn6ILj9cg,14554
|
| 582 |
+
networkx/tests/test_removed_functions_exception_messages.py,sha256=V6AyU-RHQmilakEMJ1kpK4HSgzKbmimIxu0pBQ1DVaY,177
|
| 583 |
+
networkx/utils/__init__.py,sha256=7pxleRNpBWuL3FEQz3CzKLn17b6_eSwkM7dqnL1okDk,302
|
| 584 |
+
networkx/utils/backends.py,sha256=IDXNJjBWOfcqPm3Any5-kfwU9hZTH33R16gr3vZ6wnE,96862
|
| 585 |
+
networkx/utils/configs.py,sha256=1LFNHgkR6CdXxTpNT8j4QdQ5vn5r7BTzPlxFYrEm7_E,15440
|
| 586 |
+
networkx/utils/decorators.py,sha256=rRgAZw6glxOBYN6n5kkbQ7RS43EH3eVbJ5F91-uk0IM,44713
|
| 587 |
+
networkx/utils/heaps.py,sha256=98tdylWKqrLQKdNlpjT2NvIpuOF2mT2Lhh5OzVg3Hu8,10355
|
| 588 |
+
networkx/utils/mapped_queue.py,sha256=WdIRk27D_ArmPs9tdpvQLQCV4Tmus212BQhxsFIMYgk,10184
|
| 589 |
+
networkx/utils/misc.py,sha256=zifBxwKM3msQsmMVg5vAMDo84ZPByU_yEig0VPS0iek,22844
|
| 590 |
+
networkx/utils/random_sequence.py,sha256=kk3F8_5cazolIeSL_eDdZzQ15aB3b5lHazef9kM1NNw,5303
|
| 591 |
+
networkx/utils/rcm.py,sha256=t2LJq6BG39JnPl_353nM8eDfGWy3LVL8BdrBZCcAy2g,4618
|
| 592 |
+
networkx/utils/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 593 |
+
networkx/utils/tests/test__init.py,sha256=QE0i-lNE4pG2eYjB2mZ0uw7jPD-7TdL7Y9p73JoWQmo,363
|
| 594 |
+
networkx/utils/tests/test_backends.py,sha256=VzzgmdT_ymvQ7EKB4BbdntkBYaO5w6OgXzvr7pbgQsY,7784
|
| 595 |
+
networkx/utils/tests/test_config.py,sha256=eBAiwADWJgCAIyJjgF3-zn89VPIGftiWMWyccpFnyMU,8717
|
| 596 |
+
networkx/utils/tests/test_decorators.py,sha256=dm3b5yiQPlnlT_4pSm0FwK-xBGV9dcnhv14Vh9Jiz1o,14050
|
| 597 |
+
networkx/utils/tests/test_heaps.py,sha256=qCuWMzpcMH1Gwu014CAams78o151QD5YL0mB1fz16Yw,3711
|
| 598 |
+
networkx/utils/tests/test_mapped_queue.py,sha256=l1Nguzz68Fv91FnAT7y7B0GXSoje9uoWiObHo7TliGM,7354
|
| 599 |
+
networkx/utils/tests/test_misc.py,sha256=3rKc5wy3qAwk1JdVZYD8FaTF4_4Y1_Tq1nbza6eR_jc,13965
|
| 600 |
+
networkx/utils/tests/test_random_sequence.py,sha256=yvfWhJQJJqM1W-_etHo7BsLXA18YiHcLaF-IdhSwcYA,1502
|
| 601 |
+
networkx/utils/tests/test_rcm.py,sha256=UvUAkgmQMGk_Nn94TJyQsle4A5SLQFqMQWld1tiQ2lk,1421
|
| 602 |
+
networkx/utils/tests/test_unionfind.py,sha256=j-DF5XyeJzq1hoeAgN5Nye2Au7EPD040t8oS4Aw2IwU,1579
|
| 603 |
+
networkx/utils/union_find.py,sha256=NxKlBlyS71A1Wlnt28L-wyZoI9ExZvJth_0e2XSVris,3338
|
.venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/REQUESTED
ADDED
|
File without changes
|
.venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (80.9.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
.venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[networkx.backends]
|
| 2 |
+
nx_loopback = networkx.classes.tests.dispatch_interface:backend_interface
|
.venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txt
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NetworkX is distributed with the 3-clause BSD license.
|
| 2 |
+
|
| 3 |
+
::
|
| 4 |
+
|
| 5 |
+
Copyright (c) 2004-2025, NetworkX Developers
|
| 6 |
+
Aric Hagberg <hagberg@lanl.gov>
|
| 7 |
+
Dan Schult <dschult@colgate.edu>
|
| 8 |
+
Pieter Swart <swart@lanl.gov>
|
| 9 |
+
All rights reserved.
|
| 10 |
+
|
| 11 |
+
Redistribution and use in source and binary forms, with or without
|
| 12 |
+
modification, are permitted provided that the following conditions are
|
| 13 |
+
met:
|
| 14 |
+
|
| 15 |
+
* Redistributions of source code must retain the above copyright
|
| 16 |
+
notice, this list of conditions and the following disclaimer.
|
| 17 |
+
|
| 18 |
+
* Redistributions in binary form must reproduce the above
|
| 19 |
+
copyright notice, this list of conditions and the following
|
| 20 |
+
disclaimer in the documentation and/or other materials provided
|
| 21 |
+
with the distribution.
|
| 22 |
+
|
| 23 |
+
* Neither the name of the NetworkX Developers nor the names of its
|
| 24 |
+
contributors may be used to endorse or promote products derived
|
| 25 |
+
from this software without specific prior written permission.
|
| 26 |
+
|
| 27 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 28 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 29 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 30 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 31 |
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 32 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
| 33 |
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
| 34 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
| 35 |
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 36 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 37 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.venv/lib/python3.11/site-packages/networkx-3.6.1.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
networkx
|
.venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_load_centrality.py
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestLoadCentrality:
|
| 7 |
+
@classmethod
|
| 8 |
+
def setup_class(cls):
|
| 9 |
+
G = nx.Graph()
|
| 10 |
+
G.add_edge(0, 1, weight=3)
|
| 11 |
+
G.add_edge(0, 2, weight=2)
|
| 12 |
+
G.add_edge(0, 3, weight=6)
|
| 13 |
+
G.add_edge(0, 4, weight=4)
|
| 14 |
+
G.add_edge(1, 3, weight=5)
|
| 15 |
+
G.add_edge(1, 5, weight=5)
|
| 16 |
+
G.add_edge(2, 4, weight=1)
|
| 17 |
+
G.add_edge(3, 4, weight=2)
|
| 18 |
+
G.add_edge(3, 5, weight=1)
|
| 19 |
+
G.add_edge(4, 5, weight=4)
|
| 20 |
+
cls.G = G
|
| 21 |
+
cls.exact_weighted = {0: 4.0, 1: 0.0, 2: 8.0, 3: 6.0, 4: 8.0, 5: 0.0}
|
| 22 |
+
cls.K = nx.krackhardt_kite_graph()
|
| 23 |
+
cls.P3 = nx.path_graph(3)
|
| 24 |
+
cls.P4 = nx.path_graph(4)
|
| 25 |
+
cls.K5 = nx.complete_graph(5)
|
| 26 |
+
cls.P2 = nx.path_graph(2)
|
| 27 |
+
|
| 28 |
+
cls.C4 = nx.cycle_graph(4)
|
| 29 |
+
cls.T = nx.balanced_tree(r=2, h=2)
|
| 30 |
+
cls.Gb = nx.Graph()
|
| 31 |
+
cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)])
|
| 32 |
+
cls.F = nx.florentine_families_graph()
|
| 33 |
+
cls.LM = nx.les_miserables_graph()
|
| 34 |
+
cls.D = nx.cycle_graph(3, create_using=nx.DiGraph())
|
| 35 |
+
cls.D.add_edges_from([(3, 0), (4, 3)])
|
| 36 |
+
|
| 37 |
+
def test_not_strongly_connected(self):
|
| 38 |
+
b = nx.load_centrality(self.D)
|
| 39 |
+
result = {0: 5.0 / 12, 1: 1.0 / 4, 2: 1.0 / 12, 3: 1.0 / 4, 4: 0.000}
|
| 40 |
+
for n in sorted(self.D):
|
| 41 |
+
assert result[n] == pytest.approx(b[n], abs=1e-3)
|
| 42 |
+
assert result[n] == pytest.approx(nx.load_centrality(self.D, n), abs=1e-3)
|
| 43 |
+
|
| 44 |
+
def test_P2_normalized_load(self):
|
| 45 |
+
G = self.P2
|
| 46 |
+
c = nx.load_centrality(G, normalized=True)
|
| 47 |
+
d = {0: 0.000, 1: 0.000}
|
| 48 |
+
for n in sorted(G):
|
| 49 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 50 |
+
|
| 51 |
+
def test_weighted_load(self):
|
| 52 |
+
b = nx.load_centrality(self.G, weight="weight", normalized=False)
|
| 53 |
+
for n in sorted(self.G):
|
| 54 |
+
assert b[n] == self.exact_weighted[n]
|
| 55 |
+
|
| 56 |
+
def test_k5_load(self):
|
| 57 |
+
G = self.K5
|
| 58 |
+
c = nx.load_centrality(G)
|
| 59 |
+
d = {0: 0.000, 1: 0.000, 2: 0.000, 3: 0.000, 4: 0.000}
|
| 60 |
+
for n in sorted(G):
|
| 61 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 62 |
+
|
| 63 |
+
def test_p3_load(self):
|
| 64 |
+
G = self.P3
|
| 65 |
+
c = nx.load_centrality(G)
|
| 66 |
+
d = {0: 0.000, 1: 1.000, 2: 0.000}
|
| 67 |
+
for n in sorted(G):
|
| 68 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 69 |
+
c = nx.load_centrality(G, v=1)
|
| 70 |
+
assert c == pytest.approx(1.0, abs=1e-7)
|
| 71 |
+
c = nx.load_centrality(G, v=1, normalized=True)
|
| 72 |
+
assert c == pytest.approx(1.0, abs=1e-7)
|
| 73 |
+
|
| 74 |
+
def test_p2_load(self):
|
| 75 |
+
G = nx.path_graph(2)
|
| 76 |
+
c = nx.load_centrality(G)
|
| 77 |
+
d = {0: 0.000, 1: 0.000}
|
| 78 |
+
for n in sorted(G):
|
| 79 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 80 |
+
|
| 81 |
+
def test_krackhardt_load(self):
|
| 82 |
+
G = self.K
|
| 83 |
+
c = nx.load_centrality(G)
|
| 84 |
+
d = {
|
| 85 |
+
0: 0.023,
|
| 86 |
+
1: 0.023,
|
| 87 |
+
2: 0.000,
|
| 88 |
+
3: 0.102,
|
| 89 |
+
4: 0.000,
|
| 90 |
+
5: 0.231,
|
| 91 |
+
6: 0.231,
|
| 92 |
+
7: 0.389,
|
| 93 |
+
8: 0.222,
|
| 94 |
+
9: 0.000,
|
| 95 |
+
}
|
| 96 |
+
for n in sorted(G):
|
| 97 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 98 |
+
|
| 99 |
+
def test_florentine_families_load(self):
|
| 100 |
+
G = self.F
|
| 101 |
+
c = nx.load_centrality(G)
|
| 102 |
+
d = {
|
| 103 |
+
"Acciaiuoli": 0.000,
|
| 104 |
+
"Albizzi": 0.211,
|
| 105 |
+
"Barbadori": 0.093,
|
| 106 |
+
"Bischeri": 0.104,
|
| 107 |
+
"Castellani": 0.055,
|
| 108 |
+
"Ginori": 0.000,
|
| 109 |
+
"Guadagni": 0.251,
|
| 110 |
+
"Lamberteschi": 0.000,
|
| 111 |
+
"Medici": 0.522,
|
| 112 |
+
"Pazzi": 0.000,
|
| 113 |
+
"Peruzzi": 0.022,
|
| 114 |
+
"Ridolfi": 0.117,
|
| 115 |
+
"Salviati": 0.143,
|
| 116 |
+
"Strozzi": 0.106,
|
| 117 |
+
"Tornabuoni": 0.090,
|
| 118 |
+
}
|
| 119 |
+
for n in sorted(G):
|
| 120 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 121 |
+
|
| 122 |
+
def test_les_miserables_load(self):
|
| 123 |
+
G = self.LM
|
| 124 |
+
c = nx.load_centrality(G)
|
| 125 |
+
d = {
|
| 126 |
+
"Napoleon": 0.000,
|
| 127 |
+
"Myriel": 0.177,
|
| 128 |
+
"MlleBaptistine": 0.000,
|
| 129 |
+
"MmeMagloire": 0.000,
|
| 130 |
+
"CountessDeLo": 0.000,
|
| 131 |
+
"Geborand": 0.000,
|
| 132 |
+
"Champtercier": 0.000,
|
| 133 |
+
"Cravatte": 0.000,
|
| 134 |
+
"Count": 0.000,
|
| 135 |
+
"OldMan": 0.000,
|
| 136 |
+
"Valjean": 0.567,
|
| 137 |
+
"Labarre": 0.000,
|
| 138 |
+
"Marguerite": 0.000,
|
| 139 |
+
"MmeDeR": 0.000,
|
| 140 |
+
"Isabeau": 0.000,
|
| 141 |
+
"Gervais": 0.000,
|
| 142 |
+
"Listolier": 0.000,
|
| 143 |
+
"Tholomyes": 0.043,
|
| 144 |
+
"Fameuil": 0.000,
|
| 145 |
+
"Blacheville": 0.000,
|
| 146 |
+
"Favourite": 0.000,
|
| 147 |
+
"Dahlia": 0.000,
|
| 148 |
+
"Zephine": 0.000,
|
| 149 |
+
"Fantine": 0.128,
|
| 150 |
+
"MmeThenardier": 0.029,
|
| 151 |
+
"Thenardier": 0.075,
|
| 152 |
+
"Cosette": 0.024,
|
| 153 |
+
"Javert": 0.054,
|
| 154 |
+
"Fauchelevent": 0.026,
|
| 155 |
+
"Bamatabois": 0.008,
|
| 156 |
+
"Perpetue": 0.000,
|
| 157 |
+
"Simplice": 0.009,
|
| 158 |
+
"Scaufflaire": 0.000,
|
| 159 |
+
"Woman1": 0.000,
|
| 160 |
+
"Judge": 0.000,
|
| 161 |
+
"Champmathieu": 0.000,
|
| 162 |
+
"Brevet": 0.000,
|
| 163 |
+
"Chenildieu": 0.000,
|
| 164 |
+
"Cochepaille": 0.000,
|
| 165 |
+
"Pontmercy": 0.007,
|
| 166 |
+
"Boulatruelle": 0.000,
|
| 167 |
+
"Eponine": 0.012,
|
| 168 |
+
"Anzelma": 0.000,
|
| 169 |
+
"Woman2": 0.000,
|
| 170 |
+
"MotherInnocent": 0.000,
|
| 171 |
+
"Gribier": 0.000,
|
| 172 |
+
"MmeBurgon": 0.026,
|
| 173 |
+
"Jondrette": 0.000,
|
| 174 |
+
"Gavroche": 0.164,
|
| 175 |
+
"Gillenormand": 0.021,
|
| 176 |
+
"Magnon": 0.000,
|
| 177 |
+
"MlleGillenormand": 0.047,
|
| 178 |
+
"MmePontmercy": 0.000,
|
| 179 |
+
"MlleVaubois": 0.000,
|
| 180 |
+
"LtGillenormand": 0.000,
|
| 181 |
+
"Marius": 0.133,
|
| 182 |
+
"BaronessT": 0.000,
|
| 183 |
+
"Mabeuf": 0.028,
|
| 184 |
+
"Enjolras": 0.041,
|
| 185 |
+
"Combeferre": 0.001,
|
| 186 |
+
"Prouvaire": 0.000,
|
| 187 |
+
"Feuilly": 0.001,
|
| 188 |
+
"Courfeyrac": 0.006,
|
| 189 |
+
"Bahorel": 0.002,
|
| 190 |
+
"Bossuet": 0.032,
|
| 191 |
+
"Joly": 0.002,
|
| 192 |
+
"Grantaire": 0.000,
|
| 193 |
+
"MotherPlutarch": 0.000,
|
| 194 |
+
"Gueulemer": 0.005,
|
| 195 |
+
"Babet": 0.005,
|
| 196 |
+
"Claquesous": 0.005,
|
| 197 |
+
"Montparnasse": 0.004,
|
| 198 |
+
"Toussaint": 0.000,
|
| 199 |
+
"Child1": 0.000,
|
| 200 |
+
"Child2": 0.000,
|
| 201 |
+
"Brujon": 0.000,
|
| 202 |
+
"MmeHucheloup": 0.000,
|
| 203 |
+
}
|
| 204 |
+
for n in sorted(G):
|
| 205 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 206 |
+
|
| 207 |
+
def test_unnormalized_k5_load(self):
|
| 208 |
+
G = self.K5
|
| 209 |
+
c = nx.load_centrality(G, normalized=False)
|
| 210 |
+
d = {0: 0.000, 1: 0.000, 2: 0.000, 3: 0.000, 4: 0.000}
|
| 211 |
+
for n in sorted(G):
|
| 212 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 213 |
+
|
| 214 |
+
def test_unnormalized_p3_load(self):
|
| 215 |
+
G = self.P3
|
| 216 |
+
c = nx.load_centrality(G, normalized=False)
|
| 217 |
+
d = {0: 0.000, 1: 2.000, 2: 0.000}
|
| 218 |
+
for n in sorted(G):
|
| 219 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 220 |
+
|
| 221 |
+
def test_unnormalized_krackhardt_load(self):
|
| 222 |
+
G = self.K
|
| 223 |
+
c = nx.load_centrality(G, normalized=False)
|
| 224 |
+
d = {
|
| 225 |
+
0: 1.667,
|
| 226 |
+
1: 1.667,
|
| 227 |
+
2: 0.000,
|
| 228 |
+
3: 7.333,
|
| 229 |
+
4: 0.000,
|
| 230 |
+
5: 16.667,
|
| 231 |
+
6: 16.667,
|
| 232 |
+
7: 28.000,
|
| 233 |
+
8: 16.000,
|
| 234 |
+
9: 0.000,
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
for n in sorted(G):
|
| 238 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 239 |
+
|
| 240 |
+
def test_unnormalized_florentine_families_load(self):
|
| 241 |
+
G = self.F
|
| 242 |
+
c = nx.load_centrality(G, normalized=False)
|
| 243 |
+
|
| 244 |
+
d = {
|
| 245 |
+
"Acciaiuoli": 0.000,
|
| 246 |
+
"Albizzi": 38.333,
|
| 247 |
+
"Barbadori": 17.000,
|
| 248 |
+
"Bischeri": 19.000,
|
| 249 |
+
"Castellani": 10.000,
|
| 250 |
+
"Ginori": 0.000,
|
| 251 |
+
"Guadagni": 45.667,
|
| 252 |
+
"Lamberteschi": 0.000,
|
| 253 |
+
"Medici": 95.000,
|
| 254 |
+
"Pazzi": 0.000,
|
| 255 |
+
"Peruzzi": 4.000,
|
| 256 |
+
"Ridolfi": 21.333,
|
| 257 |
+
"Salviati": 26.000,
|
| 258 |
+
"Strozzi": 19.333,
|
| 259 |
+
"Tornabuoni": 16.333,
|
| 260 |
+
}
|
| 261 |
+
for n in sorted(G):
|
| 262 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 263 |
+
|
| 264 |
+
def test_load_betweenness_difference(self):
|
| 265 |
+
# Difference Between Load and Betweenness
|
| 266 |
+
# --------------------------------------- The smallest graph
|
| 267 |
+
# that shows the difference between load and betweenness is
|
| 268 |
+
# G=ladder_graph(3) (Graph B below)
|
| 269 |
+
|
| 270 |
+
# Graph A and B are from Tao Zhou, Jian-Guo Liu, Bing-Hong
|
| 271 |
+
# Wang: Comment on "Scientific collaboration
|
| 272 |
+
# networks. II. Shortest paths, weighted networks, and
|
| 273 |
+
# centrality". https://arxiv.org/pdf/physics/0511084
|
| 274 |
+
|
| 275 |
+
# Notice that unlike here, their calculation adds to 1 to the
|
| 276 |
+
# betweenness of every node i for every path from i to every
|
| 277 |
+
# other node. This is exactly what it should be, based on
|
| 278 |
+
# Eqn. (1) in their paper: the eqn is B(v) = \sum_{s\neq t,
|
| 279 |
+
# s\neq v}{\frac{\sigma_{st}(v)}{\sigma_{st}}}, therefore,
|
| 280 |
+
# they allow v to be the target node.
|
| 281 |
+
|
| 282 |
+
# We follow Brandes 2001, who follows Freeman 1977 that make
|
| 283 |
+
# the sum for betweenness of v exclude paths where v is either
|
| 284 |
+
# the source or target node. To agree with their numbers, we
|
| 285 |
+
# must additionally, remove edge (4,8) from the graph, see AC
|
| 286 |
+
# example following (there is a mistake in the figure in their
|
| 287 |
+
# paper - personal communication).
|
| 288 |
+
|
| 289 |
+
# A = nx.Graph()
|
| 290 |
+
# A.add_edges_from([(0,1), (1,2), (1,3), (2,4),
|
| 291 |
+
# (3,5), (4,6), (4,7), (4,8),
|
| 292 |
+
# (5,8), (6,9), (7,9), (8,9)])
|
| 293 |
+
B = nx.Graph() # ladder_graph(3)
|
| 294 |
+
B.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)])
|
| 295 |
+
c = nx.load_centrality(B, normalized=False)
|
| 296 |
+
d = {0: 1.750, 1: 1.750, 2: 6.500, 3: 6.500, 4: 1.750, 5: 1.750}
|
| 297 |
+
for n in sorted(B):
|
| 298 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 299 |
+
|
| 300 |
+
def test_c4_edge_load(self):
|
| 301 |
+
G = self.C4
|
| 302 |
+
c = nx.edge_load_centrality(G)
|
| 303 |
+
d = {(0, 1): 6.000, (0, 3): 6.000, (1, 2): 6.000, (2, 3): 6.000}
|
| 304 |
+
for n in G.edges():
|
| 305 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 306 |
+
|
| 307 |
+
def test_p4_edge_load(self):
|
| 308 |
+
G = self.P4
|
| 309 |
+
c = nx.edge_load_centrality(G)
|
| 310 |
+
d = {(0, 1): 6.000, (1, 2): 8.000, (2, 3): 6.000}
|
| 311 |
+
for n in G.edges():
|
| 312 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 313 |
+
|
| 314 |
+
def test_k5_edge_load(self):
|
| 315 |
+
G = self.K5
|
| 316 |
+
c = nx.edge_load_centrality(G)
|
| 317 |
+
d = {
|
| 318 |
+
(0, 1): 5.000,
|
| 319 |
+
(0, 2): 5.000,
|
| 320 |
+
(0, 3): 5.000,
|
| 321 |
+
(0, 4): 5.000,
|
| 322 |
+
(1, 2): 5.000,
|
| 323 |
+
(1, 3): 5.000,
|
| 324 |
+
(1, 4): 5.000,
|
| 325 |
+
(2, 3): 5.000,
|
| 326 |
+
(2, 4): 5.000,
|
| 327 |
+
(3, 4): 5.000,
|
| 328 |
+
}
|
| 329 |
+
for n in G.edges():
|
| 330 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
| 331 |
+
|
| 332 |
+
def test_tree_edge_load(self):
|
| 333 |
+
G = self.T
|
| 334 |
+
c = nx.edge_load_centrality(G)
|
| 335 |
+
d = {
|
| 336 |
+
(0, 1): 24.000,
|
| 337 |
+
(0, 2): 24.000,
|
| 338 |
+
(1, 3): 12.000,
|
| 339 |
+
(1, 4): 12.000,
|
| 340 |
+
(2, 5): 12.000,
|
| 341 |
+
(2, 6): 12.000,
|
| 342 |
+
}
|
| 343 |
+
for n in G.edges():
|
| 344 |
+
assert c[n] == pytest.approx(d[n], abs=1e-3)
|
.venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_percolation_centrality.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def example1a_G():
|
| 7 |
+
G = nx.Graph()
|
| 8 |
+
G.add_node(1, percolation=0.1)
|
| 9 |
+
G.add_node(2, percolation=0.2)
|
| 10 |
+
G.add_node(3, percolation=0.2)
|
| 11 |
+
G.add_node(4, percolation=0.2)
|
| 12 |
+
G.add_node(5, percolation=0.3)
|
| 13 |
+
G.add_node(6, percolation=0.2)
|
| 14 |
+
G.add_node(7, percolation=0.5)
|
| 15 |
+
G.add_node(8, percolation=0.5)
|
| 16 |
+
G.add_edges_from([(1, 4), (2, 4), (3, 4), (4, 5), (5, 6), (6, 7), (6, 8)])
|
| 17 |
+
return G
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def example1b_G():
|
| 21 |
+
G = nx.Graph()
|
| 22 |
+
G.add_node(1, percolation=0.3)
|
| 23 |
+
G.add_node(2, percolation=0.5)
|
| 24 |
+
G.add_node(3, percolation=0.5)
|
| 25 |
+
G.add_node(4, percolation=0.2)
|
| 26 |
+
G.add_node(5, percolation=0.3)
|
| 27 |
+
G.add_node(6, percolation=0.2)
|
| 28 |
+
G.add_node(7, percolation=0.1)
|
| 29 |
+
G.add_node(8, percolation=0.1)
|
| 30 |
+
G.add_edges_from([(1, 4), (2, 4), (3, 4), (4, 5), (5, 6), (6, 7), (6, 8)])
|
| 31 |
+
return G
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_percolation_example1a():
|
| 35 |
+
"""percolation centrality: example 1a"""
|
| 36 |
+
G = example1a_G()
|
| 37 |
+
p = nx.percolation_centrality(G)
|
| 38 |
+
p_answer = {4: 0.625, 6: 0.667}
|
| 39 |
+
for n, k in p_answer.items():
|
| 40 |
+
assert p[n] == pytest.approx(k, abs=1e-3)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_percolation_example1b():
|
| 44 |
+
"""percolation centrality: example 1a"""
|
| 45 |
+
G = example1b_G()
|
| 46 |
+
p = nx.percolation_centrality(G)
|
| 47 |
+
p_answer = {4: 0.825, 6: 0.4}
|
| 48 |
+
for n, k in p_answer.items():
|
| 49 |
+
assert p[n] == pytest.approx(k, abs=1e-3)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_converge_to_betweenness():
|
| 53 |
+
"""percolation centrality: should converge to betweenness
|
| 54 |
+
centrality when all nodes are percolated the same"""
|
| 55 |
+
# taken from betweenness test test_florentine_families_graph
|
| 56 |
+
G = nx.florentine_families_graph()
|
| 57 |
+
b_answer = {
|
| 58 |
+
"Acciaiuoli": 0.000,
|
| 59 |
+
"Albizzi": 0.212,
|
| 60 |
+
"Barbadori": 0.093,
|
| 61 |
+
"Bischeri": 0.104,
|
| 62 |
+
"Castellani": 0.055,
|
| 63 |
+
"Ginori": 0.000,
|
| 64 |
+
"Guadagni": 0.255,
|
| 65 |
+
"Lamberteschi": 0.000,
|
| 66 |
+
"Medici": 0.522,
|
| 67 |
+
"Pazzi": 0.000,
|
| 68 |
+
"Peruzzi": 0.022,
|
| 69 |
+
"Ridolfi": 0.114,
|
| 70 |
+
"Salviati": 0.143,
|
| 71 |
+
"Strozzi": 0.103,
|
| 72 |
+
"Tornabuoni": 0.092,
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
# If no initial state is provided, state for
|
| 76 |
+
# every node defaults to 1
|
| 77 |
+
p_answer = nx.percolation_centrality(G)
|
| 78 |
+
assert p_answer == pytest.approx(b_answer, abs=1e-3)
|
| 79 |
+
|
| 80 |
+
p_states = {k: 0.3 for k, v in b_answer.items()}
|
| 81 |
+
p_answer = nx.percolation_centrality(G, states=p_states)
|
| 82 |
+
assert p_answer == pytest.approx(b_answer, abs=1e-3)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_default_percolation():
|
| 86 |
+
G = nx.erdos_renyi_graph(42, 0.42, seed=42)
|
| 87 |
+
assert nx.percolation_centrality(G) == pytest.approx(nx.betweenness_centrality(G))
|
.venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_reaching.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for the :mod:`networkx.algorithms.centrality.reaching` module."""
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestGlobalReachingCentrality:
|
| 9 |
+
"""Unit tests for the global reaching centrality function."""
|
| 10 |
+
|
| 11 |
+
def test_non_positive_weights(self):
|
| 12 |
+
with pytest.raises(nx.NetworkXError):
|
| 13 |
+
G = nx.DiGraph()
|
| 14 |
+
nx.global_reaching_centrality(G, weight="weight")
|
| 15 |
+
|
| 16 |
+
def test_negatively_weighted(self):
|
| 17 |
+
with pytest.raises(nx.NetworkXError):
|
| 18 |
+
G = nx.Graph()
|
| 19 |
+
G.add_weighted_edges_from([(0, 1, -2), (1, 2, +1)])
|
| 20 |
+
nx.global_reaching_centrality(G, weight="weight")
|
| 21 |
+
|
| 22 |
+
def test_directed_star(self):
|
| 23 |
+
G = nx.DiGraph()
|
| 24 |
+
G.add_weighted_edges_from([(1, 2, 0.5), (1, 3, 0.5)])
|
| 25 |
+
grc = nx.global_reaching_centrality
|
| 26 |
+
assert grc(G, normalized=False, weight="weight") == 0.5
|
| 27 |
+
assert grc(G) == 1
|
| 28 |
+
|
| 29 |
+
def test_undirected_unweighted_star(self):
|
| 30 |
+
G = nx.star_graph(2)
|
| 31 |
+
grc = nx.global_reaching_centrality
|
| 32 |
+
assert grc(G, normalized=False, weight=None) == 0.25
|
| 33 |
+
|
| 34 |
+
def test_undirected_weighted_star(self):
|
| 35 |
+
G = nx.Graph()
|
| 36 |
+
G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2)])
|
| 37 |
+
grc = nx.global_reaching_centrality
|
| 38 |
+
assert grc(G, normalized=False, weight="weight") == 0.375
|
| 39 |
+
|
| 40 |
+
def test_cycle_directed_unweighted(self):
|
| 41 |
+
G = nx.DiGraph()
|
| 42 |
+
G.add_edge(1, 2)
|
| 43 |
+
G.add_edge(2, 1)
|
| 44 |
+
assert nx.global_reaching_centrality(G, weight=None) == 0
|
| 45 |
+
|
| 46 |
+
def test_cycle_undirected_unweighted(self):
|
| 47 |
+
G = nx.Graph()
|
| 48 |
+
G.add_edge(1, 2)
|
| 49 |
+
assert nx.global_reaching_centrality(G, weight=None) == 0
|
| 50 |
+
|
| 51 |
+
def test_cycle_directed_weighted(self):
|
| 52 |
+
G = nx.DiGraph()
|
| 53 |
+
G.add_weighted_edges_from([(1, 2, 1), (2, 1, 1)])
|
| 54 |
+
assert nx.global_reaching_centrality(G) == 0
|
| 55 |
+
|
| 56 |
+
def test_cycle_undirected_weighted(self):
|
| 57 |
+
G = nx.Graph()
|
| 58 |
+
G.add_edge(1, 2, weight=1)
|
| 59 |
+
grc = nx.global_reaching_centrality
|
| 60 |
+
assert grc(G, normalized=False) == 0
|
| 61 |
+
|
| 62 |
+
def test_directed_weighted(self):
|
| 63 |
+
G = nx.DiGraph()
|
| 64 |
+
G.add_edge("A", "B", weight=5)
|
| 65 |
+
G.add_edge("B", "C", weight=1)
|
| 66 |
+
G.add_edge("B", "D", weight=0.25)
|
| 67 |
+
G.add_edge("D", "E", weight=1)
|
| 68 |
+
|
| 69 |
+
denom = len(G) - 1
|
| 70 |
+
A_local = sum([5, 3, 2.625, 2.0833333333333]) / denom
|
| 71 |
+
B_local = sum([1, 0.25, 0.625]) / denom
|
| 72 |
+
C_local = 0
|
| 73 |
+
D_local = sum([1]) / denom
|
| 74 |
+
E_local = 0
|
| 75 |
+
|
| 76 |
+
local_reach_ctrs = [A_local, C_local, B_local, D_local, E_local]
|
| 77 |
+
max_local = max(local_reach_ctrs)
|
| 78 |
+
expected = sum(max_local - lrc for lrc in local_reach_ctrs) / denom
|
| 79 |
+
grc = nx.global_reaching_centrality
|
| 80 |
+
actual = grc(G, normalized=False, weight="weight")
|
| 81 |
+
assert expected == pytest.approx(actual, abs=1e-7)
|
| 82 |
+
|
| 83 |
+
def test_single_node_with_cycle(self):
|
| 84 |
+
G = nx.DiGraph([(1, 1)])
|
| 85 |
+
with pytest.raises(nx.NetworkXError, match="local_reaching_centrality"):
|
| 86 |
+
nx.global_reaching_centrality(G)
|
| 87 |
+
|
| 88 |
+
def test_single_node_with_weighted_cycle(self):
|
| 89 |
+
G = nx.DiGraph()
|
| 90 |
+
G.add_weighted_edges_from([(1, 1, 2)])
|
| 91 |
+
with pytest.raises(nx.NetworkXError, match="local_reaching_centrality"):
|
| 92 |
+
nx.global_reaching_centrality(G, weight="weight")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class TestLocalReachingCentrality:
|
| 96 |
+
"""Unit tests for the local reaching centrality function."""
|
| 97 |
+
|
| 98 |
+
def test_non_positive_weights(self):
|
| 99 |
+
with pytest.raises(nx.NetworkXError):
|
| 100 |
+
G = nx.DiGraph()
|
| 101 |
+
G.add_weighted_edges_from([(0, 1, 0)])
|
| 102 |
+
nx.local_reaching_centrality(G, 0, weight="weight")
|
| 103 |
+
|
| 104 |
+
def test_negatively_weighted(self):
|
| 105 |
+
with pytest.raises(nx.NetworkXError):
|
| 106 |
+
G = nx.Graph()
|
| 107 |
+
G.add_weighted_edges_from([(0, 1, -2), (1, 2, +1)])
|
| 108 |
+
nx.local_reaching_centrality(G, 0, weight="weight")
|
| 109 |
+
|
| 110 |
+
def test_undirected_unweighted_star(self):
|
| 111 |
+
G = nx.star_graph(2)
|
| 112 |
+
grc = nx.local_reaching_centrality
|
| 113 |
+
assert grc(G, 1, weight=None, normalized=False) == 0.75
|
| 114 |
+
|
| 115 |
+
def test_undirected_weighted_star(self):
|
| 116 |
+
G = nx.Graph()
|
| 117 |
+
G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2)])
|
| 118 |
+
centrality = nx.local_reaching_centrality(
|
| 119 |
+
G, 1, normalized=False, weight="weight"
|
| 120 |
+
)
|
| 121 |
+
assert centrality == 1.5
|
| 122 |
+
|
| 123 |
+
def test_undirected_weighted_normalized(self):
|
| 124 |
+
G = nx.Graph()
|
| 125 |
+
G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2)])
|
| 126 |
+
centrality = nx.local_reaching_centrality(
|
| 127 |
+
G, 1, normalized=True, weight="weight"
|
| 128 |
+
)
|
| 129 |
+
assert centrality == 1.0
|
| 130 |
+
|
| 131 |
+
def test_single_node_with_cycle(self):
|
| 132 |
+
G = nx.DiGraph([(1, 1)])
|
| 133 |
+
with pytest.raises(nx.NetworkXError, match="local_reaching_centrality"):
|
| 134 |
+
nx.local_reaching_centrality(G, 1)
|
| 135 |
+
|
| 136 |
+
def test_single_node_with_weighted_cycle(self):
|
| 137 |
+
G = nx.DiGraph()
|
| 138 |
+
G.add_weighted_edges_from([(1, 1, 2)])
|
| 139 |
+
with pytest.raises(nx.NetworkXError, match="local_reaching_centrality"):
|
| 140 |
+
nx.local_reaching_centrality(G, 1, weight="weight")
|
.venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_second_order_centrality.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests for second order centrality.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
pytest.importorskip("numpy")
|
| 8 |
+
pytest.importorskip("scipy")
|
| 9 |
+
|
| 10 |
+
import networkx as nx
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_empty():
|
| 14 |
+
with pytest.raises(nx.NetworkXException):
|
| 15 |
+
G = nx.empty_graph()
|
| 16 |
+
nx.second_order_centrality(G)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_non_connected():
|
| 20 |
+
with pytest.raises(nx.NetworkXException):
|
| 21 |
+
G = nx.Graph()
|
| 22 |
+
G.add_node(0)
|
| 23 |
+
G.add_node(1)
|
| 24 |
+
nx.second_order_centrality(G)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_non_negative_edge_weights():
|
| 28 |
+
with pytest.raises(nx.NetworkXException):
|
| 29 |
+
G = nx.path_graph(2)
|
| 30 |
+
G.add_edge(0, 1, weight=-1)
|
| 31 |
+
nx.second_order_centrality(G)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_weight_attribute():
|
| 35 |
+
G = nx.Graph()
|
| 36 |
+
G.add_weighted_edges_from([(0, 1, 1.0), (1, 2, 3.5)], weight="w")
|
| 37 |
+
expected = {0: 3.431, 1: 3.082, 2: 5.612}
|
| 38 |
+
b = nx.second_order_centrality(G, weight="w")
|
| 39 |
+
|
| 40 |
+
for n in sorted(G):
|
| 41 |
+
assert b[n] == pytest.approx(expected[n], abs=1e-2)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_one_node_graph():
|
| 45 |
+
"""Second order centrality: single node"""
|
| 46 |
+
G = nx.Graph()
|
| 47 |
+
G.add_node(0)
|
| 48 |
+
G.add_edge(0, 0)
|
| 49 |
+
assert nx.second_order_centrality(G)[0] == 0
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_P3():
|
| 53 |
+
"""Second order centrality: line graph, as defined in paper"""
|
| 54 |
+
G = nx.path_graph(3)
|
| 55 |
+
b_answer = {0: 3.741, 1: 1.414, 2: 3.741}
|
| 56 |
+
|
| 57 |
+
b = nx.second_order_centrality(G)
|
| 58 |
+
|
| 59 |
+
for n in sorted(G):
|
| 60 |
+
assert b[n] == pytest.approx(b_answer[n], abs=1e-2)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_K3():
|
| 64 |
+
"""Second order centrality: complete graph, as defined in paper"""
|
| 65 |
+
G = nx.complete_graph(3)
|
| 66 |
+
b_answer = {0: 1.414, 1: 1.414, 2: 1.414}
|
| 67 |
+
|
| 68 |
+
b = nx.second_order_centrality(G)
|
| 69 |
+
|
| 70 |
+
for n in sorted(G):
|
| 71 |
+
assert b[n] == pytest.approx(b_answer[n], abs=1e-2)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_ring_graph():
|
| 75 |
+
"""Second order centrality: ring graph, as defined in paper"""
|
| 76 |
+
G = nx.cycle_graph(5)
|
| 77 |
+
b_answer = {0: 4.472, 1: 4.472, 2: 4.472, 3: 4.472, 4: 4.472}
|
| 78 |
+
|
| 79 |
+
b = nx.second_order_centrality(G)
|
| 80 |
+
|
| 81 |
+
for n in sorted(G):
|
| 82 |
+
assert b[n] == pytest.approx(b_answer[n], abs=1e-2)
|
.venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_subgraph.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
pytest.importorskip("numpy")
|
| 4 |
+
pytest.importorskip("scipy")
|
| 5 |
+
|
| 6 |
+
import networkx as nx
|
| 7 |
+
from networkx.algorithms.centrality.subgraph_alg import (
|
| 8 |
+
communicability_betweenness_centrality,
|
| 9 |
+
estrada_index,
|
| 10 |
+
subgraph_centrality,
|
| 11 |
+
subgraph_centrality_exp,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TestSubgraph:
|
| 16 |
+
def test_subgraph_centrality(self):
|
| 17 |
+
answer = {0: 1.5430806348152433, 1: 1.5430806348152433}
|
| 18 |
+
result = subgraph_centrality(nx.path_graph(2))
|
| 19 |
+
for k, v in result.items():
|
| 20 |
+
assert answer[k] == pytest.approx(v, abs=1e-7)
|
| 21 |
+
|
| 22 |
+
answer1 = {
|
| 23 |
+
"1": 1.6445956054135658,
|
| 24 |
+
"Albert": 2.4368257358712189,
|
| 25 |
+
"Aric": 2.4368257358712193,
|
| 26 |
+
"Dan": 3.1306328496328168,
|
| 27 |
+
"Franck": 2.3876142275231915,
|
| 28 |
+
}
|
| 29 |
+
G1 = nx.Graph(
|
| 30 |
+
[
|
| 31 |
+
("Franck", "Aric"),
|
| 32 |
+
("Aric", "Dan"),
|
| 33 |
+
("Dan", "Albert"),
|
| 34 |
+
("Albert", "Franck"),
|
| 35 |
+
("Dan", "1"),
|
| 36 |
+
("Franck", "Albert"),
|
| 37 |
+
]
|
| 38 |
+
)
|
| 39 |
+
result1 = subgraph_centrality(G1)
|
| 40 |
+
for k, v in result1.items():
|
| 41 |
+
assert answer1[k] == pytest.approx(v, abs=1e-7)
|
| 42 |
+
result1 = subgraph_centrality_exp(G1)
|
| 43 |
+
for k, v in result1.items():
|
| 44 |
+
assert answer1[k] == pytest.approx(v, abs=1e-7)
|
| 45 |
+
|
| 46 |
+
def test_subgraph_centrality_big_graph(self):
|
| 47 |
+
g199 = nx.complete_graph(199)
|
| 48 |
+
g200 = nx.complete_graph(200)
|
| 49 |
+
|
| 50 |
+
comm199 = nx.subgraph_centrality(g199)
|
| 51 |
+
comm199_exp = nx.subgraph_centrality_exp(g199)
|
| 52 |
+
|
| 53 |
+
comm200 = nx.subgraph_centrality(g200)
|
| 54 |
+
comm200_exp = nx.subgraph_centrality_exp(g200)
|
| 55 |
+
|
| 56 |
+
def test_communicability_betweenness_centrality_small(self):
|
| 57 |
+
result = communicability_betweenness_centrality(nx.path_graph(2))
|
| 58 |
+
assert result == {0: 0, 1: 0}
|
| 59 |
+
|
| 60 |
+
result = communicability_betweenness_centrality(nx.path_graph(1))
|
| 61 |
+
assert result == {0: 0}
|
| 62 |
+
|
| 63 |
+
result = communicability_betweenness_centrality(nx.path_graph(0))
|
| 64 |
+
assert result == {}
|
| 65 |
+
|
| 66 |
+
answer = {0: 0.1411224421177313, 1: 1.0, 2: 0.1411224421177313}
|
| 67 |
+
result = communicability_betweenness_centrality(nx.path_graph(3))
|
| 68 |
+
for k, v in result.items():
|
| 69 |
+
assert answer[k] == pytest.approx(v, abs=1e-7)
|
| 70 |
+
|
| 71 |
+
result = communicability_betweenness_centrality(nx.complete_graph(3))
|
| 72 |
+
for k, v in result.items():
|
| 73 |
+
assert 0.49786143366223296 == pytest.approx(v, abs=1e-7)
|
| 74 |
+
|
| 75 |
+
def test_communicability_betweenness_centrality(self):
|
| 76 |
+
answer = {
|
| 77 |
+
0: 0.07017447951484615,
|
| 78 |
+
1: 0.71565598701107991,
|
| 79 |
+
2: 0.71565598701107991,
|
| 80 |
+
3: 0.07017447951484615,
|
| 81 |
+
}
|
| 82 |
+
result = communicability_betweenness_centrality(nx.path_graph(4))
|
| 83 |
+
for k, v in result.items():
|
| 84 |
+
assert answer[k] == pytest.approx(v, abs=1e-7)
|
| 85 |
+
|
| 86 |
+
answer1 = {
|
| 87 |
+
"1": 0.060039074193949521,
|
| 88 |
+
"Albert": 0.315470761661372,
|
| 89 |
+
"Aric": 0.31547076166137211,
|
| 90 |
+
"Dan": 0.68297778678316201,
|
| 91 |
+
"Franck": 0.21977926617449497,
|
| 92 |
+
}
|
| 93 |
+
G1 = nx.Graph(
|
| 94 |
+
[
|
| 95 |
+
("Franck", "Aric"),
|
| 96 |
+
("Aric", "Dan"),
|
| 97 |
+
("Dan", "Albert"),
|
| 98 |
+
("Albert", "Franck"),
|
| 99 |
+
("Dan", "1"),
|
| 100 |
+
("Franck", "Albert"),
|
| 101 |
+
]
|
| 102 |
+
)
|
| 103 |
+
result1 = communicability_betweenness_centrality(G1)
|
| 104 |
+
for k, v in result1.items():
|
| 105 |
+
assert answer1[k] == pytest.approx(v, abs=1e-7)
|
| 106 |
+
|
| 107 |
+
def test_estrada_index(self):
|
| 108 |
+
answer = 1041.2470334195475
|
| 109 |
+
result = estrada_index(nx.karate_club_graph())
|
| 110 |
+
assert answer == pytest.approx(result, abs=1e-7)
|
.venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_trophic.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test trophic levels, trophic differences and trophic coherence"""
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
np = pytest.importorskip("numpy")
|
| 8 |
+
pytest.importorskip("scipy")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_trophic_levels():
|
| 12 |
+
"""Trivial example"""
|
| 13 |
+
G = nx.DiGraph()
|
| 14 |
+
G.add_edge("a", "b")
|
| 15 |
+
G.add_edge("b", "c")
|
| 16 |
+
|
| 17 |
+
d = nx.trophic_levels(G)
|
| 18 |
+
assert d == {"a": 1, "b": 2, "c": 3}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_trophic_levels_levine():
|
| 22 |
+
"""Example from Figure 5 in Stephen Levine (1980) J. theor. Biol. 83,
|
| 23 |
+
195-207
|
| 24 |
+
"""
|
| 25 |
+
S = nx.DiGraph()
|
| 26 |
+
S.add_edge(1, 2, weight=1.0)
|
| 27 |
+
S.add_edge(1, 3, weight=0.2)
|
| 28 |
+
S.add_edge(1, 4, weight=0.8)
|
| 29 |
+
S.add_edge(2, 3, weight=0.2)
|
| 30 |
+
S.add_edge(2, 5, weight=0.3)
|
| 31 |
+
S.add_edge(4, 3, weight=0.6)
|
| 32 |
+
S.add_edge(4, 5, weight=0.7)
|
| 33 |
+
S.add_edge(5, 4, weight=0.2)
|
| 34 |
+
|
| 35 |
+
# save copy for later, test intermediate implementation details first
|
| 36 |
+
S2 = S.copy()
|
| 37 |
+
|
| 38 |
+
# drop nodes of in-degree zero
|
| 39 |
+
z = [nid for nid, d in S.in_degree if d == 0]
|
| 40 |
+
for nid in z:
|
| 41 |
+
S.remove_node(nid)
|
| 42 |
+
|
| 43 |
+
# find adjacency matrix
|
| 44 |
+
q = nx.linalg.graphmatrix.adjacency_matrix(S).T
|
| 45 |
+
|
| 46 |
+
# fmt: off
|
| 47 |
+
expected_q = np.array([
|
| 48 |
+
[0, 0, 0., 0],
|
| 49 |
+
[0.2, 0, 0.6, 0],
|
| 50 |
+
[0, 0, 0, 0.2],
|
| 51 |
+
[0.3, 0, 0.7, 0]
|
| 52 |
+
])
|
| 53 |
+
# fmt: on
|
| 54 |
+
assert np.array_equal(q.todense(), expected_q)
|
| 55 |
+
|
| 56 |
+
# must be square, size of number of nodes
|
| 57 |
+
assert len(q.shape) == 2
|
| 58 |
+
assert q.shape[0] == q.shape[1]
|
| 59 |
+
assert q.shape[0] == len(S)
|
| 60 |
+
|
| 61 |
+
nn = q.shape[0]
|
| 62 |
+
|
| 63 |
+
i = np.eye(nn)
|
| 64 |
+
n = np.linalg.inv(i - q)
|
| 65 |
+
y = np.asarray(n) @ np.ones(nn)
|
| 66 |
+
|
| 67 |
+
expected_y = np.array([1, 2.07906977, 1.46511628, 2.3255814])
|
| 68 |
+
assert np.allclose(y, expected_y)
|
| 69 |
+
|
| 70 |
+
expected_d = {1: 1, 2: 2, 3: 3.07906977, 4: 2.46511628, 5: 3.3255814}
|
| 71 |
+
|
| 72 |
+
d = nx.trophic_levels(S2)
|
| 73 |
+
|
| 74 |
+
for nid, level in d.items():
|
| 75 |
+
expected_level = expected_d[nid]
|
| 76 |
+
assert expected_level == pytest.approx(level, abs=1e-7)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_trophic_levels_simple():
|
| 80 |
+
matrix_a = np.array([[0, 0], [1, 0]])
|
| 81 |
+
G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
|
| 82 |
+
d = nx.trophic_levels(G)
|
| 83 |
+
assert d[0] == pytest.approx(2, abs=1e-7)
|
| 84 |
+
assert d[1] == pytest.approx(1, abs=1e-7)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_trophic_levels_more_complex():
|
| 88 |
+
# fmt: off
|
| 89 |
+
matrix = np.array([
|
| 90 |
+
[0, 1, 0, 0],
|
| 91 |
+
[0, 0, 1, 0],
|
| 92 |
+
[0, 0, 0, 1],
|
| 93 |
+
[0, 0, 0, 0]
|
| 94 |
+
])
|
| 95 |
+
# fmt: on
|
| 96 |
+
G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
|
| 97 |
+
d = nx.trophic_levels(G)
|
| 98 |
+
expected_result = [1, 2, 3, 4]
|
| 99 |
+
for ind in range(4):
|
| 100 |
+
assert d[ind] == pytest.approx(expected_result[ind], abs=1e-7)
|
| 101 |
+
|
| 102 |
+
# fmt: off
|
| 103 |
+
matrix = np.array([
|
| 104 |
+
[0, 1, 1, 0],
|
| 105 |
+
[0, 0, 1, 1],
|
| 106 |
+
[0, 0, 0, 1],
|
| 107 |
+
[0, 0, 0, 0]
|
| 108 |
+
])
|
| 109 |
+
# fmt: on
|
| 110 |
+
G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
|
| 111 |
+
d = nx.trophic_levels(G)
|
| 112 |
+
|
| 113 |
+
expected_result = [1, 2, 2.5, 3.25]
|
| 114 |
+
for ind in range(4):
|
| 115 |
+
assert d[ind] == pytest.approx(expected_result[ind], abs=1e-7)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_trophic_levels_even_more_complex():
|
| 119 |
+
# fmt: off
|
| 120 |
+
# Another, bigger matrix
|
| 121 |
+
matrix = np.array([
|
| 122 |
+
[0, 0, 0, 0, 0],
|
| 123 |
+
[0, 1, 0, 1, 0],
|
| 124 |
+
[1, 0, 0, 0, 0],
|
| 125 |
+
[0, 1, 0, 0, 0],
|
| 126 |
+
[0, 0, 0, 1, 0]
|
| 127 |
+
])
|
| 128 |
+
# Generated this linear system using pen and paper:
|
| 129 |
+
K = np.array([
|
| 130 |
+
[1, 0, -1, 0, 0],
|
| 131 |
+
[0, 0.5, 0, -0.5, 0],
|
| 132 |
+
[0, 0, 1, 0, 0],
|
| 133 |
+
[0, -0.5, 0, 1, -0.5],
|
| 134 |
+
[0, 0, 0, 0, 1],
|
| 135 |
+
])
|
| 136 |
+
# fmt: on
|
| 137 |
+
result_1 = np.ravel(np.linalg.inv(K) @ np.ones(5))
|
| 138 |
+
G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
|
| 139 |
+
result_2 = nx.trophic_levels(G)
|
| 140 |
+
|
| 141 |
+
for ind in range(5):
|
| 142 |
+
assert result_1[ind] == pytest.approx(result_2[ind], abs=1e-7)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def test_trophic_levels_singular_matrix():
|
| 146 |
+
"""Should raise an error with graphs with only non-basal nodes"""
|
| 147 |
+
matrix = np.identity(4)
|
| 148 |
+
G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
|
| 149 |
+
with pytest.raises(nx.NetworkXError, match="no basal nodes"):
|
| 150 |
+
nx.trophic_levels(G)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def test_trophic_levels_singular_with_basal():
|
| 154 |
+
"""Should fail to compute if there are any parts of the graph which are not
|
| 155 |
+
reachable from any basal node (with in-degree zero).
|
| 156 |
+
"""
|
| 157 |
+
G = nx.DiGraph()
|
| 158 |
+
# a has in-degree zero
|
| 159 |
+
G.add_edge("a", "b")
|
| 160 |
+
|
| 161 |
+
# b is one level above a, c and d
|
| 162 |
+
G.add_edge("c", "b")
|
| 163 |
+
G.add_edge("d", "b")
|
| 164 |
+
|
| 165 |
+
# c and d form a loop, neither are reachable from a
|
| 166 |
+
G.add_edge("c", "d")
|
| 167 |
+
G.add_edge("d", "c")
|
| 168 |
+
|
| 169 |
+
with pytest.raises(nx.NetworkXError) as e:
|
| 170 |
+
nx.trophic_levels(G)
|
| 171 |
+
msg = (
|
| 172 |
+
"Trophic levels are only defined for graphs where every node "
|
| 173 |
+
+ "has a path from a basal node (basal nodes are nodes with no "
|
| 174 |
+
+ "incoming edges)."
|
| 175 |
+
)
|
| 176 |
+
assert msg in str(e.value)
|
| 177 |
+
|
| 178 |
+
# if self-loops are allowed, smaller example:
|
| 179 |
+
G = nx.DiGraph()
|
| 180 |
+
G.add_edge("a", "b") # a has in-degree zero
|
| 181 |
+
G.add_edge("c", "b") # b is one level above a and c
|
| 182 |
+
G.add_edge("c", "c") # c has a self-loop
|
| 183 |
+
with pytest.raises(nx.NetworkXError) as e:
|
| 184 |
+
nx.trophic_levels(G)
|
| 185 |
+
msg = (
|
| 186 |
+
"Trophic levels are only defined for graphs where every node "
|
| 187 |
+
+ "has a path from a basal node (basal nodes are nodes with no "
|
| 188 |
+
+ "incoming edges)."
|
| 189 |
+
)
|
| 190 |
+
assert msg in str(e.value)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_trophic_differences():
|
| 194 |
+
matrix_a = np.array([[0, 1], [0, 0]])
|
| 195 |
+
G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
|
| 196 |
+
diffs = nx.trophic_differences(G)
|
| 197 |
+
assert diffs[(0, 1)] == pytest.approx(1, abs=1e-7)
|
| 198 |
+
|
| 199 |
+
# fmt: off
|
| 200 |
+
matrix_b = np.array([
|
| 201 |
+
[0, 1, 1, 0],
|
| 202 |
+
[0, 0, 1, 1],
|
| 203 |
+
[0, 0, 0, 1],
|
| 204 |
+
[0, 0, 0, 0]
|
| 205 |
+
])
|
| 206 |
+
# fmt: on
|
| 207 |
+
G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
|
| 208 |
+
diffs = nx.trophic_differences(G)
|
| 209 |
+
|
| 210 |
+
assert diffs[(0, 1)] == pytest.approx(1, abs=1e-7)
|
| 211 |
+
assert diffs[(0, 2)] == pytest.approx(1.5, abs=1e-7)
|
| 212 |
+
assert diffs[(1, 2)] == pytest.approx(0.5, abs=1e-7)
|
| 213 |
+
assert diffs[(1, 3)] == pytest.approx(1.25, abs=1e-7)
|
| 214 |
+
assert diffs[(2, 3)] == pytest.approx(0.75, abs=1e-7)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def test_trophic_incoherence_parameter_no_cannibalism():
|
| 218 |
+
matrix_a = np.array([[0, 1], [0, 0]])
|
| 219 |
+
G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
|
| 220 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=False)
|
| 221 |
+
assert q == pytest.approx(0, abs=1e-7)
|
| 222 |
+
|
| 223 |
+
# fmt: off
|
| 224 |
+
matrix_b = np.array([
|
| 225 |
+
[0, 1, 1, 0],
|
| 226 |
+
[0, 0, 1, 1],
|
| 227 |
+
[0, 0, 0, 1],
|
| 228 |
+
[0, 0, 0, 0]
|
| 229 |
+
])
|
| 230 |
+
# fmt: on
|
| 231 |
+
G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
|
| 232 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=False)
|
| 233 |
+
assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
|
| 234 |
+
|
| 235 |
+
# fmt: off
|
| 236 |
+
matrix_c = np.array([
|
| 237 |
+
[0, 1, 1, 0],
|
| 238 |
+
[0, 1, 1, 1],
|
| 239 |
+
[0, 0, 0, 1],
|
| 240 |
+
[0, 0, 0, 1]
|
| 241 |
+
])
|
| 242 |
+
# fmt: on
|
| 243 |
+
G = nx.from_numpy_array(matrix_c, create_using=nx.DiGraph)
|
| 244 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=False)
|
| 245 |
+
# Ignore the -link
|
| 246 |
+
assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
|
| 247 |
+
|
| 248 |
+
# no self-loops case
|
| 249 |
+
# fmt: off
|
| 250 |
+
matrix_d = np.array([
|
| 251 |
+
[0, 1, 1, 0],
|
| 252 |
+
[0, 0, 1, 1],
|
| 253 |
+
[0, 0, 0, 1],
|
| 254 |
+
[0, 0, 0, 0]
|
| 255 |
+
])
|
| 256 |
+
# fmt: on
|
| 257 |
+
G = nx.from_numpy_array(matrix_d, create_using=nx.DiGraph)
|
| 258 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=False)
|
| 259 |
+
# Ignore the -link
|
| 260 |
+
assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def test_trophic_incoherence_parameter_cannibalism():
|
| 264 |
+
matrix_a = np.array([[0, 1], [0, 0]])
|
| 265 |
+
G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
|
| 266 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=True)
|
| 267 |
+
assert q == pytest.approx(0, abs=1e-7)
|
| 268 |
+
|
| 269 |
+
# fmt: off
|
| 270 |
+
matrix_b = np.array([
|
| 271 |
+
[0, 0, 0, 0, 0],
|
| 272 |
+
[0, 1, 0, 1, 0],
|
| 273 |
+
[1, 0, 0, 0, 0],
|
| 274 |
+
[0, 1, 0, 0, 0],
|
| 275 |
+
[0, 0, 0, 1, 0]
|
| 276 |
+
])
|
| 277 |
+
# fmt: on
|
| 278 |
+
G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
|
| 279 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=True)
|
| 280 |
+
assert q == pytest.approx(2, abs=1e-7)
|
| 281 |
+
|
| 282 |
+
# fmt: off
|
| 283 |
+
matrix_c = np.array([
|
| 284 |
+
[0, 1, 1, 0],
|
| 285 |
+
[0, 0, 1, 1],
|
| 286 |
+
[0, 0, 0, 1],
|
| 287 |
+
[0, 0, 0, 0]
|
| 288 |
+
])
|
| 289 |
+
# fmt: on
|
| 290 |
+
G = nx.from_numpy_array(matrix_c, create_using=nx.DiGraph)
|
| 291 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=True)
|
| 292 |
+
# Ignore the -link
|
| 293 |
+
assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def test_no_basal_node():
|
| 297 |
+
G = nx.DiGraph([(1, 2), (2, 3), (3, 1)]) # No basal node, should raise an error
|
| 298 |
+
with pytest.raises(nx.NetworkXError, match="no basal node"):
|
| 299 |
+
nx.trophic_levels(G)
|
| 300 |
+
G.add_node(4) # add basal node, but not connected
|
| 301 |
+
with pytest.raises(nx.NetworkXError, match="every node .* path from a basal node"):
|
| 302 |
+
nx.trophic_levels(G)
|
.venv/lib/python3.11/site-packages/networkx/algorithms/centrality/tests/test_voterank.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unit tests for VoteRank.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestVoteRankCentrality:
|
| 9 |
+
# Example Graph present in reference paper
|
| 10 |
+
def test_voterank_centrality_1(self):
|
| 11 |
+
G = nx.Graph()
|
| 12 |
+
G.add_edges_from(
|
| 13 |
+
[
|
| 14 |
+
(7, 8),
|
| 15 |
+
(7, 5),
|
| 16 |
+
(7, 9),
|
| 17 |
+
(5, 0),
|
| 18 |
+
(0, 1),
|
| 19 |
+
(0, 2),
|
| 20 |
+
(0, 3),
|
| 21 |
+
(0, 4),
|
| 22 |
+
(1, 6),
|
| 23 |
+
(2, 6),
|
| 24 |
+
(3, 6),
|
| 25 |
+
(4, 6),
|
| 26 |
+
]
|
| 27 |
+
)
|
| 28 |
+
assert [0, 7, 6] == nx.voterank(G)
|
| 29 |
+
|
| 30 |
+
def test_voterank_emptygraph(self):
|
| 31 |
+
G = nx.Graph()
|
| 32 |
+
assert [] == nx.voterank(G)
|
| 33 |
+
|
| 34 |
+
# Graph unit test
|
| 35 |
+
def test_voterank_centrality_2(self):
|
| 36 |
+
G = nx.florentine_families_graph()
|
| 37 |
+
d = nx.voterank(G, 4)
|
| 38 |
+
exact = ["Medici", "Strozzi", "Guadagni", "Castellani"]
|
| 39 |
+
assert exact == d
|
| 40 |
+
|
| 41 |
+
# DiGraph unit test
|
| 42 |
+
def test_voterank_centrality_3(self):
|
| 43 |
+
G = nx.gnc_graph(10, seed=7)
|
| 44 |
+
d = nx.voterank(G, 4)
|
| 45 |
+
exact = [3, 6, 8]
|
| 46 |
+
assert exact == d
|
| 47 |
+
|
| 48 |
+
# MultiGraph unit test
|
| 49 |
+
def test_voterank_centrality_4(self):
|
| 50 |
+
G = nx.MultiGraph()
|
| 51 |
+
G.add_edges_from(
|
| 52 |
+
[(0, 1), (0, 1), (1, 2), (2, 5), (2, 5), (5, 6), (5, 6), (2, 4), (4, 3)]
|
| 53 |
+
)
|
| 54 |
+
exact = [2, 1, 5, 4]
|
| 55 |
+
assert exact == nx.voterank(G)
|
| 56 |
+
|
| 57 |
+
# MultiDiGraph unit test
|
| 58 |
+
def test_voterank_centrality_5(self):
|
| 59 |
+
G = nx.MultiDiGraph()
|
| 60 |
+
G.add_edges_from(
|
| 61 |
+
[(0, 1), (0, 1), (1, 2), (2, 5), (2, 5), (5, 6), (5, 6), (2, 4), (4, 3)]
|
| 62 |
+
)
|
| 63 |
+
exact = [2, 0, 5, 4]
|
| 64 |
+
assert exact == nx.voterank(G)
|
.venv/lib/python3.11/site-packages/networkx/algorithms/centrality/trophic.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trophic levels"""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.utils import not_implemented_for
|
| 5 |
+
|
| 6 |
+
__all__ = ["trophic_levels", "trophic_differences", "trophic_incoherence_parameter"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@not_implemented_for("undirected")
|
| 10 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 11 |
+
def trophic_levels(G, weight="weight"):
|
| 12 |
+
r"""Compute the trophic levels of nodes.
|
| 13 |
+
|
| 14 |
+
The trophic level of a node $i$ is
|
| 15 |
+
|
| 16 |
+
.. math::
|
| 17 |
+
|
| 18 |
+
s_i = 1 + \frac{1}{k^{in}_i} \sum_{j} a_{ij} s_j
|
| 19 |
+
|
| 20 |
+
where $k^{in}_i$ is the in-degree of i
|
| 21 |
+
|
| 22 |
+
.. math::
|
| 23 |
+
|
| 24 |
+
k^{in}_i = \sum_{j} a_{ij}
|
| 25 |
+
|
| 26 |
+
and nodes with $k^{in}_i = 0$ have $s_i = 1$ by convention.
|
| 27 |
+
|
| 28 |
+
These are calculated using the method outlined in Levine [1]_.
|
| 29 |
+
|
| 30 |
+
Parameters
|
| 31 |
+
----------
|
| 32 |
+
G : DiGraph
|
| 33 |
+
A directed networkx graph
|
| 34 |
+
|
| 35 |
+
Returns
|
| 36 |
+
-------
|
| 37 |
+
nodes : dict
|
| 38 |
+
Dictionary of nodes with trophic level as the value.
|
| 39 |
+
|
| 40 |
+
References
|
| 41 |
+
----------
|
| 42 |
+
.. [1] Stephen Levine (1980) J. theor. Biol. 83, 195-207
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
basal_nodes = [n for n, deg in G.in_degree if deg == 0]
|
| 46 |
+
if not basal_nodes:
|
| 47 |
+
raise nx.NetworkXError(
|
| 48 |
+
"This graph has no basal nodes (nodes with no incoming edges)."
|
| 49 |
+
"Trophic levels are not defined without at least one basal node."
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
reachable_nodes = {
|
| 53 |
+
node for layer in nx.bfs_layers(G, sources=basal_nodes) for node in layer
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
if len(reachable_nodes) != len(G.nodes):
|
| 57 |
+
raise nx.NetworkXError(
|
| 58 |
+
"Trophic levels are only defined for graphs where every node has a path "
|
| 59 |
+
"from a basal node (basal nodes are nodes with no incoming edges)."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
import numpy as np
|
| 63 |
+
|
| 64 |
+
# find adjacency matrix
|
| 65 |
+
a = nx.adjacency_matrix(G, weight=weight).T.toarray()
|
| 66 |
+
|
| 67 |
+
# drop rows/columns where in-degree is zero
|
| 68 |
+
rowsum = np.sum(a, axis=1)
|
| 69 |
+
p = a[rowsum != 0][:, rowsum != 0]
|
| 70 |
+
# normalise so sum of in-degree weights is 1 along each row
|
| 71 |
+
p = p / rowsum[rowsum != 0][:, np.newaxis]
|
| 72 |
+
|
| 73 |
+
# calculate trophic levels
|
| 74 |
+
nn = p.shape[0]
|
| 75 |
+
i = np.eye(nn)
|
| 76 |
+
try:
|
| 77 |
+
n = np.linalg.inv(i - p)
|
| 78 |
+
except np.linalg.LinAlgError as err:
|
| 79 |
+
# LinAlgError is raised when there is a non-basal node
|
| 80 |
+
msg = (
|
| 81 |
+
"Trophic levels are only defined for graphs where every "
|
| 82 |
+
+ "node has a path from a basal node (basal nodes are nodes "
|
| 83 |
+
+ "with no incoming edges)."
|
| 84 |
+
)
|
| 85 |
+
raise nx.NetworkXError(msg) from err
|
| 86 |
+
y = n.sum(axis=1) + 1
|
| 87 |
+
|
| 88 |
+
levels = {}
|
| 89 |
+
|
| 90 |
+
# all nodes with in-degree zero have trophic level == 1
|
| 91 |
+
zero_node_ids = (node_id for node_id, degree in G.in_degree if degree == 0)
|
| 92 |
+
for node_id in zero_node_ids:
|
| 93 |
+
levels[node_id] = 1
|
| 94 |
+
|
| 95 |
+
# all other nodes have levels as calculated
|
| 96 |
+
nonzero_node_ids = (node_id for node_id, degree in G.in_degree if degree != 0)
|
| 97 |
+
for i, node_id in enumerate(nonzero_node_ids):
|
| 98 |
+
levels[node_id] = y.item(i)
|
| 99 |
+
|
| 100 |
+
return levels
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@not_implemented_for("undirected")
|
| 104 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 105 |
+
def trophic_differences(G, weight="weight"):
|
| 106 |
+
r"""Compute the trophic differences of the edges of a directed graph.
|
| 107 |
+
|
| 108 |
+
The trophic difference $x_ij$ for each edge is defined in Johnson et al.
|
| 109 |
+
[1]_ as:
|
| 110 |
+
|
| 111 |
+
.. math::
|
| 112 |
+
x_ij = s_j - s_i
|
| 113 |
+
|
| 114 |
+
Where $s_i$ is the trophic level of node $i$.
|
| 115 |
+
|
| 116 |
+
Parameters
|
| 117 |
+
----------
|
| 118 |
+
G : DiGraph
|
| 119 |
+
A directed networkx graph
|
| 120 |
+
|
| 121 |
+
Returns
|
| 122 |
+
-------
|
| 123 |
+
diffs : dict
|
| 124 |
+
Dictionary of edges with trophic differences as the value.
|
| 125 |
+
|
| 126 |
+
References
|
| 127 |
+
----------
|
| 128 |
+
.. [1] Samuel Johnson, Virginia Dominguez-Garcia, Luca Donetti, Miguel A.
|
| 129 |
+
Munoz (2014) PNAS "Trophic coherence determines food-web stability"
|
| 130 |
+
"""
|
| 131 |
+
levels = trophic_levels(G, weight=weight)
|
| 132 |
+
diffs = {}
|
| 133 |
+
for u, v in G.edges:
|
| 134 |
+
diffs[(u, v)] = levels[v] - levels[u]
|
| 135 |
+
return diffs
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@not_implemented_for("undirected")
|
| 139 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 140 |
+
def trophic_incoherence_parameter(G, weight="weight", cannibalism=False):
|
| 141 |
+
r"""Compute the trophic incoherence parameter of a graph.
|
| 142 |
+
|
| 143 |
+
Trophic coherence is defined as the homogeneity of the distribution of
|
| 144 |
+
trophic distances: the more similar, the more coherent. This is measured by
|
| 145 |
+
the standard deviation of the trophic differences and referred to as the
|
| 146 |
+
trophic incoherence parameter $q$ by [1].
|
| 147 |
+
|
| 148 |
+
Parameters
|
| 149 |
+
----------
|
| 150 |
+
G : DiGraph
|
| 151 |
+
A directed networkx graph
|
| 152 |
+
|
| 153 |
+
cannibalism: Boolean
|
| 154 |
+
If set to False, self edges are not considered in the calculation
|
| 155 |
+
|
| 156 |
+
Returns
|
| 157 |
+
-------
|
| 158 |
+
trophic_incoherence_parameter : float
|
| 159 |
+
The trophic coherence of a graph
|
| 160 |
+
|
| 161 |
+
References
|
| 162 |
+
----------
|
| 163 |
+
.. [1] Samuel Johnson, Virginia Dominguez-Garcia, Luca Donetti, Miguel A.
|
| 164 |
+
Munoz (2014) PNAS "Trophic coherence determines food-web stability"
|
| 165 |
+
"""
|
| 166 |
+
import numpy as np
|
| 167 |
+
|
| 168 |
+
if cannibalism:
|
| 169 |
+
diffs = trophic_differences(G, weight=weight)
|
| 170 |
+
else:
|
| 171 |
+
# If no cannibalism, remove self-edges
|
| 172 |
+
self_loops = list(nx.selfloop_edges(G))
|
| 173 |
+
if self_loops:
|
| 174 |
+
# Make a copy so we do not change G's edges in memory
|
| 175 |
+
G_2 = G.copy()
|
| 176 |
+
G_2.remove_edges_from(self_loops)
|
| 177 |
+
else:
|
| 178 |
+
# Avoid copy otherwise
|
| 179 |
+
G_2 = G
|
| 180 |
+
diffs = trophic_differences(G_2, weight=weight)
|
| 181 |
+
return float(np.std(list(diffs.values())))
|
.venv/lib/python3.11/site-packages/networkx/algorithms/centrality/voterank_alg.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Algorithm to select influential nodes in a graph using VoteRank."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = ["voterank"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@nx._dispatchable
|
| 9 |
+
def voterank(G, number_of_nodes=None):
|
| 10 |
+
"""Select a list of influential nodes in a graph using VoteRank algorithm
|
| 11 |
+
|
| 12 |
+
VoteRank [1]_ computes a ranking of the nodes in a graph G based on a
|
| 13 |
+
voting scheme. With VoteRank, all nodes vote for each of its in-neighbors
|
| 14 |
+
and the node with the highest votes is elected iteratively. The voting
|
| 15 |
+
ability of out-neighbors of elected nodes is decreased in subsequent turns.
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
----------
|
| 19 |
+
G : graph
|
| 20 |
+
A NetworkX graph.
|
| 21 |
+
|
| 22 |
+
number_of_nodes : integer, optional
|
| 23 |
+
Number of ranked nodes to extract (default all nodes).
|
| 24 |
+
|
| 25 |
+
Returns
|
| 26 |
+
-------
|
| 27 |
+
voterank : list
|
| 28 |
+
Ordered list of computed seeds.
|
| 29 |
+
Only nodes with positive number of votes are returned.
|
| 30 |
+
|
| 31 |
+
Examples
|
| 32 |
+
--------
|
| 33 |
+
>>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 4)])
|
| 34 |
+
>>> nx.voterank(G)
|
| 35 |
+
[0, 1]
|
| 36 |
+
|
| 37 |
+
The algorithm can be used both for undirected and directed graphs.
|
| 38 |
+
However, the directed version is different in two ways:
|
| 39 |
+
(i) nodes only vote for their in-neighbors and
|
| 40 |
+
(ii) only the voting ability of elected node and its out-neighbors are updated:
|
| 41 |
+
|
| 42 |
+
>>> G = nx.DiGraph([(0, 1), (2, 1), (2, 3), (3, 4)])
|
| 43 |
+
>>> nx.voterank(G)
|
| 44 |
+
[2, 3]
|
| 45 |
+
|
| 46 |
+
Notes
|
| 47 |
+
-----
|
| 48 |
+
Each edge is treated independently in case of multigraphs.
|
| 49 |
+
|
| 50 |
+
References
|
| 51 |
+
----------
|
| 52 |
+
.. [1] Zhang, J.-X. et al. (2016).
|
| 53 |
+
Identifying a set of influential spreaders in complex networks.
|
| 54 |
+
Sci. Rep. 6, 27823; doi: 10.1038/srep27823.
|
| 55 |
+
"""
|
| 56 |
+
influential_nodes = []
|
| 57 |
+
vote_rank = {}
|
| 58 |
+
if len(G) == 0:
|
| 59 |
+
return influential_nodes
|
| 60 |
+
if number_of_nodes is None or number_of_nodes > len(G):
|
| 61 |
+
number_of_nodes = len(G)
|
| 62 |
+
if G.is_directed():
|
| 63 |
+
# For directed graphs compute average out-degree
|
| 64 |
+
avgDegree = sum(deg for _, deg in G.out_degree()) / len(G)
|
| 65 |
+
else:
|
| 66 |
+
# For undirected graphs compute average degree
|
| 67 |
+
avgDegree = sum(deg for _, deg in G.degree()) / len(G)
|
| 68 |
+
# step 1 - initiate all nodes to (0,1) (score, voting ability)
|
| 69 |
+
for n in G.nodes():
|
| 70 |
+
vote_rank[n] = [0, 1]
|
| 71 |
+
# Repeat steps 1b to 4 until num_seeds are elected.
|
| 72 |
+
for _ in range(number_of_nodes):
|
| 73 |
+
# step 1b - reset rank
|
| 74 |
+
for n in G.nodes():
|
| 75 |
+
vote_rank[n][0] = 0
|
| 76 |
+
# step 2 - vote
|
| 77 |
+
for n, nbr in G.edges():
|
| 78 |
+
# In directed graphs nodes only vote for their in-neighbors
|
| 79 |
+
vote_rank[n][0] += vote_rank[nbr][1]
|
| 80 |
+
if not G.is_directed():
|
| 81 |
+
vote_rank[nbr][0] += vote_rank[n][1]
|
| 82 |
+
for n in influential_nodes:
|
| 83 |
+
vote_rank[n][0] = 0
|
| 84 |
+
# step 3 - select top node
|
| 85 |
+
n = max(G.nodes, key=lambda x: vote_rank[x][0])
|
| 86 |
+
if vote_rank[n][0] == 0:
|
| 87 |
+
return influential_nodes
|
| 88 |
+
influential_nodes.append(n)
|
| 89 |
+
# weaken the selected node
|
| 90 |
+
vote_rank[n] = [0, 0]
|
| 91 |
+
# step 4 - update voterank properties
|
| 92 |
+
for _, nbr in G.edges(n):
|
| 93 |
+
vote_rank[nbr][1] -= 1 / avgDegree
|
| 94 |
+
vote_rank[nbr][1] = max(vote_rank[nbr][1], 0)
|
| 95 |
+
return influential_nodes
|
.venv/lib/python3.11/site-packages/networkx/algorithms/chains.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for finding chains in a graph."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.utils import not_implemented_for
|
| 5 |
+
|
| 6 |
+
__all__ = ["chain_decomposition"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@not_implemented_for("directed")
|
| 10 |
+
@not_implemented_for("multigraph")
|
| 11 |
+
@nx._dispatchable
|
| 12 |
+
def chain_decomposition(G, root=None):
|
| 13 |
+
"""Returns the chain decomposition of a graph.
|
| 14 |
+
|
| 15 |
+
The *chain decomposition* of a graph with respect a depth-first
|
| 16 |
+
search tree is a set of cycles or paths derived from the set of
|
| 17 |
+
fundamental cycles of the tree in the following manner. Consider
|
| 18 |
+
each fundamental cycle with respect to the given tree, represented
|
| 19 |
+
as a list of edges beginning with the nontree edge oriented away
|
| 20 |
+
from the root of the tree. For each fundamental cycle, if it
|
| 21 |
+
overlaps with any previous fundamental cycle, just take the initial
|
| 22 |
+
non-overlapping segment, which is a path instead of a cycle. Each
|
| 23 |
+
cycle or path is called a *chain*. For more information, see [1]_.
|
| 24 |
+
|
| 25 |
+
Parameters
|
| 26 |
+
----------
|
| 27 |
+
G : undirected graph
|
| 28 |
+
|
| 29 |
+
root : node (optional)
|
| 30 |
+
A node in the graph `G`. If specified, only the chain
|
| 31 |
+
decomposition for the connected component containing this node
|
| 32 |
+
will be returned. This node indicates the root of the depth-first
|
| 33 |
+
search tree.
|
| 34 |
+
|
| 35 |
+
Yields
|
| 36 |
+
------
|
| 37 |
+
chain : list
|
| 38 |
+
A list of edges representing a chain. There is no guarantee on
|
| 39 |
+
the orientation of the edges in each chain (for example, if a
|
| 40 |
+
chain includes the edge joining nodes 1 and 2, the chain may
|
| 41 |
+
include either (1, 2) or (2, 1)).
|
| 42 |
+
|
| 43 |
+
Raises
|
| 44 |
+
------
|
| 45 |
+
NodeNotFound
|
| 46 |
+
If `root` is not in the graph `G`.
|
| 47 |
+
|
| 48 |
+
Examples
|
| 49 |
+
--------
|
| 50 |
+
>>> G = nx.Graph([(0, 1), (1, 4), (3, 4), (3, 5), (4, 5)])
|
| 51 |
+
>>> list(nx.chain_decomposition(G))
|
| 52 |
+
[[(4, 5), (5, 3), (3, 4)]]
|
| 53 |
+
|
| 54 |
+
Notes
|
| 55 |
+
-----
|
| 56 |
+
The worst-case running time of this implementation is linear in the
|
| 57 |
+
number of nodes and number of edges [1]_.
|
| 58 |
+
|
| 59 |
+
References
|
| 60 |
+
----------
|
| 61 |
+
.. [1] Jens M. Schmidt (2013). "A simple test on 2-vertex-
|
| 62 |
+
and 2-edge-connectivity." *Information Processing Letters*,
|
| 63 |
+
113, 241–244. Elsevier. <https://doi.org/10.1016/j.ipl.2013.01.016>
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def _dfs_cycle_forest(G, root=None):
|
| 68 |
+
"""Builds a directed graph composed of cycles from the given graph.
|
| 69 |
+
|
| 70 |
+
`G` is an undirected simple graph. `root` is a node in the graph
|
| 71 |
+
from which the depth-first search is started.
|
| 72 |
+
|
| 73 |
+
This function returns both the depth-first search cycle graph
|
| 74 |
+
(as a :class:`~networkx.DiGraph`) and the list of nodes in
|
| 75 |
+
depth-first preorder. The depth-first search cycle graph is a
|
| 76 |
+
directed graph whose edges are the edges of `G` oriented toward
|
| 77 |
+
the root if the edge is a tree edge and away from the root if
|
| 78 |
+
the edge is a non-tree edge. If `root` is not specified, this
|
| 79 |
+
performs a depth-first search on each connected component of `G`
|
| 80 |
+
and returns a directed forest instead.
|
| 81 |
+
|
| 82 |
+
If `root` is not in the graph, this raises :exc:`KeyError`.
|
| 83 |
+
|
| 84 |
+
"""
|
| 85 |
+
# Create a directed graph from the depth-first search tree with
|
| 86 |
+
# root node `root` in which tree edges are directed toward the
|
| 87 |
+
# root and nontree edges are directed away from the root. For
|
| 88 |
+
# each node with an incident nontree edge, this creates a
|
| 89 |
+
# directed cycle starting with the nontree edge and returning to
|
| 90 |
+
# that node.
|
| 91 |
+
#
|
| 92 |
+
# The `parent` node attribute stores the parent of each node in
|
| 93 |
+
# the DFS tree. The `nontree` edge attribute indicates whether
|
| 94 |
+
# the edge is a tree edge or a nontree edge.
|
| 95 |
+
#
|
| 96 |
+
# We also store the order of the nodes found in the depth-first
|
| 97 |
+
# search in the `nodes` list.
|
| 98 |
+
H = nx.DiGraph()
|
| 99 |
+
nodes = []
|
| 100 |
+
for u, v, d in nx.dfs_labeled_edges(G, source=root):
|
| 101 |
+
if d == "forward":
|
| 102 |
+
# `dfs_labeled_edges()` yields (root, root, 'forward')
|
| 103 |
+
# if it is beginning the search on a new connected
|
| 104 |
+
# component.
|
| 105 |
+
if u == v:
|
| 106 |
+
H.add_node(v, parent=None)
|
| 107 |
+
nodes.append(v)
|
| 108 |
+
else:
|
| 109 |
+
H.add_node(v, parent=u)
|
| 110 |
+
H.add_edge(v, u, nontree=False)
|
| 111 |
+
nodes.append(v)
|
| 112 |
+
# `dfs_labeled_edges` considers nontree edges in both
|
| 113 |
+
# orientations, so we need to not add the edge if it its
|
| 114 |
+
# other orientation has been added.
|
| 115 |
+
elif d == "nontree" and v not in H[u]:
|
| 116 |
+
H.add_edge(v, u, nontree=True)
|
| 117 |
+
else:
|
| 118 |
+
# Do nothing on 'reverse' edges; we only care about
|
| 119 |
+
# forward and nontree edges.
|
| 120 |
+
pass
|
| 121 |
+
return H, nodes
|
| 122 |
+
|
| 123 |
+
def _build_chain(G, u, v, visited):
|
| 124 |
+
"""Generate the chain starting from the given nontree edge.
|
| 125 |
+
|
| 126 |
+
`G` is a DFS cycle graph as constructed by
|
| 127 |
+
:func:`_dfs_cycle_graph`. The edge (`u`, `v`) is a nontree edge
|
| 128 |
+
that begins a chain. `visited` is a set representing the nodes
|
| 129 |
+
in `G` that have already been visited.
|
| 130 |
+
|
| 131 |
+
This function yields the edges in an initial segment of the
|
| 132 |
+
fundamental cycle of `G` starting with the nontree edge (`u`,
|
| 133 |
+
`v`) that includes all the edges up until the first node that
|
| 134 |
+
appears in `visited`. The tree edges are given by the 'parent'
|
| 135 |
+
node attribute. The `visited` set is updated to add each node in
|
| 136 |
+
an edge yielded by this function.
|
| 137 |
+
|
| 138 |
+
"""
|
| 139 |
+
while v not in visited:
|
| 140 |
+
yield u, v
|
| 141 |
+
visited.add(v)
|
| 142 |
+
u, v = v, G.nodes[v]["parent"]
|
| 143 |
+
yield u, v
|
| 144 |
+
|
| 145 |
+
# Check if the root is in the graph G. If not, raise NodeNotFound
|
| 146 |
+
if root is not None and root not in G:
|
| 147 |
+
raise nx.NodeNotFound(f"Root node {root} is not in graph")
|
| 148 |
+
|
| 149 |
+
# Create a directed version of H that has the DFS edges directed
|
| 150 |
+
# toward the root and the nontree edges directed away from the root
|
| 151 |
+
# (in each connected component).
|
| 152 |
+
H, nodes = _dfs_cycle_forest(G, root)
|
| 153 |
+
|
| 154 |
+
# Visit the nodes again in DFS order. For each node, and for each
|
| 155 |
+
# nontree edge leaving that node, compute the fundamental cycle for
|
| 156 |
+
# that nontree edge starting with that edge. If the fundamental
|
| 157 |
+
# cycle overlaps with any visited nodes, just take the prefix of the
|
| 158 |
+
# cycle up to the point of visited nodes.
|
| 159 |
+
#
|
| 160 |
+
# We repeat this process for each connected component (implicitly,
|
| 161 |
+
# since `nodes` already has a list of the nodes grouped by connected
|
| 162 |
+
# component).
|
| 163 |
+
visited = set()
|
| 164 |
+
for u in nodes:
|
| 165 |
+
visited.add(u)
|
| 166 |
+
# For each nontree edge going out of node u...
|
| 167 |
+
edges = ((u, v) for u, v, d in H.out_edges(u, data="nontree") if d)
|
| 168 |
+
for u, v in edges:
|
| 169 |
+
# Create the cycle or cycle prefix starting with the
|
| 170 |
+
# nontree edge.
|
| 171 |
+
chain = list(_build_chain(H, u, v, visited))
|
| 172 |
+
yield chain
|
.venv/lib/python3.11/site-packages/networkx/algorithms/chordal.py
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Algorithms for chordal graphs.
|
| 3 |
+
|
| 4 |
+
A graph is chordal if every cycle of length at least 4 has a chord
|
| 5 |
+
(an edge joining two nodes not adjacent in the cycle).
|
| 6 |
+
https://en.wikipedia.org/wiki/Chordal_graph
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
import networkx as nx
|
| 12 |
+
from networkx.algorithms.components import connected_components
|
| 13 |
+
from networkx.utils import arbitrary_element, not_implemented_for
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
"is_chordal",
|
| 17 |
+
"find_induced_nodes",
|
| 18 |
+
"chordal_graph_cliques",
|
| 19 |
+
"chordal_graph_treewidth",
|
| 20 |
+
"NetworkXTreewidthBoundExceeded",
|
| 21 |
+
"complete_to_chordal_graph",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class NetworkXTreewidthBoundExceeded(nx.NetworkXException):
|
| 26 |
+
"""Exception raised when a treewidth bound has been provided and it has
|
| 27 |
+
been exceeded"""
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@not_implemented_for("directed")
|
| 31 |
+
@not_implemented_for("multigraph")
|
| 32 |
+
@nx._dispatchable
|
| 33 |
+
def is_chordal(G):
|
| 34 |
+
"""Checks whether G is a chordal graph.
|
| 35 |
+
|
| 36 |
+
A graph is chordal if every cycle of length at least 4 has a chord
|
| 37 |
+
(an edge joining two nodes not adjacent in the cycle).
|
| 38 |
+
|
| 39 |
+
Parameters
|
| 40 |
+
----------
|
| 41 |
+
G : graph
|
| 42 |
+
A NetworkX graph.
|
| 43 |
+
|
| 44 |
+
Returns
|
| 45 |
+
-------
|
| 46 |
+
chordal : bool
|
| 47 |
+
True if G is a chordal graph and False otherwise.
|
| 48 |
+
|
| 49 |
+
Raises
|
| 50 |
+
------
|
| 51 |
+
NetworkXNotImplemented
|
| 52 |
+
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
|
| 53 |
+
|
| 54 |
+
Examples
|
| 55 |
+
--------
|
| 56 |
+
>>> e = [
|
| 57 |
+
... (1, 2),
|
| 58 |
+
... (1, 3),
|
| 59 |
+
... (2, 3),
|
| 60 |
+
... (2, 4),
|
| 61 |
+
... (3, 4),
|
| 62 |
+
... (3, 5),
|
| 63 |
+
... (3, 6),
|
| 64 |
+
... (4, 5),
|
| 65 |
+
... (4, 6),
|
| 66 |
+
... (5, 6),
|
| 67 |
+
... ]
|
| 68 |
+
>>> G = nx.Graph(e)
|
| 69 |
+
>>> nx.is_chordal(G)
|
| 70 |
+
True
|
| 71 |
+
|
| 72 |
+
Notes
|
| 73 |
+
-----
|
| 74 |
+
The routine tries to go through every node following maximum cardinality
|
| 75 |
+
search. It returns False when it finds that the separator for any node
|
| 76 |
+
is not a clique. Based on the algorithms in [1]_.
|
| 77 |
+
|
| 78 |
+
Self loops are ignored.
|
| 79 |
+
|
| 80 |
+
References
|
| 81 |
+
----------
|
| 82 |
+
.. [1] R. E. Tarjan and M. Yannakakis, Simple linear-time algorithms
|
| 83 |
+
to test chordality of graphs, test acyclicity of hypergraphs, and
|
| 84 |
+
selectively reduce acyclic hypergraphs, SIAM J. Comput., 13 (1984),
|
| 85 |
+
pp. 566–579.
|
| 86 |
+
"""
|
| 87 |
+
if len(G.nodes) <= 3:
|
| 88 |
+
return True
|
| 89 |
+
return len(_find_chordality_breaker(G)) == 0
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@nx._dispatchable
|
| 93 |
+
def find_induced_nodes(G, s, t, treewidth_bound=sys.maxsize):
|
| 94 |
+
"""Returns the set of induced nodes in the path from s to t.
|
| 95 |
+
|
| 96 |
+
Parameters
|
| 97 |
+
----------
|
| 98 |
+
G : graph
|
| 99 |
+
A chordal NetworkX graph
|
| 100 |
+
s : node
|
| 101 |
+
Source node to look for induced nodes
|
| 102 |
+
t : node
|
| 103 |
+
Destination node to look for induced nodes
|
| 104 |
+
treewidth_bound: float
|
| 105 |
+
Maximum treewidth acceptable for the graph H. The search
|
| 106 |
+
for induced nodes will end as soon as the treewidth_bound is exceeded.
|
| 107 |
+
|
| 108 |
+
Returns
|
| 109 |
+
-------
|
| 110 |
+
induced_nodes : Set of nodes
|
| 111 |
+
The set of induced nodes in the path from s to t in G
|
| 112 |
+
|
| 113 |
+
Raises
|
| 114 |
+
------
|
| 115 |
+
NetworkXError
|
| 116 |
+
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
|
| 117 |
+
If the input graph is an instance of one of these classes, a
|
| 118 |
+
:exc:`NetworkXError` is raised.
|
| 119 |
+
The algorithm can only be applied to chordal graphs. If the input
|
| 120 |
+
graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
|
| 121 |
+
|
| 122 |
+
Examples
|
| 123 |
+
--------
|
| 124 |
+
>>> G = nx.Graph()
|
| 125 |
+
>>> G = nx.generators.classic.path_graph(10)
|
| 126 |
+
>>> induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
|
| 127 |
+
>>> sorted(induced_nodes)
|
| 128 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9]
|
| 129 |
+
|
| 130 |
+
Notes
|
| 131 |
+
-----
|
| 132 |
+
G must be a chordal graph and (s,t) an edge that is not in G.
|
| 133 |
+
|
| 134 |
+
If a treewidth_bound is provided, the search for induced nodes will end
|
| 135 |
+
as soon as the treewidth_bound is exceeded.
|
| 136 |
+
|
| 137 |
+
The algorithm is inspired by Algorithm 4 in [1]_.
|
| 138 |
+
A formal definition of induced node can also be found on that reference.
|
| 139 |
+
|
| 140 |
+
Self Loops are ignored
|
| 141 |
+
|
| 142 |
+
References
|
| 143 |
+
----------
|
| 144 |
+
.. [1] Learning Bounded Treewidth Bayesian Networks.
|
| 145 |
+
Gal Elidan, Stephen Gould; JMLR, 9(Dec):2699--2731, 2008.
|
| 146 |
+
http://jmlr.csail.mit.edu/papers/volume9/elidan08a/elidan08a.pdf
|
| 147 |
+
"""
|
| 148 |
+
if not is_chordal(G):
|
| 149 |
+
raise nx.NetworkXError("Input graph is not chordal.")
|
| 150 |
+
|
| 151 |
+
H = nx.Graph(G)
|
| 152 |
+
H.add_edge(s, t)
|
| 153 |
+
induced_nodes = set()
|
| 154 |
+
triplet = _find_chordality_breaker(H, s, treewidth_bound)
|
| 155 |
+
while triplet:
|
| 156 |
+
(u, v, w) = triplet
|
| 157 |
+
induced_nodes.update(triplet)
|
| 158 |
+
for n in triplet:
|
| 159 |
+
if n != s:
|
| 160 |
+
H.add_edge(s, n)
|
| 161 |
+
triplet = _find_chordality_breaker(H, s, treewidth_bound)
|
| 162 |
+
if induced_nodes:
|
| 163 |
+
# Add t and the second node in the induced path from s to t.
|
| 164 |
+
induced_nodes.add(t)
|
| 165 |
+
for u in G[s]:
|
| 166 |
+
if len(induced_nodes & set(G[u])) == 2:
|
| 167 |
+
induced_nodes.add(u)
|
| 168 |
+
break
|
| 169 |
+
return induced_nodes
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@nx._dispatchable
|
| 173 |
+
def chordal_graph_cliques(G):
|
| 174 |
+
"""Returns all maximal cliques of a chordal graph.
|
| 175 |
+
|
| 176 |
+
The algorithm breaks the graph in connected components and performs a
|
| 177 |
+
maximum cardinality search in each component to get the cliques.
|
| 178 |
+
|
| 179 |
+
Parameters
|
| 180 |
+
----------
|
| 181 |
+
G : graph
|
| 182 |
+
A NetworkX graph
|
| 183 |
+
|
| 184 |
+
Yields
|
| 185 |
+
------
|
| 186 |
+
frozenset of nodes
|
| 187 |
+
Maximal cliques, each of which is a frozenset of
|
| 188 |
+
nodes in `G`. The order of cliques is arbitrary.
|
| 189 |
+
|
| 190 |
+
Raises
|
| 191 |
+
------
|
| 192 |
+
NetworkXError
|
| 193 |
+
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
|
| 194 |
+
The algorithm can only be applied to chordal graphs. If the input
|
| 195 |
+
graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
|
| 196 |
+
|
| 197 |
+
Examples
|
| 198 |
+
--------
|
| 199 |
+
>>> e = [
|
| 200 |
+
... (1, 2),
|
| 201 |
+
... (1, 3),
|
| 202 |
+
... (2, 3),
|
| 203 |
+
... (2, 4),
|
| 204 |
+
... (3, 4),
|
| 205 |
+
... (3, 5),
|
| 206 |
+
... (3, 6),
|
| 207 |
+
... (4, 5),
|
| 208 |
+
... (4, 6),
|
| 209 |
+
... (5, 6),
|
| 210 |
+
... (7, 8),
|
| 211 |
+
... ]
|
| 212 |
+
>>> G = nx.Graph(e)
|
| 213 |
+
>>> G.add_node(9)
|
| 214 |
+
>>> cliques = [c for c in chordal_graph_cliques(G)]
|
| 215 |
+
>>> cliques[0]
|
| 216 |
+
frozenset({1, 2, 3})
|
| 217 |
+
"""
|
| 218 |
+
for C in (G.subgraph(c).copy() for c in connected_components(G)):
|
| 219 |
+
if C.number_of_nodes() == 1:
|
| 220 |
+
if nx.number_of_selfloops(C) > 0:
|
| 221 |
+
raise nx.NetworkXError("Input graph is not chordal.")
|
| 222 |
+
yield frozenset(C.nodes())
|
| 223 |
+
else:
|
| 224 |
+
unnumbered = set(C.nodes())
|
| 225 |
+
v = arbitrary_element(C)
|
| 226 |
+
unnumbered.remove(v)
|
| 227 |
+
numbered = {v}
|
| 228 |
+
clique_wanna_be = {v}
|
| 229 |
+
while unnumbered:
|
| 230 |
+
v = _max_cardinality_node(C, unnumbered, numbered)
|
| 231 |
+
unnumbered.remove(v)
|
| 232 |
+
numbered.add(v)
|
| 233 |
+
new_clique_wanna_be = set(C.neighbors(v)) & numbered
|
| 234 |
+
sg = C.subgraph(clique_wanna_be)
|
| 235 |
+
if _is_complete_graph(sg):
|
| 236 |
+
new_clique_wanna_be.add(v)
|
| 237 |
+
if not new_clique_wanna_be >= clique_wanna_be:
|
| 238 |
+
yield frozenset(clique_wanna_be)
|
| 239 |
+
clique_wanna_be = new_clique_wanna_be
|
| 240 |
+
else:
|
| 241 |
+
raise nx.NetworkXError("Input graph is not chordal.")
|
| 242 |
+
yield frozenset(clique_wanna_be)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@nx._dispatchable
|
| 246 |
+
def chordal_graph_treewidth(G):
|
| 247 |
+
"""Returns the treewidth of the chordal graph G.
|
| 248 |
+
|
| 249 |
+
Parameters
|
| 250 |
+
----------
|
| 251 |
+
G : graph
|
| 252 |
+
A NetworkX graph
|
| 253 |
+
|
| 254 |
+
Returns
|
| 255 |
+
-------
|
| 256 |
+
treewidth : int
|
| 257 |
+
The size of the largest clique in the graph minus one.
|
| 258 |
+
|
| 259 |
+
Raises
|
| 260 |
+
------
|
| 261 |
+
NetworkXError
|
| 262 |
+
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
|
| 263 |
+
The algorithm can only be applied to chordal graphs. If the input
|
| 264 |
+
graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
|
| 265 |
+
|
| 266 |
+
Examples
|
| 267 |
+
--------
|
| 268 |
+
>>> e = [
|
| 269 |
+
... (1, 2),
|
| 270 |
+
... (1, 3),
|
| 271 |
+
... (2, 3),
|
| 272 |
+
... (2, 4),
|
| 273 |
+
... (3, 4),
|
| 274 |
+
... (3, 5),
|
| 275 |
+
... (3, 6),
|
| 276 |
+
... (4, 5),
|
| 277 |
+
... (4, 6),
|
| 278 |
+
... (5, 6),
|
| 279 |
+
... (7, 8),
|
| 280 |
+
... ]
|
| 281 |
+
>>> G = nx.Graph(e)
|
| 282 |
+
>>> G.add_node(9)
|
| 283 |
+
>>> nx.chordal_graph_treewidth(G)
|
| 284 |
+
3
|
| 285 |
+
|
| 286 |
+
References
|
| 287 |
+
----------
|
| 288 |
+
.. [1] https://en.wikipedia.org/wiki/Tree_decomposition#Treewidth
|
| 289 |
+
"""
|
| 290 |
+
if not is_chordal(G):
|
| 291 |
+
raise nx.NetworkXError("Input graph is not chordal.")
|
| 292 |
+
|
| 293 |
+
max_clique = -1
|
| 294 |
+
for clique in nx.chordal_graph_cliques(G):
|
| 295 |
+
max_clique = max(max_clique, len(clique))
|
| 296 |
+
return max_clique - 1
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def _is_complete_graph(G):
|
| 300 |
+
"""Returns True if G is a complete graph."""
|
| 301 |
+
if nx.number_of_selfloops(G) > 0:
|
| 302 |
+
raise nx.NetworkXError("Self loop found in _is_complete_graph()")
|
| 303 |
+
n = G.number_of_nodes()
|
| 304 |
+
if n < 2:
|
| 305 |
+
return True
|
| 306 |
+
e = G.number_of_edges()
|
| 307 |
+
max_edges = (n * (n - 1)) / 2
|
| 308 |
+
return e == max_edges
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _find_missing_edge(G):
|
| 312 |
+
"""Given a non-complete graph G, returns a missing edge."""
|
| 313 |
+
nodes = set(G)
|
| 314 |
+
for u in G:
|
| 315 |
+
missing = nodes - set(list(G[u].keys()) + [u])
|
| 316 |
+
if missing:
|
| 317 |
+
return (u, missing.pop())
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _max_cardinality_node(G, choices, wanna_connect):
|
| 321 |
+
"""Returns a the node in choices that has more connections in G
|
| 322 |
+
to nodes in wanna_connect.
|
| 323 |
+
"""
|
| 324 |
+
max_number = -1
|
| 325 |
+
for x in choices:
|
| 326 |
+
number = len([y for y in G[x] if y in wanna_connect])
|
| 327 |
+
if number > max_number:
|
| 328 |
+
max_number = number
|
| 329 |
+
max_cardinality_node = x
|
| 330 |
+
return max_cardinality_node
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _find_chordality_breaker(G, s=None, treewidth_bound=sys.maxsize):
|
| 334 |
+
"""Given a graph G, starts a max cardinality search
|
| 335 |
+
(starting from s if s is given and from an arbitrary node otherwise)
|
| 336 |
+
trying to find a non-chordal cycle.
|
| 337 |
+
|
| 338 |
+
If it does find one, it returns (u,v,w) where u,v,w are the three
|
| 339 |
+
nodes that together with s are involved in the cycle.
|
| 340 |
+
|
| 341 |
+
It ignores any self loops.
|
| 342 |
+
"""
|
| 343 |
+
if len(G) == 0:
|
| 344 |
+
raise nx.NetworkXPointlessConcept("Graph has no nodes.")
|
| 345 |
+
unnumbered = set(G)
|
| 346 |
+
if s is None:
|
| 347 |
+
s = arbitrary_element(G)
|
| 348 |
+
unnumbered.remove(s)
|
| 349 |
+
numbered = {s}
|
| 350 |
+
current_treewidth = -1
|
| 351 |
+
while unnumbered: # and current_treewidth <= treewidth_bound:
|
| 352 |
+
v = _max_cardinality_node(G, unnumbered, numbered)
|
| 353 |
+
unnumbered.remove(v)
|
| 354 |
+
numbered.add(v)
|
| 355 |
+
clique_wanna_be = set(G[v]) & numbered
|
| 356 |
+
sg = G.subgraph(clique_wanna_be)
|
| 357 |
+
if _is_complete_graph(sg):
|
| 358 |
+
# The graph seems to be chordal by now. We update the treewidth
|
| 359 |
+
current_treewidth = max(current_treewidth, len(clique_wanna_be))
|
| 360 |
+
if current_treewidth > treewidth_bound:
|
| 361 |
+
raise nx.NetworkXTreewidthBoundExceeded(
|
| 362 |
+
f"treewidth_bound exceeded: {current_treewidth}"
|
| 363 |
+
)
|
| 364 |
+
else:
|
| 365 |
+
# sg is not a clique,
|
| 366 |
+
# look for an edge that is not included in sg
|
| 367 |
+
(u, w) = _find_missing_edge(sg)
|
| 368 |
+
return (u, v, w)
|
| 369 |
+
return ()
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
@not_implemented_for("directed")
|
| 373 |
+
@nx._dispatchable(returns_graph=True)
|
| 374 |
+
def complete_to_chordal_graph(G):
|
| 375 |
+
"""Return a copy of G completed to a chordal graph
|
| 376 |
+
|
| 377 |
+
Adds edges to a copy of G to create a chordal graph. A graph G=(V,E) is
|
| 378 |
+
called chordal if for each cycle with length bigger than 3, there exist
|
| 379 |
+
two non-adjacent nodes connected by an edge (called a chord).
|
| 380 |
+
|
| 381 |
+
Parameters
|
| 382 |
+
----------
|
| 383 |
+
G : NetworkX graph
|
| 384 |
+
Undirected graph
|
| 385 |
+
|
| 386 |
+
Returns
|
| 387 |
+
-------
|
| 388 |
+
H : NetworkX graph
|
| 389 |
+
The chordal enhancement of G
|
| 390 |
+
alpha : Dictionary
|
| 391 |
+
The elimination ordering of nodes of G
|
| 392 |
+
|
| 393 |
+
Notes
|
| 394 |
+
-----
|
| 395 |
+
There are different approaches to calculate the chordal
|
| 396 |
+
enhancement of a graph. The algorithm used here is called
|
| 397 |
+
MCS-M and gives at least minimal (local) triangulation of graph. Note
|
| 398 |
+
that this triangulation is not necessarily a global minimum.
|
| 399 |
+
|
| 400 |
+
https://en.wikipedia.org/wiki/Chordal_graph
|
| 401 |
+
|
| 402 |
+
References
|
| 403 |
+
----------
|
| 404 |
+
.. [1] Berry, Anne & Blair, Jean & Heggernes, Pinar & Peyton, Barry. (2004)
|
| 405 |
+
Maximum Cardinality Search for Computing Minimal Triangulations of
|
| 406 |
+
Graphs. Algorithmica. 39. 287-298. 10.1007/s00453-004-1084-3.
|
| 407 |
+
|
| 408 |
+
Examples
|
| 409 |
+
--------
|
| 410 |
+
>>> from networkx.algorithms.chordal import complete_to_chordal_graph
|
| 411 |
+
>>> G = nx.wheel_graph(10)
|
| 412 |
+
>>> H, alpha = complete_to_chordal_graph(G)
|
| 413 |
+
"""
|
| 414 |
+
H = G.copy()
|
| 415 |
+
alpha = {node: 0 for node in H}
|
| 416 |
+
if nx.is_chordal(H):
|
| 417 |
+
return H, alpha
|
| 418 |
+
chords = set()
|
| 419 |
+
weight = {node: 0 for node in H.nodes()}
|
| 420 |
+
unnumbered_nodes = list(H.nodes())
|
| 421 |
+
for i in range(len(H.nodes()), 0, -1):
|
| 422 |
+
# get the node in unnumbered_nodes with the maximum weight
|
| 423 |
+
z = max(unnumbered_nodes, key=lambda node: weight[node])
|
| 424 |
+
unnumbered_nodes.remove(z)
|
| 425 |
+
alpha[z] = i
|
| 426 |
+
update_nodes = []
|
| 427 |
+
for y in unnumbered_nodes:
|
| 428 |
+
if G.has_edge(y, z):
|
| 429 |
+
update_nodes.append(y)
|
| 430 |
+
else:
|
| 431 |
+
# y_weight will be bigger than node weights between y and z
|
| 432 |
+
y_weight = weight[y]
|
| 433 |
+
lower_nodes = [
|
| 434 |
+
node for node in unnumbered_nodes if weight[node] < y_weight
|
| 435 |
+
]
|
| 436 |
+
if nx.has_path(H.subgraph(lower_nodes + [z, y]), y, z):
|
| 437 |
+
update_nodes.append(y)
|
| 438 |
+
chords.add((z, y))
|
| 439 |
+
# during calculation of paths the weights should not be updated
|
| 440 |
+
for node in update_nodes:
|
| 441 |
+
weight[node] += 1
|
| 442 |
+
H.add_edges_from(chords)
|
| 443 |
+
return H, alpha
|
.venv/lib/python3.11/site-packages/networkx/algorithms/clique.py
ADDED
|
@@ -0,0 +1,818 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for finding and manipulating cliques.
|
| 2 |
+
|
| 3 |
+
Finding the largest clique in a graph is NP-complete problem, so most of
|
| 4 |
+
these algorithms have an exponential running time; for more information,
|
| 5 |
+
see the Wikipedia article on the clique problem [1]_.
|
| 6 |
+
|
| 7 |
+
.. [1] clique problem:: https://en.wikipedia.org/wiki/Clique_problem
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from collections import Counter, defaultdict, deque
|
| 12 |
+
from itertools import chain, combinations, islice
|
| 13 |
+
|
| 14 |
+
import networkx as nx
|
| 15 |
+
from networkx.utils import not_implemented_for
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"find_cliques",
|
| 19 |
+
"find_cliques_recursive",
|
| 20 |
+
"make_max_clique_graph",
|
| 21 |
+
"make_clique_bipartite",
|
| 22 |
+
"node_clique_number",
|
| 23 |
+
"number_of_cliques",
|
| 24 |
+
"enumerate_all_cliques",
|
| 25 |
+
"max_weight_clique",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@not_implemented_for("directed")
|
| 30 |
+
@nx._dispatchable
|
| 31 |
+
def enumerate_all_cliques(G):
|
| 32 |
+
"""Returns all cliques in an undirected graph.
|
| 33 |
+
|
| 34 |
+
This function returns an iterator over cliques, each of which is a
|
| 35 |
+
list of nodes. The iteration is ordered by cardinality of the
|
| 36 |
+
cliques: first all cliques of size one, then all cliques of size
|
| 37 |
+
two, etc.
|
| 38 |
+
|
| 39 |
+
Parameters
|
| 40 |
+
----------
|
| 41 |
+
G : NetworkX graph
|
| 42 |
+
An undirected graph.
|
| 43 |
+
|
| 44 |
+
Returns
|
| 45 |
+
-------
|
| 46 |
+
iterator
|
| 47 |
+
An iterator over cliques, each of which is a list of nodes in
|
| 48 |
+
`G`. The cliques are ordered according to size.
|
| 49 |
+
|
| 50 |
+
Notes
|
| 51 |
+
-----
|
| 52 |
+
To obtain a list of all cliques, use
|
| 53 |
+
`list(enumerate_all_cliques(G))`. However, be aware that in the
|
| 54 |
+
worst-case, the length of this list can be exponential in the number
|
| 55 |
+
of nodes in the graph (for example, when the graph is the complete
|
| 56 |
+
graph). This function avoids storing all cliques in memory by only
|
| 57 |
+
keeping current candidate node lists in memory during its search.
|
| 58 |
+
|
| 59 |
+
The implementation is adapted from the algorithm by Zhang, et
|
| 60 |
+
al. (2005) [1]_ to output all cliques discovered.
|
| 61 |
+
|
| 62 |
+
This algorithm ignores self-loops and parallel edges, since cliques
|
| 63 |
+
are not conventionally defined with such edges.
|
| 64 |
+
|
| 65 |
+
References
|
| 66 |
+
----------
|
| 67 |
+
.. [1] Yun Zhang, Abu-Khzam, F.N., Baldwin, N.E., Chesler, E.J.,
|
| 68 |
+
Langston, M.A., Samatova, N.F.,
|
| 69 |
+
"Genome-Scale Computational Approaches to Memory-Intensive
|
| 70 |
+
Applications in Systems Biology".
|
| 71 |
+
*Supercomputing*, 2005. Proceedings of the ACM/IEEE SC 2005
|
| 72 |
+
Conference, pp. 12, 12--18 Nov. 2005.
|
| 73 |
+
<https://doi.org/10.1109/SC.2005.29>.
|
| 74 |
+
|
| 75 |
+
"""
|
| 76 |
+
index = {}
|
| 77 |
+
nbrs = {}
|
| 78 |
+
for u in G:
|
| 79 |
+
index[u] = len(index)
|
| 80 |
+
# Neighbors of u that appear after u in the iteration order of G.
|
| 81 |
+
nbrs[u] = {v for v in G[u] if v not in index}
|
| 82 |
+
|
| 83 |
+
queue = deque(([u], sorted(nbrs[u], key=index.__getitem__)) for u in G)
|
| 84 |
+
# Loop invariants:
|
| 85 |
+
# 1. len(base) is nondecreasing.
|
| 86 |
+
# 2. (base + cnbrs) is sorted with respect to the iteration order of G.
|
| 87 |
+
# 3. cnbrs is a set of common neighbors of nodes in base.
|
| 88 |
+
while queue:
|
| 89 |
+
base, cnbrs = map(list, queue.popleft())
|
| 90 |
+
yield base
|
| 91 |
+
for i, u in enumerate(cnbrs):
|
| 92 |
+
# Use generators to reduce memory consumption.
|
| 93 |
+
queue.append(
|
| 94 |
+
(
|
| 95 |
+
chain(base, [u]),
|
| 96 |
+
filter(nbrs[u].__contains__, islice(cnbrs, i + 1, None)),
|
| 97 |
+
)
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@not_implemented_for("directed")
|
| 102 |
+
@nx._dispatchable
|
| 103 |
+
def find_cliques(G, nodes=None):
|
| 104 |
+
"""Returns all maximal cliques in an undirected graph.
|
| 105 |
+
|
| 106 |
+
For each node *n*, a *maximal clique for n* is a largest complete
|
| 107 |
+
subgraph containing *n*. The largest maximal clique is sometimes
|
| 108 |
+
called the *maximum clique*.
|
| 109 |
+
|
| 110 |
+
This function returns an iterator over cliques, each of which is a
|
| 111 |
+
list of nodes. It is an iterative implementation, so should not
|
| 112 |
+
suffer from recursion depth issues.
|
| 113 |
+
|
| 114 |
+
This function accepts a list of `nodes` and only the maximal cliques
|
| 115 |
+
containing all of these `nodes` are returned. It can considerably speed up
|
| 116 |
+
the running time if some specific cliques are desired.
|
| 117 |
+
|
| 118 |
+
Parameters
|
| 119 |
+
----------
|
| 120 |
+
G : NetworkX graph
|
| 121 |
+
An undirected graph.
|
| 122 |
+
|
| 123 |
+
nodes : list, optional (default=None)
|
| 124 |
+
If provided, only yield *maximal cliques* containing all nodes in `nodes`.
|
| 125 |
+
If `nodes` isn't a clique itself, a ValueError is raised.
|
| 126 |
+
|
| 127 |
+
Returns
|
| 128 |
+
-------
|
| 129 |
+
iterator
|
| 130 |
+
An iterator over maximal cliques, each of which is a list of
|
| 131 |
+
nodes in `G`. If `nodes` is provided, only the maximal cliques
|
| 132 |
+
containing all the nodes in `nodes` are returned. The order of
|
| 133 |
+
cliques is arbitrary.
|
| 134 |
+
|
| 135 |
+
Raises
|
| 136 |
+
------
|
| 137 |
+
ValueError
|
| 138 |
+
If `nodes` is not a clique.
|
| 139 |
+
|
| 140 |
+
Examples
|
| 141 |
+
--------
|
| 142 |
+
>>> from pprint import pprint # For nice dict formatting
|
| 143 |
+
>>> G = nx.karate_club_graph()
|
| 144 |
+
>>> sum(1 for c in nx.find_cliques(G)) # The number of maximal cliques in G
|
| 145 |
+
36
|
| 146 |
+
>>> max(nx.find_cliques(G), key=len) # The largest maximal clique in G
|
| 147 |
+
[0, 1, 2, 3, 13]
|
| 148 |
+
|
| 149 |
+
The size of the largest maximal clique is known as the *clique number* of
|
| 150 |
+
the graph, which can be found directly with:
|
| 151 |
+
|
| 152 |
+
>>> max(len(c) for c in nx.find_cliques(G))
|
| 153 |
+
5
|
| 154 |
+
|
| 155 |
+
One can also compute the number of maximal cliques in `G` that contain a given
|
| 156 |
+
node. The following produces a dictionary keyed by node whose
|
| 157 |
+
values are the number of maximal cliques in `G` that contain the node:
|
| 158 |
+
|
| 159 |
+
>>> from collections import Counter
|
| 160 |
+
>>> from itertools import chain
|
| 161 |
+
>>> counts = Counter(chain.from_iterable(nx.find_cliques(G)))
|
| 162 |
+
>>> pprint(dict(counts))
|
| 163 |
+
{0: 13,
|
| 164 |
+
1: 6,
|
| 165 |
+
2: 7,
|
| 166 |
+
3: 3,
|
| 167 |
+
4: 2,
|
| 168 |
+
5: 3,
|
| 169 |
+
6: 3,
|
| 170 |
+
7: 1,
|
| 171 |
+
8: 3,
|
| 172 |
+
9: 2,
|
| 173 |
+
10: 2,
|
| 174 |
+
11: 1,
|
| 175 |
+
12: 1,
|
| 176 |
+
13: 2,
|
| 177 |
+
14: 1,
|
| 178 |
+
15: 1,
|
| 179 |
+
16: 1,
|
| 180 |
+
17: 1,
|
| 181 |
+
18: 1,
|
| 182 |
+
19: 2,
|
| 183 |
+
20: 1,
|
| 184 |
+
21: 1,
|
| 185 |
+
22: 1,
|
| 186 |
+
23: 3,
|
| 187 |
+
24: 2,
|
| 188 |
+
25: 2,
|
| 189 |
+
26: 1,
|
| 190 |
+
27: 3,
|
| 191 |
+
28: 2,
|
| 192 |
+
29: 2,
|
| 193 |
+
30: 2,
|
| 194 |
+
31: 4,
|
| 195 |
+
32: 9,
|
| 196 |
+
33: 14}
|
| 197 |
+
|
| 198 |
+
Or, similarly, the maximal cliques in `G` that contain a given node.
|
| 199 |
+
For example, the 4 maximal cliques that contain node 31:
|
| 200 |
+
|
| 201 |
+
>>> [c for c in nx.find_cliques(G) if 31 in c]
|
| 202 |
+
[[0, 31], [33, 32, 31], [33, 28, 31], [24, 25, 31]]
|
| 203 |
+
|
| 204 |
+
See Also
|
| 205 |
+
--------
|
| 206 |
+
find_cliques_recursive
|
| 207 |
+
A recursive version of the same algorithm.
|
| 208 |
+
|
| 209 |
+
Notes
|
| 210 |
+
-----
|
| 211 |
+
To obtain a list of all maximal cliques, use
|
| 212 |
+
`list(find_cliques(G))`. However, be aware that in the worst-case,
|
| 213 |
+
the length of this list can be exponential in the number of nodes in
|
| 214 |
+
the graph. This function avoids storing all cliques in memory by
|
| 215 |
+
only keeping current candidate node lists in memory during its search.
|
| 216 |
+
|
| 217 |
+
This implementation is based on the algorithm published by Bron and
|
| 218 |
+
Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi
|
| 219 |
+
(2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. It
|
| 220 |
+
essentially unrolls the recursion used in the references to avoid
|
| 221 |
+
issues of recursion stack depth (for a recursive implementation, see
|
| 222 |
+
:func:`find_cliques_recursive`).
|
| 223 |
+
|
| 224 |
+
This algorithm ignores self-loops and parallel edges, since cliques
|
| 225 |
+
are not conventionally defined with such edges.
|
| 226 |
+
|
| 227 |
+
References
|
| 228 |
+
----------
|
| 229 |
+
.. [1] Bron, C. and Kerbosch, J.
|
| 230 |
+
"Algorithm 457: finding all cliques of an undirected graph".
|
| 231 |
+
*Communications of the ACM* 16, 9 (Sep. 1973), 575--577.
|
| 232 |
+
<http://portal.acm.org/citation.cfm?doid=362342.362367>
|
| 233 |
+
|
| 234 |
+
.. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi,
|
| 235 |
+
"The worst-case time complexity for generating all maximal
|
| 236 |
+
cliques and computational experiments",
|
| 237 |
+
*Theoretical Computer Science*, Volume 363, Issue 1,
|
| 238 |
+
Computing and Combinatorics,
|
| 239 |
+
10th Annual International Conference on
|
| 240 |
+
Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42
|
| 241 |
+
<https://doi.org/10.1016/j.tcs.2006.06.015>
|
| 242 |
+
|
| 243 |
+
.. [3] F. Cazals, C. Karande,
|
| 244 |
+
"A note on the problem of reporting maximal cliques",
|
| 245 |
+
*Theoretical Computer Science*,
|
| 246 |
+
Volume 407, Issues 1--3, 6 November 2008, Pages 564--568,
|
| 247 |
+
<https://doi.org/10.1016/j.tcs.2008.05.010>
|
| 248 |
+
|
| 249 |
+
"""
|
| 250 |
+
if len(G) == 0:
|
| 251 |
+
return
|
| 252 |
+
|
| 253 |
+
adj = {u: {v for v in G[u] if v != u} for u in G}
|
| 254 |
+
|
| 255 |
+
# Initialize Q with the given nodes and subg, cand with their nbrs
|
| 256 |
+
Q = nodes[:] if nodes is not None else []
|
| 257 |
+
cand = set(G)
|
| 258 |
+
for node in Q:
|
| 259 |
+
if node not in cand:
|
| 260 |
+
raise ValueError(f"The given `nodes` {nodes} do not form a clique")
|
| 261 |
+
cand &= adj[node]
|
| 262 |
+
|
| 263 |
+
if not cand:
|
| 264 |
+
yield Q[:]
|
| 265 |
+
return
|
| 266 |
+
|
| 267 |
+
subg = cand.copy()
|
| 268 |
+
stack = []
|
| 269 |
+
Q.append(None)
|
| 270 |
+
|
| 271 |
+
u = max(subg, key=lambda u: len(cand & adj[u]))
|
| 272 |
+
ext_u = cand - adj[u]
|
| 273 |
+
|
| 274 |
+
try:
|
| 275 |
+
while True:
|
| 276 |
+
if ext_u:
|
| 277 |
+
q = ext_u.pop()
|
| 278 |
+
cand.remove(q)
|
| 279 |
+
Q[-1] = q
|
| 280 |
+
adj_q = adj[q]
|
| 281 |
+
subg_q = subg & adj_q
|
| 282 |
+
if not subg_q:
|
| 283 |
+
yield Q[:]
|
| 284 |
+
else:
|
| 285 |
+
cand_q = cand & adj_q
|
| 286 |
+
if cand_q:
|
| 287 |
+
stack.append((subg, cand, ext_u))
|
| 288 |
+
Q.append(None)
|
| 289 |
+
subg = subg_q
|
| 290 |
+
cand = cand_q
|
| 291 |
+
u = max(subg, key=lambda u: len(cand & adj[u]))
|
| 292 |
+
ext_u = cand - adj[u]
|
| 293 |
+
else:
|
| 294 |
+
Q.pop()
|
| 295 |
+
subg, cand, ext_u = stack.pop()
|
| 296 |
+
except IndexError:
|
| 297 |
+
pass
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
@not_implemented_for("directed")
|
| 301 |
+
@nx._dispatchable
|
| 302 |
+
def find_cliques_recursive(G, nodes=None):
|
| 303 |
+
"""Returns all maximal cliques in a graph.
|
| 304 |
+
|
| 305 |
+
For each node *v*, a *maximal clique for v* is a largest complete
|
| 306 |
+
subgraph containing *v*. The largest maximal clique is sometimes
|
| 307 |
+
called the *maximum clique*.
|
| 308 |
+
|
| 309 |
+
This function returns an iterator over cliques, each of which is a
|
| 310 |
+
list of nodes. It is a recursive implementation, so may suffer from
|
| 311 |
+
recursion depth issues, but is included for pedagogical reasons.
|
| 312 |
+
For a non-recursive implementation, see :func:`find_cliques`.
|
| 313 |
+
|
| 314 |
+
This function accepts a list of `nodes` and only the maximal cliques
|
| 315 |
+
containing all of these `nodes` are returned. It can considerably speed up
|
| 316 |
+
the running time if some specific cliques are desired.
|
| 317 |
+
|
| 318 |
+
Parameters
|
| 319 |
+
----------
|
| 320 |
+
G : NetworkX graph
|
| 321 |
+
An undirected graph.
|
| 322 |
+
|
| 323 |
+
nodes : list, optional (default=None)
|
| 324 |
+
If provided, only yield *maximal cliques* containing all nodes in `nodes`.
|
| 325 |
+
If `nodes` isn't a clique itself, a ValueError is raised.
|
| 326 |
+
|
| 327 |
+
Returns
|
| 328 |
+
-------
|
| 329 |
+
iterator
|
| 330 |
+
An iterator over maximal cliques, each of which is a list of
|
| 331 |
+
nodes in `G`. If `nodes` is provided, only the maximal cliques
|
| 332 |
+
containing all the nodes in `nodes` are yielded. The order of
|
| 333 |
+
cliques is arbitrary.
|
| 334 |
+
|
| 335 |
+
Raises
|
| 336 |
+
------
|
| 337 |
+
NetworkXNotImplemented
|
| 338 |
+
If `G` is directed.
|
| 339 |
+
|
| 340 |
+
ValueError
|
| 341 |
+
If `nodes` is not a clique.
|
| 342 |
+
|
| 343 |
+
See Also
|
| 344 |
+
--------
|
| 345 |
+
find_cliques
|
| 346 |
+
An iterative version of the same algorithm. See docstring for examples.
|
| 347 |
+
|
| 348 |
+
Notes
|
| 349 |
+
-----
|
| 350 |
+
To obtain a list of all maximal cliques, use
|
| 351 |
+
`list(find_cliques_recursive(G))`. However, be aware that in the
|
| 352 |
+
worst-case, the length of this list can be exponential in the number
|
| 353 |
+
of nodes in the graph. This function avoids storing all cliques in memory
|
| 354 |
+
by only keeping current candidate node lists in memory during its search.
|
| 355 |
+
|
| 356 |
+
This implementation is based on the algorithm published by Bron and
|
| 357 |
+
Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi
|
| 358 |
+
(2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. For a
|
| 359 |
+
non-recursive implementation, see :func:`find_cliques`.
|
| 360 |
+
|
| 361 |
+
This algorithm ignores self-loops and parallel edges, since cliques
|
| 362 |
+
are not conventionally defined with such edges.
|
| 363 |
+
|
| 364 |
+
References
|
| 365 |
+
----------
|
| 366 |
+
.. [1] Bron, C. and Kerbosch, J.
|
| 367 |
+
"Algorithm 457: finding all cliques of an undirected graph".
|
| 368 |
+
*Communications of the ACM* 16, 9 (Sep. 1973), 575--577.
|
| 369 |
+
<http://portal.acm.org/citation.cfm?doid=362342.362367>
|
| 370 |
+
|
| 371 |
+
.. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi,
|
| 372 |
+
"The worst-case time complexity for generating all maximal
|
| 373 |
+
cliques and computational experiments",
|
| 374 |
+
*Theoretical Computer Science*, Volume 363, Issue 1,
|
| 375 |
+
Computing and Combinatorics,
|
| 376 |
+
10th Annual International Conference on
|
| 377 |
+
Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42
|
| 378 |
+
<https://doi.org/10.1016/j.tcs.2006.06.015>
|
| 379 |
+
|
| 380 |
+
.. [3] F. Cazals, C. Karande,
|
| 381 |
+
"A note on the problem of reporting maximal cliques",
|
| 382 |
+
*Theoretical Computer Science*,
|
| 383 |
+
Volume 407, Issues 1--3, 6 November 2008, Pages 564--568,
|
| 384 |
+
<https://doi.org/10.1016/j.tcs.2008.05.010>
|
| 385 |
+
|
| 386 |
+
"""
|
| 387 |
+
if len(G) == 0:
|
| 388 |
+
return iter([])
|
| 389 |
+
|
| 390 |
+
adj = {u: {v for v in G[u] if v != u} for u in G}
|
| 391 |
+
|
| 392 |
+
# Initialize Q with the given nodes and subg, cand with their nbrs
|
| 393 |
+
Q = nodes[:] if nodes is not None else []
|
| 394 |
+
cand_init = set(G)
|
| 395 |
+
for node in Q:
|
| 396 |
+
if node not in cand_init:
|
| 397 |
+
raise ValueError(f"The given `nodes` {nodes} do not form a clique")
|
| 398 |
+
cand_init &= adj[node]
|
| 399 |
+
|
| 400 |
+
if not cand_init:
|
| 401 |
+
return iter([Q])
|
| 402 |
+
|
| 403 |
+
subg_init = cand_init.copy()
|
| 404 |
+
|
| 405 |
+
def expand(subg, cand):
|
| 406 |
+
u = max(subg, key=lambda u: len(cand & adj[u]))
|
| 407 |
+
for q in cand - adj[u]:
|
| 408 |
+
cand.remove(q)
|
| 409 |
+
Q.append(q)
|
| 410 |
+
adj_q = adj[q]
|
| 411 |
+
subg_q = subg & adj_q
|
| 412 |
+
if not subg_q:
|
| 413 |
+
yield Q[:]
|
| 414 |
+
else:
|
| 415 |
+
cand_q = cand & adj_q
|
| 416 |
+
if cand_q:
|
| 417 |
+
yield from expand(subg_q, cand_q)
|
| 418 |
+
Q.pop()
|
| 419 |
+
|
| 420 |
+
return expand(subg_init, cand_init)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
@nx._dispatchable(returns_graph=True)
|
| 424 |
+
def make_max_clique_graph(G, create_using=None):
|
| 425 |
+
"""Returns the maximal clique graph of the given graph.
|
| 426 |
+
|
| 427 |
+
The nodes of the maximal clique graph of `G` are the cliques of
|
| 428 |
+
`G` and an edge joins two cliques if the cliques are not disjoint.
|
| 429 |
+
|
| 430 |
+
Parameters
|
| 431 |
+
----------
|
| 432 |
+
G : NetworkX graph
|
| 433 |
+
|
| 434 |
+
create_using : NetworkX graph constructor, optional (default=nx.Graph)
|
| 435 |
+
Graph type to create. If graph instance, then cleared before populated.
|
| 436 |
+
|
| 437 |
+
Returns
|
| 438 |
+
-------
|
| 439 |
+
NetworkX graph
|
| 440 |
+
A graph whose nodes are the cliques of `G` and whose edges
|
| 441 |
+
join two cliques if they are not disjoint.
|
| 442 |
+
|
| 443 |
+
Notes
|
| 444 |
+
-----
|
| 445 |
+
This function behaves like the following code::
|
| 446 |
+
|
| 447 |
+
import networkx as nx
|
| 448 |
+
|
| 449 |
+
G = nx.make_clique_bipartite(G)
|
| 450 |
+
cliques = [v for v in G.nodes() if G.nodes[v]["bipartite"] == 0]
|
| 451 |
+
G = nx.bipartite.projected_graph(G, cliques)
|
| 452 |
+
G = nx.relabel_nodes(G, {-v: v - 1 for v in G})
|
| 453 |
+
|
| 454 |
+
It should be faster, though, since it skips all the intermediate
|
| 455 |
+
steps.
|
| 456 |
+
|
| 457 |
+
"""
|
| 458 |
+
if create_using is None:
|
| 459 |
+
B = G.__class__()
|
| 460 |
+
else:
|
| 461 |
+
B = nx.empty_graph(0, create_using)
|
| 462 |
+
cliques = list(enumerate(set(c) for c in find_cliques(G)))
|
| 463 |
+
# Add a numbered node for each clique.
|
| 464 |
+
B.add_nodes_from(i for i, c in cliques)
|
| 465 |
+
# Join cliques by an edge if they share a node.
|
| 466 |
+
clique_pairs = combinations(cliques, 2)
|
| 467 |
+
B.add_edges_from((i, j) for (i, c1), (j, c2) in clique_pairs if c1 & c2)
|
| 468 |
+
return B
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
@nx._dispatchable(returns_graph=True)
|
| 472 |
+
def make_clique_bipartite(G, fpos=None, create_using=None, name=None):
|
| 473 |
+
"""Returns the bipartite clique graph corresponding to `G`.
|
| 474 |
+
|
| 475 |
+
In the returned bipartite graph, the "bottom" nodes are the nodes of
|
| 476 |
+
`G` and the "top" nodes represent the maximal cliques of `G`.
|
| 477 |
+
There is an edge from node *v* to clique *C* in the returned graph
|
| 478 |
+
if and only if *v* is an element of *C*.
|
| 479 |
+
|
| 480 |
+
Parameters
|
| 481 |
+
----------
|
| 482 |
+
G : NetworkX graph
|
| 483 |
+
An undirected graph.
|
| 484 |
+
|
| 485 |
+
fpos : bool
|
| 486 |
+
If True or not None, the returned graph will have an
|
| 487 |
+
additional attribute, `pos`, a dictionary mapping node to
|
| 488 |
+
position in the Euclidean plane.
|
| 489 |
+
|
| 490 |
+
create_using : NetworkX graph constructor, optional (default=nx.Graph)
|
| 491 |
+
Graph type to create. If graph instance, then cleared before populated.
|
| 492 |
+
|
| 493 |
+
Returns
|
| 494 |
+
-------
|
| 495 |
+
NetworkX graph
|
| 496 |
+
A bipartite graph whose "bottom" set is the nodes of the graph
|
| 497 |
+
`G`, whose "top" set is the cliques of `G`, and whose edges
|
| 498 |
+
join nodes of `G` to the cliques that contain them.
|
| 499 |
+
|
| 500 |
+
The nodes of the graph `G` have the node attribute
|
| 501 |
+
'bipartite' set to 1 and the nodes representing cliques
|
| 502 |
+
have the node attribute 'bipartite' set to 0, as is the
|
| 503 |
+
convention for bipartite graphs in NetworkX.
|
| 504 |
+
|
| 505 |
+
"""
|
| 506 |
+
B = nx.empty_graph(0, create_using)
|
| 507 |
+
B.clear()
|
| 508 |
+
# The "bottom" nodes in the bipartite graph are the nodes of the
|
| 509 |
+
# original graph, G.
|
| 510 |
+
B.add_nodes_from(G, bipartite=1)
|
| 511 |
+
for i, cl in enumerate(find_cliques(G)):
|
| 512 |
+
# The "top" nodes in the bipartite graph are the cliques. These
|
| 513 |
+
# nodes get negative numbers as labels.
|
| 514 |
+
name = -i - 1
|
| 515 |
+
B.add_node(name, bipartite=0)
|
| 516 |
+
B.add_edges_from((v, name) for v in cl)
|
| 517 |
+
return B
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
@nx._dispatchable
|
| 521 |
+
def node_clique_number(G, nodes=None, cliques=None, separate_nodes=False):
|
| 522 |
+
"""Returns the size of the largest maximal clique containing each given node.
|
| 523 |
+
|
| 524 |
+
Returns a single or list depending on input nodes.
|
| 525 |
+
An optional list of cliques can be input if already computed.
|
| 526 |
+
|
| 527 |
+
Parameters
|
| 528 |
+
----------
|
| 529 |
+
G : NetworkX graph
|
| 530 |
+
An undirected graph.
|
| 531 |
+
|
| 532 |
+
cliques : list, optional (default=None)
|
| 533 |
+
A list of cliques, each of which is itself a list of nodes.
|
| 534 |
+
If not specified, the list of all cliques will be computed
|
| 535 |
+
using :func:`find_cliques`.
|
| 536 |
+
|
| 537 |
+
Returns
|
| 538 |
+
-------
|
| 539 |
+
int or dict
|
| 540 |
+
If `nodes` is a single node, returns the size of the
|
| 541 |
+
largest maximal clique in `G` containing that node.
|
| 542 |
+
Otherwise return a dict keyed by node to the size
|
| 543 |
+
of the largest maximal clique containing that node.
|
| 544 |
+
|
| 545 |
+
See Also
|
| 546 |
+
--------
|
| 547 |
+
find_cliques
|
| 548 |
+
find_cliques yields the maximal cliques of G.
|
| 549 |
+
It accepts a `nodes` argument which restricts consideration to
|
| 550 |
+
maximal cliques containing all the given `nodes`.
|
| 551 |
+
The search for the cliques is optimized for `nodes`.
|
| 552 |
+
number_of_cliques
|
| 553 |
+
"""
|
| 554 |
+
if cliques is None:
|
| 555 |
+
if nodes is not None:
|
| 556 |
+
# Use ego_graph to decrease size of graph
|
| 557 |
+
# check for single node
|
| 558 |
+
if nodes in G:
|
| 559 |
+
return max(len(c) for c in find_cliques(nx.ego_graph(G, nodes)))
|
| 560 |
+
# handle multiple nodes
|
| 561 |
+
return {
|
| 562 |
+
n: max(len(c) for c in find_cliques(nx.ego_graph(G, n))) for n in nodes
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
# nodes is None--find all cliques
|
| 566 |
+
cliques = list(find_cliques(G))
|
| 567 |
+
|
| 568 |
+
# single node requested
|
| 569 |
+
if nodes in G:
|
| 570 |
+
return max(len(c) for c in cliques if nodes in c)
|
| 571 |
+
|
| 572 |
+
# multiple nodes requested
|
| 573 |
+
# preprocess all nodes (faster than one at a time for even 2 nodes)
|
| 574 |
+
size_for_n = defaultdict(int)
|
| 575 |
+
for c in cliques:
|
| 576 |
+
size_of_c = len(c)
|
| 577 |
+
for n in c:
|
| 578 |
+
if size_for_n[n] < size_of_c:
|
| 579 |
+
size_for_n[n] = size_of_c
|
| 580 |
+
if nodes is None:
|
| 581 |
+
return size_for_n
|
| 582 |
+
return {n: size_for_n[n] for n in nodes}
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def number_of_cliques(G, nodes=None, cliques=None):
|
| 586 |
+
"""Return the number of maximal cliques each node is part of.
|
| 587 |
+
|
| 588 |
+
Output is a single value or dict depending on `nodes`.
|
| 589 |
+
Optional list of cliques can be input if already computed.
|
| 590 |
+
|
| 591 |
+
Parameters
|
| 592 |
+
----------
|
| 593 |
+
G : NetworkX graph
|
| 594 |
+
An undirected graph.
|
| 595 |
+
|
| 596 |
+
nodes : list or None, optional (default=None)
|
| 597 |
+
A list of nodes to return the number of maximal cliques for.
|
| 598 |
+
If `None`, return the number of maximal cliques for all nodes.
|
| 599 |
+
|
| 600 |
+
cliques : list or None, optional (default=None)
|
| 601 |
+
A precomputed list of maximal cliques to use for the calculation.
|
| 602 |
+
|
| 603 |
+
Returns
|
| 604 |
+
-------
|
| 605 |
+
int or dict
|
| 606 |
+
If `nodes` is a single node, return the number of maximal cliques it is
|
| 607 |
+
part of. If `nodes` is a list, return a dictionary keyed by node to the
|
| 608 |
+
number of maximal cliques it is part of.
|
| 609 |
+
|
| 610 |
+
Raises
|
| 611 |
+
------
|
| 612 |
+
NetworkXNotImplemented
|
| 613 |
+
If `G` is directed.
|
| 614 |
+
|
| 615 |
+
See Also
|
| 616 |
+
--------
|
| 617 |
+
find_cliques
|
| 618 |
+
node_clique_number
|
| 619 |
+
|
| 620 |
+
Examples
|
| 621 |
+
--------
|
| 622 |
+
Compute the number of maximal cliques a node is part of:
|
| 623 |
+
|
| 624 |
+
>>> G = nx.complete_graph(3)
|
| 625 |
+
>>> nx.add_cycle(G, [0, 3, 4])
|
| 626 |
+
>>> nx.number_of_cliques(G, nodes=0)
|
| 627 |
+
2
|
| 628 |
+
>>> nx.number_of_cliques(G, nodes=1)
|
| 629 |
+
1
|
| 630 |
+
|
| 631 |
+
Or, for a list of nodes:
|
| 632 |
+
|
| 633 |
+
>>> nx.number_of_cliques(G, nodes=[0, 1])
|
| 634 |
+
{0: 2, 1: 1}
|
| 635 |
+
|
| 636 |
+
If no explicit `nodes` are provided, all nodes are considered:
|
| 637 |
+
|
| 638 |
+
>>> nx.number_of_cliques(G)
|
| 639 |
+
{0: 2, 1: 1, 2: 1, 3: 1, 4: 1}
|
| 640 |
+
|
| 641 |
+
The list of maximal cliques can also be precomputed:
|
| 642 |
+
|
| 643 |
+
>>> cl = list(nx.find_cliques(G))
|
| 644 |
+
>>> nx.number_of_cliques(G, cliques=cl)
|
| 645 |
+
{0: 2, 1: 1, 2: 1, 3: 1, 4: 1}
|
| 646 |
+
"""
|
| 647 |
+
if cliques is None:
|
| 648 |
+
cliques = find_cliques(G)
|
| 649 |
+
|
| 650 |
+
if nodes is None:
|
| 651 |
+
nodes = list(G.nodes()) # none, get entire graph
|
| 652 |
+
|
| 653 |
+
if not isinstance(nodes, list): # check for a list
|
| 654 |
+
v = nodes
|
| 655 |
+
# assume it is a single value
|
| 656 |
+
numcliq = sum(1 for c in cliques if v in c)
|
| 657 |
+
else:
|
| 658 |
+
numcliq = Counter(chain.from_iterable(cliques))
|
| 659 |
+
numcliq = {v: numcliq[v] for v in nodes} # return a dict
|
| 660 |
+
return numcliq
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
class MaxWeightClique:
|
| 664 |
+
"""A class for the maximum weight clique algorithm.
|
| 665 |
+
|
| 666 |
+
This class is a helper for the `max_weight_clique` function. The class
|
| 667 |
+
should not normally be used directly.
|
| 668 |
+
|
| 669 |
+
Parameters
|
| 670 |
+
----------
|
| 671 |
+
G : NetworkX graph
|
| 672 |
+
The undirected graph for which a maximum weight clique is sought
|
| 673 |
+
weight : string or None, optional (default='weight')
|
| 674 |
+
The node attribute that holds the integer value used as a weight.
|
| 675 |
+
If None, then each node has weight 1.
|
| 676 |
+
|
| 677 |
+
Attributes
|
| 678 |
+
----------
|
| 679 |
+
G : NetworkX graph
|
| 680 |
+
The undirected graph for which a maximum weight clique is sought
|
| 681 |
+
node_weights: dict
|
| 682 |
+
The weight of each node
|
| 683 |
+
incumbent_nodes : list
|
| 684 |
+
The nodes of the incumbent clique (the best clique found so far)
|
| 685 |
+
incumbent_weight: int
|
| 686 |
+
The weight of the incumbent clique
|
| 687 |
+
"""
|
| 688 |
+
|
| 689 |
+
def __init__(self, G, weight):
|
| 690 |
+
self.G = G
|
| 691 |
+
self.incumbent_nodes = []
|
| 692 |
+
self.incumbent_weight = 0
|
| 693 |
+
|
| 694 |
+
if weight is None:
|
| 695 |
+
self.node_weights = {v: 1 for v in G.nodes()}
|
| 696 |
+
else:
|
| 697 |
+
for v in G.nodes():
|
| 698 |
+
if weight not in G.nodes[v]:
|
| 699 |
+
errmsg = f"Node {v!r} does not have the requested weight field."
|
| 700 |
+
raise KeyError(errmsg)
|
| 701 |
+
if not isinstance(G.nodes[v][weight], int):
|
| 702 |
+
errmsg = f"The {weight!r} field of node {v!r} is not an integer."
|
| 703 |
+
raise ValueError(errmsg)
|
| 704 |
+
self.node_weights = {v: G.nodes[v][weight] for v in G.nodes()}
|
| 705 |
+
|
| 706 |
+
def update_incumbent_if_improved(self, C, C_weight):
|
| 707 |
+
"""Update the incumbent if the node set C has greater weight.
|
| 708 |
+
|
| 709 |
+
C is assumed to be a clique.
|
| 710 |
+
"""
|
| 711 |
+
if C_weight > self.incumbent_weight:
|
| 712 |
+
self.incumbent_nodes = C[:]
|
| 713 |
+
self.incumbent_weight = C_weight
|
| 714 |
+
|
| 715 |
+
def greedily_find_independent_set(self, P):
|
| 716 |
+
"""Greedily find an independent set of nodes from a set of
|
| 717 |
+
nodes P."""
|
| 718 |
+
independent_set = []
|
| 719 |
+
P = P[:]
|
| 720 |
+
while P:
|
| 721 |
+
v = P[0]
|
| 722 |
+
independent_set.append(v)
|
| 723 |
+
P = [w for w in P if v != w and not self.G.has_edge(v, w)]
|
| 724 |
+
return independent_set
|
| 725 |
+
|
| 726 |
+
def find_branching_nodes(self, P, target):
|
| 727 |
+
"""Find a set of nodes to branch on."""
|
| 728 |
+
residual_wt = {v: self.node_weights[v] for v in P}
|
| 729 |
+
total_wt = 0
|
| 730 |
+
P = P[:]
|
| 731 |
+
while P:
|
| 732 |
+
independent_set = self.greedily_find_independent_set(P)
|
| 733 |
+
min_wt_in_class = min(residual_wt[v] for v in independent_set)
|
| 734 |
+
total_wt += min_wt_in_class
|
| 735 |
+
if total_wt > target:
|
| 736 |
+
break
|
| 737 |
+
for v in independent_set:
|
| 738 |
+
residual_wt[v] -= min_wt_in_class
|
| 739 |
+
P = [v for v in P if residual_wt[v] != 0]
|
| 740 |
+
return P
|
| 741 |
+
|
| 742 |
+
def expand(self, C, C_weight, P):
|
| 743 |
+
"""Look for the best clique that contains all the nodes in C and zero or
|
| 744 |
+
more of the nodes in P, backtracking if it can be shown that no such
|
| 745 |
+
clique has greater weight than the incumbent.
|
| 746 |
+
"""
|
| 747 |
+
self.update_incumbent_if_improved(C, C_weight)
|
| 748 |
+
branching_nodes = self.find_branching_nodes(P, self.incumbent_weight - C_weight)
|
| 749 |
+
while branching_nodes:
|
| 750 |
+
v = branching_nodes.pop()
|
| 751 |
+
P.remove(v)
|
| 752 |
+
new_C = C + [v]
|
| 753 |
+
new_C_weight = C_weight + self.node_weights[v]
|
| 754 |
+
new_P = [w for w in P if self.G.has_edge(v, w)]
|
| 755 |
+
self.expand(new_C, new_C_weight, new_P)
|
| 756 |
+
|
| 757 |
+
def find_max_weight_clique(self):
|
| 758 |
+
"""Find a maximum weight clique."""
|
| 759 |
+
# Sort nodes in reverse order of degree for speed
|
| 760 |
+
nodes = sorted(self.G.nodes(), key=lambda v: self.G.degree(v), reverse=True)
|
| 761 |
+
nodes = [v for v in nodes if self.node_weights[v] > 0]
|
| 762 |
+
self.expand([], 0, nodes)
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
@not_implemented_for("directed")
|
| 766 |
+
@nx._dispatchable(node_attrs="weight")
|
| 767 |
+
def max_weight_clique(G, weight="weight"):
|
| 768 |
+
"""Find a maximum weight clique in G.
|
| 769 |
+
|
| 770 |
+
A *clique* in a graph is a set of nodes such that every two distinct nodes
|
| 771 |
+
are adjacent. The *weight* of a clique is the sum of the weights of its
|
| 772 |
+
nodes. A *maximum weight clique* of graph G is a clique C in G such that
|
| 773 |
+
no clique in G has weight greater than the weight of C.
|
| 774 |
+
|
| 775 |
+
Parameters
|
| 776 |
+
----------
|
| 777 |
+
G : NetworkX graph
|
| 778 |
+
Undirected graph
|
| 779 |
+
weight : string or None, optional (default='weight')
|
| 780 |
+
The node attribute that holds the integer value used as a weight.
|
| 781 |
+
If None, then each node has weight 1.
|
| 782 |
+
|
| 783 |
+
Returns
|
| 784 |
+
-------
|
| 785 |
+
clique : list
|
| 786 |
+
the nodes of a maximum weight clique
|
| 787 |
+
weight : int
|
| 788 |
+
the weight of a maximum weight clique
|
| 789 |
+
|
| 790 |
+
Notes
|
| 791 |
+
-----
|
| 792 |
+
The implementation is recursive, and therefore it may run into recursion
|
| 793 |
+
depth issues if G contains a clique whose number of nodes is close to the
|
| 794 |
+
recursion depth limit.
|
| 795 |
+
|
| 796 |
+
At each search node, the algorithm greedily constructs a weighted
|
| 797 |
+
independent set cover of part of the graph in order to find a small set of
|
| 798 |
+
nodes on which to branch. The algorithm is very similar to the algorithm
|
| 799 |
+
of Tavares et al. [1]_, other than the fact that the NetworkX version does
|
| 800 |
+
not use bitsets. This style of algorithm for maximum weight clique (and
|
| 801 |
+
maximum weight independent set, which is the same problem but on the
|
| 802 |
+
complement graph) has a decades-long history. See Algorithm B of Warren
|
| 803 |
+
and Hicks [2]_ and the references in that paper.
|
| 804 |
+
|
| 805 |
+
References
|
| 806 |
+
----------
|
| 807 |
+
.. [1] Tavares, W.A., Neto, M.B.C., Rodrigues, C.D., Michelon, P.: Um
|
| 808 |
+
algoritmo de branch and bound para o problema da clique máxima
|
| 809 |
+
ponderada. Proceedings of XLVII SBPO 1 (2015).
|
| 810 |
+
|
| 811 |
+
.. [2] Warren, Jeffrey S, Hicks, Illya V.: Combinatorial Branch-and-Bound
|
| 812 |
+
for the Maximum Weight Independent Set Problem. Technical Report,
|
| 813 |
+
Texas A&M University (2016).
|
| 814 |
+
"""
|
| 815 |
+
|
| 816 |
+
mwc = MaxWeightClique(G, weight)
|
| 817 |
+
mwc.find_max_weight_clique()
|
| 818 |
+
return mwc.incumbent_nodes, mwc.incumbent_weight
|
.venv/lib/python3.11/site-packages/networkx/algorithms/cluster.py
ADDED
|
@@ -0,0 +1,732 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Algorithms to characterize the number of triangles in a graph."""
|
| 2 |
+
|
| 3 |
+
from collections import Counter
|
| 4 |
+
from itertools import chain, combinations
|
| 5 |
+
|
| 6 |
+
import networkx as nx
|
| 7 |
+
from networkx.utils import not_implemented_for
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
"triangles",
|
| 11 |
+
"all_triangles",
|
| 12 |
+
"average_clustering",
|
| 13 |
+
"clustering",
|
| 14 |
+
"transitivity",
|
| 15 |
+
"square_clustering",
|
| 16 |
+
"generalized_degree",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@not_implemented_for("directed")
|
| 21 |
+
@nx._dispatchable
|
| 22 |
+
def triangles(G, nodes=None):
|
| 23 |
+
"""Compute the number of triangles.
|
| 24 |
+
|
| 25 |
+
Finds the number of triangles that include a node as one vertex.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
G : graph
|
| 30 |
+
A networkx graph
|
| 31 |
+
|
| 32 |
+
nodes : node, iterable of nodes, or None (default=None)
|
| 33 |
+
If a singleton node, return the number of triangles for that node.
|
| 34 |
+
If an iterable, compute the number of triangles for each of those nodes.
|
| 35 |
+
If `None` (the default) compute the number of triangles for all nodes in `G`.
|
| 36 |
+
|
| 37 |
+
Returns
|
| 38 |
+
-------
|
| 39 |
+
out : dict or int
|
| 40 |
+
If `nodes` is a container of nodes, returns number of triangles keyed by node (dict).
|
| 41 |
+
If `nodes` is a specific node, returns number of triangles for the node (int).
|
| 42 |
+
|
| 43 |
+
Examples
|
| 44 |
+
--------
|
| 45 |
+
>>> G = nx.complete_graph(5)
|
| 46 |
+
>>> print(nx.triangles(G, 0))
|
| 47 |
+
6
|
| 48 |
+
>>> print(nx.triangles(G))
|
| 49 |
+
{0: 6, 1: 6, 2: 6, 3: 6, 4: 6}
|
| 50 |
+
>>> print(list(nx.triangles(G, [0, 1]).values()))
|
| 51 |
+
[6, 6]
|
| 52 |
+
|
| 53 |
+
The total number of unique triangles in `G` can be determined by summing
|
| 54 |
+
the number of triangles for each node and dividing by 3 (because a given
|
| 55 |
+
triangle gets counted three times, once for each of its nodes).
|
| 56 |
+
|
| 57 |
+
>>> sum(nx.triangles(G).values()) // 3
|
| 58 |
+
10
|
| 59 |
+
|
| 60 |
+
Notes
|
| 61 |
+
-----
|
| 62 |
+
Self loops are ignored.
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
if nodes is not None:
|
| 66 |
+
# If `nodes` represents a single node, return only its number of triangles
|
| 67 |
+
if nodes in G:
|
| 68 |
+
return next(_triangles_and_degree_iter(G, nodes))[2] // 2
|
| 69 |
+
|
| 70 |
+
# if `nodes` is a container of nodes, then return a
|
| 71 |
+
# dictionary mapping node to number of triangles.
|
| 72 |
+
return {v: t // 2 for v, d, t, _ in _triangles_and_degree_iter(G, nodes)}
|
| 73 |
+
|
| 74 |
+
# if nodes is None, then compute triangles for the complete graph
|
| 75 |
+
|
| 76 |
+
# dict used to avoid visiting the same nodes twice
|
| 77 |
+
# this allows calculating/counting each triangle only once
|
| 78 |
+
later_nbrs = {}
|
| 79 |
+
|
| 80 |
+
# iterate over the nodes in a graph
|
| 81 |
+
for node, neighbors in G.adjacency():
|
| 82 |
+
later_nbrs[node] = {n for n in neighbors if n not in later_nbrs and n != node}
|
| 83 |
+
|
| 84 |
+
# instantiate Counter for each node to include isolated nodes
|
| 85 |
+
# add 1 to the count if a nodes neighbor's neighbor is also a neighbor
|
| 86 |
+
triangle_counts = Counter(dict.fromkeys(G, 0))
|
| 87 |
+
for node1, neighbors in later_nbrs.items():
|
| 88 |
+
for node2 in neighbors:
|
| 89 |
+
third_nodes = neighbors & later_nbrs[node2]
|
| 90 |
+
m = len(third_nodes)
|
| 91 |
+
triangle_counts[node1] += m
|
| 92 |
+
triangle_counts[node2] += m
|
| 93 |
+
triangle_counts.update(third_nodes)
|
| 94 |
+
|
| 95 |
+
return dict(triangle_counts)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@not_implemented_for("multigraph")
|
| 99 |
+
def _triangles_and_degree_iter(G, nodes=None):
|
| 100 |
+
"""Return an iterator of (node, degree, triangles, generalized degree).
|
| 101 |
+
|
| 102 |
+
This double counts triangles so you may want to divide by 2.
|
| 103 |
+
See degree(), triangles() and generalized_degree() for definitions
|
| 104 |
+
and details.
|
| 105 |
+
|
| 106 |
+
"""
|
| 107 |
+
if nodes is None:
|
| 108 |
+
nodes_nbrs = G.adj.items()
|
| 109 |
+
else:
|
| 110 |
+
nodes_nbrs = ((n, G[n]) for n in G.nbunch_iter(nodes))
|
| 111 |
+
|
| 112 |
+
for v, v_nbrs in nodes_nbrs:
|
| 113 |
+
vs = set(v_nbrs) - {v}
|
| 114 |
+
gen_degree = Counter(len(vs & (set(G[w]) - {w})) for w in vs)
|
| 115 |
+
ntriangles = sum(k * val for k, val in gen_degree.items())
|
| 116 |
+
yield (v, len(vs), ntriangles, gen_degree)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@not_implemented_for("multigraph")
|
| 120 |
+
def _weighted_triangles_and_degree_iter(G, nodes=None, weight="weight"):
|
| 121 |
+
"""Return an iterator of (node, degree, weighted_triangles).
|
| 122 |
+
|
| 123 |
+
Used for weighted clustering.
|
| 124 |
+
Note: this returns the geometric average weight of edges in the triangle.
|
| 125 |
+
Also, each triangle is counted twice (each direction).
|
| 126 |
+
So you may want to divide by 2.
|
| 127 |
+
|
| 128 |
+
"""
|
| 129 |
+
import numpy as np
|
| 130 |
+
|
| 131 |
+
if weight is None or G.number_of_edges() == 0:
|
| 132 |
+
max_weight = 1
|
| 133 |
+
else:
|
| 134 |
+
max_weight = max(d.get(weight, 1) for u, v, d in G.edges(data=True))
|
| 135 |
+
if nodes is None:
|
| 136 |
+
nodes_nbrs = G.adj.items()
|
| 137 |
+
else:
|
| 138 |
+
nodes_nbrs = ((n, G[n]) for n in G.nbunch_iter(nodes))
|
| 139 |
+
|
| 140 |
+
def wt(u, v):
|
| 141 |
+
return G[u][v].get(weight, 1) / max_weight
|
| 142 |
+
|
| 143 |
+
for i, nbrs in nodes_nbrs:
|
| 144 |
+
inbrs = set(nbrs) - {i}
|
| 145 |
+
weighted_triangles = 0
|
| 146 |
+
seen = set()
|
| 147 |
+
for j in inbrs:
|
| 148 |
+
seen.add(j)
|
| 149 |
+
# This avoids counting twice -- we double at the end.
|
| 150 |
+
jnbrs = set(G[j]) - seen
|
| 151 |
+
# Only compute the edge weight once, before the inner inner
|
| 152 |
+
# loop.
|
| 153 |
+
wij = wt(i, j)
|
| 154 |
+
weighted_triangles += np.cbrt(
|
| 155 |
+
[(wij * wt(j, k) * wt(k, i)) for k in inbrs & jnbrs]
|
| 156 |
+
).sum()
|
| 157 |
+
yield (i, len(inbrs), 2 * float(weighted_triangles))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@not_implemented_for("multigraph")
|
| 161 |
+
def _directed_triangles_and_degree_iter(G, nodes=None):
|
| 162 |
+
"""Return an iterator of
|
| 163 |
+
(node, total_degree, reciprocal_degree, directed_triangles).
|
| 164 |
+
|
| 165 |
+
Used for directed clustering.
|
| 166 |
+
Note that unlike `_triangles_and_degree_iter()`, this function counts
|
| 167 |
+
directed triangles so does not count triangles twice.
|
| 168 |
+
|
| 169 |
+
"""
|
| 170 |
+
nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))
|
| 171 |
+
|
| 172 |
+
for i, preds, succs in nodes_nbrs:
|
| 173 |
+
ipreds = set(preds) - {i}
|
| 174 |
+
isuccs = set(succs) - {i}
|
| 175 |
+
|
| 176 |
+
directed_triangles = 0
|
| 177 |
+
for j in chain(ipreds, isuccs):
|
| 178 |
+
jpreds = set(G._pred[j]) - {j}
|
| 179 |
+
jsuccs = set(G._succ[j]) - {j}
|
| 180 |
+
directed_triangles += sum(
|
| 181 |
+
1
|
| 182 |
+
for k in chain(
|
| 183 |
+
(ipreds & jpreds),
|
| 184 |
+
(ipreds & jsuccs),
|
| 185 |
+
(isuccs & jpreds),
|
| 186 |
+
(isuccs & jsuccs),
|
| 187 |
+
)
|
| 188 |
+
)
|
| 189 |
+
dtotal = len(ipreds) + len(isuccs)
|
| 190 |
+
dbidirectional = len(ipreds & isuccs)
|
| 191 |
+
yield (i, dtotal, dbidirectional, directed_triangles)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@not_implemented_for("multigraph")
|
| 195 |
+
def _directed_weighted_triangles_and_degree_iter(G, nodes=None, weight="weight"):
|
| 196 |
+
"""Return an iterator of
|
| 197 |
+
(node, total_degree, reciprocal_degree, directed_weighted_triangles).
|
| 198 |
+
|
| 199 |
+
Used for directed weighted clustering.
|
| 200 |
+
Note that unlike `_weighted_triangles_and_degree_iter()`, this function counts
|
| 201 |
+
directed triangles so does not count triangles twice.
|
| 202 |
+
|
| 203 |
+
"""
|
| 204 |
+
import numpy as np
|
| 205 |
+
|
| 206 |
+
if weight is None or G.number_of_edges() == 0:
|
| 207 |
+
max_weight = 1
|
| 208 |
+
else:
|
| 209 |
+
max_weight = max(d.get(weight, 1) for u, v, d in G.edges(data=True))
|
| 210 |
+
|
| 211 |
+
nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))
|
| 212 |
+
|
| 213 |
+
def wt(u, v):
|
| 214 |
+
return G[u][v].get(weight, 1) / max_weight
|
| 215 |
+
|
| 216 |
+
for i, preds, succs in nodes_nbrs:
|
| 217 |
+
ipreds = set(preds) - {i}
|
| 218 |
+
isuccs = set(succs) - {i}
|
| 219 |
+
|
| 220 |
+
directed_triangles = 0
|
| 221 |
+
for j in ipreds:
|
| 222 |
+
jpreds = set(G._pred[j]) - {j}
|
| 223 |
+
jsuccs = set(G._succ[j]) - {j}
|
| 224 |
+
directed_triangles += np.cbrt(
|
| 225 |
+
[(wt(j, i) * wt(k, i) * wt(k, j)) for k in ipreds & jpreds]
|
| 226 |
+
).sum()
|
| 227 |
+
directed_triangles += np.cbrt(
|
| 228 |
+
[(wt(j, i) * wt(k, i) * wt(j, k)) for k in ipreds & jsuccs]
|
| 229 |
+
).sum()
|
| 230 |
+
directed_triangles += np.cbrt(
|
| 231 |
+
[(wt(j, i) * wt(i, k) * wt(k, j)) for k in isuccs & jpreds]
|
| 232 |
+
).sum()
|
| 233 |
+
directed_triangles += np.cbrt(
|
| 234 |
+
[(wt(j, i) * wt(i, k) * wt(j, k)) for k in isuccs & jsuccs]
|
| 235 |
+
).sum()
|
| 236 |
+
|
| 237 |
+
for j in isuccs:
|
| 238 |
+
jpreds = set(G._pred[j]) - {j}
|
| 239 |
+
jsuccs = set(G._succ[j]) - {j}
|
| 240 |
+
directed_triangles += np.cbrt(
|
| 241 |
+
[(wt(i, j) * wt(k, i) * wt(k, j)) for k in ipreds & jpreds]
|
| 242 |
+
).sum()
|
| 243 |
+
directed_triangles += np.cbrt(
|
| 244 |
+
[(wt(i, j) * wt(k, i) * wt(j, k)) for k in ipreds & jsuccs]
|
| 245 |
+
).sum()
|
| 246 |
+
directed_triangles += np.cbrt(
|
| 247 |
+
[(wt(i, j) * wt(i, k) * wt(k, j)) for k in isuccs & jpreds]
|
| 248 |
+
).sum()
|
| 249 |
+
directed_triangles += np.cbrt(
|
| 250 |
+
[(wt(i, j) * wt(i, k) * wt(j, k)) for k in isuccs & jsuccs]
|
| 251 |
+
).sum()
|
| 252 |
+
|
| 253 |
+
dtotal = len(ipreds) + len(isuccs)
|
| 254 |
+
dbidirectional = len(ipreds & isuccs)
|
| 255 |
+
yield (i, dtotal, dbidirectional, float(directed_triangles))
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@not_implemented_for("directed")
|
| 259 |
+
@nx._dispatchable
|
| 260 |
+
def all_triangles(G, nbunch=None):
|
| 261 |
+
"""
|
| 262 |
+
Yields all unique triangles in an undirected graph.
|
| 263 |
+
|
| 264 |
+
A triangle is a set of three distinct nodes where each node is connected to
|
| 265 |
+
the other two.
|
| 266 |
+
|
| 267 |
+
Parameters
|
| 268 |
+
----------
|
| 269 |
+
G : NetworkX graph
|
| 270 |
+
An undirected graph.
|
| 271 |
+
|
| 272 |
+
nbunch : node, iterable of nodes, or None (default=None)
|
| 273 |
+
If a node or iterable of nodes, only triangles involving at least one
|
| 274 |
+
node in `nbunch` are yielded.
|
| 275 |
+
If ``None``, yields all unique triangles in the graph.
|
| 276 |
+
|
| 277 |
+
Yields
|
| 278 |
+
------
|
| 279 |
+
tuple
|
| 280 |
+
A tuple of three nodes forming a triangle ``(u, v, w)``.
|
| 281 |
+
|
| 282 |
+
Examples
|
| 283 |
+
--------
|
| 284 |
+
>>> G = nx.complete_graph(4)
|
| 285 |
+
>>> sorted([sorted(t) for t in all_triangles(G)])
|
| 286 |
+
[[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]
|
| 287 |
+
|
| 288 |
+
Notes
|
| 289 |
+
-----
|
| 290 |
+
This algorithm ensures each triangle is yielded once using an internal node ordering.
|
| 291 |
+
In multigraphs, triangles are identified by their unique set of nodes,
|
| 292 |
+
ignoring multiple edges between the same nodes. Self-loops are ignored.
|
| 293 |
+
Runs in ``O(m * d)`` time in the worst case, where ``m`` the number of edges
|
| 294 |
+
and ``d`` the maximum degree.
|
| 295 |
+
|
| 296 |
+
See Also
|
| 297 |
+
--------
|
| 298 |
+
:func:`~networkx.algorithms.triads.all_triads` : related function for directed graphs
|
| 299 |
+
"""
|
| 300 |
+
if nbunch is None:
|
| 301 |
+
nbunch = relevant_nodes = G
|
| 302 |
+
else:
|
| 303 |
+
nbunch = dict.fromkeys(G.nbunch_iter(nbunch))
|
| 304 |
+
relevant_nodes = chain(
|
| 305 |
+
nbunch,
|
| 306 |
+
(nbr for node in nbunch for nbr in G.neighbors(node) if nbr not in nbunch),
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
node_to_id = {node: i for i, node in enumerate(relevant_nodes)}
|
| 310 |
+
|
| 311 |
+
for u in nbunch:
|
| 312 |
+
u_id = node_to_id[u]
|
| 313 |
+
u_nbrs = G._adj[u].keys()
|
| 314 |
+
for v in u_nbrs:
|
| 315 |
+
v_id = node_to_id.get(v, -1)
|
| 316 |
+
if v_id <= u_id:
|
| 317 |
+
continue
|
| 318 |
+
v_nbrs = G._adj[v].keys()
|
| 319 |
+
for w in v_nbrs & u_nbrs:
|
| 320 |
+
if node_to_id.get(w, -1) > v_id:
|
| 321 |
+
yield u, v, w
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 325 |
+
def average_clustering(G, nodes=None, weight=None, count_zeros=True):
|
| 326 |
+
r"""Compute the average clustering coefficient for the graph G.
|
| 327 |
+
|
| 328 |
+
The clustering coefficient for the graph is the average,
|
| 329 |
+
|
| 330 |
+
.. math::
|
| 331 |
+
|
| 332 |
+
C = \frac{1}{n}\sum_{v \in G} c_v,
|
| 333 |
+
|
| 334 |
+
where :math:`n` is the number of nodes in `G`.
|
| 335 |
+
|
| 336 |
+
Parameters
|
| 337 |
+
----------
|
| 338 |
+
G : graph
|
| 339 |
+
|
| 340 |
+
nodes : container of nodes, optional (default=all nodes in G)
|
| 341 |
+
Compute average clustering for nodes in this container.
|
| 342 |
+
|
| 343 |
+
weight : string or None, optional (default=None)
|
| 344 |
+
The edge attribute that holds the numerical value used as a weight.
|
| 345 |
+
If None, then each edge has weight 1.
|
| 346 |
+
|
| 347 |
+
count_zeros : bool
|
| 348 |
+
If False include only the nodes with nonzero clustering in the average.
|
| 349 |
+
|
| 350 |
+
Returns
|
| 351 |
+
-------
|
| 352 |
+
avg : float
|
| 353 |
+
Average clustering
|
| 354 |
+
|
| 355 |
+
Examples
|
| 356 |
+
--------
|
| 357 |
+
>>> G = nx.complete_graph(5)
|
| 358 |
+
>>> print(nx.average_clustering(G))
|
| 359 |
+
1.0
|
| 360 |
+
|
| 361 |
+
Notes
|
| 362 |
+
-----
|
| 363 |
+
This is a space saving routine; it might be faster
|
| 364 |
+
to use the clustering function to get a list and then take the average.
|
| 365 |
+
|
| 366 |
+
Self loops are ignored.
|
| 367 |
+
|
| 368 |
+
References
|
| 369 |
+
----------
|
| 370 |
+
.. [1] Generalizations of the clustering coefficient to weighted
|
| 371 |
+
complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
|
| 372 |
+
K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
|
| 373 |
+
http://jponnela.com/web_documents/a9.pdf
|
| 374 |
+
.. [2] Marcus Kaiser, Mean clustering coefficients: the role of isolated
|
| 375 |
+
nodes and leafs on clustering measures for small-world networks.
|
| 376 |
+
https://arxiv.org/abs/0802.2512
|
| 377 |
+
"""
|
| 378 |
+
c = clustering(G, nodes, weight=weight).values()
|
| 379 |
+
if not count_zeros:
|
| 380 |
+
c = [v for v in c if abs(v) > 0]
|
| 381 |
+
return sum(c) / len(c)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 385 |
+
def clustering(G, nodes=None, weight=None):
|
| 386 |
+
r"""Compute the clustering coefficient for nodes.
|
| 387 |
+
|
| 388 |
+
For unweighted graphs, the clustering of a node :math:`u`
|
| 389 |
+
is the fraction of possible triangles through that node that exist,
|
| 390 |
+
|
| 391 |
+
.. math::
|
| 392 |
+
|
| 393 |
+
c_u = \frac{2 T(u)}{deg(u)(deg(u)-1)},
|
| 394 |
+
|
| 395 |
+
where :math:`T(u)` is the number of triangles through node :math:`u` and
|
| 396 |
+
:math:`deg(u)` is the degree of :math:`u`.
|
| 397 |
+
|
| 398 |
+
For weighted graphs, there are several ways to define clustering [1]_.
|
| 399 |
+
the one used here is defined
|
| 400 |
+
as the geometric average of the subgraph edge weights [2]_,
|
| 401 |
+
|
| 402 |
+
.. math::
|
| 403 |
+
|
| 404 |
+
c_u = \frac{1}{deg(u)(deg(u)-1))}
|
| 405 |
+
\sum_{vw} (\hat{w}_{uv} \hat{w}_{uw} \hat{w}_{vw})^{1/3}.
|
| 406 |
+
|
| 407 |
+
The edge weights :math:`\hat{w}_{uv}` are normalized by the maximum weight
|
| 408 |
+
in the network :math:`\hat{w}_{uv} = w_{uv}/\max(w)`.
|
| 409 |
+
|
| 410 |
+
The value of :math:`c_u` is assigned to 0 if :math:`deg(u) < 2`.
|
| 411 |
+
|
| 412 |
+
Additionally, this weighted definition has been generalized to support negative edge weights [3]_.
|
| 413 |
+
|
| 414 |
+
For directed graphs, the clustering is similarly defined as the fraction
|
| 415 |
+
of all possible directed triangles or geometric average of the subgraph
|
| 416 |
+
edge weights for unweighted and weighted directed graph respectively [4]_.
|
| 417 |
+
|
| 418 |
+
.. math::
|
| 419 |
+
|
| 420 |
+
c_u = \frac{T(u)}{2(deg^{tot}(u)(deg^{tot}(u)-1) - 2deg^{\leftrightarrow}(u))},
|
| 421 |
+
|
| 422 |
+
where :math:`T(u)` is the number of directed triangles through node
|
| 423 |
+
:math:`u`, :math:`deg^{tot}(u)` is the sum of in degree and out degree of
|
| 424 |
+
:math:`u` and :math:`deg^{\leftrightarrow}(u)` is the reciprocal degree of
|
| 425 |
+
:math:`u`.
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
Parameters
|
| 429 |
+
----------
|
| 430 |
+
G : graph
|
| 431 |
+
|
| 432 |
+
nodes : node, iterable of nodes, or None (default=None)
|
| 433 |
+
If a singleton node, return the number of triangles for that node.
|
| 434 |
+
If an iterable, compute the number of triangles for each of those nodes.
|
| 435 |
+
If `None` (the default) compute the number of triangles for all nodes in `G`.
|
| 436 |
+
|
| 437 |
+
weight : string or None, optional (default=None)
|
| 438 |
+
The edge attribute that holds the numerical value used as a weight.
|
| 439 |
+
If None, then each edge has weight 1.
|
| 440 |
+
|
| 441 |
+
Returns
|
| 442 |
+
-------
|
| 443 |
+
out : float, or dictionary
|
| 444 |
+
Clustering coefficient at specified nodes
|
| 445 |
+
|
| 446 |
+
Examples
|
| 447 |
+
--------
|
| 448 |
+
>>> G = nx.complete_graph(5)
|
| 449 |
+
>>> print(nx.clustering(G, 0))
|
| 450 |
+
1.0
|
| 451 |
+
>>> print(nx.clustering(G))
|
| 452 |
+
{0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
|
| 453 |
+
|
| 454 |
+
Notes
|
| 455 |
+
-----
|
| 456 |
+
Self loops are ignored.
|
| 457 |
+
|
| 458 |
+
References
|
| 459 |
+
----------
|
| 460 |
+
.. [1] Generalizations of the clustering coefficient to weighted
|
| 461 |
+
complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
|
| 462 |
+
K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
|
| 463 |
+
http://jponnela.com/web_documents/a9.pdf
|
| 464 |
+
.. [2] Intensity and coherence of motifs in weighted complex
|
| 465 |
+
networks by J. P. Onnela, J. Saramäki, J. Kertész, and K. Kaski,
|
| 466 |
+
Physical Review E, 71(6), 065103 (2005).
|
| 467 |
+
.. [3] Generalization of Clustering Coefficients to Signed Correlation Networks
|
| 468 |
+
by G. Costantini and M. Perugini, PloS one, 9(2), e88669 (2014).
|
| 469 |
+
.. [4] Clustering in complex directed networks by G. Fagiolo,
|
| 470 |
+
Physical Review E, 76(2), 026107 (2007).
|
| 471 |
+
"""
|
| 472 |
+
if G.is_directed():
|
| 473 |
+
if weight is not None:
|
| 474 |
+
td_iter = _directed_weighted_triangles_and_degree_iter(G, nodes, weight)
|
| 475 |
+
clusterc = {
|
| 476 |
+
v: 0 if t == 0 else t / ((dt * (dt - 1) - 2 * db) * 2)
|
| 477 |
+
for v, dt, db, t in td_iter
|
| 478 |
+
}
|
| 479 |
+
else:
|
| 480 |
+
td_iter = _directed_triangles_and_degree_iter(G, nodes)
|
| 481 |
+
clusterc = {
|
| 482 |
+
v: 0 if t == 0 else t / ((dt * (dt - 1) - 2 * db) * 2)
|
| 483 |
+
for v, dt, db, t in td_iter
|
| 484 |
+
}
|
| 485 |
+
else:
|
| 486 |
+
# The formula 2*T/(d*(d-1)) from docs is t/(d*(d-1)) here b/c t==2*T
|
| 487 |
+
if weight is not None:
|
| 488 |
+
td_iter = _weighted_triangles_and_degree_iter(G, nodes, weight)
|
| 489 |
+
clusterc = {v: 0 if t == 0 else t / (d * (d - 1)) for v, d, t in td_iter}
|
| 490 |
+
else:
|
| 491 |
+
td_iter = _triangles_and_degree_iter(G, nodes)
|
| 492 |
+
clusterc = {v: 0 if t == 0 else t / (d * (d - 1)) for v, d, t, _ in td_iter}
|
| 493 |
+
if nodes in G:
|
| 494 |
+
# Return the value of the sole entry in the dictionary.
|
| 495 |
+
return clusterc[nodes]
|
| 496 |
+
return clusterc
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
@nx._dispatchable
|
| 500 |
+
def transitivity(G):
|
| 501 |
+
r"""Compute graph transitivity, the fraction of all possible triangles
|
| 502 |
+
present in G.
|
| 503 |
+
|
| 504 |
+
Possible triangles are identified by the number of "triads"
|
| 505 |
+
(two edges with a shared vertex).
|
| 506 |
+
|
| 507 |
+
The transitivity is
|
| 508 |
+
|
| 509 |
+
.. math::
|
| 510 |
+
|
| 511 |
+
T = 3\frac{\#triangles}{\#triads}.
|
| 512 |
+
|
| 513 |
+
Parameters
|
| 514 |
+
----------
|
| 515 |
+
G : graph
|
| 516 |
+
|
| 517 |
+
Returns
|
| 518 |
+
-------
|
| 519 |
+
out : float
|
| 520 |
+
Transitivity
|
| 521 |
+
|
| 522 |
+
Notes
|
| 523 |
+
-----
|
| 524 |
+
Self loops are ignored.
|
| 525 |
+
|
| 526 |
+
Examples
|
| 527 |
+
--------
|
| 528 |
+
>>> G = nx.complete_graph(5)
|
| 529 |
+
>>> print(nx.transitivity(G))
|
| 530 |
+
1.0
|
| 531 |
+
"""
|
| 532 |
+
triangles_contri = [
|
| 533 |
+
(t, d * (d - 1)) for v, d, t, _ in _triangles_and_degree_iter(G)
|
| 534 |
+
]
|
| 535 |
+
# If the graph is empty
|
| 536 |
+
if len(triangles_contri) == 0:
|
| 537 |
+
return 0
|
| 538 |
+
triangles, contri = map(sum, zip(*triangles_contri))
|
| 539 |
+
return 0 if triangles == 0 else triangles / contri
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
@nx._dispatchable
|
| 543 |
+
def square_clustering(G, nodes=None):
|
| 544 |
+
r"""Compute the squares clustering coefficient for nodes.
|
| 545 |
+
|
| 546 |
+
For each node return the fraction of possible squares that exist at
|
| 547 |
+
the node [1]_
|
| 548 |
+
|
| 549 |
+
.. math::
|
| 550 |
+
C_4(v) = \frac{ \sum_{u=1}^{k_v}
|
| 551 |
+
\sum_{w=u+1}^{k_v} q_v(u,w) }{ \sum_{u=1}^{k_v}
|
| 552 |
+
\sum_{w=u+1}^{k_v} [a_v(u,w) + q_v(u,w)]},
|
| 553 |
+
|
| 554 |
+
where :math:`q_v(u,w)` are the number of common neighbors of :math:`u` and
|
| 555 |
+
:math:`w` other than :math:`v` (ie squares), and :math:`a_v(u,w) = (k_u -
|
| 556 |
+
(1+q_v(u,w)+\theta_{uv})) + (k_w - (1+q_v(u,w)+\theta_{uw}))`, where
|
| 557 |
+
:math:`\theta_{uw} = 1` if :math:`u` and :math:`w` are connected and 0
|
| 558 |
+
otherwise. [2]_
|
| 559 |
+
|
| 560 |
+
Parameters
|
| 561 |
+
----------
|
| 562 |
+
G : graph
|
| 563 |
+
|
| 564 |
+
nodes : container of nodes, optional (default=all nodes in G)
|
| 565 |
+
Compute clustering for nodes in this container.
|
| 566 |
+
|
| 567 |
+
Returns
|
| 568 |
+
-------
|
| 569 |
+
c4 : dictionary
|
| 570 |
+
A dictionary keyed by node with the square clustering coefficient value.
|
| 571 |
+
|
| 572 |
+
Examples
|
| 573 |
+
--------
|
| 574 |
+
>>> G = nx.complete_graph(5)
|
| 575 |
+
>>> print(nx.square_clustering(G, 0))
|
| 576 |
+
1.0
|
| 577 |
+
>>> print(nx.square_clustering(G))
|
| 578 |
+
{0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
|
| 579 |
+
|
| 580 |
+
Notes
|
| 581 |
+
-----
|
| 582 |
+
Self loops are ignored.
|
| 583 |
+
|
| 584 |
+
While :math:`C_3(v)` (triangle clustering) gives the probability that
|
| 585 |
+
two neighbors of node v are connected with each other, :math:`C_4(v)` is
|
| 586 |
+
the probability that two neighbors of node v share a common
|
| 587 |
+
neighbor different from v. This algorithm can be applied to both
|
| 588 |
+
bipartite and unipartite networks.
|
| 589 |
+
|
| 590 |
+
References
|
| 591 |
+
----------
|
| 592 |
+
.. [1] Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005
|
| 593 |
+
Cycles and clustering in bipartite networks.
|
| 594 |
+
Physical Review E (72) 056127.
|
| 595 |
+
.. [2] Zhang, Peng et al. Clustering Coefficient and Community Structure of
|
| 596 |
+
Bipartite Networks. Physica A: Statistical Mechanics and its Applications 387.27 (2008): 6869–6875.
|
| 597 |
+
https://arxiv.org/abs/0710.0117v1
|
| 598 |
+
"""
|
| 599 |
+
if nodes is None:
|
| 600 |
+
node_iter = G
|
| 601 |
+
else:
|
| 602 |
+
node_iter = G.nbunch_iter(nodes)
|
| 603 |
+
clustering = {}
|
| 604 |
+
_G_adj = G._adj
|
| 605 |
+
|
| 606 |
+
class GAdj(dict):
|
| 607 |
+
"""Calculate (and cache) node neighbor sets excluding self-loops."""
|
| 608 |
+
|
| 609 |
+
def __missing__(self, v):
|
| 610 |
+
v_neighbors = self[v] = set(_G_adj[v])
|
| 611 |
+
v_neighbors.discard(v) # Ignore self-loops
|
| 612 |
+
return v_neighbors
|
| 613 |
+
|
| 614 |
+
G_adj = GAdj() # Values are sets of neighbors (no self-loops)
|
| 615 |
+
|
| 616 |
+
for v in node_iter:
|
| 617 |
+
v_neighbors = G_adj[v]
|
| 618 |
+
v_degrees_m1 = len(v_neighbors) - 1 # degrees[v] - 1 (used below)
|
| 619 |
+
if v_degrees_m1 <= 0:
|
| 620 |
+
# Can't form a square without at least two neighbors
|
| 621 |
+
clustering[v] = 0
|
| 622 |
+
continue
|
| 623 |
+
|
| 624 |
+
# Count squares with nodes u-v-w-x from the current node v.
|
| 625 |
+
# Terms of the denominator: potential = uw_degrees - uw_count - triangles - squares
|
| 626 |
+
# uw_degrees: degrees[u] + degrees[w] for each u-w combo
|
| 627 |
+
uw_degrees = 0
|
| 628 |
+
# uw_count: 1 for each u and 1 for each w for all combos (degrees * (degrees - 1))
|
| 629 |
+
uw_count = len(v_neighbors) * v_degrees_m1
|
| 630 |
+
# triangles: 1 for each edge where u-w or w-u are connected (i.e. triangles)
|
| 631 |
+
triangles = 0
|
| 632 |
+
# squares: the number of squares (also the numerator)
|
| 633 |
+
squares = 0
|
| 634 |
+
|
| 635 |
+
# Iterate over all neighbors
|
| 636 |
+
for u in v_neighbors:
|
| 637 |
+
u_neighbors = G_adj[u]
|
| 638 |
+
uw_degrees += len(u_neighbors) * v_degrees_m1
|
| 639 |
+
# P2 from https://arxiv.org/abs/2007.11111
|
| 640 |
+
p2 = len(u_neighbors & v_neighbors)
|
| 641 |
+
# triangles is C_3, sigma_4 from https://arxiv.org/abs/2007.11111
|
| 642 |
+
# This double-counts triangles compared to `triangles` function
|
| 643 |
+
triangles += p2
|
| 644 |
+
# squares is C_4, sigma_12 from https://arxiv.org/abs/2007.11111
|
| 645 |
+
# Include this term, b/c a neighbor u can also be a neighbor of neighbor x
|
| 646 |
+
squares += p2 * (p2 - 1) # Will divide by 2 later
|
| 647 |
+
|
| 648 |
+
# And iterate over all neighbors of neighbors.
|
| 649 |
+
# These nodes x may be the corners opposite v in squares u-v-w-x.
|
| 650 |
+
two_hop_neighbors = set.union(*(G_adj[u] for u in v_neighbors))
|
| 651 |
+
two_hop_neighbors -= v_neighbors # Neighbors already counted above
|
| 652 |
+
two_hop_neighbors.discard(v)
|
| 653 |
+
for x in two_hop_neighbors:
|
| 654 |
+
p2 = len(v_neighbors & G_adj[x])
|
| 655 |
+
squares += p2 * (p2 - 1) # Will divide by 2 later
|
| 656 |
+
|
| 657 |
+
squares //= 2
|
| 658 |
+
potential = uw_degrees - uw_count - triangles - squares
|
| 659 |
+
if potential > 0:
|
| 660 |
+
clustering[v] = squares / potential
|
| 661 |
+
else:
|
| 662 |
+
clustering[v] = 0
|
| 663 |
+
if nodes in G:
|
| 664 |
+
# Return the value of the sole entry in the dictionary.
|
| 665 |
+
return clustering[nodes]
|
| 666 |
+
return clustering
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
@not_implemented_for("directed")
|
| 670 |
+
@nx._dispatchable
|
| 671 |
+
def generalized_degree(G, nodes=None):
|
| 672 |
+
r"""Compute the generalized degree for nodes.
|
| 673 |
+
|
| 674 |
+
For each node, the generalized degree shows how many edges of given
|
| 675 |
+
triangle multiplicity the node is connected to. The triangle multiplicity
|
| 676 |
+
of an edge is the number of triangles an edge participates in. The
|
| 677 |
+
generalized degree of node :math:`i` can be written as a vector
|
| 678 |
+
:math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc, k_i^{(N-2)})` where
|
| 679 |
+
:math:`k_i^{(j)}` is the number of edges attached to node :math:`i` that
|
| 680 |
+
participate in :math:`j` triangles.
|
| 681 |
+
|
| 682 |
+
Parameters
|
| 683 |
+
----------
|
| 684 |
+
G : graph
|
| 685 |
+
|
| 686 |
+
nodes : container of nodes, optional (default=all nodes in G)
|
| 687 |
+
Compute the generalized degree for nodes in this container.
|
| 688 |
+
|
| 689 |
+
Returns
|
| 690 |
+
-------
|
| 691 |
+
out : Counter, or dictionary of Counters
|
| 692 |
+
Generalized degree of specified nodes. The Counter is keyed by edge
|
| 693 |
+
triangle multiplicity.
|
| 694 |
+
|
| 695 |
+
Examples
|
| 696 |
+
--------
|
| 697 |
+
>>> G = nx.complete_graph(5)
|
| 698 |
+
>>> print(nx.generalized_degree(G, 0))
|
| 699 |
+
Counter({3: 4})
|
| 700 |
+
>>> print(nx.generalized_degree(G))
|
| 701 |
+
{0: Counter({3: 4}), 1: Counter({3: 4}), 2: Counter({3: 4}), 3: Counter({3: 4}), 4: Counter({3: 4})}
|
| 702 |
+
|
| 703 |
+
To recover the number of triangles attached to a node:
|
| 704 |
+
|
| 705 |
+
>>> k1 = nx.generalized_degree(G, 0)
|
| 706 |
+
>>> sum([k * v for k, v in k1.items()]) / 2 == nx.triangles(G, 0)
|
| 707 |
+
True
|
| 708 |
+
|
| 709 |
+
Notes
|
| 710 |
+
-----
|
| 711 |
+
Self loops are ignored.
|
| 712 |
+
|
| 713 |
+
In a network of N nodes, the highest triangle multiplicity an edge can have
|
| 714 |
+
is N-2.
|
| 715 |
+
|
| 716 |
+
The return value does not include a `zero` entry if no edges of a
|
| 717 |
+
particular triangle multiplicity are present.
|
| 718 |
+
|
| 719 |
+
The number of triangles node :math:`i` is attached to can be recovered from
|
| 720 |
+
the generalized degree :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc,
|
| 721 |
+
k_i^{(N-2)})` by :math:`(k_i^{(1)}+2k_i^{(2)}+\dotsc +(N-2)k_i^{(N-2)})/2`.
|
| 722 |
+
|
| 723 |
+
References
|
| 724 |
+
----------
|
| 725 |
+
.. [1] Networks with arbitrary edge multiplicities by V. Zlatić,
|
| 726 |
+
D. Garlaschelli and G. Caldarelli, EPL (Europhysics Letters),
|
| 727 |
+
Volume 97, Number 2 (2012).
|
| 728 |
+
https://iopscience.iop.org/article/10.1209/0295-5075/97/28005
|
| 729 |
+
"""
|
| 730 |
+
if nodes in G:
|
| 731 |
+
return next(_triangles_and_degree_iter(G, nodes))[3]
|
| 732 |
+
return {v: gd for v, d, t, gd in _triangles_and_degree_iter(G, nodes)}
|
.venv/lib/python3.11/site-packages/networkx/algorithms/coloring/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from networkx.algorithms.coloring.greedy_coloring import *
|
| 2 |
+
from networkx.algorithms.coloring.equitable_coloring import equitable_color
|
| 3 |
+
|
| 4 |
+
__all__ = ["greedy_color", "equitable_color"]
|
.venv/lib/python3.11/site-packages/networkx/algorithms/coloring/equitable_coloring.py
ADDED
|
@@ -0,0 +1,505 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Equitable coloring of graphs with bounded degree.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
|
| 9 |
+
__all__ = ["equitable_color"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@nx._dispatchable
|
| 13 |
+
def is_coloring(G, coloring):
|
| 14 |
+
"""Determine if the coloring is a valid coloring for the graph G."""
|
| 15 |
+
# Verify that the coloring is valid.
|
| 16 |
+
return all(coloring[s] != coloring[d] for s, d in G.edges)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@nx._dispatchable
|
| 20 |
+
def is_equitable(G, coloring, num_colors=None):
|
| 21 |
+
"""Determines if the coloring is valid and equitable for the graph G."""
|
| 22 |
+
|
| 23 |
+
if not is_coloring(G, coloring):
|
| 24 |
+
return False
|
| 25 |
+
|
| 26 |
+
# Verify whether it is equitable.
|
| 27 |
+
color_set_size = defaultdict(int)
|
| 28 |
+
for color in coloring.values():
|
| 29 |
+
color_set_size[color] += 1
|
| 30 |
+
|
| 31 |
+
if num_colors is not None:
|
| 32 |
+
for color in range(num_colors):
|
| 33 |
+
if color not in color_set_size:
|
| 34 |
+
# These colors do not have any vertices attached to them.
|
| 35 |
+
color_set_size[color] = 0
|
| 36 |
+
|
| 37 |
+
# If there are more than 2 distinct values, the coloring cannot be equitable
|
| 38 |
+
all_set_sizes = set(color_set_size.values())
|
| 39 |
+
if len(all_set_sizes) == 0 and num_colors is None: # Was an empty graph
|
| 40 |
+
return True
|
| 41 |
+
elif len(all_set_sizes) == 1:
|
| 42 |
+
return True
|
| 43 |
+
elif len(all_set_sizes) == 2:
|
| 44 |
+
a, b = list(all_set_sizes)
|
| 45 |
+
return abs(a - b) <= 1
|
| 46 |
+
else: # len(all_set_sizes) > 2:
|
| 47 |
+
return False
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def make_C_from_F(F):
|
| 51 |
+
C = defaultdict(list)
|
| 52 |
+
for node, color in F.items():
|
| 53 |
+
C[color].append(node)
|
| 54 |
+
|
| 55 |
+
return C
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def make_N_from_L_C(L, C):
|
| 59 |
+
nodes = L.keys()
|
| 60 |
+
colors = C.keys()
|
| 61 |
+
return {
|
| 62 |
+
(node, color): sum(1 for v in L[node] if v in C[color])
|
| 63 |
+
for node in nodes
|
| 64 |
+
for color in colors
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def make_H_from_C_N(C, N):
|
| 69 |
+
return {
|
| 70 |
+
(c1, c2): sum(1 for node in C[c1] if N[(node, c2)] == 0) for c1 in C for c2 in C
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def change_color(u, X, Y, N, H, F, C, L):
|
| 75 |
+
"""Change the color of 'u' from X to Y and update N, H, F, C."""
|
| 76 |
+
assert F[u] == X and X != Y
|
| 77 |
+
|
| 78 |
+
# Change the class of 'u' from X to Y
|
| 79 |
+
F[u] = Y
|
| 80 |
+
|
| 81 |
+
for k in C:
|
| 82 |
+
# 'u' witnesses an edge from k -> Y instead of from k -> X now.
|
| 83 |
+
if N[u, k] == 0:
|
| 84 |
+
H[(X, k)] -= 1
|
| 85 |
+
H[(Y, k)] += 1
|
| 86 |
+
|
| 87 |
+
for v in L[u]:
|
| 88 |
+
# 'v' has lost a neighbor in X and gained one in Y
|
| 89 |
+
N[(v, X)] -= 1
|
| 90 |
+
N[(v, Y)] += 1
|
| 91 |
+
|
| 92 |
+
if N[(v, X)] == 0:
|
| 93 |
+
# 'v' witnesses F[v] -> X
|
| 94 |
+
H[(F[v], X)] += 1
|
| 95 |
+
|
| 96 |
+
if N[(v, Y)] == 1:
|
| 97 |
+
# 'v' no longer witnesses F[v] -> Y
|
| 98 |
+
H[(F[v], Y)] -= 1
|
| 99 |
+
|
| 100 |
+
C[X].remove(u)
|
| 101 |
+
C[Y].append(u)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def move_witnesses(src_color, dst_color, N, H, F, C, T_cal, L):
|
| 105 |
+
"""Move witness along a path from src_color to dst_color."""
|
| 106 |
+
X = src_color
|
| 107 |
+
while X != dst_color:
|
| 108 |
+
Y = T_cal[X]
|
| 109 |
+
# Move _any_ witness from X to Y = T_cal[X]
|
| 110 |
+
w = next(x for x in C[X] if N[(x, Y)] == 0)
|
| 111 |
+
change_color(w, X, Y, N=N, H=H, F=F, C=C, L=L)
|
| 112 |
+
X = Y
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@nx._dispatchable(mutates_input=True)
|
| 116 |
+
def pad_graph(G, num_colors):
|
| 117 |
+
"""Add a disconnected complete clique K_p such that the number of nodes in
|
| 118 |
+
the graph becomes a multiple of `num_colors`.
|
| 119 |
+
|
| 120 |
+
Assumes that the graph's nodes are labelled using integers.
|
| 121 |
+
|
| 122 |
+
Returns the number of nodes with each color.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
n_ = len(G)
|
| 126 |
+
r = num_colors - 1
|
| 127 |
+
|
| 128 |
+
# Ensure that the number of nodes in G is a multiple of (r + 1)
|
| 129 |
+
s = n_ // (r + 1)
|
| 130 |
+
if n_ != s * (r + 1):
|
| 131 |
+
p = (r + 1) - n_ % (r + 1)
|
| 132 |
+
s += 1
|
| 133 |
+
|
| 134 |
+
# Complete graph K_p between (imaginary) nodes [n_, ... , n_ + p]
|
| 135 |
+
K = nx.relabel_nodes(nx.complete_graph(p), {idx: idx + n_ for idx in range(p)})
|
| 136 |
+
G.add_edges_from(K.edges)
|
| 137 |
+
|
| 138 |
+
return s
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def procedure_P(V_minus, V_plus, N, H, F, C, L, excluded_colors=None):
|
| 142 |
+
"""Procedure P as described in the paper."""
|
| 143 |
+
|
| 144 |
+
if excluded_colors is None:
|
| 145 |
+
excluded_colors = set()
|
| 146 |
+
|
| 147 |
+
A_cal = set()
|
| 148 |
+
T_cal = {}
|
| 149 |
+
R_cal = []
|
| 150 |
+
|
| 151 |
+
# BFS to determine A_cal, i.e. colors reachable from V-
|
| 152 |
+
reachable = [V_minus]
|
| 153 |
+
marked = set(reachable)
|
| 154 |
+
idx = 0
|
| 155 |
+
|
| 156 |
+
while idx < len(reachable):
|
| 157 |
+
pop = reachable[idx]
|
| 158 |
+
idx += 1
|
| 159 |
+
|
| 160 |
+
A_cal.add(pop)
|
| 161 |
+
R_cal.append(pop)
|
| 162 |
+
|
| 163 |
+
# TODO: Checking whether a color has been visited can be made faster by
|
| 164 |
+
# using a look-up table instead of testing for membership in a set by a
|
| 165 |
+
# logarithmic factor.
|
| 166 |
+
next_layer = []
|
| 167 |
+
for k in C:
|
| 168 |
+
if (
|
| 169 |
+
H[(k, pop)] > 0
|
| 170 |
+
and k not in A_cal
|
| 171 |
+
and k not in excluded_colors
|
| 172 |
+
and k not in marked
|
| 173 |
+
):
|
| 174 |
+
next_layer.append(k)
|
| 175 |
+
|
| 176 |
+
for dst in next_layer:
|
| 177 |
+
# Record that `dst` can reach `pop`
|
| 178 |
+
T_cal[dst] = pop
|
| 179 |
+
|
| 180 |
+
marked.update(next_layer)
|
| 181 |
+
reachable.extend(next_layer)
|
| 182 |
+
|
| 183 |
+
# Variables for the algorithm
|
| 184 |
+
b = len(C) - len(A_cal)
|
| 185 |
+
|
| 186 |
+
if V_plus in A_cal:
|
| 187 |
+
# Easy case: V+ is in A_cal
|
| 188 |
+
# Move one node from V+ to V- using T_cal to find the parents.
|
| 189 |
+
move_witnesses(V_plus, V_minus, N=N, H=H, F=F, C=C, T_cal=T_cal, L=L)
|
| 190 |
+
else:
|
| 191 |
+
# If there is a solo edge, we can resolve the situation by
|
| 192 |
+
# moving witnesses from B to A, making G[A] equitable and then
|
| 193 |
+
# recursively balancing G[B - w] with a different V_minus and
|
| 194 |
+
# but the same V_plus.
|
| 195 |
+
|
| 196 |
+
A_0 = set()
|
| 197 |
+
A_cal_0 = set()
|
| 198 |
+
num_terminal_sets_found = 0
|
| 199 |
+
made_equitable = False
|
| 200 |
+
|
| 201 |
+
for W_1 in R_cal[::-1]:
|
| 202 |
+
for v in C[W_1]:
|
| 203 |
+
X = None
|
| 204 |
+
|
| 205 |
+
for U in C:
|
| 206 |
+
if N[(v, U)] == 0 and U in A_cal and U != W_1:
|
| 207 |
+
X = U
|
| 208 |
+
|
| 209 |
+
# v does not witness an edge in H[A_cal]
|
| 210 |
+
if X is None:
|
| 211 |
+
continue
|
| 212 |
+
|
| 213 |
+
for U in C:
|
| 214 |
+
# Note: Departing from the paper here.
|
| 215 |
+
if N[(v, U)] >= 1 and U not in A_cal:
|
| 216 |
+
X_prime = U
|
| 217 |
+
w = v
|
| 218 |
+
|
| 219 |
+
try:
|
| 220 |
+
# Finding the solo neighbor of w in X_prime
|
| 221 |
+
y = next(
|
| 222 |
+
node
|
| 223 |
+
for node in L[w]
|
| 224 |
+
if F[node] == X_prime and N[(node, W_1)] == 1
|
| 225 |
+
)
|
| 226 |
+
except StopIteration:
|
| 227 |
+
pass
|
| 228 |
+
else:
|
| 229 |
+
W = W_1
|
| 230 |
+
|
| 231 |
+
# Move w from W to X, now X has one extra node.
|
| 232 |
+
change_color(w, W, X, N=N, H=H, F=F, C=C, L=L)
|
| 233 |
+
|
| 234 |
+
# Move witness from X to V_minus, making the coloring
|
| 235 |
+
# equitable.
|
| 236 |
+
move_witnesses(
|
| 237 |
+
src_color=X,
|
| 238 |
+
dst_color=V_minus,
|
| 239 |
+
N=N,
|
| 240 |
+
H=H,
|
| 241 |
+
F=F,
|
| 242 |
+
C=C,
|
| 243 |
+
T_cal=T_cal,
|
| 244 |
+
L=L,
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# Move y from X_prime to W, making W the correct size.
|
| 248 |
+
change_color(y, X_prime, W, N=N, H=H, F=F, C=C, L=L)
|
| 249 |
+
|
| 250 |
+
# Then call the procedure on G[B - y]
|
| 251 |
+
procedure_P(
|
| 252 |
+
V_minus=X_prime,
|
| 253 |
+
V_plus=V_plus,
|
| 254 |
+
N=N,
|
| 255 |
+
H=H,
|
| 256 |
+
C=C,
|
| 257 |
+
F=F,
|
| 258 |
+
L=L,
|
| 259 |
+
excluded_colors=excluded_colors.union(A_cal),
|
| 260 |
+
)
|
| 261 |
+
made_equitable = True
|
| 262 |
+
break
|
| 263 |
+
|
| 264 |
+
if made_equitable:
|
| 265 |
+
break
|
| 266 |
+
else:
|
| 267 |
+
# No node in W_1 was found such that
|
| 268 |
+
# it had a solo-neighbor.
|
| 269 |
+
A_cal_0.add(W_1)
|
| 270 |
+
A_0.update(C[W_1])
|
| 271 |
+
num_terminal_sets_found += 1
|
| 272 |
+
|
| 273 |
+
if num_terminal_sets_found == b:
|
| 274 |
+
# Otherwise, construct the maximal independent set and find
|
| 275 |
+
# a pair of z_1, z_2 as in Case II.
|
| 276 |
+
|
| 277 |
+
# BFS to determine B_cal': the set of colors reachable from V+
|
| 278 |
+
B_cal_prime = set()
|
| 279 |
+
T_cal_prime = {}
|
| 280 |
+
|
| 281 |
+
reachable = [V_plus]
|
| 282 |
+
marked = set(reachable)
|
| 283 |
+
idx = 0
|
| 284 |
+
while idx < len(reachable):
|
| 285 |
+
pop = reachable[idx]
|
| 286 |
+
idx += 1
|
| 287 |
+
|
| 288 |
+
B_cal_prime.add(pop)
|
| 289 |
+
|
| 290 |
+
# No need to check for excluded_colors here because
|
| 291 |
+
# they only exclude colors from A_cal
|
| 292 |
+
next_layer = [
|
| 293 |
+
k
|
| 294 |
+
for k in C
|
| 295 |
+
if H[(pop, k)] > 0 and k not in B_cal_prime and k not in marked
|
| 296 |
+
]
|
| 297 |
+
|
| 298 |
+
for dst in next_layer:
|
| 299 |
+
T_cal_prime[pop] = dst
|
| 300 |
+
|
| 301 |
+
marked.update(next_layer)
|
| 302 |
+
reachable.extend(next_layer)
|
| 303 |
+
|
| 304 |
+
# Construct the independent set of G[B']
|
| 305 |
+
I_set = set()
|
| 306 |
+
I_covered = set()
|
| 307 |
+
W_covering = {}
|
| 308 |
+
|
| 309 |
+
B_prime = [node for k in B_cal_prime for node in C[k]]
|
| 310 |
+
|
| 311 |
+
# Add the nodes in V_plus to I first.
|
| 312 |
+
for z in C[V_plus] + B_prime:
|
| 313 |
+
if z in I_covered or F[z] not in B_cal_prime:
|
| 314 |
+
continue
|
| 315 |
+
|
| 316 |
+
I_set.add(z)
|
| 317 |
+
I_covered.add(z)
|
| 318 |
+
I_covered.update(list(L[z]))
|
| 319 |
+
|
| 320 |
+
for w in L[z]:
|
| 321 |
+
if F[w] in A_cal_0 and N[(z, F[w])] == 1:
|
| 322 |
+
if w not in W_covering:
|
| 323 |
+
W_covering[w] = z
|
| 324 |
+
else:
|
| 325 |
+
# Found z1, z2 which have the same solo
|
| 326 |
+
# neighbor in some W
|
| 327 |
+
z_1 = W_covering[w]
|
| 328 |
+
# z_2 = z
|
| 329 |
+
|
| 330 |
+
Z = F[z_1]
|
| 331 |
+
W = F[w]
|
| 332 |
+
|
| 333 |
+
# shift nodes along W, V-
|
| 334 |
+
move_witnesses(
|
| 335 |
+
W, V_minus, N=N, H=H, F=F, C=C, T_cal=T_cal, L=L
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
# shift nodes along V+ to Z
|
| 339 |
+
move_witnesses(
|
| 340 |
+
V_plus,
|
| 341 |
+
Z,
|
| 342 |
+
N=N,
|
| 343 |
+
H=H,
|
| 344 |
+
F=F,
|
| 345 |
+
C=C,
|
| 346 |
+
T_cal=T_cal_prime,
|
| 347 |
+
L=L,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
# change color of z_1 to W
|
| 351 |
+
change_color(z_1, Z, W, N=N, H=H, F=F, C=C, L=L)
|
| 352 |
+
|
| 353 |
+
# change color of w to some color in B_cal
|
| 354 |
+
W_plus = next(
|
| 355 |
+
k for k in C if N[(w, k)] == 0 and k not in A_cal
|
| 356 |
+
)
|
| 357 |
+
change_color(w, W, W_plus, N=N, H=H, F=F, C=C, L=L)
|
| 358 |
+
|
| 359 |
+
# recurse with G[B \cup W*]
|
| 360 |
+
excluded_colors.update(
|
| 361 |
+
[k for k in C if k != W and k not in B_cal_prime]
|
| 362 |
+
)
|
| 363 |
+
procedure_P(
|
| 364 |
+
V_minus=W,
|
| 365 |
+
V_plus=W_plus,
|
| 366 |
+
N=N,
|
| 367 |
+
H=H,
|
| 368 |
+
C=C,
|
| 369 |
+
F=F,
|
| 370 |
+
L=L,
|
| 371 |
+
excluded_colors=excluded_colors,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
made_equitable = True
|
| 375 |
+
break
|
| 376 |
+
|
| 377 |
+
if made_equitable:
|
| 378 |
+
break
|
| 379 |
+
else:
|
| 380 |
+
assert False, (
|
| 381 |
+
"Must find a w which is the solo neighbor "
|
| 382 |
+
"of two vertices in B_cal_prime."
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
if made_equitable:
|
| 386 |
+
break
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
@nx._dispatchable
|
| 390 |
+
def equitable_color(G, num_colors):
|
| 391 |
+
"""Provides an equitable coloring for nodes of `G`.
|
| 392 |
+
|
| 393 |
+
Attempts to color a graph using `num_colors` colors, where no neighbors of
|
| 394 |
+
a node can have same color as the node itself and the number of nodes with
|
| 395 |
+
each color differ by at most 1. `num_colors` must be greater than the
|
| 396 |
+
maximum degree of `G`. The algorithm is described in [1]_ and has
|
| 397 |
+
complexity O(num_colors * n**2).
|
| 398 |
+
|
| 399 |
+
Parameters
|
| 400 |
+
----------
|
| 401 |
+
G : networkX graph
|
| 402 |
+
The nodes of this graph will be colored.
|
| 403 |
+
|
| 404 |
+
num_colors : number of colors to use
|
| 405 |
+
This number must be at least one more than the maximum degree of nodes
|
| 406 |
+
in the graph.
|
| 407 |
+
|
| 408 |
+
Returns
|
| 409 |
+
-------
|
| 410 |
+
A dictionary with keys representing nodes and values representing
|
| 411 |
+
corresponding coloring.
|
| 412 |
+
|
| 413 |
+
Examples
|
| 414 |
+
--------
|
| 415 |
+
>>> G = nx.cycle_graph(4)
|
| 416 |
+
>>> nx.coloring.equitable_color(G, num_colors=3) # doctest: +SKIP
|
| 417 |
+
{0: 2, 1: 1, 2: 2, 3: 0}
|
| 418 |
+
|
| 419 |
+
Raises
|
| 420 |
+
------
|
| 421 |
+
NetworkXAlgorithmError
|
| 422 |
+
If `num_colors` is not at least the maximum degree of the graph `G`
|
| 423 |
+
|
| 424 |
+
References
|
| 425 |
+
----------
|
| 426 |
+
.. [1] Kierstead, H. A., Kostochka, A. V., Mydlarz, M., & Szemerédi, E.
|
| 427 |
+
(2010). A fast algorithm for equitable coloring. Combinatorica, 30(2),
|
| 428 |
+
217-224.
|
| 429 |
+
"""
|
| 430 |
+
|
| 431 |
+
# Map nodes to integers for simplicity later.
|
| 432 |
+
nodes_to_int = {}
|
| 433 |
+
int_to_nodes = {}
|
| 434 |
+
|
| 435 |
+
for idx, node in enumerate(G.nodes):
|
| 436 |
+
nodes_to_int[node] = idx
|
| 437 |
+
int_to_nodes[idx] = node
|
| 438 |
+
|
| 439 |
+
G = nx.relabel_nodes(G, nodes_to_int, copy=True)
|
| 440 |
+
|
| 441 |
+
# Basic graph statistics and sanity check.
|
| 442 |
+
if len(G.nodes) > 0:
|
| 443 |
+
r_ = max(G.degree(node) for node in G.nodes)
|
| 444 |
+
else:
|
| 445 |
+
r_ = 0
|
| 446 |
+
|
| 447 |
+
if r_ >= num_colors:
|
| 448 |
+
raise nx.NetworkXAlgorithmError(
|
| 449 |
+
f"Graph has maximum degree {r_}, needs "
|
| 450 |
+
f"{r_ + 1} (> {num_colors}) colors for guaranteed coloring."
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
# Ensure that the number of nodes in G is a multiple of (r + 1)
|
| 454 |
+
pad_graph(G, num_colors)
|
| 455 |
+
|
| 456 |
+
# Starting the algorithm.
|
| 457 |
+
# L = {node: list(G.neighbors(node)) for node in G.nodes}
|
| 458 |
+
L_ = {node: [] for node in G.nodes}
|
| 459 |
+
|
| 460 |
+
# Arbitrary equitable allocation of colors to nodes.
|
| 461 |
+
F = {node: idx % num_colors for idx, node in enumerate(G.nodes)}
|
| 462 |
+
|
| 463 |
+
C = make_C_from_F(F)
|
| 464 |
+
|
| 465 |
+
# The neighborhood is empty initially.
|
| 466 |
+
N = make_N_from_L_C(L_, C)
|
| 467 |
+
|
| 468 |
+
# Currently all nodes witness all edges.
|
| 469 |
+
H = make_H_from_C_N(C, N)
|
| 470 |
+
|
| 471 |
+
# Start of algorithm.
|
| 472 |
+
edges_seen = set()
|
| 473 |
+
|
| 474 |
+
for u in sorted(G.nodes):
|
| 475 |
+
for v in sorted(G.neighbors(u)):
|
| 476 |
+
# Do not double count edges if (v, u) has already been seen.
|
| 477 |
+
if (v, u) in edges_seen:
|
| 478 |
+
continue
|
| 479 |
+
|
| 480 |
+
edges_seen.add((u, v))
|
| 481 |
+
|
| 482 |
+
L_[u].append(v)
|
| 483 |
+
L_[v].append(u)
|
| 484 |
+
|
| 485 |
+
N[(u, F[v])] += 1
|
| 486 |
+
N[(v, F[u])] += 1
|
| 487 |
+
|
| 488 |
+
if F[u] != F[v]:
|
| 489 |
+
# Were 'u' and 'v' witnesses for F[u] -> F[v] or F[v] -> F[u]?
|
| 490 |
+
if N[(u, F[v])] == 1:
|
| 491 |
+
H[F[u], F[v]] -= 1 # u cannot witness an edge between F[u], F[v]
|
| 492 |
+
|
| 493 |
+
if N[(v, F[u])] == 1:
|
| 494 |
+
H[F[v], F[u]] -= 1 # v cannot witness an edge between F[v], F[u]
|
| 495 |
+
|
| 496 |
+
if N[(u, F[u])] != 0:
|
| 497 |
+
# Find the first color where 'u' does not have any neighbors.
|
| 498 |
+
Y = next(k for k in C if N[(u, k)] == 0)
|
| 499 |
+
X = F[u]
|
| 500 |
+
change_color(u, X, Y, N=N, H=H, F=F, C=C, L=L_)
|
| 501 |
+
|
| 502 |
+
# Procedure P
|
| 503 |
+
procedure_P(V_minus=X, V_plus=Y, N=N, H=H, F=F, C=C, L=L_)
|
| 504 |
+
|
| 505 |
+
return {int_to_nodes[x]: F[x] for x in int_to_nodes}
|
.venv/lib/python3.11/site-packages/networkx/algorithms/coloring/greedy_coloring.py
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Greedy graph coloring using various strategies.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import itertools
|
| 6 |
+
from collections import defaultdict, deque
|
| 7 |
+
|
| 8 |
+
import networkx as nx
|
| 9 |
+
from networkx.utils import arbitrary_element, py_random_state
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"greedy_color",
|
| 13 |
+
"strategy_connected_sequential",
|
| 14 |
+
"strategy_connected_sequential_bfs",
|
| 15 |
+
"strategy_connected_sequential_dfs",
|
| 16 |
+
"strategy_independent_set",
|
| 17 |
+
"strategy_largest_first",
|
| 18 |
+
"strategy_random_sequential",
|
| 19 |
+
"strategy_saturation_largest_first",
|
| 20 |
+
"strategy_smallest_last",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def strategy_largest_first(G, colors):
|
| 25 |
+
"""Returns a list of the nodes of ``G`` in decreasing order by
|
| 26 |
+
degree.
|
| 27 |
+
|
| 28 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 29 |
+
|
| 30 |
+
"""
|
| 31 |
+
return sorted(G, key=G.degree, reverse=True)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@py_random_state(2)
|
| 35 |
+
def strategy_random_sequential(G, colors, seed=None):
|
| 36 |
+
"""Returns a random permutation of the nodes of ``G`` as a list.
|
| 37 |
+
|
| 38 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 39 |
+
|
| 40 |
+
seed : integer, random_state, or None (default)
|
| 41 |
+
Indicator of random number generation state.
|
| 42 |
+
See :ref:`Randomness<randomness>`.
|
| 43 |
+
"""
|
| 44 |
+
nodes = list(G)
|
| 45 |
+
seed.shuffle(nodes)
|
| 46 |
+
return nodes
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def strategy_smallest_last(G, colors):
|
| 50 |
+
"""Returns a deque of the nodes of ``G``, "smallest" last.
|
| 51 |
+
|
| 52 |
+
Specifically, the degrees of each node are tracked in a bucket queue.
|
| 53 |
+
From this, the node of minimum degree is repeatedly popped from the
|
| 54 |
+
graph, updating its neighbors' degrees.
|
| 55 |
+
|
| 56 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 57 |
+
|
| 58 |
+
This implementation of the strategy runs in $O(n + m)$ time
|
| 59 |
+
(ignoring polylogarithmic factors), where $n$ is the number of nodes
|
| 60 |
+
and $m$ is the number of edges.
|
| 61 |
+
|
| 62 |
+
This strategy is related to :func:`strategy_independent_set`: if we
|
| 63 |
+
interpret each node removed as an independent set of size one, then
|
| 64 |
+
this strategy chooses an independent set of size one instead of a
|
| 65 |
+
maximal independent set.
|
| 66 |
+
|
| 67 |
+
"""
|
| 68 |
+
H = G.copy()
|
| 69 |
+
result = deque()
|
| 70 |
+
|
| 71 |
+
# Build initial degree list (i.e. the bucket queue data structure)
|
| 72 |
+
degrees = defaultdict(set) # set(), for fast random-access removals
|
| 73 |
+
lbound = float("inf")
|
| 74 |
+
for node, d in H.degree():
|
| 75 |
+
degrees[d].add(node)
|
| 76 |
+
lbound = min(lbound, d) # Lower bound on min-degree.
|
| 77 |
+
|
| 78 |
+
def find_min_degree():
|
| 79 |
+
# Save time by starting the iterator at `lbound`, not 0.
|
| 80 |
+
# The value that we find will be our new `lbound`, which we set later.
|
| 81 |
+
return next(d for d in itertools.count(lbound) if d in degrees)
|
| 82 |
+
|
| 83 |
+
for _ in G:
|
| 84 |
+
# Pop a min-degree node and add it to the list.
|
| 85 |
+
min_degree = find_min_degree()
|
| 86 |
+
u = degrees[min_degree].pop()
|
| 87 |
+
if not degrees[min_degree]: # Clean up the degree list.
|
| 88 |
+
del degrees[min_degree]
|
| 89 |
+
result.appendleft(u)
|
| 90 |
+
|
| 91 |
+
# Update degrees of removed node's neighbors.
|
| 92 |
+
for v in H[u]:
|
| 93 |
+
degree = H.degree(v)
|
| 94 |
+
degrees[degree].remove(v)
|
| 95 |
+
if not degrees[degree]: # Clean up the degree list.
|
| 96 |
+
del degrees[degree]
|
| 97 |
+
degrees[degree - 1].add(v)
|
| 98 |
+
|
| 99 |
+
# Finally, remove the node.
|
| 100 |
+
H.remove_node(u)
|
| 101 |
+
lbound = min_degree - 1 # Subtract 1 in case of tied neighbors.
|
| 102 |
+
|
| 103 |
+
return result
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _maximal_independent_set(G):
|
| 107 |
+
"""Returns a maximal independent set of nodes in ``G`` by repeatedly
|
| 108 |
+
choosing an independent node of minimum degree (with respect to the
|
| 109 |
+
subgraph of unchosen nodes).
|
| 110 |
+
|
| 111 |
+
"""
|
| 112 |
+
result = set()
|
| 113 |
+
remaining = set(G)
|
| 114 |
+
while remaining:
|
| 115 |
+
G = G.subgraph(remaining)
|
| 116 |
+
v = min(remaining, key=G.degree)
|
| 117 |
+
result.add(v)
|
| 118 |
+
remaining -= set(G[v]) | {v}
|
| 119 |
+
return result
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def strategy_independent_set(G, colors):
|
| 123 |
+
"""Uses a greedy independent set removal strategy to determine the
|
| 124 |
+
colors.
|
| 125 |
+
|
| 126 |
+
This function updates ``colors`` **in-place** and return ``None``,
|
| 127 |
+
unlike the other strategy functions in this module.
|
| 128 |
+
|
| 129 |
+
This algorithm repeatedly finds and removes a maximal independent
|
| 130 |
+
set, assigning each node in the set an unused color.
|
| 131 |
+
|
| 132 |
+
``G`` is a NetworkX graph.
|
| 133 |
+
|
| 134 |
+
This strategy is related to :func:`strategy_smallest_last`: in that
|
| 135 |
+
strategy, an independent set of size one is chosen at each step
|
| 136 |
+
instead of a maximal independent set.
|
| 137 |
+
|
| 138 |
+
"""
|
| 139 |
+
remaining_nodes = set(G)
|
| 140 |
+
while len(remaining_nodes) > 0:
|
| 141 |
+
nodes = _maximal_independent_set(G.subgraph(remaining_nodes))
|
| 142 |
+
remaining_nodes -= nodes
|
| 143 |
+
yield from nodes
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def strategy_connected_sequential_bfs(G, colors):
|
| 147 |
+
"""Returns an iterable over nodes in ``G`` in the order given by a
|
| 148 |
+
breadth-first traversal.
|
| 149 |
+
|
| 150 |
+
The generated sequence has the property that for each node except
|
| 151 |
+
the first, at least one neighbor appeared earlier in the sequence.
|
| 152 |
+
|
| 153 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 154 |
+
|
| 155 |
+
"""
|
| 156 |
+
return strategy_connected_sequential(G, colors, "bfs")
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def strategy_connected_sequential_dfs(G, colors):
|
| 160 |
+
"""Returns an iterable over nodes in ``G`` in the order given by a
|
| 161 |
+
depth-first traversal.
|
| 162 |
+
|
| 163 |
+
The generated sequence has the property that for each node except
|
| 164 |
+
the first, at least one neighbor appeared earlier in the sequence.
|
| 165 |
+
|
| 166 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 167 |
+
|
| 168 |
+
"""
|
| 169 |
+
return strategy_connected_sequential(G, colors, "dfs")
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def strategy_connected_sequential(G, colors, traversal="bfs"):
|
| 173 |
+
"""Returns an iterable over nodes in ``G`` in the order given by a
|
| 174 |
+
breadth-first or depth-first traversal.
|
| 175 |
+
|
| 176 |
+
``traversal`` must be one of the strings ``'dfs'`` or ``'bfs'``,
|
| 177 |
+
representing depth-first traversal or breadth-first traversal,
|
| 178 |
+
respectively.
|
| 179 |
+
|
| 180 |
+
The generated sequence has the property that for each node except
|
| 181 |
+
the first, at least one neighbor appeared earlier in the sequence.
|
| 182 |
+
|
| 183 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 184 |
+
|
| 185 |
+
"""
|
| 186 |
+
if traversal == "bfs":
|
| 187 |
+
traverse = nx.bfs_edges
|
| 188 |
+
elif traversal == "dfs":
|
| 189 |
+
traverse = nx.dfs_edges
|
| 190 |
+
else:
|
| 191 |
+
raise nx.NetworkXError(
|
| 192 |
+
"Please specify one of the strings 'bfs' or"
|
| 193 |
+
" 'dfs' for connected sequential ordering"
|
| 194 |
+
)
|
| 195 |
+
for component in nx.connected_components(G):
|
| 196 |
+
source = arbitrary_element(component)
|
| 197 |
+
# Yield the source node, then all the nodes in the specified
|
| 198 |
+
# traversal order.
|
| 199 |
+
yield source
|
| 200 |
+
for _, end in traverse(G.subgraph(component), source):
|
| 201 |
+
yield end
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def strategy_saturation_largest_first(G, colors):
|
| 205 |
+
"""Iterates over all the nodes of ``G`` in "saturation order" (also
|
| 206 |
+
known as "DSATUR").
|
| 207 |
+
|
| 208 |
+
``G`` is a NetworkX graph. ``colors`` is a dictionary mapping nodes of
|
| 209 |
+
``G`` to colors, for those nodes that have already been colored.
|
| 210 |
+
|
| 211 |
+
"""
|
| 212 |
+
distinct_colors = {v: set() for v in G}
|
| 213 |
+
|
| 214 |
+
# Add the node color assignments given in colors to the
|
| 215 |
+
# distinct colors set for each neighbor of that node
|
| 216 |
+
for node, color in colors.items():
|
| 217 |
+
for neighbor in G[node]:
|
| 218 |
+
distinct_colors[neighbor].add(color)
|
| 219 |
+
|
| 220 |
+
# Check that the color assignments in colors are valid
|
| 221 |
+
# i.e. no neighboring nodes have the same color
|
| 222 |
+
if len(colors) >= 2:
|
| 223 |
+
for node, color in colors.items():
|
| 224 |
+
if color in distinct_colors[node]:
|
| 225 |
+
raise nx.NetworkXError("Neighboring nodes must have different colors")
|
| 226 |
+
|
| 227 |
+
# If 0 nodes have been colored, simply choose the node of highest degree.
|
| 228 |
+
if not colors:
|
| 229 |
+
node = max(G, key=G.degree)
|
| 230 |
+
yield node
|
| 231 |
+
# Add the color 0 to the distinct colors set for each
|
| 232 |
+
# neighbor of that node.
|
| 233 |
+
for v in G[node]:
|
| 234 |
+
distinct_colors[v].add(0)
|
| 235 |
+
|
| 236 |
+
while len(G) != len(colors):
|
| 237 |
+
# Update the distinct color sets for the neighbors.
|
| 238 |
+
for node, color in colors.items():
|
| 239 |
+
for neighbor in G[node]:
|
| 240 |
+
distinct_colors[neighbor].add(color)
|
| 241 |
+
|
| 242 |
+
# Compute the maximum saturation and the set of nodes that
|
| 243 |
+
# achieve that saturation.
|
| 244 |
+
saturation = {v: len(c) for v, c in distinct_colors.items() if v not in colors}
|
| 245 |
+
# Yield the node with the highest saturation, and break ties by
|
| 246 |
+
# degree.
|
| 247 |
+
node = max(saturation, key=lambda v: (saturation[v], G.degree(v)))
|
| 248 |
+
yield node
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
#: Dictionary mapping name of a strategy as a string to the strategy function.
|
| 252 |
+
STRATEGIES = {
|
| 253 |
+
"largest_first": strategy_largest_first,
|
| 254 |
+
"random_sequential": strategy_random_sequential,
|
| 255 |
+
"smallest_last": strategy_smallest_last,
|
| 256 |
+
"independent_set": strategy_independent_set,
|
| 257 |
+
"connected_sequential_bfs": strategy_connected_sequential_bfs,
|
| 258 |
+
"connected_sequential_dfs": strategy_connected_sequential_dfs,
|
| 259 |
+
"connected_sequential": strategy_connected_sequential,
|
| 260 |
+
"saturation_largest_first": strategy_saturation_largest_first,
|
| 261 |
+
"DSATUR": strategy_saturation_largest_first,
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@nx._dispatchable
|
| 266 |
+
def greedy_color(G, strategy="largest_first", interchange=False):
|
| 267 |
+
"""Color a graph using various strategies of greedy graph coloring.
|
| 268 |
+
|
| 269 |
+
Attempts to color a graph using as few colors as possible, where no
|
| 270 |
+
neighbors of a node can have same color as the node itself. The
|
| 271 |
+
given strategy determines the order in which nodes are colored.
|
| 272 |
+
|
| 273 |
+
The strategies are described in [1]_, and smallest-last is based on
|
| 274 |
+
[2]_.
|
| 275 |
+
|
| 276 |
+
Parameters
|
| 277 |
+
----------
|
| 278 |
+
G : NetworkX graph
|
| 279 |
+
|
| 280 |
+
strategy : string or function(G, colors)
|
| 281 |
+
A function (or a string representing a function) that provides
|
| 282 |
+
the coloring strategy, by returning nodes in the ordering they
|
| 283 |
+
should be colored. ``G`` is the graph, and ``colors`` is a
|
| 284 |
+
dictionary of the currently assigned colors, keyed by nodes. The
|
| 285 |
+
function must return an iterable over all the nodes in ``G``.
|
| 286 |
+
|
| 287 |
+
If the strategy function is an iterator generator (that is, a
|
| 288 |
+
function with ``yield`` statements), keep in mind that the
|
| 289 |
+
``colors`` dictionary will be updated after each ``yield``, since
|
| 290 |
+
this function chooses colors greedily.
|
| 291 |
+
|
| 292 |
+
If ``strategy`` is a string, it must be one of the following,
|
| 293 |
+
each of which represents one of the built-in strategy functions.
|
| 294 |
+
|
| 295 |
+
* ``'largest_first'``
|
| 296 |
+
* ``'random_sequential'``
|
| 297 |
+
* ``'smallest_last'``
|
| 298 |
+
* ``'independent_set'``
|
| 299 |
+
* ``'connected_sequential_bfs'``
|
| 300 |
+
* ``'connected_sequential_dfs'``
|
| 301 |
+
* ``'connected_sequential'`` (alias for the previous strategy)
|
| 302 |
+
* ``'saturation_largest_first'``
|
| 303 |
+
* ``'DSATUR'`` (alias for the previous strategy)
|
| 304 |
+
|
| 305 |
+
interchange: bool
|
| 306 |
+
Will use the color interchange algorithm described by [3]_ if set
|
| 307 |
+
to ``True``.
|
| 308 |
+
|
| 309 |
+
Note that ``saturation_largest_first`` and ``independent_set``
|
| 310 |
+
do not work with interchange. Furthermore, if you use
|
| 311 |
+
interchange with your own strategy function, you cannot rely
|
| 312 |
+
on the values in the ``colors`` argument.
|
| 313 |
+
|
| 314 |
+
Returns
|
| 315 |
+
-------
|
| 316 |
+
A dictionary with keys representing nodes and values representing
|
| 317 |
+
corresponding coloring.
|
| 318 |
+
|
| 319 |
+
Examples
|
| 320 |
+
--------
|
| 321 |
+
>>> G = nx.cycle_graph(4)
|
| 322 |
+
>>> d = nx.coloring.greedy_color(G, strategy="largest_first")
|
| 323 |
+
>>> d in [{0: 0, 1: 1, 2: 0, 3: 1}, {0: 1, 1: 0, 2: 1, 3: 0}]
|
| 324 |
+
True
|
| 325 |
+
|
| 326 |
+
Raises
|
| 327 |
+
------
|
| 328 |
+
NetworkXPointlessConcept
|
| 329 |
+
If ``strategy`` is ``saturation_largest_first`` or
|
| 330 |
+
``independent_set`` and ``interchange`` is ``True``.
|
| 331 |
+
|
| 332 |
+
References
|
| 333 |
+
----------
|
| 334 |
+
.. [1] Adrian Kosowski, and Krzysztof Manuszewski,
|
| 335 |
+
Classical Coloring of Graphs, Graph Colorings, 2-19, 2004.
|
| 336 |
+
ISBN 0-8218-3458-4.
|
| 337 |
+
.. [2] David W. Matula, and Leland L. Beck, "Smallest-last
|
| 338 |
+
ordering and clustering and graph coloring algorithms." *J. ACM* 30,
|
| 339 |
+
3 (July 1983), 417–427. <https://doi.org/10.1145/2402.322385>
|
| 340 |
+
.. [3] Maciej M. Sysło, Narsingh Deo, Janusz S. Kowalik,
|
| 341 |
+
Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
|
| 342 |
+
ISBN 0-486-45353-7.
|
| 343 |
+
|
| 344 |
+
"""
|
| 345 |
+
if len(G) == 0:
|
| 346 |
+
return {}
|
| 347 |
+
# Determine the strategy provided by the caller.
|
| 348 |
+
strategy = STRATEGIES.get(strategy, strategy)
|
| 349 |
+
if not callable(strategy):
|
| 350 |
+
raise nx.NetworkXError(
|
| 351 |
+
f"strategy must be callable or a valid string. {strategy} not valid."
|
| 352 |
+
)
|
| 353 |
+
# Perform some validation on the arguments before executing any
|
| 354 |
+
# strategy functions.
|
| 355 |
+
if interchange:
|
| 356 |
+
if strategy is strategy_independent_set:
|
| 357 |
+
msg = "interchange cannot be used with independent_set"
|
| 358 |
+
raise nx.NetworkXPointlessConcept(msg)
|
| 359 |
+
if strategy is strategy_saturation_largest_first:
|
| 360 |
+
msg = "interchange cannot be used with saturation_largest_first"
|
| 361 |
+
raise nx.NetworkXPointlessConcept(msg)
|
| 362 |
+
colors = {}
|
| 363 |
+
nodes = strategy(G, colors)
|
| 364 |
+
if interchange:
|
| 365 |
+
return _greedy_coloring_with_interchange(G, nodes)
|
| 366 |
+
for u in nodes:
|
| 367 |
+
# Set to keep track of colors of neighbors
|
| 368 |
+
nbr_colors = {colors[v] for v in G[u] if v in colors}
|
| 369 |
+
# Find the first unused color.
|
| 370 |
+
for color in itertools.count():
|
| 371 |
+
if color not in nbr_colors:
|
| 372 |
+
break
|
| 373 |
+
# Assign the new color to the current node.
|
| 374 |
+
colors[u] = color
|
| 375 |
+
return colors
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
# Tools for coloring with interchanges
|
| 379 |
+
class _Node:
|
| 380 |
+
__slots__ = ["node_id", "color", "adj_list", "adj_color"]
|
| 381 |
+
|
| 382 |
+
def __init__(self, node_id, n):
|
| 383 |
+
self.node_id = node_id
|
| 384 |
+
self.color = -1
|
| 385 |
+
self.adj_list = None
|
| 386 |
+
self.adj_color = [None for _ in range(n)]
|
| 387 |
+
|
| 388 |
+
def __repr__(self):
|
| 389 |
+
return (
|
| 390 |
+
f"Node_id: {self.node_id}, Color: {self.color}, "
|
| 391 |
+
f"Adj_list: ({self.adj_list}), adj_color: ({self.adj_color})"
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
def assign_color(self, adj_entry, color):
|
| 395 |
+
adj_entry.col_prev = None
|
| 396 |
+
adj_entry.col_next = self.adj_color[color]
|
| 397 |
+
self.adj_color[color] = adj_entry
|
| 398 |
+
if adj_entry.col_next is not None:
|
| 399 |
+
adj_entry.col_next.col_prev = adj_entry
|
| 400 |
+
|
| 401 |
+
def clear_color(self, adj_entry, color):
|
| 402 |
+
if adj_entry.col_prev is None:
|
| 403 |
+
self.adj_color[color] = adj_entry.col_next
|
| 404 |
+
else:
|
| 405 |
+
adj_entry.col_prev.col_next = adj_entry.col_next
|
| 406 |
+
if adj_entry.col_next is not None:
|
| 407 |
+
adj_entry.col_next.col_prev = adj_entry.col_prev
|
| 408 |
+
|
| 409 |
+
def iter_neighbors(self):
|
| 410 |
+
adj_node = self.adj_list
|
| 411 |
+
while adj_node is not None:
|
| 412 |
+
yield adj_node
|
| 413 |
+
adj_node = adj_node.next
|
| 414 |
+
|
| 415 |
+
def iter_neighbors_color(self, color):
|
| 416 |
+
adj_color_node = self.adj_color[color]
|
| 417 |
+
while adj_color_node is not None:
|
| 418 |
+
yield adj_color_node.node_id
|
| 419 |
+
adj_color_node = adj_color_node.col_next
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
class _AdjEntry:
|
| 423 |
+
__slots__ = ["node_id", "next", "mate", "col_next", "col_prev"]
|
| 424 |
+
|
| 425 |
+
def __init__(self, node_id):
|
| 426 |
+
self.node_id = node_id
|
| 427 |
+
self.next = None
|
| 428 |
+
self.mate = None
|
| 429 |
+
self.col_next = None
|
| 430 |
+
self.col_prev = None
|
| 431 |
+
|
| 432 |
+
def __repr__(self):
|
| 433 |
+
col_next = None if self.col_next is None else self.col_next.node_id
|
| 434 |
+
col_prev = None if self.col_prev is None else self.col_prev.node_id
|
| 435 |
+
return (
|
| 436 |
+
f"Node_id: {self.node_id}, Next: ({self.next}), "
|
| 437 |
+
f"Mate: ({self.mate.node_id}), "
|
| 438 |
+
f"col_next: ({col_next}), col_prev: ({col_prev})"
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def _greedy_coloring_with_interchange(G, nodes):
|
| 443 |
+
"""Return a coloring for `original_graph` using interchange approach
|
| 444 |
+
|
| 445 |
+
This procedure is an adaption of the algorithm described by [1]_,
|
| 446 |
+
and is an implementation of coloring with interchange. Please be
|
| 447 |
+
advised, that the datastructures used are rather complex because
|
| 448 |
+
they are optimized to minimize the time spent identifying
|
| 449 |
+
subcomponents of the graph, which are possible candidates for color
|
| 450 |
+
interchange.
|
| 451 |
+
|
| 452 |
+
Parameters
|
| 453 |
+
----------
|
| 454 |
+
G : NetworkX graph
|
| 455 |
+
The graph to be colored
|
| 456 |
+
|
| 457 |
+
nodes : list
|
| 458 |
+
nodes ordered using the strategy of choice
|
| 459 |
+
|
| 460 |
+
Returns
|
| 461 |
+
-------
|
| 462 |
+
dict :
|
| 463 |
+
A dictionary keyed by node to a color value
|
| 464 |
+
|
| 465 |
+
References
|
| 466 |
+
----------
|
| 467 |
+
.. [1] Maciej M. Syslo, Narsingh Deo, Janusz S. Kowalik,
|
| 468 |
+
Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
|
| 469 |
+
ISBN 0-486-45353-7.
|
| 470 |
+
"""
|
| 471 |
+
n = len(G)
|
| 472 |
+
|
| 473 |
+
graph = {node: _Node(node, n) for node in G}
|
| 474 |
+
|
| 475 |
+
for node1, node2 in G.edges():
|
| 476 |
+
adj_entry1 = _AdjEntry(node2)
|
| 477 |
+
adj_entry2 = _AdjEntry(node1)
|
| 478 |
+
adj_entry1.mate = adj_entry2
|
| 479 |
+
adj_entry2.mate = adj_entry1
|
| 480 |
+
node1_head = graph[node1].adj_list
|
| 481 |
+
adj_entry1.next = node1_head
|
| 482 |
+
graph[node1].adj_list = adj_entry1
|
| 483 |
+
node2_head = graph[node2].adj_list
|
| 484 |
+
adj_entry2.next = node2_head
|
| 485 |
+
graph[node2].adj_list = adj_entry2
|
| 486 |
+
|
| 487 |
+
k = 0
|
| 488 |
+
for node in nodes:
|
| 489 |
+
# Find the smallest possible, unused color
|
| 490 |
+
neighbors = graph[node].iter_neighbors()
|
| 491 |
+
col_used = {graph[adj_node.node_id].color for adj_node in neighbors}
|
| 492 |
+
col_used.discard(-1)
|
| 493 |
+
k1 = next(itertools.dropwhile(lambda x: x in col_used, itertools.count()))
|
| 494 |
+
|
| 495 |
+
# k1 is now the lowest available color
|
| 496 |
+
if k1 > k:
|
| 497 |
+
connected = True
|
| 498 |
+
visited = set()
|
| 499 |
+
col1 = -1
|
| 500 |
+
col2 = -1
|
| 501 |
+
while connected and col1 < k:
|
| 502 |
+
col1 += 1
|
| 503 |
+
neighbor_cols = graph[node].iter_neighbors_color(col1)
|
| 504 |
+
col1_adj = list(neighbor_cols)
|
| 505 |
+
|
| 506 |
+
col2 = col1
|
| 507 |
+
while connected and col2 < k:
|
| 508 |
+
col2 += 1
|
| 509 |
+
visited = set(col1_adj)
|
| 510 |
+
frontier = list(col1_adj)
|
| 511 |
+
i = 0
|
| 512 |
+
while i < len(frontier):
|
| 513 |
+
search_node = frontier[i]
|
| 514 |
+
i += 1
|
| 515 |
+
col_opp = col2 if graph[search_node].color == col1 else col1
|
| 516 |
+
neighbor_cols = graph[search_node].iter_neighbors_color(col_opp)
|
| 517 |
+
|
| 518 |
+
for neighbor in neighbor_cols:
|
| 519 |
+
if neighbor not in visited:
|
| 520 |
+
visited.add(neighbor)
|
| 521 |
+
frontier.append(neighbor)
|
| 522 |
+
|
| 523 |
+
# Search if node is not adj to any col2 vertex
|
| 524 |
+
connected = (
|
| 525 |
+
len(
|
| 526 |
+
visited.intersection(graph[node].iter_neighbors_color(col2))
|
| 527 |
+
)
|
| 528 |
+
> 0
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
# If connected is false then we can swap !!!
|
| 532 |
+
if not connected:
|
| 533 |
+
# Update all the nodes in the component
|
| 534 |
+
for search_node in visited:
|
| 535 |
+
graph[search_node].color = (
|
| 536 |
+
col2 if graph[search_node].color == col1 else col1
|
| 537 |
+
)
|
| 538 |
+
col2_adj = graph[search_node].adj_color[col2]
|
| 539 |
+
graph[search_node].adj_color[col2] = graph[search_node].adj_color[
|
| 540 |
+
col1
|
| 541 |
+
]
|
| 542 |
+
graph[search_node].adj_color[col1] = col2_adj
|
| 543 |
+
|
| 544 |
+
# Update all the neighboring nodes
|
| 545 |
+
for search_node in visited:
|
| 546 |
+
col = graph[search_node].color
|
| 547 |
+
col_opp = col1 if col == col2 else col2
|
| 548 |
+
for adj_node in graph[search_node].iter_neighbors():
|
| 549 |
+
if graph[adj_node.node_id].color != col_opp:
|
| 550 |
+
# Direct reference to entry
|
| 551 |
+
adj_mate = adj_node.mate
|
| 552 |
+
graph[adj_node.node_id].clear_color(adj_mate, col_opp)
|
| 553 |
+
graph[adj_node.node_id].assign_color(adj_mate, col)
|
| 554 |
+
k1 = col1
|
| 555 |
+
|
| 556 |
+
# We can color this node color k1
|
| 557 |
+
graph[node].color = k1
|
| 558 |
+
k = max(k1, k)
|
| 559 |
+
|
| 560 |
+
# Update the neighbors of this node
|
| 561 |
+
for adj_node in graph[node].iter_neighbors():
|
| 562 |
+
adj_mate = adj_node.mate
|
| 563 |
+
graph[adj_node.node_id].assign_color(adj_mate, k1)
|
| 564 |
+
|
| 565 |
+
return {node.node_id: node.color for node in graph.values()}
|
.venv/lib/python3.11/site-packages/networkx/algorithms/coloring/tests/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.11/site-packages/networkx/algorithms/coloring/tests/test_coloring.py
ADDED
|
@@ -0,0 +1,863 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Greedy coloring test suite."""
|
| 2 |
+
|
| 3 |
+
import itertools
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
|
| 9 |
+
is_coloring = nx.algorithms.coloring.equitable_coloring.is_coloring
|
| 10 |
+
is_equitable = nx.algorithms.coloring.equitable_coloring.is_equitable
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
ALL_STRATEGIES = [
|
| 14 |
+
"largest_first",
|
| 15 |
+
"random_sequential",
|
| 16 |
+
"smallest_last",
|
| 17 |
+
"independent_set",
|
| 18 |
+
"connected_sequential_bfs",
|
| 19 |
+
"connected_sequential_dfs",
|
| 20 |
+
"connected_sequential",
|
| 21 |
+
"saturation_largest_first",
|
| 22 |
+
"DSATUR",
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
# List of strategies where interchange=True results in an error
|
| 26 |
+
INTERCHANGE_INVALID = ["independent_set", "saturation_largest_first", "DSATUR"]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class TestColoring:
|
| 30 |
+
def test_basic_cases(self):
|
| 31 |
+
def check_basic_case(graph_func, n_nodes, strategy, interchange):
|
| 32 |
+
graph = graph_func()
|
| 33 |
+
coloring = nx.coloring.greedy_color(
|
| 34 |
+
graph, strategy=strategy, interchange=interchange
|
| 35 |
+
)
|
| 36 |
+
assert verify_length(coloring, n_nodes)
|
| 37 |
+
assert verify_coloring(graph, coloring)
|
| 38 |
+
|
| 39 |
+
for graph_func, n_nodes in BASIC_TEST_CASES.items():
|
| 40 |
+
for interchange in [True, False]:
|
| 41 |
+
for strategy in ALL_STRATEGIES:
|
| 42 |
+
check_basic_case(graph_func, n_nodes, strategy, False)
|
| 43 |
+
if strategy not in INTERCHANGE_INVALID:
|
| 44 |
+
check_basic_case(graph_func, n_nodes, strategy, True)
|
| 45 |
+
|
| 46 |
+
def test_special_cases(self):
|
| 47 |
+
def check_special_case(strategy, graph_func, interchange, colors):
|
| 48 |
+
graph = graph_func()
|
| 49 |
+
coloring = nx.coloring.greedy_color(
|
| 50 |
+
graph, strategy=strategy, interchange=interchange
|
| 51 |
+
)
|
| 52 |
+
if not hasattr(colors, "__len__"):
|
| 53 |
+
colors = [colors]
|
| 54 |
+
assert any(verify_length(coloring, n_colors) for n_colors in colors)
|
| 55 |
+
assert verify_coloring(graph, coloring)
|
| 56 |
+
|
| 57 |
+
for strategy, arglist in SPECIAL_TEST_CASES.items():
|
| 58 |
+
for args in arglist:
|
| 59 |
+
check_special_case(strategy, args[0], args[1], args[2])
|
| 60 |
+
|
| 61 |
+
def test_interchange_invalid(self):
|
| 62 |
+
graph = one_node_graph()
|
| 63 |
+
for strategy in INTERCHANGE_INVALID:
|
| 64 |
+
pytest.raises(
|
| 65 |
+
nx.NetworkXPointlessConcept,
|
| 66 |
+
nx.coloring.greedy_color,
|
| 67 |
+
graph,
|
| 68 |
+
strategy=strategy,
|
| 69 |
+
interchange=True,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
def test_bad_inputs(self):
|
| 73 |
+
graph = one_node_graph()
|
| 74 |
+
pytest.raises(
|
| 75 |
+
nx.NetworkXError,
|
| 76 |
+
nx.coloring.greedy_color,
|
| 77 |
+
graph,
|
| 78 |
+
strategy="invalid strategy",
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
def test_strategy_as_function(self):
|
| 82 |
+
graph = lf_shc()
|
| 83 |
+
colors_1 = nx.coloring.greedy_color(graph, "largest_first")
|
| 84 |
+
colors_2 = nx.coloring.greedy_color(graph, nx.coloring.strategy_largest_first)
|
| 85 |
+
assert colors_1 == colors_2
|
| 86 |
+
|
| 87 |
+
def test_seed_argument(self):
|
| 88 |
+
graph = lf_shc()
|
| 89 |
+
rs = nx.coloring.strategy_random_sequential
|
| 90 |
+
c1 = nx.coloring.greedy_color(graph, lambda g, c: rs(g, c, seed=1))
|
| 91 |
+
for u, v in graph.edges:
|
| 92 |
+
assert c1[u] != c1[v]
|
| 93 |
+
|
| 94 |
+
def test_is_coloring(self):
|
| 95 |
+
G = nx.Graph()
|
| 96 |
+
G.add_edges_from([(0, 1), (1, 2)])
|
| 97 |
+
coloring = {0: 0, 1: 1, 2: 0}
|
| 98 |
+
assert is_coloring(G, coloring)
|
| 99 |
+
|
| 100 |
+
coloring[0] = 1
|
| 101 |
+
assert not is_coloring(G, coloring)
|
| 102 |
+
assert not is_equitable(G, coloring)
|
| 103 |
+
|
| 104 |
+
def test_is_equitable(self):
|
| 105 |
+
G = nx.Graph()
|
| 106 |
+
G.add_edges_from([(0, 1), (1, 2)])
|
| 107 |
+
coloring = {0: 0, 1: 1, 2: 0}
|
| 108 |
+
assert is_equitable(G, coloring)
|
| 109 |
+
|
| 110 |
+
G.add_edges_from([(2, 3), (2, 4), (2, 5)])
|
| 111 |
+
coloring[3] = 1
|
| 112 |
+
coloring[4] = 1
|
| 113 |
+
coloring[5] = 1
|
| 114 |
+
assert is_coloring(G, coloring)
|
| 115 |
+
assert not is_equitable(G, coloring)
|
| 116 |
+
|
| 117 |
+
def test_num_colors(self):
|
| 118 |
+
G = nx.Graph()
|
| 119 |
+
G.add_edges_from([(0, 1), (0, 2), (0, 3)])
|
| 120 |
+
pytest.raises(nx.NetworkXAlgorithmError, nx.coloring.equitable_color, G, 2)
|
| 121 |
+
|
| 122 |
+
def test_equitable_color(self):
|
| 123 |
+
G = nx.fast_gnp_random_graph(n=10, p=0.2, seed=42)
|
| 124 |
+
coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
|
| 125 |
+
assert is_equitable(G, coloring)
|
| 126 |
+
|
| 127 |
+
def test_equitable_color_empty(self):
|
| 128 |
+
G = nx.empty_graph()
|
| 129 |
+
coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
|
| 130 |
+
assert is_equitable(G, coloring)
|
| 131 |
+
|
| 132 |
+
def test_equitable_color_large(self):
|
| 133 |
+
G = nx.fast_gnp_random_graph(100, 0.1, seed=42)
|
| 134 |
+
coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
|
| 135 |
+
assert is_equitable(G, coloring, num_colors=max_degree(G) + 1)
|
| 136 |
+
|
| 137 |
+
def test_case_V_plus_not_in_A_cal(self):
|
| 138 |
+
# Hand crafted case to avoid the easy case.
|
| 139 |
+
L = {
|
| 140 |
+
0: [2, 5],
|
| 141 |
+
1: [3, 4],
|
| 142 |
+
2: [0, 8],
|
| 143 |
+
3: [1, 7],
|
| 144 |
+
4: [1, 6],
|
| 145 |
+
5: [0, 6],
|
| 146 |
+
6: [4, 5],
|
| 147 |
+
7: [3],
|
| 148 |
+
8: [2],
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
F = {
|
| 152 |
+
# Color 0
|
| 153 |
+
0: 0,
|
| 154 |
+
1: 0,
|
| 155 |
+
# Color 1
|
| 156 |
+
2: 1,
|
| 157 |
+
3: 1,
|
| 158 |
+
4: 1,
|
| 159 |
+
5: 1,
|
| 160 |
+
# Color 2
|
| 161 |
+
6: 2,
|
| 162 |
+
7: 2,
|
| 163 |
+
8: 2,
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
|
| 167 |
+
N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
|
| 168 |
+
H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
|
| 169 |
+
|
| 170 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
| 171 |
+
V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L
|
| 172 |
+
)
|
| 173 |
+
check_state(L=L, N=N, H=H, F=F, C=C)
|
| 174 |
+
|
| 175 |
+
def test_cast_no_solo(self):
|
| 176 |
+
L = {
|
| 177 |
+
0: [8, 9],
|
| 178 |
+
1: [10, 11],
|
| 179 |
+
2: [8],
|
| 180 |
+
3: [9],
|
| 181 |
+
4: [10, 11],
|
| 182 |
+
5: [8],
|
| 183 |
+
6: [9],
|
| 184 |
+
7: [10, 11],
|
| 185 |
+
8: [0, 2, 5],
|
| 186 |
+
9: [0, 3, 6],
|
| 187 |
+
10: [1, 4, 7],
|
| 188 |
+
11: [1, 4, 7],
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
F = {0: 0, 1: 0, 2: 2, 3: 2, 4: 2, 5: 3, 6: 3, 7: 3, 8: 1, 9: 1, 10: 1, 11: 1}
|
| 192 |
+
|
| 193 |
+
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
|
| 194 |
+
N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
|
| 195 |
+
H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
|
| 196 |
+
|
| 197 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
| 198 |
+
V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L
|
| 199 |
+
)
|
| 200 |
+
check_state(L=L, N=N, H=H, F=F, C=C)
|
| 201 |
+
|
| 202 |
+
def test_hard_prob(self):
|
| 203 |
+
# Tests for two levels of recursion.
|
| 204 |
+
num_colors, s = 5, 5
|
| 205 |
+
|
| 206 |
+
G = nx.Graph()
|
| 207 |
+
G.add_edges_from(
|
| 208 |
+
[
|
| 209 |
+
(0, 10),
|
| 210 |
+
(0, 11),
|
| 211 |
+
(0, 12),
|
| 212 |
+
(0, 23),
|
| 213 |
+
(10, 4),
|
| 214 |
+
(10, 9),
|
| 215 |
+
(10, 20),
|
| 216 |
+
(11, 4),
|
| 217 |
+
(11, 8),
|
| 218 |
+
(11, 16),
|
| 219 |
+
(12, 9),
|
| 220 |
+
(12, 22),
|
| 221 |
+
(12, 23),
|
| 222 |
+
(23, 7),
|
| 223 |
+
(1, 17),
|
| 224 |
+
(1, 18),
|
| 225 |
+
(1, 19),
|
| 226 |
+
(1, 24),
|
| 227 |
+
(17, 5),
|
| 228 |
+
(17, 13),
|
| 229 |
+
(17, 22),
|
| 230 |
+
(18, 5),
|
| 231 |
+
(19, 5),
|
| 232 |
+
(19, 6),
|
| 233 |
+
(19, 8),
|
| 234 |
+
(24, 7),
|
| 235 |
+
(24, 16),
|
| 236 |
+
(2, 4),
|
| 237 |
+
(2, 13),
|
| 238 |
+
(2, 14),
|
| 239 |
+
(2, 15),
|
| 240 |
+
(4, 6),
|
| 241 |
+
(13, 5),
|
| 242 |
+
(13, 21),
|
| 243 |
+
(14, 6),
|
| 244 |
+
(14, 15),
|
| 245 |
+
(15, 6),
|
| 246 |
+
(15, 21),
|
| 247 |
+
(3, 16),
|
| 248 |
+
(3, 20),
|
| 249 |
+
(3, 21),
|
| 250 |
+
(3, 22),
|
| 251 |
+
(16, 8),
|
| 252 |
+
(20, 8),
|
| 253 |
+
(21, 9),
|
| 254 |
+
(22, 7),
|
| 255 |
+
]
|
| 256 |
+
)
|
| 257 |
+
F = {node: node // s for node in range(num_colors * s)}
|
| 258 |
+
F[s - 1] = num_colors - 1
|
| 259 |
+
|
| 260 |
+
params = make_params_from_graph(G=G, F=F)
|
| 261 |
+
|
| 262 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
| 263 |
+
V_minus=0, V_plus=num_colors - 1, **params
|
| 264 |
+
)
|
| 265 |
+
check_state(**params)
|
| 266 |
+
|
| 267 |
+
def test_hardest_prob(self):
|
| 268 |
+
# Tests for two levels of recursion.
|
| 269 |
+
num_colors, s = 10, 4
|
| 270 |
+
|
| 271 |
+
G = nx.Graph()
|
| 272 |
+
G.add_edges_from(
|
| 273 |
+
[
|
| 274 |
+
(0, 19),
|
| 275 |
+
(0, 24),
|
| 276 |
+
(0, 29),
|
| 277 |
+
(0, 30),
|
| 278 |
+
(0, 35),
|
| 279 |
+
(19, 3),
|
| 280 |
+
(19, 7),
|
| 281 |
+
(19, 9),
|
| 282 |
+
(19, 15),
|
| 283 |
+
(19, 21),
|
| 284 |
+
(19, 24),
|
| 285 |
+
(19, 30),
|
| 286 |
+
(19, 38),
|
| 287 |
+
(24, 5),
|
| 288 |
+
(24, 11),
|
| 289 |
+
(24, 13),
|
| 290 |
+
(24, 20),
|
| 291 |
+
(24, 30),
|
| 292 |
+
(24, 37),
|
| 293 |
+
(24, 38),
|
| 294 |
+
(29, 6),
|
| 295 |
+
(29, 10),
|
| 296 |
+
(29, 13),
|
| 297 |
+
(29, 15),
|
| 298 |
+
(29, 16),
|
| 299 |
+
(29, 17),
|
| 300 |
+
(29, 20),
|
| 301 |
+
(29, 26),
|
| 302 |
+
(30, 6),
|
| 303 |
+
(30, 10),
|
| 304 |
+
(30, 15),
|
| 305 |
+
(30, 22),
|
| 306 |
+
(30, 23),
|
| 307 |
+
(30, 39),
|
| 308 |
+
(35, 6),
|
| 309 |
+
(35, 9),
|
| 310 |
+
(35, 14),
|
| 311 |
+
(35, 18),
|
| 312 |
+
(35, 22),
|
| 313 |
+
(35, 23),
|
| 314 |
+
(35, 25),
|
| 315 |
+
(35, 27),
|
| 316 |
+
(1, 20),
|
| 317 |
+
(1, 26),
|
| 318 |
+
(1, 31),
|
| 319 |
+
(1, 34),
|
| 320 |
+
(1, 38),
|
| 321 |
+
(20, 4),
|
| 322 |
+
(20, 8),
|
| 323 |
+
(20, 14),
|
| 324 |
+
(20, 18),
|
| 325 |
+
(20, 28),
|
| 326 |
+
(20, 33),
|
| 327 |
+
(26, 7),
|
| 328 |
+
(26, 10),
|
| 329 |
+
(26, 14),
|
| 330 |
+
(26, 18),
|
| 331 |
+
(26, 21),
|
| 332 |
+
(26, 32),
|
| 333 |
+
(26, 39),
|
| 334 |
+
(31, 5),
|
| 335 |
+
(31, 8),
|
| 336 |
+
(31, 13),
|
| 337 |
+
(31, 16),
|
| 338 |
+
(31, 17),
|
| 339 |
+
(31, 21),
|
| 340 |
+
(31, 25),
|
| 341 |
+
(31, 27),
|
| 342 |
+
(34, 7),
|
| 343 |
+
(34, 8),
|
| 344 |
+
(34, 13),
|
| 345 |
+
(34, 18),
|
| 346 |
+
(34, 22),
|
| 347 |
+
(34, 23),
|
| 348 |
+
(34, 25),
|
| 349 |
+
(34, 27),
|
| 350 |
+
(38, 4),
|
| 351 |
+
(38, 9),
|
| 352 |
+
(38, 12),
|
| 353 |
+
(38, 14),
|
| 354 |
+
(38, 21),
|
| 355 |
+
(38, 27),
|
| 356 |
+
(2, 3),
|
| 357 |
+
(2, 18),
|
| 358 |
+
(2, 21),
|
| 359 |
+
(2, 28),
|
| 360 |
+
(2, 32),
|
| 361 |
+
(2, 33),
|
| 362 |
+
(2, 36),
|
| 363 |
+
(2, 37),
|
| 364 |
+
(2, 39),
|
| 365 |
+
(3, 5),
|
| 366 |
+
(3, 9),
|
| 367 |
+
(3, 13),
|
| 368 |
+
(3, 22),
|
| 369 |
+
(3, 23),
|
| 370 |
+
(3, 25),
|
| 371 |
+
(3, 27),
|
| 372 |
+
(18, 6),
|
| 373 |
+
(18, 11),
|
| 374 |
+
(18, 15),
|
| 375 |
+
(18, 39),
|
| 376 |
+
(21, 4),
|
| 377 |
+
(21, 10),
|
| 378 |
+
(21, 14),
|
| 379 |
+
(21, 36),
|
| 380 |
+
(28, 6),
|
| 381 |
+
(28, 10),
|
| 382 |
+
(28, 14),
|
| 383 |
+
(28, 16),
|
| 384 |
+
(28, 17),
|
| 385 |
+
(28, 25),
|
| 386 |
+
(28, 27),
|
| 387 |
+
(32, 5),
|
| 388 |
+
(32, 10),
|
| 389 |
+
(32, 12),
|
| 390 |
+
(32, 16),
|
| 391 |
+
(32, 17),
|
| 392 |
+
(32, 22),
|
| 393 |
+
(32, 23),
|
| 394 |
+
(33, 7),
|
| 395 |
+
(33, 10),
|
| 396 |
+
(33, 12),
|
| 397 |
+
(33, 16),
|
| 398 |
+
(33, 17),
|
| 399 |
+
(33, 25),
|
| 400 |
+
(33, 27),
|
| 401 |
+
(36, 5),
|
| 402 |
+
(36, 8),
|
| 403 |
+
(36, 15),
|
| 404 |
+
(36, 16),
|
| 405 |
+
(36, 17),
|
| 406 |
+
(36, 25),
|
| 407 |
+
(36, 27),
|
| 408 |
+
(37, 5),
|
| 409 |
+
(37, 11),
|
| 410 |
+
(37, 15),
|
| 411 |
+
(37, 16),
|
| 412 |
+
(37, 17),
|
| 413 |
+
(37, 22),
|
| 414 |
+
(37, 23),
|
| 415 |
+
(39, 7),
|
| 416 |
+
(39, 8),
|
| 417 |
+
(39, 15),
|
| 418 |
+
(39, 22),
|
| 419 |
+
(39, 23),
|
| 420 |
+
]
|
| 421 |
+
)
|
| 422 |
+
F = {node: node // s for node in range(num_colors * s)}
|
| 423 |
+
F[s - 1] = num_colors - 1 # V- = 0, V+ = num_colors - 1
|
| 424 |
+
|
| 425 |
+
params = make_params_from_graph(G=G, F=F)
|
| 426 |
+
|
| 427 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
| 428 |
+
V_minus=0, V_plus=num_colors - 1, **params
|
| 429 |
+
)
|
| 430 |
+
check_state(**params)
|
| 431 |
+
|
| 432 |
+
def test_strategy_saturation_largest_first(self):
|
| 433 |
+
def color_remaining_nodes(
|
| 434 |
+
G,
|
| 435 |
+
colored_nodes,
|
| 436 |
+
full_color_assignment=None,
|
| 437 |
+
nodes_to_add_between_calls=1,
|
| 438 |
+
):
|
| 439 |
+
color_assignments = []
|
| 440 |
+
aux_colored_nodes = colored_nodes.copy()
|
| 441 |
+
|
| 442 |
+
node_iterator = nx.algorithms.coloring.greedy_coloring.strategy_saturation_largest_first(
|
| 443 |
+
G, aux_colored_nodes
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
for u in node_iterator:
|
| 447 |
+
# Set to keep track of colors of neighbors
|
| 448 |
+
nbr_colors = {
|
| 449 |
+
aux_colored_nodes[v] for v in G[u] if v in aux_colored_nodes
|
| 450 |
+
}
|
| 451 |
+
# Find the first unused color.
|
| 452 |
+
for color in itertools.count():
|
| 453 |
+
if color not in nbr_colors:
|
| 454 |
+
break
|
| 455 |
+
aux_colored_nodes[u] = color
|
| 456 |
+
color_assignments.append((u, color))
|
| 457 |
+
|
| 458 |
+
# Color nodes between iterations
|
| 459 |
+
for i in range(nodes_to_add_between_calls - 1):
|
| 460 |
+
if not len(color_assignments) + len(colored_nodes) >= len(
|
| 461 |
+
full_color_assignment
|
| 462 |
+
):
|
| 463 |
+
full_color_assignment_node, color = full_color_assignment[
|
| 464 |
+
len(color_assignments) + len(colored_nodes)
|
| 465 |
+
]
|
| 466 |
+
|
| 467 |
+
# Assign the new color to the current node.
|
| 468 |
+
aux_colored_nodes[full_color_assignment_node] = color
|
| 469 |
+
color_assignments.append((full_color_assignment_node, color))
|
| 470 |
+
|
| 471 |
+
return color_assignments, aux_colored_nodes
|
| 472 |
+
|
| 473 |
+
for G, _, _ in SPECIAL_TEST_CASES["saturation_largest_first"]:
|
| 474 |
+
G = G()
|
| 475 |
+
|
| 476 |
+
# Check that function still works when nodes are colored between iterations
|
| 477 |
+
for nodes_to_add_between_calls in range(1, 5):
|
| 478 |
+
# Get a full color assignment, (including the order in which nodes were colored)
|
| 479 |
+
colored_nodes = {}
|
| 480 |
+
full_color_assignment, full_colored_nodes = color_remaining_nodes(
|
| 481 |
+
G, colored_nodes
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
# For each node in the color assignment, add it to colored_nodes and re-run the function
|
| 485 |
+
for ind, (node, color) in enumerate(full_color_assignment):
|
| 486 |
+
colored_nodes[node] = color
|
| 487 |
+
|
| 488 |
+
(
|
| 489 |
+
partial_color_assignment,
|
| 490 |
+
partial_colored_nodes,
|
| 491 |
+
) = color_remaining_nodes(
|
| 492 |
+
G,
|
| 493 |
+
colored_nodes,
|
| 494 |
+
full_color_assignment=full_color_assignment,
|
| 495 |
+
nodes_to_add_between_calls=nodes_to_add_between_calls,
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
# Check that the color assignment and order of remaining nodes are the same
|
| 499 |
+
assert full_color_assignment[ind + 1 :] == partial_color_assignment
|
| 500 |
+
assert full_colored_nodes == partial_colored_nodes
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
# ############################ Utility functions ############################
|
| 504 |
+
def verify_coloring(graph, coloring):
|
| 505 |
+
for node in graph.nodes():
|
| 506 |
+
if node not in coloring:
|
| 507 |
+
return False
|
| 508 |
+
|
| 509 |
+
color = coloring[node]
|
| 510 |
+
for neighbor in graph.neighbors(node):
|
| 511 |
+
if coloring[neighbor] == color:
|
| 512 |
+
return False
|
| 513 |
+
|
| 514 |
+
return True
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def verify_length(coloring, expected):
|
| 518 |
+
coloring = dict_to_sets(coloring)
|
| 519 |
+
return len(coloring) == expected
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def dict_to_sets(colors):
|
| 523 |
+
if len(colors) == 0:
|
| 524 |
+
return []
|
| 525 |
+
|
| 526 |
+
k = max(colors.values()) + 1
|
| 527 |
+
sets = [set() for _ in range(k)]
|
| 528 |
+
|
| 529 |
+
for node, color in colors.items():
|
| 530 |
+
sets[color].add(node)
|
| 531 |
+
|
| 532 |
+
return sets
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
# ############################ Graph Generation ############################
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def empty_graph():
|
| 539 |
+
return nx.Graph()
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def one_node_graph():
|
| 543 |
+
graph = nx.Graph()
|
| 544 |
+
graph.add_nodes_from([1])
|
| 545 |
+
return graph
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
def two_node_graph():
|
| 549 |
+
graph = nx.Graph()
|
| 550 |
+
graph.add_nodes_from([1, 2])
|
| 551 |
+
graph.add_edges_from([(1, 2)])
|
| 552 |
+
return graph
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def three_node_clique():
|
| 556 |
+
graph = nx.Graph()
|
| 557 |
+
graph.add_nodes_from([1, 2, 3])
|
| 558 |
+
graph.add_edges_from([(1, 2), (1, 3), (2, 3)])
|
| 559 |
+
return graph
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def disconnected():
|
| 563 |
+
graph = nx.Graph()
|
| 564 |
+
graph.add_edges_from([(1, 2), (2, 3), (4, 5), (5, 6)])
|
| 565 |
+
return graph
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def rs_shc():
|
| 569 |
+
graph = nx.Graph()
|
| 570 |
+
graph.add_nodes_from([1, 2, 3, 4])
|
| 571 |
+
graph.add_edges_from([(1, 2), (2, 3), (3, 4)])
|
| 572 |
+
return graph
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def slf_shc():
|
| 576 |
+
graph = nx.Graph()
|
| 577 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
| 578 |
+
graph.add_edges_from(
|
| 579 |
+
[(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)]
|
| 580 |
+
)
|
| 581 |
+
return graph
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def slf_hc():
|
| 585 |
+
graph = nx.Graph()
|
| 586 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
|
| 587 |
+
graph.add_edges_from(
|
| 588 |
+
[
|
| 589 |
+
(1, 2),
|
| 590 |
+
(1, 3),
|
| 591 |
+
(1, 4),
|
| 592 |
+
(1, 5),
|
| 593 |
+
(2, 3),
|
| 594 |
+
(2, 4),
|
| 595 |
+
(2, 6),
|
| 596 |
+
(5, 7),
|
| 597 |
+
(5, 8),
|
| 598 |
+
(6, 7),
|
| 599 |
+
(6, 8),
|
| 600 |
+
(7, 8),
|
| 601 |
+
]
|
| 602 |
+
)
|
| 603 |
+
return graph
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def lf_shc():
|
| 607 |
+
graph = nx.Graph()
|
| 608 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
| 609 |
+
graph.add_edges_from([(6, 1), (1, 4), (4, 3), (3, 2), (2, 5)])
|
| 610 |
+
return graph
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def lf_hc():
|
| 614 |
+
graph = nx.Graph()
|
| 615 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
| 616 |
+
graph.add_edges_from(
|
| 617 |
+
[
|
| 618 |
+
(1, 7),
|
| 619 |
+
(1, 6),
|
| 620 |
+
(1, 3),
|
| 621 |
+
(1, 4),
|
| 622 |
+
(7, 2),
|
| 623 |
+
(2, 6),
|
| 624 |
+
(2, 3),
|
| 625 |
+
(2, 5),
|
| 626 |
+
(5, 3),
|
| 627 |
+
(5, 4),
|
| 628 |
+
(4, 3),
|
| 629 |
+
]
|
| 630 |
+
)
|
| 631 |
+
return graph
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def sl_shc():
|
| 635 |
+
graph = nx.Graph()
|
| 636 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
| 637 |
+
graph.add_edges_from(
|
| 638 |
+
[(1, 2), (1, 3), (2, 3), (1, 4), (2, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
|
| 639 |
+
)
|
| 640 |
+
return graph
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def sl_hc():
|
| 644 |
+
graph = nx.Graph()
|
| 645 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
|
| 646 |
+
graph.add_edges_from(
|
| 647 |
+
[
|
| 648 |
+
(1, 2),
|
| 649 |
+
(1, 3),
|
| 650 |
+
(1, 5),
|
| 651 |
+
(1, 7),
|
| 652 |
+
(2, 3),
|
| 653 |
+
(2, 4),
|
| 654 |
+
(2, 8),
|
| 655 |
+
(8, 4),
|
| 656 |
+
(8, 6),
|
| 657 |
+
(8, 7),
|
| 658 |
+
(7, 5),
|
| 659 |
+
(7, 6),
|
| 660 |
+
(3, 4),
|
| 661 |
+
(4, 6),
|
| 662 |
+
(6, 5),
|
| 663 |
+
(5, 3),
|
| 664 |
+
]
|
| 665 |
+
)
|
| 666 |
+
return graph
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def gis_shc():
|
| 670 |
+
graph = nx.Graph()
|
| 671 |
+
graph.add_nodes_from([1, 2, 3, 4])
|
| 672 |
+
graph.add_edges_from([(1, 2), (2, 3), (3, 4)])
|
| 673 |
+
return graph
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def gis_hc():
|
| 677 |
+
graph = nx.Graph()
|
| 678 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
| 679 |
+
graph.add_edges_from([(1, 5), (2, 5), (3, 6), (4, 6), (5, 6)])
|
| 680 |
+
return graph
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def cs_shc():
|
| 684 |
+
graph = nx.Graph()
|
| 685 |
+
graph.add_nodes_from([1, 2, 3, 4, 5])
|
| 686 |
+
graph.add_edges_from([(1, 2), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (4, 5)])
|
| 687 |
+
return graph
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def rsi_shc():
|
| 691 |
+
graph = nx.Graph()
|
| 692 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
| 693 |
+
graph.add_edges_from(
|
| 694 |
+
[(1, 2), (1, 5), (1, 6), (2, 3), (3, 4), (4, 5), (4, 6), (5, 6)]
|
| 695 |
+
)
|
| 696 |
+
return graph
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
def lfi_shc():
|
| 700 |
+
graph = nx.Graph()
|
| 701 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
| 702 |
+
graph.add_edges_from(
|
| 703 |
+
[(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)]
|
| 704 |
+
)
|
| 705 |
+
return graph
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
def lfi_hc():
|
| 709 |
+
graph = nx.Graph()
|
| 710 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
|
| 711 |
+
graph.add_edges_from(
|
| 712 |
+
[
|
| 713 |
+
(1, 2),
|
| 714 |
+
(1, 5),
|
| 715 |
+
(1, 6),
|
| 716 |
+
(1, 7),
|
| 717 |
+
(2, 3),
|
| 718 |
+
(2, 8),
|
| 719 |
+
(2, 9),
|
| 720 |
+
(3, 4),
|
| 721 |
+
(3, 8),
|
| 722 |
+
(3, 9),
|
| 723 |
+
(4, 5),
|
| 724 |
+
(4, 6),
|
| 725 |
+
(4, 7),
|
| 726 |
+
(5, 6),
|
| 727 |
+
]
|
| 728 |
+
)
|
| 729 |
+
return graph
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def sli_shc():
|
| 733 |
+
graph = nx.Graph()
|
| 734 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
| 735 |
+
graph.add_edges_from(
|
| 736 |
+
[
|
| 737 |
+
(1, 2),
|
| 738 |
+
(1, 3),
|
| 739 |
+
(1, 5),
|
| 740 |
+
(1, 7),
|
| 741 |
+
(2, 3),
|
| 742 |
+
(2, 6),
|
| 743 |
+
(3, 4),
|
| 744 |
+
(4, 5),
|
| 745 |
+
(4, 6),
|
| 746 |
+
(5, 7),
|
| 747 |
+
(6, 7),
|
| 748 |
+
]
|
| 749 |
+
)
|
| 750 |
+
return graph
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
def sli_hc():
|
| 754 |
+
graph = nx.Graph()
|
| 755 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
|
| 756 |
+
graph.add_edges_from(
|
| 757 |
+
[
|
| 758 |
+
(1, 2),
|
| 759 |
+
(1, 3),
|
| 760 |
+
(1, 4),
|
| 761 |
+
(1, 5),
|
| 762 |
+
(2, 3),
|
| 763 |
+
(2, 7),
|
| 764 |
+
(2, 8),
|
| 765 |
+
(2, 9),
|
| 766 |
+
(3, 6),
|
| 767 |
+
(3, 7),
|
| 768 |
+
(3, 9),
|
| 769 |
+
(4, 5),
|
| 770 |
+
(4, 6),
|
| 771 |
+
(4, 8),
|
| 772 |
+
(4, 9),
|
| 773 |
+
(5, 6),
|
| 774 |
+
(5, 7),
|
| 775 |
+
(5, 8),
|
| 776 |
+
(6, 7),
|
| 777 |
+
(6, 9),
|
| 778 |
+
(7, 8),
|
| 779 |
+
(8, 9),
|
| 780 |
+
]
|
| 781 |
+
)
|
| 782 |
+
return graph
|
| 783 |
+
|
| 784 |
+
|
| 785 |
+
# --------------------------------------------------------------------------
|
| 786 |
+
# Basic tests for all strategies
|
| 787 |
+
# For each basic graph function, specify the number of expected colors.
|
| 788 |
+
BASIC_TEST_CASES = {
|
| 789 |
+
empty_graph: 0,
|
| 790 |
+
one_node_graph: 1,
|
| 791 |
+
two_node_graph: 2,
|
| 792 |
+
disconnected: 2,
|
| 793 |
+
three_node_clique: 3,
|
| 794 |
+
}
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
# --------------------------------------------------------------------------
|
| 798 |
+
# Special test cases. Each strategy has a list of tuples of the form
|
| 799 |
+
# (graph function, interchange, valid # of colors)
|
| 800 |
+
SPECIAL_TEST_CASES = {
|
| 801 |
+
"random_sequential": [
|
| 802 |
+
(rs_shc, False, (2, 3)),
|
| 803 |
+
(rs_shc, True, 2),
|
| 804 |
+
(rsi_shc, True, (3, 4)),
|
| 805 |
+
],
|
| 806 |
+
"saturation_largest_first": [(slf_shc, False, (3, 4)), (slf_hc, False, 4)],
|
| 807 |
+
"largest_first": [
|
| 808 |
+
(lf_shc, False, (2, 3)),
|
| 809 |
+
(lf_hc, False, 4),
|
| 810 |
+
(lf_shc, True, 2),
|
| 811 |
+
(lf_hc, True, 3),
|
| 812 |
+
(lfi_shc, True, (3, 4)),
|
| 813 |
+
(lfi_hc, True, 4),
|
| 814 |
+
],
|
| 815 |
+
"smallest_last": [
|
| 816 |
+
(sl_shc, False, (3, 4)),
|
| 817 |
+
(sl_hc, False, 5),
|
| 818 |
+
(sl_shc, True, 3),
|
| 819 |
+
(sl_hc, True, 4),
|
| 820 |
+
(sli_shc, True, (3, 4)),
|
| 821 |
+
(sli_hc, True, 5),
|
| 822 |
+
],
|
| 823 |
+
"independent_set": [(gis_shc, False, (2, 3)), (gis_hc, False, 3)],
|
| 824 |
+
"connected_sequential": [(cs_shc, False, (3, 4)), (cs_shc, True, 3)],
|
| 825 |
+
"connected_sequential_dfs": [(cs_shc, False, (3, 4))],
|
| 826 |
+
}
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
# --------------------------------------------------------------------------
|
| 830 |
+
# Helper functions to test
|
| 831 |
+
# (graph function, interchange, valid # of colors)
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
def check_state(L, N, H, F, C):
|
| 835 |
+
s = len(C[0])
|
| 836 |
+
num_colors = len(C.keys())
|
| 837 |
+
|
| 838 |
+
assert all(u in L[v] for u in L for v in L[u])
|
| 839 |
+
assert all(F[u] != F[v] for u in L for v in L[u])
|
| 840 |
+
assert all(len(L[u]) < num_colors for u in L)
|
| 841 |
+
assert all(len(C[x]) == s for x in C)
|
| 842 |
+
assert all(H[(c1, c2)] >= 0 for c1 in C for c2 in C)
|
| 843 |
+
assert all(N[(u, F[u])] == 0 for u in F)
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def max_degree(G):
|
| 847 |
+
"""Get the maximum degree of any node in G."""
|
| 848 |
+
return max(G.degree(node) for node in G.nodes) if len(G.nodes) > 0 else 0
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
def make_params_from_graph(G, F):
|
| 852 |
+
"""Returns {N, L, H, C} from the given graph."""
|
| 853 |
+
num_nodes = len(G)
|
| 854 |
+
L = {u: [] for u in range(num_nodes)}
|
| 855 |
+
for u, v in G.edges:
|
| 856 |
+
L[u].append(v)
|
| 857 |
+
L[v].append(u)
|
| 858 |
+
|
| 859 |
+
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
|
| 860 |
+
N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
|
| 861 |
+
H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
|
| 862 |
+
|
| 863 |
+
return {"N": N, "F": F, "C": C, "H": H, "L": L}
|
.venv/lib/python3.11/site-packages/networkx/algorithms/communicability_alg.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Communicability.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = ["communicability", "communicability_exp"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@not_implemented_for("directed")
|
| 12 |
+
@not_implemented_for("multigraph")
|
| 13 |
+
@nx._dispatchable
|
| 14 |
+
def communicability(G):
|
| 15 |
+
r"""Returns communicability between all pairs of nodes in G.
|
| 16 |
+
|
| 17 |
+
The communicability between pairs of nodes in G is the sum of
|
| 18 |
+
walks of different lengths starting at node u and ending at node v.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
G: graph
|
| 23 |
+
|
| 24 |
+
Returns
|
| 25 |
+
-------
|
| 26 |
+
comm: dictionary of dictionaries
|
| 27 |
+
Dictionary of dictionaries keyed by nodes with communicability
|
| 28 |
+
as the value.
|
| 29 |
+
|
| 30 |
+
Raises
|
| 31 |
+
------
|
| 32 |
+
NetworkXError
|
| 33 |
+
If the graph is not undirected and simple.
|
| 34 |
+
|
| 35 |
+
See Also
|
| 36 |
+
--------
|
| 37 |
+
communicability_exp:
|
| 38 |
+
Communicability between all pairs of nodes in G using spectral
|
| 39 |
+
decomposition.
|
| 40 |
+
communicability_betweenness_centrality:
|
| 41 |
+
Communicability betweenness centrality for each node in G.
|
| 42 |
+
|
| 43 |
+
Notes
|
| 44 |
+
-----
|
| 45 |
+
This algorithm uses a spectral decomposition of the adjacency matrix.
|
| 46 |
+
Let G=(V,E) be a simple undirected graph. Using the connection between
|
| 47 |
+
the powers of the adjacency matrix and the number of walks in the graph,
|
| 48 |
+
the communicability between nodes `u` and `v` based on the graph spectrum
|
| 49 |
+
is [1]_
|
| 50 |
+
|
| 51 |
+
.. math::
|
| 52 |
+
C(u,v)=\sum_{j=1}^{n}\phi_{j}(u)\phi_{j}(v)e^{\lambda_{j}},
|
| 53 |
+
|
| 54 |
+
where `\phi_{j}(u)` is the `u\rm{th}` element of the `j\rm{th}` orthonormal
|
| 55 |
+
eigenvector of the adjacency matrix associated with the eigenvalue
|
| 56 |
+
`\lambda_{j}`.
|
| 57 |
+
|
| 58 |
+
References
|
| 59 |
+
----------
|
| 60 |
+
.. [1] Ernesto Estrada, Naomichi Hatano,
|
| 61 |
+
"Communicability in complex networks",
|
| 62 |
+
Phys. Rev. E 77, 036111 (2008).
|
| 63 |
+
https://arxiv.org/abs/0707.0756
|
| 64 |
+
|
| 65 |
+
Examples
|
| 66 |
+
--------
|
| 67 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
|
| 68 |
+
>>> c = nx.communicability(G)
|
| 69 |
+
"""
|
| 70 |
+
import numpy as np
|
| 71 |
+
|
| 72 |
+
nodelist = list(G) # ordering of nodes in matrix
|
| 73 |
+
A = nx.to_numpy_array(G, nodelist)
|
| 74 |
+
# convert to 0-1 matrix
|
| 75 |
+
A[A != 0.0] = 1
|
| 76 |
+
w, vec = np.linalg.eigh(A)
|
| 77 |
+
expw = np.exp(w)
|
| 78 |
+
mapping = dict(zip(nodelist, range(len(nodelist))))
|
| 79 |
+
c = {}
|
| 80 |
+
# computing communicabilities
|
| 81 |
+
for u in G:
|
| 82 |
+
c[u] = {}
|
| 83 |
+
for v in G:
|
| 84 |
+
s = 0
|
| 85 |
+
p = mapping[u]
|
| 86 |
+
q = mapping[v]
|
| 87 |
+
for j in range(len(nodelist)):
|
| 88 |
+
s += vec[:, j][p] * vec[:, j][q] * expw[j]
|
| 89 |
+
c[u][v] = float(s)
|
| 90 |
+
return c
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@not_implemented_for("directed")
|
| 94 |
+
@not_implemented_for("multigraph")
|
| 95 |
+
@nx._dispatchable
|
| 96 |
+
def communicability_exp(G):
|
| 97 |
+
r"""Returns communicability between all pairs of nodes in G.
|
| 98 |
+
|
| 99 |
+
Communicability between pair of node (u,v) of node in G is the sum of
|
| 100 |
+
walks of different lengths starting at node u and ending at node v.
|
| 101 |
+
|
| 102 |
+
Parameters
|
| 103 |
+
----------
|
| 104 |
+
G: graph
|
| 105 |
+
|
| 106 |
+
Returns
|
| 107 |
+
-------
|
| 108 |
+
comm: dictionary of dictionaries
|
| 109 |
+
Dictionary of dictionaries keyed by nodes with communicability
|
| 110 |
+
as the value.
|
| 111 |
+
|
| 112 |
+
Raises
|
| 113 |
+
------
|
| 114 |
+
NetworkXError
|
| 115 |
+
If the graph is not undirected and simple.
|
| 116 |
+
|
| 117 |
+
See Also
|
| 118 |
+
--------
|
| 119 |
+
communicability:
|
| 120 |
+
Communicability between pairs of nodes in G.
|
| 121 |
+
communicability_betweenness_centrality:
|
| 122 |
+
Communicability betweenness centrality for each node in G.
|
| 123 |
+
|
| 124 |
+
Notes
|
| 125 |
+
-----
|
| 126 |
+
This algorithm uses matrix exponentiation of the adjacency matrix.
|
| 127 |
+
|
| 128 |
+
Let G=(V,E) be a simple undirected graph. Using the connection between
|
| 129 |
+
the powers of the adjacency matrix and the number of walks in the graph,
|
| 130 |
+
the communicability between nodes u and v is [1]_,
|
| 131 |
+
|
| 132 |
+
.. math::
|
| 133 |
+
C(u,v) = (e^A)_{uv},
|
| 134 |
+
|
| 135 |
+
where `A` is the adjacency matrix of G.
|
| 136 |
+
|
| 137 |
+
References
|
| 138 |
+
----------
|
| 139 |
+
.. [1] Ernesto Estrada, Naomichi Hatano,
|
| 140 |
+
"Communicability in complex networks",
|
| 141 |
+
Phys. Rev. E 77, 036111 (2008).
|
| 142 |
+
https://arxiv.org/abs/0707.0756
|
| 143 |
+
|
| 144 |
+
Examples
|
| 145 |
+
--------
|
| 146 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
|
| 147 |
+
>>> c = nx.communicability_exp(G)
|
| 148 |
+
"""
|
| 149 |
+
import scipy as sp
|
| 150 |
+
|
| 151 |
+
nodelist = list(G) # ordering of nodes in matrix
|
| 152 |
+
A = nx.to_numpy_array(G, nodelist)
|
| 153 |
+
# convert to 0-1 matrix
|
| 154 |
+
A[A != 0.0] = 1
|
| 155 |
+
# communicability matrix
|
| 156 |
+
expA = sp.linalg.expm(A)
|
| 157 |
+
mapping = dict(zip(nodelist, range(len(nodelist))))
|
| 158 |
+
c = {}
|
| 159 |
+
for u in G:
|
| 160 |
+
c[u] = {}
|
| 161 |
+
for v in G:
|
| 162 |
+
c[u][v] = float(expA[mapping[u], mapping[v]])
|
| 163 |
+
return c
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for computing and measuring community structure.
|
| 2 |
+
|
| 3 |
+
The ``community`` subpackage can be accessed by using :mod:`networkx.community`, then accessing the
|
| 4 |
+
functions as attributes of ``community``. For example::
|
| 5 |
+
|
| 6 |
+
>>> import networkx as nx
|
| 7 |
+
>>> G = nx.barbell_graph(5, 1)
|
| 8 |
+
>>> communities_generator = nx.community.girvan_newman(G)
|
| 9 |
+
>>> top_level_communities = next(communities_generator)
|
| 10 |
+
>>> next_level_communities = next(communities_generator)
|
| 11 |
+
>>> sorted(map(sorted, next_level_communities))
|
| 12 |
+
[[0, 1, 2, 3, 4], [5], [6, 7, 8, 9, 10]]
|
| 13 |
+
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from networkx.algorithms.community.asyn_fluid import *
|
| 17 |
+
from networkx.algorithms.community.bipartitions import *
|
| 18 |
+
from networkx.algorithms.community.centrality import *
|
| 19 |
+
from networkx.algorithms.community.divisive import *
|
| 20 |
+
from networkx.algorithms.community.kclique import *
|
| 21 |
+
from networkx.algorithms.community.label_propagation import *
|
| 22 |
+
from networkx.algorithms.community.lukes import *
|
| 23 |
+
from networkx.algorithms.community.modularity_max import *
|
| 24 |
+
from networkx.algorithms.community.quality import *
|
| 25 |
+
from networkx.algorithms.community.community_utils import *
|
| 26 |
+
from networkx.algorithms.community.louvain import *
|
| 27 |
+
from networkx.algorithms.community.leiden import *
|
| 28 |
+
from networkx.algorithms.community.local import *
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/asyn_fluid.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Asynchronous Fluid Communities algorithm for community detection."""
|
| 2 |
+
|
| 3 |
+
from collections import Counter
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.algorithms.components import is_connected
|
| 7 |
+
from networkx.exception import NetworkXError
|
| 8 |
+
from networkx.utils import groups, not_implemented_for, py_random_state
|
| 9 |
+
|
| 10 |
+
__all__ = ["asyn_fluidc"]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@not_implemented_for("directed")
|
| 14 |
+
@not_implemented_for("multigraph")
|
| 15 |
+
@py_random_state(3)
|
| 16 |
+
@nx._dispatchable
|
| 17 |
+
def asyn_fluidc(G, k, max_iter=100, seed=None):
|
| 18 |
+
"""Returns communities in `G` as detected by Fluid Communities algorithm.
|
| 19 |
+
|
| 20 |
+
The asynchronous fluid communities algorithm is described in
|
| 21 |
+
[1]_. The algorithm is based on the simple idea of fluids interacting
|
| 22 |
+
in an environment, expanding and pushing each other. Its initialization is
|
| 23 |
+
random, so found communities may vary on different executions.
|
| 24 |
+
|
| 25 |
+
The algorithm proceeds as follows. First each of the initial k communities
|
| 26 |
+
is initialized in a random vertex in the graph. Then the algorithm iterates
|
| 27 |
+
over all vertices in a random order, updating the community of each vertex
|
| 28 |
+
based on its own community and the communities of its neighbors. This
|
| 29 |
+
process is performed several times until convergence.
|
| 30 |
+
At all times, each community has a total density of 1, which is equally
|
| 31 |
+
distributed among the vertices it contains. If a vertex changes of
|
| 32 |
+
community, vertex densities of affected communities are adjusted
|
| 33 |
+
immediately. When a complete iteration over all vertices is done, such that
|
| 34 |
+
no vertex changes the community it belongs to, the algorithm has converged
|
| 35 |
+
and returns.
|
| 36 |
+
|
| 37 |
+
This is the original version of the algorithm described in [1]_.
|
| 38 |
+
Unfortunately, it does not support weighted graphs yet.
|
| 39 |
+
|
| 40 |
+
Parameters
|
| 41 |
+
----------
|
| 42 |
+
G : NetworkX graph
|
| 43 |
+
Graph must be simple and undirected.
|
| 44 |
+
|
| 45 |
+
k : integer
|
| 46 |
+
The number of communities to be found.
|
| 47 |
+
|
| 48 |
+
max_iter : integer
|
| 49 |
+
The number of maximum iterations allowed. By default 100.
|
| 50 |
+
|
| 51 |
+
seed : integer, random_state, or None (default)
|
| 52 |
+
Indicator of random number generation state.
|
| 53 |
+
See :ref:`Randomness<randomness>`.
|
| 54 |
+
|
| 55 |
+
Returns
|
| 56 |
+
-------
|
| 57 |
+
communities : iterable
|
| 58 |
+
Iterable of communities given as sets of nodes.
|
| 59 |
+
|
| 60 |
+
Notes
|
| 61 |
+
-----
|
| 62 |
+
k variable is not an optional argument.
|
| 63 |
+
|
| 64 |
+
References
|
| 65 |
+
----------
|
| 66 |
+
.. [1] Parés F., Garcia-Gasulla D. et al. "Fluid Communities: A
|
| 67 |
+
Competitive and Highly Scalable Community Detection Algorithm".
|
| 68 |
+
[https://arxiv.org/pdf/1703.09307.pdf].
|
| 69 |
+
"""
|
| 70 |
+
# Initial checks
|
| 71 |
+
if not isinstance(k, int):
|
| 72 |
+
raise NetworkXError("k must be an integer.")
|
| 73 |
+
if not k > 0:
|
| 74 |
+
raise NetworkXError("k must be greater than 0.")
|
| 75 |
+
if not is_connected(G):
|
| 76 |
+
raise NetworkXError("Fluid Communities require connected Graphs.")
|
| 77 |
+
if len(G) < k:
|
| 78 |
+
raise NetworkXError("k cannot be bigger than the number of nodes.")
|
| 79 |
+
if max_iter <= 0:
|
| 80 |
+
msg = f"{max_iter=} must be greater than 0"
|
| 81 |
+
raise ValueError(msg)
|
| 82 |
+
# Initialization
|
| 83 |
+
max_density = 1.0
|
| 84 |
+
vertices = list(G)
|
| 85 |
+
seed.shuffle(vertices)
|
| 86 |
+
communities = {n: i for i, n in enumerate(vertices[:k])}
|
| 87 |
+
density = {}
|
| 88 |
+
com_to_numvertices = {}
|
| 89 |
+
for vertex in communities:
|
| 90 |
+
com_to_numvertices[communities[vertex]] = 1
|
| 91 |
+
density[communities[vertex]] = max_density
|
| 92 |
+
# Set up control variables and start iterating
|
| 93 |
+
iter_count = 0
|
| 94 |
+
cont = True
|
| 95 |
+
while cont and iter_count < max_iter:
|
| 96 |
+
cont = False
|
| 97 |
+
iter_count += 1
|
| 98 |
+
# Loop over all vertices in graph in a random order
|
| 99 |
+
vertices = list(G)
|
| 100 |
+
seed.shuffle(vertices)
|
| 101 |
+
for vertex in vertices:
|
| 102 |
+
# Updating rule
|
| 103 |
+
com_counter = Counter()
|
| 104 |
+
# Take into account self vertex community
|
| 105 |
+
try:
|
| 106 |
+
com_counter.update({communities[vertex]: density[communities[vertex]]})
|
| 107 |
+
except KeyError:
|
| 108 |
+
pass
|
| 109 |
+
# Gather neighbor vertex communities
|
| 110 |
+
for v in G[vertex]:
|
| 111 |
+
try:
|
| 112 |
+
com_counter.update({communities[v]: density[communities[v]]})
|
| 113 |
+
except KeyError:
|
| 114 |
+
continue
|
| 115 |
+
# Check which is the community with highest density
|
| 116 |
+
new_com = -1
|
| 117 |
+
if len(com_counter.keys()) > 0:
|
| 118 |
+
max_freq = max(com_counter.values())
|
| 119 |
+
best_communities = [
|
| 120 |
+
com
|
| 121 |
+
for com, freq in com_counter.items()
|
| 122 |
+
if (max_freq - freq) < 0.0001
|
| 123 |
+
]
|
| 124 |
+
# If actual vertex com in best communities, it is preserved
|
| 125 |
+
try:
|
| 126 |
+
if communities[vertex] in best_communities:
|
| 127 |
+
new_com = communities[vertex]
|
| 128 |
+
except KeyError:
|
| 129 |
+
pass
|
| 130 |
+
|
| 131 |
+
# If vertex community changes...
|
| 132 |
+
if new_com == -1:
|
| 133 |
+
# Set flag of non-convergence
|
| 134 |
+
cont = True
|
| 135 |
+
# Randomly chose a new community from candidates
|
| 136 |
+
new_com = seed.choice(best_communities)
|
| 137 |
+
# Update previous community status
|
| 138 |
+
try:
|
| 139 |
+
com_to_numvertices[communities[vertex]] -= 1
|
| 140 |
+
density[communities[vertex]] = (
|
| 141 |
+
max_density / com_to_numvertices[communities[vertex]]
|
| 142 |
+
)
|
| 143 |
+
except KeyError:
|
| 144 |
+
pass
|
| 145 |
+
# Update new community status
|
| 146 |
+
communities[vertex] = new_com
|
| 147 |
+
com_to_numvertices[communities[vertex]] += 1
|
| 148 |
+
density[communities[vertex]] = (
|
| 149 |
+
max_density / com_to_numvertices[communities[vertex]]
|
| 150 |
+
)
|
| 151 |
+
# If maximum iterations reached --> output actual results
|
| 152 |
+
# Return results by grouping communities as list of vertices
|
| 153 |
+
return iter(groups(communities).values())
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/bipartitions.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for splitting a network into two communities (finding a bipartition)."""
|
| 2 |
+
|
| 3 |
+
import random
|
| 4 |
+
from copy import deepcopy
|
| 5 |
+
from itertools import count
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
"kernighan_lin_bisection",
|
| 11 |
+
"spectral_modularity_bipartition",
|
| 12 |
+
"greedy_node_swap_bipartition",
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _kernighan_lin_sweep(edge_info, side):
|
| 17 |
+
"""
|
| 18 |
+
This is a modified form of Kernighan-Lin, which moves single nodes at a
|
| 19 |
+
time, alternating between sides to keep the bisection balanced. We keep
|
| 20 |
+
two min-heaps of swap costs to make optimal-next-move selection fast.
|
| 21 |
+
"""
|
| 22 |
+
heap0, heap1 = cost_heaps = nx.utils.BinaryHeap(), nx.utils.BinaryHeap()
|
| 23 |
+
# we use heap methods insert, pop, and get
|
| 24 |
+
for u, nbrs in edge_info.items():
|
| 25 |
+
cost_u = sum(wt if side[v] else -wt for v, wt in nbrs.items())
|
| 26 |
+
if side[u]:
|
| 27 |
+
heap1.insert(u, cost_u)
|
| 28 |
+
else:
|
| 29 |
+
heap0.insert(u, -cost_u)
|
| 30 |
+
|
| 31 |
+
def _update_heap_values(node):
|
| 32 |
+
side_node = side[node]
|
| 33 |
+
for nbr, wt in edge_info[node].items():
|
| 34 |
+
side_nbr = side[nbr]
|
| 35 |
+
if side_nbr == side_node:
|
| 36 |
+
wt = -wt
|
| 37 |
+
heap_nbr = cost_heaps[side_nbr]
|
| 38 |
+
if nbr in heap_nbr:
|
| 39 |
+
cost_nbr = heap_nbr.get(nbr) + 2 * wt
|
| 40 |
+
# allow_increase lets us update a value already on the heap
|
| 41 |
+
heap_nbr.insert(nbr, cost_nbr, allow_increase=True)
|
| 42 |
+
|
| 43 |
+
i = 0
|
| 44 |
+
totcost = 0
|
| 45 |
+
while heap0 and heap1:
|
| 46 |
+
u, cost_u = heap0.pop()
|
| 47 |
+
_update_heap_values(u)
|
| 48 |
+
v, cost_v = heap1.pop()
|
| 49 |
+
_update_heap_values(v)
|
| 50 |
+
totcost += cost_u + cost_v
|
| 51 |
+
i += 1
|
| 52 |
+
yield totcost, i, (u, v)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@nx.utils.not_implemented_for("directed")
|
| 56 |
+
@nx.utils.py_random_state(4)
|
| 57 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 58 |
+
def kernighan_lin_bisection(G, partition=None, max_iter=10, weight="weight", seed=None):
|
| 59 |
+
"""Partition a graph into two blocks using the Kernighan–Lin algorithm.
|
| 60 |
+
|
| 61 |
+
This algorithm partitions a network into two sets by iteratively
|
| 62 |
+
swapping pairs of nodes to reduce the edge cut between the two sets. The
|
| 63 |
+
pairs are chosen according to a modified form of Kernighan-Lin [1]_, which
|
| 64 |
+
moves nodes individually, alternating between sides to keep the bisection
|
| 65 |
+
balanced.
|
| 66 |
+
|
| 67 |
+
Kernighan-Lin is an approximate algorithm for maximal modularity bisection.
|
| 68 |
+
In [2]_ they suggest that fine-tuned improvements can be made using
|
| 69 |
+
greedy node swapping, (see `greedy_node_swap_bipartition`).
|
| 70 |
+
The improvements are typically only a few percent of the modularity value.
|
| 71 |
+
But they claim that can make a difference between a good and excellent method.
|
| 72 |
+
This function does not perform any improvements. But you can do that yourself.
|
| 73 |
+
|
| 74 |
+
Parameters
|
| 75 |
+
----------
|
| 76 |
+
G : NetworkX graph
|
| 77 |
+
Graph must be undirected.
|
| 78 |
+
|
| 79 |
+
partition : tuple
|
| 80 |
+
Pair of iterables containing an initial partition. If not
|
| 81 |
+
specified, a random balanced partition is used.
|
| 82 |
+
|
| 83 |
+
max_iter : int
|
| 84 |
+
Maximum number of times to attempt swaps to find an
|
| 85 |
+
improvement before giving up.
|
| 86 |
+
|
| 87 |
+
weight : string or function (default: "weight")
|
| 88 |
+
If this is a string, then edge weights will be accessed via the
|
| 89 |
+
edge attribute with this key (that is, the weight of the edge
|
| 90 |
+
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
|
| 91 |
+
such edge attribute exists, the weight of the edge is assumed to
|
| 92 |
+
be one.
|
| 93 |
+
|
| 94 |
+
If this is a function, the weight of an edge is the value
|
| 95 |
+
returned by the function. The function must accept exactly three
|
| 96 |
+
positional arguments: the two endpoints of an edge and the
|
| 97 |
+
dictionary of edge attributes for that edge. The function must
|
| 98 |
+
return a number or None to indicate a hidden edge.
|
| 99 |
+
|
| 100 |
+
seed : integer, random_state, or None (default)
|
| 101 |
+
Indicator of random number generation state.
|
| 102 |
+
See :ref:`Randomness<randomness>`.
|
| 103 |
+
Only used if partition is None
|
| 104 |
+
|
| 105 |
+
Returns
|
| 106 |
+
-------
|
| 107 |
+
partition : tuple
|
| 108 |
+
A pair of sets of nodes representing the bipartition.
|
| 109 |
+
|
| 110 |
+
Raises
|
| 111 |
+
------
|
| 112 |
+
NetworkXError
|
| 113 |
+
If `partition` is not a valid partition of the nodes of the graph.
|
| 114 |
+
|
| 115 |
+
References
|
| 116 |
+
----------
|
| 117 |
+
.. [1] Kernighan, B. W.; Lin, Shen (1970).
|
| 118 |
+
"An efficient heuristic procedure for partitioning graphs."
|
| 119 |
+
*Bell Systems Technical Journal* 49: 291--307.
|
| 120 |
+
Oxford University Press 2011.
|
| 121 |
+
.. [2] M. E. J. Newman,
|
| 122 |
+
"Modularity and community structure in networks",
|
| 123 |
+
PNAS, 103 (23), p. 8577-8582,
|
| 124 |
+
https://doi.org/10.1073/pnas.0601602103
|
| 125 |
+
|
| 126 |
+
"""
|
| 127 |
+
nodes = list(G)
|
| 128 |
+
|
| 129 |
+
if partition is None:
|
| 130 |
+
seed.shuffle(nodes)
|
| 131 |
+
mid = len(nodes) // 2
|
| 132 |
+
A, B = nodes[:mid], nodes[mid:]
|
| 133 |
+
else:
|
| 134 |
+
try:
|
| 135 |
+
A, B = partition
|
| 136 |
+
except (TypeError, ValueError) as err:
|
| 137 |
+
raise nx.NetworkXError("partition must be two sets") from err
|
| 138 |
+
if not nx.community.is_partition(G, [A, B]):
|
| 139 |
+
raise nx.NetworkXError("partition invalid")
|
| 140 |
+
|
| 141 |
+
side = {node: (node in A) for node in nodes}
|
| 142 |
+
|
| 143 |
+
# ruff: noqa: E731 skips check for no lambda functions
|
| 144 |
+
# Using shortest_paths _weight_function with sum instead of min on multiedges
|
| 145 |
+
if callable(weight):
|
| 146 |
+
sum_weight = weight
|
| 147 |
+
elif G.is_multigraph():
|
| 148 |
+
sum_weight = lambda u, v, d: sum(dd.get(weight, 1) for dd in d.values())
|
| 149 |
+
else:
|
| 150 |
+
sum_weight = lambda u, v, d: d.get(weight, 1)
|
| 151 |
+
|
| 152 |
+
edge_info = {
|
| 153 |
+
u: {v: wt for v, d in nbrs.items() if (wt := sum_weight(u, v, d)) is not None}
|
| 154 |
+
for u, nbrs in G._adj.items()
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
for i in range(max_iter):
|
| 158 |
+
costs = list(_kernighan_lin_sweep(edge_info, side))
|
| 159 |
+
# find out how many edges to update: min_i
|
| 160 |
+
min_cost, min_i, _ = min(costs)
|
| 161 |
+
if min_cost >= 0:
|
| 162 |
+
break
|
| 163 |
+
|
| 164 |
+
for _, _, (u, v) in costs[:min_i]:
|
| 165 |
+
side[u] = 1
|
| 166 |
+
side[v] = 0
|
| 167 |
+
|
| 168 |
+
part1 = {u for u, s in side.items() if s == 0}
|
| 169 |
+
part2 = {u for u, s in side.items() if s == 1}
|
| 170 |
+
return part1, part2
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
@nx.utils.not_implemented_for("directed")
|
| 174 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 175 |
+
def spectral_modularity_bipartition(G):
|
| 176 |
+
r"""Return a bipartition of the nodes based on the spectrum of the
|
| 177 |
+
modularity matrix of the graph.
|
| 178 |
+
|
| 179 |
+
This method calculates the eigenvector associated with the second
|
| 180 |
+
largest eigenvalue of the modularity matrix, where the modularity
|
| 181 |
+
matrix *B* is defined by
|
| 182 |
+
|
| 183 |
+
..math::
|
| 184 |
+
|
| 185 |
+
B_{i j} = A_{i j} - \frac{k_i k_j}{2 m},
|
| 186 |
+
|
| 187 |
+
where *A* is the adjacency matrix, `k_i` is the degree of node *i*,
|
| 188 |
+
and *m* is the number of edges in the graph. Nodes whose
|
| 189 |
+
corresponding values in the eigenvector are negative are placed in
|
| 190 |
+
one block, nodes whose values are nonnegative are placed in another
|
| 191 |
+
block.
|
| 192 |
+
|
| 193 |
+
Parameters
|
| 194 |
+
----------
|
| 195 |
+
G : NetworkX graph
|
| 196 |
+
|
| 197 |
+
Returns
|
| 198 |
+
-------
|
| 199 |
+
C : tuple
|
| 200 |
+
Pair of communities as two sets of nodes of ``G``, partitioned
|
| 201 |
+
according to second largest eigenvalue of the modularity matrix.
|
| 202 |
+
|
| 203 |
+
Examples
|
| 204 |
+
--------
|
| 205 |
+
>>> G = nx.karate_club_graph()
|
| 206 |
+
>>> MrHi, Officer = nx.community.spectral_modularity_bipartition(G)
|
| 207 |
+
>>> MrHi, Officer = sorted([sorted(MrHi), sorted(Officer)])
|
| 208 |
+
>>> MrHi
|
| 209 |
+
[0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21]
|
| 210 |
+
>>> Officer
|
| 211 |
+
[8, 9, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
|
| 212 |
+
|
| 213 |
+
References
|
| 214 |
+
----------
|
| 215 |
+
.. [1] M. E. J. Newman *Networks: An Introduction*, pages 373--378
|
| 216 |
+
Oxford University Press 2011.
|
| 217 |
+
.. [2] M. E. J. Newman,
|
| 218 |
+
"Modularity and community structure in networks",
|
| 219 |
+
PNAS, 103 (23), p. 8577-8582,
|
| 220 |
+
https://doi.org/10.1073/pnas.0601602103
|
| 221 |
+
|
| 222 |
+
"""
|
| 223 |
+
import numpy as np
|
| 224 |
+
|
| 225 |
+
B = nx.linalg.modularity_matrix(G)
|
| 226 |
+
eigenvalues, eigenvectors = np.linalg.eig(B)
|
| 227 |
+
index = np.argsort(eigenvalues)[-1]
|
| 228 |
+
v2 = zip(np.real(eigenvectors[:, index]), G)
|
| 229 |
+
left, right = set(), set()
|
| 230 |
+
for u, n in v2:
|
| 231 |
+
if u < 0:
|
| 232 |
+
left.add(n)
|
| 233 |
+
else:
|
| 234 |
+
right.add(n)
|
| 235 |
+
return left, right
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 239 |
+
def greedy_node_swap_bipartition(G, *, init_split=None, max_iter=10):
|
| 240 |
+
"""Split the nodes into two communities based on greedy
|
| 241 |
+
modularity maximization.
|
| 242 |
+
|
| 243 |
+
The algorithm works by selecting a node to change communities which
|
| 244 |
+
will maximize the modularity. The swap is made and the community
|
| 245 |
+
structure with the highest modularity is kept.
|
| 246 |
+
|
| 247 |
+
Parameters
|
| 248 |
+
----------
|
| 249 |
+
G : NetworkX graph
|
| 250 |
+
|
| 251 |
+
init_split : 2-tuple of sets of nodes
|
| 252 |
+
Pair of sets of nodes in ``G`` providing an initial bipartition
|
| 253 |
+
for the algorithm. If not specified, a random balanced partition
|
| 254 |
+
is used. If this pair of sets is not a partition of the nodes of `G`,
|
| 255 |
+
:exc:`NetworkXException` is raised.
|
| 256 |
+
|
| 257 |
+
max_iter : int
|
| 258 |
+
Maximum number of iterations of attempting swaps to find an improvement.
|
| 259 |
+
|
| 260 |
+
Returns
|
| 261 |
+
-------
|
| 262 |
+
max_split : 2-tuple of sets of nodes
|
| 263 |
+
Pair of sets of nodes of ``G``, partitioned according to a
|
| 264 |
+
node swap greedy modularity maximization algorithm.
|
| 265 |
+
|
| 266 |
+
Raises
|
| 267 |
+
------
|
| 268 |
+
NetworkXError
|
| 269 |
+
if init_split is not a valid partition of the
|
| 270 |
+
graph into two communities or if G is a MultiGraph
|
| 271 |
+
|
| 272 |
+
Examples
|
| 273 |
+
--------
|
| 274 |
+
>>> G = nx.barbell_graph(3, 0)
|
| 275 |
+
>>> left, right = nx.community.greedy_node_swap_bipartition(G)
|
| 276 |
+
>>> # Sort the communities so the nodes appear in increasing order.
|
| 277 |
+
>>> left, right = sorted([sorted(left), sorted(right)])
|
| 278 |
+
>>> sorted(left)
|
| 279 |
+
[0, 1, 2]
|
| 280 |
+
>>> sorted(right)
|
| 281 |
+
[3, 4, 5]
|
| 282 |
+
|
| 283 |
+
Notes
|
| 284 |
+
-----
|
| 285 |
+
This function is not implemented for multigraphs.
|
| 286 |
+
|
| 287 |
+
References
|
| 288 |
+
----------
|
| 289 |
+
.. [1] M. E. J. Newman "Networks: An Introduction", pages 373--375.
|
| 290 |
+
Oxford University Press 2011.
|
| 291 |
+
|
| 292 |
+
"""
|
| 293 |
+
if init_split is None:
|
| 294 |
+
m1 = len(G) // 2
|
| 295 |
+
m2 = len(G) - m1
|
| 296 |
+
some_nodes = set(random.sample(list(G), m1))
|
| 297 |
+
other_nodes = {n for n in G if n not in some_nodes}
|
| 298 |
+
best_split_so_far = (some_nodes, other_nodes)
|
| 299 |
+
else:
|
| 300 |
+
if not nx.community.is_partition(G, init_split):
|
| 301 |
+
raise nx.NetworkXError("init_split is not a partition of G")
|
| 302 |
+
if not len(init_split) == 2:
|
| 303 |
+
raise nx.NetworkXError("init_split must be a bipartition")
|
| 304 |
+
best_split_so_far = deepcopy(init_split)
|
| 305 |
+
|
| 306 |
+
best_mod = nx.community.modularity(G, best_split_so_far)
|
| 307 |
+
|
| 308 |
+
max_split, max_mod = best_split_so_far, best_mod
|
| 309 |
+
its = 0
|
| 310 |
+
m = G.number_of_edges()
|
| 311 |
+
G_degree = dict(G.degree)
|
| 312 |
+
|
| 313 |
+
while max_mod >= best_mod and its < max_iter:
|
| 314 |
+
best_split_so_far = max_split
|
| 315 |
+
best_mod = max_mod
|
| 316 |
+
next_split = deepcopy(max_split)
|
| 317 |
+
next_mod = max_mod
|
| 318 |
+
nodes = set(G)
|
| 319 |
+
while nodes:
|
| 320 |
+
max_swap = -1
|
| 321 |
+
max_node = None
|
| 322 |
+
max_node_comm = None
|
| 323 |
+
left, right = next_split
|
| 324 |
+
leftd = sum(G_degree[n] for n in left)
|
| 325 |
+
rightd = sum(G_degree[n] for n in right)
|
| 326 |
+
for n in nodes:
|
| 327 |
+
if n in left:
|
| 328 |
+
in_comm, out_comm = left, right
|
| 329 |
+
in_deg, out_deg = leftd, rightd
|
| 330 |
+
else:
|
| 331 |
+
in_comm, out_comm = right, left
|
| 332 |
+
in_deg, out_deg = rightd, leftd
|
| 333 |
+
|
| 334 |
+
d_eii = -len(G[n].keys() & in_comm) / m
|
| 335 |
+
d_ejj = len(G[n].keys() & out_comm) / m
|
| 336 |
+
deg = G_degree[n]
|
| 337 |
+
d_sum_ai = (deg / (2 * m**2)) * (in_deg - out_deg - deg)
|
| 338 |
+
swap_change = d_eii + d_ejj + d_sum_ai
|
| 339 |
+
|
| 340 |
+
if swap_change > max_swap:
|
| 341 |
+
max_swap = swap_change
|
| 342 |
+
max_node = n
|
| 343 |
+
max_node_comm = in_comm
|
| 344 |
+
non_max_node_comm = out_comm
|
| 345 |
+
# swap the node from one comm to the other
|
| 346 |
+
max_node_comm.remove(max_node)
|
| 347 |
+
non_max_node_comm.add(max_node)
|
| 348 |
+
next_mod += max_swap
|
| 349 |
+
# deepcopy next_split each time it reaches a high (might go lower later)
|
| 350 |
+
if next_mod > max_mod:
|
| 351 |
+
max_split, max_mod = deepcopy(next_split), next_mod
|
| 352 |
+
nodes.remove(max_node)
|
| 353 |
+
its += 1
|
| 354 |
+
return best_split_so_far
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/centrality.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for computing communities based on centrality notions."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = ["girvan_newman"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@nx._dispatchable(preserve_edge_attrs="most_valuable_edge")
|
| 9 |
+
def girvan_newman(G, most_valuable_edge=None):
|
| 10 |
+
"""Finds communities in a graph using the Girvan–Newman method.
|
| 11 |
+
|
| 12 |
+
Parameters
|
| 13 |
+
----------
|
| 14 |
+
G : NetworkX graph
|
| 15 |
+
|
| 16 |
+
most_valuable_edge : function
|
| 17 |
+
Function that takes a graph as input and outputs an edge. The
|
| 18 |
+
edge returned by this function will be recomputed and removed at
|
| 19 |
+
each iteration of the algorithm.
|
| 20 |
+
|
| 21 |
+
If not specified, the edge with the highest
|
| 22 |
+
:func:`networkx.edge_betweenness_centrality` will be used.
|
| 23 |
+
|
| 24 |
+
Returns
|
| 25 |
+
-------
|
| 26 |
+
iterator
|
| 27 |
+
Iterator over tuples of sets of nodes in `G`. Each set of node
|
| 28 |
+
is a community, each tuple is a sequence of communities at a
|
| 29 |
+
particular level of the algorithm.
|
| 30 |
+
|
| 31 |
+
Examples
|
| 32 |
+
--------
|
| 33 |
+
To get the first pair of communities::
|
| 34 |
+
|
| 35 |
+
>>> G = nx.path_graph(10)
|
| 36 |
+
>>> comp = nx.community.girvan_newman(G)
|
| 37 |
+
>>> tuple(sorted(c) for c in next(comp))
|
| 38 |
+
([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])
|
| 39 |
+
|
| 40 |
+
To get only the first *k* tuples of communities, use
|
| 41 |
+
:func:`itertools.islice`::
|
| 42 |
+
|
| 43 |
+
>>> import itertools
|
| 44 |
+
>>> G = nx.path_graph(8)
|
| 45 |
+
>>> k = 2
|
| 46 |
+
>>> comp = nx.community.girvan_newman(G)
|
| 47 |
+
>>> for communities in itertools.islice(comp, k):
|
| 48 |
+
... print(tuple(sorted(c) for c in communities))
|
| 49 |
+
...
|
| 50 |
+
([0, 1, 2, 3], [4, 5, 6, 7])
|
| 51 |
+
([0, 1], [2, 3], [4, 5, 6, 7])
|
| 52 |
+
|
| 53 |
+
To stop getting tuples of communities once the number of communities
|
| 54 |
+
is greater than *k*, use :func:`itertools.takewhile`::
|
| 55 |
+
|
| 56 |
+
>>> import itertools
|
| 57 |
+
>>> G = nx.path_graph(8)
|
| 58 |
+
>>> k = 4
|
| 59 |
+
>>> comp = nx.community.girvan_newman(G)
|
| 60 |
+
>>> limited = itertools.takewhile(lambda c: len(c) <= k, comp)
|
| 61 |
+
>>> for communities in limited:
|
| 62 |
+
... print(tuple(sorted(c) for c in communities))
|
| 63 |
+
...
|
| 64 |
+
([0, 1, 2, 3], [4, 5, 6, 7])
|
| 65 |
+
([0, 1], [2, 3], [4, 5, 6, 7])
|
| 66 |
+
([0, 1], [2, 3], [4, 5], [6, 7])
|
| 67 |
+
|
| 68 |
+
To just choose an edge to remove based on the weight::
|
| 69 |
+
|
| 70 |
+
>>> from operator import itemgetter
|
| 71 |
+
>>> G = nx.path_graph(10)
|
| 72 |
+
>>> edges = G.edges()
|
| 73 |
+
>>> nx.set_edge_attributes(G, {(u, v): v for u, v in edges}, "weight")
|
| 74 |
+
>>> def heaviest(G):
|
| 75 |
+
... u, v, w = max(G.edges(data="weight"), key=itemgetter(2))
|
| 76 |
+
... return (u, v)
|
| 77 |
+
...
|
| 78 |
+
>>> comp = nx.community.girvan_newman(G, most_valuable_edge=heaviest)
|
| 79 |
+
>>> tuple(sorted(c) for c in next(comp))
|
| 80 |
+
([0, 1, 2, 3, 4, 5, 6, 7, 8], [9])
|
| 81 |
+
|
| 82 |
+
To utilize edge weights when choosing an edge with, for example, the
|
| 83 |
+
highest betweenness centrality::
|
| 84 |
+
|
| 85 |
+
>>> from networkx import edge_betweenness_centrality as betweenness
|
| 86 |
+
>>> def most_central_edge(G):
|
| 87 |
+
... centrality = betweenness(G, weight="weight")
|
| 88 |
+
... return max(centrality, key=centrality.get)
|
| 89 |
+
...
|
| 90 |
+
>>> G = nx.path_graph(10)
|
| 91 |
+
>>> comp = nx.community.girvan_newman(G, most_valuable_edge=most_central_edge)
|
| 92 |
+
>>> tuple(sorted(c) for c in next(comp))
|
| 93 |
+
([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])
|
| 94 |
+
|
| 95 |
+
To specify a different ranking algorithm for edges, use the
|
| 96 |
+
`most_valuable_edge` keyword argument::
|
| 97 |
+
|
| 98 |
+
>>> from networkx import edge_betweenness_centrality
|
| 99 |
+
>>> from random import random
|
| 100 |
+
>>> def most_central_edge(G):
|
| 101 |
+
... centrality = edge_betweenness_centrality(G)
|
| 102 |
+
... max_cent = max(centrality.values())
|
| 103 |
+
... # Scale the centrality values so they are between 0 and 1,
|
| 104 |
+
... # and add some random noise.
|
| 105 |
+
... centrality = {e: c / max_cent for e, c in centrality.items()}
|
| 106 |
+
... # Add some random noise.
|
| 107 |
+
... centrality = {e: c + random() for e, c in centrality.items()}
|
| 108 |
+
... return max(centrality, key=centrality.get)
|
| 109 |
+
...
|
| 110 |
+
>>> G = nx.path_graph(10)
|
| 111 |
+
>>> comp = nx.community.girvan_newman(G, most_valuable_edge=most_central_edge)
|
| 112 |
+
|
| 113 |
+
Notes
|
| 114 |
+
-----
|
| 115 |
+
The Girvan–Newman algorithm detects communities by progressively
|
| 116 |
+
removing edges from the original graph. The algorithm removes the
|
| 117 |
+
"most valuable" edge, traditionally the edge with the highest
|
| 118 |
+
betweenness centrality, at each step. As the graph breaks down into
|
| 119 |
+
pieces, the tightly knit community structure is exposed and the
|
| 120 |
+
result can be depicted as a dendrogram.
|
| 121 |
+
|
| 122 |
+
"""
|
| 123 |
+
# If the graph is already empty, simply return its connected
|
| 124 |
+
# components.
|
| 125 |
+
if G.number_of_edges() == 0:
|
| 126 |
+
yield tuple(nx.connected_components(G))
|
| 127 |
+
return
|
| 128 |
+
# If no function is provided for computing the most valuable edge,
|
| 129 |
+
# use the edge betweenness centrality.
|
| 130 |
+
if most_valuable_edge is None:
|
| 131 |
+
|
| 132 |
+
def most_valuable_edge(G):
|
| 133 |
+
"""Returns the edge with the highest betweenness centrality
|
| 134 |
+
in the graph `G`.
|
| 135 |
+
|
| 136 |
+
"""
|
| 137 |
+
# We have guaranteed that the graph is non-empty, so this
|
| 138 |
+
# dictionary will never be empty.
|
| 139 |
+
betweenness = nx.edge_betweenness_centrality(G)
|
| 140 |
+
return max(betweenness, key=betweenness.get)
|
| 141 |
+
|
| 142 |
+
# The copy of G here must include the edge weight data.
|
| 143 |
+
g = G.copy().to_undirected()
|
| 144 |
+
# Self-loops must be removed because their removal has no effect on
|
| 145 |
+
# the connected components of the graph.
|
| 146 |
+
g.remove_edges_from(nx.selfloop_edges(g))
|
| 147 |
+
while g.number_of_edges() > 0:
|
| 148 |
+
yield _without_most_central_edges(g, most_valuable_edge)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _without_most_central_edges(G, most_valuable_edge):
|
| 152 |
+
"""Returns the connected components of the graph that results from
|
| 153 |
+
repeatedly removing the most "valuable" edge in the graph.
|
| 154 |
+
|
| 155 |
+
`G` must be a non-empty graph. This function modifies the graph `G`
|
| 156 |
+
in-place; that is, it removes edges on the graph `G`.
|
| 157 |
+
|
| 158 |
+
`most_valuable_edge` is a function that takes the graph `G` as input
|
| 159 |
+
(or a subgraph with one or more edges of `G` removed) and returns an
|
| 160 |
+
edge. That edge will be removed and this process will be repeated
|
| 161 |
+
until the number of connected components in the graph increases.
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
original_num_components = nx.number_connected_components(G)
|
| 165 |
+
num_new_components = original_num_components
|
| 166 |
+
while num_new_components <= original_num_components:
|
| 167 |
+
edge = most_valuable_edge(G)
|
| 168 |
+
G.remove_edge(*edge)
|
| 169 |
+
new_components = tuple(nx.connected_components(G))
|
| 170 |
+
num_new_components = len(new_components)
|
| 171 |
+
return new_components
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/community_utils.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helper functions for community-finding algorithms."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = ["is_partition"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@nx._dispatchable
|
| 9 |
+
def is_partition(G, communities):
|
| 10 |
+
"""Returns *True* if `communities` is a partition of the nodes of `G`.
|
| 11 |
+
|
| 12 |
+
A partition of a universe set is a family of pairwise disjoint sets
|
| 13 |
+
whose union is the entire universe set.
|
| 14 |
+
|
| 15 |
+
Parameters
|
| 16 |
+
----------
|
| 17 |
+
G : NetworkX graph.
|
| 18 |
+
|
| 19 |
+
communities : list or iterable of sets of nodes
|
| 20 |
+
If not a list, the iterable is converted internally to a list.
|
| 21 |
+
If it is an iterator it is exhausted.
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
# Alternate implementation:
|
| 25 |
+
# return all(sum(1 if v in c else 0 for c in communities) == 1 for v in G)
|
| 26 |
+
if not isinstance(communities, list):
|
| 27 |
+
communities = list(communities)
|
| 28 |
+
nodes = {n for c in communities for n in c if n in G}
|
| 29 |
+
|
| 30 |
+
return len(G) == len(nodes) == sum(len(c) for c in communities)
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/divisive.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
"edge_betweenness_partition",
|
| 7 |
+
"edge_current_flow_betweenness_partition",
|
| 8 |
+
]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 12 |
+
def edge_betweenness_partition(G, number_of_sets, *, weight=None):
|
| 13 |
+
"""Partition created by iteratively removing the highest edge betweenness edge.
|
| 14 |
+
|
| 15 |
+
This algorithm works by calculating the edge betweenness for all
|
| 16 |
+
edges and removing the edge with the highest value. It is then
|
| 17 |
+
determined whether the graph has been broken into at least
|
| 18 |
+
`number_of_sets` connected components.
|
| 19 |
+
If not the process is repeated.
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
G : NetworkX Graph, DiGraph or MultiGraph
|
| 24 |
+
Graph to be partitioned
|
| 25 |
+
|
| 26 |
+
number_of_sets : int
|
| 27 |
+
Number of sets in the desired partition of the graph
|
| 28 |
+
|
| 29 |
+
weight : key, optional, default=None
|
| 30 |
+
The key to use if using weights for edge betweenness calculation
|
| 31 |
+
|
| 32 |
+
Returns
|
| 33 |
+
-------
|
| 34 |
+
C : list of sets
|
| 35 |
+
Partition of the nodes of G
|
| 36 |
+
|
| 37 |
+
Raises
|
| 38 |
+
------
|
| 39 |
+
NetworkXError
|
| 40 |
+
If number_of_sets is <= 0 or if number_of_sets > len(G)
|
| 41 |
+
|
| 42 |
+
Examples
|
| 43 |
+
--------
|
| 44 |
+
>>> G = nx.karate_club_graph()
|
| 45 |
+
>>> part = nx.community.edge_betweenness_partition(G, 2)
|
| 46 |
+
>>> {0, 1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21} in part
|
| 47 |
+
True
|
| 48 |
+
>>> {
|
| 49 |
+
... 2,
|
| 50 |
+
... 8,
|
| 51 |
+
... 9,
|
| 52 |
+
... 14,
|
| 53 |
+
... 15,
|
| 54 |
+
... 18,
|
| 55 |
+
... 20,
|
| 56 |
+
... 22,
|
| 57 |
+
... 23,
|
| 58 |
+
... 24,
|
| 59 |
+
... 25,
|
| 60 |
+
... 26,
|
| 61 |
+
... 27,
|
| 62 |
+
... 28,
|
| 63 |
+
... 29,
|
| 64 |
+
... 30,
|
| 65 |
+
... 31,
|
| 66 |
+
... 32,
|
| 67 |
+
... 33,
|
| 68 |
+
... } in part
|
| 69 |
+
True
|
| 70 |
+
|
| 71 |
+
See Also
|
| 72 |
+
--------
|
| 73 |
+
edge_current_flow_betweenness_partition
|
| 74 |
+
|
| 75 |
+
Notes
|
| 76 |
+
-----
|
| 77 |
+
This algorithm is fairly slow, as both the calculation of connected
|
| 78 |
+
components and edge betweenness relies on all pairs shortest
|
| 79 |
+
path algorithms. They could potentially be combined to cut down
|
| 80 |
+
on overall computation time.
|
| 81 |
+
|
| 82 |
+
References
|
| 83 |
+
----------
|
| 84 |
+
.. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports
|
| 85 |
+
Volume 486, Issue 3-5 p. 75-174
|
| 86 |
+
http://arxiv.org/abs/0906.0612
|
| 87 |
+
"""
|
| 88 |
+
if number_of_sets <= 0:
|
| 89 |
+
raise nx.NetworkXError("number_of_sets must be >0")
|
| 90 |
+
if number_of_sets == 1:
|
| 91 |
+
return [set(G)]
|
| 92 |
+
if number_of_sets == len(G):
|
| 93 |
+
return [{n} for n in G]
|
| 94 |
+
if number_of_sets > len(G):
|
| 95 |
+
raise nx.NetworkXError("number_of_sets must be <= len(G)")
|
| 96 |
+
|
| 97 |
+
H = G.copy()
|
| 98 |
+
partition = list(nx.connected_components(H))
|
| 99 |
+
while len(partition) < number_of_sets:
|
| 100 |
+
ranking = nx.edge_betweenness_centrality(H, weight=weight)
|
| 101 |
+
edge = max(ranking, key=ranking.get)
|
| 102 |
+
H.remove_edge(*edge)
|
| 103 |
+
partition = list(nx.connected_components(H))
|
| 104 |
+
return partition
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 108 |
+
def edge_current_flow_betweenness_partition(G, number_of_sets, *, weight=None):
|
| 109 |
+
"""Partition created by removing the highest edge current flow betweenness edge.
|
| 110 |
+
|
| 111 |
+
This algorithm works by calculating the edge current flow
|
| 112 |
+
betweenness for all edges and removing the edge with the
|
| 113 |
+
highest value. It is then determined whether the graph has
|
| 114 |
+
been broken into at least `number_of_sets` connected
|
| 115 |
+
components. If not the process is repeated.
|
| 116 |
+
|
| 117 |
+
Parameters
|
| 118 |
+
----------
|
| 119 |
+
G : NetworkX Graph, DiGraph or MultiGraph
|
| 120 |
+
Graph to be partitioned
|
| 121 |
+
|
| 122 |
+
number_of_sets : int
|
| 123 |
+
Number of sets in the desired partition of the graph
|
| 124 |
+
|
| 125 |
+
weight : key, optional (default=None)
|
| 126 |
+
The edge attribute key to use as weights for
|
| 127 |
+
edge current flow betweenness calculations
|
| 128 |
+
|
| 129 |
+
Returns
|
| 130 |
+
-------
|
| 131 |
+
C : list of sets
|
| 132 |
+
Partition of G
|
| 133 |
+
|
| 134 |
+
Raises
|
| 135 |
+
------
|
| 136 |
+
NetworkXError
|
| 137 |
+
If number_of_sets is <= 0 or number_of_sets > len(G)
|
| 138 |
+
|
| 139 |
+
Examples
|
| 140 |
+
--------
|
| 141 |
+
>>> G = nx.karate_club_graph()
|
| 142 |
+
>>> part = nx.community.edge_current_flow_betweenness_partition(G, 2)
|
| 143 |
+
>>> {0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 16, 17, 19, 21} in part
|
| 144 |
+
True
|
| 145 |
+
>>> {8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33} in part
|
| 146 |
+
True
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
See Also
|
| 150 |
+
--------
|
| 151 |
+
edge_betweenness_partition
|
| 152 |
+
|
| 153 |
+
Notes
|
| 154 |
+
-----
|
| 155 |
+
This algorithm is extremely slow, as the recalculation of the edge
|
| 156 |
+
current flow betweenness is extremely slow.
|
| 157 |
+
|
| 158 |
+
References
|
| 159 |
+
----------
|
| 160 |
+
.. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports
|
| 161 |
+
Volume 486, Issue 3-5 p. 75-174
|
| 162 |
+
http://arxiv.org/abs/0906.0612
|
| 163 |
+
"""
|
| 164 |
+
if number_of_sets <= 0:
|
| 165 |
+
raise nx.NetworkXError("number_of_sets must be >0")
|
| 166 |
+
elif number_of_sets == 1:
|
| 167 |
+
return [set(G)]
|
| 168 |
+
elif number_of_sets == len(G):
|
| 169 |
+
return [{n} for n in G]
|
| 170 |
+
elif number_of_sets > len(G):
|
| 171 |
+
raise nx.NetworkXError("number_of_sets must be <= len(G)")
|
| 172 |
+
|
| 173 |
+
rank = functools.partial(
|
| 174 |
+
nx.edge_current_flow_betweenness_centrality, normalized=False, weight=weight
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
# current flow requires a connected network so we track the components explicitly
|
| 178 |
+
H = G.copy()
|
| 179 |
+
partition = list(nx.connected_components(H))
|
| 180 |
+
if len(partition) > 1:
|
| 181 |
+
Hcc_subgraphs = [H.subgraph(cc).copy() for cc in partition]
|
| 182 |
+
else:
|
| 183 |
+
Hcc_subgraphs = [H]
|
| 184 |
+
|
| 185 |
+
ranking = {}
|
| 186 |
+
for Hcc in Hcc_subgraphs:
|
| 187 |
+
ranking.update(rank(Hcc))
|
| 188 |
+
|
| 189 |
+
while len(partition) < number_of_sets:
|
| 190 |
+
edge = max(ranking, key=ranking.get)
|
| 191 |
+
for cc, Hcc in zip(partition, Hcc_subgraphs):
|
| 192 |
+
if edge[0] in cc:
|
| 193 |
+
Hcc.remove_edge(*edge)
|
| 194 |
+
del ranking[edge]
|
| 195 |
+
splitcc_list = list(nx.connected_components(Hcc))
|
| 196 |
+
if len(splitcc_list) > 1:
|
| 197 |
+
# there are 2 connected components. split off smaller one
|
| 198 |
+
cc_new = min(splitcc_list, key=len)
|
| 199 |
+
Hcc_new = Hcc.subgraph(cc_new).copy()
|
| 200 |
+
# update edge rankings for Hcc_new
|
| 201 |
+
newranks = rank(Hcc_new)
|
| 202 |
+
for e, r in newranks.items():
|
| 203 |
+
ranking[e if e in ranking else e[::-1]] = r
|
| 204 |
+
# append new cc and Hcc to their lists.
|
| 205 |
+
partition.append(cc_new)
|
| 206 |
+
Hcc_subgraphs.append(Hcc_new)
|
| 207 |
+
|
| 208 |
+
# leave existing cc and Hcc in their lists, but shrink them
|
| 209 |
+
Hcc.remove_nodes_from(cc_new)
|
| 210 |
+
cc.difference_update(cc_new)
|
| 211 |
+
# update edge rankings for Hcc whether it was split or not
|
| 212 |
+
newranks = rank(Hcc)
|
| 213 |
+
for e, r in newranks.items():
|
| 214 |
+
ranking[e if e in ranking else e[::-1]] = r
|
| 215 |
+
break
|
| 216 |
+
return partition
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/kclique.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = ["k_clique_communities"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@nx._dispatchable
|
| 9 |
+
def k_clique_communities(G, k, cliques=None):
|
| 10 |
+
"""Find k-clique communities in graph using the percolation method.
|
| 11 |
+
|
| 12 |
+
A k-clique community is the union of all cliques of size k that
|
| 13 |
+
can be reached through adjacent (sharing k-1 nodes) k-cliques.
|
| 14 |
+
|
| 15 |
+
Parameters
|
| 16 |
+
----------
|
| 17 |
+
G : NetworkX graph
|
| 18 |
+
|
| 19 |
+
k : int
|
| 20 |
+
Size of smallest clique
|
| 21 |
+
|
| 22 |
+
cliques: list or generator
|
| 23 |
+
Precomputed cliques (use networkx.find_cliques(G))
|
| 24 |
+
|
| 25 |
+
Returns
|
| 26 |
+
-------
|
| 27 |
+
Yields sets of nodes, one for each k-clique community.
|
| 28 |
+
|
| 29 |
+
Examples
|
| 30 |
+
--------
|
| 31 |
+
>>> G = nx.complete_graph(5)
|
| 32 |
+
>>> K5 = nx.convert_node_labels_to_integers(G, first_label=2)
|
| 33 |
+
>>> G.add_edges_from(K5.edges())
|
| 34 |
+
>>> c = list(nx.community.k_clique_communities(G, 4))
|
| 35 |
+
>>> sorted(list(c[0]))
|
| 36 |
+
[0, 1, 2, 3, 4, 5, 6]
|
| 37 |
+
>>> list(nx.community.k_clique_communities(G, 6))
|
| 38 |
+
[]
|
| 39 |
+
|
| 40 |
+
References
|
| 41 |
+
----------
|
| 42 |
+
.. [1] Gergely Palla, Imre Derényi, Illés Farkas1, and Tamás Vicsek,
|
| 43 |
+
Uncovering the overlapping community structure of complex networks
|
| 44 |
+
in nature and society Nature 435, 814-818, 2005,
|
| 45 |
+
doi:10.1038/nature03607
|
| 46 |
+
"""
|
| 47 |
+
if k < 2:
|
| 48 |
+
raise nx.NetworkXError(f"k={k}, k must be greater than 1.")
|
| 49 |
+
if cliques is None:
|
| 50 |
+
cliques = nx.find_cliques(G)
|
| 51 |
+
cliques = [frozenset(c) for c in cliques if len(c) >= k]
|
| 52 |
+
|
| 53 |
+
# First index which nodes are in which cliques
|
| 54 |
+
membership_dict = defaultdict(list)
|
| 55 |
+
for clique in cliques:
|
| 56 |
+
for node in clique:
|
| 57 |
+
membership_dict[node].append(clique)
|
| 58 |
+
|
| 59 |
+
# For each clique, see which adjacent cliques percolate
|
| 60 |
+
perc_graph = nx.Graph()
|
| 61 |
+
perc_graph.add_nodes_from(cliques)
|
| 62 |
+
for clique in cliques:
|
| 63 |
+
for adj_clique in _get_adjacent_cliques(clique, membership_dict):
|
| 64 |
+
if len(clique.intersection(adj_clique)) >= (k - 1):
|
| 65 |
+
perc_graph.add_edge(clique, adj_clique)
|
| 66 |
+
|
| 67 |
+
# Connected components of clique graph with perc edges
|
| 68 |
+
# are the percolated cliques
|
| 69 |
+
for component in nx.connected_components(perc_graph):
|
| 70 |
+
yield (frozenset.union(*component))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _get_adjacent_cliques(clique, membership_dict):
|
| 74 |
+
adjacent_cliques = set()
|
| 75 |
+
for n in clique:
|
| 76 |
+
for adj_clique in membership_dict[n]:
|
| 77 |
+
if clique != adj_clique:
|
| 78 |
+
adjacent_cliques.add(adj_clique)
|
| 79 |
+
return adjacent_cliques
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/label_propagation.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Label propagation community detection algorithms.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from collections import Counter, defaultdict, deque
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx.utils import groups, not_implemented_for, py_random_state
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"label_propagation_communities",
|
| 12 |
+
"asyn_lpa_communities",
|
| 13 |
+
"fast_label_propagation_communities",
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@py_random_state("seed")
|
| 18 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 19 |
+
def fast_label_propagation_communities(G, *, weight=None, seed=None):
|
| 20 |
+
"""Returns communities in `G` as detected by fast label propagation.
|
| 21 |
+
|
| 22 |
+
The fast label propagation algorithm is described in [1]_. The algorithm is
|
| 23 |
+
probabilistic and the found communities may vary in different executions.
|
| 24 |
+
|
| 25 |
+
The algorithm operates as follows. First, the community label of each node is
|
| 26 |
+
set to a unique label. The algorithm then repeatedly updates the labels of
|
| 27 |
+
the nodes to the most frequent label in their neighborhood. In case of ties,
|
| 28 |
+
a random label is chosen from the most frequent labels.
|
| 29 |
+
|
| 30 |
+
The algorithm maintains a queue of nodes that still need to be processed.
|
| 31 |
+
Initially, all nodes are added to the queue in a random order. Then the nodes
|
| 32 |
+
are removed from the queue one by one and processed. If a node updates its label,
|
| 33 |
+
all its neighbors that have a different label are added to the queue (if not
|
| 34 |
+
already in the queue). The algorithm stops when the queue is empty.
|
| 35 |
+
|
| 36 |
+
Parameters
|
| 37 |
+
----------
|
| 38 |
+
G : Graph, DiGraph, MultiGraph, or MultiDiGraph
|
| 39 |
+
Any NetworkX graph.
|
| 40 |
+
|
| 41 |
+
weight : string, or None (default)
|
| 42 |
+
The edge attribute representing a non-negative weight of an edge. If None,
|
| 43 |
+
each edge is assumed to have weight one. The weight of an edge is used in
|
| 44 |
+
determining the frequency with which a label appears among the neighbors of
|
| 45 |
+
a node (edge with weight `w` is equivalent to `w` unweighted edges).
|
| 46 |
+
|
| 47 |
+
seed : integer, random_state, or None (default)
|
| 48 |
+
Indicator of random number generation state. See :ref:`Randomness<randomness>`.
|
| 49 |
+
|
| 50 |
+
Returns
|
| 51 |
+
-------
|
| 52 |
+
communities : iterable
|
| 53 |
+
Iterable of communities given as sets of nodes.
|
| 54 |
+
|
| 55 |
+
Notes
|
| 56 |
+
-----
|
| 57 |
+
Edge directions are ignored for directed graphs.
|
| 58 |
+
Edge weights must be non-negative numbers.
|
| 59 |
+
|
| 60 |
+
References
|
| 61 |
+
----------
|
| 62 |
+
.. [1] Vincent A. Traag & Lovro Šubelj. "Large network community detection by
|
| 63 |
+
fast label propagation." Scientific Reports 13 (2023): 2701.
|
| 64 |
+
https://doi.org/10.1038/s41598-023-29610-z
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
# Queue of nodes to be processed.
|
| 68 |
+
nodes_queue = deque(G)
|
| 69 |
+
seed.shuffle(nodes_queue)
|
| 70 |
+
|
| 71 |
+
# Set of nodes in the queue.
|
| 72 |
+
nodes_set = set(G)
|
| 73 |
+
|
| 74 |
+
# Assign unique label to each node.
|
| 75 |
+
comms = {node: i for i, node in enumerate(G)}
|
| 76 |
+
|
| 77 |
+
while nodes_queue:
|
| 78 |
+
# Remove next node from the queue to process.
|
| 79 |
+
node = nodes_queue.popleft()
|
| 80 |
+
nodes_set.remove(node)
|
| 81 |
+
|
| 82 |
+
# Isolated nodes retain their initial label.
|
| 83 |
+
if G.degree(node) > 0:
|
| 84 |
+
# Compute frequency of labels in node's neighborhood.
|
| 85 |
+
label_freqs = _fast_label_count(G, comms, node, weight)
|
| 86 |
+
max_freq = max(label_freqs.values())
|
| 87 |
+
|
| 88 |
+
# Always sample new label from most frequent labels.
|
| 89 |
+
comm = seed.choice(
|
| 90 |
+
[comm for comm in label_freqs if label_freqs[comm] == max_freq]
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
if comms[node] != comm:
|
| 94 |
+
comms[node] = comm
|
| 95 |
+
|
| 96 |
+
# Add neighbors that have different label to the queue.
|
| 97 |
+
for nbr in nx.all_neighbors(G, node):
|
| 98 |
+
if comms[nbr] != comm and nbr not in nodes_set:
|
| 99 |
+
nodes_queue.append(nbr)
|
| 100 |
+
nodes_set.add(nbr)
|
| 101 |
+
|
| 102 |
+
yield from groups(comms).values()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _fast_label_count(G, comms, node, weight=None):
|
| 106 |
+
"""Computes the frequency of labels in the neighborhood of a node.
|
| 107 |
+
|
| 108 |
+
Returns a dictionary keyed by label to the frequency of that label.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
if weight is None:
|
| 112 |
+
# Unweighted (un)directed simple graph.
|
| 113 |
+
if not G.is_multigraph():
|
| 114 |
+
label_freqs = Counter(map(comms.get, nx.all_neighbors(G, node)))
|
| 115 |
+
|
| 116 |
+
# Unweighted (un)directed multigraph.
|
| 117 |
+
else:
|
| 118 |
+
label_freqs = defaultdict(int)
|
| 119 |
+
for nbr in G[node]:
|
| 120 |
+
label_freqs[comms[nbr]] += len(G[node][nbr])
|
| 121 |
+
|
| 122 |
+
if G.is_directed():
|
| 123 |
+
for nbr in G.pred[node]:
|
| 124 |
+
label_freqs[comms[nbr]] += len(G.pred[node][nbr])
|
| 125 |
+
|
| 126 |
+
else:
|
| 127 |
+
# Weighted undirected simple/multigraph.
|
| 128 |
+
label_freqs = defaultdict(float)
|
| 129 |
+
for _, nbr, w in G.edges(node, data=weight, default=1):
|
| 130 |
+
label_freqs[comms[nbr]] += w
|
| 131 |
+
|
| 132 |
+
# Weighted directed simple/multigraph.
|
| 133 |
+
if G.is_directed():
|
| 134 |
+
for nbr, _, w in G.in_edges(node, data=weight, default=1):
|
| 135 |
+
label_freqs[comms[nbr]] += w
|
| 136 |
+
|
| 137 |
+
return label_freqs
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@py_random_state(2)
|
| 141 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 142 |
+
def asyn_lpa_communities(G, weight=None, seed=None):
|
| 143 |
+
"""Returns communities in `G` as detected by asynchronous label
|
| 144 |
+
propagation.
|
| 145 |
+
|
| 146 |
+
The asynchronous label propagation algorithm is described in
|
| 147 |
+
[1]_. The algorithm is probabilistic and the found communities may
|
| 148 |
+
vary on different executions.
|
| 149 |
+
|
| 150 |
+
The algorithm proceeds as follows. After initializing each node with
|
| 151 |
+
a unique label, the algorithm repeatedly sets the label of a node to
|
| 152 |
+
be the label that appears most frequently among that nodes
|
| 153 |
+
neighbors. The algorithm halts when each node has the label that
|
| 154 |
+
appears most frequently among its neighbors. The algorithm is
|
| 155 |
+
asynchronous because each node is updated without waiting for
|
| 156 |
+
updates on the remaining nodes.
|
| 157 |
+
|
| 158 |
+
This generalized version of the algorithm in [1]_ accepts edge
|
| 159 |
+
weights.
|
| 160 |
+
|
| 161 |
+
Parameters
|
| 162 |
+
----------
|
| 163 |
+
G : Graph
|
| 164 |
+
|
| 165 |
+
weight : string
|
| 166 |
+
The edge attribute representing the weight of an edge.
|
| 167 |
+
If None, each edge is assumed to have weight one. In this
|
| 168 |
+
algorithm, the weight of an edge is used in determining the
|
| 169 |
+
frequency with which a label appears among the neighbors of a
|
| 170 |
+
node: a higher weight means the label appears more often.
|
| 171 |
+
|
| 172 |
+
seed : integer, random_state, or None (default)
|
| 173 |
+
Indicator of random number generation state.
|
| 174 |
+
See :ref:`Randomness<randomness>`.
|
| 175 |
+
|
| 176 |
+
Returns
|
| 177 |
+
-------
|
| 178 |
+
communities : iterable
|
| 179 |
+
Iterable of communities given as sets of nodes.
|
| 180 |
+
|
| 181 |
+
Notes
|
| 182 |
+
-----
|
| 183 |
+
Edge weight attributes must be numerical.
|
| 184 |
+
|
| 185 |
+
References
|
| 186 |
+
----------
|
| 187 |
+
.. [1] Raghavan, Usha Nandini, Réka Albert, and Soundar Kumara. "Near
|
| 188 |
+
linear time algorithm to detect community structures in large-scale
|
| 189 |
+
networks." Physical Review E 76.3 (2007): 036106.
|
| 190 |
+
"""
|
| 191 |
+
|
| 192 |
+
labels = {n: i for i, n in enumerate(G)}
|
| 193 |
+
cont = True
|
| 194 |
+
|
| 195 |
+
while cont:
|
| 196 |
+
cont = False
|
| 197 |
+
nodes = list(G)
|
| 198 |
+
seed.shuffle(nodes)
|
| 199 |
+
|
| 200 |
+
for node in nodes:
|
| 201 |
+
if not G[node]:
|
| 202 |
+
continue
|
| 203 |
+
|
| 204 |
+
# Get label frequencies among adjacent nodes.
|
| 205 |
+
# Depending on the order they are processed in,
|
| 206 |
+
# some nodes will be in iteration t and others in t-1,
|
| 207 |
+
# making the algorithm asynchronous.
|
| 208 |
+
if weight is None:
|
| 209 |
+
# initialising a Counter from an iterator of labels is
|
| 210 |
+
# faster for getting unweighted label frequencies
|
| 211 |
+
label_freq = Counter(map(labels.get, G[node]))
|
| 212 |
+
else:
|
| 213 |
+
# updating a defaultdict is substantially faster
|
| 214 |
+
# for getting weighted label frequencies
|
| 215 |
+
label_freq = defaultdict(float)
|
| 216 |
+
for _, v, wt in G.edges(node, data=weight, default=1):
|
| 217 |
+
label_freq[labels[v]] += wt
|
| 218 |
+
|
| 219 |
+
# Get the labels that appear with maximum frequency.
|
| 220 |
+
max_freq = max(label_freq.values())
|
| 221 |
+
best_labels = [
|
| 222 |
+
label for label, freq in label_freq.items() if freq == max_freq
|
| 223 |
+
]
|
| 224 |
+
|
| 225 |
+
# If the node does not have one of the maximum frequency labels,
|
| 226 |
+
# randomly choose one of them and update the node's label.
|
| 227 |
+
# Continue the iteration as long as at least one node
|
| 228 |
+
# doesn't have a maximum frequency label.
|
| 229 |
+
if labels[node] not in best_labels:
|
| 230 |
+
labels[node] = seed.choice(best_labels)
|
| 231 |
+
cont = True
|
| 232 |
+
|
| 233 |
+
yield from groups(labels).values()
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@not_implemented_for("directed")
|
| 237 |
+
@nx._dispatchable
|
| 238 |
+
def label_propagation_communities(G):
|
| 239 |
+
"""Generates community sets determined by label propagation
|
| 240 |
+
|
| 241 |
+
Finds communities in `G` using a semi-synchronous label propagation
|
| 242 |
+
method [1]_. This method combines the advantages of both the synchronous
|
| 243 |
+
and asynchronous models. Not implemented for directed graphs.
|
| 244 |
+
|
| 245 |
+
Parameters
|
| 246 |
+
----------
|
| 247 |
+
G : graph
|
| 248 |
+
An undirected NetworkX graph.
|
| 249 |
+
|
| 250 |
+
Returns
|
| 251 |
+
-------
|
| 252 |
+
communities : iterable
|
| 253 |
+
A dict_values object that contains a set of nodes for each community.
|
| 254 |
+
|
| 255 |
+
Raises
|
| 256 |
+
------
|
| 257 |
+
NetworkXNotImplemented
|
| 258 |
+
If the graph is directed
|
| 259 |
+
|
| 260 |
+
References
|
| 261 |
+
----------
|
| 262 |
+
.. [1] Cordasco, G., & Gargano, L. (2010, December). Community detection
|
| 263 |
+
via semi-synchronous label propagation algorithms. In Business
|
| 264 |
+
Applications of Social Network Analysis (BASNA), 2010 IEEE International
|
| 265 |
+
Workshop on (pp. 1-8). IEEE.
|
| 266 |
+
"""
|
| 267 |
+
coloring = _color_network(G)
|
| 268 |
+
# Create a unique label for each node in the graph
|
| 269 |
+
labeling = {v: k for k, v in enumerate(G)}
|
| 270 |
+
while not _labeling_complete(labeling, G):
|
| 271 |
+
# Update the labels of every node with the same color.
|
| 272 |
+
for color, nodes in coloring.items():
|
| 273 |
+
for n in nodes:
|
| 274 |
+
_update_label(n, labeling, G)
|
| 275 |
+
|
| 276 |
+
clusters = defaultdict(set)
|
| 277 |
+
for node, label in labeling.items():
|
| 278 |
+
clusters[label].add(node)
|
| 279 |
+
return clusters.values()
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _color_network(G):
|
| 283 |
+
"""Colors the network so that neighboring nodes all have distinct colors.
|
| 284 |
+
|
| 285 |
+
Returns a dict keyed by color to a set of nodes with that color.
|
| 286 |
+
"""
|
| 287 |
+
coloring = {} # color => set(node)
|
| 288 |
+
colors = nx.coloring.greedy_color(G)
|
| 289 |
+
for node, color in colors.items():
|
| 290 |
+
if color in coloring:
|
| 291 |
+
coloring[color].add(node)
|
| 292 |
+
else:
|
| 293 |
+
coloring[color] = {node}
|
| 294 |
+
return coloring
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _labeling_complete(labeling, G):
|
| 298 |
+
"""Determines whether or not LPA is done.
|
| 299 |
+
|
| 300 |
+
Label propagation is complete when all nodes have a label that is
|
| 301 |
+
in the set of highest frequency labels amongst its neighbors.
|
| 302 |
+
|
| 303 |
+
Nodes with no neighbors are considered complete.
|
| 304 |
+
"""
|
| 305 |
+
return all(
|
| 306 |
+
labeling[v] in _most_frequent_labels(v, labeling, G) for v in G if len(G[v]) > 0
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _most_frequent_labels(node, labeling, G):
|
| 311 |
+
"""Returns a set of all labels with maximum frequency in `labeling`.
|
| 312 |
+
|
| 313 |
+
Input `labeling` should be a dict keyed by node to labels.
|
| 314 |
+
"""
|
| 315 |
+
if not G[node]:
|
| 316 |
+
# Nodes with no neighbors are themselves a community and are labeled
|
| 317 |
+
# accordingly, hence the immediate if statement.
|
| 318 |
+
return {labeling[node]}
|
| 319 |
+
|
| 320 |
+
# Compute the frequencies of all neighbors of node
|
| 321 |
+
freqs = Counter(labeling[q] for q in G[node])
|
| 322 |
+
max_freq = max(freqs.values())
|
| 323 |
+
return {label for label, freq in freqs.items() if freq == max_freq}
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _update_label(node, labeling, G):
|
| 327 |
+
"""Updates the label of a node using the Prec-Max tie breaking algorithm
|
| 328 |
+
|
| 329 |
+
The algorithm is explained in: 'Community Detection via Semi-Synchronous
|
| 330 |
+
Label Propagation Algorithms' Cordasco and Gargano, 2011
|
| 331 |
+
"""
|
| 332 |
+
high_labels = _most_frequent_labels(node, labeling, G)
|
| 333 |
+
if len(high_labels) == 1:
|
| 334 |
+
labeling[node] = high_labels.pop()
|
| 335 |
+
elif len(high_labels) > 1:
|
| 336 |
+
# Prec-Max
|
| 337 |
+
if labeling[node] not in high_labels:
|
| 338 |
+
labeling[node] = max(high_labels)
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/leiden.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for detecting communities based on Leiden Community Detection
|
| 2 |
+
algorithm.
|
| 3 |
+
|
| 4 |
+
These functions do not have NetworkX implementations.
|
| 5 |
+
They may only be run with an installable :doc:`backend </backends>`
|
| 6 |
+
that supports them.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import itertools
|
| 10 |
+
from collections import deque
|
| 11 |
+
|
| 12 |
+
import networkx as nx
|
| 13 |
+
from networkx.utils import not_implemented_for, py_random_state
|
| 14 |
+
|
| 15 |
+
__all__ = ["leiden_communities", "leiden_partitions"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@not_implemented_for("directed")
|
| 19 |
+
@py_random_state("seed")
|
| 20 |
+
@nx._dispatchable(edge_attrs="weight", implemented_by_nx=False)
|
| 21 |
+
def leiden_communities(G, weight="weight", resolution=1, max_level=None, seed=None):
|
| 22 |
+
r"""Find a best partition of `G` using Leiden Community Detection (backend required)
|
| 23 |
+
|
| 24 |
+
Leiden Community Detection is an algorithm to extract the community structure
|
| 25 |
+
of a network based on modularity optimization. It is an improvement upon the
|
| 26 |
+
Louvain Community Detection algorithm. See :any:`louvain_communities`.
|
| 27 |
+
|
| 28 |
+
Unlike the Louvain algorithm, it guarantees that communities are well connected in addition
|
| 29 |
+
to being faster and uncovering better partitions. [1]_
|
| 30 |
+
|
| 31 |
+
The algorithm works in 3 phases. On the first phase, it adds the nodes to a queue randomly
|
| 32 |
+
and assigns every node to be in its own community. For each node it tries to find the
|
| 33 |
+
maximum positive modularity gain by moving each node to all of its neighbor communities.
|
| 34 |
+
If a node is moved from its community, it adds to the rear of the queue all neighbors of
|
| 35 |
+
the node that do not belong to the node’s new community and that are not in the queue.
|
| 36 |
+
|
| 37 |
+
The first phase continues until the queue is empty.
|
| 38 |
+
|
| 39 |
+
The second phase consists in refining the partition $P$ obtained from the first phase. It starts
|
| 40 |
+
with a singleton partition $P_{refined}$. Then it merges nodes locally in $P_{refined}$ within
|
| 41 |
+
each community of the partition $P$. Nodes are merged with a community in $P_{refined}$ only if
|
| 42 |
+
both are sufficiently well connected to their community in $P$. This means that after the
|
| 43 |
+
refinement phase is concluded, communities in $P$ sometimes will have been split into multiple
|
| 44 |
+
communities.
|
| 45 |
+
|
| 46 |
+
The third phase consists of aggregating the network by building a new network whose nodes are
|
| 47 |
+
now the communities found in the second phase. However, the non-refined partition is used to create
|
| 48 |
+
an initial partition for the aggregate network.
|
| 49 |
+
|
| 50 |
+
Once this phase is complete it is possible to reapply the first and second phases creating bigger
|
| 51 |
+
communities with increased modularity.
|
| 52 |
+
|
| 53 |
+
The above three phases are executed until no modularity gain is achieved or `max_level` number
|
| 54 |
+
of iterations have been performed.
|
| 55 |
+
|
| 56 |
+
Parameters
|
| 57 |
+
----------
|
| 58 |
+
G : NetworkX graph
|
| 59 |
+
weight : string or None, optional (default="weight")
|
| 60 |
+
The name of an edge attribute that holds the numerical value
|
| 61 |
+
used as a weight. If None then each edge has weight 1.
|
| 62 |
+
resolution : float, optional (default=1)
|
| 63 |
+
If resolution is less than 1, the algorithm favors larger communities.
|
| 64 |
+
Greater than 1 favors smaller communities.
|
| 65 |
+
max_level : int or None, optional (default=None)
|
| 66 |
+
The maximum number of levels (steps of the algorithm) to compute.
|
| 67 |
+
Must be a positive integer or None. If None, then there is no max
|
| 68 |
+
level and the algorithm will run until converged.
|
| 69 |
+
seed : integer, random_state, or None (default)
|
| 70 |
+
Indicator of random number generation state.
|
| 71 |
+
See :ref:`Randomness<randomness>`.
|
| 72 |
+
|
| 73 |
+
Returns
|
| 74 |
+
-------
|
| 75 |
+
list
|
| 76 |
+
A list of disjoint sets (partition of `G`). Each set represents one community.
|
| 77 |
+
All communities together contain all the nodes in `G`.
|
| 78 |
+
|
| 79 |
+
Examples
|
| 80 |
+
--------
|
| 81 |
+
>>> import networkx as nx
|
| 82 |
+
>>> G = nx.petersen_graph()
|
| 83 |
+
>>> nx.community.leiden_communities(G, backend="example_backend") # doctest: +SKIP
|
| 84 |
+
[{2, 3, 5, 7, 8}, {0, 1, 4, 6, 9}]
|
| 85 |
+
|
| 86 |
+
Notes
|
| 87 |
+
-----
|
| 88 |
+
The order in which the nodes are considered can affect the final output. In the algorithm
|
| 89 |
+
the ordering happens using a random shuffle.
|
| 90 |
+
|
| 91 |
+
References
|
| 92 |
+
----------
|
| 93 |
+
.. [1] Traag, V.A., Waltman, L. & van Eck, N.J. From Louvain to Leiden: guaranteeing
|
| 94 |
+
well-connected communities. Sci Rep 9, 5233 (2019). https://doi.org/10.1038/s41598-019-41695-z
|
| 95 |
+
|
| 96 |
+
See Also
|
| 97 |
+
--------
|
| 98 |
+
leiden_partitions
|
| 99 |
+
:any:`louvain_communities`
|
| 100 |
+
"""
|
| 101 |
+
partitions = leiden_partitions(G, weight, resolution, seed)
|
| 102 |
+
if max_level is not None:
|
| 103 |
+
if max_level <= 0:
|
| 104 |
+
raise ValueError("max_level argument must be a positive integer or None")
|
| 105 |
+
partitions = itertools.islice(partitions, max_level)
|
| 106 |
+
final_partition = deque(partitions, maxlen=1)
|
| 107 |
+
return final_partition.pop()
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@not_implemented_for("directed")
|
| 111 |
+
@py_random_state("seed")
|
| 112 |
+
@nx._dispatchable(edge_attrs="weight", implemented_by_nx=False)
|
| 113 |
+
def leiden_partitions(G, weight="weight", resolution=1, seed=None):
|
| 114 |
+
"""Yield partitions for each level of Leiden Community Detection (backend required)
|
| 115 |
+
|
| 116 |
+
Leiden Community Detection is an algorithm to extract the community
|
| 117 |
+
structure of a network based on modularity optimization.
|
| 118 |
+
|
| 119 |
+
The partitions across levels (steps of the algorithm) form a dendrogram
|
| 120 |
+
of communities. A dendrogram is a diagram representing a tree and each
|
| 121 |
+
level represents a partition of the G graph. The top level contains the
|
| 122 |
+
smallest communities and as you traverse to the bottom of the tree the
|
| 123 |
+
communities get bigger and the overall modularity increases making
|
| 124 |
+
the partition better.
|
| 125 |
+
|
| 126 |
+
Each level is generated by executing the three phases of the Leiden Community
|
| 127 |
+
Detection algorithm. See :any:`leiden_communities`.
|
| 128 |
+
|
| 129 |
+
Parameters
|
| 130 |
+
----------
|
| 131 |
+
G : NetworkX graph
|
| 132 |
+
weight : string or None, optional (default="weight")
|
| 133 |
+
The name of an edge attribute that holds the numerical value
|
| 134 |
+
used as a weight. If None then each edge has weight 1.
|
| 135 |
+
resolution : float, optional (default=1)
|
| 136 |
+
If resolution is less than 1, the algorithm favors larger communities.
|
| 137 |
+
Greater than 1 favors smaller communities.
|
| 138 |
+
seed : integer, random_state, or None (default)
|
| 139 |
+
Indicator of random number generation state.
|
| 140 |
+
See :ref:`Randomness<randomness>`.
|
| 141 |
+
|
| 142 |
+
Yields
|
| 143 |
+
------
|
| 144 |
+
list
|
| 145 |
+
A list of disjoint sets (partition of `G`). Each set represents one community.
|
| 146 |
+
All communities together contain all the nodes in `G`. The yielded partitions
|
| 147 |
+
increase modularity with each iteration.
|
| 148 |
+
|
| 149 |
+
References
|
| 150 |
+
----------
|
| 151 |
+
.. [1] Traag, V.A., Waltman, L. & van Eck, N.J. From Louvain to Leiden: guaranteeing
|
| 152 |
+
well-connected communities. Sci Rep 9, 5233 (2019). https://doi.org/10.1038/s41598-019-41695-z
|
| 153 |
+
|
| 154 |
+
See Also
|
| 155 |
+
--------
|
| 156 |
+
leiden_communities
|
| 157 |
+
:any:`louvain_partitions`
|
| 158 |
+
"""
|
| 159 |
+
raise NotImplementedError(
|
| 160 |
+
"'leiden_partitions' is not implemented by networkx. "
|
| 161 |
+
"Please try a different backend."
|
| 162 |
+
)
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/local.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Local Community Detection Algorithms
|
| 3 |
+
|
| 4 |
+
Local Community Detection (LCD) aims to detected one or a few communities
|
| 5 |
+
starting from certain source nodes in the network. This differs from Global
|
| 6 |
+
Community Detection (GCD), which aims to partition an entire network into
|
| 7 |
+
communities.
|
| 8 |
+
|
| 9 |
+
LCD is often useful when only a portion of the graph is known or the
|
| 10 |
+
graph is large enough that GCD is infeasable
|
| 11 |
+
|
| 12 |
+
[1]_ Gives a good introduction and overview of LCD
|
| 13 |
+
|
| 14 |
+
References
|
| 15 |
+
----------
|
| 16 |
+
.. [1] Baltsou, Georgia, Konstantinos Christopoulos, and Konstantinos Tsichlas.
|
| 17 |
+
Local community detection: A survey. IEEE Access 10 (2022): 110701-110726.
|
| 18 |
+
https://doi.org/10.1109/ACCESS.2022.3213980
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
__all__ = ["greedy_source_expansion"]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _clauset_greedy_source_expansion(G, *, source, cutoff=None):
|
| 27 |
+
if cutoff is None:
|
| 28 |
+
cutoff = float("inf")
|
| 29 |
+
C = {source}
|
| 30 |
+
B = {source}
|
| 31 |
+
U = G[source].keys() - C
|
| 32 |
+
T = {frozenset([node, nbr]) for node in B for nbr in G.neighbors(node)}
|
| 33 |
+
I = {edge for edge in T if all(node in C for node in edge)}
|
| 34 |
+
|
| 35 |
+
R_value = 0
|
| 36 |
+
while len(C) < cutoff:
|
| 37 |
+
if not U:
|
| 38 |
+
break
|
| 39 |
+
|
| 40 |
+
max_R = 0
|
| 41 |
+
best_node = None
|
| 42 |
+
best_node_B = best_node_T = best_node_I = set()
|
| 43 |
+
|
| 44 |
+
for v in U:
|
| 45 |
+
R_tmp, B_tmp, T_tmp, I_tmp = _calculate_local_modularity_for_candidate(
|
| 46 |
+
G, v, C, B, T, I
|
| 47 |
+
)
|
| 48 |
+
if R_tmp > max_R:
|
| 49 |
+
max_R = R_tmp
|
| 50 |
+
best_node = v
|
| 51 |
+
best_node_B = B_tmp
|
| 52 |
+
best_node_T = T_tmp
|
| 53 |
+
best_node_I = I_tmp
|
| 54 |
+
|
| 55 |
+
C = C | {best_node}
|
| 56 |
+
U.update(G[best_node].keys() - C)
|
| 57 |
+
U.remove(best_node)
|
| 58 |
+
B = best_node_B
|
| 59 |
+
T = best_node_T
|
| 60 |
+
I = best_node_I
|
| 61 |
+
if max_R < R_value:
|
| 62 |
+
break
|
| 63 |
+
R_value = max_R
|
| 64 |
+
|
| 65 |
+
return C
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _calculate_local_modularity_for_candidate(G, v, C, B, T, I):
|
| 69 |
+
"""
|
| 70 |
+
Compute the local modularity R and updated variables when adding node v to the community.
|
| 71 |
+
|
| 72 |
+
Parameters
|
| 73 |
+
----------
|
| 74 |
+
G : NetworkX graph
|
| 75 |
+
The input graph.
|
| 76 |
+
v : node
|
| 77 |
+
The candidate node to add to the community.
|
| 78 |
+
C : set
|
| 79 |
+
The current set of community nodes.
|
| 80 |
+
B : set
|
| 81 |
+
The current set of boundary nodes.
|
| 82 |
+
T : set of frozenset
|
| 83 |
+
The current set of boundary edges.
|
| 84 |
+
I : set of frozenset
|
| 85 |
+
The current set of internal boundary edges.
|
| 86 |
+
|
| 87 |
+
Returns
|
| 88 |
+
-------
|
| 89 |
+
R_tmp : float
|
| 90 |
+
The local modularity after adding node v.
|
| 91 |
+
B_tmp : set
|
| 92 |
+
The updated set of boundary nodes.
|
| 93 |
+
T_tmp : set of frozenset
|
| 94 |
+
The updated set of boundary edges.
|
| 95 |
+
I_tmp : set of frozenset
|
| 96 |
+
The updated set of internal boundary edges.
|
| 97 |
+
"""
|
| 98 |
+
C_tmp = C | {v}
|
| 99 |
+
B_tmp = B.copy()
|
| 100 |
+
T_tmp = T.copy()
|
| 101 |
+
I_tmp = I.copy()
|
| 102 |
+
removed_B_nodes = set()
|
| 103 |
+
|
| 104 |
+
# Update boundary nodes and edges
|
| 105 |
+
for nbr in G[v]:
|
| 106 |
+
if nbr not in C_tmp:
|
| 107 |
+
# v has nbrs not in the community, so it remains a boundary node
|
| 108 |
+
B_tmp.add(v)
|
| 109 |
+
# Add edge between v and nbr to boundary edges
|
| 110 |
+
T_tmp.add(frozenset([v, nbr]))
|
| 111 |
+
|
| 112 |
+
if nbr in B:
|
| 113 |
+
# Check if nbr should be removed from boundary nodes
|
| 114 |
+
# Go through nbrs nbrs to see if it is still a boundary node
|
| 115 |
+
nbr_still_in_B = any(nbr_nbr not in C_tmp for nbr_nbr in G[nbr])
|
| 116 |
+
if not nbr_still_in_B:
|
| 117 |
+
B_tmp.remove(nbr)
|
| 118 |
+
removed_B_nodes.add(nbr)
|
| 119 |
+
|
| 120 |
+
if nbr in C_tmp:
|
| 121 |
+
# Add edge between v and nbr to internal edges
|
| 122 |
+
I_tmp.add(frozenset([v, nbr]))
|
| 123 |
+
|
| 124 |
+
# Remove edges no longer in the boundary
|
| 125 |
+
for removed_node in removed_B_nodes:
|
| 126 |
+
for removed_node_nbr in G[removed_node]:
|
| 127 |
+
if removed_node_nbr not in B_tmp:
|
| 128 |
+
T_tmp.discard(frozenset([removed_node_nbr, removed_node]))
|
| 129 |
+
I_tmp.discard(frozenset([removed_node_nbr, removed_node]))
|
| 130 |
+
|
| 131 |
+
R_tmp = len(I_tmp) / len(T_tmp) if len(T_tmp) > 0 else 1
|
| 132 |
+
return R_tmp, B_tmp, T_tmp, I_tmp
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
ALGORITHMS = {
|
| 136 |
+
"clauset": _clauset_greedy_source_expansion,
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def greedy_source_expansion(G, *, source, cutoff=None, method="clauset"):
|
| 141 |
+
r"""Find the local community around a source node.
|
| 142 |
+
|
| 143 |
+
Find the local community around a source node using Greedy Source
|
| 144 |
+
Expansion. Greedy Source Expansion generally identifies a local community
|
| 145 |
+
starting from the source node and expands it based on the criteria of the
|
| 146 |
+
chosen algorithm.
|
| 147 |
+
|
| 148 |
+
The algorithm is specified with the `method` keyword argument.
|
| 149 |
+
|
| 150 |
+
* `"clauset"` [1]_ uses local modularity gain to determine local communities.
|
| 151 |
+
The algorithm adds nbring nodes that maximize local modularity to the
|
| 152 |
+
community iteratively, stopping when no additional nodes improve the modularity
|
| 153 |
+
or when a predefined cutoff is reached.
|
| 154 |
+
|
| 155 |
+
Local modularity measures the density of edges within a community relative
|
| 156 |
+
to the total graph. By focusing on local modularity, the algorithm efficiently
|
| 157 |
+
uncovers communities around a specific node without requiring global
|
| 158 |
+
optimization over the entire graph.
|
| 159 |
+
|
| 160 |
+
The algorithm assumes that the graph $G$ consists of a known community $C$ and
|
| 161 |
+
an unknown set of nodes $U$, which are adjacent to $C$ . The boundary of the
|
| 162 |
+
community $B$, consists of nodes in $C$ that have at least one nbr in $U$.
|
| 163 |
+
|
| 164 |
+
Mathematically, the local modularity is expressed as:
|
| 165 |
+
|
| 166 |
+
.. math::
|
| 167 |
+
R = \frac{I}{T}
|
| 168 |
+
|
| 169 |
+
where $T$ is the number of edges with one or more endpoints in $B$, and $I$ is the
|
| 170 |
+
number of those edges with neither endpoint in $U$.
|
| 171 |
+
|
| 172 |
+
Parameters
|
| 173 |
+
----------
|
| 174 |
+
G : NetworkX graph
|
| 175 |
+
The input graph.
|
| 176 |
+
|
| 177 |
+
source : node
|
| 178 |
+
The source node from which the community expansion begins.
|
| 179 |
+
|
| 180 |
+
cutoff : int, optional (default=None)
|
| 181 |
+
The maximum number of nodes to include in the community. If None, the algorithm
|
| 182 |
+
expands until no further modularity gain can be made.
|
| 183 |
+
|
| 184 |
+
method : string, optional (default='clauset')
|
| 185 |
+
The algorithm to use to carry out greedy source expansion.
|
| 186 |
+
Supported options: 'clauset'. Other inputs produce a ValueError
|
| 187 |
+
|
| 188 |
+
Returns
|
| 189 |
+
-------
|
| 190 |
+
set
|
| 191 |
+
A set of nodes representing the local community around the source node.
|
| 192 |
+
|
| 193 |
+
Examples
|
| 194 |
+
--------
|
| 195 |
+
>>> G = nx.karate_club_graph()
|
| 196 |
+
>>> nx.community.greedy_source_expansion(G, source=16)
|
| 197 |
+
{16, 0, 4, 5, 6, 10}
|
| 198 |
+
|
| 199 |
+
Notes
|
| 200 |
+
-----
|
| 201 |
+
This algorithm is designed for detecting local communities around a specific node,
|
| 202 |
+
which is useful for large networks where global community detection is computationally
|
| 203 |
+
expensive.
|
| 204 |
+
|
| 205 |
+
The result of the algorithm may vary based on the structure of the graph, the choice of
|
| 206 |
+
the source node, and the presence of ties between nodes during the greedy expansion process.
|
| 207 |
+
|
| 208 |
+
References
|
| 209 |
+
----------
|
| 210 |
+
.. [1] Clauset, Aaron. Finding local community structure in networks.
|
| 211 |
+
Physical Review E—Statistical, Nonlinear, and Soft Matter Physics 72, no. 2 (2005): 026132.
|
| 212 |
+
https://arxiv.org/pdf/physics/0503036
|
| 213 |
+
|
| 214 |
+
"""
|
| 215 |
+
try:
|
| 216 |
+
algo = ALGORITHMS[method]
|
| 217 |
+
except KeyError as e:
|
| 218 |
+
raise ValueError(f"{method} is not a valid choice for an algorithm.") from e
|
| 219 |
+
|
| 220 |
+
return algo(G, source=source, cutoff=cutoff)
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/louvain.py
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for detecting communities based on Louvain Community Detection
|
| 2 |
+
Algorithm"""
|
| 3 |
+
|
| 4 |
+
import itertools
|
| 5 |
+
from collections import defaultdict, deque
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx.algorithms.community import modularity
|
| 9 |
+
from networkx.utils import py_random_state
|
| 10 |
+
|
| 11 |
+
__all__ = ["louvain_communities", "louvain_partitions"]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@py_random_state("seed")
|
| 15 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 16 |
+
def louvain_communities(
|
| 17 |
+
G, weight="weight", resolution=1, threshold=0.0000001, max_level=None, seed=None
|
| 18 |
+
):
|
| 19 |
+
r"""Find the best partition of a graph using the Louvain Community Detection
|
| 20 |
+
Algorithm.
|
| 21 |
+
|
| 22 |
+
Louvain Community Detection Algorithm is a simple method to extract the community
|
| 23 |
+
structure of a network. This is a heuristic method based on modularity optimization. [1]_
|
| 24 |
+
|
| 25 |
+
The algorithm works in 2 steps. On the first step it assigns every node to be
|
| 26 |
+
in its own community and then for each node it tries to find the maximum positive
|
| 27 |
+
modularity gain by moving each node to all of its neighbor communities. If no positive
|
| 28 |
+
gain is achieved the node remains in its original community.
|
| 29 |
+
|
| 30 |
+
The modularity gain obtained by moving an isolated node $i$ into a community $C$ can
|
| 31 |
+
easily be calculated by the following formula (combining [1]_ [2]_ and some algebra):
|
| 32 |
+
|
| 33 |
+
.. math::
|
| 34 |
+
\Delta Q = \frac{k_{i,in}}{2m} - \gamma\frac{ \Sigma_{tot} \cdot k_i}{2m^2}
|
| 35 |
+
|
| 36 |
+
where $m$ is the size of the graph, $k_{i,in}$ is the sum of the weights of the links
|
| 37 |
+
from $i$ to nodes in $C$, $k_i$ is the sum of the weights of the links incident to node $i$,
|
| 38 |
+
$\Sigma_{tot}$ is the sum of the weights of the links incident to nodes in $C$ and $\gamma$
|
| 39 |
+
is the resolution parameter.
|
| 40 |
+
|
| 41 |
+
For the directed case the modularity gain can be computed using this formula according to [3]_
|
| 42 |
+
|
| 43 |
+
.. math::
|
| 44 |
+
\Delta Q = \frac{k_{i,in}}{m}
|
| 45 |
+
- \gamma\frac{k_i^{out} \cdot\Sigma_{tot}^{in} + k_i^{in} \cdot \Sigma_{tot}^{out}}{m^2}
|
| 46 |
+
|
| 47 |
+
where $k_i^{out}$, $k_i^{in}$ are the outer and inner weighted degrees of node $i$ and
|
| 48 |
+
$\Sigma_{tot}^{in}$, $\Sigma_{tot}^{out}$ are the sum of in-going and out-going links incident
|
| 49 |
+
to nodes in $C$.
|
| 50 |
+
|
| 51 |
+
The first phase continues until no individual move can improve the modularity.
|
| 52 |
+
|
| 53 |
+
The second phase consists in building a new network whose nodes are now the communities
|
| 54 |
+
found in the first phase. To do so, the weights of the links between the new nodes are given by
|
| 55 |
+
the sum of the weight of the links between nodes in the corresponding two communities. Once this
|
| 56 |
+
phase is complete it is possible to reapply the first phase creating bigger communities with
|
| 57 |
+
increased modularity.
|
| 58 |
+
|
| 59 |
+
The above two phases are executed until no modularity gain is achieved (or is less than
|
| 60 |
+
the `threshold`, or until `max_levels` is reached).
|
| 61 |
+
|
| 62 |
+
Be careful with self-loops in the input graph. These are treated as
|
| 63 |
+
previously reduced communities -- as if the process had been started
|
| 64 |
+
in the middle of the algorithm. Large self-loop edge weights thus
|
| 65 |
+
represent strong communities and in practice may be hard to add
|
| 66 |
+
other nodes to. If your input graph edge weights for self-loops
|
| 67 |
+
do not represent already reduced communities you may want to remove
|
| 68 |
+
the self-loops before inputting that graph.
|
| 69 |
+
|
| 70 |
+
Parameters
|
| 71 |
+
----------
|
| 72 |
+
G : NetworkX graph
|
| 73 |
+
weight : string or None, optional (default="weight")
|
| 74 |
+
The name of an edge attribute that holds the numerical value
|
| 75 |
+
used as a weight. If None then each edge has weight 1.
|
| 76 |
+
resolution : float, optional (default=1)
|
| 77 |
+
If resolution is less than 1, the algorithm favors larger communities.
|
| 78 |
+
Greater than 1 favors smaller communities
|
| 79 |
+
threshold : float, optional (default=0.0000001)
|
| 80 |
+
Modularity gain threshold for each level. If the gain of modularity
|
| 81 |
+
between 2 levels of the algorithm is less than the given threshold
|
| 82 |
+
then the algorithm stops and returns the resulting communities.
|
| 83 |
+
max_level : int or None, optional (default=None)
|
| 84 |
+
The maximum number of levels (steps of the algorithm) to compute.
|
| 85 |
+
Must be a positive integer or None. If None, then there is no max
|
| 86 |
+
level and the threshold parameter determines the stopping condition.
|
| 87 |
+
seed : integer, random_state, or None (default)
|
| 88 |
+
Indicator of random number generation state.
|
| 89 |
+
See :ref:`Randomness<randomness>`.
|
| 90 |
+
|
| 91 |
+
Returns
|
| 92 |
+
-------
|
| 93 |
+
list
|
| 94 |
+
A list of sets (partition of `G`). Each set represents one community and contains
|
| 95 |
+
all the nodes that constitute it.
|
| 96 |
+
|
| 97 |
+
Examples
|
| 98 |
+
--------
|
| 99 |
+
>>> import networkx as nx
|
| 100 |
+
>>> G = nx.petersen_graph()
|
| 101 |
+
>>> nx.community.louvain_communities(G, seed=123)
|
| 102 |
+
[{0, 4, 5, 7, 9}, {1, 2, 3, 6, 8}]
|
| 103 |
+
|
| 104 |
+
Notes
|
| 105 |
+
-----
|
| 106 |
+
The order in which the nodes are considered can affect the final output. In the algorithm
|
| 107 |
+
the ordering happens using a random shuffle.
|
| 108 |
+
|
| 109 |
+
References
|
| 110 |
+
----------
|
| 111 |
+
.. [1] Blondel, V.D. et al. Fast unfolding of communities in
|
| 112 |
+
large networks. J. Stat. Mech 10008, 1-12(2008). https://doi.org/10.1088/1742-5468/2008/10/P10008
|
| 113 |
+
.. [2] Traag, V.A., Waltman, L. & van Eck, N.J. From Louvain to Leiden: guaranteeing
|
| 114 |
+
well-connected communities. Sci Rep 9, 5233 (2019). https://doi.org/10.1038/s41598-019-41695-z
|
| 115 |
+
.. [3] Nicolas Dugué, Anthony Perez. Directed Louvain : maximizing modularity in directed networks.
|
| 116 |
+
[Research Report] Université d’Orléans. 2015. hal-01231784. https://hal.archives-ouvertes.fr/hal-01231784
|
| 117 |
+
|
| 118 |
+
See Also
|
| 119 |
+
--------
|
| 120 |
+
louvain_partitions
|
| 121 |
+
:any:`leiden_communities`
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
partitions = louvain_partitions(G, weight, resolution, threshold, seed)
|
| 125 |
+
if max_level is not None:
|
| 126 |
+
if max_level <= 0:
|
| 127 |
+
raise ValueError("max_level argument must be a positive integer or None")
|
| 128 |
+
partitions = itertools.islice(partitions, max_level)
|
| 129 |
+
final_partition = deque(partitions, maxlen=1)
|
| 130 |
+
return final_partition.pop()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@py_random_state("seed")
|
| 134 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 135 |
+
def louvain_partitions(
|
| 136 |
+
G, weight="weight", resolution=1, threshold=0.0000001, seed=None
|
| 137 |
+
):
|
| 138 |
+
"""Yield partitions for each level of the Louvain Community Detection Algorithm
|
| 139 |
+
|
| 140 |
+
Louvain Community Detection Algorithm is a simple method to extract the community
|
| 141 |
+
structure of a network. This is a heuristic method based on modularity optimization. [1]_
|
| 142 |
+
|
| 143 |
+
The partitions at each level (step of the algorithm) form a dendrogram of communities.
|
| 144 |
+
A dendrogram is a diagram representing a tree and each level represents
|
| 145 |
+
a partition of the G graph. The top level contains the smallest communities
|
| 146 |
+
and as you traverse to the bottom of the tree the communities get bigger
|
| 147 |
+
and the overall modularity increases making the partition better.
|
| 148 |
+
|
| 149 |
+
Each level is generated by executing the two phases of the Louvain Community
|
| 150 |
+
Detection Algorithm.
|
| 151 |
+
|
| 152 |
+
Be careful with self-loops in the input graph. These are treated as
|
| 153 |
+
previously reduced communities -- as if the process had been started
|
| 154 |
+
in the middle of the algorithm. Large self-loop edge weights thus
|
| 155 |
+
represent strong communities and in practice may be hard to add
|
| 156 |
+
other nodes to. If your input graph edge weights for self-loops
|
| 157 |
+
do not represent already reduced communities you may want to remove
|
| 158 |
+
the self-loops before inputting that graph.
|
| 159 |
+
|
| 160 |
+
Parameters
|
| 161 |
+
----------
|
| 162 |
+
G : NetworkX graph
|
| 163 |
+
weight : string or None, optional (default="weight")
|
| 164 |
+
The name of an edge attribute that holds the numerical value
|
| 165 |
+
used as a weight. If None then each edge has weight 1.
|
| 166 |
+
resolution : float, optional (default=1)
|
| 167 |
+
If resolution is less than 1, the algorithm favors larger communities.
|
| 168 |
+
Greater than 1 favors smaller communities
|
| 169 |
+
threshold : float, optional (default=0.0000001)
|
| 170 |
+
Modularity gain threshold for each level. If the gain of modularity
|
| 171 |
+
between 2 levels of the algorithm is less than the given threshold
|
| 172 |
+
then the algorithm stops and returns the resulting communities.
|
| 173 |
+
seed : integer, random_state, or None (default)
|
| 174 |
+
Indicator of random number generation state.
|
| 175 |
+
See :ref:`Randomness<randomness>`.
|
| 176 |
+
|
| 177 |
+
Yields
|
| 178 |
+
------
|
| 179 |
+
list
|
| 180 |
+
A list of sets (partition of `G`). Each set represents one community and contains
|
| 181 |
+
all the nodes that constitute it.
|
| 182 |
+
|
| 183 |
+
References
|
| 184 |
+
----------
|
| 185 |
+
.. [1] Blondel, V.D. et al. Fast unfolding of communities in
|
| 186 |
+
large networks. J. Stat. Mech 10008, 1-12(2008)
|
| 187 |
+
|
| 188 |
+
See Also
|
| 189 |
+
--------
|
| 190 |
+
louvain_communities
|
| 191 |
+
:any:`leiden_partitions`
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
partition = [{u} for u in G.nodes()]
|
| 195 |
+
if nx.is_empty(G):
|
| 196 |
+
yield partition
|
| 197 |
+
return
|
| 198 |
+
mod = modularity(G, partition, resolution=resolution, weight=weight)
|
| 199 |
+
is_directed = G.is_directed()
|
| 200 |
+
if G.is_multigraph():
|
| 201 |
+
graph = _convert_multigraph(G, weight, is_directed)
|
| 202 |
+
else:
|
| 203 |
+
graph = G.__class__()
|
| 204 |
+
graph.add_nodes_from(G)
|
| 205 |
+
graph.add_weighted_edges_from(G.edges(data=weight, default=1))
|
| 206 |
+
|
| 207 |
+
m = graph.size(weight="weight")
|
| 208 |
+
partition, inner_partition, improvement = _one_level(
|
| 209 |
+
graph, m, partition, resolution, is_directed, seed
|
| 210 |
+
)
|
| 211 |
+
improvement = True
|
| 212 |
+
while improvement:
|
| 213 |
+
# gh-5901 protect the sets in the yielded list from further manipulation here
|
| 214 |
+
yield [s.copy() for s in partition]
|
| 215 |
+
new_mod = modularity(
|
| 216 |
+
graph, inner_partition, resolution=resolution, weight="weight"
|
| 217 |
+
)
|
| 218 |
+
if new_mod - mod <= threshold:
|
| 219 |
+
return
|
| 220 |
+
mod = new_mod
|
| 221 |
+
graph = _gen_graph(graph, inner_partition)
|
| 222 |
+
partition, inner_partition, improvement = _one_level(
|
| 223 |
+
graph, m, partition, resolution, is_directed, seed
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _one_level(G, m, partition, resolution=1, is_directed=False, seed=None):
|
| 228 |
+
"""Calculate one level of the Louvain partitions tree
|
| 229 |
+
|
| 230 |
+
Parameters
|
| 231 |
+
----------
|
| 232 |
+
G : NetworkX Graph/DiGraph
|
| 233 |
+
The graph from which to detect communities
|
| 234 |
+
m : number
|
| 235 |
+
The size of the graph `G`.
|
| 236 |
+
partition : list of sets of nodes
|
| 237 |
+
A valid partition of the graph `G`
|
| 238 |
+
resolution : positive number
|
| 239 |
+
The resolution parameter for computing the modularity of a partition
|
| 240 |
+
is_directed : bool
|
| 241 |
+
True if `G` is a directed graph.
|
| 242 |
+
seed : integer, random_state, or None (default)
|
| 243 |
+
Indicator of random number generation state.
|
| 244 |
+
See :ref:`Randomness<randomness>`.
|
| 245 |
+
|
| 246 |
+
"""
|
| 247 |
+
node2com = {u: i for i, u in enumerate(G.nodes())}
|
| 248 |
+
inner_partition = [{u} for u in G.nodes()]
|
| 249 |
+
if is_directed:
|
| 250 |
+
in_degrees = dict(G.in_degree(weight="weight"))
|
| 251 |
+
out_degrees = dict(G.out_degree(weight="weight"))
|
| 252 |
+
Stot_in = list(in_degrees.values())
|
| 253 |
+
Stot_out = list(out_degrees.values())
|
| 254 |
+
# Calculate weights for both in and out neighbors without considering self-loops
|
| 255 |
+
nbrs = {}
|
| 256 |
+
for u in G:
|
| 257 |
+
nbrs[u] = defaultdict(float)
|
| 258 |
+
for _, n, wt in G.out_edges(u, data="weight"):
|
| 259 |
+
if u != n:
|
| 260 |
+
nbrs[u][n] += wt
|
| 261 |
+
for n, _, wt in G.in_edges(u, data="weight"):
|
| 262 |
+
if u != n:
|
| 263 |
+
nbrs[u][n] += wt
|
| 264 |
+
else:
|
| 265 |
+
degrees = dict(G.degree(weight="weight"))
|
| 266 |
+
Stot = list(degrees.values())
|
| 267 |
+
nbrs = {u: {v: data["weight"] for v, data in G[u].items() if v != u} for u in G}
|
| 268 |
+
rand_nodes = list(G.nodes)
|
| 269 |
+
seed.shuffle(rand_nodes)
|
| 270 |
+
nb_moves = 1
|
| 271 |
+
improvement = False
|
| 272 |
+
while nb_moves > 0:
|
| 273 |
+
nb_moves = 0
|
| 274 |
+
for u in rand_nodes:
|
| 275 |
+
best_mod = 0
|
| 276 |
+
best_com = node2com[u]
|
| 277 |
+
weights2com = _neighbor_weights(nbrs[u], node2com)
|
| 278 |
+
if is_directed:
|
| 279 |
+
in_degree = in_degrees[u]
|
| 280 |
+
out_degree = out_degrees[u]
|
| 281 |
+
Stot_in[best_com] -= in_degree
|
| 282 |
+
Stot_out[best_com] -= out_degree
|
| 283 |
+
remove_cost = (
|
| 284 |
+
-weights2com[best_com] / m
|
| 285 |
+
+ resolution
|
| 286 |
+
* (out_degree * Stot_in[best_com] + in_degree * Stot_out[best_com])
|
| 287 |
+
/ m**2
|
| 288 |
+
)
|
| 289 |
+
else:
|
| 290 |
+
degree = degrees[u]
|
| 291 |
+
Stot[best_com] -= degree
|
| 292 |
+
remove_cost = -weights2com[best_com] / m + resolution * (
|
| 293 |
+
Stot[best_com] * degree
|
| 294 |
+
) / (2 * m**2)
|
| 295 |
+
for nbr_com, wt in weights2com.items():
|
| 296 |
+
if is_directed:
|
| 297 |
+
gain = (
|
| 298 |
+
remove_cost
|
| 299 |
+
+ wt / m
|
| 300 |
+
- resolution
|
| 301 |
+
* (
|
| 302 |
+
out_degree * Stot_in[nbr_com]
|
| 303 |
+
+ in_degree * Stot_out[nbr_com]
|
| 304 |
+
)
|
| 305 |
+
/ m**2
|
| 306 |
+
)
|
| 307 |
+
else:
|
| 308 |
+
gain = (
|
| 309 |
+
remove_cost
|
| 310 |
+
+ wt / m
|
| 311 |
+
- resolution * (Stot[nbr_com] * degree) / (2 * m**2)
|
| 312 |
+
)
|
| 313 |
+
if gain > best_mod:
|
| 314 |
+
best_mod = gain
|
| 315 |
+
best_com = nbr_com
|
| 316 |
+
if is_directed:
|
| 317 |
+
Stot_in[best_com] += in_degree
|
| 318 |
+
Stot_out[best_com] += out_degree
|
| 319 |
+
else:
|
| 320 |
+
Stot[best_com] += degree
|
| 321 |
+
if best_com != node2com[u]:
|
| 322 |
+
com = G.nodes[u].get("nodes", {u})
|
| 323 |
+
partition[node2com[u]].difference_update(com)
|
| 324 |
+
inner_partition[node2com[u]].remove(u)
|
| 325 |
+
partition[best_com].update(com)
|
| 326 |
+
inner_partition[best_com].add(u)
|
| 327 |
+
improvement = True
|
| 328 |
+
nb_moves += 1
|
| 329 |
+
node2com[u] = best_com
|
| 330 |
+
partition = list(filter(len, partition))
|
| 331 |
+
inner_partition = list(filter(len, inner_partition))
|
| 332 |
+
return partition, inner_partition, improvement
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def _neighbor_weights(nbrs, node2com):
|
| 336 |
+
"""Calculate weights between node and its neighbor communities.
|
| 337 |
+
|
| 338 |
+
Parameters
|
| 339 |
+
----------
|
| 340 |
+
nbrs : dictionary
|
| 341 |
+
Dictionary with nodes' neighbors as keys and their edge weight as value.
|
| 342 |
+
node2com : dictionary
|
| 343 |
+
Dictionary with all graph's nodes as keys and their community index as value.
|
| 344 |
+
|
| 345 |
+
"""
|
| 346 |
+
weights = defaultdict(float)
|
| 347 |
+
for nbr, wt in nbrs.items():
|
| 348 |
+
weights[node2com[nbr]] += wt
|
| 349 |
+
return weights
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def _gen_graph(G, partition):
|
| 353 |
+
"""Generate a new graph based on the partitions of a given graph"""
|
| 354 |
+
H = G.__class__()
|
| 355 |
+
node2com = {}
|
| 356 |
+
for i, part in enumerate(partition):
|
| 357 |
+
nodes = set()
|
| 358 |
+
for node in part:
|
| 359 |
+
node2com[node] = i
|
| 360 |
+
nodes.update(G.nodes[node].get("nodes", {node}))
|
| 361 |
+
H.add_node(i, nodes=nodes)
|
| 362 |
+
|
| 363 |
+
for node1, node2, wt in G.edges(data=True):
|
| 364 |
+
wt = wt["weight"]
|
| 365 |
+
com1 = node2com[node1]
|
| 366 |
+
com2 = node2com[node2]
|
| 367 |
+
temp = H.get_edge_data(com1, com2, {"weight": 0})["weight"]
|
| 368 |
+
H.add_edge(com1, com2, weight=wt + temp)
|
| 369 |
+
return H
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def _convert_multigraph(G, weight, is_directed):
|
| 373 |
+
"""Convert a Multigraph to normal Graph"""
|
| 374 |
+
if is_directed:
|
| 375 |
+
H = nx.DiGraph()
|
| 376 |
+
else:
|
| 377 |
+
H = nx.Graph()
|
| 378 |
+
H.add_nodes_from(G)
|
| 379 |
+
for u, v, wt in G.edges(data=weight, default=1):
|
| 380 |
+
if H.has_edge(u, v):
|
| 381 |
+
H[u][v]["weight"] += wt
|
| 382 |
+
else:
|
| 383 |
+
H.add_edge(u, v, weight=wt)
|
| 384 |
+
return H
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/lukes.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lukes Algorithm for exact optimal weighted tree partitioning."""
|
| 2 |
+
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
from random import choice
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx.utils import not_implemented_for
|
| 9 |
+
|
| 10 |
+
__all__ = ["lukes_partitioning"]
|
| 11 |
+
|
| 12 |
+
D_EDGE_W = "weight"
|
| 13 |
+
D_EDGE_VALUE = 1.0
|
| 14 |
+
D_NODE_W = "weight"
|
| 15 |
+
D_NODE_VALUE = 1
|
| 16 |
+
PKEY = "partitions"
|
| 17 |
+
CLUSTER_EVAL_CACHE_SIZE = 2048
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _split_n_from(n, min_size_of_first_part):
|
| 21 |
+
# splits j in two parts of which the first is at least
|
| 22 |
+
# the second argument
|
| 23 |
+
assert n >= min_size_of_first_part
|
| 24 |
+
for p1 in range(min_size_of_first_part, n + 1):
|
| 25 |
+
yield p1, n - p1
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@nx._dispatchable(node_attrs="node_weight", edge_attrs="edge_weight")
|
| 29 |
+
def lukes_partitioning(G, max_size, node_weight=None, edge_weight=None):
|
| 30 |
+
"""Optimal partitioning of a weighted tree using the Lukes algorithm.
|
| 31 |
+
|
| 32 |
+
This algorithm partitions a connected, acyclic graph featuring integer
|
| 33 |
+
node weights and float edge weights. The resulting clusters are such
|
| 34 |
+
that the total weight of the nodes in each cluster does not exceed
|
| 35 |
+
max_size and that the weight of the edges that are cut by the partition
|
| 36 |
+
is minimum. The algorithm is based on [1]_.
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
G : NetworkX graph
|
| 41 |
+
|
| 42 |
+
max_size : int
|
| 43 |
+
Maximum weight a partition can have in terms of sum of
|
| 44 |
+
node_weight for all nodes in the partition
|
| 45 |
+
|
| 46 |
+
edge_weight : key
|
| 47 |
+
Edge data key to use as weight. If None, the weights are all
|
| 48 |
+
set to one.
|
| 49 |
+
|
| 50 |
+
node_weight : key
|
| 51 |
+
Node data key to use as weight. If None, the weights are all
|
| 52 |
+
set to one. The data must be int.
|
| 53 |
+
|
| 54 |
+
Returns
|
| 55 |
+
-------
|
| 56 |
+
partition : list
|
| 57 |
+
A list of sets of nodes representing the clusters of the
|
| 58 |
+
partition.
|
| 59 |
+
|
| 60 |
+
Raises
|
| 61 |
+
------
|
| 62 |
+
NotATree
|
| 63 |
+
If G is not a tree.
|
| 64 |
+
TypeError
|
| 65 |
+
If any of the values of node_weight is not int.
|
| 66 |
+
|
| 67 |
+
References
|
| 68 |
+
----------
|
| 69 |
+
.. [1] Lukes, J. A. (1974).
|
| 70 |
+
"Efficient Algorithm for the Partitioning of Trees."
|
| 71 |
+
IBM Journal of Research and Development, 18(3), 217–224.
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
# First sanity check and tree preparation
|
| 75 |
+
if not nx.is_tree(G):
|
| 76 |
+
raise nx.NotATree("lukes_partitioning works only on trees")
|
| 77 |
+
else:
|
| 78 |
+
if nx.is_directed(G):
|
| 79 |
+
root = [n for n, d in G.in_degree() if d == 0]
|
| 80 |
+
assert len(root) == 1
|
| 81 |
+
root = root[0]
|
| 82 |
+
t_G = deepcopy(G)
|
| 83 |
+
else:
|
| 84 |
+
root = choice(list(G.nodes))
|
| 85 |
+
# this has the desirable side effect of not inheriting attributes
|
| 86 |
+
t_G = nx.dfs_tree(G, root)
|
| 87 |
+
|
| 88 |
+
# Since we do not want to screw up the original graph,
|
| 89 |
+
# if we have a blank attribute, we make a deepcopy
|
| 90 |
+
if edge_weight is None or node_weight is None:
|
| 91 |
+
safe_G = deepcopy(G)
|
| 92 |
+
if edge_weight is None:
|
| 93 |
+
nx.set_edge_attributes(safe_G, D_EDGE_VALUE, D_EDGE_W)
|
| 94 |
+
edge_weight = D_EDGE_W
|
| 95 |
+
if node_weight is None:
|
| 96 |
+
nx.set_node_attributes(safe_G, D_NODE_VALUE, D_NODE_W)
|
| 97 |
+
node_weight = D_NODE_W
|
| 98 |
+
else:
|
| 99 |
+
safe_G = G
|
| 100 |
+
|
| 101 |
+
# Second sanity check
|
| 102 |
+
# The values of node_weight MUST BE int.
|
| 103 |
+
# I cannot see any room for duck typing without incurring serious
|
| 104 |
+
# danger of subtle bugs.
|
| 105 |
+
all_n_attr = nx.get_node_attributes(safe_G, node_weight).values()
|
| 106 |
+
for x in all_n_attr:
|
| 107 |
+
if not isinstance(x, int):
|
| 108 |
+
raise TypeError(
|
| 109 |
+
"lukes_partitioning needs integer "
|
| 110 |
+
f"values for node_weight ({node_weight})"
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# SUBROUTINES -----------------------
|
| 114 |
+
# these functions are defined here for two reasons:
|
| 115 |
+
# - brevity: we can leverage global "safe_G"
|
| 116 |
+
# - caching: signatures are hashable
|
| 117 |
+
|
| 118 |
+
@not_implemented_for("undirected")
|
| 119 |
+
# this is intended to be called only on t_G
|
| 120 |
+
def _leaves(gr):
|
| 121 |
+
for x in gr.nodes:
|
| 122 |
+
if not nx.descendants(gr, x):
|
| 123 |
+
yield x
|
| 124 |
+
|
| 125 |
+
@not_implemented_for("undirected")
|
| 126 |
+
def _a_parent_of_leaves_only(gr):
|
| 127 |
+
tleaves = set(_leaves(gr))
|
| 128 |
+
for n in set(gr.nodes) - tleaves:
|
| 129 |
+
if all(x in tleaves for x in nx.descendants(gr, n)):
|
| 130 |
+
return n
|
| 131 |
+
|
| 132 |
+
@lru_cache(CLUSTER_EVAL_CACHE_SIZE)
|
| 133 |
+
def _value_of_cluster(cluster):
|
| 134 |
+
valid_edges = [e for e in safe_G.edges if e[0] in cluster and e[1] in cluster]
|
| 135 |
+
return sum(safe_G.edges[e][edge_weight] for e in valid_edges)
|
| 136 |
+
|
| 137 |
+
def _value_of_partition(partition):
|
| 138 |
+
return sum(_value_of_cluster(frozenset(c)) for c in partition)
|
| 139 |
+
|
| 140 |
+
@lru_cache(CLUSTER_EVAL_CACHE_SIZE)
|
| 141 |
+
def _weight_of_cluster(cluster):
|
| 142 |
+
return sum(safe_G.nodes[n][node_weight] for n in cluster)
|
| 143 |
+
|
| 144 |
+
def _pivot(partition, node):
|
| 145 |
+
ccx = [c for c in partition if node in c]
|
| 146 |
+
assert len(ccx) == 1
|
| 147 |
+
return ccx[0]
|
| 148 |
+
|
| 149 |
+
def _concatenate_or_merge(partition_1, partition_2, x, i, ref_weight):
|
| 150 |
+
ccx = _pivot(partition_1, x)
|
| 151 |
+
cci = _pivot(partition_2, i)
|
| 152 |
+
merged_xi = ccx.union(cci)
|
| 153 |
+
|
| 154 |
+
# We first check if we can do the merge.
|
| 155 |
+
# If so, we do the actual calculations, otherwise we concatenate
|
| 156 |
+
if _weight_of_cluster(frozenset(merged_xi)) <= ref_weight:
|
| 157 |
+
cp1 = list(filter(lambda x: x != ccx, partition_1))
|
| 158 |
+
cp2 = list(filter(lambda x: x != cci, partition_2))
|
| 159 |
+
|
| 160 |
+
option_2 = [merged_xi] + cp1 + cp2
|
| 161 |
+
return option_2, _value_of_partition(option_2)
|
| 162 |
+
else:
|
| 163 |
+
option_1 = partition_1 + partition_2
|
| 164 |
+
return option_1, _value_of_partition(option_1)
|
| 165 |
+
|
| 166 |
+
# INITIALIZATION -----------------------
|
| 167 |
+
leaves = set(_leaves(t_G))
|
| 168 |
+
for lv in leaves:
|
| 169 |
+
t_G.nodes[lv][PKEY] = {}
|
| 170 |
+
slot = safe_G.nodes[lv][node_weight]
|
| 171 |
+
t_G.nodes[lv][PKEY][slot] = [{lv}]
|
| 172 |
+
t_G.nodes[lv][PKEY][0] = [{lv}]
|
| 173 |
+
|
| 174 |
+
for inner in [x for x in t_G.nodes if x not in leaves]:
|
| 175 |
+
t_G.nodes[inner][PKEY] = {}
|
| 176 |
+
slot = safe_G.nodes[inner][node_weight]
|
| 177 |
+
t_G.nodes[inner][PKEY][slot] = [{inner}]
|
| 178 |
+
nx._clear_cache(t_G)
|
| 179 |
+
|
| 180 |
+
# CORE ALGORITHM -----------------------
|
| 181 |
+
while True:
|
| 182 |
+
x_node = _a_parent_of_leaves_only(t_G)
|
| 183 |
+
weight_of_x = safe_G.nodes[x_node][node_weight]
|
| 184 |
+
best_value = 0
|
| 185 |
+
best_partition = None
|
| 186 |
+
bp_buffer = {}
|
| 187 |
+
x_descendants = nx.descendants(t_G, x_node)
|
| 188 |
+
for i_node in x_descendants:
|
| 189 |
+
for j in range(weight_of_x, max_size + 1):
|
| 190 |
+
for a, b in _split_n_from(j, weight_of_x):
|
| 191 |
+
if (
|
| 192 |
+
a not in t_G.nodes[x_node][PKEY]
|
| 193 |
+
or b not in t_G.nodes[i_node][PKEY]
|
| 194 |
+
):
|
| 195 |
+
# it's not possible to form this particular weight sum
|
| 196 |
+
continue
|
| 197 |
+
|
| 198 |
+
part1 = t_G.nodes[x_node][PKEY][a]
|
| 199 |
+
part2 = t_G.nodes[i_node][PKEY][b]
|
| 200 |
+
part, value = _concatenate_or_merge(part1, part2, x_node, i_node, j)
|
| 201 |
+
|
| 202 |
+
if j not in bp_buffer or bp_buffer[j][1] < value:
|
| 203 |
+
# we annotate in the buffer the best partition for j
|
| 204 |
+
bp_buffer[j] = part, value
|
| 205 |
+
|
| 206 |
+
# we also keep track of the overall best partition
|
| 207 |
+
if best_value <= value:
|
| 208 |
+
best_value = value
|
| 209 |
+
best_partition = part
|
| 210 |
+
|
| 211 |
+
# as illustrated in Lukes, once we finished a child, we can
|
| 212 |
+
# discharge the partitions we found into the graph
|
| 213 |
+
# (the key phrase is make all x == x')
|
| 214 |
+
# so that they are used by the subsequent children
|
| 215 |
+
for w, (best_part_for_vl, vl) in bp_buffer.items():
|
| 216 |
+
t_G.nodes[x_node][PKEY][w] = best_part_for_vl
|
| 217 |
+
bp_buffer.clear()
|
| 218 |
+
|
| 219 |
+
# the absolute best partition for this node
|
| 220 |
+
# across all weights has to be stored at 0
|
| 221 |
+
t_G.nodes[x_node][PKEY][0] = best_partition
|
| 222 |
+
t_G.remove_nodes_from(x_descendants)
|
| 223 |
+
|
| 224 |
+
if x_node == root:
|
| 225 |
+
# the 0-labeled partition of root
|
| 226 |
+
# is the optimal one for the whole tree
|
| 227 |
+
return t_G.nodes[root][PKEY][0]
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/modularity_max.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for detecting communities based on modularity."""
|
| 2 |
+
|
| 3 |
+
import random
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from copy import deepcopy
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx.algorithms.community.quality import modularity
|
| 9 |
+
from networkx.utils.mapped_queue import MappedQueue
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"greedy_modularity_communities",
|
| 13 |
+
"naive_greedy_modularity_communities",
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _greedy_modularity_communities_generator(G, weight=None, resolution=1):
|
| 18 |
+
r"""Yield community partitions of G and the modularity change at each step.
|
| 19 |
+
|
| 20 |
+
This function performs Clauset-Newman-Moore greedy modularity maximization [2]_
|
| 21 |
+
At each step of the process it yields the change in modularity that will occur in
|
| 22 |
+
the next step followed by yielding the new community partition after that step.
|
| 23 |
+
|
| 24 |
+
Greedy modularity maximization begins with each node in its own community
|
| 25 |
+
and repeatedly joins the pair of communities that lead to the largest
|
| 26 |
+
modularity until one community contains all nodes (the partition has one set).
|
| 27 |
+
|
| 28 |
+
This function maximizes the generalized modularity, where `resolution`
|
| 29 |
+
is the resolution parameter, often expressed as $\gamma$.
|
| 30 |
+
See :func:`~networkx.algorithms.community.quality.modularity`.
|
| 31 |
+
|
| 32 |
+
Parameters
|
| 33 |
+
----------
|
| 34 |
+
G : NetworkX graph
|
| 35 |
+
|
| 36 |
+
weight : string or None, optional (default=None)
|
| 37 |
+
The name of an edge attribute that holds the numerical value used
|
| 38 |
+
as a weight. If None, then each edge has weight 1.
|
| 39 |
+
The degree is the sum of the edge weights adjacent to the node.
|
| 40 |
+
|
| 41 |
+
resolution : float (default=1)
|
| 42 |
+
If resolution is less than 1, modularity favors larger communities.
|
| 43 |
+
Greater than 1 favors smaller communities.
|
| 44 |
+
|
| 45 |
+
Yields
|
| 46 |
+
------
|
| 47 |
+
Alternating yield statements produce the following two objects:
|
| 48 |
+
|
| 49 |
+
communities: dict_values
|
| 50 |
+
A dict_values of frozensets of nodes, one for each community.
|
| 51 |
+
This represents a partition of the nodes of the graph into communities.
|
| 52 |
+
The first yield is the partition with each node in its own community.
|
| 53 |
+
|
| 54 |
+
dq: float
|
| 55 |
+
The change in modularity when merging the next two communities
|
| 56 |
+
that leads to the largest modularity.
|
| 57 |
+
|
| 58 |
+
See Also
|
| 59 |
+
--------
|
| 60 |
+
modularity
|
| 61 |
+
|
| 62 |
+
References
|
| 63 |
+
----------
|
| 64 |
+
.. [1] Newman, M. E. J. "Networks: An Introduction", page 224
|
| 65 |
+
Oxford University Press 2011.
|
| 66 |
+
.. [2] Clauset, A., Newman, M. E., & Moore, C.
|
| 67 |
+
"Finding community structure in very large networks."
|
| 68 |
+
Physical Review E 70(6), 2004.
|
| 69 |
+
.. [3] Reichardt and Bornholdt "Statistical Mechanics of Community
|
| 70 |
+
Detection" Phys. Rev. E74, 2006.
|
| 71 |
+
.. [4] Newman, M. E. J."Analysis of weighted networks"
|
| 72 |
+
Physical Review E 70(5 Pt 2):056131, 2004.
|
| 73 |
+
"""
|
| 74 |
+
directed = G.is_directed()
|
| 75 |
+
N = G.number_of_nodes()
|
| 76 |
+
|
| 77 |
+
# Count edges (or the sum of edge-weights for weighted graphs)
|
| 78 |
+
m = G.size(weight)
|
| 79 |
+
q0 = 1 / m
|
| 80 |
+
|
| 81 |
+
# Calculate degrees (notation from the papers)
|
| 82 |
+
# a : the fraction of (weighted) out-degree for each node
|
| 83 |
+
# b : the fraction of (weighted) in-degree for each node
|
| 84 |
+
if directed:
|
| 85 |
+
a = {node: deg_out * q0 for node, deg_out in G.out_degree(weight=weight)}
|
| 86 |
+
b = {node: deg_in * q0 for node, deg_in in G.in_degree(weight=weight)}
|
| 87 |
+
else:
|
| 88 |
+
a = b = {node: deg * q0 * 0.5 for node, deg in G.degree(weight=weight)}
|
| 89 |
+
|
| 90 |
+
# this preliminary step collects the edge weights for each node pair
|
| 91 |
+
# It handles multigraph and digraph and works fine for graph.
|
| 92 |
+
dq_dict = defaultdict(lambda: defaultdict(float))
|
| 93 |
+
for u, v, wt in G.edges(data=weight, default=1):
|
| 94 |
+
if u == v:
|
| 95 |
+
continue
|
| 96 |
+
dq_dict[u][v] += wt
|
| 97 |
+
dq_dict[v][u] += wt
|
| 98 |
+
|
| 99 |
+
# now scale and subtract the expected edge-weights term
|
| 100 |
+
for u, nbrdict in dq_dict.items():
|
| 101 |
+
for v, wt in nbrdict.items():
|
| 102 |
+
dq_dict[u][v] = q0 * wt - resolution * (a[u] * b[v] + b[u] * a[v])
|
| 103 |
+
|
| 104 |
+
# Use -dq to get a max_heap instead of a min_heap
|
| 105 |
+
# dq_heap holds a heap for each node's neighbors
|
| 106 |
+
dq_heap = {u: MappedQueue({(u, v): -dq for v, dq in dq_dict[u].items()}) for u in G}
|
| 107 |
+
# H -> all_dq_heap holds a heap with the best items for each node
|
| 108 |
+
H = MappedQueue([dq_heap[n].heap[0] for n in G if len(dq_heap[n]) > 0])
|
| 109 |
+
|
| 110 |
+
# Initialize single-node communities
|
| 111 |
+
communities = {n: frozenset([n]) for n in G}
|
| 112 |
+
yield communities.values()
|
| 113 |
+
|
| 114 |
+
# Merge the two communities that lead to the largest modularity
|
| 115 |
+
while len(H) > 1:
|
| 116 |
+
# Find best merge
|
| 117 |
+
# Remove from heap of row maxes
|
| 118 |
+
# Ties will be broken by choosing the pair with lowest min community id
|
| 119 |
+
try:
|
| 120 |
+
negdq, u, v = H.pop()
|
| 121 |
+
except IndexError:
|
| 122 |
+
break
|
| 123 |
+
dq = -negdq
|
| 124 |
+
yield dq
|
| 125 |
+
# Remove best merge from row u heap
|
| 126 |
+
dq_heap[u].pop()
|
| 127 |
+
# Push new row max onto H
|
| 128 |
+
if len(dq_heap[u]) > 0:
|
| 129 |
+
H.push(dq_heap[u].heap[0])
|
| 130 |
+
# If this element was also at the root of row v, we need to remove the
|
| 131 |
+
# duplicate entry from H
|
| 132 |
+
if dq_heap[v].heap[0] == (v, u):
|
| 133 |
+
H.remove((v, u))
|
| 134 |
+
# Remove best merge from row v heap
|
| 135 |
+
dq_heap[v].remove((v, u))
|
| 136 |
+
# Push new row max onto H
|
| 137 |
+
if len(dq_heap[v]) > 0:
|
| 138 |
+
H.push(dq_heap[v].heap[0])
|
| 139 |
+
else:
|
| 140 |
+
# Duplicate wasn't in H, just remove from row v heap
|
| 141 |
+
dq_heap[v].remove((v, u))
|
| 142 |
+
|
| 143 |
+
# Perform merge
|
| 144 |
+
communities[v] = frozenset(communities[u] | communities[v])
|
| 145 |
+
del communities[u]
|
| 146 |
+
|
| 147 |
+
# Get neighbor communities connected to the merged communities
|
| 148 |
+
u_nbrs = set(dq_dict[u])
|
| 149 |
+
v_nbrs = set(dq_dict[v])
|
| 150 |
+
all_nbrs = (u_nbrs | v_nbrs) - {u, v}
|
| 151 |
+
both_nbrs = u_nbrs & v_nbrs
|
| 152 |
+
# Update dq for merge of u into v
|
| 153 |
+
for w in all_nbrs:
|
| 154 |
+
# Calculate new dq value
|
| 155 |
+
if w in both_nbrs:
|
| 156 |
+
dq_vw = dq_dict[v][w] + dq_dict[u][w]
|
| 157 |
+
elif w in v_nbrs:
|
| 158 |
+
dq_vw = dq_dict[v][w] - resolution * (a[u] * b[w] + a[w] * b[u])
|
| 159 |
+
else: # w in u_nbrs
|
| 160 |
+
dq_vw = dq_dict[u][w] - resolution * (a[v] * b[w] + a[w] * b[v])
|
| 161 |
+
# Update rows v and w
|
| 162 |
+
for row, col in [(v, w), (w, v)]:
|
| 163 |
+
dq_heap_row = dq_heap[row]
|
| 164 |
+
# Update dict for v,w only (u is removed below)
|
| 165 |
+
dq_dict[row][col] = dq_vw
|
| 166 |
+
# Save old max of per-row heap
|
| 167 |
+
if len(dq_heap_row) > 0:
|
| 168 |
+
d_oldmax = dq_heap_row.heap[0]
|
| 169 |
+
else:
|
| 170 |
+
d_oldmax = None
|
| 171 |
+
# Add/update heaps
|
| 172 |
+
d = (row, col)
|
| 173 |
+
d_negdq = -dq_vw
|
| 174 |
+
# Save old value for finding heap index
|
| 175 |
+
if w in v_nbrs:
|
| 176 |
+
# Update existing element in per-row heap
|
| 177 |
+
dq_heap_row.update(d, d, priority=d_negdq)
|
| 178 |
+
else:
|
| 179 |
+
# We're creating a new nonzero element, add to heap
|
| 180 |
+
dq_heap_row.push(d, priority=d_negdq)
|
| 181 |
+
# Update heap of row maxes if necessary
|
| 182 |
+
if d_oldmax is None:
|
| 183 |
+
# No entries previously in this row, push new max
|
| 184 |
+
H.push(d, priority=d_negdq)
|
| 185 |
+
else:
|
| 186 |
+
# We've updated an entry in this row, has the max changed?
|
| 187 |
+
row_max = dq_heap_row.heap[0]
|
| 188 |
+
if d_oldmax != row_max or d_oldmax.priority != row_max.priority:
|
| 189 |
+
H.update(d_oldmax, row_max)
|
| 190 |
+
|
| 191 |
+
# Remove row/col u from dq_dict matrix
|
| 192 |
+
for w in dq_dict[u]:
|
| 193 |
+
# Remove from dict
|
| 194 |
+
dq_old = dq_dict[w][u]
|
| 195 |
+
del dq_dict[w][u]
|
| 196 |
+
# Remove from heaps if we haven't already
|
| 197 |
+
if w != v:
|
| 198 |
+
# Remove both row and column
|
| 199 |
+
for row, col in [(w, u), (u, w)]:
|
| 200 |
+
dq_heap_row = dq_heap[row]
|
| 201 |
+
# Check if replaced dq is row max
|
| 202 |
+
d_old = (row, col)
|
| 203 |
+
if dq_heap_row.heap[0] == d_old:
|
| 204 |
+
# Update per-row heap and heap of row maxes
|
| 205 |
+
dq_heap_row.remove(d_old)
|
| 206 |
+
H.remove(d_old)
|
| 207 |
+
# Update row max
|
| 208 |
+
if len(dq_heap_row) > 0:
|
| 209 |
+
H.push(dq_heap_row.heap[0])
|
| 210 |
+
else:
|
| 211 |
+
# Only update per-row heap
|
| 212 |
+
dq_heap_row.remove(d_old)
|
| 213 |
+
|
| 214 |
+
del dq_dict[u]
|
| 215 |
+
# Mark row u as deleted, but keep placeholder
|
| 216 |
+
dq_heap[u] = MappedQueue()
|
| 217 |
+
# Merge u into v and update a
|
| 218 |
+
a[v] += a[u]
|
| 219 |
+
a[u] = 0
|
| 220 |
+
if directed:
|
| 221 |
+
b[v] += b[u]
|
| 222 |
+
b[u] = 0
|
| 223 |
+
|
| 224 |
+
yield communities.values()
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 228 |
+
def greedy_modularity_communities(
|
| 229 |
+
G,
|
| 230 |
+
weight=None,
|
| 231 |
+
resolution=1,
|
| 232 |
+
cutoff=1,
|
| 233 |
+
best_n=None,
|
| 234 |
+
):
|
| 235 |
+
r"""Find communities in G using greedy modularity maximization.
|
| 236 |
+
|
| 237 |
+
This function uses Clauset-Newman-Moore greedy modularity maximization [2]_
|
| 238 |
+
to find the community partition with the largest modularity.
|
| 239 |
+
|
| 240 |
+
Greedy modularity maximization begins with each node in its own community
|
| 241 |
+
and repeatedly joins the pair of communities that lead to the largest
|
| 242 |
+
modularity until no further increase in modularity is possible (a maximum).
|
| 243 |
+
Two keyword arguments adjust the stopping condition. `cutoff` is a lower
|
| 244 |
+
limit on the number of communities so you can stop the process before
|
| 245 |
+
reaching a maximum (used to save computation time). `best_n` is an upper
|
| 246 |
+
limit on the number of communities so you can make the process continue
|
| 247 |
+
until at most n communities remain even if the maximum modularity occurs
|
| 248 |
+
for more. To obtain exactly n communities, set both `cutoff` and `best_n` to n.
|
| 249 |
+
|
| 250 |
+
This function maximizes the generalized modularity, where `resolution`
|
| 251 |
+
is the resolution parameter, often expressed as $\gamma$.
|
| 252 |
+
See :func:`~networkx.algorithms.community.quality.modularity`.
|
| 253 |
+
|
| 254 |
+
Parameters
|
| 255 |
+
----------
|
| 256 |
+
G : NetworkX graph
|
| 257 |
+
|
| 258 |
+
weight : string or None, optional (default=None)
|
| 259 |
+
The name of an edge attribute that holds the numerical value used
|
| 260 |
+
as a weight. If None, then each edge has weight 1.
|
| 261 |
+
The degree is the sum of the edge weights adjacent to the node.
|
| 262 |
+
|
| 263 |
+
resolution : float, optional (default=1)
|
| 264 |
+
If resolution is less than 1, modularity favors larger communities.
|
| 265 |
+
Greater than 1 favors smaller communities.
|
| 266 |
+
|
| 267 |
+
cutoff : int, optional (default=1)
|
| 268 |
+
A minimum number of communities below which the merging process stops.
|
| 269 |
+
The process stops at this number of communities even if modularity
|
| 270 |
+
is not maximized. The goal is to let the user stop the process early.
|
| 271 |
+
The process stops before the cutoff if it finds a maximum of modularity.
|
| 272 |
+
|
| 273 |
+
best_n : int or None, optional (default=None)
|
| 274 |
+
A maximum number of communities above which the merging process will
|
| 275 |
+
not stop. This forces community merging to continue after modularity
|
| 276 |
+
starts to decrease until `best_n` communities remain.
|
| 277 |
+
If ``None``, don't force it to continue beyond a maximum.
|
| 278 |
+
|
| 279 |
+
Raises
|
| 280 |
+
------
|
| 281 |
+
ValueError : If the `cutoff` or `best_n` value is not in the range
|
| 282 |
+
``[1, G.number_of_nodes()]``, or if `best_n` < `cutoff`.
|
| 283 |
+
|
| 284 |
+
Returns
|
| 285 |
+
-------
|
| 286 |
+
communities: list
|
| 287 |
+
A list of frozensets of nodes, one for each community.
|
| 288 |
+
Sorted by length with largest communities first.
|
| 289 |
+
|
| 290 |
+
Examples
|
| 291 |
+
--------
|
| 292 |
+
>>> G = nx.karate_club_graph()
|
| 293 |
+
>>> c = nx.community.greedy_modularity_communities(G)
|
| 294 |
+
>>> sorted(c[0])
|
| 295 |
+
[8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
|
| 296 |
+
|
| 297 |
+
See Also
|
| 298 |
+
--------
|
| 299 |
+
modularity
|
| 300 |
+
|
| 301 |
+
References
|
| 302 |
+
----------
|
| 303 |
+
.. [1] Newman, M. E. J. "Networks: An Introduction", page 224
|
| 304 |
+
Oxford University Press 2011.
|
| 305 |
+
.. [2] Clauset, A., Newman, M. E., & Moore, C.
|
| 306 |
+
"Finding community structure in very large networks."
|
| 307 |
+
Physical Review E 70(6), 2004.
|
| 308 |
+
.. [3] Reichardt and Bornholdt "Statistical Mechanics of Community
|
| 309 |
+
Detection" Phys. Rev. E74, 2006.
|
| 310 |
+
.. [4] Newman, M. E. J."Analysis of weighted networks"
|
| 311 |
+
Physical Review E 70(5 Pt 2):056131, 2004.
|
| 312 |
+
"""
|
| 313 |
+
if not G.size():
|
| 314 |
+
return [{n} for n in G]
|
| 315 |
+
|
| 316 |
+
if (cutoff < 1) or (cutoff > G.number_of_nodes()):
|
| 317 |
+
raise ValueError(f"cutoff must be between 1 and {len(G)}. Got {cutoff}.")
|
| 318 |
+
if best_n is not None:
|
| 319 |
+
if (best_n < 1) or (best_n > G.number_of_nodes()):
|
| 320 |
+
raise ValueError(f"best_n must be between 1 and {len(G)}. Got {best_n}.")
|
| 321 |
+
if best_n < cutoff:
|
| 322 |
+
raise ValueError(f"Must have best_n >= cutoff. Got {best_n} < {cutoff}")
|
| 323 |
+
if best_n == 1:
|
| 324 |
+
return [set(G)]
|
| 325 |
+
else:
|
| 326 |
+
best_n = G.number_of_nodes()
|
| 327 |
+
|
| 328 |
+
# retrieve generator object to construct output
|
| 329 |
+
community_gen = _greedy_modularity_communities_generator(
|
| 330 |
+
G, weight=weight, resolution=resolution
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
# construct the first best community
|
| 334 |
+
communities = next(community_gen)
|
| 335 |
+
|
| 336 |
+
# continue merging communities until one of the breaking criteria is satisfied
|
| 337 |
+
while len(communities) > cutoff:
|
| 338 |
+
try:
|
| 339 |
+
dq = next(community_gen)
|
| 340 |
+
# StopIteration occurs when communities are the connected components
|
| 341 |
+
except StopIteration:
|
| 342 |
+
communities = sorted(communities, key=len, reverse=True)
|
| 343 |
+
# if best_n requires more merging, merge big sets for highest modularity
|
| 344 |
+
while len(communities) > best_n:
|
| 345 |
+
comm1, comm2, *rest = communities
|
| 346 |
+
communities = [comm1 ^ comm2]
|
| 347 |
+
communities.extend(rest)
|
| 348 |
+
return communities
|
| 349 |
+
|
| 350 |
+
# keep going unless max_mod is reached or best_n says to merge more
|
| 351 |
+
if dq < 0 and len(communities) <= best_n:
|
| 352 |
+
break
|
| 353 |
+
communities = next(community_gen)
|
| 354 |
+
|
| 355 |
+
return sorted(communities, key=len, reverse=True)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@nx.utils.not_implemented_for("directed")
|
| 359 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 360 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 361 |
+
def naive_greedy_modularity_communities(G, resolution=1, weight=None):
|
| 362 |
+
r"""Find communities in G using greedy modularity maximization.
|
| 363 |
+
|
| 364 |
+
This implementation is O(n^4), much slower than alternatives, but it is
|
| 365 |
+
provided as an easy-to-understand reference implementation.
|
| 366 |
+
|
| 367 |
+
Greedy modularity maximization begins with each node in its own community
|
| 368 |
+
and joins the pair of communities that most increases modularity until no
|
| 369 |
+
such pair exists.
|
| 370 |
+
|
| 371 |
+
This function maximizes the generalized modularity, where `resolution`
|
| 372 |
+
is the resolution parameter, often expressed as $\gamma$.
|
| 373 |
+
See :func:`~networkx.algorithms.community.quality.modularity`.
|
| 374 |
+
|
| 375 |
+
Parameters
|
| 376 |
+
----------
|
| 377 |
+
G : NetworkX graph
|
| 378 |
+
Graph must be simple and undirected.
|
| 379 |
+
|
| 380 |
+
resolution : float (default=1)
|
| 381 |
+
If resolution is less than 1, modularity favors larger communities.
|
| 382 |
+
Greater than 1 favors smaller communities.
|
| 383 |
+
|
| 384 |
+
weight : string or None, optional (default=None)
|
| 385 |
+
The name of an edge attribute that holds the numerical value used
|
| 386 |
+
as a weight. If None, then each edge has weight 1.
|
| 387 |
+
The degree is the sum of the edge weights adjacent to the node.
|
| 388 |
+
|
| 389 |
+
Returns
|
| 390 |
+
-------
|
| 391 |
+
list
|
| 392 |
+
A list of sets of nodes, one for each community.
|
| 393 |
+
Sorted by length with largest communities first.
|
| 394 |
+
|
| 395 |
+
Examples
|
| 396 |
+
--------
|
| 397 |
+
>>> G = nx.karate_club_graph()
|
| 398 |
+
>>> c = nx.community.naive_greedy_modularity_communities(G)
|
| 399 |
+
>>> sorted(c[0])
|
| 400 |
+
[8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
|
| 401 |
+
|
| 402 |
+
See Also
|
| 403 |
+
--------
|
| 404 |
+
greedy_modularity_communities
|
| 405 |
+
modularity
|
| 406 |
+
"""
|
| 407 |
+
# First create one community for each node
|
| 408 |
+
communities = [frozenset([u]) for u in G.nodes()]
|
| 409 |
+
# Track merges
|
| 410 |
+
merges = []
|
| 411 |
+
# Greedily merge communities until no improvement is possible
|
| 412 |
+
old_modularity = None
|
| 413 |
+
new_modularity = modularity(G, communities, resolution=resolution, weight=weight)
|
| 414 |
+
while old_modularity is None or new_modularity > old_modularity:
|
| 415 |
+
# Save modularity for comparison
|
| 416 |
+
old_modularity = new_modularity
|
| 417 |
+
# Find best pair to merge
|
| 418 |
+
trial_communities = list(communities)
|
| 419 |
+
to_merge = None
|
| 420 |
+
for i, u in enumerate(communities):
|
| 421 |
+
for j, v in enumerate(communities):
|
| 422 |
+
# Skip i==j and empty communities
|
| 423 |
+
if j <= i or len(u) == 0 or len(v) == 0:
|
| 424 |
+
continue
|
| 425 |
+
# Merge communities u and v
|
| 426 |
+
trial_communities[j] = u | v
|
| 427 |
+
trial_communities[i] = frozenset([])
|
| 428 |
+
trial_modularity = modularity(
|
| 429 |
+
G, trial_communities, resolution=resolution, weight=weight
|
| 430 |
+
)
|
| 431 |
+
if trial_modularity >= new_modularity:
|
| 432 |
+
# Check if strictly better or tie
|
| 433 |
+
if trial_modularity > new_modularity:
|
| 434 |
+
# Found new best, save modularity and group indexes
|
| 435 |
+
new_modularity = trial_modularity
|
| 436 |
+
to_merge = (i, j, new_modularity - old_modularity)
|
| 437 |
+
elif to_merge and min(i, j) < min(to_merge[0], to_merge[1]):
|
| 438 |
+
# Break ties by choosing pair with lowest min id
|
| 439 |
+
new_modularity = trial_modularity
|
| 440 |
+
to_merge = (i, j, new_modularity - old_modularity)
|
| 441 |
+
# Un-merge
|
| 442 |
+
trial_communities[i] = u
|
| 443 |
+
trial_communities[j] = v
|
| 444 |
+
if to_merge is not None:
|
| 445 |
+
# If the best merge improves modularity, use it
|
| 446 |
+
merges.append(to_merge)
|
| 447 |
+
i, j, dq = to_merge
|
| 448 |
+
u, v = communities[i], communities[j]
|
| 449 |
+
communities[j] = u | v
|
| 450 |
+
communities[i] = frozenset([])
|
| 451 |
+
# Remove empty communities and sort
|
| 452 |
+
return sorted((c for c in communities if len(c) > 0), key=len, reverse=True)
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/quality.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for measuring the quality of a partition (into
|
| 2 |
+
communities).
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from itertools import combinations
|
| 7 |
+
|
| 8 |
+
import networkx as nx
|
| 9 |
+
from networkx import NetworkXError
|
| 10 |
+
from networkx.algorithms.community.community_utils import is_partition
|
| 11 |
+
from networkx.utils.decorators import argmap
|
| 12 |
+
|
| 13 |
+
__all__ = ["modularity", "partition_quality"]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class NotAPartition(NetworkXError):
|
| 17 |
+
"""Raised if a given collection is not a partition."""
|
| 18 |
+
|
| 19 |
+
def __init__(self, G, collection):
|
| 20 |
+
msg = f"{collection} is not a valid partition of the graph {G}"
|
| 21 |
+
super().__init__(msg)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _require_partition(G, partition):
|
| 25 |
+
"""Decorator to check that a valid partition is input to a function
|
| 26 |
+
|
| 27 |
+
Raises :exc:`networkx.NetworkXError` if the partition is not valid.
|
| 28 |
+
|
| 29 |
+
This decorator should be used on functions whose first two arguments
|
| 30 |
+
are a graph and a partition of the nodes of that graph (in that
|
| 31 |
+
order)::
|
| 32 |
+
|
| 33 |
+
>>> @require_partition
|
| 34 |
+
... def foo(G, partition):
|
| 35 |
+
... print("partition is valid!")
|
| 36 |
+
...
|
| 37 |
+
>>> G = nx.complete_graph(5)
|
| 38 |
+
>>> partition = [{0, 1}, {2, 3}, {4}]
|
| 39 |
+
>>> foo(G, partition)
|
| 40 |
+
partition is valid!
|
| 41 |
+
>>> partition = [{0}, {2, 3}, {4}]
|
| 42 |
+
>>> foo(G, partition)
|
| 43 |
+
Traceback (most recent call last):
|
| 44 |
+
...
|
| 45 |
+
networkx.exception.NetworkXError: `partition` is not a valid partition of the nodes of G
|
| 46 |
+
>>> partition = [{0, 1}, {1, 2, 3}, {4}]
|
| 47 |
+
>>> foo(G, partition)
|
| 48 |
+
Traceback (most recent call last):
|
| 49 |
+
...
|
| 50 |
+
networkx.exception.NetworkXError: `partition` is not a valid partition of the nodes of G
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
if is_partition(G, partition):
|
| 54 |
+
return G, partition
|
| 55 |
+
raise nx.NetworkXError("`partition` is not a valid partition of the nodes of G")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
require_partition = argmap(_require_partition, (0, 1))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@nx._dispatchable
|
| 62 |
+
def intra_community_edges(G, partition):
|
| 63 |
+
"""Returns the number of intra-community edges for a partition of `G`.
|
| 64 |
+
|
| 65 |
+
Parameters
|
| 66 |
+
----------
|
| 67 |
+
G : NetworkX graph.
|
| 68 |
+
|
| 69 |
+
partition : iterable of sets of nodes
|
| 70 |
+
This must be a partition of the nodes of `G`.
|
| 71 |
+
|
| 72 |
+
The "intra-community edges" are those edges joining a pair of nodes
|
| 73 |
+
in the same block of the partition.
|
| 74 |
+
|
| 75 |
+
"""
|
| 76 |
+
return sum(G.subgraph(block).size() for block in partition)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@nx._dispatchable
|
| 80 |
+
def inter_community_edges(G, partition):
|
| 81 |
+
"""Returns the number of inter-community edges for a partition of `G`.
|
| 82 |
+
according to the given
|
| 83 |
+
partition of the nodes of `G`.
|
| 84 |
+
|
| 85 |
+
Parameters
|
| 86 |
+
----------
|
| 87 |
+
G : NetworkX graph.
|
| 88 |
+
|
| 89 |
+
partition : iterable of sets of nodes
|
| 90 |
+
This must be a partition of the nodes of `G`.
|
| 91 |
+
|
| 92 |
+
The *inter-community edges* are those edges joining a pair of nodes
|
| 93 |
+
in different blocks of the partition.
|
| 94 |
+
|
| 95 |
+
Implementation note: this function creates an intermediate graph
|
| 96 |
+
that may require the same amount of memory as that of `G`.
|
| 97 |
+
|
| 98 |
+
"""
|
| 99 |
+
# Alternate implementation that does not require constructing a new
|
| 100 |
+
# graph object (but does require constructing an affiliation
|
| 101 |
+
# dictionary):
|
| 102 |
+
#
|
| 103 |
+
# aff = dict(chain.from_iterable(((v, block) for v in block)
|
| 104 |
+
# for block in partition))
|
| 105 |
+
# return sum(1 for u, v in G.edges() if aff[u] != aff[v])
|
| 106 |
+
#
|
| 107 |
+
MG = nx.MultiDiGraph if G.is_directed() else nx.MultiGraph
|
| 108 |
+
return nx.quotient_graph(G, partition, create_using=MG).size()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@nx._dispatchable
|
| 112 |
+
def inter_community_non_edges(G, partition):
|
| 113 |
+
"""Returns the number of inter-community non-edges according to the
|
| 114 |
+
given partition of the nodes of `G`.
|
| 115 |
+
|
| 116 |
+
Parameters
|
| 117 |
+
----------
|
| 118 |
+
G : NetworkX graph.
|
| 119 |
+
|
| 120 |
+
partition : iterable of sets of nodes
|
| 121 |
+
This must be a partition of the nodes of `G`.
|
| 122 |
+
|
| 123 |
+
A *non-edge* is a pair of nodes (undirected if `G` is undirected)
|
| 124 |
+
that are not adjacent in `G`. The *inter-community non-edges* are
|
| 125 |
+
those non-edges on a pair of nodes in different blocks of the
|
| 126 |
+
partition.
|
| 127 |
+
|
| 128 |
+
Implementation note: this function creates two intermediate graphs,
|
| 129 |
+
which may require up to twice the amount of memory as required to
|
| 130 |
+
store `G`.
|
| 131 |
+
|
| 132 |
+
"""
|
| 133 |
+
# Alternate implementation that does not require constructing two
|
| 134 |
+
# new graph objects (but does require constructing an affiliation
|
| 135 |
+
# dictionary):
|
| 136 |
+
#
|
| 137 |
+
# aff = dict(chain.from_iterable(((v, block) for v in block)
|
| 138 |
+
# for block in partition))
|
| 139 |
+
# return sum(1 for u, v in nx.non_edges(G) if aff[u] != aff[v])
|
| 140 |
+
#
|
| 141 |
+
return inter_community_edges(nx.complement(G), partition)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 145 |
+
def modularity(G, communities, weight="weight", resolution=1):
|
| 146 |
+
r"""Returns the modularity of the given partition of the graph.
|
| 147 |
+
|
| 148 |
+
Modularity is defined in [1]_ as
|
| 149 |
+
|
| 150 |
+
.. math::
|
| 151 |
+
Q = \frac{1}{2m} \sum_{ij} \left( A_{ij} - \gamma\frac{k_ik_j}{2m}\right)
|
| 152 |
+
\delta(c_i,c_j)
|
| 153 |
+
|
| 154 |
+
where $m$ is the number of edges (or sum of all edge weights as in [5]_),
|
| 155 |
+
$A$ is the adjacency matrix of `G`, $k_i$ is the (weighted) degree of $i$,
|
| 156 |
+
$\gamma$ is the resolution parameter, and $\delta(c_i, c_j)$ is 1 if $i$ and
|
| 157 |
+
$j$ are in the same community else 0.
|
| 158 |
+
|
| 159 |
+
According to [2]_ (and verified by some algebra) this can be reduced to
|
| 160 |
+
|
| 161 |
+
.. math::
|
| 162 |
+
Q = \sum_{c=1}^{n}
|
| 163 |
+
\left[ \frac{L_c}{m} - \gamma\left( \frac{k_c}{2m} \right) ^2 \right]
|
| 164 |
+
|
| 165 |
+
where the sum iterates over all communities $c$, $m$ is the number of edges,
|
| 166 |
+
$L_c$ is the number of intra-community links for community $c$,
|
| 167 |
+
$k_c$ is the sum of degrees of the nodes in community $c$,
|
| 168 |
+
and $\gamma$ is the resolution parameter.
|
| 169 |
+
|
| 170 |
+
The resolution parameter sets an arbitrary tradeoff between intra-group
|
| 171 |
+
edges and inter-group edges. More complex grouping patterns can be
|
| 172 |
+
discovered by analyzing the same network with multiple values of gamma
|
| 173 |
+
and then combining the results [3]_. That said, it is very common to
|
| 174 |
+
simply use gamma=1. More on the choice of gamma is in [4]_.
|
| 175 |
+
|
| 176 |
+
The second formula is the one actually used in calculation of the modularity.
|
| 177 |
+
For directed graphs the second formula replaces $k_c$ with $k^{in}_c k^{out}_c$.
|
| 178 |
+
|
| 179 |
+
Parameters
|
| 180 |
+
----------
|
| 181 |
+
G : NetworkX Graph
|
| 182 |
+
|
| 183 |
+
communities : list or iterable of set of nodes
|
| 184 |
+
These node sets must represent a partition of G's nodes.
|
| 185 |
+
|
| 186 |
+
weight : string or None, optional (default="weight")
|
| 187 |
+
The edge attribute that holds the numerical value used
|
| 188 |
+
as a weight. If None or an edge does not have that attribute,
|
| 189 |
+
then that edge has weight 1.
|
| 190 |
+
|
| 191 |
+
resolution : float (default=1)
|
| 192 |
+
If resolution is less than 1, modularity favors larger communities.
|
| 193 |
+
Greater than 1 favors smaller communities.
|
| 194 |
+
|
| 195 |
+
Returns
|
| 196 |
+
-------
|
| 197 |
+
Q : float
|
| 198 |
+
The modularity of the partition.
|
| 199 |
+
|
| 200 |
+
Raises
|
| 201 |
+
------
|
| 202 |
+
NotAPartition
|
| 203 |
+
If `communities` is not a partition of the nodes of `G`.
|
| 204 |
+
|
| 205 |
+
Examples
|
| 206 |
+
--------
|
| 207 |
+
>>> G = nx.barbell_graph(3, 0)
|
| 208 |
+
>>> nx.community.modularity(G, [{0, 1, 2}, {3, 4, 5}])
|
| 209 |
+
0.35714285714285715
|
| 210 |
+
>>> nx.community.modularity(G, nx.community.label_propagation_communities(G))
|
| 211 |
+
0.35714285714285715
|
| 212 |
+
|
| 213 |
+
References
|
| 214 |
+
----------
|
| 215 |
+
.. [1] M. E. J. Newman "Networks: An Introduction", page 224.
|
| 216 |
+
Oxford University Press, 2011.
|
| 217 |
+
.. [2] Clauset, Aaron, Mark EJ Newman, and Cristopher Moore.
|
| 218 |
+
"Finding community structure in very large networks."
|
| 219 |
+
Phys. Rev. E 70.6 (2004). <https://arxiv.org/abs/cond-mat/0408187>
|
| 220 |
+
.. [3] Reichardt and Bornholdt "Statistical Mechanics of Community Detection"
|
| 221 |
+
Phys. Rev. E 74, 016110, 2006. https://doi.org/10.1103/PhysRevE.74.016110
|
| 222 |
+
.. [4] M. E. J. Newman, "Equivalence between modularity optimization and
|
| 223 |
+
maximum likelihood methods for community detection"
|
| 224 |
+
Phys. Rev. E 94, 052315, 2016. https://doi.org/10.1103/PhysRevE.94.052315
|
| 225 |
+
.. [5] Blondel, V.D. et al. "Fast unfolding of communities in large
|
| 226 |
+
networks" J. Stat. Mech 10008, 1-12 (2008).
|
| 227 |
+
https://doi.org/10.1088/1742-5468/2008/10/P10008
|
| 228 |
+
"""
|
| 229 |
+
if not isinstance(communities, list):
|
| 230 |
+
communities = list(communities)
|
| 231 |
+
if not is_partition(G, communities):
|
| 232 |
+
raise NotAPartition(G, communities)
|
| 233 |
+
|
| 234 |
+
directed = G.is_directed()
|
| 235 |
+
if directed:
|
| 236 |
+
out_degree = dict(G.out_degree(weight=weight))
|
| 237 |
+
in_degree = dict(G.in_degree(weight=weight))
|
| 238 |
+
m = sum(out_degree.values())
|
| 239 |
+
norm = 1 / m**2
|
| 240 |
+
else:
|
| 241 |
+
out_degree = in_degree = dict(G.degree(weight=weight))
|
| 242 |
+
deg_sum = sum(out_degree.values())
|
| 243 |
+
m = deg_sum / 2
|
| 244 |
+
norm = 1 / deg_sum**2
|
| 245 |
+
|
| 246 |
+
def community_contribution(community):
|
| 247 |
+
comm = set(community)
|
| 248 |
+
L_c = sum(wt for u, v, wt in G.edges(comm, data=weight, default=1) if v in comm)
|
| 249 |
+
|
| 250 |
+
out_degree_sum = sum(out_degree[u] for u in comm)
|
| 251 |
+
in_degree_sum = sum(in_degree[u] for u in comm) if directed else out_degree_sum
|
| 252 |
+
|
| 253 |
+
return L_c / m - resolution * out_degree_sum * in_degree_sum * norm
|
| 254 |
+
|
| 255 |
+
return sum(map(community_contribution, communities))
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@require_partition
|
| 259 |
+
@nx._dispatchable
|
| 260 |
+
def partition_quality(G, partition):
|
| 261 |
+
"""Returns the coverage and performance of a partition of G.
|
| 262 |
+
|
| 263 |
+
The *coverage* of a partition is the ratio of the number of
|
| 264 |
+
intra-community edges to the total number of edges in the graph.
|
| 265 |
+
|
| 266 |
+
The *performance* of a partition is the number of
|
| 267 |
+
intra-community edges plus inter-community non-edges divided by the total
|
| 268 |
+
number of potential edges.
|
| 269 |
+
|
| 270 |
+
This algorithm has complexity $O(C^2 + L)$ where C is the number of
|
| 271 |
+
communities and L is the number of links.
|
| 272 |
+
|
| 273 |
+
Parameters
|
| 274 |
+
----------
|
| 275 |
+
G : NetworkX graph
|
| 276 |
+
|
| 277 |
+
partition : sequence
|
| 278 |
+
Partition of the nodes of `G`, represented as a sequence of
|
| 279 |
+
sets of nodes (blocks). Each block of the partition represents a
|
| 280 |
+
community.
|
| 281 |
+
|
| 282 |
+
Returns
|
| 283 |
+
-------
|
| 284 |
+
(float, float)
|
| 285 |
+
The (coverage, performance) tuple of the partition, as defined above.
|
| 286 |
+
|
| 287 |
+
Raises
|
| 288 |
+
------
|
| 289 |
+
NetworkXError
|
| 290 |
+
If `partition` is not a valid partition of the nodes of `G`.
|
| 291 |
+
|
| 292 |
+
Notes
|
| 293 |
+
-----
|
| 294 |
+
If `G` is a multigraph;
|
| 295 |
+
- for coverage, the multiplicity of edges is counted
|
| 296 |
+
- for performance, the result is -1 (total number of possible edges is not defined)
|
| 297 |
+
|
| 298 |
+
References
|
| 299 |
+
----------
|
| 300 |
+
.. [1] Santo Fortunato.
|
| 301 |
+
"Community Detection in Graphs".
|
| 302 |
+
*Physical Reports*, Volume 486, Issue 3--5 pp. 75--174
|
| 303 |
+
<https://arxiv.org/abs/0906.0612>
|
| 304 |
+
"""
|
| 305 |
+
|
| 306 |
+
node_community = {}
|
| 307 |
+
for i, community in enumerate(partition):
|
| 308 |
+
for node in community:
|
| 309 |
+
node_community[node] = i
|
| 310 |
+
|
| 311 |
+
# `performance` is not defined for multigraphs
|
| 312 |
+
if not G.is_multigraph():
|
| 313 |
+
# Iterate over the communities, quadratic, to calculate `possible_inter_community_edges`
|
| 314 |
+
possible_inter_community_edges = sum(
|
| 315 |
+
len(p1) * len(p2) for p1, p2 in combinations(partition, 2)
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
if G.is_directed():
|
| 319 |
+
possible_inter_community_edges *= 2
|
| 320 |
+
else:
|
| 321 |
+
possible_inter_community_edges = 0
|
| 322 |
+
|
| 323 |
+
# Compute the number of edges in the complete graph -- `n` nodes,
|
| 324 |
+
# directed or undirected, depending on `G`
|
| 325 |
+
n = len(G)
|
| 326 |
+
total_pairs = n * (n - 1)
|
| 327 |
+
if not G.is_directed():
|
| 328 |
+
total_pairs //= 2
|
| 329 |
+
|
| 330 |
+
intra_community_edges = 0
|
| 331 |
+
inter_community_non_edges = possible_inter_community_edges
|
| 332 |
+
|
| 333 |
+
# Iterate over the links to count `intra_community_edges` and `inter_community_non_edges`
|
| 334 |
+
for e in G.edges():
|
| 335 |
+
if node_community[e[0]] == node_community[e[1]]:
|
| 336 |
+
intra_community_edges += 1
|
| 337 |
+
else:
|
| 338 |
+
inter_community_non_edges -= 1
|
| 339 |
+
|
| 340 |
+
coverage = intra_community_edges / len(G.edges)
|
| 341 |
+
|
| 342 |
+
if G.is_multigraph():
|
| 343 |
+
performance = -1.0
|
| 344 |
+
else:
|
| 345 |
+
performance = (intra_community_edges + inter_community_non_edges) / total_pairs
|
| 346 |
+
|
| 347 |
+
return coverage, performance
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_asyn_fluid.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx import Graph, NetworkXError
|
| 5 |
+
from networkx.algorithms.community import asyn_fluidc
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.mark.parametrize("graph_constructor", (nx.DiGraph, nx.MultiGraph))
|
| 9 |
+
def test_raises_on_directed_and_multigraphs(graph_constructor):
|
| 10 |
+
G = graph_constructor([(0, 1), (1, 2)])
|
| 11 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
| 12 |
+
nx.community.asyn_fluidc(G, 1)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_exceptions():
|
| 16 |
+
test = Graph()
|
| 17 |
+
test.add_node("a")
|
| 18 |
+
pytest.raises(NetworkXError, asyn_fluidc, test, "hi")
|
| 19 |
+
pytest.raises(NetworkXError, asyn_fluidc, test, -1)
|
| 20 |
+
pytest.raises(NetworkXError, asyn_fluidc, test, 3)
|
| 21 |
+
with pytest.raises(ValueError, match="must be greater than 0"):
|
| 22 |
+
asyn_fluidc(test, 1, max_iter=0)
|
| 23 |
+
test.add_node("b")
|
| 24 |
+
pytest.raises(NetworkXError, asyn_fluidc, test, 1)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_single_node():
|
| 28 |
+
test = Graph()
|
| 29 |
+
|
| 30 |
+
test.add_node("a")
|
| 31 |
+
|
| 32 |
+
# ground truth
|
| 33 |
+
ground_truth = {frozenset(["a"])}
|
| 34 |
+
|
| 35 |
+
communities = asyn_fluidc(test, 1)
|
| 36 |
+
result = {frozenset(c) for c in communities}
|
| 37 |
+
assert result == ground_truth
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_two_nodes():
|
| 41 |
+
test = Graph()
|
| 42 |
+
|
| 43 |
+
test.add_edge("a", "b")
|
| 44 |
+
|
| 45 |
+
# ground truth
|
| 46 |
+
ground_truth = {frozenset(["a"]), frozenset(["b"])}
|
| 47 |
+
|
| 48 |
+
communities = asyn_fluidc(test, 2)
|
| 49 |
+
result = {frozenset(c) for c in communities}
|
| 50 |
+
assert result == ground_truth
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_two_clique_communities():
|
| 54 |
+
test = Graph()
|
| 55 |
+
|
| 56 |
+
# c1
|
| 57 |
+
test.add_edge("a", "b")
|
| 58 |
+
test.add_edge("a", "c")
|
| 59 |
+
test.add_edge("b", "c")
|
| 60 |
+
|
| 61 |
+
# connection
|
| 62 |
+
test.add_edge("c", "d")
|
| 63 |
+
|
| 64 |
+
# c2
|
| 65 |
+
test.add_edge("d", "e")
|
| 66 |
+
test.add_edge("d", "f")
|
| 67 |
+
test.add_edge("f", "e")
|
| 68 |
+
|
| 69 |
+
# ground truth
|
| 70 |
+
ground_truth = {frozenset(["a", "c", "b"]), frozenset(["e", "d", "f"])}
|
| 71 |
+
|
| 72 |
+
communities = asyn_fluidc(test, 2, seed=7)
|
| 73 |
+
result = {frozenset(c) for c in communities}
|
| 74 |
+
assert result == ground_truth
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_five_clique_ring():
|
| 78 |
+
test = Graph()
|
| 79 |
+
|
| 80 |
+
# c1
|
| 81 |
+
test.add_edge("1a", "1b")
|
| 82 |
+
test.add_edge("1a", "1c")
|
| 83 |
+
test.add_edge("1a", "1d")
|
| 84 |
+
test.add_edge("1b", "1c")
|
| 85 |
+
test.add_edge("1b", "1d")
|
| 86 |
+
test.add_edge("1c", "1d")
|
| 87 |
+
|
| 88 |
+
# c2
|
| 89 |
+
test.add_edge("2a", "2b")
|
| 90 |
+
test.add_edge("2a", "2c")
|
| 91 |
+
test.add_edge("2a", "2d")
|
| 92 |
+
test.add_edge("2b", "2c")
|
| 93 |
+
test.add_edge("2b", "2d")
|
| 94 |
+
test.add_edge("2c", "2d")
|
| 95 |
+
|
| 96 |
+
# c3
|
| 97 |
+
test.add_edge("3a", "3b")
|
| 98 |
+
test.add_edge("3a", "3c")
|
| 99 |
+
test.add_edge("3a", "3d")
|
| 100 |
+
test.add_edge("3b", "3c")
|
| 101 |
+
test.add_edge("3b", "3d")
|
| 102 |
+
test.add_edge("3c", "3d")
|
| 103 |
+
|
| 104 |
+
# c4
|
| 105 |
+
test.add_edge("4a", "4b")
|
| 106 |
+
test.add_edge("4a", "4c")
|
| 107 |
+
test.add_edge("4a", "4d")
|
| 108 |
+
test.add_edge("4b", "4c")
|
| 109 |
+
test.add_edge("4b", "4d")
|
| 110 |
+
test.add_edge("4c", "4d")
|
| 111 |
+
|
| 112 |
+
# c5
|
| 113 |
+
test.add_edge("5a", "5b")
|
| 114 |
+
test.add_edge("5a", "5c")
|
| 115 |
+
test.add_edge("5a", "5d")
|
| 116 |
+
test.add_edge("5b", "5c")
|
| 117 |
+
test.add_edge("5b", "5d")
|
| 118 |
+
test.add_edge("5c", "5d")
|
| 119 |
+
|
| 120 |
+
# connections
|
| 121 |
+
test.add_edge("1a", "2c")
|
| 122 |
+
test.add_edge("2a", "3c")
|
| 123 |
+
test.add_edge("3a", "4c")
|
| 124 |
+
test.add_edge("4a", "5c")
|
| 125 |
+
test.add_edge("5a", "1c")
|
| 126 |
+
|
| 127 |
+
# ground truth
|
| 128 |
+
ground_truth = {
|
| 129 |
+
frozenset(["1a", "1b", "1c", "1d"]),
|
| 130 |
+
frozenset(["2a", "2b", "2c", "2d"]),
|
| 131 |
+
frozenset(["3a", "3b", "3c", "3d"]),
|
| 132 |
+
frozenset(["4a", "4b", "4c", "4d"]),
|
| 133 |
+
frozenset(["5a", "5b", "5c", "5d"]),
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
communities = asyn_fluidc(test, 5, seed=9)
|
| 137 |
+
result = {frozenset(c) for c in communities}
|
| 138 |
+
assert result == ground_truth
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_asyn_fluidc_max_iter():
|
| 142 |
+
"""Check that setting `max_iter` stops the algorithm early."""
|
| 143 |
+
test = nx.barbell_graph(3, 2)
|
| 144 |
+
|
| 145 |
+
c1 = asyn_fluidc(test, 2, max_iter=1, seed=42)
|
| 146 |
+
c2 = asyn_fluidc(test, 2, max_iter=100, seed=42)
|
| 147 |
+
assert {map(frozenset, c1)} != {map(frozenset, c2)}
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_bipartitions.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import permutations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.algorithms.community import (
|
| 7 |
+
greedy_node_swap_bipartition,
|
| 8 |
+
kernighan_lin_bisection,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def assert_partition_equal(x, y):
|
| 13 |
+
assert set(map(frozenset, x)) == set(map(frozenset, y))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_partition():
|
| 17 |
+
G = nx.barbell_graph(3, 0)
|
| 18 |
+
split = kernighan_lin_bisection(G)
|
| 19 |
+
assert_partition_equal(split, [{0, 1, 2}, {3, 4, 5}])
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_partition_argument():
|
| 23 |
+
G = nx.barbell_graph(3, 0)
|
| 24 |
+
partition = [{0, 1, 2}, {3, 4, 5}]
|
| 25 |
+
split = kernighan_lin_bisection(G, partition)
|
| 26 |
+
assert_partition_equal(split, partition)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_partition_argument_non_integer_nodes():
|
| 30 |
+
G = nx.Graph([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")])
|
| 31 |
+
partition = ({"A", "B"}, {"C", "D"})
|
| 32 |
+
split = kernighan_lin_bisection(G, partition)
|
| 33 |
+
assert_partition_equal(split, partition)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_seed_argument():
|
| 37 |
+
G = nx.barbell_graph(3, 0)
|
| 38 |
+
split = kernighan_lin_bisection(G, seed=1)
|
| 39 |
+
assert_partition_equal(split, [{0, 1, 2}, {3, 4, 5}])
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_non_disjoint_partition():
|
| 43 |
+
with pytest.raises(nx.NetworkXError):
|
| 44 |
+
G = nx.barbell_graph(3, 0)
|
| 45 |
+
partition = ({0, 1, 2}, {2, 3, 4, 5})
|
| 46 |
+
kernighan_lin_bisection(G, partition)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_kernighan_lin_too_many_blocks():
|
| 50 |
+
with pytest.raises(nx.NetworkXError):
|
| 51 |
+
G = nx.barbell_graph(3, 0)
|
| 52 |
+
partition = ({0, 1}, {2}, {3, 4, 5})
|
| 53 |
+
kernighan_lin_bisection(G, partition)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_multigraph():
|
| 57 |
+
G = nx.cycle_graph(4)
|
| 58 |
+
M = nx.MultiGraph(G.edges())
|
| 59 |
+
M.add_edges_from(G.edges())
|
| 60 |
+
M.remove_edge(1, 2)
|
| 61 |
+
for labels in permutations(range(4)):
|
| 62 |
+
mapping = dict(zip(M, labels))
|
| 63 |
+
A, B = kernighan_lin_bisection(nx.relabel_nodes(M, mapping), seed=0)
|
| 64 |
+
assert_partition_equal(
|
| 65 |
+
[A, B], [{mapping[0], mapping[1]}, {mapping[2], mapping[3]}]
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_max_iter_argument():
|
| 70 |
+
G = nx.Graph(
|
| 71 |
+
[
|
| 72 |
+
("A", "B", {"weight": 1}),
|
| 73 |
+
("A", "C", {"weight": 2}),
|
| 74 |
+
("A", "D", {"weight": 3}),
|
| 75 |
+
("A", "E", {"weight": 2}),
|
| 76 |
+
("A", "F", {"weight": 4}),
|
| 77 |
+
("B", "C", {"weight": 1}),
|
| 78 |
+
("B", "D", {"weight": 4}),
|
| 79 |
+
("B", "E", {"weight": 2}),
|
| 80 |
+
("B", "F", {"weight": 1}),
|
| 81 |
+
("C", "D", {"weight": 3}),
|
| 82 |
+
("C", "E", {"weight": 2}),
|
| 83 |
+
("C", "F", {"weight": 1}),
|
| 84 |
+
("D", "E", {"weight": 4}),
|
| 85 |
+
("D", "F", {"weight": 3}),
|
| 86 |
+
("E", "F", {"weight": 2}),
|
| 87 |
+
]
|
| 88 |
+
)
|
| 89 |
+
partition = ({"A", "B", "C"}, {"D", "E", "F"})
|
| 90 |
+
split = kernighan_lin_bisection(G, partition, max_iter=1)
|
| 91 |
+
assert_partition_equal(split, ({"A", "F", "C"}, {"D", "E", "B"}))
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_weight_function():
|
| 95 |
+
G = nx.cycle_graph(4)
|
| 96 |
+
|
| 97 |
+
def my_weight(u, v, d):
|
| 98 |
+
if u == 2 and v == 3:
|
| 99 |
+
return None
|
| 100 |
+
return u + v
|
| 101 |
+
|
| 102 |
+
split = kernighan_lin_bisection(G, weight=my_weight)
|
| 103 |
+
assert_partition_equal(split, ({1, 2}, {0, 3}))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
## Test Spectral Modularity Bipartition
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_spectral_bipartition():
|
| 110 |
+
pytest.importorskip("scipy")
|
| 111 |
+
G = nx.barbell_graph(3, 0)
|
| 112 |
+
split = nx.community.spectral_modularity_bipartition(G)
|
| 113 |
+
soln = ({3, 4, 5}, {0, 1, 2})
|
| 114 |
+
assert set(map(frozenset, split)) == set(map(frozenset, soln))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_karate_club():
|
| 118 |
+
pytest.importorskip("scipy")
|
| 119 |
+
G = nx.karate_club_graph()
|
| 120 |
+
MrHi = {v for v, club in G.nodes.data("club") if club == "Mr. Hi"}
|
| 121 |
+
Officer = {v for v, club in G.nodes.data("club") if club == "Officer"}
|
| 122 |
+
split = nx.community.spectral_modularity_bipartition(G)
|
| 123 |
+
|
| 124 |
+
# spectral method misplaces member 8
|
| 125 |
+
MrHi.remove(8)
|
| 126 |
+
Officer.add(8)
|
| 127 |
+
soln = (MrHi, Officer)
|
| 128 |
+
assert set(map(frozenset, split)) == set(map(frozenset, soln))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
## Test Node Swap Greedy Bipartition
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def test_greedy_bipartition():
|
| 135 |
+
G = nx.barbell_graph(3, 0)
|
| 136 |
+
split = nx.community.greedy_node_swap_bipartition(G)
|
| 137 |
+
soln = ({0, 1, 2}, {3, 4, 5})
|
| 138 |
+
assert set(map(frozenset, split)) == set(map(frozenset, soln))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_greedy_non_disjoint_partition():
|
| 142 |
+
G = nx.barbell_graph(3, 0)
|
| 143 |
+
split = ({0, 1, 2}, {2, 3, 4, 5})
|
| 144 |
+
with pytest.raises(nx.NetworkXError):
|
| 145 |
+
nx.community.greedy_node_swap_bipartition(G, init_split=split)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def test_greedy_node_swap_too_many_blocks():
|
| 149 |
+
G = nx.barbell_graph(3, 0)
|
| 150 |
+
split = ({0, 1}, {2}, {3, 4, 5})
|
| 151 |
+
with pytest.raises(nx.NetworkXError):
|
| 152 |
+
nx.community.greedy_node_swap_bipartition(G, init_split=split)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_greedy_multigraph_disallowed():
|
| 156 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
| 157 |
+
nx.community.greedy_node_swap_bipartition(nx.MultiGraph())
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_centrality.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for the :mod:`networkx.algorithms.community.centrality`
|
| 2 |
+
module.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from operator import itemgetter
|
| 7 |
+
|
| 8 |
+
import networkx as nx
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def set_of_sets(iterable):
|
| 12 |
+
return set(map(frozenset, iterable))
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def validate_communities(result, expected):
|
| 16 |
+
assert set_of_sets(result) == set_of_sets(expected)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def validate_possible_communities(result, *expected):
|
| 20 |
+
assert any(set_of_sets(result) == set_of_sets(p) for p in expected)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TestGirvanNewman:
|
| 24 |
+
"""Unit tests for the
|
| 25 |
+
:func:`networkx.algorithms.community.centrality.girvan_newman`
|
| 26 |
+
function.
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def test_no_edges(self):
|
| 31 |
+
G = nx.empty_graph(3)
|
| 32 |
+
communities = list(nx.community.girvan_newman(G))
|
| 33 |
+
assert len(communities) == 1
|
| 34 |
+
validate_communities(communities[0], [{0}, {1}, {2}])
|
| 35 |
+
|
| 36 |
+
def test_undirected(self):
|
| 37 |
+
# Start with the graph .-.-.-.
|
| 38 |
+
G = nx.path_graph(4)
|
| 39 |
+
communities = list(nx.community.girvan_newman(G))
|
| 40 |
+
assert len(communities) == 3
|
| 41 |
+
# After one removal, we get the graph .-. .-.
|
| 42 |
+
validate_communities(communities[0], [{0, 1}, {2, 3}])
|
| 43 |
+
# After the next, we get the graph .-. . ., but there are two
|
| 44 |
+
# symmetric possible versions.
|
| 45 |
+
validate_possible_communities(
|
| 46 |
+
communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}]
|
| 47 |
+
)
|
| 48 |
+
# After the last removal, we always get the empty graph.
|
| 49 |
+
validate_communities(communities[2], [{0}, {1}, {2}, {3}])
|
| 50 |
+
|
| 51 |
+
def test_directed(self):
|
| 52 |
+
G = nx.DiGraph(nx.path_graph(4))
|
| 53 |
+
communities = list(nx.community.girvan_newman(G))
|
| 54 |
+
assert len(communities) == 3
|
| 55 |
+
validate_communities(communities[0], [{0, 1}, {2, 3}])
|
| 56 |
+
validate_possible_communities(
|
| 57 |
+
communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}]
|
| 58 |
+
)
|
| 59 |
+
validate_communities(communities[2], [{0}, {1}, {2}, {3}])
|
| 60 |
+
|
| 61 |
+
def test_selfloops(self):
|
| 62 |
+
G = nx.path_graph(4)
|
| 63 |
+
G.add_edge(0, 0)
|
| 64 |
+
G.add_edge(2, 2)
|
| 65 |
+
communities = list(nx.community.girvan_newman(G))
|
| 66 |
+
assert len(communities) == 3
|
| 67 |
+
validate_communities(communities[0], [{0, 1}, {2, 3}])
|
| 68 |
+
validate_possible_communities(
|
| 69 |
+
communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}]
|
| 70 |
+
)
|
| 71 |
+
validate_communities(communities[2], [{0}, {1}, {2}, {3}])
|
| 72 |
+
|
| 73 |
+
def test_most_valuable_edge(self):
|
| 74 |
+
G = nx.Graph()
|
| 75 |
+
G.add_weighted_edges_from([(0, 1, 3), (1, 2, 2), (2, 3, 1)])
|
| 76 |
+
# Let the most valuable edge be the one with the highest weight.
|
| 77 |
+
|
| 78 |
+
def heaviest(G):
|
| 79 |
+
return max(G.edges(data="weight"), key=itemgetter(2))[:2]
|
| 80 |
+
|
| 81 |
+
communities = list(nx.community.girvan_newman(G, heaviest))
|
| 82 |
+
assert len(communities) == 3
|
| 83 |
+
validate_communities(communities[0], [{0}, {1, 2, 3}])
|
| 84 |
+
validate_communities(communities[1], [{0}, {1}, {2, 3}])
|
| 85 |
+
validate_communities(communities[2], [{0}, {1}, {2}, {3}])
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_divisive.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_edge_betweenness_partition():
|
| 7 |
+
G = nx.barbell_graph(3, 0)
|
| 8 |
+
C = nx.community.edge_betweenness_partition(G, 2)
|
| 9 |
+
answer = [{0, 1, 2}, {3, 4, 5}]
|
| 10 |
+
assert len(C) == len(answer)
|
| 11 |
+
for s in answer:
|
| 12 |
+
assert s in C
|
| 13 |
+
|
| 14 |
+
G = nx.barbell_graph(3, 1)
|
| 15 |
+
C = nx.community.edge_betweenness_partition(G, 3)
|
| 16 |
+
answer = [{0, 1, 2}, {4, 5, 6}, {3}]
|
| 17 |
+
assert len(C) == len(answer)
|
| 18 |
+
for s in answer:
|
| 19 |
+
assert s in C
|
| 20 |
+
|
| 21 |
+
C = nx.community.edge_betweenness_partition(G, 7)
|
| 22 |
+
answer = [{n} for n in G]
|
| 23 |
+
assert len(C) == len(answer)
|
| 24 |
+
for s in answer:
|
| 25 |
+
assert s in C
|
| 26 |
+
|
| 27 |
+
C = nx.community.edge_betweenness_partition(G, 1)
|
| 28 |
+
assert C == [set(G)]
|
| 29 |
+
|
| 30 |
+
C = nx.community.edge_betweenness_partition(G, 1, weight="weight")
|
| 31 |
+
assert C == [set(G)]
|
| 32 |
+
|
| 33 |
+
with pytest.raises(nx.NetworkXError):
|
| 34 |
+
nx.community.edge_betweenness_partition(G, 0)
|
| 35 |
+
|
| 36 |
+
with pytest.raises(nx.NetworkXError):
|
| 37 |
+
nx.community.edge_betweenness_partition(G, -1)
|
| 38 |
+
|
| 39 |
+
with pytest.raises(nx.NetworkXError):
|
| 40 |
+
nx.community.edge_betweenness_partition(G, 10)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_edge_current_flow_betweenness_partition():
|
| 44 |
+
pytest.importorskip("scipy")
|
| 45 |
+
|
| 46 |
+
G = nx.barbell_graph(3, 0)
|
| 47 |
+
C = nx.community.edge_current_flow_betweenness_partition(G, 2)
|
| 48 |
+
answer = [{0, 1, 2}, {3, 4, 5}]
|
| 49 |
+
assert len(C) == len(answer)
|
| 50 |
+
for s in answer:
|
| 51 |
+
assert s in C
|
| 52 |
+
|
| 53 |
+
G = nx.barbell_graph(3, 1)
|
| 54 |
+
C = nx.community.edge_current_flow_betweenness_partition(G, 2)
|
| 55 |
+
answers = [[{0, 1, 2, 3}, {4, 5, 6}], [{0, 1, 2}, {3, 4, 5, 6}]]
|
| 56 |
+
assert len(C) == len(answers[0])
|
| 57 |
+
assert any(all(s in answer for s in C) for answer in answers)
|
| 58 |
+
|
| 59 |
+
C = nx.community.edge_current_flow_betweenness_partition(G, 3)
|
| 60 |
+
answer = [{0, 1, 2}, {4, 5, 6}, {3}]
|
| 61 |
+
assert len(C) == len(answer)
|
| 62 |
+
for s in answer:
|
| 63 |
+
assert s in C
|
| 64 |
+
|
| 65 |
+
C = nx.community.edge_current_flow_betweenness_partition(G, 4)
|
| 66 |
+
answers = [[{1, 2}, {4, 5, 6}, {3}, {0}], [{0, 1, 2}, {5, 6}, {3}, {4}]]
|
| 67 |
+
assert len(C) == len(answers[0])
|
| 68 |
+
assert any(all(s in answer for s in C) for answer in answers)
|
| 69 |
+
|
| 70 |
+
C = nx.community.edge_current_flow_betweenness_partition(G, 5)
|
| 71 |
+
answer = [{1, 2}, {5, 6}, {3}, {0}, {4}]
|
| 72 |
+
assert len(C) == len(answer)
|
| 73 |
+
for s in answer:
|
| 74 |
+
assert s in C
|
| 75 |
+
|
| 76 |
+
C = nx.community.edge_current_flow_betweenness_partition(G, 6)
|
| 77 |
+
answers = [[{2}, {5, 6}, {3}, {0}, {4}, {1}], [{1, 2}, {6}, {3}, {0}, {4}, {5}]]
|
| 78 |
+
assert len(C) == len(answers[0])
|
| 79 |
+
assert any(all(s in answer for s in C) for answer in answers)
|
| 80 |
+
|
| 81 |
+
C = nx.community.edge_current_flow_betweenness_partition(G, 7)
|
| 82 |
+
answer = [{n} for n in G]
|
| 83 |
+
assert len(C) == len(answer)
|
| 84 |
+
for s in answer:
|
| 85 |
+
assert s in C
|
| 86 |
+
|
| 87 |
+
C = nx.community.edge_current_flow_betweenness_partition(G, 1)
|
| 88 |
+
assert C == [set(G)]
|
| 89 |
+
|
| 90 |
+
C = nx.community.edge_current_flow_betweenness_partition(G, 1, weight="weight")
|
| 91 |
+
assert C == [set(G)]
|
| 92 |
+
|
| 93 |
+
with pytest.raises(nx.NetworkXError):
|
| 94 |
+
nx.community.edge_current_flow_betweenness_partition(G, 0)
|
| 95 |
+
|
| 96 |
+
with pytest.raises(nx.NetworkXError):
|
| 97 |
+
nx.community.edge_current_flow_betweenness_partition(G, -1)
|
| 98 |
+
|
| 99 |
+
with pytest.raises(nx.NetworkXError):
|
| 100 |
+
nx.community.edge_current_flow_betweenness_partition(G, 10)
|
| 101 |
+
|
| 102 |
+
N = 10
|
| 103 |
+
G = nx.empty_graph(N)
|
| 104 |
+
for i in range(2, N - 1):
|
| 105 |
+
C = nx.community.edge_current_flow_betweenness_partition(G, i)
|
| 106 |
+
assert C == [{n} for n in G]
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_kclique.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import combinations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_overlapping_K5():
|
| 9 |
+
G = nx.Graph()
|
| 10 |
+
G.add_edges_from(combinations(range(5), 2)) # Add a five clique
|
| 11 |
+
G.add_edges_from(combinations(range(2, 7), 2)) # Add another five clique
|
| 12 |
+
c = list(nx.community.k_clique_communities(G, 4))
|
| 13 |
+
assert c == [frozenset(range(7))]
|
| 14 |
+
c = set(nx.community.k_clique_communities(G, 5))
|
| 15 |
+
assert c == {frozenset(range(5)), frozenset(range(2, 7))}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_isolated_K5():
|
| 19 |
+
G = nx.Graph()
|
| 20 |
+
G.add_edges_from(combinations(range(5), 2)) # Add a five clique
|
| 21 |
+
G.add_edges_from(combinations(range(5, 10), 2)) # Add another five clique
|
| 22 |
+
c = set(nx.community.k_clique_communities(G, 5))
|
| 23 |
+
assert c == {frozenset(range(5)), frozenset(range(5, 10))}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class TestZacharyKarateClub:
|
| 27 |
+
def setup_method(self):
|
| 28 |
+
self.G = nx.karate_club_graph()
|
| 29 |
+
|
| 30 |
+
def _check_communities(self, k, expected):
|
| 31 |
+
communities = set(nx.community.k_clique_communities(self.G, k))
|
| 32 |
+
assert communities == expected
|
| 33 |
+
|
| 34 |
+
def test_k2(self):
|
| 35 |
+
# clique percolation with k=2 is just connected components
|
| 36 |
+
expected = {frozenset(self.G)}
|
| 37 |
+
self._check_communities(2, expected)
|
| 38 |
+
|
| 39 |
+
def test_k3(self):
|
| 40 |
+
comm1 = [
|
| 41 |
+
0,
|
| 42 |
+
1,
|
| 43 |
+
2,
|
| 44 |
+
3,
|
| 45 |
+
7,
|
| 46 |
+
8,
|
| 47 |
+
12,
|
| 48 |
+
13,
|
| 49 |
+
14,
|
| 50 |
+
15,
|
| 51 |
+
17,
|
| 52 |
+
18,
|
| 53 |
+
19,
|
| 54 |
+
20,
|
| 55 |
+
21,
|
| 56 |
+
22,
|
| 57 |
+
23,
|
| 58 |
+
26,
|
| 59 |
+
27,
|
| 60 |
+
28,
|
| 61 |
+
29,
|
| 62 |
+
30,
|
| 63 |
+
31,
|
| 64 |
+
32,
|
| 65 |
+
33,
|
| 66 |
+
]
|
| 67 |
+
comm2 = [0, 4, 5, 6, 10, 16]
|
| 68 |
+
comm3 = [24, 25, 31]
|
| 69 |
+
expected = {frozenset(comm1), frozenset(comm2), frozenset(comm3)}
|
| 70 |
+
self._check_communities(3, expected)
|
| 71 |
+
|
| 72 |
+
def test_k4(self):
|
| 73 |
+
expected = {
|
| 74 |
+
frozenset([0, 1, 2, 3, 7, 13]),
|
| 75 |
+
frozenset([8, 32, 30, 33]),
|
| 76 |
+
frozenset([32, 33, 29, 23]),
|
| 77 |
+
}
|
| 78 |
+
self._check_communities(4, expected)
|
| 79 |
+
|
| 80 |
+
def test_k5(self):
|
| 81 |
+
expected = {frozenset([0, 1, 2, 3, 7, 13])}
|
| 82 |
+
self._check_communities(5, expected)
|
| 83 |
+
|
| 84 |
+
def test_k6(self):
|
| 85 |
+
expected = set()
|
| 86 |
+
self._check_communities(6, expected)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_bad_k():
|
| 90 |
+
with pytest.raises(nx.NetworkXError):
|
| 91 |
+
list(nx.community.k_clique_communities(nx.Graph(), 1))
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_label_propagation.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import chain, combinations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_directed_not_supported():
|
| 9 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
| 10 |
+
# not supported for directed graphs
|
| 11 |
+
test = nx.DiGraph()
|
| 12 |
+
test.add_edge("a", "b")
|
| 13 |
+
test.add_edge("a", "c")
|
| 14 |
+
test.add_edge("b", "d")
|
| 15 |
+
result = nx.community.label_propagation_communities(test)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_iterator_vs_iterable():
|
| 19 |
+
G = nx.empty_graph("a")
|
| 20 |
+
assert list(nx.community.label_propagation_communities(G)) == [{"a"}]
|
| 21 |
+
for community in nx.community.label_propagation_communities(G):
|
| 22 |
+
assert community == {"a"}
|
| 23 |
+
pytest.raises(TypeError, next, nx.community.label_propagation_communities(G))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_one_node():
|
| 27 |
+
test = nx.Graph()
|
| 28 |
+
test.add_node("a")
|
| 29 |
+
|
| 30 |
+
# The expected communities are:
|
| 31 |
+
ground_truth = {frozenset(["a"])}
|
| 32 |
+
|
| 33 |
+
communities = nx.community.label_propagation_communities(test)
|
| 34 |
+
result = {frozenset(c) for c in communities}
|
| 35 |
+
assert result == ground_truth
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_unconnected_communities():
|
| 39 |
+
test = nx.Graph()
|
| 40 |
+
# community 1
|
| 41 |
+
test.add_edge("a", "c")
|
| 42 |
+
test.add_edge("a", "d")
|
| 43 |
+
test.add_edge("d", "c")
|
| 44 |
+
# community 2
|
| 45 |
+
test.add_edge("b", "e")
|
| 46 |
+
test.add_edge("e", "f")
|
| 47 |
+
test.add_edge("f", "b")
|
| 48 |
+
|
| 49 |
+
# The expected communities are:
|
| 50 |
+
ground_truth = {frozenset(["a", "c", "d"]), frozenset(["b", "e", "f"])}
|
| 51 |
+
|
| 52 |
+
communities = nx.community.label_propagation_communities(test)
|
| 53 |
+
result = {frozenset(c) for c in communities}
|
| 54 |
+
assert result == ground_truth
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_connected_communities():
|
| 58 |
+
test = nx.Graph()
|
| 59 |
+
# community 1
|
| 60 |
+
test.add_edge("a", "b")
|
| 61 |
+
test.add_edge("c", "a")
|
| 62 |
+
test.add_edge("c", "b")
|
| 63 |
+
test.add_edge("d", "a")
|
| 64 |
+
test.add_edge("d", "b")
|
| 65 |
+
test.add_edge("d", "c")
|
| 66 |
+
test.add_edge("e", "a")
|
| 67 |
+
test.add_edge("e", "b")
|
| 68 |
+
test.add_edge("e", "c")
|
| 69 |
+
test.add_edge("e", "d")
|
| 70 |
+
# community 2
|
| 71 |
+
test.add_edge("1", "2")
|
| 72 |
+
test.add_edge("3", "1")
|
| 73 |
+
test.add_edge("3", "2")
|
| 74 |
+
test.add_edge("4", "1")
|
| 75 |
+
test.add_edge("4", "2")
|
| 76 |
+
test.add_edge("4", "3")
|
| 77 |
+
test.add_edge("5", "1")
|
| 78 |
+
test.add_edge("5", "2")
|
| 79 |
+
test.add_edge("5", "3")
|
| 80 |
+
test.add_edge("5", "4")
|
| 81 |
+
# edge between community 1 and 2
|
| 82 |
+
test.add_edge("a", "1")
|
| 83 |
+
# community 3
|
| 84 |
+
test.add_edge("x", "y")
|
| 85 |
+
# community 4 with only a single node
|
| 86 |
+
test.add_node("z")
|
| 87 |
+
|
| 88 |
+
# The expected communities are:
|
| 89 |
+
ground_truth1 = {
|
| 90 |
+
frozenset(["a", "b", "c", "d", "e"]),
|
| 91 |
+
frozenset(["1", "2", "3", "4", "5"]),
|
| 92 |
+
frozenset(["x", "y"]),
|
| 93 |
+
frozenset(["z"]),
|
| 94 |
+
}
|
| 95 |
+
ground_truth2 = {
|
| 96 |
+
frozenset(["a", "b", "c", "d", "e", "1", "2", "3", "4", "5"]),
|
| 97 |
+
frozenset(["x", "y"]),
|
| 98 |
+
frozenset(["z"]),
|
| 99 |
+
}
|
| 100 |
+
ground_truth = (ground_truth1, ground_truth2)
|
| 101 |
+
|
| 102 |
+
communities = nx.community.label_propagation_communities(test)
|
| 103 |
+
result = {frozenset(c) for c in communities}
|
| 104 |
+
assert result in ground_truth
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_termination():
|
| 108 |
+
# ensure termination of asyn_lpa_communities in two cases
|
| 109 |
+
# that led to an endless loop in a previous version
|
| 110 |
+
test1 = nx.karate_club_graph()
|
| 111 |
+
test2 = nx.caveman_graph(2, 10)
|
| 112 |
+
test2.add_edges_from([(0, 20), (20, 10)])
|
| 113 |
+
nx.community.asyn_lpa_communities(test1)
|
| 114 |
+
nx.community.asyn_lpa_communities(test2)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class TestAsynLpaCommunities:
|
| 118 |
+
def _check_communities(self, G, expected):
|
| 119 |
+
"""Checks that the communities computed from the given graph ``G``
|
| 120 |
+
using the :func:`~networkx.asyn_lpa_communities` function match
|
| 121 |
+
the set of nodes given in ``expected``.
|
| 122 |
+
|
| 123 |
+
``expected`` must be a :class:`set` of :class:`frozenset`
|
| 124 |
+
instances, each element of which is a node in the graph.
|
| 125 |
+
|
| 126 |
+
"""
|
| 127 |
+
communities = nx.community.asyn_lpa_communities(G)
|
| 128 |
+
result = {frozenset(c) for c in communities}
|
| 129 |
+
assert result == expected
|
| 130 |
+
|
| 131 |
+
def test_null_graph(self):
|
| 132 |
+
G = nx.null_graph()
|
| 133 |
+
ground_truth = set()
|
| 134 |
+
self._check_communities(G, ground_truth)
|
| 135 |
+
|
| 136 |
+
def test_single_node(self):
|
| 137 |
+
G = nx.empty_graph(1)
|
| 138 |
+
ground_truth = {frozenset([0])}
|
| 139 |
+
self._check_communities(G, ground_truth)
|
| 140 |
+
|
| 141 |
+
def test_simple_communities(self):
|
| 142 |
+
# This graph is the disjoint union of two triangles.
|
| 143 |
+
G = nx.Graph(["ab", "ac", "bc", "de", "df", "fe"])
|
| 144 |
+
ground_truth = {frozenset("abc"), frozenset("def")}
|
| 145 |
+
self._check_communities(G, ground_truth)
|
| 146 |
+
|
| 147 |
+
def test_seed_argument(self):
|
| 148 |
+
G = nx.Graph(["ab", "ac", "bc", "de", "df", "fe"])
|
| 149 |
+
ground_truth = {frozenset("abc"), frozenset("def")}
|
| 150 |
+
communities = nx.community.asyn_lpa_communities(G, seed=1)
|
| 151 |
+
result = {frozenset(c) for c in communities}
|
| 152 |
+
assert result == ground_truth
|
| 153 |
+
|
| 154 |
+
def test_several_communities(self):
|
| 155 |
+
# This graph is the disjoint union of five triangles.
|
| 156 |
+
ground_truth = {frozenset(range(3 * i, 3 * (i + 1))) for i in range(5)}
|
| 157 |
+
edges = chain.from_iterable(combinations(c, 2) for c in ground_truth)
|
| 158 |
+
G = nx.Graph(edges)
|
| 159 |
+
self._check_communities(G, ground_truth)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class TestFastLabelPropagationCommunities:
|
| 163 |
+
N = 100 # number of nodes
|
| 164 |
+
K = 15 # average node degree
|
| 165 |
+
|
| 166 |
+
def _check_communities(self, G, truth, weight=None, seed=42):
|
| 167 |
+
C = nx.community.fast_label_propagation_communities(G, weight=weight, seed=seed)
|
| 168 |
+
assert {frozenset(c) for c in C} == truth
|
| 169 |
+
|
| 170 |
+
def test_null_graph(self):
|
| 171 |
+
G = nx.null_graph()
|
| 172 |
+
truth = set()
|
| 173 |
+
self._check_communities(G, truth)
|
| 174 |
+
|
| 175 |
+
def test_empty_graph(self):
|
| 176 |
+
G = nx.empty_graph(self.N)
|
| 177 |
+
truth = {frozenset([i]) for i in G}
|
| 178 |
+
self._check_communities(G, truth)
|
| 179 |
+
|
| 180 |
+
def test_star_graph(self):
|
| 181 |
+
G = nx.star_graph(self.N)
|
| 182 |
+
truth = {frozenset(G)}
|
| 183 |
+
self._check_communities(G, truth)
|
| 184 |
+
|
| 185 |
+
def test_complete_graph(self):
|
| 186 |
+
G = nx.complete_graph(self.N)
|
| 187 |
+
truth = {frozenset(G)}
|
| 188 |
+
self._check_communities(G, truth)
|
| 189 |
+
|
| 190 |
+
def test_bipartite_graph(self):
|
| 191 |
+
G = nx.complete_bipartite_graph(self.N // 2, self.N // 2)
|
| 192 |
+
truth = {frozenset(G)}
|
| 193 |
+
self._check_communities(G, truth)
|
| 194 |
+
|
| 195 |
+
def test_random_graph(self):
|
| 196 |
+
G = nx.gnm_random_graph(self.N, self.N * self.K // 2, seed=42)
|
| 197 |
+
truth = {frozenset(G)}
|
| 198 |
+
self._check_communities(G, truth)
|
| 199 |
+
|
| 200 |
+
def test_disjoin_cliques(self):
|
| 201 |
+
G = nx.Graph(["ab", "AB", "AC", "BC", "12", "13", "14", "23", "24", "34"])
|
| 202 |
+
truth = {frozenset("ab"), frozenset("ABC"), frozenset("1234")}
|
| 203 |
+
self._check_communities(G, truth)
|
| 204 |
+
|
| 205 |
+
def test_ring_of_cliques(self):
|
| 206 |
+
N, K = self.N, self.K
|
| 207 |
+
G = nx.ring_of_cliques(N, K)
|
| 208 |
+
truth = {frozenset([K * i + k for k in range(K)]) for i in range(N)}
|
| 209 |
+
self._check_communities(G, truth)
|
| 210 |
+
|
| 211 |
+
def test_larger_graph(self):
|
| 212 |
+
G = nx.gnm_random_graph(100 * self.N, 50 * self.N * self.K, seed=42)
|
| 213 |
+
nx.community.fast_label_propagation_communities(G)
|
| 214 |
+
|
| 215 |
+
def test_graph_type(self):
|
| 216 |
+
G1 = nx.complete_graph(self.N, nx.MultiDiGraph())
|
| 217 |
+
G2 = nx.MultiGraph(G1)
|
| 218 |
+
G3 = nx.DiGraph(G1)
|
| 219 |
+
G4 = nx.Graph(G1)
|
| 220 |
+
truth = {frozenset(G1)}
|
| 221 |
+
self._check_communities(G1, truth)
|
| 222 |
+
self._check_communities(G2, truth)
|
| 223 |
+
self._check_communities(G3, truth)
|
| 224 |
+
self._check_communities(G4, truth)
|
| 225 |
+
|
| 226 |
+
def test_weight_argument(self):
|
| 227 |
+
G = nx.MultiDiGraph()
|
| 228 |
+
G.add_edge(1, 2, weight=1.41)
|
| 229 |
+
G.add_edge(2, 1, weight=1.41)
|
| 230 |
+
G.add_edge(2, 3)
|
| 231 |
+
G.add_edge(3, 4, weight=3.14)
|
| 232 |
+
truth = {frozenset({1, 2}), frozenset({3, 4})}
|
| 233 |
+
self._check_communities(G, truth, weight="weight")
|
| 234 |
+
|
| 235 |
+
def test_seed_argument(self):
|
| 236 |
+
G = nx.karate_club_graph()
|
| 237 |
+
C = nx.community.fast_label_propagation_communities(G, seed=2023)
|
| 238 |
+
truth = {frozenset(c) for c in C}
|
| 239 |
+
self._check_communities(G, truth, seed=2023)
|
| 240 |
+
# smoke test that seed=None works
|
| 241 |
+
C = nx.community.fast_label_propagation_communities(G, seed=None)
|
.venv/lib/python3.11/site-packages/networkx/algorithms/community/tests/test_leiden.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.algorithms.community import leiden_communities, leiden_partitions
|
| 5 |
+
|
| 6 |
+
# Leiden is not yet implemented by networkx, so only run tests in this file for
|
| 7 |
+
# backends that implement Leiden.
|
| 8 |
+
no_backends_for_leiden_communities = (
|
| 9 |
+
"not set(nx.config.backend_priority.algos) & leiden_communities.backends"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
no_backends_for_leiden_partitions = (
|
| 13 |
+
"not set(nx.config.backend_priority.algos) & leiden_partitions.backends"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_leiden_with_nx_backend():
|
| 18 |
+
G = nx.karate_club_graph()
|
| 19 |
+
with pytest.raises(NotImplementedError):
|
| 20 |
+
nx.community.leiden_partitions(G, backend="networkx")
|
| 21 |
+
with pytest.raises(NotImplementedError):
|
| 22 |
+
nx.community.leiden_communities(G, backend="networkx")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.mark.skipif(no_backends_for_leiden_communities)
|
| 26 |
+
def test_modularity_increase():
|
| 27 |
+
G = nx.LFR_benchmark_graph(
|
| 28 |
+
250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
|
| 29 |
+
)
|
| 30 |
+
partition = [{u} for u in G.nodes()]
|
| 31 |
+
mod = nx.community.modularity(G, partition)
|
| 32 |
+
partition = nx.community.leiden_communities(G)
|
| 33 |
+
|
| 34 |
+
assert nx.community.modularity(G, partition) > mod
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.mark.skipif(no_backends_for_leiden_communities)
|
| 38 |
+
def test_valid_partition():
|
| 39 |
+
G = nx.LFR_benchmark_graph(
|
| 40 |
+
250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
|
| 41 |
+
)
|
| 42 |
+
partition = nx.community.leiden_communities(G)
|
| 43 |
+
|
| 44 |
+
assert nx.community.is_partition(G, partition)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@pytest.mark.skipif(no_backends_for_leiden_partitions)
|
| 48 |
+
def test_partition_iterator():
|
| 49 |
+
G = nx.path_graph(15)
|
| 50 |
+
parts_iter = nx.community.leiden_partitions(G, seed=42)
|
| 51 |
+
first_part = next(parts_iter)
|
| 52 |
+
first_copy = [s.copy() for s in first_part]
|
| 53 |
+
|
| 54 |
+
# check 1st part stays fixed even after 2nd iteration (like gh-5901 in louvain)
|
| 55 |
+
assert first_copy[0] == first_part[0]
|
| 56 |
+
second_part = next(parts_iter)
|
| 57 |
+
assert first_copy[0] == first_part[0]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@pytest.mark.skipif(no_backends_for_leiden_communities)
|
| 61 |
+
def test_none_weight_param():
|
| 62 |
+
G = nx.karate_club_graph()
|
| 63 |
+
nx.set_edge_attributes(
|
| 64 |
+
G, {edge: i * i for i, edge in enumerate(G.edges)}, name="foo"
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
partition1 = nx.community.leiden_communities(G, weight=None, seed=2)
|
| 68 |
+
partition2 = nx.community.leiden_communities(G, weight="foo", seed=2)
|
| 69 |
+
partition3 = nx.community.leiden_communities(G, weight="weight", seed=2)
|
| 70 |
+
|
| 71 |
+
assert partition1 != partition2
|
| 72 |
+
assert partition2 != partition3
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@pytest.mark.skipif(no_backends_for_leiden_communities)
|
| 76 |
+
def test_quality():
|
| 77 |
+
G = nx.LFR_benchmark_graph(
|
| 78 |
+
250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
|
| 79 |
+
)
|
| 80 |
+
H = nx.MultiGraph(G)
|
| 81 |
+
|
| 82 |
+
partition = nx.community.leiden_communities(G)
|
| 83 |
+
partition2 = nx.community.leiden_communities(H)
|
| 84 |
+
|
| 85 |
+
quality = nx.community.partition_quality(G, partition)[0]
|
| 86 |
+
quality2 = nx.community.partition_quality(H, partition2)[0]
|
| 87 |
+
|
| 88 |
+
assert quality >= 0.65
|
| 89 |
+
assert quality2 >= 0.65
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@pytest.mark.skipif(no_backends_for_leiden_communities)
|
| 93 |
+
def test_resolution():
|
| 94 |
+
G = nx.LFR_benchmark_graph(
|
| 95 |
+
250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
partition1 = nx.community.leiden_communities(G, resolution=0.5, seed=12)
|
| 99 |
+
partition2 = nx.community.leiden_communities(G, seed=12)
|
| 100 |
+
partition3 = nx.community.leiden_communities(G, resolution=2, seed=12)
|
| 101 |
+
|
| 102 |
+
assert len(partition1) <= len(partition2)
|
| 103 |
+
assert len(partition2) <= len(partition3)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@pytest.mark.skipif(no_backends_for_leiden_communities)
|
| 107 |
+
def test_empty_graph():
|
| 108 |
+
G = nx.Graph()
|
| 109 |
+
G.add_nodes_from(range(5))
|
| 110 |
+
expected = [{0}, {1}, {2}, {3}, {4}]
|
| 111 |
+
assert nx.community.leiden_communities(G) == expected
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@pytest.mark.skipif(no_backends_for_leiden_communities)
|
| 115 |
+
def test_directed_not_implemented():
|
| 116 |
+
G = nx.cycle_graph(4, create_using=nx.DiGraph)
|
| 117 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
| 118 |
+
nx.community.leiden_communities(G)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@pytest.mark.skipif(no_backends_for_leiden_partitions)
|
| 122 |
+
@pytest.mark.skipif(no_backends_for_leiden_communities)
|
| 123 |
+
def test_max_level():
|
| 124 |
+
G = nx.LFR_benchmark_graph(
|
| 125 |
+
250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
|
| 126 |
+
)
|
| 127 |
+
parts_iter = nx.community.leiden_partitions(G, seed=42)
|
| 128 |
+
for max_level, expected in enumerate(parts_iter, 1):
|
| 129 |
+
partition = nx.community.leiden_communities(G, max_level=max_level, seed=42)
|
| 130 |
+
assert partition == expected
|
| 131 |
+
assert max_level > 1 # Ensure we are actually testing max_level
|
| 132 |
+
# max_level is an upper limit; it's okay if we stop before it's hit.
|
| 133 |
+
partition = nx.community.leiden_communities(G, max_level=max_level + 1, seed=42)
|
| 134 |
+
assert partition == expected
|
| 135 |
+
with pytest.raises(
|
| 136 |
+
ValueError, match="max_level argument must be a positive integer"
|
| 137 |
+
):
|
| 138 |
+
nx.community.leiden_communities(G, max_level=0)
|