Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +181 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/approximation/vertex_cover.py +83 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/__init__.py +5 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/connectivity.py +122 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/correlation.py +302 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/mixing.py +255 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/neighbor_degree.py +160 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/pairs.py +127 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/__init__.py +88 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/basic.py +322 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/centrality.py +290 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/cluster.py +289 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/covering.py +57 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/edgelist.py +360 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/extendability.py +105 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/generators.py +603 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/link_analysis.py +316 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/matching.py +590 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/matrix.py +168 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/projection.py +526 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/redundancy.py +112 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/spectral.py +69 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/__init__.py +20 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/betweenness.py +469 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/betweenness_subset.py +275 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/closeness.py +282 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/current_flow_betweenness.py +342 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/current_flow_betweenness_subset.py +227 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/current_flow_closeness.py +96 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/degree_alg.py +150 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/dispersion.py +107 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/eigenvector.py +357 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/flow_matrix.py +130 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/group.py +787 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/harmonic.py +89 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/katz.py +331 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/laplacian.py +150 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/load.py +200 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/percolation.py +128 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/reaching.py +209 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/second_order.py +141 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/subgraph_alg.py +342 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/trophic.py +181 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/voterank_alg.py +95 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/coloring/__init__.py +4 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/coloring/equitable_coloring.py +505 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/coloring/greedy_coloring.py +565 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/community/__init__.py +28 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/community/asyn_fluid.py +151 -0
- platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/community/centrality.py +171 -0
.gitattributes
CHANGED
|
@@ -1022,3 +1022,184 @@ platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-pack
|
|
| 1022 |
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_fp.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1023 |
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_functions2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1024 |
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/multiprocess/tests/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1022 |
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_fp.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1023 |
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/mpmath/tests/__pycache__/test_functions2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1024 |
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/multiprocess/tests/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1025 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1026 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/core/__pycache__/pythonapi.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1027 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/core/__pycache__/byteflow.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1028 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/core/__pycache__/interpreter.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1029 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/core/__pycache__/ir_utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1030 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/core/runtime/_nrt_python.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1031 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/core/typeconv/_typeconv.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1032 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/cpython/__pycache__/randomimpl.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1033 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/cpython/__pycache__/unicode.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1034 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/driver.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1035 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_atomics.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1036 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/np/__pycache__/arrayobj.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1037 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/np/__pycache__/linalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1038 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/np/__pycache__/new_arraymath.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1039 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/np/__pycache__/old_arraymath.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1040 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/np/ufunc/_internal.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1041 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/np/ufunc/omppool.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1042 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/np/ufunc/tbbpool.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1043 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/np/ufunc/workqueue.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1044 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/parfors/__pycache__/array_analysis.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1045 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/parfors/__pycache__/parfor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1046 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_methods.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1047 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_dictobject.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1048 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_dyn_array.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1049 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_linalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1050 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_extending.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1051 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_lists.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1052 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_jitclasses.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1053 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_np_functions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1054 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_parfors.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1055 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_random.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1056 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_ufuncs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1057 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_unicode.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1058 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numba/tests/__pycache__/test_stencils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1059 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/_multiarray_tests.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1060 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/_multiarray_umath.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1061 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/_simd.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1062 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/linalg/_umath_linalg.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1063 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/random/_bounded_integers.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1064 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/random/_common.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1065 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/random/_generator.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1066 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/random/_mt19937.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1067 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/random/_pcg64.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1068 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/random/_philox.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1069 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/random/bit_generator.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1070 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/random/mtrand.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1071 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/__pycache__/_add_newdocs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1072 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/__pycache__/fromnumeric.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1073 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/tests/__pycache__/test_multiarray.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1074 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/tests/__pycache__/test_nditer.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1075 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/tests/__pycache__/test_regression.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1076 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/tests/__pycache__/test_datetime.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1077 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/tests/__pycache__/test_dtype.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1078 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/tests/__pycache__/test_ufunc.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1079 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/tests/__pycache__/test_umath.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1080 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/core/tests/__pycache__/test_numeric.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1081 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/f2py/__pycache__/crackfortran.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1082 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/lib/__pycache__/function_base.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1083 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/lib/tests/__pycache__/test_function_base.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1084 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/lib/tests/__pycache__/test_io.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1085 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/linalg/__pycache__/linalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1086 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/linalg/tests/__pycache__/test_linalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1087 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/ma/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1088 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/ma/tests/__pycache__/test_core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1089 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/ma/tests/__pycache__/test_extras.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1090 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/random/tests/__pycache__/test_generator_mt19937.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1091 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/random/tests/__pycache__/test_random.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1092 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/random/tests/__pycache__/test_randomstate.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1093 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/numpy/testing/tests/__pycache__/test_utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1094 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cublas/lib/libcublas.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1095 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cublas/lib/libcublasLt.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1096 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cublas/lib/libnvblas.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1097 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cuda_cupti/lib/libcheckpoint.so filter=lfs diff=lfs merge=lfs -text
|
| 1098 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cuda_cupti/lib/libcupti.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1099 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cuda_cupti/lib/libnvperf_host.so filter=lfs diff=lfs merge=lfs -text
|
| 1100 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cuda_cupti/lib/libnvperf_target.so filter=lfs diff=lfs merge=lfs -text
|
| 1101 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cuda_cupti/lib/libpcsamplingutil.so filter=lfs diff=lfs merge=lfs -text
|
| 1102 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.so.12.1 filter=lfs diff=lfs merge=lfs -text
|
| 1103 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1104 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cuda_runtime/lib/libcudart.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1105 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cudnn/lib/libcudnn.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 1106 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cudnn/lib/libcudnn_adv_infer.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 1107 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cudnn/lib/libcudnn_adv_train.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 1108 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cudnn/lib/libcudnn_cnn_infer.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 1109 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cudnn/lib/libcudnn_cnn_train.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 1110 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cudnn/lib/libcudnn_ops_infer.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 1111 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cudnn/lib/libcudnn_ops_train.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 1112 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cufft/lib/libcufft.so.11 filter=lfs diff=lfs merge=lfs -text
|
| 1113 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cufft/lib/libcufftw.so.11 filter=lfs diff=lfs merge=lfs -text
|
| 1114 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cufile/lib/libcufile.so.0 filter=lfs diff=lfs merge=lfs -text
|
| 1115 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/curand/lib/libcurand.so.10 filter=lfs diff=lfs merge=lfs -text
|
| 1116 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cusolver/lib/libcusolver.so.11 filter=lfs diff=lfs merge=lfs -text
|
| 1117 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cusolver/lib/libcusolverMg.so.11 filter=lfs diff=lfs merge=lfs -text
|
| 1118 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cusparse/lib/libcusparse.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1119 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/cusparselt/lib/libcusparseLt.so.0 filter=lfs diff=lfs merge=lfs -text
|
| 1120 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/nccl/lib/libnccl.so.2 filter=lfs diff=lfs merge=lfs -text
|
| 1121 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/nvidia/nvjitlink/lib/libnvJitLink.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1122 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/onnxruntime/capi/libonnxruntime.so.1.22.1 filter=lfs diff=lfs merge=lfs -text
|
| 1123 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/onnxruntime/capi/onnxruntime_pybind11_state.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1124 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/onnxruntime/tools/__pycache__/symbolic_shape_infer.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1125 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/onnxruntime/transformers/__pycache__/convert_generation.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1126 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/optree/__pycache__/ops.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1127 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/algos.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1128 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/sas.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1129 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/arrays.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1130 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/sparse.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1131 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/groupby.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1132 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/hashing.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1133 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/testing.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1134 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/hashtable.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1135 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/index.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1136 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/internals.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1137 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/interval.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1138 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/join.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1139 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/lib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1140 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/missing.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1141 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/ops.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1142 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/reshape.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1143 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/parsers.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1144 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1145 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/writers.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1146 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/conversion.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1147 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/dtypes.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1148 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/fields.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1149 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/nattype.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1150 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/np_datetime.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1151 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/offsets.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1152 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/parsing.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1153 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/period.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1154 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/strptime.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1155 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/timedeltas.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1156 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/timestamps.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1157 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/timezones.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1158 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/tzconversion.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1159 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/tslibs/vectorized.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1160 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/window/aggregations.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1161 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/_libs/window/indexers.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1162 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/__pycache__/frame.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1163 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/__pycache__/generic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1164 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/__pycache__/indexing.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1165 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/__pycache__/resample.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1166 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/__pycache__/series.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1167 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/arrays/__pycache__/categorical.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1168 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/arrays/arrow/__pycache__/array.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1169 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/groupby/__pycache__/generic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1170 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/groupby/__pycache__/groupby.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1171 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/indexes/__pycache__/base.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1172 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/indexes/__pycache__/multi.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1173 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/core/strings/__pycache__/accessor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1174 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1175 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1176 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1177 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/io/formats/__pycache__/style.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1178 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/__pycache__/test_algos.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1179 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_datetime64.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1180 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_timedelta64.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1181 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/computation/__pycache__/test_eval.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1182 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_methods.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1183 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/dtypes/__pycache__/test_inference.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1184 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/extension/__pycache__/test_arrow.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1185 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_arithmetic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1186 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_constructors.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1187 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_reductions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1188 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/frame/__pycache__/test_stack_unstack.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1189 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/frame/indexing/__pycache__/test_indexing.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1190 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/groupby/__pycache__/test_categorical.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1191 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/groupby/__pycache__/test_groupby.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1192 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/indexing/__pycache__/test_loc.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1193 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/io/__pycache__/test_sql.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1194 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/io/__pycache__/test_stata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1195 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/io/formats/__pycache__/test_format.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1196 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/io/json/__pycache__/test_pandas.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1197 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/plotting/__pycache__/test_datetimelike.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1198 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/plotting/frame/__pycache__/test_frame.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1199 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/resample/__pycache__/test_datetime_index.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1200 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/reshape/__pycache__/test_pivot.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1201 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/reshape/merge/__pycache__/test_merge.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1202 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/series/__pycache__/test_constructors.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1203 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/pandas/tests/tools/__pycache__/test_to_datetime.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1204 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/paramiko/__pycache__/transport.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1205 |
+
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/phonenumbers/__pycache__/phonenumberutil.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/approximation/vertex_cover.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for computing an approximate minimum weight vertex cover.
|
| 2 |
+
|
| 3 |
+
A |vertex cover|_ is a subset of nodes such that each edge in the graph
|
| 4 |
+
is incident to at least one node in the subset.
|
| 5 |
+
|
| 6 |
+
.. _vertex cover: https://en.wikipedia.org/wiki/Vertex_cover
|
| 7 |
+
.. |vertex cover| replace:: *vertex cover*
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import networkx as nx
|
| 12 |
+
|
| 13 |
+
__all__ = ["min_weighted_vertex_cover"]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@nx._dispatchable(node_attrs="weight")
|
| 17 |
+
def min_weighted_vertex_cover(G, weight=None):
|
| 18 |
+
r"""Returns an approximate minimum weighted vertex cover.
|
| 19 |
+
|
| 20 |
+
The set of nodes returned by this function is guaranteed to be a
|
| 21 |
+
vertex cover, and the total weight of the set is guaranteed to be at
|
| 22 |
+
most twice the total weight of the minimum weight vertex cover. In
|
| 23 |
+
other words,
|
| 24 |
+
|
| 25 |
+
.. math::
|
| 26 |
+
|
| 27 |
+
w(S) \leq 2 * w(S^*),
|
| 28 |
+
|
| 29 |
+
where $S$ is the vertex cover returned by this function,
|
| 30 |
+
$S^*$ is the vertex cover of minimum weight out of all vertex
|
| 31 |
+
covers of the graph, and $w$ is the function that computes the
|
| 32 |
+
sum of the weights of each node in that given set.
|
| 33 |
+
|
| 34 |
+
Parameters
|
| 35 |
+
----------
|
| 36 |
+
G : NetworkX graph
|
| 37 |
+
|
| 38 |
+
weight : string, optional (default = None)
|
| 39 |
+
If None, every node has weight 1. If a string, use this node
|
| 40 |
+
attribute as the node weight. A node without this attribute is
|
| 41 |
+
assumed to have weight 1.
|
| 42 |
+
|
| 43 |
+
Returns
|
| 44 |
+
-------
|
| 45 |
+
min_weighted_cover : set
|
| 46 |
+
Returns a set of nodes whose weight sum is no more than twice
|
| 47 |
+
the weight sum of the minimum weight vertex cover.
|
| 48 |
+
|
| 49 |
+
Notes
|
| 50 |
+
-----
|
| 51 |
+
For a directed graph, a vertex cover has the same definition: a set
|
| 52 |
+
of nodes such that each edge in the graph is incident to at least
|
| 53 |
+
one node in the set. Whether the node is the head or tail of the
|
| 54 |
+
directed edge is ignored.
|
| 55 |
+
|
| 56 |
+
This is the local-ratio algorithm for computing an approximate
|
| 57 |
+
vertex cover. The algorithm greedily reduces the costs over edges,
|
| 58 |
+
iteratively building a cover. The worst-case runtime of this
|
| 59 |
+
implementation is $O(m \log n)$, where $n$ is the number
|
| 60 |
+
of nodes and $m$ the number of edges in the graph.
|
| 61 |
+
|
| 62 |
+
References
|
| 63 |
+
----------
|
| 64 |
+
.. [1] Bar-Yehuda, R., and Even, S. (1985). "A local-ratio theorem for
|
| 65 |
+
approximating the weighted vertex cover problem."
|
| 66 |
+
*Annals of Discrete Mathematics*, 25, 27–46
|
| 67 |
+
<http://www.cs.technion.ac.il/~reuven/PDF/vc_lr.pdf>
|
| 68 |
+
|
| 69 |
+
"""
|
| 70 |
+
cost = dict(G.nodes(data=weight, default=1))
|
| 71 |
+
# While there are uncovered edges, choose an uncovered and update
|
| 72 |
+
# the cost of the remaining edges.
|
| 73 |
+
cover = set()
|
| 74 |
+
for u, v in G.edges():
|
| 75 |
+
if u in cover or v in cover:
|
| 76 |
+
continue
|
| 77 |
+
if cost[u] <= cost[v]:
|
| 78 |
+
cover.add(u)
|
| 79 |
+
cost[v] -= cost[u]
|
| 80 |
+
else:
|
| 81 |
+
cover.add(v)
|
| 82 |
+
cost[u] -= cost[v]
|
| 83 |
+
return cover
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from networkx.algorithms.assortativity.connectivity import *
|
| 2 |
+
from networkx.algorithms.assortativity.correlation import *
|
| 3 |
+
from networkx.algorithms.assortativity.mixing import *
|
| 4 |
+
from networkx.algorithms.assortativity.neighbor_degree import *
|
| 5 |
+
from networkx.algorithms.assortativity.pairs import *
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/connectivity.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = ["average_degree_connectivity"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 9 |
+
def average_degree_connectivity(
|
| 10 |
+
G, source="in+out", target="in+out", nodes=None, weight=None
|
| 11 |
+
):
|
| 12 |
+
r"""Compute the average degree connectivity of graph.
|
| 13 |
+
|
| 14 |
+
The average degree connectivity is the average nearest neighbor degree of
|
| 15 |
+
nodes with degree k. For weighted graphs, an analogous measure can
|
| 16 |
+
be computed using the weighted average neighbors degree defined in
|
| 17 |
+
[1]_, for a node `i`, as
|
| 18 |
+
|
| 19 |
+
.. math::
|
| 20 |
+
|
| 21 |
+
k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
|
| 22 |
+
|
| 23 |
+
where `s_i` is the weighted degree of node `i`,
|
| 24 |
+
`w_{ij}` is the weight of the edge that links `i` and `j`,
|
| 25 |
+
and `N(i)` are the neighbors of node `i`.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
G : NetworkX graph
|
| 30 |
+
|
| 31 |
+
source : "in"|"out"|"in+out" (default:"in+out")
|
| 32 |
+
Directed graphs only. Use "in"- or "out"-degree for source node.
|
| 33 |
+
|
| 34 |
+
target : "in"|"out"|"in+out" (default:"in+out"
|
| 35 |
+
Directed graphs only. Use "in"- or "out"-degree for target node.
|
| 36 |
+
|
| 37 |
+
nodes : list or iterable (optional)
|
| 38 |
+
Compute neighbor connectivity for these nodes. The default is all
|
| 39 |
+
nodes.
|
| 40 |
+
|
| 41 |
+
weight : string or None, optional (default=None)
|
| 42 |
+
The edge attribute that holds the numerical value used as a weight.
|
| 43 |
+
If None, then each edge has weight 1.
|
| 44 |
+
|
| 45 |
+
Returns
|
| 46 |
+
-------
|
| 47 |
+
d : dict
|
| 48 |
+
A dictionary keyed by degree k with the value of average connectivity.
|
| 49 |
+
|
| 50 |
+
Raises
|
| 51 |
+
------
|
| 52 |
+
NetworkXError
|
| 53 |
+
If either `source` or `target` are not one of 'in',
|
| 54 |
+
'out', or 'in+out'.
|
| 55 |
+
If either `source` or `target` is passed for an undirected graph.
|
| 56 |
+
|
| 57 |
+
Examples
|
| 58 |
+
--------
|
| 59 |
+
>>> G = nx.path_graph(4)
|
| 60 |
+
>>> G.edges[1, 2]["weight"] = 3
|
| 61 |
+
>>> nx.average_degree_connectivity(G)
|
| 62 |
+
{1: 2.0, 2: 1.5}
|
| 63 |
+
>>> nx.average_degree_connectivity(G, weight="weight")
|
| 64 |
+
{1: 2.0, 2: 1.75}
|
| 65 |
+
|
| 66 |
+
See Also
|
| 67 |
+
--------
|
| 68 |
+
average_neighbor_degree
|
| 69 |
+
|
| 70 |
+
References
|
| 71 |
+
----------
|
| 72 |
+
.. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
|
| 73 |
+
"The architecture of complex weighted networks".
|
| 74 |
+
PNAS 101 (11): 3747–3752 (2004).
|
| 75 |
+
"""
|
| 76 |
+
# First, determine the type of neighbors and the type of degree to use.
|
| 77 |
+
if G.is_directed():
|
| 78 |
+
if source not in ("in", "out", "in+out"):
|
| 79 |
+
raise nx.NetworkXError('source must be one of "in", "out", or "in+out"')
|
| 80 |
+
if target not in ("in", "out", "in+out"):
|
| 81 |
+
raise nx.NetworkXError('target must be one of "in", "out", or "in+out"')
|
| 82 |
+
direction = {"out": G.out_degree, "in": G.in_degree, "in+out": G.degree}
|
| 83 |
+
neighbor_funcs = {
|
| 84 |
+
"out": G.successors,
|
| 85 |
+
"in": G.predecessors,
|
| 86 |
+
"in+out": G.neighbors,
|
| 87 |
+
}
|
| 88 |
+
source_degree = direction[source]
|
| 89 |
+
target_degree = direction[target]
|
| 90 |
+
neighbors = neighbor_funcs[source]
|
| 91 |
+
# `reverse` indicates whether to look at the in-edge when
|
| 92 |
+
# computing the weight of an edge.
|
| 93 |
+
reverse = source == "in"
|
| 94 |
+
else:
|
| 95 |
+
if source != "in+out" or target != "in+out":
|
| 96 |
+
raise nx.NetworkXError(
|
| 97 |
+
f"source and target arguments are only supported for directed graphs"
|
| 98 |
+
)
|
| 99 |
+
source_degree = G.degree
|
| 100 |
+
target_degree = G.degree
|
| 101 |
+
neighbors = G.neighbors
|
| 102 |
+
reverse = False
|
| 103 |
+
dsum = defaultdict(int)
|
| 104 |
+
dnorm = defaultdict(int)
|
| 105 |
+
# Check if `source_nodes` is actually a single node in the graph.
|
| 106 |
+
source_nodes = source_degree(nodes)
|
| 107 |
+
if nodes in G:
|
| 108 |
+
source_nodes = [(nodes, source_degree(nodes))]
|
| 109 |
+
for n, k in source_nodes:
|
| 110 |
+
nbrdeg = target_degree(neighbors(n))
|
| 111 |
+
if weight is None:
|
| 112 |
+
s = sum(d for n, d in nbrdeg)
|
| 113 |
+
else: # weight nbr degree by weight of (n,nbr) edge
|
| 114 |
+
if reverse:
|
| 115 |
+
s = sum(G[nbr][n].get(weight, 1) * d for nbr, d in nbrdeg)
|
| 116 |
+
else:
|
| 117 |
+
s = sum(G[n][nbr].get(weight, 1) * d for nbr, d in nbrdeg)
|
| 118 |
+
dnorm[k] += source_degree(n, weight=weight)
|
| 119 |
+
dsum[k] += s
|
| 120 |
+
|
| 121 |
+
# normalize
|
| 122 |
+
return {k: avg if dnorm[k] == 0 else avg / dnorm[k] for k, avg in dsum.items()}
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/correlation.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Node assortativity coefficients and correlation measures."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.algorithms.assortativity.mixing import (
|
| 5 |
+
attribute_mixing_matrix,
|
| 6 |
+
degree_mixing_matrix,
|
| 7 |
+
)
|
| 8 |
+
from networkx.algorithms.assortativity.pairs import node_degree_xy
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"degree_pearson_correlation_coefficient",
|
| 12 |
+
"degree_assortativity_coefficient",
|
| 13 |
+
"attribute_assortativity_coefficient",
|
| 14 |
+
"numeric_assortativity_coefficient",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 19 |
+
def degree_assortativity_coefficient(G, x="out", y="in", weight=None, nodes=None):
|
| 20 |
+
"""Compute degree assortativity of graph.
|
| 21 |
+
|
| 22 |
+
Assortativity measures the similarity of connections
|
| 23 |
+
in the graph with respect to the node degree.
|
| 24 |
+
|
| 25 |
+
Parameters
|
| 26 |
+
----------
|
| 27 |
+
G : NetworkX graph
|
| 28 |
+
|
| 29 |
+
x: string ('in','out')
|
| 30 |
+
The degree type for source node (directed graphs only).
|
| 31 |
+
|
| 32 |
+
y: string ('in','out')
|
| 33 |
+
The degree type for target node (directed graphs only).
|
| 34 |
+
|
| 35 |
+
weight: string or None, optional (default=None)
|
| 36 |
+
The edge attribute that holds the numerical value used
|
| 37 |
+
as a weight. If None, then each edge has weight 1.
|
| 38 |
+
The degree is the sum of the edge weights adjacent to the node.
|
| 39 |
+
|
| 40 |
+
nodes: list or iterable (optional)
|
| 41 |
+
Compute degree assortativity only for nodes in container.
|
| 42 |
+
The default is all nodes.
|
| 43 |
+
|
| 44 |
+
Returns
|
| 45 |
+
-------
|
| 46 |
+
r : float
|
| 47 |
+
Assortativity of graph by degree.
|
| 48 |
+
|
| 49 |
+
Examples
|
| 50 |
+
--------
|
| 51 |
+
>>> G = nx.path_graph(4)
|
| 52 |
+
>>> r = nx.degree_assortativity_coefficient(G)
|
| 53 |
+
>>> print(f"{r:3.1f}")
|
| 54 |
+
-0.5
|
| 55 |
+
|
| 56 |
+
See Also
|
| 57 |
+
--------
|
| 58 |
+
attribute_assortativity_coefficient
|
| 59 |
+
numeric_assortativity_coefficient
|
| 60 |
+
degree_mixing_dict
|
| 61 |
+
degree_mixing_matrix
|
| 62 |
+
|
| 63 |
+
Notes
|
| 64 |
+
-----
|
| 65 |
+
This computes Eq. (21) in Ref. [1]_ , where e is the joint
|
| 66 |
+
probability distribution (mixing matrix) of the degrees. If G is
|
| 67 |
+
directed than the matrix e is the joint probability of the
|
| 68 |
+
user-specified degree type for the source and target.
|
| 69 |
+
|
| 70 |
+
References
|
| 71 |
+
----------
|
| 72 |
+
.. [1] M. E. J. Newman, Mixing patterns in networks,
|
| 73 |
+
Physical Review E, 67 026126, 2003
|
| 74 |
+
.. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
|
| 75 |
+
Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
|
| 76 |
+
"""
|
| 77 |
+
if nodes is None:
|
| 78 |
+
nodes = G.nodes
|
| 79 |
+
|
| 80 |
+
degrees = None
|
| 81 |
+
|
| 82 |
+
if G.is_directed():
|
| 83 |
+
indeg = (
|
| 84 |
+
{d for _, d in G.in_degree(nodes, weight=weight)}
|
| 85 |
+
if "in" in (x, y)
|
| 86 |
+
else set()
|
| 87 |
+
)
|
| 88 |
+
outdeg = (
|
| 89 |
+
{d for _, d in G.out_degree(nodes, weight=weight)}
|
| 90 |
+
if "out" in (x, y)
|
| 91 |
+
else set()
|
| 92 |
+
)
|
| 93 |
+
degrees = set.union(indeg, outdeg)
|
| 94 |
+
else:
|
| 95 |
+
degrees = {d for _, d in G.degree(nodes, weight=weight)}
|
| 96 |
+
|
| 97 |
+
mapping = {d: i for i, d in enumerate(degrees)}
|
| 98 |
+
M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)
|
| 99 |
+
|
| 100 |
+
return _numeric_ac(M, mapping=mapping)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 104 |
+
def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, nodes=None):
|
| 105 |
+
"""Compute degree assortativity of graph.
|
| 106 |
+
|
| 107 |
+
Assortativity measures the similarity of connections
|
| 108 |
+
in the graph with respect to the node degree.
|
| 109 |
+
|
| 110 |
+
This is the same as degree_assortativity_coefficient but uses the
|
| 111 |
+
potentially faster scipy.stats.pearsonr function.
|
| 112 |
+
|
| 113 |
+
Parameters
|
| 114 |
+
----------
|
| 115 |
+
G : NetworkX graph
|
| 116 |
+
|
| 117 |
+
x: string ('in','out')
|
| 118 |
+
The degree type for source node (directed graphs only).
|
| 119 |
+
|
| 120 |
+
y: string ('in','out')
|
| 121 |
+
The degree type for target node (directed graphs only).
|
| 122 |
+
|
| 123 |
+
weight: string or None, optional (default=None)
|
| 124 |
+
The edge attribute that holds the numerical value used
|
| 125 |
+
as a weight. If None, then each edge has weight 1.
|
| 126 |
+
The degree is the sum of the edge weights adjacent to the node.
|
| 127 |
+
|
| 128 |
+
nodes: list or iterable (optional)
|
| 129 |
+
Compute pearson correlation of degrees only for specified nodes.
|
| 130 |
+
The default is all nodes.
|
| 131 |
+
|
| 132 |
+
Returns
|
| 133 |
+
-------
|
| 134 |
+
r : float
|
| 135 |
+
Assortativity of graph by degree.
|
| 136 |
+
|
| 137 |
+
Examples
|
| 138 |
+
--------
|
| 139 |
+
>>> G = nx.path_graph(4)
|
| 140 |
+
>>> r = nx.degree_pearson_correlation_coefficient(G)
|
| 141 |
+
>>> print(f"{r:3.1f}")
|
| 142 |
+
-0.5
|
| 143 |
+
|
| 144 |
+
Notes
|
| 145 |
+
-----
|
| 146 |
+
This calls scipy.stats.pearsonr.
|
| 147 |
+
|
| 148 |
+
References
|
| 149 |
+
----------
|
| 150 |
+
.. [1] M. E. J. Newman, Mixing patterns in networks
|
| 151 |
+
Physical Review E, 67 026126, 2003
|
| 152 |
+
.. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
|
| 153 |
+
Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
|
| 154 |
+
"""
|
| 155 |
+
import scipy as sp
|
| 156 |
+
|
| 157 |
+
xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
|
| 158 |
+
x, y = zip(*xy)
|
| 159 |
+
return float(sp.stats.pearsonr(x, y)[0])
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@nx._dispatchable(node_attrs="attribute")
|
| 163 |
+
def attribute_assortativity_coefficient(G, attribute, nodes=None):
|
| 164 |
+
"""Compute assortativity for node attributes.
|
| 165 |
+
|
| 166 |
+
Assortativity measures the similarity of connections
|
| 167 |
+
in the graph with respect to the given attribute.
|
| 168 |
+
|
| 169 |
+
Parameters
|
| 170 |
+
----------
|
| 171 |
+
G : NetworkX graph
|
| 172 |
+
|
| 173 |
+
attribute : string
|
| 174 |
+
Node attribute key
|
| 175 |
+
|
| 176 |
+
nodes: list or iterable (optional)
|
| 177 |
+
Compute attribute assortativity for nodes in container.
|
| 178 |
+
The default is all nodes.
|
| 179 |
+
|
| 180 |
+
Returns
|
| 181 |
+
-------
|
| 182 |
+
r: float
|
| 183 |
+
Assortativity of graph for given attribute
|
| 184 |
+
|
| 185 |
+
Examples
|
| 186 |
+
--------
|
| 187 |
+
>>> G = nx.Graph()
|
| 188 |
+
>>> G.add_nodes_from([0, 1], color="red")
|
| 189 |
+
>>> G.add_nodes_from([2, 3], color="blue")
|
| 190 |
+
>>> G.add_edges_from([(0, 1), (2, 3)])
|
| 191 |
+
>>> print(nx.attribute_assortativity_coefficient(G, "color"))
|
| 192 |
+
1.0
|
| 193 |
+
|
| 194 |
+
Notes
|
| 195 |
+
-----
|
| 196 |
+
This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)),
|
| 197 |
+
where M is the joint probability distribution (mixing matrix)
|
| 198 |
+
of the specified attribute.
|
| 199 |
+
|
| 200 |
+
References
|
| 201 |
+
----------
|
| 202 |
+
.. [1] M. E. J. Newman, Mixing patterns in networks,
|
| 203 |
+
Physical Review E, 67 026126, 2003
|
| 204 |
+
"""
|
| 205 |
+
M = attribute_mixing_matrix(G, attribute, nodes)
|
| 206 |
+
return attribute_ac(M)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@nx._dispatchable(node_attrs="attribute")
|
| 210 |
+
def numeric_assortativity_coefficient(G, attribute, nodes=None):
|
| 211 |
+
"""Compute assortativity for numerical node attributes.
|
| 212 |
+
|
| 213 |
+
Assortativity measures the similarity of connections
|
| 214 |
+
in the graph with respect to the given numeric attribute.
|
| 215 |
+
|
| 216 |
+
Parameters
|
| 217 |
+
----------
|
| 218 |
+
G : NetworkX graph
|
| 219 |
+
|
| 220 |
+
attribute : string
|
| 221 |
+
Node attribute key.
|
| 222 |
+
|
| 223 |
+
nodes: list or iterable (optional)
|
| 224 |
+
Compute numeric assortativity only for attributes of nodes in
|
| 225 |
+
container. The default is all nodes.
|
| 226 |
+
|
| 227 |
+
Returns
|
| 228 |
+
-------
|
| 229 |
+
r: float
|
| 230 |
+
Assortativity of graph for given attribute
|
| 231 |
+
|
| 232 |
+
Examples
|
| 233 |
+
--------
|
| 234 |
+
>>> G = nx.Graph()
|
| 235 |
+
>>> G.add_nodes_from([0, 1], size=2)
|
| 236 |
+
>>> G.add_nodes_from([2, 3], size=3)
|
| 237 |
+
>>> G.add_edges_from([(0, 1), (2, 3)])
|
| 238 |
+
>>> print(nx.numeric_assortativity_coefficient(G, "size"))
|
| 239 |
+
1.0
|
| 240 |
+
|
| 241 |
+
Notes
|
| 242 |
+
-----
|
| 243 |
+
This computes Eq. (21) in Ref. [1]_ , which is the Pearson correlation
|
| 244 |
+
coefficient of the specified (scalar valued) attribute across edges.
|
| 245 |
+
|
| 246 |
+
References
|
| 247 |
+
----------
|
| 248 |
+
.. [1] M. E. J. Newman, Mixing patterns in networks
|
| 249 |
+
Physical Review E, 67 026126, 2003
|
| 250 |
+
"""
|
| 251 |
+
if nodes is None:
|
| 252 |
+
nodes = G.nodes
|
| 253 |
+
vals = {G.nodes[n][attribute] for n in nodes}
|
| 254 |
+
mapping = {d: i for i, d in enumerate(vals)}
|
| 255 |
+
M = attribute_mixing_matrix(G, attribute, nodes, mapping)
|
| 256 |
+
return _numeric_ac(M, mapping)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def attribute_ac(M):
|
| 260 |
+
"""Compute assortativity for attribute matrix M.
|
| 261 |
+
|
| 262 |
+
Parameters
|
| 263 |
+
----------
|
| 264 |
+
M : numpy.ndarray
|
| 265 |
+
2D ndarray representing the attribute mixing matrix.
|
| 266 |
+
|
| 267 |
+
Notes
|
| 268 |
+
-----
|
| 269 |
+
This computes Eq. (2) in Ref. [1]_ , (trace(e)-sum(e^2))/(1-sum(e^2)),
|
| 270 |
+
where e is the joint probability distribution (mixing matrix)
|
| 271 |
+
of the specified attribute.
|
| 272 |
+
|
| 273 |
+
References
|
| 274 |
+
----------
|
| 275 |
+
.. [1] M. E. J. Newman, Mixing patterns in networks,
|
| 276 |
+
Physical Review E, 67 026126, 2003
|
| 277 |
+
"""
|
| 278 |
+
if M.sum() != 1.0:
|
| 279 |
+
M = M / M.sum()
|
| 280 |
+
s = (M @ M).sum()
|
| 281 |
+
t = M.trace()
|
| 282 |
+
r = (t - s) / (1 - s)
|
| 283 |
+
return float(r)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def _numeric_ac(M, mapping):
|
| 287 |
+
# M is a 2D numpy array
|
| 288 |
+
# numeric assortativity coefficient, pearsonr
|
| 289 |
+
import numpy as np
|
| 290 |
+
|
| 291 |
+
if M.sum() != 1.0:
|
| 292 |
+
M = M / M.sum()
|
| 293 |
+
x = np.array(list(mapping.keys()))
|
| 294 |
+
y = x # x and y have the same support
|
| 295 |
+
idx = list(mapping.values())
|
| 296 |
+
a = M.sum(axis=0)
|
| 297 |
+
b = M.sum(axis=1)
|
| 298 |
+
vara = (a[idx] * x**2).sum() - ((a[idx] * x).sum()) ** 2
|
| 299 |
+
varb = (b[idx] * y**2).sum() - ((b[idx] * y).sum()) ** 2
|
| 300 |
+
xy = np.outer(x, y)
|
| 301 |
+
ab = np.outer(a[idx], b[idx])
|
| 302 |
+
return float((xy * (M - ab)).sum() / np.sqrt(vara * varb))
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/mixing.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Mixing matrices for node attributes and degree.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.algorithms.assortativity.pairs import node_attribute_xy, node_degree_xy
|
| 7 |
+
from networkx.utils import dict_to_numpy_array
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
"attribute_mixing_matrix",
|
| 11 |
+
"attribute_mixing_dict",
|
| 12 |
+
"degree_mixing_matrix",
|
| 13 |
+
"degree_mixing_dict",
|
| 14 |
+
"mixing_dict",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@nx._dispatchable(node_attrs="attribute")
|
| 19 |
+
def attribute_mixing_dict(G, attribute, nodes=None, normalized=False):
|
| 20 |
+
"""Returns dictionary representation of mixing matrix for attribute.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
G : graph
|
| 25 |
+
NetworkX graph object.
|
| 26 |
+
|
| 27 |
+
attribute : string
|
| 28 |
+
Node attribute key.
|
| 29 |
+
|
| 30 |
+
nodes: list or iterable (optional)
|
| 31 |
+
Unse nodes in container to build the dict. The default is all nodes.
|
| 32 |
+
|
| 33 |
+
normalized : bool (default=False)
|
| 34 |
+
Return counts if False or probabilities if True.
|
| 35 |
+
|
| 36 |
+
Examples
|
| 37 |
+
--------
|
| 38 |
+
>>> G = nx.Graph()
|
| 39 |
+
>>> G.add_nodes_from([0, 1], color="red")
|
| 40 |
+
>>> G.add_nodes_from([2, 3], color="blue")
|
| 41 |
+
>>> G.add_edge(1, 3)
|
| 42 |
+
>>> d = nx.attribute_mixing_dict(G, "color")
|
| 43 |
+
>>> print(d["red"]["blue"])
|
| 44 |
+
1
|
| 45 |
+
>>> print(d["blue"]["red"]) # d symmetric for undirected graphs
|
| 46 |
+
1
|
| 47 |
+
|
| 48 |
+
Returns
|
| 49 |
+
-------
|
| 50 |
+
d : dictionary
|
| 51 |
+
Counts or joint probability of occurrence of attribute pairs.
|
| 52 |
+
"""
|
| 53 |
+
xy_iter = node_attribute_xy(G, attribute, nodes)
|
| 54 |
+
return mixing_dict(xy_iter, normalized=normalized)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@nx._dispatchable(node_attrs="attribute")
|
| 58 |
+
def attribute_mixing_matrix(G, attribute, nodes=None, mapping=None, normalized=True):
|
| 59 |
+
"""Returns mixing matrix for attribute.
|
| 60 |
+
|
| 61 |
+
Parameters
|
| 62 |
+
----------
|
| 63 |
+
G : graph
|
| 64 |
+
NetworkX graph object.
|
| 65 |
+
|
| 66 |
+
attribute : string
|
| 67 |
+
Node attribute key.
|
| 68 |
+
|
| 69 |
+
nodes: list or iterable (optional)
|
| 70 |
+
Use only nodes in container to build the matrix. The default is
|
| 71 |
+
all nodes.
|
| 72 |
+
|
| 73 |
+
mapping : dictionary, optional
|
| 74 |
+
Mapping from node attribute to integer index in matrix.
|
| 75 |
+
If not specified, an arbitrary ordering will be used.
|
| 76 |
+
|
| 77 |
+
normalized : bool (default=True)
|
| 78 |
+
Return counts if False or probabilities if True.
|
| 79 |
+
|
| 80 |
+
Returns
|
| 81 |
+
-------
|
| 82 |
+
m: numpy array
|
| 83 |
+
Counts or joint probability of occurrence of attribute pairs.
|
| 84 |
+
|
| 85 |
+
Notes
|
| 86 |
+
-----
|
| 87 |
+
If each node has a unique attribute value, the unnormalized mixing matrix
|
| 88 |
+
will be equal to the adjacency matrix. To get a denser mixing matrix,
|
| 89 |
+
the rounding can be performed to form groups of nodes with equal values.
|
| 90 |
+
For example, the exact height of persons in cm (180.79155222, 163.9080892,
|
| 91 |
+
163.30095355, 167.99016217, 168.21590163, ...) can be rounded to (180, 163,
|
| 92 |
+
163, 168, 168, ...).
|
| 93 |
+
|
| 94 |
+
Definitions of attribute mixing matrix vary on whether the matrix
|
| 95 |
+
should include rows for attribute values that don't arise. Here we
|
| 96 |
+
do not include such empty-rows. But you can force them to appear
|
| 97 |
+
by inputting a `mapping` that includes those values.
|
| 98 |
+
|
| 99 |
+
Examples
|
| 100 |
+
--------
|
| 101 |
+
>>> G = nx.path_graph(3)
|
| 102 |
+
>>> gender = {0: "male", 1: "female", 2: "female"}
|
| 103 |
+
>>> nx.set_node_attributes(G, gender, "gender")
|
| 104 |
+
>>> mapping = {"male": 0, "female": 1}
|
| 105 |
+
>>> mix_mat = nx.attribute_mixing_matrix(G, "gender", mapping=mapping)
|
| 106 |
+
>>> mix_mat
|
| 107 |
+
array([[0. , 0.25],
|
| 108 |
+
[0.25, 0.5 ]])
|
| 109 |
+
"""
|
| 110 |
+
d = attribute_mixing_dict(G, attribute, nodes)
|
| 111 |
+
a = dict_to_numpy_array(d, mapping=mapping)
|
| 112 |
+
if normalized:
|
| 113 |
+
a = a / a.sum()
|
| 114 |
+
return a
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 118 |
+
def degree_mixing_dict(G, x="out", y="in", weight=None, nodes=None, normalized=False):
|
| 119 |
+
"""Returns dictionary representation of mixing matrix for degree.
|
| 120 |
+
|
| 121 |
+
Parameters
|
| 122 |
+
----------
|
| 123 |
+
G : graph
|
| 124 |
+
NetworkX graph object.
|
| 125 |
+
|
| 126 |
+
x: string ('in','out')
|
| 127 |
+
The degree type for source node (directed graphs only).
|
| 128 |
+
|
| 129 |
+
y: string ('in','out')
|
| 130 |
+
The degree type for target node (directed graphs only).
|
| 131 |
+
|
| 132 |
+
weight: string or None, optional (default=None)
|
| 133 |
+
The edge attribute that holds the numerical value used
|
| 134 |
+
as a weight. If None, then each edge has weight 1.
|
| 135 |
+
The degree is the sum of the edge weights adjacent to the node.
|
| 136 |
+
|
| 137 |
+
normalized : bool (default=False)
|
| 138 |
+
Return counts if False or probabilities if True.
|
| 139 |
+
|
| 140 |
+
Returns
|
| 141 |
+
-------
|
| 142 |
+
d: dictionary
|
| 143 |
+
Counts or joint probability of occurrence of degree pairs.
|
| 144 |
+
"""
|
| 145 |
+
xy_iter = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
|
| 146 |
+
return mixing_dict(xy_iter, normalized=normalized)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 150 |
+
def degree_mixing_matrix(
|
| 151 |
+
G, x="out", y="in", weight=None, nodes=None, normalized=True, mapping=None
|
| 152 |
+
):
|
| 153 |
+
"""Returns mixing matrix for attribute.
|
| 154 |
+
|
| 155 |
+
Parameters
|
| 156 |
+
----------
|
| 157 |
+
G : graph
|
| 158 |
+
NetworkX graph object.
|
| 159 |
+
|
| 160 |
+
x: string ('in','out')
|
| 161 |
+
The degree type for source node (directed graphs only).
|
| 162 |
+
|
| 163 |
+
y: string ('in','out')
|
| 164 |
+
The degree type for target node (directed graphs only).
|
| 165 |
+
|
| 166 |
+
nodes: list or iterable (optional)
|
| 167 |
+
Build the matrix using only nodes in container.
|
| 168 |
+
The default is all nodes.
|
| 169 |
+
|
| 170 |
+
weight: string or None, optional (default=None)
|
| 171 |
+
The edge attribute that holds the numerical value used
|
| 172 |
+
as a weight. If None, then each edge has weight 1.
|
| 173 |
+
The degree is the sum of the edge weights adjacent to the node.
|
| 174 |
+
|
| 175 |
+
normalized : bool (default=True)
|
| 176 |
+
Return counts if False or probabilities if True.
|
| 177 |
+
|
| 178 |
+
mapping : dictionary, optional
|
| 179 |
+
Mapping from node degree to integer index in matrix.
|
| 180 |
+
If not specified, an arbitrary ordering will be used.
|
| 181 |
+
|
| 182 |
+
Returns
|
| 183 |
+
-------
|
| 184 |
+
m: numpy array
|
| 185 |
+
Counts, or joint probability, of occurrence of node degree.
|
| 186 |
+
|
| 187 |
+
Notes
|
| 188 |
+
-----
|
| 189 |
+
Definitions of degree mixing matrix vary on whether the matrix
|
| 190 |
+
should include rows for degree values that don't arise. Here we
|
| 191 |
+
do not include such empty-rows. But you can force them to appear
|
| 192 |
+
by inputting a `mapping` that includes those values. See examples.
|
| 193 |
+
|
| 194 |
+
Examples
|
| 195 |
+
--------
|
| 196 |
+
>>> G = nx.star_graph(3)
|
| 197 |
+
>>> mix_mat = nx.degree_mixing_matrix(G)
|
| 198 |
+
>>> mix_mat
|
| 199 |
+
array([[0. , 0.5],
|
| 200 |
+
[0.5, 0. ]])
|
| 201 |
+
|
| 202 |
+
If you want every possible degree to appear as a row, even if no nodes
|
| 203 |
+
have that degree, use `mapping` as follows,
|
| 204 |
+
|
| 205 |
+
>>> max_degree = max(deg for n, deg in G.degree)
|
| 206 |
+
>>> mapping = {x: x for x in range(max_degree + 1)} # identity mapping
|
| 207 |
+
>>> mix_mat = nx.degree_mixing_matrix(G, mapping=mapping)
|
| 208 |
+
>>> mix_mat
|
| 209 |
+
array([[0. , 0. , 0. , 0. ],
|
| 210 |
+
[0. , 0. , 0. , 0.5],
|
| 211 |
+
[0. , 0. , 0. , 0. ],
|
| 212 |
+
[0. , 0.5, 0. , 0. ]])
|
| 213 |
+
"""
|
| 214 |
+
d = degree_mixing_dict(G, x=x, y=y, nodes=nodes, weight=weight)
|
| 215 |
+
a = dict_to_numpy_array(d, mapping=mapping)
|
| 216 |
+
if normalized:
|
| 217 |
+
a = a / a.sum()
|
| 218 |
+
return a
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def mixing_dict(xy, normalized=False):
|
| 222 |
+
"""Returns a dictionary representation of mixing matrix.
|
| 223 |
+
|
| 224 |
+
Parameters
|
| 225 |
+
----------
|
| 226 |
+
xy : list or container of two-tuples
|
| 227 |
+
Pairs of (x,y) items.
|
| 228 |
+
|
| 229 |
+
attribute : string
|
| 230 |
+
Node attribute key
|
| 231 |
+
|
| 232 |
+
normalized : bool (default=False)
|
| 233 |
+
Return counts if False or probabilities if True.
|
| 234 |
+
|
| 235 |
+
Returns
|
| 236 |
+
-------
|
| 237 |
+
d: dictionary
|
| 238 |
+
Counts or Joint probability of occurrence of values in xy.
|
| 239 |
+
"""
|
| 240 |
+
d = {}
|
| 241 |
+
psum = 0.0
|
| 242 |
+
for x, y in xy:
|
| 243 |
+
if x not in d:
|
| 244 |
+
d[x] = {}
|
| 245 |
+
if y not in d:
|
| 246 |
+
d[y] = {}
|
| 247 |
+
v = d[x].get(y, 0)
|
| 248 |
+
d[x][y] = v + 1
|
| 249 |
+
psum += 1
|
| 250 |
+
|
| 251 |
+
if normalized:
|
| 252 |
+
for _, jdict in d.items():
|
| 253 |
+
for j in jdict:
|
| 254 |
+
jdict[j] /= psum
|
| 255 |
+
return d
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/neighbor_degree.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import networkx as nx
|
| 2 |
+
|
| 3 |
+
__all__ = ["average_neighbor_degree"]
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 7 |
+
def average_neighbor_degree(G, source="out", target="out", nodes=None, weight=None):
|
| 8 |
+
r"""Returns the average degree of the neighborhood of each node.
|
| 9 |
+
|
| 10 |
+
In an undirected graph, the neighborhood `N(i)` of node `i` contains the
|
| 11 |
+
nodes that are connected to `i` by an edge.
|
| 12 |
+
|
| 13 |
+
For directed graphs, `N(i)` is defined according to the parameter `source`:
|
| 14 |
+
|
| 15 |
+
- if source is 'in', then `N(i)` consists of predecessors of node `i`.
|
| 16 |
+
- if source is 'out', then `N(i)` consists of successors of node `i`.
|
| 17 |
+
- if source is 'in+out', then `N(i)` is both predecessors and successors.
|
| 18 |
+
|
| 19 |
+
The average neighborhood degree of a node `i` is
|
| 20 |
+
|
| 21 |
+
.. math::
|
| 22 |
+
|
| 23 |
+
k_{nn,i} = \frac{1}{|N(i)|} \sum_{j \in N(i)} k_j
|
| 24 |
+
|
| 25 |
+
where `N(i)` are the neighbors of node `i` and `k_j` is
|
| 26 |
+
the degree of node `j` which belongs to `N(i)`. For weighted
|
| 27 |
+
graphs, an analogous measure can be defined [1]_,
|
| 28 |
+
|
| 29 |
+
.. math::
|
| 30 |
+
|
| 31 |
+
k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
|
| 32 |
+
|
| 33 |
+
where `s_i` is the weighted degree of node `i`, `w_{ij}`
|
| 34 |
+
is the weight of the edge that links `i` and `j` and
|
| 35 |
+
`N(i)` are the neighbors of node `i`.
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
G : NetworkX graph
|
| 41 |
+
|
| 42 |
+
source : string ("in"|"out"|"in+out"), optional (default="out")
|
| 43 |
+
Directed graphs only.
|
| 44 |
+
Use "in"- or "out"-neighbors of source node.
|
| 45 |
+
|
| 46 |
+
target : string ("in"|"out"|"in+out"), optional (default="out")
|
| 47 |
+
Directed graphs only.
|
| 48 |
+
Use "in"- or "out"-degree for target node.
|
| 49 |
+
|
| 50 |
+
nodes : list or iterable, optional (default=G.nodes)
|
| 51 |
+
Compute neighbor degree only for specified nodes.
|
| 52 |
+
|
| 53 |
+
weight : string or None, optional (default=None)
|
| 54 |
+
The edge attribute that holds the numerical value used as a weight.
|
| 55 |
+
If None, then each edge has weight 1.
|
| 56 |
+
|
| 57 |
+
Returns
|
| 58 |
+
-------
|
| 59 |
+
d: dict
|
| 60 |
+
A dictionary keyed by node to the average degree of its neighbors.
|
| 61 |
+
|
| 62 |
+
Raises
|
| 63 |
+
------
|
| 64 |
+
NetworkXError
|
| 65 |
+
If either `source` or `target` are not one of 'in', 'out', or 'in+out'.
|
| 66 |
+
If either `source` or `target` is passed for an undirected graph.
|
| 67 |
+
|
| 68 |
+
Examples
|
| 69 |
+
--------
|
| 70 |
+
>>> G = nx.path_graph(4)
|
| 71 |
+
>>> G.edges[0, 1]["weight"] = 5
|
| 72 |
+
>>> G.edges[2, 3]["weight"] = 3
|
| 73 |
+
|
| 74 |
+
>>> nx.average_neighbor_degree(G)
|
| 75 |
+
{0: 2.0, 1: 1.5, 2: 1.5, 3: 2.0}
|
| 76 |
+
>>> nx.average_neighbor_degree(G, weight="weight")
|
| 77 |
+
{0: 2.0, 1: 1.1666666666666667, 2: 1.25, 3: 2.0}
|
| 78 |
+
|
| 79 |
+
>>> G = nx.DiGraph()
|
| 80 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
| 81 |
+
>>> nx.average_neighbor_degree(G, source="in", target="in")
|
| 82 |
+
{0: 0.0, 1: 0.0, 2: 1.0, 3: 1.0}
|
| 83 |
+
|
| 84 |
+
>>> nx.average_neighbor_degree(G, source="out", target="out")
|
| 85 |
+
{0: 1.0, 1: 1.0, 2: 0.0, 3: 0.0}
|
| 86 |
+
|
| 87 |
+
See Also
|
| 88 |
+
--------
|
| 89 |
+
average_degree_connectivity
|
| 90 |
+
|
| 91 |
+
References
|
| 92 |
+
----------
|
| 93 |
+
.. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
|
| 94 |
+
"The architecture of complex weighted networks".
|
| 95 |
+
PNAS 101 (11): 3747–3752 (2004).
|
| 96 |
+
"""
|
| 97 |
+
if G.is_directed():
|
| 98 |
+
if source == "in":
|
| 99 |
+
source_degree = G.in_degree
|
| 100 |
+
elif source == "out":
|
| 101 |
+
source_degree = G.out_degree
|
| 102 |
+
elif source == "in+out":
|
| 103 |
+
source_degree = G.degree
|
| 104 |
+
else:
|
| 105 |
+
raise nx.NetworkXError(
|
| 106 |
+
f"source argument {source} must be 'in', 'out' or 'in+out'"
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
if target == "in":
|
| 110 |
+
target_degree = G.in_degree
|
| 111 |
+
elif target == "out":
|
| 112 |
+
target_degree = G.out_degree
|
| 113 |
+
elif target == "in+out":
|
| 114 |
+
target_degree = G.degree
|
| 115 |
+
else:
|
| 116 |
+
raise nx.NetworkXError(
|
| 117 |
+
f"target argument {target} must be 'in', 'out' or 'in+out'"
|
| 118 |
+
)
|
| 119 |
+
else:
|
| 120 |
+
if source != "out" or target != "out":
|
| 121 |
+
raise nx.NetworkXError(
|
| 122 |
+
f"source and target arguments are only supported for directed graphs"
|
| 123 |
+
)
|
| 124 |
+
source_degree = target_degree = G.degree
|
| 125 |
+
|
| 126 |
+
# precompute target degrees -- should *not* be weighted degree
|
| 127 |
+
t_deg = dict(target_degree())
|
| 128 |
+
|
| 129 |
+
# Set up both predecessor and successor neighbor dicts leaving empty if not needed
|
| 130 |
+
G_P = G_S = {n: {} for n in G}
|
| 131 |
+
if G.is_directed():
|
| 132 |
+
# "in" or "in+out" cases: G_P contains predecessors
|
| 133 |
+
if "in" in source:
|
| 134 |
+
G_P = G.pred
|
| 135 |
+
# "out" or "in+out" cases: G_S contains successors
|
| 136 |
+
if "out" in source:
|
| 137 |
+
G_S = G.succ
|
| 138 |
+
else:
|
| 139 |
+
# undirected leave G_P empty but G_S is the adjacency
|
| 140 |
+
G_S = G.adj
|
| 141 |
+
|
| 142 |
+
# Main loop: Compute average degree of neighbors
|
| 143 |
+
avg = {}
|
| 144 |
+
for n, deg in source_degree(nodes, weight=weight):
|
| 145 |
+
# handle degree zero average
|
| 146 |
+
if deg == 0:
|
| 147 |
+
avg[n] = 0.0
|
| 148 |
+
continue
|
| 149 |
+
|
| 150 |
+
# we sum over both G_P and G_S, but one of the two is usually empty.
|
| 151 |
+
if weight is None:
|
| 152 |
+
avg[n] = (
|
| 153 |
+
sum(t_deg[nbr] for nbr in G_S[n]) + sum(t_deg[nbr] for nbr in G_P[n])
|
| 154 |
+
) / deg
|
| 155 |
+
else:
|
| 156 |
+
avg[n] = (
|
| 157 |
+
sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_S[n].items())
|
| 158 |
+
+ sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_P[n].items())
|
| 159 |
+
) / deg
|
| 160 |
+
return avg
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/assortativity/pairs.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generators of x-y pairs of node data."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = ["node_attribute_xy", "node_degree_xy"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@nx._dispatchable(node_attrs="attribute")
|
| 9 |
+
def node_attribute_xy(G, attribute, nodes=None):
|
| 10 |
+
"""Yields 2-tuples of node attribute values for all edges in `G`.
|
| 11 |
+
|
| 12 |
+
This generator yields, for each edge in `G` incident to a node in `nodes`,
|
| 13 |
+
a 2-tuple of form ``(attribute value, attribute value)`` for the parameter
|
| 14 |
+
specified node-attribute.
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
----------
|
| 18 |
+
G: NetworkX graph
|
| 19 |
+
|
| 20 |
+
attribute: key
|
| 21 |
+
The node attribute key.
|
| 22 |
+
|
| 23 |
+
nodes: list or iterable (optional)
|
| 24 |
+
Use only edges that are incident to specified nodes.
|
| 25 |
+
The default is all nodes.
|
| 26 |
+
|
| 27 |
+
Yields
|
| 28 |
+
------
|
| 29 |
+
(x, y): 2-tuple
|
| 30 |
+
Generates 2-tuple of (attribute, attribute) values.
|
| 31 |
+
|
| 32 |
+
Examples
|
| 33 |
+
--------
|
| 34 |
+
>>> G = nx.DiGraph()
|
| 35 |
+
>>> G.add_node(1, color="red")
|
| 36 |
+
>>> G.add_node(2, color="blue")
|
| 37 |
+
>>> G.add_node(3, color="green")
|
| 38 |
+
>>> G.add_edge(1, 2)
|
| 39 |
+
>>> list(nx.node_attribute_xy(G, "color"))
|
| 40 |
+
[('red', 'blue')]
|
| 41 |
+
|
| 42 |
+
Notes
|
| 43 |
+
-----
|
| 44 |
+
For undirected graphs, each edge is produced twice, once for each edge
|
| 45 |
+
representation (u, v) and (v, u), with the exception of self-loop edges
|
| 46 |
+
which only appear once.
|
| 47 |
+
"""
|
| 48 |
+
if nodes is None:
|
| 49 |
+
nodes = set(G)
|
| 50 |
+
else:
|
| 51 |
+
nodes = set(nodes)
|
| 52 |
+
Gnodes = G.nodes
|
| 53 |
+
for u, nbrsdict in G.adjacency():
|
| 54 |
+
if u not in nodes:
|
| 55 |
+
continue
|
| 56 |
+
uattr = Gnodes[u].get(attribute, None)
|
| 57 |
+
if G.is_multigraph():
|
| 58 |
+
for v, keys in nbrsdict.items():
|
| 59 |
+
vattr = Gnodes[v].get(attribute, None)
|
| 60 |
+
for _ in keys:
|
| 61 |
+
yield (uattr, vattr)
|
| 62 |
+
else:
|
| 63 |
+
for v in nbrsdict:
|
| 64 |
+
vattr = Gnodes[v].get(attribute, None)
|
| 65 |
+
yield (uattr, vattr)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 69 |
+
def node_degree_xy(G, x="out", y="in", weight=None, nodes=None):
|
| 70 |
+
"""Yields 2-tuples of ``(degree, degree)`` values for edges in `G`.
|
| 71 |
+
|
| 72 |
+
This generator yields, for each edge in `G` incident to a node in `nodes`,
|
| 73 |
+
a 2-tuple of form ``(degree, degree)``. The node degrees are weighted
|
| 74 |
+
when a `weight` attribute is specified.
|
| 75 |
+
|
| 76 |
+
Parameters
|
| 77 |
+
----------
|
| 78 |
+
G: NetworkX graph
|
| 79 |
+
|
| 80 |
+
x: string ('in','out')
|
| 81 |
+
The degree type for source node (directed graphs only).
|
| 82 |
+
|
| 83 |
+
y: string ('in','out')
|
| 84 |
+
The degree type for target node (directed graphs only).
|
| 85 |
+
|
| 86 |
+
weight: string or None, optional (default=None)
|
| 87 |
+
The edge attribute that holds the numerical value used
|
| 88 |
+
as a weight. If None, then each edge has weight 1.
|
| 89 |
+
The degree is the sum of the edge weights adjacent to the node.
|
| 90 |
+
|
| 91 |
+
nodes: list or iterable (optional)
|
| 92 |
+
Use only edges that are adjacency to specified nodes.
|
| 93 |
+
The default is all nodes.
|
| 94 |
+
|
| 95 |
+
Yields
|
| 96 |
+
------
|
| 97 |
+
(x, y): 2-tuple
|
| 98 |
+
Generates 2-tuple of (degree, degree) values.
|
| 99 |
+
|
| 100 |
+
Examples
|
| 101 |
+
--------
|
| 102 |
+
>>> G = nx.DiGraph()
|
| 103 |
+
>>> G.add_edge(1, 2)
|
| 104 |
+
>>> list(nx.node_degree_xy(G, x="out", y="in"))
|
| 105 |
+
[(1, 1)]
|
| 106 |
+
>>> list(nx.node_degree_xy(G, x="in", y="out"))
|
| 107 |
+
[(0, 0)]
|
| 108 |
+
|
| 109 |
+
Notes
|
| 110 |
+
-----
|
| 111 |
+
For undirected graphs, each edge is produced twice, once for each edge
|
| 112 |
+
representation (u, v) and (v, u), with the exception of self-loop edges
|
| 113 |
+
which only appear once.
|
| 114 |
+
"""
|
| 115 |
+
nodes = set(G) if nodes is None else set(nodes)
|
| 116 |
+
if G.is_directed():
|
| 117 |
+
direction = {"out": G.out_degree, "in": G.in_degree}
|
| 118 |
+
xdeg = direction[x]
|
| 119 |
+
ydeg = direction[y]
|
| 120 |
+
else:
|
| 121 |
+
xdeg = ydeg = G.degree
|
| 122 |
+
|
| 123 |
+
for u, degu in xdeg(nodes, weight=weight):
|
| 124 |
+
# use G.edges to treat multigraphs correctly
|
| 125 |
+
neighbors = (nbr for _, nbr in G.edges(u) if nbr in nodes)
|
| 126 |
+
for _, degv in ydeg(neighbors, weight=weight):
|
| 127 |
+
yield degu, degv
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/__init__.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""This module provides functions and operations for bipartite
|
| 2 |
+
graphs. Bipartite graphs `B = (U, V, E)` have two node sets `U,V` and edges in
|
| 3 |
+
`E` that only connect nodes from opposite sets. It is common in the literature
|
| 4 |
+
to use an spatial analogy referring to the two node sets as top and bottom nodes.
|
| 5 |
+
|
| 6 |
+
The bipartite algorithms are not imported into the networkx namespace
|
| 7 |
+
at the top level so the easiest way to use them is with:
|
| 8 |
+
|
| 9 |
+
>>> from networkx.algorithms import bipartite
|
| 10 |
+
|
| 11 |
+
NetworkX does not have a custom bipartite graph class but the Graph()
|
| 12 |
+
or DiGraph() classes can be used to represent bipartite graphs. However,
|
| 13 |
+
you have to keep track of which set each node belongs to, and make
|
| 14 |
+
sure that there is no edge between nodes of the same set. The convention used
|
| 15 |
+
in NetworkX is to use a node attribute named `bipartite` with values 0 or 1 to
|
| 16 |
+
identify the sets each node belongs to. This convention is not enforced in
|
| 17 |
+
the source code of bipartite functions, it's only a recommendation.
|
| 18 |
+
|
| 19 |
+
For example:
|
| 20 |
+
|
| 21 |
+
>>> B = nx.Graph()
|
| 22 |
+
>>> # Add nodes with the node attribute "bipartite"
|
| 23 |
+
>>> B.add_nodes_from([1, 2, 3, 4], bipartite=0)
|
| 24 |
+
>>> B.add_nodes_from(["a", "b", "c"], bipartite=1)
|
| 25 |
+
>>> # Add edges only between nodes of opposite node sets
|
| 26 |
+
>>> B.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
|
| 27 |
+
|
| 28 |
+
Many algorithms of the bipartite module of NetworkX require, as an argument, a
|
| 29 |
+
container with all the nodes that belong to one set, in addition to the bipartite
|
| 30 |
+
graph `B`. The functions in the bipartite package do not check that the node set
|
| 31 |
+
is actually correct nor that the input graph is actually bipartite.
|
| 32 |
+
If `B` is connected, you can find the two node sets using a two-coloring
|
| 33 |
+
algorithm:
|
| 34 |
+
|
| 35 |
+
>>> nx.is_connected(B)
|
| 36 |
+
True
|
| 37 |
+
>>> bottom_nodes, top_nodes = bipartite.sets(B)
|
| 38 |
+
|
| 39 |
+
However, if the input graph is not connected, there are more than one possible
|
| 40 |
+
colorations. This is the reason why we require the user to pass a container
|
| 41 |
+
with all nodes of one bipartite node set as an argument to most bipartite
|
| 42 |
+
functions. In the face of ambiguity, we refuse the temptation to guess and
|
| 43 |
+
raise an :exc:`AmbiguousSolution <networkx.AmbiguousSolution>`
|
| 44 |
+
Exception if the input graph for
|
| 45 |
+
:func:`bipartite.sets <networkx.algorithms.bipartite.basic.sets>`
|
| 46 |
+
is disconnected.
|
| 47 |
+
|
| 48 |
+
Using the `bipartite` node attribute, you can easily get the two node sets:
|
| 49 |
+
|
| 50 |
+
>>> top_nodes = {n for n, d in B.nodes(data=True) if d["bipartite"] == 0}
|
| 51 |
+
>>> bottom_nodes = set(B) - top_nodes
|
| 52 |
+
|
| 53 |
+
So you can easily use the bipartite algorithms that require, as an argument, a
|
| 54 |
+
container with all nodes that belong to one node set:
|
| 55 |
+
|
| 56 |
+
>>> print(round(bipartite.density(B, bottom_nodes), 2))
|
| 57 |
+
0.5
|
| 58 |
+
>>> G = bipartite.projected_graph(B, top_nodes)
|
| 59 |
+
|
| 60 |
+
All bipartite graph generators in NetworkX build bipartite graphs with the
|
| 61 |
+
`bipartite` node attribute. Thus, you can use the same approach:
|
| 62 |
+
|
| 63 |
+
>>> RB = bipartite.random_graph(5, 7, 0.2)
|
| 64 |
+
>>> RB_top = {n for n, d in RB.nodes(data=True) if d["bipartite"] == 0}
|
| 65 |
+
>>> RB_bottom = set(RB) - RB_top
|
| 66 |
+
>>> list(RB_top)
|
| 67 |
+
[0, 1, 2, 3, 4]
|
| 68 |
+
>>> list(RB_bottom)
|
| 69 |
+
[5, 6, 7, 8, 9, 10, 11]
|
| 70 |
+
|
| 71 |
+
For other bipartite graph generators see
|
| 72 |
+
:mod:`Generators <networkx.algorithms.bipartite.generators>`.
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
from networkx.algorithms.bipartite.basic import *
|
| 77 |
+
from networkx.algorithms.bipartite.centrality import *
|
| 78 |
+
from networkx.algorithms.bipartite.cluster import *
|
| 79 |
+
from networkx.algorithms.bipartite.covering import *
|
| 80 |
+
from networkx.algorithms.bipartite.edgelist import *
|
| 81 |
+
from networkx.algorithms.bipartite.matching import *
|
| 82 |
+
from networkx.algorithms.bipartite.matrix import *
|
| 83 |
+
from networkx.algorithms.bipartite.projection import *
|
| 84 |
+
from networkx.algorithms.bipartite.redundancy import *
|
| 85 |
+
from networkx.algorithms.bipartite.spectral import *
|
| 86 |
+
from networkx.algorithms.bipartite.generators import *
|
| 87 |
+
from networkx.algorithms.bipartite.extendability import *
|
| 88 |
+
from networkx.algorithms.bipartite.link_analysis import *
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/basic.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
==========================
|
| 3 |
+
Bipartite Graph Algorithms
|
| 4 |
+
==========================
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx.algorithms.components import connected_components
|
| 9 |
+
from networkx.exception import AmbiguousSolution
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"is_bipartite",
|
| 13 |
+
"is_bipartite_node_set",
|
| 14 |
+
"color",
|
| 15 |
+
"sets",
|
| 16 |
+
"density",
|
| 17 |
+
"degrees",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@nx._dispatchable
|
| 22 |
+
def color(G):
|
| 23 |
+
"""Returns a two-coloring of the graph.
|
| 24 |
+
|
| 25 |
+
Raises an exception if the graph is not bipartite.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
G : NetworkX graph
|
| 30 |
+
|
| 31 |
+
Returns
|
| 32 |
+
-------
|
| 33 |
+
color : dictionary
|
| 34 |
+
A dictionary keyed by node with a 1 or 0 as data for each node color.
|
| 35 |
+
|
| 36 |
+
Raises
|
| 37 |
+
------
|
| 38 |
+
NetworkXError
|
| 39 |
+
If the graph is not two-colorable.
|
| 40 |
+
|
| 41 |
+
Examples
|
| 42 |
+
--------
|
| 43 |
+
>>> from networkx.algorithms import bipartite
|
| 44 |
+
>>> G = nx.path_graph(4)
|
| 45 |
+
>>> c = bipartite.color(G)
|
| 46 |
+
>>> print(c)
|
| 47 |
+
{0: 1, 1: 0, 2: 1, 3: 0}
|
| 48 |
+
|
| 49 |
+
You can use this to set a node attribute indicating the bipartite set:
|
| 50 |
+
|
| 51 |
+
>>> nx.set_node_attributes(G, c, "bipartite")
|
| 52 |
+
>>> print(G.nodes[0]["bipartite"])
|
| 53 |
+
1
|
| 54 |
+
>>> print(G.nodes[1]["bipartite"])
|
| 55 |
+
0
|
| 56 |
+
"""
|
| 57 |
+
if G.is_directed():
|
| 58 |
+
import itertools
|
| 59 |
+
|
| 60 |
+
def neighbors(v):
|
| 61 |
+
return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
|
| 62 |
+
|
| 63 |
+
else:
|
| 64 |
+
neighbors = G.neighbors
|
| 65 |
+
|
| 66 |
+
color = {}
|
| 67 |
+
for n in G: # handle disconnected graphs
|
| 68 |
+
if n in color or len(G[n]) == 0: # skip isolates
|
| 69 |
+
continue
|
| 70 |
+
queue = [n]
|
| 71 |
+
color[n] = 1 # nodes seen with color (1 or 0)
|
| 72 |
+
while queue:
|
| 73 |
+
v = queue.pop()
|
| 74 |
+
c = 1 - color[v] # opposite color of node v
|
| 75 |
+
for w in neighbors(v):
|
| 76 |
+
if w in color:
|
| 77 |
+
if color[w] == color[v]:
|
| 78 |
+
raise nx.NetworkXError("Graph is not bipartite.")
|
| 79 |
+
else:
|
| 80 |
+
color[w] = c
|
| 81 |
+
queue.append(w)
|
| 82 |
+
# color isolates with 0
|
| 83 |
+
color.update(dict.fromkeys(nx.isolates(G), 0))
|
| 84 |
+
return color
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@nx._dispatchable
|
| 88 |
+
def is_bipartite(G):
|
| 89 |
+
"""Returns True if graph G is bipartite, False if not.
|
| 90 |
+
|
| 91 |
+
Parameters
|
| 92 |
+
----------
|
| 93 |
+
G : NetworkX graph
|
| 94 |
+
|
| 95 |
+
Examples
|
| 96 |
+
--------
|
| 97 |
+
>>> from networkx.algorithms import bipartite
|
| 98 |
+
>>> G = nx.path_graph(4)
|
| 99 |
+
>>> print(bipartite.is_bipartite(G))
|
| 100 |
+
True
|
| 101 |
+
|
| 102 |
+
See Also
|
| 103 |
+
--------
|
| 104 |
+
color, is_bipartite_node_set
|
| 105 |
+
"""
|
| 106 |
+
try:
|
| 107 |
+
color(G)
|
| 108 |
+
return True
|
| 109 |
+
except nx.NetworkXError:
|
| 110 |
+
return False
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@nx._dispatchable
|
| 114 |
+
def is_bipartite_node_set(G, nodes):
|
| 115 |
+
"""Returns True if nodes and G/nodes are a bipartition of G.
|
| 116 |
+
|
| 117 |
+
Parameters
|
| 118 |
+
----------
|
| 119 |
+
G : NetworkX graph
|
| 120 |
+
|
| 121 |
+
nodes: list or container
|
| 122 |
+
Check if nodes are a one of a bipartite set.
|
| 123 |
+
|
| 124 |
+
Examples
|
| 125 |
+
--------
|
| 126 |
+
>>> from networkx.algorithms import bipartite
|
| 127 |
+
>>> G = nx.path_graph(4)
|
| 128 |
+
>>> X = set([1, 3])
|
| 129 |
+
>>> bipartite.is_bipartite_node_set(G, X)
|
| 130 |
+
True
|
| 131 |
+
|
| 132 |
+
Notes
|
| 133 |
+
-----
|
| 134 |
+
An exception is raised if the input nodes are not distinct, because in this
|
| 135 |
+
case some bipartite algorithms will yield incorrect results.
|
| 136 |
+
For connected graphs the bipartite sets are unique. This function handles
|
| 137 |
+
disconnected graphs.
|
| 138 |
+
"""
|
| 139 |
+
S = set(nodes)
|
| 140 |
+
|
| 141 |
+
if len(S) < len(nodes):
|
| 142 |
+
# this should maybe just return False?
|
| 143 |
+
raise AmbiguousSolution(
|
| 144 |
+
"The input node set contains duplicates.\n"
|
| 145 |
+
"This may lead to incorrect results when using it in bipartite algorithms.\n"
|
| 146 |
+
"Consider using set(nodes) as the input"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
for CC in (G.subgraph(c).copy() for c in connected_components(G)):
|
| 150 |
+
X, Y = sets(CC)
|
| 151 |
+
if not (
|
| 152 |
+
(X.issubset(S) and Y.isdisjoint(S)) or (Y.issubset(S) and X.isdisjoint(S))
|
| 153 |
+
):
|
| 154 |
+
return False
|
| 155 |
+
return True
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@nx._dispatchable
|
| 159 |
+
def sets(G, top_nodes=None):
|
| 160 |
+
"""Returns bipartite node sets of graph G.
|
| 161 |
+
|
| 162 |
+
Raises an exception if the graph is not bipartite or if the input
|
| 163 |
+
graph is disconnected and thus more than one valid solution exists.
|
| 164 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 165 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 166 |
+
|
| 167 |
+
Parameters
|
| 168 |
+
----------
|
| 169 |
+
G : NetworkX graph
|
| 170 |
+
|
| 171 |
+
top_nodes : container, optional
|
| 172 |
+
Container with all nodes in one bipartite node set. If not supplied
|
| 173 |
+
it will be computed. But if more than one solution exists an exception
|
| 174 |
+
will be raised.
|
| 175 |
+
|
| 176 |
+
Returns
|
| 177 |
+
-------
|
| 178 |
+
X : set
|
| 179 |
+
Nodes from one side of the bipartite graph.
|
| 180 |
+
Y : set
|
| 181 |
+
Nodes from the other side.
|
| 182 |
+
|
| 183 |
+
Raises
|
| 184 |
+
------
|
| 185 |
+
AmbiguousSolution
|
| 186 |
+
Raised if the input bipartite graph is disconnected and no container
|
| 187 |
+
with all nodes in one bipartite set is provided. When determining
|
| 188 |
+
the nodes in each bipartite set more than one valid solution is
|
| 189 |
+
possible if the input graph is disconnected.
|
| 190 |
+
NetworkXError
|
| 191 |
+
Raised if the input graph is not bipartite.
|
| 192 |
+
|
| 193 |
+
Examples
|
| 194 |
+
--------
|
| 195 |
+
>>> from networkx.algorithms import bipartite
|
| 196 |
+
>>> G = nx.path_graph(4)
|
| 197 |
+
>>> X, Y = bipartite.sets(G)
|
| 198 |
+
>>> list(X)
|
| 199 |
+
[0, 2]
|
| 200 |
+
>>> list(Y)
|
| 201 |
+
[1, 3]
|
| 202 |
+
|
| 203 |
+
See Also
|
| 204 |
+
--------
|
| 205 |
+
color
|
| 206 |
+
|
| 207 |
+
"""
|
| 208 |
+
if G.is_directed():
|
| 209 |
+
is_connected = nx.is_weakly_connected
|
| 210 |
+
else:
|
| 211 |
+
is_connected = nx.is_connected
|
| 212 |
+
if top_nodes is not None:
|
| 213 |
+
X = set(top_nodes)
|
| 214 |
+
Y = set(G) - X
|
| 215 |
+
else:
|
| 216 |
+
if not is_connected(G):
|
| 217 |
+
msg = "Disconnected graph: Ambiguous solution for bipartite sets."
|
| 218 |
+
raise nx.AmbiguousSolution(msg)
|
| 219 |
+
c = color(G)
|
| 220 |
+
X = {n for n, is_top in c.items() if is_top}
|
| 221 |
+
Y = {n for n, is_top in c.items() if not is_top}
|
| 222 |
+
return (X, Y)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@nx._dispatchable(graphs="B")
|
| 226 |
+
def density(B, nodes):
|
| 227 |
+
"""Returns density of bipartite graph B.
|
| 228 |
+
|
| 229 |
+
Parameters
|
| 230 |
+
----------
|
| 231 |
+
B : NetworkX graph
|
| 232 |
+
|
| 233 |
+
nodes: list or container
|
| 234 |
+
Nodes in one node set of the bipartite graph.
|
| 235 |
+
|
| 236 |
+
Returns
|
| 237 |
+
-------
|
| 238 |
+
d : float
|
| 239 |
+
The bipartite density
|
| 240 |
+
|
| 241 |
+
Examples
|
| 242 |
+
--------
|
| 243 |
+
>>> from networkx.algorithms import bipartite
|
| 244 |
+
>>> G = nx.complete_bipartite_graph(3, 2)
|
| 245 |
+
>>> X = set([0, 1, 2])
|
| 246 |
+
>>> bipartite.density(G, X)
|
| 247 |
+
1.0
|
| 248 |
+
>>> Y = set([3, 4])
|
| 249 |
+
>>> bipartite.density(G, Y)
|
| 250 |
+
1.0
|
| 251 |
+
|
| 252 |
+
Notes
|
| 253 |
+
-----
|
| 254 |
+
The container of nodes passed as argument must contain all nodes
|
| 255 |
+
in one of the two bipartite node sets to avoid ambiguity in the
|
| 256 |
+
case of disconnected graphs.
|
| 257 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 258 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 259 |
+
|
| 260 |
+
See Also
|
| 261 |
+
--------
|
| 262 |
+
color
|
| 263 |
+
"""
|
| 264 |
+
n = len(B)
|
| 265 |
+
m = nx.number_of_edges(B)
|
| 266 |
+
nb = len(nodes)
|
| 267 |
+
nt = n - nb
|
| 268 |
+
if m == 0: # includes cases n==0 and n==1
|
| 269 |
+
d = 0.0
|
| 270 |
+
else:
|
| 271 |
+
if B.is_directed():
|
| 272 |
+
d = m / (2 * nb * nt)
|
| 273 |
+
else:
|
| 274 |
+
d = m / (nb * nt)
|
| 275 |
+
return d
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
@nx._dispatchable(graphs="B", edge_attrs="weight")
|
| 279 |
+
def degrees(B, nodes, weight=None):
|
| 280 |
+
"""Returns the degrees of the two node sets in the bipartite graph B.
|
| 281 |
+
|
| 282 |
+
Parameters
|
| 283 |
+
----------
|
| 284 |
+
B : NetworkX graph
|
| 285 |
+
|
| 286 |
+
nodes: list or container
|
| 287 |
+
Nodes in one node set of the bipartite graph.
|
| 288 |
+
|
| 289 |
+
weight : string or None, optional (default=None)
|
| 290 |
+
The edge attribute that holds the numerical value used as a weight.
|
| 291 |
+
If None, then each edge has weight 1.
|
| 292 |
+
The degree is the sum of the edge weights adjacent to the node.
|
| 293 |
+
|
| 294 |
+
Returns
|
| 295 |
+
-------
|
| 296 |
+
(degX,degY) : tuple of dictionaries
|
| 297 |
+
The degrees of the two bipartite sets as dictionaries keyed by node.
|
| 298 |
+
|
| 299 |
+
Examples
|
| 300 |
+
--------
|
| 301 |
+
>>> from networkx.algorithms import bipartite
|
| 302 |
+
>>> G = nx.complete_bipartite_graph(3, 2)
|
| 303 |
+
>>> Y = set([3, 4])
|
| 304 |
+
>>> degX, degY = bipartite.degrees(G, Y)
|
| 305 |
+
>>> dict(degX)
|
| 306 |
+
{0: 2, 1: 2, 2: 2}
|
| 307 |
+
|
| 308 |
+
Notes
|
| 309 |
+
-----
|
| 310 |
+
The container of nodes passed as argument must contain all nodes
|
| 311 |
+
in one of the two bipartite node sets to avoid ambiguity in the
|
| 312 |
+
case of disconnected graphs.
|
| 313 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 314 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 315 |
+
|
| 316 |
+
See Also
|
| 317 |
+
--------
|
| 318 |
+
color, density
|
| 319 |
+
"""
|
| 320 |
+
bottom = set(nodes)
|
| 321 |
+
top = set(B) - bottom
|
| 322 |
+
return (B.degree(top, weight), B.degree(bottom, weight))
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/centrality.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import networkx as nx
|
| 2 |
+
|
| 3 |
+
__all__ = ["degree_centrality", "betweenness_centrality", "closeness_centrality"]
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@nx._dispatchable(name="bipartite_degree_centrality")
|
| 7 |
+
def degree_centrality(G, nodes):
|
| 8 |
+
r"""Compute the degree centrality for nodes in a bipartite network.
|
| 9 |
+
|
| 10 |
+
The degree centrality for a node `v` is the fraction of nodes
|
| 11 |
+
connected to it.
|
| 12 |
+
|
| 13 |
+
Parameters
|
| 14 |
+
----------
|
| 15 |
+
G : graph
|
| 16 |
+
A bipartite network
|
| 17 |
+
|
| 18 |
+
nodes : list or container
|
| 19 |
+
Container with all nodes in one bipartite node set.
|
| 20 |
+
|
| 21 |
+
Returns
|
| 22 |
+
-------
|
| 23 |
+
centrality : dictionary
|
| 24 |
+
Dictionary keyed by node with bipartite degree centrality as the value.
|
| 25 |
+
|
| 26 |
+
Examples
|
| 27 |
+
--------
|
| 28 |
+
>>> G = nx.wheel_graph(5)
|
| 29 |
+
>>> top_nodes = {0, 1, 2}
|
| 30 |
+
>>> nx.bipartite.degree_centrality(G, nodes=top_nodes)
|
| 31 |
+
{0: 2.0, 1: 1.5, 2: 1.5, 3: 1.0, 4: 1.0}
|
| 32 |
+
|
| 33 |
+
See Also
|
| 34 |
+
--------
|
| 35 |
+
betweenness_centrality
|
| 36 |
+
closeness_centrality
|
| 37 |
+
:func:`~networkx.algorithms.bipartite.basic.sets`
|
| 38 |
+
:func:`~networkx.algorithms.bipartite.basic.is_bipartite`
|
| 39 |
+
|
| 40 |
+
Notes
|
| 41 |
+
-----
|
| 42 |
+
The nodes input parameter must contain all nodes in one bipartite node set,
|
| 43 |
+
but the dictionary returned contains all nodes from both bipartite node
|
| 44 |
+
sets. See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 45 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 46 |
+
|
| 47 |
+
For unipartite networks, the degree centrality values are
|
| 48 |
+
normalized by dividing by the maximum possible degree (which is
|
| 49 |
+
`n-1` where `n` is the number of nodes in G).
|
| 50 |
+
|
| 51 |
+
In the bipartite case, the maximum possible degree of a node in a
|
| 52 |
+
bipartite node set is the number of nodes in the opposite node set
|
| 53 |
+
[1]_. The degree centrality for a node `v` in the bipartite
|
| 54 |
+
sets `U` with `n` nodes and `V` with `m` nodes is
|
| 55 |
+
|
| 56 |
+
.. math::
|
| 57 |
+
|
| 58 |
+
d_{v} = \frac{deg(v)}{m}, \mbox{for} v \in U ,
|
| 59 |
+
|
| 60 |
+
d_{v} = \frac{deg(v)}{n}, \mbox{for} v \in V ,
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
where `deg(v)` is the degree of node `v`.
|
| 64 |
+
|
| 65 |
+
References
|
| 66 |
+
----------
|
| 67 |
+
.. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
|
| 68 |
+
Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
|
| 69 |
+
of Social Network Analysis. Sage Publications.
|
| 70 |
+
https://dx.doi.org/10.4135/9781446294413.n28
|
| 71 |
+
"""
|
| 72 |
+
top = set(nodes)
|
| 73 |
+
bottom = set(G) - top
|
| 74 |
+
s = 1.0 / len(bottom)
|
| 75 |
+
centrality = {n: d * s for n, d in G.degree(top)}
|
| 76 |
+
s = 1.0 / len(top)
|
| 77 |
+
centrality.update({n: d * s for n, d in G.degree(bottom)})
|
| 78 |
+
return centrality
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@nx._dispatchable(name="bipartite_betweenness_centrality")
|
| 82 |
+
def betweenness_centrality(G, nodes):
|
| 83 |
+
r"""Compute betweenness centrality for nodes in a bipartite network.
|
| 84 |
+
|
| 85 |
+
Betweenness centrality of a node `v` is the sum of the
|
| 86 |
+
fraction of all-pairs shortest paths that pass through `v`.
|
| 87 |
+
|
| 88 |
+
Values of betweenness are normalized by the maximum possible
|
| 89 |
+
value which for bipartite graphs is limited by the relative size
|
| 90 |
+
of the two node sets [1]_.
|
| 91 |
+
|
| 92 |
+
Let `n` be the number of nodes in the node set `U` and
|
| 93 |
+
`m` be the number of nodes in the node set `V`, then
|
| 94 |
+
nodes in `U` are normalized by dividing by
|
| 95 |
+
|
| 96 |
+
.. math::
|
| 97 |
+
|
| 98 |
+
\frac{1}{2} [m^2 (s + 1)^2 + m (s + 1)(2t - s - 1) - t (2s - t + 3)] ,
|
| 99 |
+
|
| 100 |
+
where
|
| 101 |
+
|
| 102 |
+
.. math::
|
| 103 |
+
|
| 104 |
+
s = (n - 1) \div m , t = (n - 1) \mod m ,
|
| 105 |
+
|
| 106 |
+
and nodes in `V` are normalized by dividing by
|
| 107 |
+
|
| 108 |
+
.. math::
|
| 109 |
+
|
| 110 |
+
\frac{1}{2} [n^2 (p + 1)^2 + n (p + 1)(2r - p - 1) - r (2p - r + 3)] ,
|
| 111 |
+
|
| 112 |
+
where,
|
| 113 |
+
|
| 114 |
+
.. math::
|
| 115 |
+
|
| 116 |
+
p = (m - 1) \div n , r = (m - 1) \mod n .
|
| 117 |
+
|
| 118 |
+
Parameters
|
| 119 |
+
----------
|
| 120 |
+
G : graph
|
| 121 |
+
A bipartite graph
|
| 122 |
+
|
| 123 |
+
nodes : list or container
|
| 124 |
+
Container with all nodes in one bipartite node set.
|
| 125 |
+
|
| 126 |
+
Returns
|
| 127 |
+
-------
|
| 128 |
+
betweenness : dictionary
|
| 129 |
+
Dictionary keyed by node with bipartite betweenness centrality
|
| 130 |
+
as the value.
|
| 131 |
+
|
| 132 |
+
Examples
|
| 133 |
+
--------
|
| 134 |
+
>>> G = nx.cycle_graph(4)
|
| 135 |
+
>>> top_nodes = {1, 2}
|
| 136 |
+
>>> nx.bipartite.betweenness_centrality(G, nodes=top_nodes)
|
| 137 |
+
{0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
|
| 138 |
+
|
| 139 |
+
See Also
|
| 140 |
+
--------
|
| 141 |
+
degree_centrality
|
| 142 |
+
closeness_centrality
|
| 143 |
+
:func:`~networkx.algorithms.bipartite.basic.sets`
|
| 144 |
+
:func:`~networkx.algorithms.bipartite.basic.is_bipartite`
|
| 145 |
+
|
| 146 |
+
Notes
|
| 147 |
+
-----
|
| 148 |
+
The nodes input parameter must contain all nodes in one bipartite node set,
|
| 149 |
+
but the dictionary returned contains all nodes from both node sets.
|
| 150 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 151 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
References
|
| 155 |
+
----------
|
| 156 |
+
.. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
|
| 157 |
+
Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
|
| 158 |
+
of Social Network Analysis. Sage Publications.
|
| 159 |
+
https://dx.doi.org/10.4135/9781446294413.n28
|
| 160 |
+
"""
|
| 161 |
+
top = set(nodes)
|
| 162 |
+
bottom = set(G) - top
|
| 163 |
+
n = len(top)
|
| 164 |
+
m = len(bottom)
|
| 165 |
+
s, t = divmod(n - 1, m)
|
| 166 |
+
bet_max_top = (
|
| 167 |
+
((m**2) * ((s + 1) ** 2))
|
| 168 |
+
+ (m * (s + 1) * (2 * t - s - 1))
|
| 169 |
+
- (t * ((2 * s) - t + 3))
|
| 170 |
+
) / 2.0
|
| 171 |
+
p, r = divmod(m - 1, n)
|
| 172 |
+
bet_max_bot = (
|
| 173 |
+
((n**2) * ((p + 1) ** 2))
|
| 174 |
+
+ (n * (p + 1) * (2 * r - p - 1))
|
| 175 |
+
- (r * ((2 * p) - r + 3))
|
| 176 |
+
) / 2.0
|
| 177 |
+
betweenness = nx.betweenness_centrality(G, normalized=False, weight=None)
|
| 178 |
+
for node in top:
|
| 179 |
+
betweenness[node] /= bet_max_top
|
| 180 |
+
for node in bottom:
|
| 181 |
+
betweenness[node] /= bet_max_bot
|
| 182 |
+
return betweenness
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@nx._dispatchable(name="bipartite_closeness_centrality")
|
| 186 |
+
def closeness_centrality(G, nodes, normalized=True):
|
| 187 |
+
r"""Compute the closeness centrality for nodes in a bipartite network.
|
| 188 |
+
|
| 189 |
+
The closeness of a node is the distance to all other nodes in the
|
| 190 |
+
graph or in the case that the graph is not connected to all other nodes
|
| 191 |
+
in the connected component containing that node.
|
| 192 |
+
|
| 193 |
+
Parameters
|
| 194 |
+
----------
|
| 195 |
+
G : graph
|
| 196 |
+
A bipartite network
|
| 197 |
+
|
| 198 |
+
nodes : list or container
|
| 199 |
+
Container with all nodes in one bipartite node set.
|
| 200 |
+
|
| 201 |
+
normalized : bool, optional
|
| 202 |
+
If True (default) normalize by connected component size.
|
| 203 |
+
|
| 204 |
+
Returns
|
| 205 |
+
-------
|
| 206 |
+
closeness : dictionary
|
| 207 |
+
Dictionary keyed by node with bipartite closeness centrality
|
| 208 |
+
as the value.
|
| 209 |
+
|
| 210 |
+
Examples
|
| 211 |
+
--------
|
| 212 |
+
>>> G = nx.wheel_graph(5)
|
| 213 |
+
>>> top_nodes = {0, 1, 2}
|
| 214 |
+
>>> nx.bipartite.closeness_centrality(G, nodes=top_nodes)
|
| 215 |
+
{0: 1.5, 1: 1.2, 2: 1.2, 3: 1.0, 4: 1.0}
|
| 216 |
+
|
| 217 |
+
See Also
|
| 218 |
+
--------
|
| 219 |
+
betweenness_centrality
|
| 220 |
+
degree_centrality
|
| 221 |
+
:func:`~networkx.algorithms.bipartite.basic.sets`
|
| 222 |
+
:func:`~networkx.algorithms.bipartite.basic.is_bipartite`
|
| 223 |
+
|
| 224 |
+
Notes
|
| 225 |
+
-----
|
| 226 |
+
The nodes input parameter must contain all nodes in one bipartite node set,
|
| 227 |
+
but the dictionary returned contains all nodes from both node sets.
|
| 228 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 229 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
Closeness centrality is normalized by the minimum distance possible.
|
| 233 |
+
In the bipartite case the minimum distance for a node in one bipartite
|
| 234 |
+
node set is 1 from all nodes in the other node set and 2 from all
|
| 235 |
+
other nodes in its own set [1]_. Thus the closeness centrality
|
| 236 |
+
for node `v` in the two bipartite sets `U` with
|
| 237 |
+
`n` nodes and `V` with `m` nodes is
|
| 238 |
+
|
| 239 |
+
.. math::
|
| 240 |
+
|
| 241 |
+
c_{v} = \frac{m + 2(n - 1)}{d}, \mbox{for} v \in U,
|
| 242 |
+
|
| 243 |
+
c_{v} = \frac{n + 2(m - 1)}{d}, \mbox{for} v \in V,
|
| 244 |
+
|
| 245 |
+
where `d` is the sum of the distances from `v` to all
|
| 246 |
+
other nodes.
|
| 247 |
+
|
| 248 |
+
Higher values of closeness indicate higher centrality.
|
| 249 |
+
|
| 250 |
+
As in the unipartite case, setting normalized=True causes the
|
| 251 |
+
values to normalized further to n-1 / size(G)-1 where n is the
|
| 252 |
+
number of nodes in the connected part of graph containing the
|
| 253 |
+
node. If the graph is not completely connected, this algorithm
|
| 254 |
+
computes the closeness centrality for each connected part
|
| 255 |
+
separately.
|
| 256 |
+
|
| 257 |
+
References
|
| 258 |
+
----------
|
| 259 |
+
.. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
|
| 260 |
+
Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
|
| 261 |
+
of Social Network Analysis. Sage Publications.
|
| 262 |
+
https://dx.doi.org/10.4135/9781446294413.n28
|
| 263 |
+
"""
|
| 264 |
+
closeness = {}
|
| 265 |
+
path_length = nx.single_source_shortest_path_length
|
| 266 |
+
top = set(nodes)
|
| 267 |
+
bottom = set(G) - top
|
| 268 |
+
n = len(top)
|
| 269 |
+
m = len(bottom)
|
| 270 |
+
for node in top:
|
| 271 |
+
sp = dict(path_length(G, node))
|
| 272 |
+
totsp = sum(sp.values())
|
| 273 |
+
if totsp > 0.0 and len(G) > 1:
|
| 274 |
+
closeness[node] = (m + 2 * (n - 1)) / totsp
|
| 275 |
+
if normalized:
|
| 276 |
+
s = (len(sp) - 1) / (len(G) - 1)
|
| 277 |
+
closeness[node] *= s
|
| 278 |
+
else:
|
| 279 |
+
closeness[node] = 0.0
|
| 280 |
+
for node in bottom:
|
| 281 |
+
sp = dict(path_length(G, node))
|
| 282 |
+
totsp = sum(sp.values())
|
| 283 |
+
if totsp > 0.0 and len(G) > 1:
|
| 284 |
+
closeness[node] = (n + 2 * (m - 1)) / totsp
|
| 285 |
+
if normalized:
|
| 286 |
+
s = (len(sp) - 1) / (len(G) - 1)
|
| 287 |
+
closeness[node] *= s
|
| 288 |
+
else:
|
| 289 |
+
closeness[node] = 0.0
|
| 290 |
+
return closeness
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/cluster.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for computing clustering of pairs"""
|
| 2 |
+
|
| 3 |
+
import itertools
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"clustering",
|
| 9 |
+
"average_clustering",
|
| 10 |
+
"latapy_clustering",
|
| 11 |
+
"robins_alexander_clustering",
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def cc_dot(nu, nv):
|
| 16 |
+
return len(nu & nv) / len(nu | nv)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def cc_max(nu, nv):
|
| 20 |
+
return len(nu & nv) / max(len(nu), len(nv))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def cc_min(nu, nv):
|
| 24 |
+
return len(nu & nv) / min(len(nu), len(nv))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
modes = {"dot": cc_dot, "min": cc_min, "max": cc_max}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@nx._dispatchable
|
| 31 |
+
def latapy_clustering(G, nodes=None, mode="dot"):
|
| 32 |
+
r"""Compute a bipartite clustering coefficient for nodes.
|
| 33 |
+
|
| 34 |
+
The bipartite clustering coefficient is a measure of local density
|
| 35 |
+
of connections defined as [1]_:
|
| 36 |
+
|
| 37 |
+
.. math::
|
| 38 |
+
|
| 39 |
+
c_u = \frac{\sum_{v \in N(N(u))} c_{uv} }{|N(N(u))|}
|
| 40 |
+
|
| 41 |
+
where `N(N(u))` are the second order neighbors of `u` in `G` excluding `u`,
|
| 42 |
+
and `c_{uv}` is the pairwise clustering coefficient between nodes
|
| 43 |
+
`u` and `v`.
|
| 44 |
+
|
| 45 |
+
The mode selects the function for `c_{uv}` which can be:
|
| 46 |
+
|
| 47 |
+
`dot`:
|
| 48 |
+
|
| 49 |
+
.. math::
|
| 50 |
+
|
| 51 |
+
c_{uv}=\frac{|N(u)\cap N(v)|}{|N(u) \cup N(v)|}
|
| 52 |
+
|
| 53 |
+
`min`:
|
| 54 |
+
|
| 55 |
+
.. math::
|
| 56 |
+
|
| 57 |
+
c_{uv}=\frac{|N(u)\cap N(v)|}{min(|N(u)|,|N(v)|)}
|
| 58 |
+
|
| 59 |
+
`max`:
|
| 60 |
+
|
| 61 |
+
.. math::
|
| 62 |
+
|
| 63 |
+
c_{uv}=\frac{|N(u)\cap N(v)|}{max(|N(u)|,|N(v)|)}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
Parameters
|
| 67 |
+
----------
|
| 68 |
+
G : graph
|
| 69 |
+
A bipartite graph
|
| 70 |
+
|
| 71 |
+
nodes : list or iterable (optional)
|
| 72 |
+
Compute bipartite clustering for these nodes. The default
|
| 73 |
+
is all nodes in G.
|
| 74 |
+
|
| 75 |
+
mode : string
|
| 76 |
+
The pairwise bipartite clustering method to be used in the computation.
|
| 77 |
+
It must be "dot", "max", or "min".
|
| 78 |
+
|
| 79 |
+
Returns
|
| 80 |
+
-------
|
| 81 |
+
clustering : dictionary
|
| 82 |
+
A dictionary keyed by node with the clustering coefficient value.
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
Examples
|
| 86 |
+
--------
|
| 87 |
+
>>> from networkx.algorithms import bipartite
|
| 88 |
+
>>> G = nx.path_graph(4) # path graphs are bipartite
|
| 89 |
+
>>> c = bipartite.clustering(G)
|
| 90 |
+
>>> c[0]
|
| 91 |
+
0.5
|
| 92 |
+
>>> c = bipartite.clustering(G, mode="min")
|
| 93 |
+
>>> c[0]
|
| 94 |
+
1.0
|
| 95 |
+
|
| 96 |
+
See Also
|
| 97 |
+
--------
|
| 98 |
+
robins_alexander_clustering
|
| 99 |
+
average_clustering
|
| 100 |
+
networkx.algorithms.cluster.square_clustering
|
| 101 |
+
|
| 102 |
+
References
|
| 103 |
+
----------
|
| 104 |
+
.. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
|
| 105 |
+
Basic notions for the analysis of large two-mode networks.
|
| 106 |
+
Social Networks 30(1), 31--48.
|
| 107 |
+
"""
|
| 108 |
+
if not nx.algorithms.bipartite.is_bipartite(G):
|
| 109 |
+
raise nx.NetworkXError("Graph is not bipartite")
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
cc_func = modes[mode]
|
| 113 |
+
except KeyError as err:
|
| 114 |
+
raise nx.NetworkXError(
|
| 115 |
+
"Mode for bipartite clustering must be: dot, min or max"
|
| 116 |
+
) from err
|
| 117 |
+
|
| 118 |
+
if nodes is None:
|
| 119 |
+
nodes = G
|
| 120 |
+
ccs = {}
|
| 121 |
+
for v in nodes:
|
| 122 |
+
cc = 0.0
|
| 123 |
+
nbrs2 = {u for nbr in G[v] for u in G[nbr]} - {v}
|
| 124 |
+
for u in nbrs2:
|
| 125 |
+
cc += cc_func(set(G[u]), set(G[v]))
|
| 126 |
+
if cc > 0.0: # len(nbrs2)>0
|
| 127 |
+
cc /= len(nbrs2)
|
| 128 |
+
ccs[v] = cc
|
| 129 |
+
return ccs
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
clustering = latapy_clustering
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@nx._dispatchable(name="bipartite_average_clustering")
|
| 136 |
+
def average_clustering(G, nodes=None, mode="dot"):
|
| 137 |
+
r"""Compute the average bipartite clustering coefficient.
|
| 138 |
+
|
| 139 |
+
A clustering coefficient for the whole graph is the average,
|
| 140 |
+
|
| 141 |
+
.. math::
|
| 142 |
+
|
| 143 |
+
C = \frac{1}{n}\sum_{v \in G} c_v,
|
| 144 |
+
|
| 145 |
+
where `n` is the number of nodes in `G`.
|
| 146 |
+
|
| 147 |
+
Similar measures for the two bipartite sets can be defined [1]_
|
| 148 |
+
|
| 149 |
+
.. math::
|
| 150 |
+
|
| 151 |
+
C_X = \frac{1}{|X|}\sum_{v \in X} c_v,
|
| 152 |
+
|
| 153 |
+
where `X` is a bipartite set of `G`.
|
| 154 |
+
|
| 155 |
+
Parameters
|
| 156 |
+
----------
|
| 157 |
+
G : graph
|
| 158 |
+
a bipartite graph
|
| 159 |
+
|
| 160 |
+
nodes : list or iterable, optional
|
| 161 |
+
A container of nodes to use in computing the average.
|
| 162 |
+
The nodes should be either the entire graph (the default) or one of the
|
| 163 |
+
bipartite sets.
|
| 164 |
+
|
| 165 |
+
mode : string
|
| 166 |
+
The pairwise bipartite clustering method.
|
| 167 |
+
It must be "dot", "max", or "min"
|
| 168 |
+
|
| 169 |
+
Returns
|
| 170 |
+
-------
|
| 171 |
+
clustering : float
|
| 172 |
+
The average bipartite clustering for the given set of nodes or the
|
| 173 |
+
entire graph if no nodes are specified.
|
| 174 |
+
|
| 175 |
+
Examples
|
| 176 |
+
--------
|
| 177 |
+
>>> from networkx.algorithms import bipartite
|
| 178 |
+
>>> G = nx.star_graph(3) # star graphs are bipartite
|
| 179 |
+
>>> bipartite.average_clustering(G)
|
| 180 |
+
0.75
|
| 181 |
+
>>> X, Y = bipartite.sets(G)
|
| 182 |
+
>>> bipartite.average_clustering(G, X)
|
| 183 |
+
0.0
|
| 184 |
+
>>> bipartite.average_clustering(G, Y)
|
| 185 |
+
1.0
|
| 186 |
+
|
| 187 |
+
See Also
|
| 188 |
+
--------
|
| 189 |
+
clustering
|
| 190 |
+
|
| 191 |
+
Notes
|
| 192 |
+
-----
|
| 193 |
+
The container of nodes passed to this function must contain all of the nodes
|
| 194 |
+
in one of the bipartite sets ("top" or "bottom") in order to compute
|
| 195 |
+
the correct average bipartite clustering coefficients.
|
| 196 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 197 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
References
|
| 201 |
+
----------
|
| 202 |
+
.. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
|
| 203 |
+
Basic notions for the analysis of large two-mode networks.
|
| 204 |
+
Social Networks 30(1), 31--48.
|
| 205 |
+
"""
|
| 206 |
+
if nodes is None:
|
| 207 |
+
nodes = G
|
| 208 |
+
ccs = latapy_clustering(G, nodes=nodes, mode=mode)
|
| 209 |
+
return sum(ccs[v] for v in nodes) / len(nodes)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@nx._dispatchable
|
| 213 |
+
def robins_alexander_clustering(G):
|
| 214 |
+
r"""Compute the bipartite clustering of G.
|
| 215 |
+
|
| 216 |
+
Robins and Alexander [1]_ defined bipartite clustering coefficient as
|
| 217 |
+
four times the number of four cycles `C_4` divided by the number of
|
| 218 |
+
three paths `L_3` in a bipartite graph:
|
| 219 |
+
|
| 220 |
+
.. math::
|
| 221 |
+
|
| 222 |
+
CC_4 = \frac{4 * C_4}{L_3}
|
| 223 |
+
|
| 224 |
+
Parameters
|
| 225 |
+
----------
|
| 226 |
+
G : graph
|
| 227 |
+
a bipartite graph
|
| 228 |
+
|
| 229 |
+
Returns
|
| 230 |
+
-------
|
| 231 |
+
clustering : float
|
| 232 |
+
The Robins and Alexander bipartite clustering for the input graph.
|
| 233 |
+
|
| 234 |
+
Examples
|
| 235 |
+
--------
|
| 236 |
+
>>> from networkx.algorithms import bipartite
|
| 237 |
+
>>> G = nx.davis_southern_women_graph()
|
| 238 |
+
>>> print(round(bipartite.robins_alexander_clustering(G), 3))
|
| 239 |
+
0.468
|
| 240 |
+
|
| 241 |
+
See Also
|
| 242 |
+
--------
|
| 243 |
+
latapy_clustering
|
| 244 |
+
networkx.algorithms.cluster.square_clustering
|
| 245 |
+
|
| 246 |
+
References
|
| 247 |
+
----------
|
| 248 |
+
.. [1] Robins, G. and M. Alexander (2004). Small worlds among interlocking
|
| 249 |
+
directors: Network structure and distance in bipartite graphs.
|
| 250 |
+
Computational & Mathematical Organization Theory 10(1), 69–94.
|
| 251 |
+
|
| 252 |
+
"""
|
| 253 |
+
if G.order() < 4 or G.size() < 3:
|
| 254 |
+
return 0
|
| 255 |
+
L_3 = _threepaths(G)
|
| 256 |
+
if L_3 == 0:
|
| 257 |
+
return 0
|
| 258 |
+
C_4 = _four_cycles(G)
|
| 259 |
+
return (4.0 * C_4) / L_3
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def _four_cycles(G):
|
| 263 |
+
# Also see `square_clustering` which counts squares in a similar way
|
| 264 |
+
cycles = 0
|
| 265 |
+
seen = set()
|
| 266 |
+
G_adj = G._adj
|
| 267 |
+
for v in G:
|
| 268 |
+
seen.add(v)
|
| 269 |
+
v_neighbors = set(G_adj[v])
|
| 270 |
+
if len(v_neighbors) < 2:
|
| 271 |
+
# Can't form a square without at least two neighbors
|
| 272 |
+
continue
|
| 273 |
+
two_hop_neighbors = set().union(*(G_adj[u] for u in v_neighbors))
|
| 274 |
+
two_hop_neighbors -= seen
|
| 275 |
+
for x in two_hop_neighbors:
|
| 276 |
+
p2 = len(v_neighbors.intersection(G_adj[x]))
|
| 277 |
+
cycles += p2 * (p2 - 1)
|
| 278 |
+
return cycles / 4
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _threepaths(G):
|
| 282 |
+
paths = 0
|
| 283 |
+
for v in G:
|
| 284 |
+
for u in G[v]:
|
| 285 |
+
for w in set(G[u]) - {v}:
|
| 286 |
+
paths += len(set(G[w]) - {v, u})
|
| 287 |
+
# Divide by two because we count each three path twice
|
| 288 |
+
# one for each possible starting point
|
| 289 |
+
return paths / 2
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/covering.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions related to graph covers."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.algorithms.bipartite.matching import hopcroft_karp_matching
|
| 5 |
+
from networkx.algorithms.covering import min_edge_cover as _min_edge_cover
|
| 6 |
+
from networkx.utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = ["min_edge_cover"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@not_implemented_for("directed")
|
| 12 |
+
@not_implemented_for("multigraph")
|
| 13 |
+
@nx._dispatchable(name="bipartite_min_edge_cover")
|
| 14 |
+
def min_edge_cover(G, matching_algorithm=None):
|
| 15 |
+
"""Returns a set of edges which constitutes
|
| 16 |
+
the minimum edge cover of the graph.
|
| 17 |
+
|
| 18 |
+
The smallest edge cover can be found in polynomial time by finding
|
| 19 |
+
a maximum matching and extending it greedily so that all nodes
|
| 20 |
+
are covered.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
G : NetworkX graph
|
| 25 |
+
An undirected bipartite graph.
|
| 26 |
+
|
| 27 |
+
matching_algorithm : function
|
| 28 |
+
A function that returns a maximum cardinality matching in a
|
| 29 |
+
given bipartite graph. The function must take one input, the
|
| 30 |
+
graph ``G``, and return a dictionary mapping each node to its
|
| 31 |
+
mate. If not specified,
|
| 32 |
+
:func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching`
|
| 33 |
+
will be used. Other possibilities include
|
| 34 |
+
:func:`~networkx.algorithms.bipartite.matching.eppstein_matching`,
|
| 35 |
+
|
| 36 |
+
Returns
|
| 37 |
+
-------
|
| 38 |
+
set
|
| 39 |
+
A set of the edges in a minimum edge cover of the graph, given as
|
| 40 |
+
pairs of nodes. It contains both the edges `(u, v)` and `(v, u)`
|
| 41 |
+
for given nodes `u` and `v` among the edges of minimum edge cover.
|
| 42 |
+
|
| 43 |
+
Notes
|
| 44 |
+
-----
|
| 45 |
+
An edge cover of a graph is a set of edges such that every node of
|
| 46 |
+
the graph is incident to at least one edge of the set.
|
| 47 |
+
A minimum edge cover is an edge covering of smallest cardinality.
|
| 48 |
+
|
| 49 |
+
Due to its implementation, the worst-case running time of this algorithm
|
| 50 |
+
is bounded by the worst-case running time of the function
|
| 51 |
+
``matching_algorithm``.
|
| 52 |
+
"""
|
| 53 |
+
if G.order() == 0: # Special case for the empty graph
|
| 54 |
+
return set()
|
| 55 |
+
if matching_algorithm is None:
|
| 56 |
+
matching_algorithm = hopcroft_karp_matching
|
| 57 |
+
return _min_edge_cover(G, matching_algorithm=matching_algorithm)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/edgelist.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
********************
|
| 3 |
+
Bipartite Edge Lists
|
| 4 |
+
********************
|
| 5 |
+
Read and write NetworkX graphs as bipartite edge lists.
|
| 6 |
+
|
| 7 |
+
Format
|
| 8 |
+
------
|
| 9 |
+
You can read or write three formats of edge lists with these functions.
|
| 10 |
+
|
| 11 |
+
Node pairs with no data::
|
| 12 |
+
|
| 13 |
+
1 2
|
| 14 |
+
|
| 15 |
+
Python dictionary as data::
|
| 16 |
+
|
| 17 |
+
1 2 {'weight':7, 'color':'green'}
|
| 18 |
+
|
| 19 |
+
Arbitrary data::
|
| 20 |
+
|
| 21 |
+
1 2 7 green
|
| 22 |
+
|
| 23 |
+
For each edge (u, v) the node u is assigned to part 0 and the node v to part 1.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
__all__ = ["generate_edgelist", "write_edgelist", "parse_edgelist", "read_edgelist"]
|
| 27 |
+
|
| 28 |
+
import networkx as nx
|
| 29 |
+
from networkx.utils import not_implemented_for, open_file
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@open_file(1, mode="wb")
|
| 33 |
+
def write_edgelist(G, path, comments="#", delimiter=" ", data=True, encoding="utf-8"):
|
| 34 |
+
"""Write a bipartite graph as a list of edges.
|
| 35 |
+
|
| 36 |
+
Parameters
|
| 37 |
+
----------
|
| 38 |
+
G : Graph
|
| 39 |
+
A NetworkX bipartite graph
|
| 40 |
+
path : file or string
|
| 41 |
+
File or filename to write. If a file is provided, it must be
|
| 42 |
+
opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed.
|
| 43 |
+
comments : string, optional
|
| 44 |
+
The character used to indicate the start of a comment
|
| 45 |
+
delimiter : string, optional
|
| 46 |
+
The string used to separate values. The default is whitespace.
|
| 47 |
+
data : bool or list, optional
|
| 48 |
+
If False write no edge data.
|
| 49 |
+
If True write a string representation of the edge data dictionary..
|
| 50 |
+
If a list (or other iterable) is provided, write the keys specified
|
| 51 |
+
in the list.
|
| 52 |
+
encoding: string, optional
|
| 53 |
+
Specify which encoding to use when writing file.
|
| 54 |
+
|
| 55 |
+
Examples
|
| 56 |
+
--------
|
| 57 |
+
>>> G = nx.path_graph(4)
|
| 58 |
+
>>> G.add_nodes_from([0, 2], bipartite=0)
|
| 59 |
+
>>> G.add_nodes_from([1, 3], bipartite=1)
|
| 60 |
+
>>> nx.write_edgelist(G, "test.edgelist")
|
| 61 |
+
>>> fh = open("test.edgelist_open", "wb")
|
| 62 |
+
>>> nx.write_edgelist(G, fh)
|
| 63 |
+
>>> nx.write_edgelist(G, "test.edgelist.gz")
|
| 64 |
+
>>> nx.write_edgelist(G, "test.edgelist_nodata.gz", data=False)
|
| 65 |
+
|
| 66 |
+
>>> G = nx.Graph()
|
| 67 |
+
>>> G.add_edge(1, 2, weight=7, color="red")
|
| 68 |
+
>>> nx.write_edgelist(G, "test.edgelist_bigger_nodata", data=False)
|
| 69 |
+
>>> nx.write_edgelist(G, "test.edgelist_color", data=["color"])
|
| 70 |
+
>>> nx.write_edgelist(G, "test.edgelist_color_weight", data=["color", "weight"])
|
| 71 |
+
|
| 72 |
+
See Also
|
| 73 |
+
--------
|
| 74 |
+
write_edgelist
|
| 75 |
+
generate_edgelist
|
| 76 |
+
"""
|
| 77 |
+
for line in generate_edgelist(G, delimiter, data):
|
| 78 |
+
line += "\n"
|
| 79 |
+
path.write(line.encode(encoding))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@not_implemented_for("directed")
|
| 83 |
+
def generate_edgelist(G, delimiter=" ", data=True):
|
| 84 |
+
"""Generate a single line of the bipartite graph G in edge list format.
|
| 85 |
+
|
| 86 |
+
Parameters
|
| 87 |
+
----------
|
| 88 |
+
G : NetworkX graph
|
| 89 |
+
The graph is assumed to have node attribute `part` set to 0,1 representing
|
| 90 |
+
the two graph parts
|
| 91 |
+
|
| 92 |
+
delimiter : string, optional
|
| 93 |
+
Separator for node labels
|
| 94 |
+
|
| 95 |
+
data : bool or list of keys
|
| 96 |
+
If False generate no edge data. If True use a dictionary
|
| 97 |
+
representation of edge data. If a list of keys use a list of data
|
| 98 |
+
values corresponding to the keys.
|
| 99 |
+
|
| 100 |
+
Returns
|
| 101 |
+
-------
|
| 102 |
+
lines : string
|
| 103 |
+
Lines of data in adjlist format.
|
| 104 |
+
|
| 105 |
+
Examples
|
| 106 |
+
--------
|
| 107 |
+
>>> from networkx.algorithms import bipartite
|
| 108 |
+
>>> G = nx.path_graph(4)
|
| 109 |
+
>>> G.add_nodes_from([0, 2], bipartite=0)
|
| 110 |
+
>>> G.add_nodes_from([1, 3], bipartite=1)
|
| 111 |
+
>>> G[1][2]["weight"] = 3
|
| 112 |
+
>>> G[2][3]["capacity"] = 12
|
| 113 |
+
>>> for line in bipartite.generate_edgelist(G, data=False):
|
| 114 |
+
... print(line)
|
| 115 |
+
0 1
|
| 116 |
+
2 1
|
| 117 |
+
2 3
|
| 118 |
+
|
| 119 |
+
>>> for line in bipartite.generate_edgelist(G):
|
| 120 |
+
... print(line)
|
| 121 |
+
0 1 {}
|
| 122 |
+
2 1 {'weight': 3}
|
| 123 |
+
2 3 {'capacity': 12}
|
| 124 |
+
|
| 125 |
+
>>> for line in bipartite.generate_edgelist(G, data=["weight"]):
|
| 126 |
+
... print(line)
|
| 127 |
+
0 1
|
| 128 |
+
2 1 3
|
| 129 |
+
2 3
|
| 130 |
+
"""
|
| 131 |
+
try:
|
| 132 |
+
part0 = [n for n, d in G.nodes.items() if d["bipartite"] == 0]
|
| 133 |
+
except BaseException as err:
|
| 134 |
+
raise AttributeError("Missing node attribute `bipartite`") from err
|
| 135 |
+
if data is True or data is False:
|
| 136 |
+
for n in part0:
|
| 137 |
+
for edge in G.edges(n, data=data):
|
| 138 |
+
yield delimiter.join(map(str, edge))
|
| 139 |
+
else:
|
| 140 |
+
for n in part0:
|
| 141 |
+
for u, v, d in G.edges(n, data=True):
|
| 142 |
+
edge = [u, v]
|
| 143 |
+
try:
|
| 144 |
+
edge.extend(d[k] for k in data)
|
| 145 |
+
except KeyError:
|
| 146 |
+
pass # missing data for this edge, should warn?
|
| 147 |
+
yield delimiter.join(map(str, edge))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@nx._dispatchable(name="bipartite_parse_edgelist", graphs=None, returns_graph=True)
|
| 151 |
+
def parse_edgelist(
|
| 152 |
+
lines, comments="#", delimiter=None, create_using=None, nodetype=None, data=True
|
| 153 |
+
):
|
| 154 |
+
"""Parse lines of an edge list representation of a bipartite graph.
|
| 155 |
+
|
| 156 |
+
Parameters
|
| 157 |
+
----------
|
| 158 |
+
lines : list or iterator of strings
|
| 159 |
+
Input data in edgelist format
|
| 160 |
+
comments : string, optional
|
| 161 |
+
Marker for comment lines
|
| 162 |
+
delimiter : string, optional
|
| 163 |
+
Separator for node labels
|
| 164 |
+
create_using: NetworkX graph container, optional
|
| 165 |
+
Use given NetworkX graph for holding nodes or edges.
|
| 166 |
+
nodetype : Python type, optional
|
| 167 |
+
Convert nodes to this type.
|
| 168 |
+
data : bool or list of (label,type) tuples
|
| 169 |
+
If False generate no edge data or if True use a dictionary
|
| 170 |
+
representation of edge data or a list tuples specifying dictionary
|
| 171 |
+
key names and types for edge data.
|
| 172 |
+
|
| 173 |
+
Returns
|
| 174 |
+
-------
|
| 175 |
+
G: NetworkX Graph
|
| 176 |
+
The bipartite graph corresponding to lines
|
| 177 |
+
|
| 178 |
+
Examples
|
| 179 |
+
--------
|
| 180 |
+
Edgelist with no data:
|
| 181 |
+
|
| 182 |
+
>>> from networkx.algorithms import bipartite
|
| 183 |
+
>>> lines = ["1 2", "2 3", "3 4"]
|
| 184 |
+
>>> G = bipartite.parse_edgelist(lines, nodetype=int)
|
| 185 |
+
>>> sorted(G.nodes())
|
| 186 |
+
[1, 2, 3, 4]
|
| 187 |
+
>>> sorted(G.nodes(data=True))
|
| 188 |
+
[(1, {'bipartite': 0}), (2, {'bipartite': 0}), (3, {'bipartite': 0}), (4, {'bipartite': 1})]
|
| 189 |
+
>>> sorted(G.edges())
|
| 190 |
+
[(1, 2), (2, 3), (3, 4)]
|
| 191 |
+
|
| 192 |
+
Edgelist with data in Python dictionary representation:
|
| 193 |
+
|
| 194 |
+
>>> lines = ["1 2 {'weight':3}", "2 3 {'weight':27}", "3 4 {'weight':3.0}"]
|
| 195 |
+
>>> G = bipartite.parse_edgelist(lines, nodetype=int)
|
| 196 |
+
>>> sorted(G.nodes())
|
| 197 |
+
[1, 2, 3, 4]
|
| 198 |
+
>>> sorted(G.edges(data=True))
|
| 199 |
+
[(1, 2, {'weight': 3}), (2, 3, {'weight': 27}), (3, 4, {'weight': 3.0})]
|
| 200 |
+
|
| 201 |
+
Edgelist with data in a list:
|
| 202 |
+
|
| 203 |
+
>>> lines = ["1 2 3", "2 3 27", "3 4 3.0"]
|
| 204 |
+
>>> G = bipartite.parse_edgelist(lines, nodetype=int, data=(("weight", float),))
|
| 205 |
+
>>> sorted(G.nodes())
|
| 206 |
+
[1, 2, 3, 4]
|
| 207 |
+
>>> sorted(G.edges(data=True))
|
| 208 |
+
[(1, 2, {'weight': 3.0}), (2, 3, {'weight': 27.0}), (3, 4, {'weight': 3.0})]
|
| 209 |
+
|
| 210 |
+
See Also
|
| 211 |
+
--------
|
| 212 |
+
"""
|
| 213 |
+
from ast import literal_eval
|
| 214 |
+
|
| 215 |
+
G = nx.empty_graph(0, create_using)
|
| 216 |
+
for line in lines:
|
| 217 |
+
p = line.find(comments)
|
| 218 |
+
if p >= 0:
|
| 219 |
+
line = line[:p]
|
| 220 |
+
if not len(line):
|
| 221 |
+
continue
|
| 222 |
+
# split line, should have 2 or more
|
| 223 |
+
s = line.rstrip("\n").split(delimiter)
|
| 224 |
+
if len(s) < 2:
|
| 225 |
+
continue
|
| 226 |
+
u = s.pop(0)
|
| 227 |
+
v = s.pop(0)
|
| 228 |
+
d = s
|
| 229 |
+
if nodetype is not None:
|
| 230 |
+
try:
|
| 231 |
+
u = nodetype(u)
|
| 232 |
+
v = nodetype(v)
|
| 233 |
+
except BaseException as err:
|
| 234 |
+
raise TypeError(
|
| 235 |
+
f"Failed to convert nodes {u},{v} to type {nodetype}."
|
| 236 |
+
) from err
|
| 237 |
+
|
| 238 |
+
if len(d) == 0 or data is False:
|
| 239 |
+
# no data or data type specified
|
| 240 |
+
edgedata = {}
|
| 241 |
+
elif data is True:
|
| 242 |
+
# no edge types specified
|
| 243 |
+
try: # try to evaluate as dictionary
|
| 244 |
+
edgedata = dict(literal_eval(" ".join(d)))
|
| 245 |
+
except BaseException as err:
|
| 246 |
+
raise TypeError(
|
| 247 |
+
f"Failed to convert edge data ({d}) to dictionary."
|
| 248 |
+
) from err
|
| 249 |
+
else:
|
| 250 |
+
# convert edge data to dictionary with specified keys and type
|
| 251 |
+
if len(d) != len(data):
|
| 252 |
+
raise IndexError(
|
| 253 |
+
f"Edge data {d} and data_keys {data} are not the same length"
|
| 254 |
+
)
|
| 255 |
+
edgedata = {}
|
| 256 |
+
for (edge_key, edge_type), edge_value in zip(data, d):
|
| 257 |
+
try:
|
| 258 |
+
edge_value = edge_type(edge_value)
|
| 259 |
+
except BaseException as err:
|
| 260 |
+
raise TypeError(
|
| 261 |
+
f"Failed to convert {edge_key} data "
|
| 262 |
+
f"{edge_value} to type {edge_type}."
|
| 263 |
+
) from err
|
| 264 |
+
edgedata.update({edge_key: edge_value})
|
| 265 |
+
G.add_node(u, bipartite=0)
|
| 266 |
+
G.add_node(v, bipartite=1)
|
| 267 |
+
G.add_edge(u, v, **edgedata)
|
| 268 |
+
return G
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@open_file(0, mode="rb")
|
| 272 |
+
@nx._dispatchable(name="bipartite_read_edgelist", graphs=None, returns_graph=True)
|
| 273 |
+
def read_edgelist(
|
| 274 |
+
path,
|
| 275 |
+
comments="#",
|
| 276 |
+
delimiter=None,
|
| 277 |
+
create_using=None,
|
| 278 |
+
nodetype=None,
|
| 279 |
+
data=True,
|
| 280 |
+
edgetype=None,
|
| 281 |
+
encoding="utf-8",
|
| 282 |
+
):
|
| 283 |
+
"""Read a bipartite graph from a list of edges.
|
| 284 |
+
|
| 285 |
+
Parameters
|
| 286 |
+
----------
|
| 287 |
+
path : file or string
|
| 288 |
+
File or filename to read. If a file is provided, it must be
|
| 289 |
+
opened in 'rb' mode.
|
| 290 |
+
Filenames ending in .gz or .bz2 will be decompressed.
|
| 291 |
+
comments : string, optional
|
| 292 |
+
The character used to indicate the start of a comment.
|
| 293 |
+
delimiter : string, optional
|
| 294 |
+
The string used to separate values. The default is whitespace.
|
| 295 |
+
create_using : Graph container, optional,
|
| 296 |
+
Use specified container to build graph. The default is networkx.Graph,
|
| 297 |
+
an undirected graph.
|
| 298 |
+
nodetype : int, float, str, Python type, optional
|
| 299 |
+
Convert node data from strings to specified type
|
| 300 |
+
data : bool or list of (label,type) tuples
|
| 301 |
+
Tuples specifying dictionary key names and types for edge data
|
| 302 |
+
edgetype : int, float, str, Python type, optional OBSOLETE
|
| 303 |
+
Convert edge data from strings to specified type and use as 'weight'
|
| 304 |
+
encoding: string, optional
|
| 305 |
+
Specify which encoding to use when reading file.
|
| 306 |
+
|
| 307 |
+
Returns
|
| 308 |
+
-------
|
| 309 |
+
G : graph
|
| 310 |
+
A networkx Graph or other type specified with create_using
|
| 311 |
+
|
| 312 |
+
Examples
|
| 313 |
+
--------
|
| 314 |
+
>>> from networkx.algorithms import bipartite
|
| 315 |
+
>>> G = nx.path_graph(4)
|
| 316 |
+
>>> G.add_nodes_from([0, 2], bipartite=0)
|
| 317 |
+
>>> G.add_nodes_from([1, 3], bipartite=1)
|
| 318 |
+
>>> bipartite.write_edgelist(G, "test.edgelist")
|
| 319 |
+
>>> G = bipartite.read_edgelist("test.edgelist")
|
| 320 |
+
|
| 321 |
+
>>> fh = open("test.edgelist", "rb")
|
| 322 |
+
>>> G = bipartite.read_edgelist(fh)
|
| 323 |
+
>>> fh.close()
|
| 324 |
+
|
| 325 |
+
>>> G = bipartite.read_edgelist("test.edgelist", nodetype=int)
|
| 326 |
+
|
| 327 |
+
Edgelist with data in a list:
|
| 328 |
+
|
| 329 |
+
>>> textline = "1 2 3"
|
| 330 |
+
>>> fh = open("test.edgelist", "w")
|
| 331 |
+
>>> d = fh.write(textline)
|
| 332 |
+
>>> fh.close()
|
| 333 |
+
>>> G = bipartite.read_edgelist(
|
| 334 |
+
... "test.edgelist", nodetype=int, data=(("weight", float),)
|
| 335 |
+
... )
|
| 336 |
+
>>> list(G)
|
| 337 |
+
[1, 2]
|
| 338 |
+
>>> list(G.edges(data=True))
|
| 339 |
+
[(1, 2, {'weight': 3.0})]
|
| 340 |
+
|
| 341 |
+
See parse_edgelist() for more examples of formatting.
|
| 342 |
+
|
| 343 |
+
See Also
|
| 344 |
+
--------
|
| 345 |
+
parse_edgelist
|
| 346 |
+
|
| 347 |
+
Notes
|
| 348 |
+
-----
|
| 349 |
+
Since nodes must be hashable, the function nodetype must return hashable
|
| 350 |
+
types (e.g. int, float, str, frozenset - or tuples of those, etc.)
|
| 351 |
+
"""
|
| 352 |
+
lines = (line.decode(encoding) for line in path)
|
| 353 |
+
return parse_edgelist(
|
| 354 |
+
lines,
|
| 355 |
+
comments=comments,
|
| 356 |
+
delimiter=delimiter,
|
| 357 |
+
create_using=create_using,
|
| 358 |
+
nodetype=nodetype,
|
| 359 |
+
data=data,
|
| 360 |
+
)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/extendability.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provides a function for computing the extendability of a graph which is
|
| 2 |
+
undirected, simple, connected and bipartite and contains at least one perfect matching."""
|
| 3 |
+
|
| 4 |
+
import networkx as nx
|
| 5 |
+
from networkx.utils import not_implemented_for
|
| 6 |
+
|
| 7 |
+
__all__ = ["maximal_extendability"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@not_implemented_for("directed")
|
| 11 |
+
@not_implemented_for("multigraph")
|
| 12 |
+
@nx._dispatchable
|
| 13 |
+
def maximal_extendability(G):
|
| 14 |
+
"""Computes the extendability of a graph.
|
| 15 |
+
|
| 16 |
+
The extendability of a graph is defined as the maximum $k$ for which `G`
|
| 17 |
+
is $k$-extendable. Graph `G` is $k$-extendable if and only if `G` has a
|
| 18 |
+
perfect matching and every set of $k$ independent edges can be extended
|
| 19 |
+
to a perfect matching in `G`.
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
G : NetworkX Graph
|
| 24 |
+
A fully-connected bipartite graph without self-loops
|
| 25 |
+
|
| 26 |
+
Returns
|
| 27 |
+
-------
|
| 28 |
+
extendability : int
|
| 29 |
+
|
| 30 |
+
Raises
|
| 31 |
+
------
|
| 32 |
+
NetworkXError
|
| 33 |
+
If the graph `G` is disconnected.
|
| 34 |
+
If the graph `G` is not bipartite.
|
| 35 |
+
If the graph `G` does not contain a perfect matching.
|
| 36 |
+
If the residual graph of `G` is not strongly connected.
|
| 37 |
+
|
| 38 |
+
Notes
|
| 39 |
+
-----
|
| 40 |
+
Definition:
|
| 41 |
+
Let `G` be a simple, connected, undirected and bipartite graph with a perfect
|
| 42 |
+
matching M and bipartition (U,V). The residual graph of `G`, denoted by $G_M$,
|
| 43 |
+
is the graph obtained from G by directing the edges of M from V to U and the
|
| 44 |
+
edges that do not belong to M from U to V.
|
| 45 |
+
|
| 46 |
+
Lemma [1]_ :
|
| 47 |
+
Let M be a perfect matching of `G`. `G` is $k$-extendable if and only if its residual
|
| 48 |
+
graph $G_M$ is strongly connected and there are $k$ vertex-disjoint directed
|
| 49 |
+
paths between every vertex of U and every vertex of V.
|
| 50 |
+
|
| 51 |
+
Assuming that input graph `G` is undirected, simple, connected, bipartite and contains
|
| 52 |
+
a perfect matching M, this function constructs the residual graph $G_M$ of G and
|
| 53 |
+
returns the minimum value among the maximum vertex-disjoint directed paths between
|
| 54 |
+
every vertex of U and every vertex of V in $G_M$. By combining the definitions
|
| 55 |
+
and the lemma, this value represents the extendability of the graph `G`.
|
| 56 |
+
|
| 57 |
+
Time complexity O($n^3$ $m^2$)) where $n$ is the number of vertices
|
| 58 |
+
and $m$ is the number of edges.
|
| 59 |
+
|
| 60 |
+
References
|
| 61 |
+
----------
|
| 62 |
+
.. [1] "A polynomial algorithm for the extendability problem in bipartite graphs",
|
| 63 |
+
J. Lakhal, L. Litzler, Information Processing Letters, 1998.
|
| 64 |
+
.. [2] "On n-extendible graphs", M. D. Plummer, Discrete Mathematics, 31:201–210, 1980
|
| 65 |
+
https://doi.org/10.1016/0012-365X(80)90037-0
|
| 66 |
+
|
| 67 |
+
"""
|
| 68 |
+
if not nx.is_connected(G):
|
| 69 |
+
raise nx.NetworkXError("Graph G is not connected")
|
| 70 |
+
|
| 71 |
+
if not nx.bipartite.is_bipartite(G):
|
| 72 |
+
raise nx.NetworkXError("Graph G is not bipartite")
|
| 73 |
+
|
| 74 |
+
U, V = nx.bipartite.sets(G)
|
| 75 |
+
|
| 76 |
+
maximum_matching = nx.bipartite.hopcroft_karp_matching(G)
|
| 77 |
+
|
| 78 |
+
if not nx.is_perfect_matching(G, maximum_matching):
|
| 79 |
+
raise nx.NetworkXError("Graph G does not contain a perfect matching")
|
| 80 |
+
|
| 81 |
+
# list of edges in perfect matching, directed from V to U
|
| 82 |
+
pm = [(node, maximum_matching[node]) for node in V & maximum_matching.keys()]
|
| 83 |
+
|
| 84 |
+
# Direct all the edges of G, from V to U if in matching, else from U to V
|
| 85 |
+
directed_edges = [
|
| 86 |
+
(x, y) if (x in V and (x, y) in pm) or (x in U and (y, x) not in pm) else (y, x)
|
| 87 |
+
for x, y in G.edges
|
| 88 |
+
]
|
| 89 |
+
|
| 90 |
+
# Construct the residual graph of G
|
| 91 |
+
residual_G = nx.DiGraph()
|
| 92 |
+
residual_G.add_nodes_from(G)
|
| 93 |
+
residual_G.add_edges_from(directed_edges)
|
| 94 |
+
|
| 95 |
+
if not nx.is_strongly_connected(residual_G):
|
| 96 |
+
raise nx.NetworkXError("The residual graph of G is not strongly connected")
|
| 97 |
+
|
| 98 |
+
# For node-pairs between V & U, keep min of max number of node-disjoint paths
|
| 99 |
+
# Variable $k$ stands for the extendability of graph G
|
| 100 |
+
k = float("inf")
|
| 101 |
+
for u in U:
|
| 102 |
+
for v in V:
|
| 103 |
+
num_paths = sum(1 for _ in nx.node_disjoint_paths(residual_G, u, v))
|
| 104 |
+
k = k if k < num_paths else num_paths
|
| 105 |
+
return k
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/generators.py
ADDED
|
@@ -0,0 +1,603 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Generators and functions for bipartite graphs.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
import numbers
|
| 7 |
+
from functools import reduce
|
| 8 |
+
|
| 9 |
+
import networkx as nx
|
| 10 |
+
from networkx.utils import nodes_or_number, py_random_state
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"configuration_model",
|
| 14 |
+
"havel_hakimi_graph",
|
| 15 |
+
"reverse_havel_hakimi_graph",
|
| 16 |
+
"alternating_havel_hakimi_graph",
|
| 17 |
+
"preferential_attachment_graph",
|
| 18 |
+
"random_graph",
|
| 19 |
+
"gnmk_random_graph",
|
| 20 |
+
"complete_bipartite_graph",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 25 |
+
@nodes_or_number([0, 1])
|
| 26 |
+
def complete_bipartite_graph(n1, n2, create_using=None):
|
| 27 |
+
"""Returns the complete bipartite graph `K_{n_1,n_2}`.
|
| 28 |
+
|
| 29 |
+
The graph is composed of two partitions with nodes 0 to (n1 - 1)
|
| 30 |
+
in the first and nodes n1 to (n1 + n2 - 1) in the second.
|
| 31 |
+
Each node in the first is connected to each node in the second.
|
| 32 |
+
|
| 33 |
+
Parameters
|
| 34 |
+
----------
|
| 35 |
+
n1, n2 : integer or iterable container of nodes
|
| 36 |
+
If integers, nodes are from `range(n1)` and `range(n1, n1 + n2)`.
|
| 37 |
+
If a container, the elements are the nodes.
|
| 38 |
+
create_using : NetworkX graph instance, (default: nx.Graph)
|
| 39 |
+
Return graph of this type.
|
| 40 |
+
|
| 41 |
+
Notes
|
| 42 |
+
-----
|
| 43 |
+
Nodes are the integers 0 to `n1 + n2 - 1` unless either n1 or n2 are
|
| 44 |
+
containers of nodes. If only one of n1 or n2 are integers, that
|
| 45 |
+
integer is replaced by `range` of that integer.
|
| 46 |
+
|
| 47 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
| 48 |
+
to indicate which bipartite set the node belongs to.
|
| 49 |
+
|
| 50 |
+
This function is not imported in the main namespace.
|
| 51 |
+
To use it use nx.bipartite.complete_bipartite_graph
|
| 52 |
+
"""
|
| 53 |
+
G = nx.empty_graph(0, create_using)
|
| 54 |
+
if G.is_directed():
|
| 55 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
| 56 |
+
|
| 57 |
+
n1, top = n1
|
| 58 |
+
n2, bottom = n2
|
| 59 |
+
if isinstance(n1, numbers.Integral) and isinstance(n2, numbers.Integral):
|
| 60 |
+
bottom = [n1 + i for i in bottom]
|
| 61 |
+
G.add_nodes_from(top, bipartite=0)
|
| 62 |
+
G.add_nodes_from(bottom, bipartite=1)
|
| 63 |
+
if len(G) != len(top) + len(bottom):
|
| 64 |
+
raise nx.NetworkXError("Inputs n1 and n2 must contain distinct nodes")
|
| 65 |
+
G.add_edges_from((u, v) for u in top for v in bottom)
|
| 66 |
+
G.graph["name"] = f"complete_bipartite_graph({len(top)}, {len(bottom)})"
|
| 67 |
+
return G
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@py_random_state(3)
|
| 71 |
+
@nx._dispatchable(name="bipartite_configuration_model", graphs=None, returns_graph=True)
|
| 72 |
+
def configuration_model(aseq, bseq, create_using=None, seed=None):
|
| 73 |
+
"""Returns a random bipartite graph from two given degree sequences.
|
| 74 |
+
|
| 75 |
+
Parameters
|
| 76 |
+
----------
|
| 77 |
+
aseq : list
|
| 78 |
+
Degree sequence for node set A.
|
| 79 |
+
bseq : list
|
| 80 |
+
Degree sequence for node set B.
|
| 81 |
+
create_using : NetworkX graph instance, optional
|
| 82 |
+
Return graph of this type.
|
| 83 |
+
seed : integer, random_state, or None (default)
|
| 84 |
+
Indicator of random number generation state.
|
| 85 |
+
See :ref:`Randomness<randomness>`.
|
| 86 |
+
|
| 87 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
| 88 |
+
(len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
|
| 89 |
+
Nodes from set A are connected to nodes in set B by choosing
|
| 90 |
+
randomly from the possible free stubs, one in A and one in B.
|
| 91 |
+
|
| 92 |
+
Notes
|
| 93 |
+
-----
|
| 94 |
+
The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
|
| 95 |
+
If no graph type is specified use MultiGraph with parallel edges.
|
| 96 |
+
If you want a graph with no parallel edges use create_using=Graph()
|
| 97 |
+
but then the resulting degree sequences might not be exact.
|
| 98 |
+
|
| 99 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
| 100 |
+
to indicate which bipartite set the node belongs to.
|
| 101 |
+
|
| 102 |
+
This function is not imported in the main namespace.
|
| 103 |
+
To use it use nx.bipartite.configuration_model
|
| 104 |
+
"""
|
| 105 |
+
G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
|
| 106 |
+
if G.is_directed():
|
| 107 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
| 108 |
+
|
| 109 |
+
# length and sum of each sequence
|
| 110 |
+
lena = len(aseq)
|
| 111 |
+
lenb = len(bseq)
|
| 112 |
+
suma = sum(aseq)
|
| 113 |
+
sumb = sum(bseq)
|
| 114 |
+
|
| 115 |
+
if not suma == sumb:
|
| 116 |
+
raise nx.NetworkXError(
|
| 117 |
+
f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
G = _add_nodes_with_bipartite_label(G, lena, lenb)
|
| 121 |
+
|
| 122 |
+
if len(aseq) == 0 or max(aseq) == 0:
|
| 123 |
+
return G # done if no edges
|
| 124 |
+
|
| 125 |
+
# build lists of degree-repeated vertex numbers
|
| 126 |
+
stubs = [[v] * aseq[v] for v in range(lena)]
|
| 127 |
+
astubs = [x for subseq in stubs for x in subseq]
|
| 128 |
+
|
| 129 |
+
stubs = [[v] * bseq[v - lena] for v in range(lena, lena + lenb)]
|
| 130 |
+
bstubs = [x for subseq in stubs for x in subseq]
|
| 131 |
+
|
| 132 |
+
# shuffle lists
|
| 133 |
+
seed.shuffle(astubs)
|
| 134 |
+
seed.shuffle(bstubs)
|
| 135 |
+
|
| 136 |
+
G.add_edges_from([astubs[i], bstubs[i]] for i in range(suma))
|
| 137 |
+
|
| 138 |
+
G.name = "bipartite_configuration_model"
|
| 139 |
+
return G
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@nx._dispatchable(name="bipartite_havel_hakimi_graph", graphs=None, returns_graph=True)
|
| 143 |
+
def havel_hakimi_graph(aseq, bseq, create_using=None):
|
| 144 |
+
"""Returns a bipartite graph from two given degree sequences using a
|
| 145 |
+
Havel-Hakimi style construction.
|
| 146 |
+
|
| 147 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
| 148 |
+
(len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
|
| 149 |
+
Nodes from the set A are connected to nodes in the set B by
|
| 150 |
+
connecting the highest degree nodes in set A to the highest degree
|
| 151 |
+
nodes in set B until all stubs are connected.
|
| 152 |
+
|
| 153 |
+
Parameters
|
| 154 |
+
----------
|
| 155 |
+
aseq : list
|
| 156 |
+
Degree sequence for node set A.
|
| 157 |
+
bseq : list
|
| 158 |
+
Degree sequence for node set B.
|
| 159 |
+
create_using : NetworkX graph instance, optional
|
| 160 |
+
Return graph of this type.
|
| 161 |
+
|
| 162 |
+
Notes
|
| 163 |
+
-----
|
| 164 |
+
The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
|
| 165 |
+
If no graph type is specified use MultiGraph with parallel edges.
|
| 166 |
+
If you want a graph with no parallel edges use create_using=Graph()
|
| 167 |
+
but then the resulting degree sequences might not be exact.
|
| 168 |
+
|
| 169 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
| 170 |
+
to indicate which bipartite set the node belongs to.
|
| 171 |
+
|
| 172 |
+
This function is not imported in the main namespace.
|
| 173 |
+
To use it use nx.bipartite.havel_hakimi_graph
|
| 174 |
+
"""
|
| 175 |
+
G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
|
| 176 |
+
if G.is_directed():
|
| 177 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
| 178 |
+
|
| 179 |
+
# length of the each sequence
|
| 180 |
+
naseq = len(aseq)
|
| 181 |
+
nbseq = len(bseq)
|
| 182 |
+
|
| 183 |
+
suma = sum(aseq)
|
| 184 |
+
sumb = sum(bseq)
|
| 185 |
+
|
| 186 |
+
if not suma == sumb:
|
| 187 |
+
raise nx.NetworkXError(
|
| 188 |
+
f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
G = _add_nodes_with_bipartite_label(G, naseq, nbseq)
|
| 192 |
+
|
| 193 |
+
if len(aseq) == 0 or max(aseq) == 0:
|
| 194 |
+
return G # done if no edges
|
| 195 |
+
|
| 196 |
+
# build list of degree-repeated vertex numbers
|
| 197 |
+
astubs = [[aseq[v], v] for v in range(naseq)]
|
| 198 |
+
bstubs = [[bseq[v - naseq], v] for v in range(naseq, naseq + nbseq)]
|
| 199 |
+
astubs.sort()
|
| 200 |
+
while astubs:
|
| 201 |
+
(degree, u) = astubs.pop() # take of largest degree node in the a set
|
| 202 |
+
if degree == 0:
|
| 203 |
+
break # done, all are zero
|
| 204 |
+
# connect the source to largest degree nodes in the b set
|
| 205 |
+
bstubs.sort()
|
| 206 |
+
for target in bstubs[-degree:]:
|
| 207 |
+
v = target[1]
|
| 208 |
+
G.add_edge(u, v)
|
| 209 |
+
target[0] -= 1 # note this updates bstubs too.
|
| 210 |
+
if target[0] == 0:
|
| 211 |
+
bstubs.remove(target)
|
| 212 |
+
|
| 213 |
+
G.name = "bipartite_havel_hakimi_graph"
|
| 214 |
+
return G
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 218 |
+
def reverse_havel_hakimi_graph(aseq, bseq, create_using=None):
|
| 219 |
+
"""Returns a bipartite graph from two given degree sequences using a
|
| 220 |
+
Havel-Hakimi style construction.
|
| 221 |
+
|
| 222 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
| 223 |
+
(len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
|
| 224 |
+
Nodes from set A are connected to nodes in the set B by connecting
|
| 225 |
+
the highest degree nodes in set A to the lowest degree nodes in
|
| 226 |
+
set B until all stubs are connected.
|
| 227 |
+
|
| 228 |
+
Parameters
|
| 229 |
+
----------
|
| 230 |
+
aseq : list
|
| 231 |
+
Degree sequence for node set A.
|
| 232 |
+
bseq : list
|
| 233 |
+
Degree sequence for node set B.
|
| 234 |
+
create_using : NetworkX graph instance, optional
|
| 235 |
+
Return graph of this type.
|
| 236 |
+
|
| 237 |
+
Notes
|
| 238 |
+
-----
|
| 239 |
+
The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
|
| 240 |
+
If no graph type is specified use MultiGraph with parallel edges.
|
| 241 |
+
If you want a graph with no parallel edges use create_using=Graph()
|
| 242 |
+
but then the resulting degree sequences might not be exact.
|
| 243 |
+
|
| 244 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
| 245 |
+
to indicate which bipartite set the node belongs to.
|
| 246 |
+
|
| 247 |
+
This function is not imported in the main namespace.
|
| 248 |
+
To use it use nx.bipartite.reverse_havel_hakimi_graph
|
| 249 |
+
"""
|
| 250 |
+
G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
|
| 251 |
+
if G.is_directed():
|
| 252 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
| 253 |
+
|
| 254 |
+
# length of the each sequence
|
| 255 |
+
lena = len(aseq)
|
| 256 |
+
lenb = len(bseq)
|
| 257 |
+
suma = sum(aseq)
|
| 258 |
+
sumb = sum(bseq)
|
| 259 |
+
|
| 260 |
+
if not suma == sumb:
|
| 261 |
+
raise nx.NetworkXError(
|
| 262 |
+
f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
G = _add_nodes_with_bipartite_label(G, lena, lenb)
|
| 266 |
+
|
| 267 |
+
if len(aseq) == 0 or max(aseq) == 0:
|
| 268 |
+
return G # done if no edges
|
| 269 |
+
|
| 270 |
+
# build list of degree-repeated vertex numbers
|
| 271 |
+
astubs = [[aseq[v], v] for v in range(lena)]
|
| 272 |
+
bstubs = [[bseq[v - lena], v] for v in range(lena, lena + lenb)]
|
| 273 |
+
astubs.sort()
|
| 274 |
+
bstubs.sort()
|
| 275 |
+
while astubs:
|
| 276 |
+
(degree, u) = astubs.pop() # take of largest degree node in the a set
|
| 277 |
+
if degree == 0:
|
| 278 |
+
break # done, all are zero
|
| 279 |
+
# connect the source to the smallest degree nodes in the b set
|
| 280 |
+
for target in bstubs[0:degree]:
|
| 281 |
+
v = target[1]
|
| 282 |
+
G.add_edge(u, v)
|
| 283 |
+
target[0] -= 1 # note this updates bstubs too.
|
| 284 |
+
if target[0] == 0:
|
| 285 |
+
bstubs.remove(target)
|
| 286 |
+
|
| 287 |
+
G.name = "bipartite_reverse_havel_hakimi_graph"
|
| 288 |
+
return G
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 292 |
+
def alternating_havel_hakimi_graph(aseq, bseq, create_using=None):
|
| 293 |
+
"""Returns a bipartite graph from two given degree sequences using
|
| 294 |
+
an alternating Havel-Hakimi style construction.
|
| 295 |
+
|
| 296 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
| 297 |
+
(len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
|
| 298 |
+
Nodes from the set A are connected to nodes in the set B by
|
| 299 |
+
connecting the highest degree nodes in set A to alternatively the
|
| 300 |
+
highest and the lowest degree nodes in set B until all stubs are
|
| 301 |
+
connected.
|
| 302 |
+
|
| 303 |
+
Parameters
|
| 304 |
+
----------
|
| 305 |
+
aseq : list
|
| 306 |
+
Degree sequence for node set A.
|
| 307 |
+
bseq : list
|
| 308 |
+
Degree sequence for node set B.
|
| 309 |
+
create_using : NetworkX graph instance, optional
|
| 310 |
+
Return graph of this type.
|
| 311 |
+
|
| 312 |
+
Notes
|
| 313 |
+
-----
|
| 314 |
+
The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
|
| 315 |
+
If no graph type is specified use MultiGraph with parallel edges.
|
| 316 |
+
If you want a graph with no parallel edges use create_using=Graph()
|
| 317 |
+
but then the resulting degree sequences might not be exact.
|
| 318 |
+
|
| 319 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
| 320 |
+
to indicate which bipartite set the node belongs to.
|
| 321 |
+
|
| 322 |
+
This function is not imported in the main namespace.
|
| 323 |
+
To use it use nx.bipartite.alternating_havel_hakimi_graph
|
| 324 |
+
"""
|
| 325 |
+
G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
|
| 326 |
+
if G.is_directed():
|
| 327 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
| 328 |
+
|
| 329 |
+
# length of the each sequence
|
| 330 |
+
naseq = len(aseq)
|
| 331 |
+
nbseq = len(bseq)
|
| 332 |
+
suma = sum(aseq)
|
| 333 |
+
sumb = sum(bseq)
|
| 334 |
+
|
| 335 |
+
if not suma == sumb:
|
| 336 |
+
raise nx.NetworkXError(
|
| 337 |
+
f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
G = _add_nodes_with_bipartite_label(G, naseq, nbseq)
|
| 341 |
+
|
| 342 |
+
if len(aseq) == 0 or max(aseq) == 0:
|
| 343 |
+
return G # done if no edges
|
| 344 |
+
# build list of degree-repeated vertex numbers
|
| 345 |
+
astubs = [[aseq[v], v] for v in range(naseq)]
|
| 346 |
+
bstubs = [[bseq[v - naseq], v] for v in range(naseq, naseq + nbseq)]
|
| 347 |
+
while astubs:
|
| 348 |
+
astubs.sort()
|
| 349 |
+
(degree, u) = astubs.pop() # take of largest degree node in the a set
|
| 350 |
+
if degree == 0:
|
| 351 |
+
break # done, all are zero
|
| 352 |
+
bstubs.sort()
|
| 353 |
+
small = bstubs[0 : degree // 2] # add these low degree targets
|
| 354 |
+
large = bstubs[(-degree + degree // 2) :] # now high degree targets
|
| 355 |
+
stubs = [x for z in zip(large, small) for x in z] # combine, sorry
|
| 356 |
+
if len(stubs) < len(small) + len(large): # check for zip truncation
|
| 357 |
+
stubs.append(large.pop())
|
| 358 |
+
for target in stubs:
|
| 359 |
+
v = target[1]
|
| 360 |
+
G.add_edge(u, v)
|
| 361 |
+
target[0] -= 1 # note this updates bstubs too.
|
| 362 |
+
if target[0] == 0:
|
| 363 |
+
bstubs.remove(target)
|
| 364 |
+
|
| 365 |
+
G.name = "bipartite_alternating_havel_hakimi_graph"
|
| 366 |
+
return G
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
@py_random_state(3)
|
| 370 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 371 |
+
def preferential_attachment_graph(aseq, p, create_using=None, seed=None):
|
| 372 |
+
"""Create a bipartite graph with a preferential attachment model from
|
| 373 |
+
a given single degree sequence.
|
| 374 |
+
|
| 375 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
| 376 |
+
(len(aseq) - 1) and set B has nodes starting with node len(aseq).
|
| 377 |
+
The number of nodes in set B is random.
|
| 378 |
+
|
| 379 |
+
Parameters
|
| 380 |
+
----------
|
| 381 |
+
aseq : list
|
| 382 |
+
Degree sequence for node set A.
|
| 383 |
+
p : float
|
| 384 |
+
Probability that a new bottom node is added.
|
| 385 |
+
create_using : NetworkX graph instance, optional
|
| 386 |
+
Return graph of this type.
|
| 387 |
+
seed : integer, random_state, or None (default)
|
| 388 |
+
Indicator of random number generation state.
|
| 389 |
+
See :ref:`Randomness<randomness>`.
|
| 390 |
+
|
| 391 |
+
References
|
| 392 |
+
----------
|
| 393 |
+
.. [1] Guillaume, J.L. and Latapy, M.,
|
| 394 |
+
Bipartite graphs as models of complex networks.
|
| 395 |
+
Physica A: Statistical Mechanics and its Applications,
|
| 396 |
+
2006, 371(2), pp.795-813.
|
| 397 |
+
.. [2] Jean-Loup Guillaume and Matthieu Latapy,
|
| 398 |
+
Bipartite structure of all complex networks,
|
| 399 |
+
Inf. Process. Lett. 90, 2004, pg. 215-221
|
| 400 |
+
https://doi.org/10.1016/j.ipl.2004.03.007
|
| 401 |
+
|
| 402 |
+
Notes
|
| 403 |
+
-----
|
| 404 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
| 405 |
+
to indicate which bipartite set the node belongs to.
|
| 406 |
+
|
| 407 |
+
This function is not imported in the main namespace.
|
| 408 |
+
To use it use nx.bipartite.preferential_attachment_graph
|
| 409 |
+
"""
|
| 410 |
+
G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
|
| 411 |
+
if G.is_directed():
|
| 412 |
+
raise nx.NetworkXError("Directed Graph not supported")
|
| 413 |
+
|
| 414 |
+
if p > 1:
|
| 415 |
+
raise nx.NetworkXError(f"probability {p} > 1")
|
| 416 |
+
|
| 417 |
+
naseq = len(aseq)
|
| 418 |
+
G = _add_nodes_with_bipartite_label(G, naseq, 0)
|
| 419 |
+
vv = [[v] * aseq[v] for v in range(naseq)]
|
| 420 |
+
while vv:
|
| 421 |
+
while vv[0]:
|
| 422 |
+
source = vv[0][0]
|
| 423 |
+
vv[0].remove(source)
|
| 424 |
+
if seed.random() < p or len(G) == naseq:
|
| 425 |
+
target = len(G)
|
| 426 |
+
G.add_node(target, bipartite=1)
|
| 427 |
+
G.add_edge(source, target)
|
| 428 |
+
else:
|
| 429 |
+
bb = [[b] * G.degree(b) for b in range(naseq, len(G))]
|
| 430 |
+
# flatten the list of lists into a list.
|
| 431 |
+
bbstubs = reduce(lambda x, y: x + y, bb)
|
| 432 |
+
# choose preferentially a bottom node.
|
| 433 |
+
target = seed.choice(bbstubs)
|
| 434 |
+
G.add_node(target, bipartite=1)
|
| 435 |
+
G.add_edge(source, target)
|
| 436 |
+
vv.remove(vv[0])
|
| 437 |
+
G.name = "bipartite_preferential_attachment_model"
|
| 438 |
+
return G
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
@py_random_state(3)
|
| 442 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 443 |
+
def random_graph(n, m, p, seed=None, directed=False):
|
| 444 |
+
"""Returns a bipartite random graph.
|
| 445 |
+
|
| 446 |
+
This is a bipartite version of the binomial (Erdős-Rényi) graph.
|
| 447 |
+
The graph is composed of two partitions. Set A has nodes 0 to
|
| 448 |
+
(n - 1) and set B has nodes n to (n + m - 1).
|
| 449 |
+
|
| 450 |
+
Parameters
|
| 451 |
+
----------
|
| 452 |
+
n : int
|
| 453 |
+
The number of nodes in the first bipartite set.
|
| 454 |
+
m : int
|
| 455 |
+
The number of nodes in the second bipartite set.
|
| 456 |
+
p : float
|
| 457 |
+
Probability for edge creation.
|
| 458 |
+
seed : integer, random_state, or None (default)
|
| 459 |
+
Indicator of random number generation state.
|
| 460 |
+
See :ref:`Randomness<randomness>`.
|
| 461 |
+
directed : bool, optional (default=False)
|
| 462 |
+
If True return a directed graph
|
| 463 |
+
|
| 464 |
+
Notes
|
| 465 |
+
-----
|
| 466 |
+
The bipartite random graph algorithm chooses each of the n*m (undirected)
|
| 467 |
+
or 2*nm (directed) possible edges with probability p.
|
| 468 |
+
|
| 469 |
+
This algorithm is $O(n+m)$ where $m$ is the expected number of edges.
|
| 470 |
+
|
| 471 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
| 472 |
+
to indicate which bipartite set the node belongs to.
|
| 473 |
+
|
| 474 |
+
This function is not imported in the main namespace.
|
| 475 |
+
To use it use nx.bipartite.random_graph
|
| 476 |
+
|
| 477 |
+
See Also
|
| 478 |
+
--------
|
| 479 |
+
gnp_random_graph, configuration_model
|
| 480 |
+
|
| 481 |
+
References
|
| 482 |
+
----------
|
| 483 |
+
.. [1] Vladimir Batagelj and Ulrik Brandes,
|
| 484 |
+
"Efficient generation of large random networks",
|
| 485 |
+
Phys. Rev. E, 71, 036113, 2005.
|
| 486 |
+
"""
|
| 487 |
+
G = nx.Graph()
|
| 488 |
+
G = _add_nodes_with_bipartite_label(G, n, m)
|
| 489 |
+
if directed:
|
| 490 |
+
G = nx.DiGraph(G)
|
| 491 |
+
G.name = f"fast_gnp_random_graph({n},{m},{p})"
|
| 492 |
+
|
| 493 |
+
if p <= 0:
|
| 494 |
+
return G
|
| 495 |
+
if p >= 1:
|
| 496 |
+
return nx.complete_bipartite_graph(n, m)
|
| 497 |
+
|
| 498 |
+
lp = math.log(1.0 - p)
|
| 499 |
+
|
| 500 |
+
v = 0
|
| 501 |
+
w = -1
|
| 502 |
+
while v < n:
|
| 503 |
+
lr = math.log(1.0 - seed.random())
|
| 504 |
+
w = w + 1 + int(lr / lp)
|
| 505 |
+
while w >= m and v < n:
|
| 506 |
+
w = w - m
|
| 507 |
+
v = v + 1
|
| 508 |
+
if v < n:
|
| 509 |
+
G.add_edge(v, n + w)
|
| 510 |
+
|
| 511 |
+
if directed:
|
| 512 |
+
# use the same algorithm to
|
| 513 |
+
# add edges from the "m" to "n" set
|
| 514 |
+
v = 0
|
| 515 |
+
w = -1
|
| 516 |
+
while v < n:
|
| 517 |
+
lr = math.log(1.0 - seed.random())
|
| 518 |
+
w = w + 1 + int(lr / lp)
|
| 519 |
+
while w >= m and v < n:
|
| 520 |
+
w = w - m
|
| 521 |
+
v = v + 1
|
| 522 |
+
if v < n:
|
| 523 |
+
G.add_edge(n + w, v)
|
| 524 |
+
|
| 525 |
+
return G
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
@py_random_state(3)
|
| 529 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 530 |
+
def gnmk_random_graph(n, m, k, seed=None, directed=False):
|
| 531 |
+
"""Returns a random bipartite graph G_{n,m,k}.
|
| 532 |
+
|
| 533 |
+
Produces a bipartite graph chosen randomly out of the set of all graphs
|
| 534 |
+
with n top nodes, m bottom nodes, and k edges.
|
| 535 |
+
The graph is composed of two sets of nodes.
|
| 536 |
+
Set A has nodes 0 to (n - 1) and set B has nodes n to (n + m - 1).
|
| 537 |
+
|
| 538 |
+
Parameters
|
| 539 |
+
----------
|
| 540 |
+
n : int
|
| 541 |
+
The number of nodes in the first bipartite set.
|
| 542 |
+
m : int
|
| 543 |
+
The number of nodes in the second bipartite set.
|
| 544 |
+
k : int
|
| 545 |
+
The number of edges
|
| 546 |
+
seed : integer, random_state, or None (default)
|
| 547 |
+
Indicator of random number generation state.
|
| 548 |
+
See :ref:`Randomness<randomness>`.
|
| 549 |
+
directed : bool, optional (default=False)
|
| 550 |
+
If True return a directed graph
|
| 551 |
+
|
| 552 |
+
Examples
|
| 553 |
+
--------
|
| 554 |
+
>>> G = nx.bipartite.gnmk_random_graph(10, 20, 50)
|
| 555 |
+
|
| 556 |
+
See Also
|
| 557 |
+
--------
|
| 558 |
+
gnm_random_graph
|
| 559 |
+
|
| 560 |
+
Notes
|
| 561 |
+
-----
|
| 562 |
+
If k > m * n then a complete bipartite graph is returned.
|
| 563 |
+
|
| 564 |
+
This graph is a bipartite version of the `G_{nm}` random graph model.
|
| 565 |
+
|
| 566 |
+
The nodes are assigned the attribute 'bipartite' with the value 0 or 1
|
| 567 |
+
to indicate which bipartite set the node belongs to.
|
| 568 |
+
|
| 569 |
+
This function is not imported in the main namespace.
|
| 570 |
+
To use it use nx.bipartite.gnmk_random_graph
|
| 571 |
+
"""
|
| 572 |
+
G = nx.Graph()
|
| 573 |
+
G = _add_nodes_with_bipartite_label(G, n, m)
|
| 574 |
+
if directed:
|
| 575 |
+
G = nx.DiGraph(G)
|
| 576 |
+
G.name = f"bipartite_gnm_random_graph({n},{m},{k})"
|
| 577 |
+
if n == 1 or m == 1:
|
| 578 |
+
return G
|
| 579 |
+
max_edges = n * m # max_edges for bipartite networks
|
| 580 |
+
if k >= max_edges: # Maybe we should raise an exception here
|
| 581 |
+
return nx.complete_bipartite_graph(n, m, create_using=G)
|
| 582 |
+
|
| 583 |
+
top = [n for n, d in G.nodes(data=True) if d["bipartite"] == 0]
|
| 584 |
+
bottom = list(set(G) - set(top))
|
| 585 |
+
edge_count = 0
|
| 586 |
+
while edge_count < k:
|
| 587 |
+
# generate random edge,u,v
|
| 588 |
+
u = seed.choice(top)
|
| 589 |
+
v = seed.choice(bottom)
|
| 590 |
+
if v in G[u]:
|
| 591 |
+
continue
|
| 592 |
+
else:
|
| 593 |
+
G.add_edge(u, v)
|
| 594 |
+
edge_count += 1
|
| 595 |
+
return G
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def _add_nodes_with_bipartite_label(G, lena, lenb):
|
| 599 |
+
G.add_nodes_from(range(lena + lenb))
|
| 600 |
+
b = dict(zip(range(lena), [0] * lena))
|
| 601 |
+
b.update(dict(zip(range(lena, lena + lenb), [1] * lenb)))
|
| 602 |
+
nx.set_node_attributes(G, b, "bipartite")
|
| 603 |
+
return G
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/link_analysis.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = ["birank"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 9 |
+
def birank(
|
| 10 |
+
G,
|
| 11 |
+
nodes,
|
| 12 |
+
*,
|
| 13 |
+
alpha=None,
|
| 14 |
+
beta=None,
|
| 15 |
+
top_personalization=None,
|
| 16 |
+
bottom_personalization=None,
|
| 17 |
+
max_iter=100,
|
| 18 |
+
tol=1.0e-6,
|
| 19 |
+
weight="weight",
|
| 20 |
+
):
|
| 21 |
+
r"""Compute the BiRank score for nodes in a bipartite network.
|
| 22 |
+
|
| 23 |
+
Given the bipartite sets $U$ and $P$, the BiRank algorithm seeks to satisfy
|
| 24 |
+
the following recursive relationships between the scores of nodes $j \in P$
|
| 25 |
+
and $i \in U$:
|
| 26 |
+
|
| 27 |
+
.. math::
|
| 28 |
+
|
| 29 |
+
p_j = \alpha \sum_{i \in U} \frac{w_{ij}}{\sqrt{d_i}\sqrt{d_j}} u_i
|
| 30 |
+
+ (1 - \alpha) p_j^0
|
| 31 |
+
|
| 32 |
+
u_i = \beta \sum_{j \in P} \frac{w_{ij}}{\sqrt{d_i}\sqrt{d_j}} p_j
|
| 33 |
+
+ (1 - \beta) u_i^0
|
| 34 |
+
|
| 35 |
+
where
|
| 36 |
+
|
| 37 |
+
* $p_j$ and $u_i$ are the BiRank scores of nodes $j \in P$ and $i \in U$.
|
| 38 |
+
* $w_{ij}$ is the weight of the edge between nodes $i \in U$ and $j \in P$
|
| 39 |
+
(With a value of 0 if no edge exists).
|
| 40 |
+
* $d_i$ and $d_j$ are the weighted degrees of nodes $i \in U$ and $j \in P$,
|
| 41 |
+
respectively.
|
| 42 |
+
* $p_j^0$ and $u_i^0$ are personalization values that can encode a priori
|
| 43 |
+
weights for the nodes $j \in P$ and $i \in U$, respectively. Akin to the
|
| 44 |
+
personalization vector used by PageRank.
|
| 45 |
+
* $\alpha$ and $\beta$ are damping hyperparameters applying to nodes in $P$
|
| 46 |
+
and $U$ respectively. They can take values in the interval $[0, 1]$, and
|
| 47 |
+
are analogous to those used by PageRank.
|
| 48 |
+
|
| 49 |
+
Below are two use cases for this algorithm.
|
| 50 |
+
|
| 51 |
+
1. Personalized Recommendation System
|
| 52 |
+
Given a bipartite graph representing users and items, BiRank can be used
|
| 53 |
+
as a collaborative filtering algorithm to recommend items to users.
|
| 54 |
+
Previous ratings are encoded as edge weights, and the specific ratings
|
| 55 |
+
of an individual user on a set of items is used as the personalization
|
| 56 |
+
vector over items. See the example below for an implementation of this
|
| 57 |
+
on a toy dataset provided in [1]_.
|
| 58 |
+
|
| 59 |
+
2. Popularity Prediction
|
| 60 |
+
Given a bipartite graph representing user interactions with items, e.g.
|
| 61 |
+
commits to a GitHub repository, BiRank can be used to predict the
|
| 62 |
+
popularity of a given item. Edge weights should encode the strength of
|
| 63 |
+
the interaction signal. This could be a raw count, or weighted by a time
|
| 64 |
+
decay function like that specified in Eq. (15) of [1]_. The
|
| 65 |
+
personalization vectors can be used to encode existing popularity
|
| 66 |
+
signals, for example, the monthly download count of a repository's
|
| 67 |
+
package.
|
| 68 |
+
|
| 69 |
+
Parameters
|
| 70 |
+
----------
|
| 71 |
+
G : graph
|
| 72 |
+
A bipartite network
|
| 73 |
+
|
| 74 |
+
nodes : iterable of nodes
|
| 75 |
+
Container with all nodes belonging to the first bipartite node set
|
| 76 |
+
('top'). The nodes in this set use the hyperparameter `alpha`, and the
|
| 77 |
+
personalization dictionary `top_personalization`. The nodes in the second
|
| 78 |
+
bipartite node set ('bottom') are automatically determined by taking the
|
| 79 |
+
complement of 'top' with respect to the graph `G`.
|
| 80 |
+
|
| 81 |
+
alpha : float, optional (default=0.80 if top_personalization not empty, else 1)
|
| 82 |
+
Damping factor for the 'top' nodes. Must be in the interval $[0, 1]$.
|
| 83 |
+
Larger alpha and beta generally reduce the effect of the personalizations
|
| 84 |
+
and increase the number of iterations before convergence. Choice of value
|
| 85 |
+
is largely dependent on use case, and experimentation is recommended.
|
| 86 |
+
|
| 87 |
+
beta : float, optional (default=0.80 if bottom_personalization not empty, else 1)
|
| 88 |
+
Damping factor for the 'bottom' nodes. Must be in the interval $[0, 1]$.
|
| 89 |
+
Larger alpha and beta generally reduce the effect of the personalizations
|
| 90 |
+
and increase the number of iterations before convergence. Choice of value
|
| 91 |
+
is largely dependent on use case, and experimentation is recommended.
|
| 92 |
+
|
| 93 |
+
top_personalization : dict, optional (default=None)
|
| 94 |
+
Dictionary keyed by nodes in 'top' to that node's personalization value.
|
| 95 |
+
Unspecified nodes in 'top' will be assigned a personalization value of 0.
|
| 96 |
+
Personalization values are used to encode a priori weights for a given node,
|
| 97 |
+
and should be non-negative.
|
| 98 |
+
|
| 99 |
+
bottom_personalization : dict, optional (default=None)
|
| 100 |
+
Dictionary keyed by nodes in 'bottom' to that node's personalization value.
|
| 101 |
+
Unspecified nodes in 'bottom' will be assigned a personalization value of 0.
|
| 102 |
+
Personalization values are used to encode a priori weights for a given node,
|
| 103 |
+
and should be non-negative.
|
| 104 |
+
|
| 105 |
+
max_iter : int, optional (default=100)
|
| 106 |
+
Maximum number of iterations in power method eigenvalue solver.
|
| 107 |
+
|
| 108 |
+
tol : float, optional (default=1.0e-6)
|
| 109 |
+
Error tolerance used to check convergence in power method solver. The
|
| 110 |
+
iteration will stop after a tolerance of both ``len(top) * tol`` and
|
| 111 |
+
``len(bottom) * tol`` is reached for nodes in 'top' and 'bottom'
|
| 112 |
+
respectively.
|
| 113 |
+
|
| 114 |
+
weight : string or None, optional (default='weight')
|
| 115 |
+
Edge data key to use as weight.
|
| 116 |
+
|
| 117 |
+
Returns
|
| 118 |
+
-------
|
| 119 |
+
birank : dictionary
|
| 120 |
+
Dictionary keyed by node to that node's BiRank score.
|
| 121 |
+
|
| 122 |
+
Raises
|
| 123 |
+
------
|
| 124 |
+
NetworkXAlgorithmError
|
| 125 |
+
If the parameters `alpha` or `beta` are not in the interval [0, 1],
|
| 126 |
+
if either of the bipartite sets are empty, or if negative values are
|
| 127 |
+
provided in the personalization dictionaries.
|
| 128 |
+
|
| 129 |
+
PowerIterationFailedConvergence
|
| 130 |
+
If the algorithm fails to converge to the specified tolerance
|
| 131 |
+
within the specified number of iterations of the power iteration
|
| 132 |
+
method.
|
| 133 |
+
|
| 134 |
+
Examples
|
| 135 |
+
--------
|
| 136 |
+
Construct a bipartite graph with user-item ratings and use BiRank to
|
| 137 |
+
recommend items to a user (user 1). The example below uses the `rating`
|
| 138 |
+
edge attribute as the weight of the edges. The `top_personalization` vector
|
| 139 |
+
is used to encode the user's previous ratings on items.
|
| 140 |
+
|
| 141 |
+
Creation of graph, bipartite sets for the example.
|
| 142 |
+
|
| 143 |
+
>>> elist = [
|
| 144 |
+
... ("u1", "p1", 5),
|
| 145 |
+
... ("u2", "p1", 5),
|
| 146 |
+
... ("u2", "p2", 4),
|
| 147 |
+
... ("u3", "p1", 3),
|
| 148 |
+
... ("u3", "p3", 2),
|
| 149 |
+
... ]
|
| 150 |
+
>>> G = nx.Graph()
|
| 151 |
+
>>> G.add_weighted_edges_from(elist, weight="rating")
|
| 152 |
+
>>> product_nodes = ("p1", "p2", "p3")
|
| 153 |
+
>>> user = "u1"
|
| 154 |
+
|
| 155 |
+
First, we create a personalization vector for the user based on on their
|
| 156 |
+
ratings of past items. In this case they have only rated one item (p1, with
|
| 157 |
+
a rating of 5) in the past.
|
| 158 |
+
|
| 159 |
+
>>> user_personalization = {
|
| 160 |
+
... product: rating
|
| 161 |
+
... for _, product, rating in G.edges(nbunch=user, data="rating")
|
| 162 |
+
... }
|
| 163 |
+
>>> user_personalization
|
| 164 |
+
{'p1': 5}
|
| 165 |
+
|
| 166 |
+
Calculate the BiRank score of all nodes in the graph, filter for the items
|
| 167 |
+
that the user has not rated yet, and sort the results by score.
|
| 168 |
+
|
| 169 |
+
>>> user_birank_results = nx.bipartite.birank(
|
| 170 |
+
... G, product_nodes, top_personalization=user_personalization, weight="rating"
|
| 171 |
+
... )
|
| 172 |
+
>>> user_birank_results = filter(
|
| 173 |
+
... lambda item: item[0][0] == "p" and user not in G.neighbors(item[0]),
|
| 174 |
+
... user_birank_results.items(),
|
| 175 |
+
... )
|
| 176 |
+
>>> user_birank_results = sorted(
|
| 177 |
+
... user_birank_results, key=lambda item: item[1], reverse=True
|
| 178 |
+
... )
|
| 179 |
+
>>> user_recommendations = {
|
| 180 |
+
... product: round(score, 5) for product, score in user_birank_results
|
| 181 |
+
... }
|
| 182 |
+
>>> user_recommendations
|
| 183 |
+
{'p2': 1.44818, 'p3': 1.04811}
|
| 184 |
+
|
| 185 |
+
We find that user 1 should be recommended item p2 over item p3. This is due
|
| 186 |
+
to the fact that user 2 rated also rated p1 highly, while user 3 did not.
|
| 187 |
+
Thus user 2's tastes are inferred to be similar to user 1's, and carry more
|
| 188 |
+
weight in the recommendation.
|
| 189 |
+
|
| 190 |
+
See Also
|
| 191 |
+
--------
|
| 192 |
+
:func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
|
| 193 |
+
:func:`~networkx.algorithms.link_analysis.hits_alg.hits`
|
| 194 |
+
:func:`~networkx.algorithms.bipartite.centrality.betweenness_centrality`
|
| 195 |
+
:func:`~networkx.algorithms.bipartite.basic.sets`
|
| 196 |
+
:func:`~networkx.algorithms.bipartite.basic.is_bipartite`
|
| 197 |
+
|
| 198 |
+
Notes
|
| 199 |
+
-----
|
| 200 |
+
The `nodes` input parameter must contain all nodes in one bipartite
|
| 201 |
+
node set, but the dictionary returned contains all nodes from both
|
| 202 |
+
bipartite node sets. See :mod:`bipartite documentation
|
| 203 |
+
<networkx.algorithms.bipartite>` for further details on how
|
| 204 |
+
bipartite graphs are handled in NetworkX.
|
| 205 |
+
|
| 206 |
+
In the case a personalization dictionary is not provided for top (bottom)
|
| 207 |
+
`alpha` (`beta`) will default to 1. This is because a damping factor
|
| 208 |
+
without a non-zero entry in the personalization vector will lead to the
|
| 209 |
+
algorithm converging to the zero vector.
|
| 210 |
+
|
| 211 |
+
References
|
| 212 |
+
----------
|
| 213 |
+
.. [1] Xiangnan He, Ming Gao, Min-Yen Kan, and Dingxian Wang. 2017.
|
| 214 |
+
BiRank: Towards Ranking on Bipartite Graphs. IEEE Trans. on Knowl.
|
| 215 |
+
and Data Eng. 29, 1 (January 2017), 57–71.
|
| 216 |
+
https://arxiv.org/pdf/1708.04396
|
| 217 |
+
|
| 218 |
+
"""
|
| 219 |
+
import numpy as np
|
| 220 |
+
import scipy as sp
|
| 221 |
+
|
| 222 |
+
# Initialize the sets of top and bottom nodes
|
| 223 |
+
top = set(nodes)
|
| 224 |
+
bottom = set(G) - top
|
| 225 |
+
top_count = len(top)
|
| 226 |
+
bottom_count = len(bottom)
|
| 227 |
+
|
| 228 |
+
if top_count == 0 or bottom_count == 0:
|
| 229 |
+
raise nx.NetworkXAlgorithmError(
|
| 230 |
+
"The BiRank algorithm requires a bipartite graph with at least one"
|
| 231 |
+
"node in each set."
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
# Clean the personalization dictionaries
|
| 235 |
+
top_personalization = _clean_personalization_dict(top_personalization)
|
| 236 |
+
bottom_personalization = _clean_personalization_dict(bottom_personalization)
|
| 237 |
+
|
| 238 |
+
# Set default values for alpha and beta if not provided
|
| 239 |
+
if alpha is None:
|
| 240 |
+
alpha = 0.8 if top_personalization else 1
|
| 241 |
+
if beta is None:
|
| 242 |
+
beta = 0.8 if bottom_personalization else 1
|
| 243 |
+
|
| 244 |
+
if alpha < 0 or alpha > 1:
|
| 245 |
+
raise nx.NetworkXAlgorithmError("alpha must be in the interval [0, 1]")
|
| 246 |
+
if beta < 0 or beta > 1:
|
| 247 |
+
raise nx.NetworkXAlgorithmError("beta must be in the interval [0, 1]")
|
| 248 |
+
|
| 249 |
+
# Initialize query vectors
|
| 250 |
+
p0 = np.array([top_personalization.get(n, 0) for n in top], dtype=float)
|
| 251 |
+
u0 = np.array([bottom_personalization.get(n, 0) for n in bottom], dtype=float)
|
| 252 |
+
|
| 253 |
+
# Construct degree normalized biadjacency matrix `S` and its transpose
|
| 254 |
+
W = nx.bipartite.biadjacency_matrix(G, bottom, top, weight=weight, dtype=float)
|
| 255 |
+
p_degrees = W.sum(axis=0, dtype=float)
|
| 256 |
+
# Handle case where the node is disconnected - avoids warning
|
| 257 |
+
p_degrees[p_degrees == 0] = 1.0
|
| 258 |
+
D_p = sp.sparse.dia_array(
|
| 259 |
+
([1.0 / np.sqrt(p_degrees)], [0]),
|
| 260 |
+
shape=(top_count, top_count),
|
| 261 |
+
dtype=float,
|
| 262 |
+
)
|
| 263 |
+
u_degrees = W.sum(axis=1, dtype=float)
|
| 264 |
+
u_degrees[u_degrees == 0] = 1.0
|
| 265 |
+
D_u = sp.sparse.dia_array(
|
| 266 |
+
([1.0 / np.sqrt(u_degrees)], [0]),
|
| 267 |
+
shape=(bottom_count, bottom_count),
|
| 268 |
+
dtype=float,
|
| 269 |
+
)
|
| 270 |
+
S = D_u.tocsr() @ W @ D_p.tocsr()
|
| 271 |
+
S_T = S.T
|
| 272 |
+
|
| 273 |
+
# Initialize birank vectors for iteration
|
| 274 |
+
p = np.ones(top_count, dtype=float) / top_count
|
| 275 |
+
u = beta * (S @ p) + (1 - beta) * u0
|
| 276 |
+
|
| 277 |
+
# Iterate until convergence
|
| 278 |
+
for _ in range(max_iter):
|
| 279 |
+
p_last = p
|
| 280 |
+
u_last = u
|
| 281 |
+
p = alpha * (S_T @ u) + (1 - alpha) * p0
|
| 282 |
+
u = beta * (S @ p) + (1 - beta) * u0
|
| 283 |
+
|
| 284 |
+
# Continue iterating if the error (absolute if less than 1, relative otherwise)
|
| 285 |
+
# is above the tolerance threshold for either p or u
|
| 286 |
+
err_u = np.absolute((u_last - u) / np.maximum(1.0, u_last)).sum()
|
| 287 |
+
if err_u >= len(u) * tol:
|
| 288 |
+
continue
|
| 289 |
+
err_p = np.absolute((p_last - p) / np.maximum(1.0, p_last)).sum()
|
| 290 |
+
if err_p >= len(p) * tol:
|
| 291 |
+
continue
|
| 292 |
+
|
| 293 |
+
# Handle edge case where if both alpha and beta are 1, scale is
|
| 294 |
+
# indeterminate, so normalization is required to return consistent results
|
| 295 |
+
if alpha == 1 and beta == 1:
|
| 296 |
+
p = p / np.linalg.norm(p, 1)
|
| 297 |
+
u = u / np.linalg.norm(u, 1)
|
| 298 |
+
|
| 299 |
+
# If both error thresholds pass, return a single dictionary mapping
|
| 300 |
+
# nodes to their scores
|
| 301 |
+
return dict(
|
| 302 |
+
zip(itertools.chain(top, bottom), map(float, itertools.chain(p, u)))
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
# If we reach this point, we have not converged
|
| 306 |
+
raise nx.PowerIterationFailedConvergence(max_iter)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _clean_personalization_dict(personalization):
|
| 310 |
+
"""Filter out zero values from the personalization dictionary,
|
| 311 |
+
handle case where None is passed, ensure values are non-negative."""
|
| 312 |
+
if personalization is None:
|
| 313 |
+
return {}
|
| 314 |
+
if any(value < 0 for value in personalization.values()):
|
| 315 |
+
raise nx.NetworkXAlgorithmError("Personalization values must be non-negative.")
|
| 316 |
+
return {node: value for node, value in personalization.items() if value != 0}
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/matching.py
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This module uses material from the Wikipedia article Hopcroft--Karp algorithm
|
| 2 |
+
# <https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm>, accessed on
|
| 3 |
+
# January 3, 2015, which is released under the Creative Commons
|
| 4 |
+
# Attribution-Share-Alike License 3.0
|
| 5 |
+
# <http://creativecommons.org/licenses/by-sa/3.0/>. That article includes
|
| 6 |
+
# pseudocode, which has been translated into the corresponding Python code.
|
| 7 |
+
#
|
| 8 |
+
# Portions of this module use code from David Eppstein's Python Algorithms and
|
| 9 |
+
# Data Structures (PADS) library, which is dedicated to the public domain (for
|
| 10 |
+
# proof, see <http://www.ics.uci.edu/~eppstein/PADS/ABOUT-PADS.txt>).
|
| 11 |
+
"""Provides functions for computing maximum cardinality matchings and minimum
|
| 12 |
+
weight full matchings in a bipartite graph.
|
| 13 |
+
|
| 14 |
+
If you don't care about the particular implementation of the maximum matching
|
| 15 |
+
algorithm, simply use the :func:`maximum_matching`. If you do care, you can
|
| 16 |
+
import one of the named maximum matching algorithms directly.
|
| 17 |
+
|
| 18 |
+
For example, to find a maximum matching in the complete bipartite graph with
|
| 19 |
+
two vertices on the left and three vertices on the right:
|
| 20 |
+
|
| 21 |
+
>>> G = nx.complete_bipartite_graph(2, 3)
|
| 22 |
+
>>> left, right = nx.bipartite.sets(G)
|
| 23 |
+
>>> list(left)
|
| 24 |
+
[0, 1]
|
| 25 |
+
>>> list(right)
|
| 26 |
+
[2, 3, 4]
|
| 27 |
+
>>> nx.bipartite.maximum_matching(G)
|
| 28 |
+
{0: 2, 1: 3, 2: 0, 3: 1}
|
| 29 |
+
|
| 30 |
+
The dictionary returned by :func:`maximum_matching` includes a mapping for
|
| 31 |
+
vertices in both the left and right vertex sets.
|
| 32 |
+
|
| 33 |
+
Similarly, :func:`minimum_weight_full_matching` produces, for a complete
|
| 34 |
+
weighted bipartite graph, a matching whose cardinality is the cardinality of
|
| 35 |
+
the smaller of the two partitions, and for which the sum of the weights of the
|
| 36 |
+
edges included in the matching is minimal.
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
import collections
|
| 41 |
+
import itertools
|
| 42 |
+
|
| 43 |
+
import networkx as nx
|
| 44 |
+
from networkx.algorithms.bipartite import sets as bipartite_sets
|
| 45 |
+
from networkx.algorithms.bipartite.matrix import biadjacency_matrix
|
| 46 |
+
|
| 47 |
+
__all__ = [
|
| 48 |
+
"maximum_matching",
|
| 49 |
+
"hopcroft_karp_matching",
|
| 50 |
+
"eppstein_matching",
|
| 51 |
+
"to_vertex_cover",
|
| 52 |
+
"minimum_weight_full_matching",
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
INFINITY = float("inf")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@nx._dispatchable
|
| 59 |
+
def hopcroft_karp_matching(G, top_nodes=None):
|
| 60 |
+
"""Returns the maximum cardinality matching of the bipartite graph `G`.
|
| 61 |
+
|
| 62 |
+
A matching is a set of edges that do not share any nodes. A maximum
|
| 63 |
+
cardinality matching is a matching with the most edges possible. It
|
| 64 |
+
is not always unique. Finding a matching in a bipartite graph can be
|
| 65 |
+
treated as a networkx flow problem.
|
| 66 |
+
|
| 67 |
+
The functions ``hopcroft_karp_matching`` and ``maximum_matching``
|
| 68 |
+
are aliases of the same function.
|
| 69 |
+
|
| 70 |
+
Parameters
|
| 71 |
+
----------
|
| 72 |
+
G : NetworkX graph
|
| 73 |
+
|
| 74 |
+
Undirected bipartite graph
|
| 75 |
+
|
| 76 |
+
top_nodes : container of nodes
|
| 77 |
+
|
| 78 |
+
Container with all nodes in one bipartite node set. If not supplied
|
| 79 |
+
it will be computed. But if more than one solution exists an exception
|
| 80 |
+
will be raised.
|
| 81 |
+
|
| 82 |
+
Returns
|
| 83 |
+
-------
|
| 84 |
+
matches : dictionary
|
| 85 |
+
|
| 86 |
+
The matching is returned as a dictionary, `matches`, such that
|
| 87 |
+
``matches[v] == w`` if node `v` is matched to node `w`. Unmatched
|
| 88 |
+
nodes do not occur as a key in `matches`.
|
| 89 |
+
|
| 90 |
+
Raises
|
| 91 |
+
------
|
| 92 |
+
AmbiguousSolution
|
| 93 |
+
Raised if the input bipartite graph is disconnected and no container
|
| 94 |
+
with all nodes in one bipartite set is provided. When determining
|
| 95 |
+
the nodes in each bipartite set more than one valid solution is
|
| 96 |
+
possible if the input graph is disconnected.
|
| 97 |
+
|
| 98 |
+
Notes
|
| 99 |
+
-----
|
| 100 |
+
This function is implemented with the `Hopcroft--Karp matching algorithm
|
| 101 |
+
<https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm>`_ for
|
| 102 |
+
bipartite graphs.
|
| 103 |
+
|
| 104 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 105 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 106 |
+
|
| 107 |
+
See Also
|
| 108 |
+
--------
|
| 109 |
+
maximum_matching
|
| 110 |
+
hopcroft_karp_matching
|
| 111 |
+
eppstein_matching
|
| 112 |
+
|
| 113 |
+
References
|
| 114 |
+
----------
|
| 115 |
+
.. [1] John E. Hopcroft and Richard M. Karp. "An n^{5 / 2} Algorithm for
|
| 116 |
+
Maximum Matchings in Bipartite Graphs" In: **SIAM Journal of Computing**
|
| 117 |
+
2.4 (1973), pp. 225--231. <https://doi.org/10.1137/0202019>.
|
| 118 |
+
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
# First we define some auxiliary search functions.
|
| 122 |
+
#
|
| 123 |
+
# If you are a human reading these auxiliary search functions, the "global"
|
| 124 |
+
# variables `leftmatches`, `rightmatches`, `distances`, etc. are defined
|
| 125 |
+
# below the functions, so that they are initialized close to the initial
|
| 126 |
+
# invocation of the search functions.
|
| 127 |
+
def breadth_first_search():
|
| 128 |
+
for v in left:
|
| 129 |
+
if leftmatches[v] is None:
|
| 130 |
+
distances[v] = 0
|
| 131 |
+
queue.append(v)
|
| 132 |
+
else:
|
| 133 |
+
distances[v] = INFINITY
|
| 134 |
+
distances[None] = INFINITY
|
| 135 |
+
while queue:
|
| 136 |
+
v = queue.popleft()
|
| 137 |
+
if distances[v] < distances[None]:
|
| 138 |
+
for u in G[v]:
|
| 139 |
+
if distances[rightmatches[u]] is INFINITY:
|
| 140 |
+
distances[rightmatches[u]] = distances[v] + 1
|
| 141 |
+
queue.append(rightmatches[u])
|
| 142 |
+
return distances[None] is not INFINITY
|
| 143 |
+
|
| 144 |
+
def depth_first_search(v):
|
| 145 |
+
if v is not None:
|
| 146 |
+
for u in G[v]:
|
| 147 |
+
if distances[rightmatches[u]] == distances[v] + 1:
|
| 148 |
+
if depth_first_search(rightmatches[u]):
|
| 149 |
+
rightmatches[u] = v
|
| 150 |
+
leftmatches[v] = u
|
| 151 |
+
return True
|
| 152 |
+
distances[v] = INFINITY
|
| 153 |
+
return False
|
| 154 |
+
return True
|
| 155 |
+
|
| 156 |
+
# Initialize the "global" variables that maintain state during the search.
|
| 157 |
+
left, right = bipartite_sets(G, top_nodes)
|
| 158 |
+
leftmatches = dict.fromkeys(left)
|
| 159 |
+
rightmatches = dict.fromkeys(right)
|
| 160 |
+
distances = {}
|
| 161 |
+
queue = collections.deque()
|
| 162 |
+
|
| 163 |
+
# Implementation note: this counter is incremented as pairs are matched but
|
| 164 |
+
# it is currently not used elsewhere in the computation.
|
| 165 |
+
num_matched_pairs = 0
|
| 166 |
+
while breadth_first_search():
|
| 167 |
+
for v in left:
|
| 168 |
+
if leftmatches[v] is None:
|
| 169 |
+
if depth_first_search(v):
|
| 170 |
+
num_matched_pairs += 1
|
| 171 |
+
|
| 172 |
+
# Strip the entries matched to `None`.
|
| 173 |
+
leftmatches = {k: v for k, v in leftmatches.items() if v is not None}
|
| 174 |
+
rightmatches = {k: v for k, v in rightmatches.items() if v is not None}
|
| 175 |
+
|
| 176 |
+
# At this point, the left matches and the right matches are inverses of one
|
| 177 |
+
# another. In other words,
|
| 178 |
+
#
|
| 179 |
+
# leftmatches == {v, k for k, v in rightmatches.items()}
|
| 180 |
+
#
|
| 181 |
+
# Finally, we combine both the left matches and right matches.
|
| 182 |
+
return dict(itertools.chain(leftmatches.items(), rightmatches.items()))
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@nx._dispatchable
|
| 186 |
+
def eppstein_matching(G, top_nodes=None):
|
| 187 |
+
"""Returns the maximum cardinality matching of the bipartite graph `G`.
|
| 188 |
+
|
| 189 |
+
Parameters
|
| 190 |
+
----------
|
| 191 |
+
G : NetworkX graph
|
| 192 |
+
|
| 193 |
+
Undirected bipartite graph
|
| 194 |
+
|
| 195 |
+
top_nodes : container
|
| 196 |
+
|
| 197 |
+
Container with all nodes in one bipartite node set. If not supplied
|
| 198 |
+
it will be computed. But if more than one solution exists an exception
|
| 199 |
+
will be raised.
|
| 200 |
+
|
| 201 |
+
Returns
|
| 202 |
+
-------
|
| 203 |
+
matches : dictionary
|
| 204 |
+
|
| 205 |
+
The matching is returned as a dictionary, `matching`, such that
|
| 206 |
+
``matching[v] == w`` if node `v` is matched to node `w`. Unmatched
|
| 207 |
+
nodes do not occur as a key in `matching`.
|
| 208 |
+
|
| 209 |
+
Raises
|
| 210 |
+
------
|
| 211 |
+
AmbiguousSolution
|
| 212 |
+
Raised if the input bipartite graph is disconnected and no container
|
| 213 |
+
with all nodes in one bipartite set is provided. When determining
|
| 214 |
+
the nodes in each bipartite set more than one valid solution is
|
| 215 |
+
possible if the input graph is disconnected.
|
| 216 |
+
|
| 217 |
+
Notes
|
| 218 |
+
-----
|
| 219 |
+
This function is implemented with David Eppstein's version of the algorithm
|
| 220 |
+
Hopcroft--Karp algorithm (see :func:`hopcroft_karp_matching`), which
|
| 221 |
+
originally appeared in the `Python Algorithms and Data Structures library
|
| 222 |
+
(PADS) <http://www.ics.uci.edu/~eppstein/PADS/ABOUT-PADS.txt>`_.
|
| 223 |
+
|
| 224 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 225 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 226 |
+
|
| 227 |
+
See Also
|
| 228 |
+
--------
|
| 229 |
+
|
| 230 |
+
hopcroft_karp_matching
|
| 231 |
+
|
| 232 |
+
"""
|
| 233 |
+
# Due to its original implementation, a directed graph is needed
|
| 234 |
+
# so that the two sets of bipartite nodes can be distinguished
|
| 235 |
+
left, right = bipartite_sets(G, top_nodes)
|
| 236 |
+
G = nx.DiGraph(G.edges(left))
|
| 237 |
+
# initialize greedy matching (redundant, but faster than full search)
|
| 238 |
+
matching = {}
|
| 239 |
+
for u in G:
|
| 240 |
+
for v in G[u]:
|
| 241 |
+
if v not in matching:
|
| 242 |
+
matching[v] = u
|
| 243 |
+
break
|
| 244 |
+
while True:
|
| 245 |
+
# structure residual graph into layers
|
| 246 |
+
# pred[u] gives the neighbor in the previous layer for u in U
|
| 247 |
+
# preds[v] gives a list of neighbors in the previous layer for v in V
|
| 248 |
+
# unmatched gives a list of unmatched vertices in final layer of V,
|
| 249 |
+
# and is also used as a flag value for pred[u] when u is in the first
|
| 250 |
+
# layer
|
| 251 |
+
preds = {}
|
| 252 |
+
unmatched = []
|
| 253 |
+
pred = dict.fromkeys(G, unmatched)
|
| 254 |
+
for v in matching:
|
| 255 |
+
del pred[matching[v]]
|
| 256 |
+
layer = list(pred)
|
| 257 |
+
|
| 258 |
+
# repeatedly extend layering structure by another pair of layers
|
| 259 |
+
while layer and not unmatched:
|
| 260 |
+
newLayer = {}
|
| 261 |
+
for u in layer:
|
| 262 |
+
for v in G[u]:
|
| 263 |
+
if v not in preds:
|
| 264 |
+
newLayer.setdefault(v, []).append(u)
|
| 265 |
+
layer = []
|
| 266 |
+
for v in newLayer:
|
| 267 |
+
preds[v] = newLayer[v]
|
| 268 |
+
if v in matching:
|
| 269 |
+
layer.append(matching[v])
|
| 270 |
+
pred[matching[v]] = v
|
| 271 |
+
else:
|
| 272 |
+
unmatched.append(v)
|
| 273 |
+
|
| 274 |
+
# did we finish layering without finding any alternating paths?
|
| 275 |
+
if not unmatched:
|
| 276 |
+
# TODO - The lines between --- were unused and were thus commented
|
| 277 |
+
# out. This whole commented chunk should be reviewed to determine
|
| 278 |
+
# whether it should be built upon or completely removed.
|
| 279 |
+
# ---
|
| 280 |
+
# unlayered = {}
|
| 281 |
+
# for u in G:
|
| 282 |
+
# # TODO Why is extra inner loop necessary?
|
| 283 |
+
# for v in G[u]:
|
| 284 |
+
# if v not in preds:
|
| 285 |
+
# unlayered[v] = None
|
| 286 |
+
# ---
|
| 287 |
+
# TODO Originally, this function returned a three-tuple:
|
| 288 |
+
#
|
| 289 |
+
# return (matching, list(pred), list(unlayered))
|
| 290 |
+
#
|
| 291 |
+
# For some reason, the documentation for this function
|
| 292 |
+
# indicated that the second and third elements of the returned
|
| 293 |
+
# three-tuple would be the vertices in the left and right vertex
|
| 294 |
+
# sets, respectively, that are also in the maximum independent set.
|
| 295 |
+
# However, what I think the author meant was that the second
|
| 296 |
+
# element is the list of vertices that were unmatched and the third
|
| 297 |
+
# element was the list of vertices that were matched. Since that
|
| 298 |
+
# seems to be the case, they don't really need to be returned,
|
| 299 |
+
# since that information can be inferred from the matching
|
| 300 |
+
# dictionary.
|
| 301 |
+
|
| 302 |
+
# All the matched nodes must be a key in the dictionary
|
| 303 |
+
for key in matching.copy():
|
| 304 |
+
matching[matching[key]] = key
|
| 305 |
+
return matching
|
| 306 |
+
|
| 307 |
+
# recursively search backward through layers to find alternating paths
|
| 308 |
+
# recursion returns true if found path, false otherwise
|
| 309 |
+
def recurse(v):
|
| 310 |
+
if v in preds:
|
| 311 |
+
L = preds.pop(v)
|
| 312 |
+
for u in L:
|
| 313 |
+
if u in pred:
|
| 314 |
+
pu = pred.pop(u)
|
| 315 |
+
if pu is unmatched or recurse(pu):
|
| 316 |
+
matching[v] = u
|
| 317 |
+
return True
|
| 318 |
+
return False
|
| 319 |
+
|
| 320 |
+
for v in unmatched:
|
| 321 |
+
recurse(v)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def _is_connected_by_alternating_path(G, v, matched_edges, unmatched_edges, targets):
|
| 325 |
+
"""Returns True if and only if the vertex `v` is connected to one of
|
| 326 |
+
the target vertices by an alternating path in `G`.
|
| 327 |
+
|
| 328 |
+
An *alternating path* is a path in which every other edge is in the
|
| 329 |
+
specified maximum matching (and the remaining edges in the path are not in
|
| 330 |
+
the matching). An alternating path may have matched edges in the even
|
| 331 |
+
positions or in the odd positions, as long as the edges alternate between
|
| 332 |
+
'matched' and 'unmatched'.
|
| 333 |
+
|
| 334 |
+
`G` is an undirected bipartite NetworkX graph.
|
| 335 |
+
|
| 336 |
+
`v` is a vertex in `G`.
|
| 337 |
+
|
| 338 |
+
`matched_edges` is a set of edges present in a maximum matching in `G`.
|
| 339 |
+
|
| 340 |
+
`unmatched_edges` is a set of edges not present in a maximum
|
| 341 |
+
matching in `G`.
|
| 342 |
+
|
| 343 |
+
`targets` is a set of vertices.
|
| 344 |
+
|
| 345 |
+
"""
|
| 346 |
+
|
| 347 |
+
def _alternating_dfs(u, along_matched=True):
|
| 348 |
+
"""Returns True if and only if `u` is connected to one of the
|
| 349 |
+
targets by an alternating path.
|
| 350 |
+
|
| 351 |
+
`u` is a vertex in the graph `G`.
|
| 352 |
+
|
| 353 |
+
If `along_matched` is True, this step of the depth-first search
|
| 354 |
+
will continue only through edges in the given matching. Otherwise, it
|
| 355 |
+
will continue only through edges *not* in the given matching.
|
| 356 |
+
|
| 357 |
+
"""
|
| 358 |
+
visited = set()
|
| 359 |
+
# Follow matched edges when depth is even,
|
| 360 |
+
# and follow unmatched edges when depth is odd.
|
| 361 |
+
initial_depth = 0 if along_matched else 1
|
| 362 |
+
stack = [(u, iter(G[u]), initial_depth)]
|
| 363 |
+
while stack:
|
| 364 |
+
parent, children, depth = stack[-1]
|
| 365 |
+
valid_edges = matched_edges if depth % 2 else unmatched_edges
|
| 366 |
+
try:
|
| 367 |
+
child = next(children)
|
| 368 |
+
if child not in visited:
|
| 369 |
+
if (parent, child) in valid_edges or (child, parent) in valid_edges:
|
| 370 |
+
if child in targets:
|
| 371 |
+
return True
|
| 372 |
+
visited.add(child)
|
| 373 |
+
stack.append((child, iter(G[child]), depth + 1))
|
| 374 |
+
except StopIteration:
|
| 375 |
+
stack.pop()
|
| 376 |
+
return False
|
| 377 |
+
|
| 378 |
+
# Check for alternating paths starting with edges in the matching, then
|
| 379 |
+
# check for alternating paths starting with edges not in the
|
| 380 |
+
# matching.
|
| 381 |
+
return _alternating_dfs(v, along_matched=True) or _alternating_dfs(
|
| 382 |
+
v, along_matched=False
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def _connected_by_alternating_paths(G, matching, targets):
|
| 387 |
+
"""Returns the set of vertices that are connected to one of the target
|
| 388 |
+
vertices by an alternating path in `G` or are themselves a target.
|
| 389 |
+
|
| 390 |
+
An *alternating path* is a path in which every other edge is in the
|
| 391 |
+
specified maximum matching (and the remaining edges in the path are not in
|
| 392 |
+
the matching). An alternating path may have matched edges in the even
|
| 393 |
+
positions or in the odd positions, as long as the edges alternate between
|
| 394 |
+
'matched' and 'unmatched'.
|
| 395 |
+
|
| 396 |
+
`G` is an undirected bipartite NetworkX graph.
|
| 397 |
+
|
| 398 |
+
`matching` is a dictionary representing a maximum matching in `G`, as
|
| 399 |
+
returned by, for example, :func:`maximum_matching`.
|
| 400 |
+
|
| 401 |
+
`targets` is a set of vertices.
|
| 402 |
+
|
| 403 |
+
"""
|
| 404 |
+
# Get the set of matched edges and the set of unmatched edges. Only include
|
| 405 |
+
# one version of each undirected edge (for example, include edge (1, 2) but
|
| 406 |
+
# not edge (2, 1)). Using frozensets as an intermediary step we do not
|
| 407 |
+
# require nodes to be orderable.
|
| 408 |
+
edge_sets = {frozenset((u, v)) for u, v in matching.items()}
|
| 409 |
+
matched_edges = {tuple(edge) for edge in edge_sets}
|
| 410 |
+
unmatched_edges = {
|
| 411 |
+
(u, v) for (u, v) in G.edges() if frozenset((u, v)) not in edge_sets
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
return {
|
| 415 |
+
v
|
| 416 |
+
for v in G
|
| 417 |
+
if v in targets
|
| 418 |
+
or _is_connected_by_alternating_path(
|
| 419 |
+
G, v, matched_edges, unmatched_edges, targets
|
| 420 |
+
)
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
@nx._dispatchable
|
| 425 |
+
def to_vertex_cover(G, matching, top_nodes=None):
|
| 426 |
+
"""Returns the minimum vertex cover corresponding to the given maximum
|
| 427 |
+
matching of the bipartite graph `G`.
|
| 428 |
+
|
| 429 |
+
Parameters
|
| 430 |
+
----------
|
| 431 |
+
G : NetworkX graph
|
| 432 |
+
|
| 433 |
+
Undirected bipartite graph
|
| 434 |
+
|
| 435 |
+
matching : dictionary
|
| 436 |
+
|
| 437 |
+
A dictionary whose keys are vertices in `G` and whose values are the
|
| 438 |
+
distinct neighbors comprising the maximum matching for `G`, as returned
|
| 439 |
+
by, for example, :func:`maximum_matching`. The dictionary *must*
|
| 440 |
+
represent the maximum matching.
|
| 441 |
+
|
| 442 |
+
top_nodes : container
|
| 443 |
+
|
| 444 |
+
Container with all nodes in one bipartite node set. If not supplied
|
| 445 |
+
it will be computed. But if more than one solution exists an exception
|
| 446 |
+
will be raised.
|
| 447 |
+
|
| 448 |
+
Returns
|
| 449 |
+
-------
|
| 450 |
+
vertex_cover : :class:`set`
|
| 451 |
+
|
| 452 |
+
The minimum vertex cover in `G`.
|
| 453 |
+
|
| 454 |
+
Raises
|
| 455 |
+
------
|
| 456 |
+
AmbiguousSolution
|
| 457 |
+
Raised if the input bipartite graph is disconnected and no container
|
| 458 |
+
with all nodes in one bipartite set is provided. When determining
|
| 459 |
+
the nodes in each bipartite set more than one valid solution is
|
| 460 |
+
possible if the input graph is disconnected.
|
| 461 |
+
|
| 462 |
+
Notes
|
| 463 |
+
-----
|
| 464 |
+
This function is implemented using the procedure guaranteed by `Konig's
|
| 465 |
+
theorem
|
| 466 |
+
<https://en.wikipedia.org/wiki/K%C3%B6nig%27s_theorem_%28graph_theory%29>`_,
|
| 467 |
+
which proves an equivalence between a maximum matching and a minimum vertex
|
| 468 |
+
cover in bipartite graphs.
|
| 469 |
+
|
| 470 |
+
Since a minimum vertex cover is the complement of a maximum independent set
|
| 471 |
+
for any graph, one can compute the maximum independent set of a bipartite
|
| 472 |
+
graph this way:
|
| 473 |
+
|
| 474 |
+
>>> G = nx.complete_bipartite_graph(2, 3)
|
| 475 |
+
>>> matching = nx.bipartite.maximum_matching(G)
|
| 476 |
+
>>> vertex_cover = nx.bipartite.to_vertex_cover(G, matching)
|
| 477 |
+
>>> independent_set = set(G) - vertex_cover
|
| 478 |
+
>>> print(list(independent_set))
|
| 479 |
+
[2, 3, 4]
|
| 480 |
+
|
| 481 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 482 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 483 |
+
|
| 484 |
+
"""
|
| 485 |
+
# This is a Python implementation of the algorithm described at
|
| 486 |
+
# <https://en.wikipedia.org/wiki/K%C3%B6nig%27s_theorem_%28graph_theory%29#Proof>.
|
| 487 |
+
L, R = bipartite_sets(G, top_nodes)
|
| 488 |
+
# Let U be the set of unmatched vertices in the left vertex set.
|
| 489 |
+
unmatched_vertices = set(G) - set(matching)
|
| 490 |
+
U = unmatched_vertices & L
|
| 491 |
+
# Let Z be the set of vertices that are either in U or are connected to U
|
| 492 |
+
# by alternating paths.
|
| 493 |
+
Z = _connected_by_alternating_paths(G, matching, U)
|
| 494 |
+
# At this point, every edge either has a right endpoint in Z or a left
|
| 495 |
+
# endpoint not in Z. This gives us the vertex cover.
|
| 496 |
+
return (L - Z) | (R & Z)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
#: Returns the maximum cardinality matching in the given bipartite graph.
|
| 500 |
+
#:
|
| 501 |
+
#: This function is simply an alias for :func:`hopcroft_karp_matching`.
|
| 502 |
+
maximum_matching = hopcroft_karp_matching
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 506 |
+
def minimum_weight_full_matching(G, top_nodes=None, weight="weight"):
|
| 507 |
+
r"""Returns a minimum weight full matching of the bipartite graph `G`.
|
| 508 |
+
|
| 509 |
+
Let :math:`G = ((U, V), E)` be a weighted bipartite graph with real weights
|
| 510 |
+
:math:`w : E \to \mathbb{R}`. This function then produces a matching
|
| 511 |
+
:math:`M \subseteq E` with cardinality
|
| 512 |
+
|
| 513 |
+
.. math::
|
| 514 |
+
\lvert M \rvert = \min(\lvert U \rvert, \lvert V \rvert),
|
| 515 |
+
|
| 516 |
+
which minimizes the sum of the weights of the edges included in the
|
| 517 |
+
matching, :math:`\sum_{e \in M} w(e)`, or raises an error if no such
|
| 518 |
+
matching exists.
|
| 519 |
+
|
| 520 |
+
When :math:`\lvert U \rvert = \lvert V \rvert`, this is commonly
|
| 521 |
+
referred to as a perfect matching; here, since we allow
|
| 522 |
+
:math:`\lvert U \rvert` and :math:`\lvert V \rvert` to differ, we
|
| 523 |
+
follow Karp [1]_ and refer to the matching as *full*.
|
| 524 |
+
|
| 525 |
+
Parameters
|
| 526 |
+
----------
|
| 527 |
+
G : NetworkX graph
|
| 528 |
+
|
| 529 |
+
Undirected bipartite graph
|
| 530 |
+
|
| 531 |
+
top_nodes : container
|
| 532 |
+
|
| 533 |
+
Container with all nodes in one bipartite node set. If not supplied
|
| 534 |
+
it will be computed.
|
| 535 |
+
|
| 536 |
+
weight : string, optional (default='weight')
|
| 537 |
+
|
| 538 |
+
The edge data key used to provide each value in the matrix.
|
| 539 |
+
If None, then each edge has weight 1.
|
| 540 |
+
|
| 541 |
+
Returns
|
| 542 |
+
-------
|
| 543 |
+
matches : dictionary
|
| 544 |
+
|
| 545 |
+
The matching is returned as a dictionary, `matches`, such that
|
| 546 |
+
``matches[v] == w`` if node `v` is matched to node `w`. Unmatched
|
| 547 |
+
nodes do not occur as a key in `matches`.
|
| 548 |
+
|
| 549 |
+
Raises
|
| 550 |
+
------
|
| 551 |
+
ValueError
|
| 552 |
+
Raised if no full matching exists.
|
| 553 |
+
|
| 554 |
+
ImportError
|
| 555 |
+
Raised if SciPy is not available.
|
| 556 |
+
|
| 557 |
+
Notes
|
| 558 |
+
-----
|
| 559 |
+
The problem of determining a minimum weight full matching is also known as
|
| 560 |
+
the rectangular linear assignment problem. This implementation defers the
|
| 561 |
+
calculation of the assignment to SciPy.
|
| 562 |
+
|
| 563 |
+
References
|
| 564 |
+
----------
|
| 565 |
+
.. [1] Richard Manning Karp:
|
| 566 |
+
An algorithm to Solve the m x n Assignment Problem in Expected Time
|
| 567 |
+
O(mn log n).
|
| 568 |
+
Networks, 10(2):143–152, 1980.
|
| 569 |
+
|
| 570 |
+
"""
|
| 571 |
+
import numpy as np
|
| 572 |
+
import scipy as sp
|
| 573 |
+
|
| 574 |
+
left, right = nx.bipartite.sets(G, top_nodes)
|
| 575 |
+
U = list(left)
|
| 576 |
+
V = list(right)
|
| 577 |
+
# We explicitly create the biadjacency matrix having infinities
|
| 578 |
+
# where edges are missing (as opposed to zeros, which is what one would
|
| 579 |
+
# get by using toarray on the sparse matrix).
|
| 580 |
+
weights_sparse = biadjacency_matrix(
|
| 581 |
+
G, row_order=U, column_order=V, weight=weight, format="coo"
|
| 582 |
+
)
|
| 583 |
+
weights = np.full(weights_sparse.shape, np.inf)
|
| 584 |
+
weights[weights_sparse.row, weights_sparse.col] = weights_sparse.data
|
| 585 |
+
left_matches = sp.optimize.linear_sum_assignment(weights)
|
| 586 |
+
d = {U[u]: V[v] for u, v in zip(*left_matches)}
|
| 587 |
+
# d will contain the matching from edges in left to right; we need to
|
| 588 |
+
# add the ones from right to left as well.
|
| 589 |
+
d.update({v: u for u, v in d.items()})
|
| 590 |
+
return d
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/matrix.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
====================
|
| 3 |
+
Biadjacency matrices
|
| 4 |
+
====================
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import itertools
|
| 8 |
+
|
| 9 |
+
import networkx as nx
|
| 10 |
+
from networkx.convert_matrix import _generate_weighted_edges
|
| 11 |
+
|
| 12 |
+
__all__ = ["biadjacency_matrix", "from_biadjacency_matrix"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 16 |
+
def biadjacency_matrix(
|
| 17 |
+
G, row_order, column_order=None, dtype=None, weight="weight", format="csr"
|
| 18 |
+
):
|
| 19 |
+
r"""Returns the biadjacency matrix of the bipartite graph G.
|
| 20 |
+
|
| 21 |
+
Let `G = (U, V, E)` be a bipartite graph with node sets
|
| 22 |
+
`U = u_{1},...,u_{r}` and `V = v_{1},...,v_{s}`. The biadjacency
|
| 23 |
+
matrix [1]_ is the `r` x `s` matrix `B` in which `b_{i,j} = 1`
|
| 24 |
+
if, and only if, `(u_i, v_j) \in E`. If the parameter `weight` is
|
| 25 |
+
not `None` and matches the name of an edge attribute, its value is
|
| 26 |
+
used instead of 1.
|
| 27 |
+
|
| 28 |
+
Parameters
|
| 29 |
+
----------
|
| 30 |
+
G : graph
|
| 31 |
+
A NetworkX graph
|
| 32 |
+
|
| 33 |
+
row_order : list of nodes
|
| 34 |
+
The rows of the matrix are ordered according to the list of nodes.
|
| 35 |
+
|
| 36 |
+
column_order : list, optional
|
| 37 |
+
The columns of the matrix are ordered according to the list of nodes.
|
| 38 |
+
If column_order is None, then the ordering of columns is arbitrary.
|
| 39 |
+
|
| 40 |
+
dtype : NumPy data-type, optional
|
| 41 |
+
A valid NumPy dtype used to initialize the array. If None, then the
|
| 42 |
+
NumPy default is used.
|
| 43 |
+
|
| 44 |
+
weight : string or None, optional (default='weight')
|
| 45 |
+
The edge data key used to provide each value in the matrix.
|
| 46 |
+
If None, then each edge has weight 1.
|
| 47 |
+
|
| 48 |
+
format : str in {'dense', 'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'}
|
| 49 |
+
The type of the matrix to be returned (default 'csr'). For
|
| 50 |
+
some algorithms different implementations of sparse matrices
|
| 51 |
+
can perform better. See [2]_ for details.
|
| 52 |
+
|
| 53 |
+
Returns
|
| 54 |
+
-------
|
| 55 |
+
M : SciPy sparse array
|
| 56 |
+
Biadjacency matrix representation of the bipartite graph G.
|
| 57 |
+
|
| 58 |
+
Notes
|
| 59 |
+
-----
|
| 60 |
+
No attempt is made to check that the input graph is bipartite.
|
| 61 |
+
|
| 62 |
+
For directed bipartite graphs only successors are considered as neighbors.
|
| 63 |
+
To obtain an adjacency matrix with ones (or weight values) for both
|
| 64 |
+
predecessors and successors you have to generate two biadjacency matrices
|
| 65 |
+
where the rows of one of them are the columns of the other, and then add
|
| 66 |
+
one to the transpose of the other.
|
| 67 |
+
|
| 68 |
+
See Also
|
| 69 |
+
--------
|
| 70 |
+
adjacency_matrix
|
| 71 |
+
from_biadjacency_matrix
|
| 72 |
+
|
| 73 |
+
References
|
| 74 |
+
----------
|
| 75 |
+
.. [1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
|
| 76 |
+
.. [2] Scipy Dev. References, "Sparse Matrices",
|
| 77 |
+
https://docs.scipy.org/doc/scipy/reference/sparse.html
|
| 78 |
+
"""
|
| 79 |
+
import scipy as sp
|
| 80 |
+
|
| 81 |
+
nlen = len(row_order)
|
| 82 |
+
if nlen == 0:
|
| 83 |
+
raise nx.NetworkXError("row_order is empty list")
|
| 84 |
+
if len(row_order) != len(set(row_order)):
|
| 85 |
+
msg = "Ambiguous ordering: `row_order` contained duplicates."
|
| 86 |
+
raise nx.NetworkXError(msg)
|
| 87 |
+
if column_order is None:
|
| 88 |
+
column_order = list(set(G) - set(row_order))
|
| 89 |
+
mlen = len(column_order)
|
| 90 |
+
if len(column_order) != len(set(column_order)):
|
| 91 |
+
msg = "Ambiguous ordering: `column_order` contained duplicates."
|
| 92 |
+
raise nx.NetworkXError(msg)
|
| 93 |
+
|
| 94 |
+
row_index = dict(zip(row_order, itertools.count()))
|
| 95 |
+
col_index = dict(zip(column_order, itertools.count()))
|
| 96 |
+
|
| 97 |
+
if G.number_of_edges() == 0:
|
| 98 |
+
row, col, data = [], [], []
|
| 99 |
+
else:
|
| 100 |
+
row, col, data = zip(
|
| 101 |
+
*(
|
| 102 |
+
(row_index[u], col_index[v], d.get(weight, 1))
|
| 103 |
+
for u, v, d in G.edges(row_order, data=True)
|
| 104 |
+
if u in row_index and v in col_index
|
| 105 |
+
)
|
| 106 |
+
)
|
| 107 |
+
A = sp.sparse.coo_array((data, (row, col)), shape=(nlen, mlen), dtype=dtype)
|
| 108 |
+
try:
|
| 109 |
+
return A.asformat(format)
|
| 110 |
+
except ValueError as err:
|
| 111 |
+
raise nx.NetworkXError(f"Unknown sparse array format: {format}") from err
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 115 |
+
def from_biadjacency_matrix(A, create_using=None, edge_attribute="weight"):
|
| 116 |
+
r"""Creates a new bipartite graph from a biadjacency matrix given as a
|
| 117 |
+
SciPy sparse array.
|
| 118 |
+
|
| 119 |
+
Parameters
|
| 120 |
+
----------
|
| 121 |
+
A: scipy sparse array
|
| 122 |
+
A biadjacency matrix representation of a graph
|
| 123 |
+
|
| 124 |
+
create_using: NetworkX graph
|
| 125 |
+
Use specified graph for result. The default is Graph()
|
| 126 |
+
|
| 127 |
+
edge_attribute: string
|
| 128 |
+
Name of edge attribute to store matrix numeric value. The data will
|
| 129 |
+
have the same type as the matrix entry (int, float, (real,imag)).
|
| 130 |
+
|
| 131 |
+
Notes
|
| 132 |
+
-----
|
| 133 |
+
The nodes are labeled with the attribute `bipartite` set to an integer
|
| 134 |
+
0 or 1 representing membership in part 0 or part 1 of the bipartite graph.
|
| 135 |
+
|
| 136 |
+
If `create_using` is an instance of :class:`networkx.MultiGraph` or
|
| 137 |
+
:class:`networkx.MultiDiGraph` and the entries of `A` are of
|
| 138 |
+
type :class:`int`, then this function returns a multigraph (of the same
|
| 139 |
+
type as `create_using`) with parallel edges. In this case, `edge_attribute`
|
| 140 |
+
will be ignored.
|
| 141 |
+
|
| 142 |
+
See Also
|
| 143 |
+
--------
|
| 144 |
+
biadjacency_matrix
|
| 145 |
+
from_numpy_array
|
| 146 |
+
|
| 147 |
+
References
|
| 148 |
+
----------
|
| 149 |
+
[1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
|
| 150 |
+
"""
|
| 151 |
+
G = nx.empty_graph(0, create_using)
|
| 152 |
+
n, m = A.shape
|
| 153 |
+
# Make sure we get even the isolated nodes of the graph.
|
| 154 |
+
G.add_nodes_from(range(n), bipartite=0)
|
| 155 |
+
G.add_nodes_from(range(n, n + m), bipartite=1)
|
| 156 |
+
# Create an iterable over (u, v, w) triples and for each triple, add an
|
| 157 |
+
# edge from u to v with weight w.
|
| 158 |
+
triples = ((u, n + v, d) for (u, v, d) in _generate_weighted_edges(A))
|
| 159 |
+
# If the entries in the adjacency matrix are integers and the graph is a
|
| 160 |
+
# multigraph, then create parallel edges, each with weight 1, for each
|
| 161 |
+
# entry in the adjacency matrix. Otherwise, create one edge for each
|
| 162 |
+
# positive entry in the adjacency matrix and set the weight of that edge to
|
| 163 |
+
# be the entry in the matrix.
|
| 164 |
+
if A.dtype.kind in ("i", "u") and G.is_multigraph():
|
| 165 |
+
chain = itertools.chain.from_iterable
|
| 166 |
+
triples = chain(((u, v, 1) for d in range(w)) for (u, v, w) in triples)
|
| 167 |
+
G.add_weighted_edges_from(triples, weight=edge_attribute)
|
| 168 |
+
return G
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/projection.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One-mode (unipartite) projections of bipartite graphs."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.exception import NetworkXAlgorithmError
|
| 5 |
+
from networkx.utils import not_implemented_for
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"projected_graph",
|
| 9 |
+
"weighted_projected_graph",
|
| 10 |
+
"collaboration_weighted_projected_graph",
|
| 11 |
+
"overlap_weighted_projected_graph",
|
| 12 |
+
"generic_weighted_projected_graph",
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@nx._dispatchable(
|
| 17 |
+
graphs="B", preserve_node_attrs=True, preserve_graph_attrs=True, returns_graph=True
|
| 18 |
+
)
|
| 19 |
+
def projected_graph(B, nodes, multigraph=False):
|
| 20 |
+
r"""Returns the projection of B onto one of its node sets.
|
| 21 |
+
|
| 22 |
+
Returns the graph G that is the projection of the bipartite graph B
|
| 23 |
+
onto the specified nodes. They retain their attributes and are connected
|
| 24 |
+
in G if they have a common neighbor in B.
|
| 25 |
+
|
| 26 |
+
Parameters
|
| 27 |
+
----------
|
| 28 |
+
B : NetworkX graph
|
| 29 |
+
The input graph should be bipartite.
|
| 30 |
+
|
| 31 |
+
nodes : list or iterable
|
| 32 |
+
Nodes to project onto (the "bottom" nodes).
|
| 33 |
+
|
| 34 |
+
multigraph: bool (default=False)
|
| 35 |
+
If True return a multigraph where the multiple edges represent multiple
|
| 36 |
+
shared neighbors. They edge key in the multigraph is assigned to the
|
| 37 |
+
label of the neighbor.
|
| 38 |
+
|
| 39 |
+
Returns
|
| 40 |
+
-------
|
| 41 |
+
Graph : NetworkX graph or multigraph
|
| 42 |
+
A graph that is the projection onto the given nodes.
|
| 43 |
+
|
| 44 |
+
Examples
|
| 45 |
+
--------
|
| 46 |
+
>>> from networkx.algorithms import bipartite
|
| 47 |
+
>>> B = nx.path_graph(4)
|
| 48 |
+
>>> G = bipartite.projected_graph(B, [1, 3])
|
| 49 |
+
>>> list(G)
|
| 50 |
+
[1, 3]
|
| 51 |
+
>>> list(G.edges())
|
| 52 |
+
[(1, 3)]
|
| 53 |
+
|
| 54 |
+
If nodes `a`, and `b` are connected through both nodes 1 and 2 then
|
| 55 |
+
building a multigraph results in two edges in the projection onto
|
| 56 |
+
[`a`, `b`]:
|
| 57 |
+
|
| 58 |
+
>>> B = nx.Graph()
|
| 59 |
+
>>> B.add_edges_from([("a", 1), ("b", 1), ("a", 2), ("b", 2)])
|
| 60 |
+
>>> G = bipartite.projected_graph(B, ["a", "b"], multigraph=True)
|
| 61 |
+
>>> print([sorted((u, v)) for u, v in G.edges()])
|
| 62 |
+
[['a', 'b'], ['a', 'b']]
|
| 63 |
+
|
| 64 |
+
Notes
|
| 65 |
+
-----
|
| 66 |
+
No attempt is made to verify that the input graph B is bipartite.
|
| 67 |
+
Returns a simple graph that is the projection of the bipartite graph B
|
| 68 |
+
onto the set of nodes given in list nodes. If multigraph=True then
|
| 69 |
+
a multigraph is returned with an edge for every shared neighbor.
|
| 70 |
+
|
| 71 |
+
Directed graphs are allowed as input. The output will also then
|
| 72 |
+
be a directed graph with edges if there is a directed path between
|
| 73 |
+
the nodes.
|
| 74 |
+
|
| 75 |
+
The graph and node properties are (shallow) copied to the projected graph.
|
| 76 |
+
|
| 77 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 78 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 79 |
+
|
| 80 |
+
See Also
|
| 81 |
+
--------
|
| 82 |
+
is_bipartite,
|
| 83 |
+
is_bipartite_node_set,
|
| 84 |
+
sets,
|
| 85 |
+
weighted_projected_graph,
|
| 86 |
+
collaboration_weighted_projected_graph,
|
| 87 |
+
overlap_weighted_projected_graph,
|
| 88 |
+
generic_weighted_projected_graph
|
| 89 |
+
"""
|
| 90 |
+
if B.is_multigraph():
|
| 91 |
+
raise nx.NetworkXError("not defined for multigraphs")
|
| 92 |
+
if B.is_directed():
|
| 93 |
+
directed = True
|
| 94 |
+
if multigraph:
|
| 95 |
+
G = nx.MultiDiGraph()
|
| 96 |
+
else:
|
| 97 |
+
G = nx.DiGraph()
|
| 98 |
+
else:
|
| 99 |
+
directed = False
|
| 100 |
+
if multigraph:
|
| 101 |
+
G = nx.MultiGraph()
|
| 102 |
+
else:
|
| 103 |
+
G = nx.Graph()
|
| 104 |
+
G.graph.update(B.graph)
|
| 105 |
+
G.add_nodes_from((n, B.nodes[n]) for n in nodes)
|
| 106 |
+
for u in nodes:
|
| 107 |
+
nbrs2 = {v for nbr in B[u] for v in B[nbr] if v != u}
|
| 108 |
+
if multigraph:
|
| 109 |
+
for n in nbrs2:
|
| 110 |
+
if directed:
|
| 111 |
+
links = set(B[u]) & set(B.pred[n])
|
| 112 |
+
else:
|
| 113 |
+
links = set(B[u]) & set(B[n])
|
| 114 |
+
for l in links:
|
| 115 |
+
if not G.has_edge(u, n, l):
|
| 116 |
+
G.add_edge(u, n, key=l)
|
| 117 |
+
else:
|
| 118 |
+
G.add_edges_from((u, n) for n in nbrs2)
|
| 119 |
+
return G
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@not_implemented_for("multigraph")
|
| 123 |
+
@nx._dispatchable(graphs="B", returns_graph=True)
|
| 124 |
+
def weighted_projected_graph(B, nodes, ratio=False):
|
| 125 |
+
r"""Returns a weighted projection of B onto one of its node sets.
|
| 126 |
+
|
| 127 |
+
The weighted projected graph is the projection of the bipartite
|
| 128 |
+
network B onto the specified nodes with weights representing the
|
| 129 |
+
number of shared neighbors or the ratio between actual shared
|
| 130 |
+
neighbors and possible shared neighbors if ``ratio is True`` [1]_.
|
| 131 |
+
The nodes retain their attributes and are connected in the resulting
|
| 132 |
+
graph if they have an edge to a common node in the original graph.
|
| 133 |
+
|
| 134 |
+
Parameters
|
| 135 |
+
----------
|
| 136 |
+
B : NetworkX graph
|
| 137 |
+
The input graph should be bipartite.
|
| 138 |
+
|
| 139 |
+
nodes : list or iterable
|
| 140 |
+
Distinct nodes to project onto (the "bottom" nodes).
|
| 141 |
+
|
| 142 |
+
ratio: Bool (default=False)
|
| 143 |
+
If True, edge weight is the ratio between actual shared neighbors
|
| 144 |
+
and maximum possible shared neighbors (i.e., the size of the other
|
| 145 |
+
node set). If False, edges weight is the number of shared neighbors.
|
| 146 |
+
|
| 147 |
+
Returns
|
| 148 |
+
-------
|
| 149 |
+
Graph : NetworkX graph
|
| 150 |
+
A graph that is the projection onto the given nodes.
|
| 151 |
+
|
| 152 |
+
Examples
|
| 153 |
+
--------
|
| 154 |
+
>>> from networkx.algorithms import bipartite
|
| 155 |
+
>>> B = nx.path_graph(4)
|
| 156 |
+
>>> G = bipartite.weighted_projected_graph(B, [1, 3])
|
| 157 |
+
>>> list(G)
|
| 158 |
+
[1, 3]
|
| 159 |
+
>>> list(G.edges(data=True))
|
| 160 |
+
[(1, 3, {'weight': 1})]
|
| 161 |
+
>>> G = bipartite.weighted_projected_graph(B, [1, 3], ratio=True)
|
| 162 |
+
>>> list(G.edges(data=True))
|
| 163 |
+
[(1, 3, {'weight': 0.5})]
|
| 164 |
+
|
| 165 |
+
Notes
|
| 166 |
+
-----
|
| 167 |
+
No attempt is made to verify that the input graph B is bipartite, or that
|
| 168 |
+
the input nodes are distinct. However, if the length of the input nodes is
|
| 169 |
+
greater than or equal to the nodes in the graph B, an exception is raised.
|
| 170 |
+
If the nodes are not distinct but don't raise this error, the output weights
|
| 171 |
+
will be incorrect.
|
| 172 |
+
The graph and node properties are (shallow) copied to the projected graph.
|
| 173 |
+
|
| 174 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 175 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 176 |
+
|
| 177 |
+
See Also
|
| 178 |
+
--------
|
| 179 |
+
is_bipartite,
|
| 180 |
+
is_bipartite_node_set,
|
| 181 |
+
sets,
|
| 182 |
+
collaboration_weighted_projected_graph,
|
| 183 |
+
overlap_weighted_projected_graph,
|
| 184 |
+
generic_weighted_projected_graph
|
| 185 |
+
projected_graph
|
| 186 |
+
|
| 187 |
+
References
|
| 188 |
+
----------
|
| 189 |
+
.. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation
|
| 190 |
+
Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook
|
| 191 |
+
of Social Network Analysis. Sage Publications.
|
| 192 |
+
"""
|
| 193 |
+
if B.is_directed():
|
| 194 |
+
pred = B.pred
|
| 195 |
+
G = nx.DiGraph()
|
| 196 |
+
else:
|
| 197 |
+
pred = B.adj
|
| 198 |
+
G = nx.Graph()
|
| 199 |
+
G.graph.update(B.graph)
|
| 200 |
+
G.add_nodes_from((n, B.nodes[n]) for n in nodes)
|
| 201 |
+
n_top = len(B) - len(nodes)
|
| 202 |
+
|
| 203 |
+
if n_top < 1:
|
| 204 |
+
raise NetworkXAlgorithmError(
|
| 205 |
+
f"the size of the nodes to project onto ({len(nodes)}) is >= the graph size ({len(B)}).\n"
|
| 206 |
+
"They are either not a valid bipartite partition or contain duplicates"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
for u in nodes:
|
| 210 |
+
unbrs = set(B[u])
|
| 211 |
+
nbrs2 = {n for nbr in unbrs for n in B[nbr]} - {u}
|
| 212 |
+
for v in nbrs2:
|
| 213 |
+
vnbrs = set(pred[v])
|
| 214 |
+
common = unbrs & vnbrs
|
| 215 |
+
if not ratio:
|
| 216 |
+
weight = len(common)
|
| 217 |
+
else:
|
| 218 |
+
weight = len(common) / n_top
|
| 219 |
+
G.add_edge(u, v, weight=weight)
|
| 220 |
+
return G
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
@not_implemented_for("multigraph")
|
| 224 |
+
@nx._dispatchable(graphs="B", returns_graph=True)
|
| 225 |
+
def collaboration_weighted_projected_graph(B, nodes):
|
| 226 |
+
r"""Newman's weighted projection of B onto one of its node sets.
|
| 227 |
+
|
| 228 |
+
The collaboration weighted projection is the projection of the
|
| 229 |
+
bipartite network B onto the specified nodes with weights assigned
|
| 230 |
+
using Newman's collaboration model [1]_:
|
| 231 |
+
|
| 232 |
+
.. math::
|
| 233 |
+
|
| 234 |
+
w_{u, v} = \sum_k \frac{\delta_{u}^{k} \delta_{v}^{k}}{d_k - 1}
|
| 235 |
+
|
| 236 |
+
where `u` and `v` are nodes from the bottom bipartite node set,
|
| 237 |
+
and `k` is a node of the top node set.
|
| 238 |
+
The value `d_k` is the degree of node `k` in the bipartite
|
| 239 |
+
network and `\delta_{u}^{k}` is 1 if node `u` is
|
| 240 |
+
linked to node `k` in the original bipartite graph or 0 otherwise.
|
| 241 |
+
|
| 242 |
+
The nodes retain their attributes and are connected in the resulting
|
| 243 |
+
graph if have an edge to a common node in the original bipartite
|
| 244 |
+
graph.
|
| 245 |
+
|
| 246 |
+
Parameters
|
| 247 |
+
----------
|
| 248 |
+
B : NetworkX graph
|
| 249 |
+
The input graph should be bipartite.
|
| 250 |
+
|
| 251 |
+
nodes : list or iterable
|
| 252 |
+
Nodes to project onto (the "bottom" nodes).
|
| 253 |
+
|
| 254 |
+
Returns
|
| 255 |
+
-------
|
| 256 |
+
Graph : NetworkX graph
|
| 257 |
+
A graph that is the projection onto the given nodes.
|
| 258 |
+
|
| 259 |
+
Examples
|
| 260 |
+
--------
|
| 261 |
+
>>> from networkx.algorithms import bipartite
|
| 262 |
+
>>> B = nx.path_graph(5)
|
| 263 |
+
>>> B.add_edge(1, 5)
|
| 264 |
+
>>> G = bipartite.collaboration_weighted_projected_graph(B, [0, 2, 4, 5])
|
| 265 |
+
>>> list(G)
|
| 266 |
+
[0, 2, 4, 5]
|
| 267 |
+
>>> for edge in sorted(G.edges(data=True)):
|
| 268 |
+
... print(edge)
|
| 269 |
+
(0, 2, {'weight': 0.5})
|
| 270 |
+
(0, 5, {'weight': 0.5})
|
| 271 |
+
(2, 4, {'weight': 1.0})
|
| 272 |
+
(2, 5, {'weight': 0.5})
|
| 273 |
+
|
| 274 |
+
Notes
|
| 275 |
+
-----
|
| 276 |
+
No attempt is made to verify that the input graph B is bipartite.
|
| 277 |
+
The graph and node properties are (shallow) copied to the projected graph.
|
| 278 |
+
|
| 279 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 280 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 281 |
+
|
| 282 |
+
See Also
|
| 283 |
+
--------
|
| 284 |
+
is_bipartite,
|
| 285 |
+
is_bipartite_node_set,
|
| 286 |
+
sets,
|
| 287 |
+
weighted_projected_graph,
|
| 288 |
+
overlap_weighted_projected_graph,
|
| 289 |
+
generic_weighted_projected_graph,
|
| 290 |
+
projected_graph
|
| 291 |
+
|
| 292 |
+
References
|
| 293 |
+
----------
|
| 294 |
+
.. [1] Scientific collaboration networks: II.
|
| 295 |
+
Shortest paths, weighted networks, and centrality,
|
| 296 |
+
M. E. J. Newman, Phys. Rev. E 64, 016132 (2001).
|
| 297 |
+
"""
|
| 298 |
+
if B.is_directed():
|
| 299 |
+
pred = B.pred
|
| 300 |
+
G = nx.DiGraph()
|
| 301 |
+
else:
|
| 302 |
+
pred = B.adj
|
| 303 |
+
G = nx.Graph()
|
| 304 |
+
G.graph.update(B.graph)
|
| 305 |
+
G.add_nodes_from((n, B.nodes[n]) for n in nodes)
|
| 306 |
+
for u in nodes:
|
| 307 |
+
unbrs = set(B[u])
|
| 308 |
+
nbrs2 = {n for nbr in unbrs for n in B[nbr] if n != u}
|
| 309 |
+
for v in nbrs2:
|
| 310 |
+
vnbrs = set(pred[v])
|
| 311 |
+
common_degree = (len(B[n]) for n in unbrs & vnbrs)
|
| 312 |
+
weight = sum(1.0 / (deg - 1) for deg in common_degree if deg > 1)
|
| 313 |
+
G.add_edge(u, v, weight=weight)
|
| 314 |
+
return G
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@not_implemented_for("multigraph")
|
| 318 |
+
@nx._dispatchable(graphs="B", returns_graph=True)
|
| 319 |
+
def overlap_weighted_projected_graph(B, nodes, jaccard=True):
|
| 320 |
+
r"""Overlap weighted projection of B onto one of its node sets.
|
| 321 |
+
|
| 322 |
+
The overlap weighted projection is the projection of the bipartite
|
| 323 |
+
network B onto the specified nodes with weights representing
|
| 324 |
+
the Jaccard index between the neighborhoods of the two nodes in the
|
| 325 |
+
original bipartite network [1]_:
|
| 326 |
+
|
| 327 |
+
.. math::
|
| 328 |
+
|
| 329 |
+
w_{v, u} = \frac{|N(u) \cap N(v)|}{|N(u) \cup N(v)|}
|
| 330 |
+
|
| 331 |
+
or if the parameter 'jaccard' is False, the fraction of common
|
| 332 |
+
neighbors by minimum of both nodes degree in the original
|
| 333 |
+
bipartite graph [1]_:
|
| 334 |
+
|
| 335 |
+
.. math::
|
| 336 |
+
|
| 337 |
+
w_{v, u} = \frac{|N(u) \cap N(v)|}{min(|N(u)|, |N(v)|)}
|
| 338 |
+
|
| 339 |
+
The nodes retain their attributes and are connected in the resulting
|
| 340 |
+
graph if have an edge to a common node in the original bipartite graph.
|
| 341 |
+
|
| 342 |
+
Parameters
|
| 343 |
+
----------
|
| 344 |
+
B : NetworkX graph
|
| 345 |
+
The input graph should be bipartite.
|
| 346 |
+
|
| 347 |
+
nodes : list or iterable
|
| 348 |
+
Nodes to project onto (the "bottom" nodes).
|
| 349 |
+
|
| 350 |
+
jaccard: Bool (default=True)
|
| 351 |
+
|
| 352 |
+
Returns
|
| 353 |
+
-------
|
| 354 |
+
Graph : NetworkX graph
|
| 355 |
+
A graph that is the projection onto the given nodes.
|
| 356 |
+
|
| 357 |
+
Examples
|
| 358 |
+
--------
|
| 359 |
+
>>> from networkx.algorithms import bipartite
|
| 360 |
+
>>> B = nx.path_graph(5)
|
| 361 |
+
>>> nodes = [0, 2, 4]
|
| 362 |
+
>>> G = bipartite.overlap_weighted_projected_graph(B, nodes)
|
| 363 |
+
>>> list(G)
|
| 364 |
+
[0, 2, 4]
|
| 365 |
+
>>> list(G.edges(data=True))
|
| 366 |
+
[(0, 2, {'weight': 0.5}), (2, 4, {'weight': 0.5})]
|
| 367 |
+
>>> G = bipartite.overlap_weighted_projected_graph(B, nodes, jaccard=False)
|
| 368 |
+
>>> list(G.edges(data=True))
|
| 369 |
+
[(0, 2, {'weight': 1.0}), (2, 4, {'weight': 1.0})]
|
| 370 |
+
|
| 371 |
+
Notes
|
| 372 |
+
-----
|
| 373 |
+
No attempt is made to verify that the input graph B is bipartite.
|
| 374 |
+
The graph and node properties are (shallow) copied to the projected graph.
|
| 375 |
+
|
| 376 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 377 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 378 |
+
|
| 379 |
+
See Also
|
| 380 |
+
--------
|
| 381 |
+
is_bipartite,
|
| 382 |
+
is_bipartite_node_set,
|
| 383 |
+
sets,
|
| 384 |
+
weighted_projected_graph,
|
| 385 |
+
collaboration_weighted_projected_graph,
|
| 386 |
+
generic_weighted_projected_graph,
|
| 387 |
+
projected_graph
|
| 388 |
+
|
| 389 |
+
References
|
| 390 |
+
----------
|
| 391 |
+
.. [1] Borgatti, S.P. and Halgin, D. In press. Analyzing Affiliation
|
| 392 |
+
Networks. In Carrington, P. and Scott, J. (eds) The Sage Handbook
|
| 393 |
+
of Social Network Analysis. Sage Publications.
|
| 394 |
+
|
| 395 |
+
"""
|
| 396 |
+
if B.is_directed():
|
| 397 |
+
pred = B.pred
|
| 398 |
+
G = nx.DiGraph()
|
| 399 |
+
else:
|
| 400 |
+
pred = B.adj
|
| 401 |
+
G = nx.Graph()
|
| 402 |
+
G.graph.update(B.graph)
|
| 403 |
+
G.add_nodes_from((n, B.nodes[n]) for n in nodes)
|
| 404 |
+
for u in nodes:
|
| 405 |
+
unbrs = set(B[u])
|
| 406 |
+
nbrs2 = {n for nbr in unbrs for n in B[nbr]} - {u}
|
| 407 |
+
for v in nbrs2:
|
| 408 |
+
vnbrs = set(pred[v])
|
| 409 |
+
if jaccard:
|
| 410 |
+
wt = len(unbrs & vnbrs) / len(unbrs | vnbrs)
|
| 411 |
+
else:
|
| 412 |
+
wt = len(unbrs & vnbrs) / min(len(unbrs), len(vnbrs))
|
| 413 |
+
G.add_edge(u, v, weight=wt)
|
| 414 |
+
return G
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
@not_implemented_for("multigraph")
|
| 418 |
+
@nx._dispatchable(graphs="B", preserve_all_attrs=True, returns_graph=True)
|
| 419 |
+
def generic_weighted_projected_graph(B, nodes, weight_function=None):
|
| 420 |
+
r"""Weighted projection of B with a user-specified weight function.
|
| 421 |
+
|
| 422 |
+
The bipartite network B is projected on to the specified nodes
|
| 423 |
+
with weights computed by a user-specified function. This function
|
| 424 |
+
must accept as a parameter the neighborhood sets of two nodes and
|
| 425 |
+
return an integer or a float.
|
| 426 |
+
|
| 427 |
+
The nodes retain their attributes and are connected in the resulting graph
|
| 428 |
+
if they have an edge to a common node in the original graph.
|
| 429 |
+
|
| 430 |
+
Parameters
|
| 431 |
+
----------
|
| 432 |
+
B : NetworkX graph
|
| 433 |
+
The input graph should be bipartite.
|
| 434 |
+
|
| 435 |
+
nodes : list or iterable
|
| 436 |
+
Nodes to project onto (the "bottom" nodes).
|
| 437 |
+
|
| 438 |
+
weight_function : function
|
| 439 |
+
This function must accept as parameters the same input graph
|
| 440 |
+
that this function, and two nodes; and return an integer or a float.
|
| 441 |
+
The default function computes the number of shared neighbors.
|
| 442 |
+
|
| 443 |
+
Returns
|
| 444 |
+
-------
|
| 445 |
+
Graph : NetworkX graph
|
| 446 |
+
A graph that is the projection onto the given nodes.
|
| 447 |
+
|
| 448 |
+
Examples
|
| 449 |
+
--------
|
| 450 |
+
>>> from networkx.algorithms import bipartite
|
| 451 |
+
>>> # Define some custom weight functions
|
| 452 |
+
>>> def jaccard(G, u, v):
|
| 453 |
+
... unbrs = set(G[u])
|
| 454 |
+
... vnbrs = set(G[v])
|
| 455 |
+
... return float(len(unbrs & vnbrs)) / len(unbrs | vnbrs)
|
| 456 |
+
>>> def my_weight(G, u, v, weight="weight"):
|
| 457 |
+
... w = 0
|
| 458 |
+
... for nbr in set(G[u]) & set(G[v]):
|
| 459 |
+
... w += G[u][nbr].get(weight, 1) + G[v][nbr].get(weight, 1)
|
| 460 |
+
... return w
|
| 461 |
+
>>> # A complete bipartite graph with 4 nodes and 4 edges
|
| 462 |
+
>>> B = nx.complete_bipartite_graph(2, 2)
|
| 463 |
+
>>> # Add some arbitrary weight to the edges
|
| 464 |
+
>>> for i, (u, v) in enumerate(B.edges()):
|
| 465 |
+
... B.edges[u, v]["weight"] = i + 1
|
| 466 |
+
>>> for edge in B.edges(data=True):
|
| 467 |
+
... print(edge)
|
| 468 |
+
(0, 2, {'weight': 1})
|
| 469 |
+
(0, 3, {'weight': 2})
|
| 470 |
+
(1, 2, {'weight': 3})
|
| 471 |
+
(1, 3, {'weight': 4})
|
| 472 |
+
>>> # By default, the weight is the number of shared neighbors
|
| 473 |
+
>>> G = bipartite.generic_weighted_projected_graph(B, [0, 1])
|
| 474 |
+
>>> print(list(G.edges(data=True)))
|
| 475 |
+
[(0, 1, {'weight': 2})]
|
| 476 |
+
>>> # To specify a custom weight function use the weight_function parameter
|
| 477 |
+
>>> G = bipartite.generic_weighted_projected_graph(
|
| 478 |
+
... B, [0, 1], weight_function=jaccard
|
| 479 |
+
... )
|
| 480 |
+
>>> print(list(G.edges(data=True)))
|
| 481 |
+
[(0, 1, {'weight': 1.0})]
|
| 482 |
+
>>> G = bipartite.generic_weighted_projected_graph(
|
| 483 |
+
... B, [0, 1], weight_function=my_weight
|
| 484 |
+
... )
|
| 485 |
+
>>> print(list(G.edges(data=True)))
|
| 486 |
+
[(0, 1, {'weight': 10})]
|
| 487 |
+
|
| 488 |
+
Notes
|
| 489 |
+
-----
|
| 490 |
+
No attempt is made to verify that the input graph B is bipartite.
|
| 491 |
+
The graph and node properties are (shallow) copied to the projected graph.
|
| 492 |
+
|
| 493 |
+
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
|
| 494 |
+
for further details on how bipartite graphs are handled in NetworkX.
|
| 495 |
+
|
| 496 |
+
See Also
|
| 497 |
+
--------
|
| 498 |
+
is_bipartite,
|
| 499 |
+
is_bipartite_node_set,
|
| 500 |
+
sets,
|
| 501 |
+
weighted_projected_graph,
|
| 502 |
+
collaboration_weighted_projected_graph,
|
| 503 |
+
overlap_weighted_projected_graph,
|
| 504 |
+
projected_graph
|
| 505 |
+
|
| 506 |
+
"""
|
| 507 |
+
if B.is_directed():
|
| 508 |
+
pred = B.pred
|
| 509 |
+
G = nx.DiGraph()
|
| 510 |
+
else:
|
| 511 |
+
pred = B.adj
|
| 512 |
+
G = nx.Graph()
|
| 513 |
+
if weight_function is None:
|
| 514 |
+
|
| 515 |
+
def weight_function(G, u, v):
|
| 516 |
+
# Notice that we use set(pred[v]) for handling the directed case.
|
| 517 |
+
return len(set(G[u]) & set(pred[v]))
|
| 518 |
+
|
| 519 |
+
G.graph.update(B.graph)
|
| 520 |
+
G.add_nodes_from((n, B.nodes[n]) for n in nodes)
|
| 521 |
+
for u in nodes:
|
| 522 |
+
nbrs2 = {n for nbr in set(B[u]) for n in B[nbr]} - {u}
|
| 523 |
+
for v in nbrs2:
|
| 524 |
+
weight = weight_function(B, u, v)
|
| 525 |
+
G.add_edge(u, v, weight=weight)
|
| 526 |
+
return G
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/redundancy.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Node redundancy for bipartite graphs."""
|
| 2 |
+
|
| 3 |
+
from itertools import combinations
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx import NetworkXError
|
| 7 |
+
|
| 8 |
+
__all__ = ["node_redundancy"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@nx._dispatchable
|
| 12 |
+
def node_redundancy(G, nodes=None):
|
| 13 |
+
r"""Computes the node redundancy coefficients for the nodes in the bipartite
|
| 14 |
+
graph `G`.
|
| 15 |
+
|
| 16 |
+
The redundancy coefficient of a node `v` is the fraction of pairs of
|
| 17 |
+
neighbors of `v` that are both linked to other nodes. In a one-mode
|
| 18 |
+
projection these nodes would be linked together even if `v` were
|
| 19 |
+
not there.
|
| 20 |
+
|
| 21 |
+
More formally, for any vertex `v`, the *redundancy coefficient of `v`* is
|
| 22 |
+
defined by
|
| 23 |
+
|
| 24 |
+
.. math::
|
| 25 |
+
|
| 26 |
+
rc(v) = \frac{|\{\{u, w\} \subseteq N(v),
|
| 27 |
+
\: \exists v' \neq v,\: (v',u) \in E\:
|
| 28 |
+
\mathrm{and}\: (v',w) \in E\}|}{ \frac{|N(v)|(|N(v)|-1)}{2}},
|
| 29 |
+
|
| 30 |
+
where `N(v)` is the set of neighbors of `v` in `G`.
|
| 31 |
+
|
| 32 |
+
Parameters
|
| 33 |
+
----------
|
| 34 |
+
G : graph
|
| 35 |
+
A bipartite graph
|
| 36 |
+
|
| 37 |
+
nodes : list or iterable (optional)
|
| 38 |
+
Compute redundancy for these nodes. The default is all nodes in G.
|
| 39 |
+
|
| 40 |
+
Returns
|
| 41 |
+
-------
|
| 42 |
+
redundancy : dictionary
|
| 43 |
+
A dictionary keyed by node with the node redundancy value.
|
| 44 |
+
|
| 45 |
+
Examples
|
| 46 |
+
--------
|
| 47 |
+
Compute the redundancy coefficient of each node in a graph::
|
| 48 |
+
|
| 49 |
+
>>> from networkx.algorithms import bipartite
|
| 50 |
+
>>> G = nx.cycle_graph(4)
|
| 51 |
+
>>> rc = bipartite.node_redundancy(G)
|
| 52 |
+
>>> rc[0]
|
| 53 |
+
1.0
|
| 54 |
+
|
| 55 |
+
Compute the average redundancy for the graph::
|
| 56 |
+
|
| 57 |
+
>>> from networkx.algorithms import bipartite
|
| 58 |
+
>>> G = nx.cycle_graph(4)
|
| 59 |
+
>>> rc = bipartite.node_redundancy(G)
|
| 60 |
+
>>> sum(rc.values()) / len(G)
|
| 61 |
+
1.0
|
| 62 |
+
|
| 63 |
+
Compute the average redundancy for a set of nodes::
|
| 64 |
+
|
| 65 |
+
>>> from networkx.algorithms import bipartite
|
| 66 |
+
>>> G = nx.cycle_graph(4)
|
| 67 |
+
>>> rc = bipartite.node_redundancy(G)
|
| 68 |
+
>>> nodes = [0, 2]
|
| 69 |
+
>>> sum(rc[n] for n in nodes) / len(nodes)
|
| 70 |
+
1.0
|
| 71 |
+
|
| 72 |
+
Raises
|
| 73 |
+
------
|
| 74 |
+
NetworkXError
|
| 75 |
+
If any of the nodes in the graph (or in `nodes`, if specified) has
|
| 76 |
+
(out-)degree less than two (which would result in division by zero,
|
| 77 |
+
according to the definition of the redundancy coefficient).
|
| 78 |
+
|
| 79 |
+
References
|
| 80 |
+
----------
|
| 81 |
+
.. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
|
| 82 |
+
Basic notions for the analysis of large two-mode networks.
|
| 83 |
+
Social Networks 30(1), 31--48.
|
| 84 |
+
|
| 85 |
+
"""
|
| 86 |
+
if nodes is None:
|
| 87 |
+
nodes = G
|
| 88 |
+
if any(len(G[v]) < 2 for v in nodes):
|
| 89 |
+
raise NetworkXError(
|
| 90 |
+
"Cannot compute redundancy coefficient for a node"
|
| 91 |
+
" that has fewer than two neighbors."
|
| 92 |
+
)
|
| 93 |
+
# TODO This can be trivially parallelized.
|
| 94 |
+
return {v: _node_redundancy(G, v) for v in nodes}
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _node_redundancy(G, v):
|
| 98 |
+
"""Returns the redundancy of the node `v` in the bipartite graph `G`.
|
| 99 |
+
|
| 100 |
+
If `G` is a graph with `n` nodes, the redundancy of a node is the ratio
|
| 101 |
+
of the "overlap" of `v` to the maximum possible overlap of `v`
|
| 102 |
+
according to its degree. The overlap of `v` is the number of pairs of
|
| 103 |
+
neighbors that have mutual neighbors themselves, other than `v`.
|
| 104 |
+
|
| 105 |
+
`v` must have at least two neighbors in `G`.
|
| 106 |
+
|
| 107 |
+
"""
|
| 108 |
+
n = len(G[v])
|
| 109 |
+
overlap = sum(
|
| 110 |
+
1 for (u, w) in combinations(G[v], 2) if (set(G[u]) & set(G[w])) - {v}
|
| 111 |
+
)
|
| 112 |
+
return (2 * overlap) / (n * (n - 1))
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/bipartite/spectral.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Spectral bipartivity measure.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
__all__ = ["spectral_bipartivity"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 11 |
+
def spectral_bipartivity(G, nodes=None, weight="weight"):
|
| 12 |
+
"""Returns the spectral bipartivity.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
----------
|
| 16 |
+
G : NetworkX graph
|
| 17 |
+
|
| 18 |
+
nodes : list or container optional(default is all nodes)
|
| 19 |
+
Nodes to return value of spectral bipartivity contribution.
|
| 20 |
+
|
| 21 |
+
weight : string or None optional (default = 'weight')
|
| 22 |
+
Edge data key to use for edge weights. If None, weights set to 1.
|
| 23 |
+
|
| 24 |
+
Returns
|
| 25 |
+
-------
|
| 26 |
+
sb : float or dict
|
| 27 |
+
A single number if the keyword nodes is not specified, or
|
| 28 |
+
a dictionary keyed by node with the spectral bipartivity contribution
|
| 29 |
+
of that node as the value.
|
| 30 |
+
|
| 31 |
+
Examples
|
| 32 |
+
--------
|
| 33 |
+
>>> from networkx.algorithms import bipartite
|
| 34 |
+
>>> G = nx.path_graph(4)
|
| 35 |
+
>>> bipartite.spectral_bipartivity(G)
|
| 36 |
+
1.0
|
| 37 |
+
|
| 38 |
+
Notes
|
| 39 |
+
-----
|
| 40 |
+
This implementation uses Numpy (dense) matrices which are not efficient
|
| 41 |
+
for storing large sparse graphs.
|
| 42 |
+
|
| 43 |
+
See Also
|
| 44 |
+
--------
|
| 45 |
+
color
|
| 46 |
+
|
| 47 |
+
References
|
| 48 |
+
----------
|
| 49 |
+
.. [1] E. Estrada and J. A. Rodríguez-Velázquez, "Spectral measures of
|
| 50 |
+
bipartivity in complex networks", PhysRev E 72, 046105 (2005)
|
| 51 |
+
"""
|
| 52 |
+
import scipy as sp
|
| 53 |
+
|
| 54 |
+
nodelist = list(G) # ordering of nodes in matrix
|
| 55 |
+
A = nx.to_numpy_array(G, nodelist, weight=weight)
|
| 56 |
+
expA = sp.linalg.expm(A)
|
| 57 |
+
expmA = sp.linalg.expm(-A)
|
| 58 |
+
coshA = 0.5 * (expA + expmA)
|
| 59 |
+
if nodes is None:
|
| 60 |
+
# return single number for entire graph
|
| 61 |
+
return float(coshA.diagonal().sum() / expA.diagonal().sum())
|
| 62 |
+
else:
|
| 63 |
+
# contribution for individual nodes
|
| 64 |
+
index = dict(zip(nodelist, range(len(nodelist))))
|
| 65 |
+
sb = {}
|
| 66 |
+
for n in nodes:
|
| 67 |
+
i = index[n]
|
| 68 |
+
sb[n] = coshA.item(i, i) / expA.item(i, i)
|
| 69 |
+
return sb
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .betweenness import *
|
| 2 |
+
from .betweenness_subset import *
|
| 3 |
+
from .closeness import *
|
| 4 |
+
from .current_flow_betweenness import *
|
| 5 |
+
from .current_flow_betweenness_subset import *
|
| 6 |
+
from .current_flow_closeness import *
|
| 7 |
+
from .degree_alg import *
|
| 8 |
+
from .dispersion import *
|
| 9 |
+
from .eigenvector import *
|
| 10 |
+
from .group import *
|
| 11 |
+
from .harmonic import *
|
| 12 |
+
from .katz import *
|
| 13 |
+
from .load import *
|
| 14 |
+
from .percolation import *
|
| 15 |
+
from .reaching import *
|
| 16 |
+
from .second_order import *
|
| 17 |
+
from .subgraph_alg import *
|
| 18 |
+
from .trophic import *
|
| 19 |
+
from .voterank_alg import *
|
| 20 |
+
from .laplacian import *
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/betweenness.py
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Betweenness centrality measures."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from collections import deque
|
| 5 |
+
from heapq import heappop, heappush
|
| 6 |
+
from itertools import count
|
| 7 |
+
|
| 8 |
+
import networkx as nx
|
| 9 |
+
from networkx.algorithms.shortest_paths.weighted import _weight_function
|
| 10 |
+
from networkx.utils import py_random_state
|
| 11 |
+
from networkx.utils.decorators import not_implemented_for
|
| 12 |
+
|
| 13 |
+
__all__ = ["betweenness_centrality", "edge_betweenness_centrality"]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@py_random_state(5)
|
| 17 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 18 |
+
def betweenness_centrality(
|
| 19 |
+
G, k=None, normalized=True, weight=None, endpoints=False, seed=None
|
| 20 |
+
):
|
| 21 |
+
r"""Compute the shortest-path betweenness centrality for nodes.
|
| 22 |
+
|
| 23 |
+
Betweenness centrality of a node $v$ is the sum of the
|
| 24 |
+
fraction of all-pairs shortest paths that pass through $v$
|
| 25 |
+
|
| 26 |
+
.. math::
|
| 27 |
+
|
| 28 |
+
c_B(v) =\sum_{s,t \in V} \frac{\sigma(s, t|v)}{\sigma(s, t)}
|
| 29 |
+
|
| 30 |
+
where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
|
| 31 |
+
shortest $(s, t)$-paths, and $\sigma(s, t|v)$ is the number of
|
| 32 |
+
those paths passing through some node $v$ other than $s, t$.
|
| 33 |
+
If $s = t$, $\sigma(s, t) = 1$, and if $v \in {s, t}$,
|
| 34 |
+
$\sigma(s, t|v) = 0$ [2]_.
|
| 35 |
+
|
| 36 |
+
Parameters
|
| 37 |
+
----------
|
| 38 |
+
G : graph
|
| 39 |
+
A NetworkX graph.
|
| 40 |
+
|
| 41 |
+
k : int, optional (default=None)
|
| 42 |
+
If k is not None use k node samples to estimate betweenness.
|
| 43 |
+
The value of k <= n where n is the number of nodes in the graph.
|
| 44 |
+
Higher values give better approximation.
|
| 45 |
+
|
| 46 |
+
normalized : bool, optional
|
| 47 |
+
If True the betweenness values are normalized by `2/((n-1)(n-2))`
|
| 48 |
+
for graphs, and `1/((n-1)(n-2))` for directed graphs where `n`
|
| 49 |
+
is the number of nodes in G.
|
| 50 |
+
|
| 51 |
+
weight : None or string, optional (default=None)
|
| 52 |
+
If None, all edge weights are considered equal.
|
| 53 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 54 |
+
Weights are used to calculate weighted shortest paths, so they are
|
| 55 |
+
interpreted as distances.
|
| 56 |
+
|
| 57 |
+
endpoints : bool, optional
|
| 58 |
+
If True include the endpoints in the shortest path counts.
|
| 59 |
+
|
| 60 |
+
seed : integer, random_state, or None (default)
|
| 61 |
+
Indicator of random number generation state.
|
| 62 |
+
See :ref:`Randomness<randomness>`.
|
| 63 |
+
Note that this is only used if k is not None.
|
| 64 |
+
|
| 65 |
+
Returns
|
| 66 |
+
-------
|
| 67 |
+
nodes : dictionary
|
| 68 |
+
Dictionary of nodes with betweenness centrality as the value.
|
| 69 |
+
|
| 70 |
+
See Also
|
| 71 |
+
--------
|
| 72 |
+
edge_betweenness_centrality
|
| 73 |
+
load_centrality
|
| 74 |
+
|
| 75 |
+
Notes
|
| 76 |
+
-----
|
| 77 |
+
The algorithm is from Ulrik Brandes [1]_.
|
| 78 |
+
See [4]_ for the original first published version and [2]_ for details on
|
| 79 |
+
algorithms for variations and related metrics.
|
| 80 |
+
|
| 81 |
+
For approximate betweenness calculations set k=#samples to use
|
| 82 |
+
k nodes ("pivots") to estimate the betweenness values. For an estimate
|
| 83 |
+
of the number of pivots needed see [3]_.
|
| 84 |
+
|
| 85 |
+
For weighted graphs the edge weights must be greater than zero.
|
| 86 |
+
Zero edge weights can produce an infinite number of equal length
|
| 87 |
+
paths between pairs of nodes.
|
| 88 |
+
|
| 89 |
+
The total number of paths between source and target is counted
|
| 90 |
+
differently for directed and undirected graphs. Directed paths
|
| 91 |
+
are easy to count. Undirected paths are tricky: should a path
|
| 92 |
+
from "u" to "v" count as 1 undirected path or as 2 directed paths?
|
| 93 |
+
|
| 94 |
+
For betweenness_centrality we report the number of undirected
|
| 95 |
+
paths when G is undirected.
|
| 96 |
+
|
| 97 |
+
For betweenness_centrality_subset the reporting is different.
|
| 98 |
+
If the source and target subsets are the same, then we want
|
| 99 |
+
to count undirected paths. But if the source and target subsets
|
| 100 |
+
differ -- for example, if sources is {0} and targets is {1},
|
| 101 |
+
then we are only counting the paths in one direction. They are
|
| 102 |
+
undirected paths but we are counting them in a directed way.
|
| 103 |
+
To count them as undirected paths, each should count as half a path.
|
| 104 |
+
|
| 105 |
+
This algorithm is not guaranteed to be correct if edge weights
|
| 106 |
+
are floating point numbers. As a workaround you can use integer
|
| 107 |
+
numbers by multiplying the relevant edge attributes by a convenient
|
| 108 |
+
constant factor (eg 100) and converting to integers.
|
| 109 |
+
|
| 110 |
+
References
|
| 111 |
+
----------
|
| 112 |
+
.. [1] Ulrik Brandes:
|
| 113 |
+
A Faster Algorithm for Betweenness Centrality.
|
| 114 |
+
Journal of Mathematical Sociology 25(2):163-177, 2001.
|
| 115 |
+
https://doi.org/10.1080/0022250X.2001.9990249
|
| 116 |
+
.. [2] Ulrik Brandes:
|
| 117 |
+
On Variants of Shortest-Path Betweenness
|
| 118 |
+
Centrality and their Generic Computation.
|
| 119 |
+
Social Networks 30(2):136-145, 2008.
|
| 120 |
+
https://doi.org/10.1016/j.socnet.2007.11.001
|
| 121 |
+
.. [3] Ulrik Brandes and Christian Pich:
|
| 122 |
+
Centrality Estimation in Large Networks.
|
| 123 |
+
International Journal of Bifurcation and Chaos 17(7):2303-2318, 2007.
|
| 124 |
+
https://dx.doi.org/10.1142/S0218127407018403
|
| 125 |
+
.. [4] Linton C. Freeman:
|
| 126 |
+
A set of measures of centrality based on betweenness.
|
| 127 |
+
Sociometry 40: 35–41, 1977
|
| 128 |
+
https://doi.org/10.2307/3033543
|
| 129 |
+
"""
|
| 130 |
+
betweenness = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
|
| 131 |
+
if k == len(G):
|
| 132 |
+
# This is done for performance; the result is the same regardless.
|
| 133 |
+
k = None
|
| 134 |
+
if k is None:
|
| 135 |
+
nodes = G
|
| 136 |
+
else:
|
| 137 |
+
nodes = seed.sample(list(G.nodes()), k)
|
| 138 |
+
for s in nodes:
|
| 139 |
+
# single source shortest paths
|
| 140 |
+
if weight is None: # use BFS
|
| 141 |
+
S, P, sigma, _ = _single_source_shortest_path_basic(G, s)
|
| 142 |
+
else: # use Dijkstra's algorithm
|
| 143 |
+
S, P, sigma, _ = _single_source_dijkstra_path_basic(G, s, weight)
|
| 144 |
+
# accumulation
|
| 145 |
+
if endpoints:
|
| 146 |
+
betweenness, _ = _accumulate_endpoints(betweenness, S, P, sigma, s)
|
| 147 |
+
else:
|
| 148 |
+
betweenness, _ = _accumulate_basic(betweenness, S, P, sigma, s)
|
| 149 |
+
# rescaling
|
| 150 |
+
betweenness = _rescale(
|
| 151 |
+
betweenness,
|
| 152 |
+
len(G),
|
| 153 |
+
normalized=normalized,
|
| 154 |
+
directed=G.is_directed(),
|
| 155 |
+
k=k,
|
| 156 |
+
endpoints=endpoints,
|
| 157 |
+
sampled_nodes=nodes,
|
| 158 |
+
)
|
| 159 |
+
return betweenness
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@py_random_state(4)
|
| 163 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 164 |
+
def edge_betweenness_centrality(G, k=None, normalized=True, weight=None, seed=None):
|
| 165 |
+
r"""Compute betweenness centrality for edges.
|
| 166 |
+
|
| 167 |
+
Betweenness centrality of an edge $e$ is the sum of the
|
| 168 |
+
fraction of all-pairs shortest paths that pass through $e$
|
| 169 |
+
|
| 170 |
+
.. math::
|
| 171 |
+
|
| 172 |
+
c_B(e) =\sum_{s,t \in V} \frac{\sigma(s, t|e)}{\sigma(s, t)}
|
| 173 |
+
|
| 174 |
+
where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
|
| 175 |
+
shortest $(s, t)$-paths, and $\sigma(s, t|e)$ is the number of
|
| 176 |
+
those paths passing through edge $e$ [2]_.
|
| 177 |
+
|
| 178 |
+
Parameters
|
| 179 |
+
----------
|
| 180 |
+
G : graph
|
| 181 |
+
A NetworkX graph.
|
| 182 |
+
|
| 183 |
+
k : int, optional (default=None)
|
| 184 |
+
If k is not None use k node samples to estimate betweenness.
|
| 185 |
+
The value of k <= n where n is the number of nodes in the graph.
|
| 186 |
+
Higher values give better approximation.
|
| 187 |
+
|
| 188 |
+
normalized : bool, optional
|
| 189 |
+
If True the betweenness values are normalized by $2/(n(n-1))$
|
| 190 |
+
for graphs, and $1/(n(n-1))$ for directed graphs where $n$
|
| 191 |
+
is the number of nodes in G.
|
| 192 |
+
|
| 193 |
+
weight : None or string, optional (default=None)
|
| 194 |
+
If None, all edge weights are considered equal.
|
| 195 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 196 |
+
Weights are used to calculate weighted shortest paths, so they are
|
| 197 |
+
interpreted as distances.
|
| 198 |
+
|
| 199 |
+
seed : integer, random_state, or None (default)
|
| 200 |
+
Indicator of random number generation state.
|
| 201 |
+
See :ref:`Randomness<randomness>`.
|
| 202 |
+
Note that this is only used if k is not None.
|
| 203 |
+
|
| 204 |
+
Returns
|
| 205 |
+
-------
|
| 206 |
+
edges : dictionary
|
| 207 |
+
Dictionary of edges with betweenness centrality as the value.
|
| 208 |
+
|
| 209 |
+
See Also
|
| 210 |
+
--------
|
| 211 |
+
betweenness_centrality
|
| 212 |
+
edge_load
|
| 213 |
+
|
| 214 |
+
Notes
|
| 215 |
+
-----
|
| 216 |
+
The algorithm is from Ulrik Brandes [1]_.
|
| 217 |
+
|
| 218 |
+
For weighted graphs the edge weights must be greater than zero.
|
| 219 |
+
Zero edge weights can produce an infinite number of equal length
|
| 220 |
+
paths between pairs of nodes.
|
| 221 |
+
|
| 222 |
+
References
|
| 223 |
+
----------
|
| 224 |
+
.. [1] A Faster Algorithm for Betweenness Centrality. Ulrik Brandes,
|
| 225 |
+
Journal of Mathematical Sociology 25(2):163-177, 2001.
|
| 226 |
+
https://doi.org/10.1080/0022250X.2001.9990249
|
| 227 |
+
.. [2] Ulrik Brandes: On Variants of Shortest-Path Betweenness
|
| 228 |
+
Centrality and their Generic Computation.
|
| 229 |
+
Social Networks 30(2):136-145, 2008.
|
| 230 |
+
https://doi.org/10.1016/j.socnet.2007.11.001
|
| 231 |
+
"""
|
| 232 |
+
betweenness = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
|
| 233 |
+
# b[e]=0 for e in G.edges()
|
| 234 |
+
betweenness.update(dict.fromkeys(G.edges(), 0.0))
|
| 235 |
+
if k is None:
|
| 236 |
+
nodes = G
|
| 237 |
+
else:
|
| 238 |
+
nodes = seed.sample(list(G.nodes()), k)
|
| 239 |
+
for s in nodes:
|
| 240 |
+
# single source shortest paths
|
| 241 |
+
if weight is None: # use BFS
|
| 242 |
+
S, P, sigma, _ = _single_source_shortest_path_basic(G, s)
|
| 243 |
+
else: # use Dijkstra's algorithm
|
| 244 |
+
S, P, sigma, _ = _single_source_dijkstra_path_basic(G, s, weight)
|
| 245 |
+
# accumulation
|
| 246 |
+
betweenness = _accumulate_edges(betweenness, S, P, sigma, s)
|
| 247 |
+
# rescaling
|
| 248 |
+
for n in G: # remove nodes to only return edges
|
| 249 |
+
del betweenness[n]
|
| 250 |
+
betweenness = _rescale_e(
|
| 251 |
+
betweenness, len(G), normalized=normalized, directed=G.is_directed()
|
| 252 |
+
)
|
| 253 |
+
if G.is_multigraph():
|
| 254 |
+
betweenness = _add_edge_keys(G, betweenness, weight=weight)
|
| 255 |
+
return betweenness
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
# helpers for betweenness centrality
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _single_source_shortest_path_basic(G, s):
|
| 262 |
+
S = []
|
| 263 |
+
P = {}
|
| 264 |
+
for v in G:
|
| 265 |
+
P[v] = []
|
| 266 |
+
sigma = dict.fromkeys(G, 0.0) # sigma[v]=0 for v in G
|
| 267 |
+
D = {}
|
| 268 |
+
sigma[s] = 1.0
|
| 269 |
+
D[s] = 0
|
| 270 |
+
Q = deque([s])
|
| 271 |
+
while Q: # use BFS to find shortest paths
|
| 272 |
+
v = Q.popleft()
|
| 273 |
+
S.append(v)
|
| 274 |
+
Dv = D[v]
|
| 275 |
+
sigmav = sigma[v]
|
| 276 |
+
for w in G[v]:
|
| 277 |
+
if w not in D:
|
| 278 |
+
Q.append(w)
|
| 279 |
+
D[w] = Dv + 1
|
| 280 |
+
if D[w] == Dv + 1: # this is a shortest path, count paths
|
| 281 |
+
sigma[w] += sigmav
|
| 282 |
+
P[w].append(v) # predecessors
|
| 283 |
+
return S, P, sigma, D
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def _single_source_dijkstra_path_basic(G, s, weight):
|
| 287 |
+
weight = _weight_function(G, weight)
|
| 288 |
+
# modified from Eppstein
|
| 289 |
+
S = []
|
| 290 |
+
P = {}
|
| 291 |
+
for v in G:
|
| 292 |
+
P[v] = []
|
| 293 |
+
sigma = dict.fromkeys(G, 0.0) # sigma[v]=0 for v in G
|
| 294 |
+
D = {}
|
| 295 |
+
sigma[s] = 1.0
|
| 296 |
+
seen = {s: 0}
|
| 297 |
+
c = count()
|
| 298 |
+
Q = [] # use Q as heap with (distance,node id) tuples
|
| 299 |
+
heappush(Q, (0, next(c), s, s))
|
| 300 |
+
while Q:
|
| 301 |
+
(dist, _, pred, v) = heappop(Q)
|
| 302 |
+
if v in D:
|
| 303 |
+
continue # already searched this node.
|
| 304 |
+
sigma[v] += sigma[pred] # count paths
|
| 305 |
+
S.append(v)
|
| 306 |
+
D[v] = dist
|
| 307 |
+
for w, edgedata in G[v].items():
|
| 308 |
+
vw_dist = dist + weight(v, w, edgedata)
|
| 309 |
+
if w not in D and (w not in seen or vw_dist < seen[w]):
|
| 310 |
+
seen[w] = vw_dist
|
| 311 |
+
heappush(Q, (vw_dist, next(c), v, w))
|
| 312 |
+
sigma[w] = 0.0
|
| 313 |
+
P[w] = [v]
|
| 314 |
+
elif vw_dist == seen[w]: # handle equal paths
|
| 315 |
+
sigma[w] += sigma[v]
|
| 316 |
+
P[w].append(v)
|
| 317 |
+
return S, P, sigma, D
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _accumulate_basic(betweenness, S, P, sigma, s):
|
| 321 |
+
delta = dict.fromkeys(S, 0)
|
| 322 |
+
while S:
|
| 323 |
+
w = S.pop()
|
| 324 |
+
coeff = (1 + delta[w]) / sigma[w]
|
| 325 |
+
for v in P[w]:
|
| 326 |
+
delta[v] += sigma[v] * coeff
|
| 327 |
+
if w != s:
|
| 328 |
+
betweenness[w] += delta[w]
|
| 329 |
+
return betweenness, delta
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _accumulate_endpoints(betweenness, S, P, sigma, s):
|
| 333 |
+
betweenness[s] += len(S) - 1
|
| 334 |
+
delta = dict.fromkeys(S, 0)
|
| 335 |
+
while S:
|
| 336 |
+
w = S.pop()
|
| 337 |
+
coeff = (1 + delta[w]) / sigma[w]
|
| 338 |
+
for v in P[w]:
|
| 339 |
+
delta[v] += sigma[v] * coeff
|
| 340 |
+
if w != s:
|
| 341 |
+
betweenness[w] += delta[w] + 1
|
| 342 |
+
return betweenness, delta
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def _accumulate_edges(betweenness, S, P, sigma, s):
|
| 346 |
+
delta = dict.fromkeys(S, 0)
|
| 347 |
+
while S:
|
| 348 |
+
w = S.pop()
|
| 349 |
+
coeff = (1 + delta[w]) / sigma[w]
|
| 350 |
+
for v in P[w]:
|
| 351 |
+
c = sigma[v] * coeff
|
| 352 |
+
if (v, w) not in betweenness:
|
| 353 |
+
betweenness[(w, v)] += c
|
| 354 |
+
else:
|
| 355 |
+
betweenness[(v, w)] += c
|
| 356 |
+
delta[v] += c
|
| 357 |
+
if w != s:
|
| 358 |
+
betweenness[w] += delta[w]
|
| 359 |
+
return betweenness
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def _rescale(betweenness, n, *, normalized, directed, k, endpoints, sampled_nodes):
|
| 363 |
+
# N is used to count the number of valid (s, t) pairs where s != t that
|
| 364 |
+
# could have a path pass through v. If endpoints is False, then v must
|
| 365 |
+
# not be the target t, hence why we subtract by 1.
|
| 366 |
+
N = n if endpoints else n - 1
|
| 367 |
+
if N < 2:
|
| 368 |
+
# No rescaling necessary: b=0 for all nodes
|
| 369 |
+
return betweenness
|
| 370 |
+
|
| 371 |
+
K_source = N if k is None else k
|
| 372 |
+
|
| 373 |
+
if k is None or endpoints:
|
| 374 |
+
# No sampling adjustment needed
|
| 375 |
+
if normalized:
|
| 376 |
+
# Divide by the number of valid (s, t) node pairs that could have
|
| 377 |
+
# a path through v where s != t.
|
| 378 |
+
scale = 1 / (K_source * (N - 1))
|
| 379 |
+
else:
|
| 380 |
+
# Scale to the full BC
|
| 381 |
+
if not directed:
|
| 382 |
+
# The non-normalized BC values are computed the same way for
|
| 383 |
+
# directed and undirected graphs: shortest paths are computed and
|
| 384 |
+
# counted for each *ordered* (s, t) pair. Undirected graphs should
|
| 385 |
+
# only count valid *unordered* node pairs {s, t}; that is, (s, t)
|
| 386 |
+
# and (t, s) should be counted only once. We correct for this here.
|
| 387 |
+
correction = 2
|
| 388 |
+
else:
|
| 389 |
+
correction = 1
|
| 390 |
+
scale = N / (K_source * correction)
|
| 391 |
+
|
| 392 |
+
if scale != 1:
|
| 393 |
+
for v in betweenness:
|
| 394 |
+
betweenness[v] *= scale
|
| 395 |
+
return betweenness
|
| 396 |
+
|
| 397 |
+
# Sampling adjustment needed when excluding endpoints when using k. In this
|
| 398 |
+
# case, we need to handle source nodes differently from non-source nodes,
|
| 399 |
+
# because source nodes can't include themselves since endpoints are excluded.
|
| 400 |
+
# Without this, k == n would be a special case that would violate the
|
| 401 |
+
# assumption that node `v` is not one of the (s, t) node pairs.
|
| 402 |
+
if normalized:
|
| 403 |
+
# NaN for undefined 0/0; there is no data for source node when k=1
|
| 404 |
+
scale_source = 1 / ((K_source - 1) * (N - 1)) if K_source > 1 else math.nan
|
| 405 |
+
scale_nonsource = 1 / (K_source * (N - 1))
|
| 406 |
+
else:
|
| 407 |
+
correction = 1 if directed else 2
|
| 408 |
+
scale_source = N / ((K_source - 1) * correction) if K_source > 1 else math.nan
|
| 409 |
+
scale_nonsource = N / (K_source * correction)
|
| 410 |
+
|
| 411 |
+
sampled_nodes = set(sampled_nodes)
|
| 412 |
+
for v in betweenness:
|
| 413 |
+
betweenness[v] *= scale_source if v in sampled_nodes else scale_nonsource
|
| 414 |
+
return betweenness
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def _rescale_e(betweenness, n, normalized, directed=False, k=None):
|
| 418 |
+
if normalized:
|
| 419 |
+
if n <= 1:
|
| 420 |
+
scale = None # no normalization b=0 for all nodes
|
| 421 |
+
else:
|
| 422 |
+
scale = 1 / (n * (n - 1))
|
| 423 |
+
else: # rescale by 2 for undirected graphs
|
| 424 |
+
if not directed:
|
| 425 |
+
scale = 0.5
|
| 426 |
+
else:
|
| 427 |
+
scale = None
|
| 428 |
+
if scale is not None:
|
| 429 |
+
if k is not None:
|
| 430 |
+
scale = scale * n / k
|
| 431 |
+
for v in betweenness:
|
| 432 |
+
betweenness[v] *= scale
|
| 433 |
+
return betweenness
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
@not_implemented_for("graph")
|
| 437 |
+
def _add_edge_keys(G, betweenness, weight=None):
|
| 438 |
+
r"""Adds the corrected betweenness centrality (BC) values for multigraphs.
|
| 439 |
+
|
| 440 |
+
Parameters
|
| 441 |
+
----------
|
| 442 |
+
G : NetworkX graph.
|
| 443 |
+
|
| 444 |
+
betweenness : dictionary
|
| 445 |
+
Dictionary mapping adjacent node tuples to betweenness centrality values.
|
| 446 |
+
|
| 447 |
+
weight : string or function
|
| 448 |
+
See `_weight_function` for details. Defaults to `None`.
|
| 449 |
+
|
| 450 |
+
Returns
|
| 451 |
+
-------
|
| 452 |
+
edges : dictionary
|
| 453 |
+
The parameter `betweenness` including edges with keys and their
|
| 454 |
+
betweenness centrality values.
|
| 455 |
+
|
| 456 |
+
The BC value is divided among edges of equal weight.
|
| 457 |
+
"""
|
| 458 |
+
_weight = _weight_function(G, weight)
|
| 459 |
+
|
| 460 |
+
edge_bc = dict.fromkeys(G.edges, 0.0)
|
| 461 |
+
for u, v in betweenness:
|
| 462 |
+
d = G[u][v]
|
| 463 |
+
wt = _weight(u, v, d)
|
| 464 |
+
keys = [k for k in d if _weight(u, v, {k: d[k]}) == wt]
|
| 465 |
+
bc = betweenness[(u, v)] / len(keys)
|
| 466 |
+
for k in keys:
|
| 467 |
+
edge_bc[(u, v, k)] = bc
|
| 468 |
+
|
| 469 |
+
return edge_bc
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/betweenness_subset.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Betweenness centrality measures for subsets of nodes."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.algorithms.centrality.betweenness import (
|
| 5 |
+
_add_edge_keys,
|
| 6 |
+
)
|
| 7 |
+
from networkx.algorithms.centrality.betweenness import (
|
| 8 |
+
_single_source_dijkstra_path_basic as dijkstra,
|
| 9 |
+
)
|
| 10 |
+
from networkx.algorithms.centrality.betweenness import (
|
| 11 |
+
_single_source_shortest_path_basic as shortest_path,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"betweenness_centrality_subset",
|
| 16 |
+
"edge_betweenness_centrality_subset",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 21 |
+
def betweenness_centrality_subset(G, sources, targets, normalized=False, weight=None):
|
| 22 |
+
r"""Compute betweenness centrality for a subset of nodes.
|
| 23 |
+
|
| 24 |
+
.. math::
|
| 25 |
+
|
| 26 |
+
c_B(v) =\sum_{s\in S, t \in T} \frac{\sigma(s, t|v)}{\sigma(s, t)}
|
| 27 |
+
|
| 28 |
+
where $S$ is the set of sources, $T$ is the set of targets,
|
| 29 |
+
$\sigma(s, t)$ is the number of shortest $(s, t)$-paths,
|
| 30 |
+
and $\sigma(s, t|v)$ is the number of those paths
|
| 31 |
+
passing through some node $v$ other than $s, t$.
|
| 32 |
+
If $s = t$, $\sigma(s, t) = 1$,
|
| 33 |
+
and if $v \in {s, t}$, $\sigma(s, t|v) = 0$ [2]_.
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
Parameters
|
| 37 |
+
----------
|
| 38 |
+
G : graph
|
| 39 |
+
A NetworkX graph.
|
| 40 |
+
|
| 41 |
+
sources: list of nodes
|
| 42 |
+
Nodes to use as sources for shortest paths in betweenness
|
| 43 |
+
|
| 44 |
+
targets: list of nodes
|
| 45 |
+
Nodes to use as targets for shortest paths in betweenness
|
| 46 |
+
|
| 47 |
+
normalized : bool, optional
|
| 48 |
+
If True the betweenness values are normalized by $2/((n-1)(n-2))$
|
| 49 |
+
for graphs, and $1/((n-1)(n-2))$ for directed graphs where $n$
|
| 50 |
+
is the number of nodes in G.
|
| 51 |
+
|
| 52 |
+
weight : None or string, optional (default=None)
|
| 53 |
+
If None, all edge weights are considered equal.
|
| 54 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 55 |
+
Weights are used to calculate weighted shortest paths, so they are
|
| 56 |
+
interpreted as distances.
|
| 57 |
+
|
| 58 |
+
Returns
|
| 59 |
+
-------
|
| 60 |
+
nodes : dictionary
|
| 61 |
+
Dictionary of nodes with betweenness centrality as the value.
|
| 62 |
+
|
| 63 |
+
See Also
|
| 64 |
+
--------
|
| 65 |
+
edge_betweenness_centrality
|
| 66 |
+
load_centrality
|
| 67 |
+
|
| 68 |
+
Notes
|
| 69 |
+
-----
|
| 70 |
+
The basic algorithm is from [1]_.
|
| 71 |
+
|
| 72 |
+
For weighted graphs the edge weights must be greater than zero.
|
| 73 |
+
Zero edge weights can produce an infinite number of equal length
|
| 74 |
+
paths between pairs of nodes.
|
| 75 |
+
|
| 76 |
+
The normalization might seem a little strange but it is
|
| 77 |
+
designed to make betweenness_centrality(G) be the same as
|
| 78 |
+
betweenness_centrality_subset(G,sources=G.nodes(),targets=G.nodes()).
|
| 79 |
+
|
| 80 |
+
The total number of paths between source and target is counted
|
| 81 |
+
differently for directed and undirected graphs. Directed paths
|
| 82 |
+
are easy to count. Undirected paths are tricky: should a path
|
| 83 |
+
from "u" to "v" count as 1 undirected path or as 2 directed paths?
|
| 84 |
+
|
| 85 |
+
For betweenness_centrality we report the number of undirected
|
| 86 |
+
paths when G is undirected.
|
| 87 |
+
|
| 88 |
+
For betweenness_centrality_subset the reporting is different.
|
| 89 |
+
If the source and target subsets are the same, then we want
|
| 90 |
+
to count undirected paths. But if the source and target subsets
|
| 91 |
+
differ -- for example, if sources is {0} and targets is {1},
|
| 92 |
+
then we are only counting the paths in one direction. They are
|
| 93 |
+
undirected paths but we are counting them in a directed way.
|
| 94 |
+
To count them as undirected paths, each should count as half a path.
|
| 95 |
+
|
| 96 |
+
References
|
| 97 |
+
----------
|
| 98 |
+
.. [1] Ulrik Brandes, A Faster Algorithm for Betweenness Centrality.
|
| 99 |
+
Journal of Mathematical Sociology 25(2):163-177, 2001.
|
| 100 |
+
https://doi.org/10.1080/0022250X.2001.9990249
|
| 101 |
+
.. [2] Ulrik Brandes: On Variants of Shortest-Path Betweenness
|
| 102 |
+
Centrality and their Generic Computation.
|
| 103 |
+
Social Networks 30(2):136-145, 2008.
|
| 104 |
+
https://doi.org/10.1016/j.socnet.2007.11.001
|
| 105 |
+
"""
|
| 106 |
+
b = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
|
| 107 |
+
for s in sources:
|
| 108 |
+
# single source shortest paths
|
| 109 |
+
if weight is None: # use BFS
|
| 110 |
+
S, P, sigma, _ = shortest_path(G, s)
|
| 111 |
+
else: # use Dijkstra's algorithm
|
| 112 |
+
S, P, sigma, _ = dijkstra(G, s, weight)
|
| 113 |
+
b = _accumulate_subset(b, S, P, sigma, s, targets)
|
| 114 |
+
b = _rescale(b, len(G), normalized=normalized, directed=G.is_directed())
|
| 115 |
+
return b
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 119 |
+
def edge_betweenness_centrality_subset(
|
| 120 |
+
G, sources, targets, normalized=False, weight=None
|
| 121 |
+
):
|
| 122 |
+
r"""Compute betweenness centrality for edges for a subset of nodes.
|
| 123 |
+
|
| 124 |
+
.. math::
|
| 125 |
+
|
| 126 |
+
c_B(v) =\sum_{s\in S,t \in T} \frac{\sigma(s, t|e)}{\sigma(s, t)}
|
| 127 |
+
|
| 128 |
+
where $S$ is the set of sources, $T$ is the set of targets,
|
| 129 |
+
$\sigma(s, t)$ is the number of shortest $(s, t)$-paths,
|
| 130 |
+
and $\sigma(s, t|e)$ is the number of those paths
|
| 131 |
+
passing through edge $e$ [2]_.
|
| 132 |
+
|
| 133 |
+
Parameters
|
| 134 |
+
----------
|
| 135 |
+
G : graph
|
| 136 |
+
A networkx graph.
|
| 137 |
+
|
| 138 |
+
sources: list of nodes
|
| 139 |
+
Nodes to use as sources for shortest paths in betweenness
|
| 140 |
+
|
| 141 |
+
targets: list of nodes
|
| 142 |
+
Nodes to use as targets for shortest paths in betweenness
|
| 143 |
+
|
| 144 |
+
normalized : bool, optional
|
| 145 |
+
If True the betweenness values are normalized by `2/(n(n-1))`
|
| 146 |
+
for graphs, and `1/(n(n-1))` for directed graphs where `n`
|
| 147 |
+
is the number of nodes in G.
|
| 148 |
+
|
| 149 |
+
weight : None or string, optional (default=None)
|
| 150 |
+
If None, all edge weights are considered equal.
|
| 151 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 152 |
+
Weights are used to calculate weighted shortest paths, so they are
|
| 153 |
+
interpreted as distances.
|
| 154 |
+
|
| 155 |
+
Returns
|
| 156 |
+
-------
|
| 157 |
+
edges : dictionary
|
| 158 |
+
Dictionary of edges with Betweenness centrality as the value.
|
| 159 |
+
|
| 160 |
+
See Also
|
| 161 |
+
--------
|
| 162 |
+
betweenness_centrality
|
| 163 |
+
edge_load
|
| 164 |
+
|
| 165 |
+
Notes
|
| 166 |
+
-----
|
| 167 |
+
The basic algorithm is from [1]_.
|
| 168 |
+
|
| 169 |
+
For weighted graphs the edge weights must be greater than zero.
|
| 170 |
+
Zero edge weights can produce an infinite number of equal length
|
| 171 |
+
paths between pairs of nodes.
|
| 172 |
+
|
| 173 |
+
The normalization might seem a little strange but it is the same
|
| 174 |
+
as in edge_betweenness_centrality() and is designed to make
|
| 175 |
+
edge_betweenness_centrality(G) be the same as
|
| 176 |
+
edge_betweenness_centrality_subset(G,sources=G.nodes(),targets=G.nodes()).
|
| 177 |
+
|
| 178 |
+
References
|
| 179 |
+
----------
|
| 180 |
+
.. [1] Ulrik Brandes, A Faster Algorithm for Betweenness Centrality.
|
| 181 |
+
Journal of Mathematical Sociology 25(2):163-177, 2001.
|
| 182 |
+
https://doi.org/10.1080/0022250X.2001.9990249
|
| 183 |
+
.. [2] Ulrik Brandes: On Variants of Shortest-Path Betweenness
|
| 184 |
+
Centrality and their Generic Computation.
|
| 185 |
+
Social Networks 30(2):136-145, 2008.
|
| 186 |
+
https://doi.org/10.1016/j.socnet.2007.11.001
|
| 187 |
+
"""
|
| 188 |
+
b = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
|
| 189 |
+
b.update(dict.fromkeys(G.edges(), 0.0)) # b[e] for e in G.edges()
|
| 190 |
+
for s in sources:
|
| 191 |
+
# single source shortest paths
|
| 192 |
+
if weight is None: # use BFS
|
| 193 |
+
S, P, sigma, _ = shortest_path(G, s)
|
| 194 |
+
else: # use Dijkstra's algorithm
|
| 195 |
+
S, P, sigma, _ = dijkstra(G, s, weight)
|
| 196 |
+
b = _accumulate_edges_subset(b, S, P, sigma, s, targets)
|
| 197 |
+
for n in G: # remove nodes to only return edges
|
| 198 |
+
del b[n]
|
| 199 |
+
b = _rescale_e(b, len(G), normalized=normalized, directed=G.is_directed())
|
| 200 |
+
if G.is_multigraph():
|
| 201 |
+
b = _add_edge_keys(G, b, weight=weight)
|
| 202 |
+
return b
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _accumulate_subset(betweenness, S, P, sigma, s, targets):
|
| 206 |
+
delta = dict.fromkeys(S, 0.0)
|
| 207 |
+
target_set = set(targets) - {s}
|
| 208 |
+
while S:
|
| 209 |
+
w = S.pop()
|
| 210 |
+
if w in target_set:
|
| 211 |
+
coeff = (delta[w] + 1.0) / sigma[w]
|
| 212 |
+
else:
|
| 213 |
+
coeff = delta[w] / sigma[w]
|
| 214 |
+
for v in P[w]:
|
| 215 |
+
delta[v] += sigma[v] * coeff
|
| 216 |
+
if w != s:
|
| 217 |
+
betweenness[w] += delta[w]
|
| 218 |
+
return betweenness
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _accumulate_edges_subset(betweenness, S, P, sigma, s, targets):
|
| 222 |
+
"""edge_betweenness_centrality_subset helper."""
|
| 223 |
+
delta = dict.fromkeys(S, 0)
|
| 224 |
+
target_set = set(targets)
|
| 225 |
+
while S:
|
| 226 |
+
w = S.pop()
|
| 227 |
+
for v in P[w]:
|
| 228 |
+
if w in target_set:
|
| 229 |
+
c = (sigma[v] / sigma[w]) * (1.0 + delta[w])
|
| 230 |
+
else:
|
| 231 |
+
c = delta[w] / len(P[w])
|
| 232 |
+
if (v, w) not in betweenness:
|
| 233 |
+
betweenness[(w, v)] += c
|
| 234 |
+
else:
|
| 235 |
+
betweenness[(v, w)] += c
|
| 236 |
+
delta[v] += c
|
| 237 |
+
if w != s:
|
| 238 |
+
betweenness[w] += delta[w]
|
| 239 |
+
return betweenness
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def _rescale(betweenness, n, normalized, directed=False):
|
| 243 |
+
"""betweenness_centrality_subset helper."""
|
| 244 |
+
if normalized:
|
| 245 |
+
if n <= 2:
|
| 246 |
+
scale = None # no normalization b=0 for all nodes
|
| 247 |
+
else:
|
| 248 |
+
scale = 1.0 / ((n - 1) * (n - 2))
|
| 249 |
+
else: # rescale by 2 for undirected graphs
|
| 250 |
+
if not directed:
|
| 251 |
+
scale = 0.5
|
| 252 |
+
else:
|
| 253 |
+
scale = None
|
| 254 |
+
if scale is not None:
|
| 255 |
+
for v in betweenness:
|
| 256 |
+
betweenness[v] *= scale
|
| 257 |
+
return betweenness
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _rescale_e(betweenness, n, normalized, directed=False):
|
| 261 |
+
"""edge_betweenness_centrality_subset helper."""
|
| 262 |
+
if normalized:
|
| 263 |
+
if n <= 1:
|
| 264 |
+
scale = None # no normalization b=0 for all nodes
|
| 265 |
+
else:
|
| 266 |
+
scale = 1.0 / (n * (n - 1))
|
| 267 |
+
else: # rescale by 2 for undirected graphs
|
| 268 |
+
if not directed:
|
| 269 |
+
scale = 0.5
|
| 270 |
+
else:
|
| 271 |
+
scale = None
|
| 272 |
+
if scale is not None:
|
| 273 |
+
for v in betweenness:
|
| 274 |
+
betweenness[v] *= scale
|
| 275 |
+
return betweenness
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/closeness.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Closeness centrality measures.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import functools
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx.exception import NetworkXError
|
| 9 |
+
from networkx.utils.decorators import not_implemented_for
|
| 10 |
+
|
| 11 |
+
__all__ = ["closeness_centrality", "incremental_closeness_centrality"]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@nx._dispatchable(edge_attrs="distance")
|
| 15 |
+
def closeness_centrality(G, u=None, distance=None, wf_improved=True):
|
| 16 |
+
r"""Compute closeness centrality for nodes.
|
| 17 |
+
|
| 18 |
+
Closeness centrality [1]_ of a node `u` is the reciprocal of the
|
| 19 |
+
average shortest path distance to `u` over all `n-1` reachable nodes.
|
| 20 |
+
|
| 21 |
+
.. math::
|
| 22 |
+
|
| 23 |
+
C(u) = \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
|
| 24 |
+
|
| 25 |
+
where `d(v, u)` is the shortest-path distance between `v` and `u`,
|
| 26 |
+
and `n-1` is the number of nodes reachable from `u`. Notice that the
|
| 27 |
+
closeness distance function computes the incoming distance to `u`
|
| 28 |
+
for directed graphs. To use outward distance, act on `G.reverse()`.
|
| 29 |
+
|
| 30 |
+
Notice that higher values of closeness indicate higher centrality.
|
| 31 |
+
|
| 32 |
+
Wasserman and Faust propose an improved formula for graphs with
|
| 33 |
+
more than one connected component. The result is "a ratio of the
|
| 34 |
+
fraction of actors in the group who are reachable, to the average
|
| 35 |
+
distance" from the reachable actors [2]_. You might think this
|
| 36 |
+
scale factor is inverted but it is not. As is, nodes from small
|
| 37 |
+
components receive a smaller closeness value. Letting `N` denote
|
| 38 |
+
the number of nodes in the graph,
|
| 39 |
+
|
| 40 |
+
.. math::
|
| 41 |
+
|
| 42 |
+
C_{WF}(u) = \frac{n-1}{N-1} \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
|
| 43 |
+
|
| 44 |
+
Parameters
|
| 45 |
+
----------
|
| 46 |
+
G : graph
|
| 47 |
+
A NetworkX graph
|
| 48 |
+
|
| 49 |
+
u : node, optional
|
| 50 |
+
Return only the value for node u
|
| 51 |
+
|
| 52 |
+
distance : edge attribute key, optional (default=None)
|
| 53 |
+
Use the specified edge attribute as the edge distance in shortest
|
| 54 |
+
path calculations. If `None` (the default) all edges have a distance of 1.
|
| 55 |
+
Absent edge attributes are assigned a distance of 1. Note that no check
|
| 56 |
+
is performed to ensure that edges have the provided attribute.
|
| 57 |
+
|
| 58 |
+
wf_improved : bool, optional (default=True)
|
| 59 |
+
If True, scale by the fraction of nodes reachable. This gives the
|
| 60 |
+
Wasserman and Faust improved formula. For single component graphs
|
| 61 |
+
it is the same as the original formula.
|
| 62 |
+
|
| 63 |
+
Returns
|
| 64 |
+
-------
|
| 65 |
+
nodes : dictionary
|
| 66 |
+
Dictionary of nodes with closeness centrality as the value.
|
| 67 |
+
|
| 68 |
+
Examples
|
| 69 |
+
--------
|
| 70 |
+
>>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
|
| 71 |
+
>>> nx.closeness_centrality(G)
|
| 72 |
+
{0: 1.0, 1: 1.0, 2: 0.75, 3: 0.75}
|
| 73 |
+
|
| 74 |
+
See Also
|
| 75 |
+
--------
|
| 76 |
+
betweenness_centrality, load_centrality, eigenvector_centrality,
|
| 77 |
+
degree_centrality, incremental_closeness_centrality
|
| 78 |
+
|
| 79 |
+
Notes
|
| 80 |
+
-----
|
| 81 |
+
The closeness centrality is normalized to `(n-1)/(|G|-1)` where
|
| 82 |
+
`n` is the number of nodes in the connected part of graph
|
| 83 |
+
containing the node. If the graph is not completely connected,
|
| 84 |
+
this algorithm computes the closeness centrality for each
|
| 85 |
+
connected part separately scaled by that parts size.
|
| 86 |
+
|
| 87 |
+
If the 'distance' keyword is set to an edge attribute key then the
|
| 88 |
+
shortest-path length will be computed using Dijkstra's algorithm with
|
| 89 |
+
that edge attribute as the edge weight.
|
| 90 |
+
|
| 91 |
+
The closeness centrality uses *inward* distance to a node, not outward.
|
| 92 |
+
If you want to use outword distances apply the function to `G.reverse()`
|
| 93 |
+
|
| 94 |
+
In NetworkX 2.2 and earlier a bug caused Dijkstra's algorithm to use the
|
| 95 |
+
outward distance rather than the inward distance. If you use a 'distance'
|
| 96 |
+
keyword and a DiGraph, your results will change between v2.2 and v2.3.
|
| 97 |
+
|
| 98 |
+
References
|
| 99 |
+
----------
|
| 100 |
+
.. [1] Linton C. Freeman: Centrality in networks: I.
|
| 101 |
+
Conceptual clarification. Social Networks 1:215-239, 1979.
|
| 102 |
+
https://doi.org/10.1016/0378-8733(78)90021-7
|
| 103 |
+
.. [2] pg. 201 of Wasserman, S. and Faust, K.,
|
| 104 |
+
Social Network Analysis: Methods and Applications, 1994,
|
| 105 |
+
Cambridge University Press.
|
| 106 |
+
"""
|
| 107 |
+
if G.is_directed():
|
| 108 |
+
G = G.reverse() # create a reversed graph view
|
| 109 |
+
|
| 110 |
+
if distance is not None:
|
| 111 |
+
# use Dijkstra's algorithm with specified attribute as edge weight
|
| 112 |
+
path_length = functools.partial(
|
| 113 |
+
nx.single_source_dijkstra_path_length, weight=distance
|
| 114 |
+
)
|
| 115 |
+
else:
|
| 116 |
+
path_length = nx.single_source_shortest_path_length
|
| 117 |
+
|
| 118 |
+
if u is None:
|
| 119 |
+
nodes = G.nodes
|
| 120 |
+
else:
|
| 121 |
+
nodes = [u]
|
| 122 |
+
closeness_dict = {}
|
| 123 |
+
for n in nodes:
|
| 124 |
+
sp = path_length(G, n)
|
| 125 |
+
totsp = sum(sp.values())
|
| 126 |
+
len_G = len(G)
|
| 127 |
+
_closeness_centrality = 0.0
|
| 128 |
+
if totsp > 0.0 and len_G > 1:
|
| 129 |
+
_closeness_centrality = (len(sp) - 1.0) / totsp
|
| 130 |
+
# normalize to number of nodes-1 in connected part
|
| 131 |
+
if wf_improved:
|
| 132 |
+
s = (len(sp) - 1.0) / (len_G - 1)
|
| 133 |
+
_closeness_centrality *= s
|
| 134 |
+
closeness_dict[n] = _closeness_centrality
|
| 135 |
+
if u is not None:
|
| 136 |
+
return closeness_dict[u]
|
| 137 |
+
return closeness_dict
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@not_implemented_for("directed")
|
| 141 |
+
@nx._dispatchable(mutates_input=True)
|
| 142 |
+
def incremental_closeness_centrality(
|
| 143 |
+
G, edge, prev_cc=None, insertion=True, wf_improved=True
|
| 144 |
+
):
|
| 145 |
+
r"""Incremental closeness centrality for nodes.
|
| 146 |
+
|
| 147 |
+
Compute closeness centrality for nodes using level-based work filtering
|
| 148 |
+
as described in Incremental Algorithms for Closeness Centrality by Sariyuce et al.
|
| 149 |
+
|
| 150 |
+
Level-based work filtering detects unnecessary updates to the closeness
|
| 151 |
+
centrality and filters them out.
|
| 152 |
+
|
| 153 |
+
---
|
| 154 |
+
From "Incremental Algorithms for Closeness Centrality":
|
| 155 |
+
|
| 156 |
+
Theorem 1: Let :math:`G = (V, E)` be a graph and u and v be two vertices in V
|
| 157 |
+
such that there is no edge (u, v) in E. Let :math:`G' = (V, E \cup uv)`
|
| 158 |
+
Then :math:`cc[s] = cc'[s]` if and only if :math:`\left|dG(s, u) - dG(s, v)\right| \leq 1`.
|
| 159 |
+
|
| 160 |
+
Where :math:`dG(u, v)` denotes the length of the shortest path between
|
| 161 |
+
two vertices u, v in a graph G, cc[s] is the closeness centrality for a
|
| 162 |
+
vertex s in V, and cc'[s] is the closeness centrality for a
|
| 163 |
+
vertex s in V, with the (u, v) edge added.
|
| 164 |
+
---
|
| 165 |
+
|
| 166 |
+
We use Theorem 1 to filter out updates when adding or removing an edge.
|
| 167 |
+
When adding an edge (u, v), we compute the shortest path lengths from all
|
| 168 |
+
other nodes to u and to v before the node is added. When removing an edge,
|
| 169 |
+
we compute the shortest path lengths after the edge is removed. Then we
|
| 170 |
+
apply Theorem 1 to use previously computed closeness centrality for nodes
|
| 171 |
+
where :math:`\left|dG(s, u) - dG(s, v)\right| \leq 1`. This works only for
|
| 172 |
+
undirected, unweighted graphs; the distance argument is not supported.
|
| 173 |
+
|
| 174 |
+
Closeness centrality [1]_ of a node `u` is the reciprocal of the
|
| 175 |
+
sum of the shortest path distances from `u` to all `n-1` other nodes.
|
| 176 |
+
Since the sum of distances depends on the number of nodes in the
|
| 177 |
+
graph, closeness is normalized by the sum of minimum possible
|
| 178 |
+
distances `n-1`.
|
| 179 |
+
|
| 180 |
+
.. math::
|
| 181 |
+
|
| 182 |
+
C(u) = \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
|
| 183 |
+
|
| 184 |
+
where `d(v, u)` is the shortest-path distance between `v` and `u`,
|
| 185 |
+
and `n` is the number of nodes in the graph.
|
| 186 |
+
|
| 187 |
+
Notice that higher values of closeness indicate higher centrality.
|
| 188 |
+
|
| 189 |
+
Parameters
|
| 190 |
+
----------
|
| 191 |
+
G : graph
|
| 192 |
+
A NetworkX graph
|
| 193 |
+
|
| 194 |
+
edge : tuple
|
| 195 |
+
The modified edge (u, v) in the graph.
|
| 196 |
+
|
| 197 |
+
prev_cc : dictionary
|
| 198 |
+
The previous closeness centrality for all nodes in the graph.
|
| 199 |
+
|
| 200 |
+
insertion : bool, optional
|
| 201 |
+
If True (default) the edge was inserted, otherwise it was deleted from the graph.
|
| 202 |
+
|
| 203 |
+
wf_improved : bool, optional (default=True)
|
| 204 |
+
If True, scale by the fraction of nodes reachable. This gives the
|
| 205 |
+
Wasserman and Faust improved formula. For single component graphs
|
| 206 |
+
it is the same as the original formula.
|
| 207 |
+
|
| 208 |
+
Returns
|
| 209 |
+
-------
|
| 210 |
+
nodes : dictionary
|
| 211 |
+
Dictionary of nodes with closeness centrality as the value.
|
| 212 |
+
|
| 213 |
+
See Also
|
| 214 |
+
--------
|
| 215 |
+
betweenness_centrality, load_centrality, eigenvector_centrality,
|
| 216 |
+
degree_centrality, closeness_centrality
|
| 217 |
+
|
| 218 |
+
Notes
|
| 219 |
+
-----
|
| 220 |
+
The closeness centrality is normalized to `(n-1)/(|G|-1)` where
|
| 221 |
+
`n` is the number of nodes in the connected part of graph
|
| 222 |
+
containing the node. If the graph is not completely connected,
|
| 223 |
+
this algorithm computes the closeness centrality for each
|
| 224 |
+
connected part separately.
|
| 225 |
+
|
| 226 |
+
References
|
| 227 |
+
----------
|
| 228 |
+
.. [1] Freeman, L.C., 1979. Centrality in networks: I.
|
| 229 |
+
Conceptual clarification. Social Networks 1, 215--239.
|
| 230 |
+
https://doi.org/10.1016/0378-8733(78)90021-7
|
| 231 |
+
.. [2] Sariyuce, A.E. ; Kaya, K. ; Saule, E. ; Catalyiirek, U.V. Incremental
|
| 232 |
+
Algorithms for Closeness Centrality. 2013 IEEE International Conference on Big Data
|
| 233 |
+
http://sariyuce.com/papers/bigdata13.pdf
|
| 234 |
+
"""
|
| 235 |
+
if prev_cc is not None and set(prev_cc.keys()) != set(G.nodes()):
|
| 236 |
+
raise NetworkXError("prev_cc and G do not have the same nodes")
|
| 237 |
+
|
| 238 |
+
# Unpack edge
|
| 239 |
+
(u, v) = edge
|
| 240 |
+
path_length = nx.single_source_shortest_path_length
|
| 241 |
+
|
| 242 |
+
if insertion:
|
| 243 |
+
# For edge insertion, we want shortest paths before the edge is inserted
|
| 244 |
+
du = path_length(G, u)
|
| 245 |
+
dv = path_length(G, v)
|
| 246 |
+
|
| 247 |
+
G.add_edge(u, v)
|
| 248 |
+
else:
|
| 249 |
+
G.remove_edge(u, v)
|
| 250 |
+
|
| 251 |
+
# For edge removal, we want shortest paths after the edge is removed
|
| 252 |
+
du = path_length(G, u)
|
| 253 |
+
dv = path_length(G, v)
|
| 254 |
+
|
| 255 |
+
if prev_cc is None:
|
| 256 |
+
return nx.closeness_centrality(G)
|
| 257 |
+
|
| 258 |
+
nodes = G.nodes()
|
| 259 |
+
closeness_dict = {}
|
| 260 |
+
for n in nodes:
|
| 261 |
+
if n in du and n in dv and abs(du[n] - dv[n]) <= 1:
|
| 262 |
+
closeness_dict[n] = prev_cc[n]
|
| 263 |
+
else:
|
| 264 |
+
sp = path_length(G, n)
|
| 265 |
+
totsp = sum(sp.values())
|
| 266 |
+
len_G = len(G)
|
| 267 |
+
_closeness_centrality = 0.0
|
| 268 |
+
if totsp > 0.0 and len_G > 1:
|
| 269 |
+
_closeness_centrality = (len(sp) - 1.0) / totsp
|
| 270 |
+
# normalize to number of nodes-1 in connected part
|
| 271 |
+
if wf_improved:
|
| 272 |
+
s = (len(sp) - 1.0) / (len_G - 1)
|
| 273 |
+
_closeness_centrality *= s
|
| 274 |
+
closeness_dict[n] = _closeness_centrality
|
| 275 |
+
|
| 276 |
+
# Leave the graph as we found it
|
| 277 |
+
if insertion:
|
| 278 |
+
G.remove_edge(u, v)
|
| 279 |
+
else:
|
| 280 |
+
G.add_edge(u, v)
|
| 281 |
+
|
| 282 |
+
return closeness_dict
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/current_flow_betweenness.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Current-flow betweenness centrality measures."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.algorithms.centrality.flow_matrix import (
|
| 5 |
+
CGInverseLaplacian,
|
| 6 |
+
FullInverseLaplacian,
|
| 7 |
+
SuperLUInverseLaplacian,
|
| 8 |
+
flow_matrix_row,
|
| 9 |
+
)
|
| 10 |
+
from networkx.utils import (
|
| 11 |
+
not_implemented_for,
|
| 12 |
+
py_random_state,
|
| 13 |
+
reverse_cuthill_mckee_ordering,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
__all__ = [
|
| 17 |
+
"current_flow_betweenness_centrality",
|
| 18 |
+
"approximate_current_flow_betweenness_centrality",
|
| 19 |
+
"edge_current_flow_betweenness_centrality",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@not_implemented_for("directed")
|
| 24 |
+
@py_random_state(7)
|
| 25 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 26 |
+
def approximate_current_flow_betweenness_centrality(
|
| 27 |
+
G,
|
| 28 |
+
normalized=True,
|
| 29 |
+
weight=None,
|
| 30 |
+
dtype=float,
|
| 31 |
+
solver="full",
|
| 32 |
+
epsilon=0.5,
|
| 33 |
+
kmax=10000,
|
| 34 |
+
seed=None,
|
| 35 |
+
):
|
| 36 |
+
r"""Compute the approximate current-flow betweenness centrality for nodes.
|
| 37 |
+
|
| 38 |
+
Approximates the current-flow betweenness centrality within absolute
|
| 39 |
+
error of epsilon with high probability [1]_.
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
----------
|
| 44 |
+
G : graph
|
| 45 |
+
A NetworkX graph
|
| 46 |
+
|
| 47 |
+
normalized : bool, optional (default=True)
|
| 48 |
+
If True the betweenness values are normalized by 2/[(n-1)(n-2)] where
|
| 49 |
+
n is the number of nodes in G.
|
| 50 |
+
|
| 51 |
+
weight : string or None, optional (default=None)
|
| 52 |
+
Key for edge data used as the edge weight.
|
| 53 |
+
If None, then use 1 as each edge weight.
|
| 54 |
+
The weight reflects the capacity or the strength of the
|
| 55 |
+
edge.
|
| 56 |
+
|
| 57 |
+
dtype : data type (float)
|
| 58 |
+
Default data type for internal matrices.
|
| 59 |
+
Set to np.float32 for lower memory consumption.
|
| 60 |
+
|
| 61 |
+
solver : string (default='full')
|
| 62 |
+
Type of linear solver to use for computing the flow matrix.
|
| 63 |
+
Options are "full" (uses most memory), "lu" (recommended), and
|
| 64 |
+
"cg" (uses least memory).
|
| 65 |
+
|
| 66 |
+
epsilon: float
|
| 67 |
+
Absolute error tolerance.
|
| 68 |
+
|
| 69 |
+
kmax: int
|
| 70 |
+
Maximum number of sample node pairs to use for approximation.
|
| 71 |
+
|
| 72 |
+
seed : integer, random_state, or None (default)
|
| 73 |
+
Indicator of random number generation state.
|
| 74 |
+
See :ref:`Randomness<randomness>`.
|
| 75 |
+
|
| 76 |
+
Returns
|
| 77 |
+
-------
|
| 78 |
+
nodes : dictionary
|
| 79 |
+
Dictionary of nodes with betweenness centrality as the value.
|
| 80 |
+
|
| 81 |
+
See Also
|
| 82 |
+
--------
|
| 83 |
+
current_flow_betweenness_centrality
|
| 84 |
+
|
| 85 |
+
Notes
|
| 86 |
+
-----
|
| 87 |
+
The running time is $O((1/\epsilon^2)m{\sqrt k} \log n)$
|
| 88 |
+
and the space required is $O(m)$ for $n$ nodes and $m$ edges.
|
| 89 |
+
|
| 90 |
+
If the edges have a 'weight' attribute they will be used as
|
| 91 |
+
weights in this algorithm. Unspecified weights are set to 1.
|
| 92 |
+
|
| 93 |
+
References
|
| 94 |
+
----------
|
| 95 |
+
.. [1] Ulrik Brandes and Daniel Fleischer:
|
| 96 |
+
Centrality Measures Based on Current Flow.
|
| 97 |
+
Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
|
| 98 |
+
LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
|
| 99 |
+
https://doi.org/10.1007/978-3-540-31856-9_44
|
| 100 |
+
"""
|
| 101 |
+
import numpy as np
|
| 102 |
+
|
| 103 |
+
if not nx.is_connected(G):
|
| 104 |
+
raise nx.NetworkXError("Graph not connected.")
|
| 105 |
+
solvername = {
|
| 106 |
+
"full": FullInverseLaplacian,
|
| 107 |
+
"lu": SuperLUInverseLaplacian,
|
| 108 |
+
"cg": CGInverseLaplacian,
|
| 109 |
+
}
|
| 110 |
+
n = G.number_of_nodes()
|
| 111 |
+
ordering = list(reverse_cuthill_mckee_ordering(G))
|
| 112 |
+
# make a copy with integer labels according to rcm ordering
|
| 113 |
+
# this could be done without a copy if we really wanted to
|
| 114 |
+
H = nx.relabel_nodes(G, dict(zip(ordering, range(n))))
|
| 115 |
+
L = nx.laplacian_matrix(H, nodelist=range(n), weight=weight).asformat("csc")
|
| 116 |
+
L = L.astype(dtype)
|
| 117 |
+
C = solvername[solver](L, dtype=dtype) # initialize solver
|
| 118 |
+
betweenness = dict.fromkeys(H, 0.0)
|
| 119 |
+
nb = (n - 1.0) * (n - 2.0) # normalization factor
|
| 120 |
+
cstar = n * (n - 1) / nb
|
| 121 |
+
l = 1 # parameter in approximation, adjustable
|
| 122 |
+
k = l * int(np.ceil((cstar / epsilon) ** 2 * np.log(n)))
|
| 123 |
+
if k > kmax:
|
| 124 |
+
msg = f"Number random pairs k>kmax ({k}>{kmax}) "
|
| 125 |
+
raise nx.NetworkXError(msg, "Increase kmax or epsilon")
|
| 126 |
+
cstar2k = cstar / (2 * k)
|
| 127 |
+
for _ in range(k):
|
| 128 |
+
s, t = pair = seed.sample(range(n), 2)
|
| 129 |
+
b = np.zeros(n, dtype=dtype)
|
| 130 |
+
b[s] = 1
|
| 131 |
+
b[t] = -1
|
| 132 |
+
p = C.solve(b)
|
| 133 |
+
for v in H:
|
| 134 |
+
if v in pair:
|
| 135 |
+
continue
|
| 136 |
+
for nbr in H[v]:
|
| 137 |
+
w = H[v][nbr].get(weight, 1.0)
|
| 138 |
+
betweenness[v] += float(w * np.abs(p[v] - p[nbr]) * cstar2k)
|
| 139 |
+
if normalized:
|
| 140 |
+
factor = 1.0
|
| 141 |
+
else:
|
| 142 |
+
factor = nb / 2.0
|
| 143 |
+
# remap to original node names and "unnormalize" if required
|
| 144 |
+
return {ordering[k]: v * factor for k, v in betweenness.items()}
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@not_implemented_for("directed")
|
| 148 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 149 |
+
def current_flow_betweenness_centrality(
|
| 150 |
+
G, normalized=True, weight=None, dtype=float, solver="full"
|
| 151 |
+
):
|
| 152 |
+
r"""Compute current-flow betweenness centrality for nodes.
|
| 153 |
+
|
| 154 |
+
Current-flow betweenness centrality uses an electrical current
|
| 155 |
+
model for information spreading in contrast to betweenness
|
| 156 |
+
centrality which uses shortest paths.
|
| 157 |
+
|
| 158 |
+
Current-flow betweenness centrality is also known as
|
| 159 |
+
random-walk betweenness centrality [2]_.
|
| 160 |
+
|
| 161 |
+
Parameters
|
| 162 |
+
----------
|
| 163 |
+
G : graph
|
| 164 |
+
A NetworkX graph
|
| 165 |
+
|
| 166 |
+
normalized : bool, optional (default=True)
|
| 167 |
+
If True the betweenness values are normalized by 2/[(n-1)(n-2)] where
|
| 168 |
+
n is the number of nodes in G.
|
| 169 |
+
|
| 170 |
+
weight : string or None, optional (default=None)
|
| 171 |
+
Key for edge data used as the edge weight.
|
| 172 |
+
If None, then use 1 as each edge weight.
|
| 173 |
+
The weight reflects the capacity or the strength of the
|
| 174 |
+
edge.
|
| 175 |
+
|
| 176 |
+
dtype : data type (float)
|
| 177 |
+
Default data type for internal matrices.
|
| 178 |
+
Set to np.float32 for lower memory consumption.
|
| 179 |
+
|
| 180 |
+
solver : string (default='full')
|
| 181 |
+
Type of linear solver to use for computing the flow matrix.
|
| 182 |
+
Options are "full" (uses most memory), "lu" (recommended), and
|
| 183 |
+
"cg" (uses least memory).
|
| 184 |
+
|
| 185 |
+
Returns
|
| 186 |
+
-------
|
| 187 |
+
nodes : dictionary
|
| 188 |
+
Dictionary of nodes with betweenness centrality as the value.
|
| 189 |
+
|
| 190 |
+
See Also
|
| 191 |
+
--------
|
| 192 |
+
approximate_current_flow_betweenness_centrality
|
| 193 |
+
betweenness_centrality
|
| 194 |
+
edge_betweenness_centrality
|
| 195 |
+
edge_current_flow_betweenness_centrality
|
| 196 |
+
|
| 197 |
+
Notes
|
| 198 |
+
-----
|
| 199 |
+
Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$
|
| 200 |
+
time [1]_, where $I(n-1)$ is the time needed to compute the
|
| 201 |
+
inverse Laplacian. For a full matrix this is $O(n^3)$ but using
|
| 202 |
+
sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the
|
| 203 |
+
Laplacian matrix condition number.
|
| 204 |
+
|
| 205 |
+
The space required is $O(nw)$ where $w$ is the width of the sparse
|
| 206 |
+
Laplacian matrix. Worse case is $w=n$ for $O(n^2)$.
|
| 207 |
+
|
| 208 |
+
If the edges have a 'weight' attribute they will be used as
|
| 209 |
+
weights in this algorithm. Unspecified weights are set to 1.
|
| 210 |
+
|
| 211 |
+
References
|
| 212 |
+
----------
|
| 213 |
+
.. [1] Centrality Measures Based on Current Flow.
|
| 214 |
+
Ulrik Brandes and Daniel Fleischer,
|
| 215 |
+
Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
|
| 216 |
+
LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
|
| 217 |
+
https://doi.org/10.1007/978-3-540-31856-9_44
|
| 218 |
+
|
| 219 |
+
.. [2] A measure of betweenness centrality based on random walks,
|
| 220 |
+
M. E. J. Newman, Social Networks 27, 39-54 (2005).
|
| 221 |
+
"""
|
| 222 |
+
if not nx.is_connected(G):
|
| 223 |
+
raise nx.NetworkXError("Graph not connected.")
|
| 224 |
+
N = G.number_of_nodes()
|
| 225 |
+
ordering = list(reverse_cuthill_mckee_ordering(G))
|
| 226 |
+
# make a copy with integer labels according to rcm ordering
|
| 227 |
+
# this could be done without a copy if we really wanted to
|
| 228 |
+
H = nx.relabel_nodes(G, dict(zip(ordering, range(N))))
|
| 229 |
+
betweenness = dict.fromkeys(H, 0.0) # b[n]=0 for n in H
|
| 230 |
+
for row, (s, t) in flow_matrix_row(H, weight=weight, dtype=dtype, solver=solver):
|
| 231 |
+
pos = dict(zip(row.argsort()[::-1], range(N)))
|
| 232 |
+
for i in range(N):
|
| 233 |
+
betweenness[s] += (i - pos[i]) * row.item(i)
|
| 234 |
+
betweenness[t] += (N - i - 1 - pos[i]) * row.item(i)
|
| 235 |
+
if normalized:
|
| 236 |
+
nb = (N - 1.0) * (N - 2.0) # normalization factor
|
| 237 |
+
else:
|
| 238 |
+
nb = 2.0
|
| 239 |
+
return {ordering[n]: (b - n) * 2.0 / nb for n, b in betweenness.items()}
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@not_implemented_for("directed")
|
| 243 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 244 |
+
def edge_current_flow_betweenness_centrality(
|
| 245 |
+
G, normalized=True, weight=None, dtype=float, solver="full"
|
| 246 |
+
):
|
| 247 |
+
r"""Compute current-flow betweenness centrality for edges.
|
| 248 |
+
|
| 249 |
+
Current-flow betweenness centrality uses an electrical current
|
| 250 |
+
model for information spreading in contrast to betweenness
|
| 251 |
+
centrality which uses shortest paths.
|
| 252 |
+
|
| 253 |
+
Current-flow betweenness centrality is also known as
|
| 254 |
+
random-walk betweenness centrality [2]_.
|
| 255 |
+
|
| 256 |
+
Parameters
|
| 257 |
+
----------
|
| 258 |
+
G : graph
|
| 259 |
+
A NetworkX graph
|
| 260 |
+
|
| 261 |
+
normalized : bool, optional (default=True)
|
| 262 |
+
If True the betweenness values are normalized by 2/[(n-1)(n-2)] where
|
| 263 |
+
n is the number of nodes in G.
|
| 264 |
+
|
| 265 |
+
weight : string or None, optional (default=None)
|
| 266 |
+
Key for edge data used as the edge weight.
|
| 267 |
+
If None, then use 1 as each edge weight.
|
| 268 |
+
The weight reflects the capacity or the strength of the
|
| 269 |
+
edge.
|
| 270 |
+
|
| 271 |
+
dtype : data type (default=float)
|
| 272 |
+
Default data type for internal matrices.
|
| 273 |
+
Set to np.float32 for lower memory consumption.
|
| 274 |
+
|
| 275 |
+
solver : string (default='full')
|
| 276 |
+
Type of linear solver to use for computing the flow matrix.
|
| 277 |
+
Options are "full" (uses most memory), "lu" (recommended), and
|
| 278 |
+
"cg" (uses least memory).
|
| 279 |
+
|
| 280 |
+
Returns
|
| 281 |
+
-------
|
| 282 |
+
nodes : dictionary
|
| 283 |
+
Dictionary of edge tuples with betweenness centrality as the value.
|
| 284 |
+
|
| 285 |
+
Raises
|
| 286 |
+
------
|
| 287 |
+
NetworkXError
|
| 288 |
+
The algorithm does not support DiGraphs.
|
| 289 |
+
If the input graph is an instance of DiGraph class, NetworkXError
|
| 290 |
+
is raised.
|
| 291 |
+
|
| 292 |
+
See Also
|
| 293 |
+
--------
|
| 294 |
+
betweenness_centrality
|
| 295 |
+
edge_betweenness_centrality
|
| 296 |
+
current_flow_betweenness_centrality
|
| 297 |
+
|
| 298 |
+
Notes
|
| 299 |
+
-----
|
| 300 |
+
Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$
|
| 301 |
+
time [1]_, where $I(n-1)$ is the time needed to compute the
|
| 302 |
+
inverse Laplacian. For a full matrix this is $O(n^3)$ but using
|
| 303 |
+
sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the
|
| 304 |
+
Laplacian matrix condition number.
|
| 305 |
+
|
| 306 |
+
The space required is $O(nw)$ where $w$ is the width of the sparse
|
| 307 |
+
Laplacian matrix. Worse case is $w=n$ for $O(n^2)$.
|
| 308 |
+
|
| 309 |
+
If the edges have a 'weight' attribute they will be used as
|
| 310 |
+
weights in this algorithm. Unspecified weights are set to 1.
|
| 311 |
+
|
| 312 |
+
References
|
| 313 |
+
----------
|
| 314 |
+
.. [1] Centrality Measures Based on Current Flow.
|
| 315 |
+
Ulrik Brandes and Daniel Fleischer,
|
| 316 |
+
Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
|
| 317 |
+
LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
|
| 318 |
+
https://doi.org/10.1007/978-3-540-31856-9_44
|
| 319 |
+
|
| 320 |
+
.. [2] A measure of betweenness centrality based on random walks,
|
| 321 |
+
M. E. J. Newman, Social Networks 27, 39-54 (2005).
|
| 322 |
+
"""
|
| 323 |
+
if not nx.is_connected(G):
|
| 324 |
+
raise nx.NetworkXError("Graph not connected.")
|
| 325 |
+
N = G.number_of_nodes()
|
| 326 |
+
ordering = list(reverse_cuthill_mckee_ordering(G))
|
| 327 |
+
# make a copy with integer labels according to rcm ordering
|
| 328 |
+
# this could be done without a copy if we really wanted to
|
| 329 |
+
H = nx.relabel_nodes(G, dict(zip(ordering, range(N))))
|
| 330 |
+
edges = (tuple(sorted((u, v))) for u, v in H.edges())
|
| 331 |
+
betweenness = dict.fromkeys(edges, 0.0)
|
| 332 |
+
if normalized:
|
| 333 |
+
nb = (N - 1.0) * (N - 2.0) # normalization factor
|
| 334 |
+
else:
|
| 335 |
+
nb = 2.0
|
| 336 |
+
for row, (e) in flow_matrix_row(H, weight=weight, dtype=dtype, solver=solver):
|
| 337 |
+
pos = dict(zip(row.argsort()[::-1], range(1, N + 1)))
|
| 338 |
+
for i in range(N):
|
| 339 |
+
betweenness[e] += (i + 1 - pos[i]) * row.item(i)
|
| 340 |
+
betweenness[e] += (N - i - pos[i]) * row.item(i)
|
| 341 |
+
betweenness[e] /= nb
|
| 342 |
+
return {(ordering[s], ordering[t]): b for (s, t), b in betweenness.items()}
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/current_flow_betweenness_subset.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Current-flow betweenness centrality measures for subsets of nodes."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.algorithms.centrality.flow_matrix import flow_matrix_row
|
| 5 |
+
from networkx.utils import not_implemented_for, reverse_cuthill_mckee_ordering
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"current_flow_betweenness_centrality_subset",
|
| 9 |
+
"edge_current_flow_betweenness_centrality_subset",
|
| 10 |
+
]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@not_implemented_for("directed")
|
| 14 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 15 |
+
def current_flow_betweenness_centrality_subset(
|
| 16 |
+
G, sources, targets, normalized=True, weight=None, dtype=float, solver="lu"
|
| 17 |
+
):
|
| 18 |
+
r"""Compute current-flow betweenness centrality for subsets of nodes.
|
| 19 |
+
|
| 20 |
+
Current-flow betweenness centrality uses an electrical current
|
| 21 |
+
model for information spreading in contrast to betweenness
|
| 22 |
+
centrality which uses shortest paths.
|
| 23 |
+
|
| 24 |
+
Current-flow betweenness centrality is also known as
|
| 25 |
+
random-walk betweenness centrality [2]_.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
G : graph
|
| 30 |
+
A NetworkX graph
|
| 31 |
+
|
| 32 |
+
sources: list of nodes
|
| 33 |
+
Nodes to use as sources for current
|
| 34 |
+
|
| 35 |
+
targets: list of nodes
|
| 36 |
+
Nodes to use as sinks for current
|
| 37 |
+
|
| 38 |
+
normalized : bool, optional (default=True)
|
| 39 |
+
If True the betweenness values are normalized by b=b/(n-1)(n-2) where
|
| 40 |
+
n is the number of nodes in G.
|
| 41 |
+
|
| 42 |
+
weight : string or None, optional (default=None)
|
| 43 |
+
Key for edge data used as the edge weight.
|
| 44 |
+
If None, then use 1 as each edge weight.
|
| 45 |
+
The weight reflects the capacity or the strength of the
|
| 46 |
+
edge.
|
| 47 |
+
|
| 48 |
+
dtype: data type (float)
|
| 49 |
+
Default data type for internal matrices.
|
| 50 |
+
Set to np.float32 for lower memory consumption.
|
| 51 |
+
|
| 52 |
+
solver: string (default='lu')
|
| 53 |
+
Type of linear solver to use for computing the flow matrix.
|
| 54 |
+
Options are "full" (uses most memory), "lu" (recommended), and
|
| 55 |
+
"cg" (uses least memory).
|
| 56 |
+
|
| 57 |
+
Returns
|
| 58 |
+
-------
|
| 59 |
+
nodes : dictionary
|
| 60 |
+
Dictionary of nodes with betweenness centrality as the value.
|
| 61 |
+
|
| 62 |
+
See Also
|
| 63 |
+
--------
|
| 64 |
+
approximate_current_flow_betweenness_centrality
|
| 65 |
+
betweenness_centrality
|
| 66 |
+
edge_betweenness_centrality
|
| 67 |
+
edge_current_flow_betweenness_centrality
|
| 68 |
+
|
| 69 |
+
Notes
|
| 70 |
+
-----
|
| 71 |
+
Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$
|
| 72 |
+
time [1]_, where $I(n-1)$ is the time needed to compute the
|
| 73 |
+
inverse Laplacian. For a full matrix this is $O(n^3)$ but using
|
| 74 |
+
sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the
|
| 75 |
+
Laplacian matrix condition number.
|
| 76 |
+
|
| 77 |
+
The space required is $O(nw)$ where $w$ is the width of the sparse
|
| 78 |
+
Laplacian matrix. Worse case is $w=n$ for $O(n^2)$.
|
| 79 |
+
|
| 80 |
+
If the edges have a 'weight' attribute they will be used as
|
| 81 |
+
weights in this algorithm. Unspecified weights are set to 1.
|
| 82 |
+
|
| 83 |
+
References
|
| 84 |
+
----------
|
| 85 |
+
.. [1] Centrality Measures Based on Current Flow.
|
| 86 |
+
Ulrik Brandes and Daniel Fleischer,
|
| 87 |
+
Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
|
| 88 |
+
LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
|
| 89 |
+
https://doi.org/10.1007/978-3-540-31856-9_44
|
| 90 |
+
|
| 91 |
+
.. [2] A measure of betweenness centrality based on random walks,
|
| 92 |
+
M. E. J. Newman, Social Networks 27, 39-54 (2005).
|
| 93 |
+
"""
|
| 94 |
+
import numpy as np
|
| 95 |
+
|
| 96 |
+
from networkx.utils import reverse_cuthill_mckee_ordering
|
| 97 |
+
|
| 98 |
+
if not nx.is_connected(G):
|
| 99 |
+
raise nx.NetworkXError("Graph not connected.")
|
| 100 |
+
N = G.number_of_nodes()
|
| 101 |
+
ordering = list(reverse_cuthill_mckee_ordering(G))
|
| 102 |
+
# make a copy with integer labels according to rcm ordering
|
| 103 |
+
# this could be done without a copy if we really wanted to
|
| 104 |
+
mapping = dict(zip(ordering, range(N)))
|
| 105 |
+
H = nx.relabel_nodes(G, mapping)
|
| 106 |
+
betweenness = dict.fromkeys(H, 0.0) # b[n]=0 for n in H
|
| 107 |
+
for row, (s, t) in flow_matrix_row(H, weight=weight, dtype=dtype, solver=solver):
|
| 108 |
+
for ss in sources:
|
| 109 |
+
i = mapping[ss]
|
| 110 |
+
for tt in targets:
|
| 111 |
+
j = mapping[tt]
|
| 112 |
+
betweenness[s] += 0.5 * abs(row.item(i) - row.item(j))
|
| 113 |
+
betweenness[t] += 0.5 * abs(row.item(i) - row.item(j))
|
| 114 |
+
if normalized:
|
| 115 |
+
nb = (N - 1.0) * (N - 2.0) # normalization factor
|
| 116 |
+
else:
|
| 117 |
+
nb = 2.0
|
| 118 |
+
for node in H:
|
| 119 |
+
betweenness[node] = betweenness[node] / nb + 1.0 / (2 - N)
|
| 120 |
+
return {ordering[node]: value for node, value in betweenness.items()}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@not_implemented_for("directed")
|
| 124 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 125 |
+
def edge_current_flow_betweenness_centrality_subset(
|
| 126 |
+
G, sources, targets, normalized=True, weight=None, dtype=float, solver="lu"
|
| 127 |
+
):
|
| 128 |
+
r"""Compute current-flow betweenness centrality for edges using subsets
|
| 129 |
+
of nodes.
|
| 130 |
+
|
| 131 |
+
Current-flow betweenness centrality uses an electrical current
|
| 132 |
+
model for information spreading in contrast to betweenness
|
| 133 |
+
centrality which uses shortest paths.
|
| 134 |
+
|
| 135 |
+
Current-flow betweenness centrality is also known as
|
| 136 |
+
random-walk betweenness centrality [2]_.
|
| 137 |
+
|
| 138 |
+
Parameters
|
| 139 |
+
----------
|
| 140 |
+
G : graph
|
| 141 |
+
A NetworkX graph
|
| 142 |
+
|
| 143 |
+
sources: list of nodes
|
| 144 |
+
Nodes to use as sources for current
|
| 145 |
+
|
| 146 |
+
targets: list of nodes
|
| 147 |
+
Nodes to use as sinks for current
|
| 148 |
+
|
| 149 |
+
normalized : bool, optional (default=True)
|
| 150 |
+
If True the betweenness values are normalized by b=b/(n-1)(n-2) where
|
| 151 |
+
n is the number of nodes in G.
|
| 152 |
+
|
| 153 |
+
weight : string or None, optional (default=None)
|
| 154 |
+
Key for edge data used as the edge weight.
|
| 155 |
+
If None, then use 1 as each edge weight.
|
| 156 |
+
The weight reflects the capacity or the strength of the
|
| 157 |
+
edge.
|
| 158 |
+
|
| 159 |
+
dtype: data type (float)
|
| 160 |
+
Default data type for internal matrices.
|
| 161 |
+
Set to np.float32 for lower memory consumption.
|
| 162 |
+
|
| 163 |
+
solver: string (default='lu')
|
| 164 |
+
Type of linear solver to use for computing the flow matrix.
|
| 165 |
+
Options are "full" (uses most memory), "lu" (recommended), and
|
| 166 |
+
"cg" (uses least memory).
|
| 167 |
+
|
| 168 |
+
Returns
|
| 169 |
+
-------
|
| 170 |
+
nodes : dict
|
| 171 |
+
Dictionary of edge tuples with betweenness centrality as the value.
|
| 172 |
+
|
| 173 |
+
See Also
|
| 174 |
+
--------
|
| 175 |
+
betweenness_centrality
|
| 176 |
+
edge_betweenness_centrality
|
| 177 |
+
current_flow_betweenness_centrality
|
| 178 |
+
|
| 179 |
+
Notes
|
| 180 |
+
-----
|
| 181 |
+
Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$
|
| 182 |
+
time [1]_, where $I(n-1)$ is the time needed to compute the
|
| 183 |
+
inverse Laplacian. For a full matrix this is $O(n^3)$ but using
|
| 184 |
+
sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the
|
| 185 |
+
Laplacian matrix condition number.
|
| 186 |
+
|
| 187 |
+
The space required is $O(nw)$ where $w$ is the width of the sparse
|
| 188 |
+
Laplacian matrix. Worse case is $w=n$ for $O(n^2)$.
|
| 189 |
+
|
| 190 |
+
If the edges have a 'weight' attribute they will be used as
|
| 191 |
+
weights in this algorithm. Unspecified weights are set to 1.
|
| 192 |
+
|
| 193 |
+
References
|
| 194 |
+
----------
|
| 195 |
+
.. [1] Centrality Measures Based on Current Flow.
|
| 196 |
+
Ulrik Brandes and Daniel Fleischer,
|
| 197 |
+
Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
|
| 198 |
+
LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
|
| 199 |
+
https://doi.org/10.1007/978-3-540-31856-9_44
|
| 200 |
+
|
| 201 |
+
.. [2] A measure of betweenness centrality based on random walks,
|
| 202 |
+
M. E. J. Newman, Social Networks 27, 39-54 (2005).
|
| 203 |
+
"""
|
| 204 |
+
import numpy as np
|
| 205 |
+
|
| 206 |
+
if not nx.is_connected(G):
|
| 207 |
+
raise nx.NetworkXError("Graph not connected.")
|
| 208 |
+
N = G.number_of_nodes()
|
| 209 |
+
ordering = list(reverse_cuthill_mckee_ordering(G))
|
| 210 |
+
# make a copy with integer labels according to rcm ordering
|
| 211 |
+
# this could be done without a copy if we really wanted to
|
| 212 |
+
mapping = dict(zip(ordering, range(N)))
|
| 213 |
+
H = nx.relabel_nodes(G, mapping)
|
| 214 |
+
edges = (tuple(sorted((u, v))) for u, v in H.edges())
|
| 215 |
+
betweenness = dict.fromkeys(edges, 0.0)
|
| 216 |
+
if normalized:
|
| 217 |
+
nb = (N - 1.0) * (N - 2.0) # normalization factor
|
| 218 |
+
else:
|
| 219 |
+
nb = 2.0
|
| 220 |
+
for row, (e) in flow_matrix_row(H, weight=weight, dtype=dtype, solver=solver):
|
| 221 |
+
for ss in sources:
|
| 222 |
+
i = mapping[ss]
|
| 223 |
+
for tt in targets:
|
| 224 |
+
j = mapping[tt]
|
| 225 |
+
betweenness[e] += 0.5 * abs(row.item(i) - row.item(j))
|
| 226 |
+
betweenness[e] /= nb
|
| 227 |
+
return {(ordering[s], ordering[t]): value for (s, t), value in betweenness.items()}
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/current_flow_closeness.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Current-flow closeness centrality measures."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.algorithms.centrality.flow_matrix import (
|
| 5 |
+
CGInverseLaplacian,
|
| 6 |
+
FullInverseLaplacian,
|
| 7 |
+
SuperLUInverseLaplacian,
|
| 8 |
+
)
|
| 9 |
+
from networkx.utils import not_implemented_for, reverse_cuthill_mckee_ordering
|
| 10 |
+
|
| 11 |
+
__all__ = ["current_flow_closeness_centrality", "information_centrality"]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@not_implemented_for("directed")
|
| 15 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 16 |
+
def current_flow_closeness_centrality(G, weight=None, dtype=float, solver="lu"):
|
| 17 |
+
"""Compute current-flow closeness centrality for nodes.
|
| 18 |
+
|
| 19 |
+
Current-flow closeness centrality is variant of closeness
|
| 20 |
+
centrality based on effective resistance between nodes in
|
| 21 |
+
a network. This metric is also known as information centrality.
|
| 22 |
+
|
| 23 |
+
Parameters
|
| 24 |
+
----------
|
| 25 |
+
G : graph
|
| 26 |
+
A NetworkX graph.
|
| 27 |
+
|
| 28 |
+
weight : None or string, optional (default=None)
|
| 29 |
+
If None, all edge weights are considered equal.
|
| 30 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 31 |
+
The weight reflects the capacity or the strength of the
|
| 32 |
+
edge.
|
| 33 |
+
|
| 34 |
+
dtype: data type (default=float)
|
| 35 |
+
Default data type for internal matrices.
|
| 36 |
+
Set to np.float32 for lower memory consumption.
|
| 37 |
+
|
| 38 |
+
solver: string (default='lu')
|
| 39 |
+
Type of linear solver to use for computing the flow matrix.
|
| 40 |
+
Options are "full" (uses most memory), "lu" (recommended), and
|
| 41 |
+
"cg" (uses least memory).
|
| 42 |
+
|
| 43 |
+
Returns
|
| 44 |
+
-------
|
| 45 |
+
nodes : dictionary
|
| 46 |
+
Dictionary of nodes with current flow closeness centrality as the value.
|
| 47 |
+
|
| 48 |
+
See Also
|
| 49 |
+
--------
|
| 50 |
+
closeness_centrality
|
| 51 |
+
|
| 52 |
+
Notes
|
| 53 |
+
-----
|
| 54 |
+
The algorithm is from Brandes [1]_.
|
| 55 |
+
|
| 56 |
+
See also [2]_ for the original definition of information centrality.
|
| 57 |
+
|
| 58 |
+
References
|
| 59 |
+
----------
|
| 60 |
+
.. [1] Ulrik Brandes and Daniel Fleischer,
|
| 61 |
+
Centrality Measures Based on Current Flow.
|
| 62 |
+
Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
|
| 63 |
+
LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
|
| 64 |
+
https://doi.org/10.1007/978-3-540-31856-9_44
|
| 65 |
+
|
| 66 |
+
.. [2] Karen Stephenson and Marvin Zelen:
|
| 67 |
+
Rethinking centrality: Methods and examples.
|
| 68 |
+
Social Networks 11(1):1-37, 1989.
|
| 69 |
+
https://doi.org/10.1016/0378-8733(89)90016-6
|
| 70 |
+
"""
|
| 71 |
+
if not nx.is_connected(G):
|
| 72 |
+
raise nx.NetworkXError("Graph not connected.")
|
| 73 |
+
solvername = {
|
| 74 |
+
"full": FullInverseLaplacian,
|
| 75 |
+
"lu": SuperLUInverseLaplacian,
|
| 76 |
+
"cg": CGInverseLaplacian,
|
| 77 |
+
}
|
| 78 |
+
N = G.number_of_nodes()
|
| 79 |
+
ordering = list(reverse_cuthill_mckee_ordering(G))
|
| 80 |
+
# make a copy with integer labels according to rcm ordering
|
| 81 |
+
# this could be done without a copy if we really wanted to
|
| 82 |
+
H = nx.relabel_nodes(G, dict(zip(ordering, range(N))))
|
| 83 |
+
betweenness = dict.fromkeys(H, 0.0) # b[n]=0 for n in H
|
| 84 |
+
N = H.number_of_nodes()
|
| 85 |
+
L = nx.laplacian_matrix(H, nodelist=range(N), weight=weight).asformat("csc")
|
| 86 |
+
L = L.astype(dtype)
|
| 87 |
+
C2 = solvername[solver](L, width=1, dtype=dtype) # initialize solver
|
| 88 |
+
for v in H:
|
| 89 |
+
col = C2.get_row(v)
|
| 90 |
+
for w in H:
|
| 91 |
+
betweenness[v] += col.item(v) - 2 * col.item(w)
|
| 92 |
+
betweenness[w] += col.item(v)
|
| 93 |
+
return {ordering[node]: 1 / value for node, value in betweenness.items()}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
information_centrality = current_flow_closeness_centrality
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/degree_alg.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Degree centrality measures."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.utils.decorators import not_implemented_for
|
| 5 |
+
|
| 6 |
+
__all__ = ["degree_centrality", "in_degree_centrality", "out_degree_centrality"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@nx._dispatchable
|
| 10 |
+
def degree_centrality(G):
|
| 11 |
+
"""Compute the degree centrality for nodes.
|
| 12 |
+
|
| 13 |
+
The degree centrality for a node v is the fraction of nodes it
|
| 14 |
+
is connected to.
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
----------
|
| 18 |
+
G : graph
|
| 19 |
+
A networkx graph
|
| 20 |
+
|
| 21 |
+
Returns
|
| 22 |
+
-------
|
| 23 |
+
nodes : dictionary
|
| 24 |
+
Dictionary of nodes with degree centrality as the value.
|
| 25 |
+
|
| 26 |
+
Examples
|
| 27 |
+
--------
|
| 28 |
+
>>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
|
| 29 |
+
>>> nx.degree_centrality(G)
|
| 30 |
+
{0: 1.0, 1: 1.0, 2: 0.6666666666666666, 3: 0.6666666666666666}
|
| 31 |
+
|
| 32 |
+
See Also
|
| 33 |
+
--------
|
| 34 |
+
betweenness_centrality, load_centrality, eigenvector_centrality
|
| 35 |
+
|
| 36 |
+
Notes
|
| 37 |
+
-----
|
| 38 |
+
The degree centrality values are normalized by dividing by the maximum
|
| 39 |
+
possible degree in a simple graph n-1 where n is the number of nodes in G.
|
| 40 |
+
|
| 41 |
+
For multigraphs or graphs with self loops the maximum degree might
|
| 42 |
+
be higher than n-1 and values of degree centrality greater than 1
|
| 43 |
+
are possible.
|
| 44 |
+
"""
|
| 45 |
+
if len(G) <= 1:
|
| 46 |
+
return dict.fromkeys(G, 1)
|
| 47 |
+
|
| 48 |
+
s = 1.0 / (len(G) - 1.0)
|
| 49 |
+
centrality = {n: d * s for n, d in G.degree()}
|
| 50 |
+
return centrality
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@not_implemented_for("undirected")
|
| 54 |
+
@nx._dispatchable
|
| 55 |
+
def in_degree_centrality(G):
|
| 56 |
+
"""Compute the in-degree centrality for nodes.
|
| 57 |
+
|
| 58 |
+
The in-degree centrality for a node v is the fraction of nodes its
|
| 59 |
+
incoming edges are connected to.
|
| 60 |
+
|
| 61 |
+
Parameters
|
| 62 |
+
----------
|
| 63 |
+
G : graph
|
| 64 |
+
A NetworkX graph
|
| 65 |
+
|
| 66 |
+
Returns
|
| 67 |
+
-------
|
| 68 |
+
nodes : dictionary
|
| 69 |
+
Dictionary of nodes with in-degree centrality as values.
|
| 70 |
+
|
| 71 |
+
Raises
|
| 72 |
+
------
|
| 73 |
+
NetworkXNotImplemented
|
| 74 |
+
If G is undirected.
|
| 75 |
+
|
| 76 |
+
Examples
|
| 77 |
+
--------
|
| 78 |
+
>>> G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
|
| 79 |
+
>>> nx.in_degree_centrality(G)
|
| 80 |
+
{0: 0.0, 1: 0.3333333333333333, 2: 0.6666666666666666, 3: 0.6666666666666666}
|
| 81 |
+
|
| 82 |
+
See Also
|
| 83 |
+
--------
|
| 84 |
+
degree_centrality, out_degree_centrality
|
| 85 |
+
|
| 86 |
+
Notes
|
| 87 |
+
-----
|
| 88 |
+
The degree centrality values are normalized by dividing by the maximum
|
| 89 |
+
possible degree in a simple graph n-1 where n is the number of nodes in G.
|
| 90 |
+
|
| 91 |
+
For multigraphs or graphs with self loops the maximum degree might
|
| 92 |
+
be higher than n-1 and values of degree centrality greater than 1
|
| 93 |
+
are possible.
|
| 94 |
+
"""
|
| 95 |
+
if len(G) <= 1:
|
| 96 |
+
return dict.fromkeys(G, 1)
|
| 97 |
+
|
| 98 |
+
s = 1.0 / (len(G) - 1.0)
|
| 99 |
+
centrality = {n: d * s for n, d in G.in_degree()}
|
| 100 |
+
return centrality
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@not_implemented_for("undirected")
|
| 104 |
+
@nx._dispatchable
|
| 105 |
+
def out_degree_centrality(G):
|
| 106 |
+
"""Compute the out-degree centrality for nodes.
|
| 107 |
+
|
| 108 |
+
The out-degree centrality for a node v is the fraction of nodes its
|
| 109 |
+
outgoing edges are connected to.
|
| 110 |
+
|
| 111 |
+
Parameters
|
| 112 |
+
----------
|
| 113 |
+
G : graph
|
| 114 |
+
A NetworkX graph
|
| 115 |
+
|
| 116 |
+
Returns
|
| 117 |
+
-------
|
| 118 |
+
nodes : dictionary
|
| 119 |
+
Dictionary of nodes with out-degree centrality as values.
|
| 120 |
+
|
| 121 |
+
Raises
|
| 122 |
+
------
|
| 123 |
+
NetworkXNotImplemented
|
| 124 |
+
If G is undirected.
|
| 125 |
+
|
| 126 |
+
Examples
|
| 127 |
+
--------
|
| 128 |
+
>>> G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
|
| 129 |
+
>>> nx.out_degree_centrality(G)
|
| 130 |
+
{0: 1.0, 1: 0.6666666666666666, 2: 0.0, 3: 0.0}
|
| 131 |
+
|
| 132 |
+
See Also
|
| 133 |
+
--------
|
| 134 |
+
degree_centrality, in_degree_centrality
|
| 135 |
+
|
| 136 |
+
Notes
|
| 137 |
+
-----
|
| 138 |
+
The degree centrality values are normalized by dividing by the maximum
|
| 139 |
+
possible degree in a simple graph n-1 where n is the number of nodes in G.
|
| 140 |
+
|
| 141 |
+
For multigraphs or graphs with self loops the maximum degree might
|
| 142 |
+
be higher than n-1 and values of degree centrality greater than 1
|
| 143 |
+
are possible.
|
| 144 |
+
"""
|
| 145 |
+
if len(G) <= 1:
|
| 146 |
+
return dict.fromkeys(G, 1)
|
| 147 |
+
|
| 148 |
+
s = 1.0 / (len(G) - 1.0)
|
| 149 |
+
centrality = {n: d * s for n, d in G.out_degree()}
|
| 150 |
+
return centrality
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/dispersion.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import combinations
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = ["dispersion"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@nx._dispatchable
|
| 9 |
+
def dispersion(G, u=None, v=None, normalized=True, alpha=1.0, b=0.0, c=0.0):
|
| 10 |
+
r"""Calculate dispersion between `u` and `v` in `G`.
|
| 11 |
+
|
| 12 |
+
A link between two actors (`u` and `v`) has a high dispersion when their
|
| 13 |
+
mutual ties (`s` and `t`) are not well connected with each other.
|
| 14 |
+
|
| 15 |
+
Parameters
|
| 16 |
+
----------
|
| 17 |
+
G : graph
|
| 18 |
+
A NetworkX graph.
|
| 19 |
+
u : node, optional
|
| 20 |
+
The source for the dispersion score (e.g. ego node of the network).
|
| 21 |
+
v : node, optional
|
| 22 |
+
The target of the dispersion score if specified.
|
| 23 |
+
normalized : bool
|
| 24 |
+
If True (default) normalize by the embeddedness of the nodes (u and v).
|
| 25 |
+
alpha, b, c : float
|
| 26 |
+
Parameters for the normalization procedure. When `normalized` is True,
|
| 27 |
+
the dispersion value is normalized by::
|
| 28 |
+
|
| 29 |
+
result = ((dispersion + b) ** alpha) / (embeddedness + c)
|
| 30 |
+
|
| 31 |
+
as long as the denominator is nonzero.
|
| 32 |
+
|
| 33 |
+
Returns
|
| 34 |
+
-------
|
| 35 |
+
nodes : dictionary
|
| 36 |
+
If u (v) is specified, returns a dictionary of nodes with dispersion
|
| 37 |
+
score for all "target" ("source") nodes. If neither u nor v is
|
| 38 |
+
specified, returns a dictionary of dictionaries for all nodes 'u' in the
|
| 39 |
+
graph with a dispersion score for each node 'v'.
|
| 40 |
+
|
| 41 |
+
Notes
|
| 42 |
+
-----
|
| 43 |
+
This implementation follows Lars Backstrom and Jon Kleinberg [1]_. Typical
|
| 44 |
+
usage would be to run dispersion on the ego network $G_u$ if $u$ were
|
| 45 |
+
specified. Running :func:`dispersion` with neither $u$ nor $v$ specified
|
| 46 |
+
can take some time to complete.
|
| 47 |
+
|
| 48 |
+
References
|
| 49 |
+
----------
|
| 50 |
+
.. [1] Romantic Partnerships and the Dispersion of Social Ties:
|
| 51 |
+
A Network Analysis of Relationship Status on Facebook.
|
| 52 |
+
Lars Backstrom, Jon Kleinberg.
|
| 53 |
+
https://arxiv.org/pdf/1310.6753v1.pdf
|
| 54 |
+
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def _dispersion(G_u, u, v):
|
| 58 |
+
"""dispersion for all nodes 'v' in a ego network G_u of node 'u'"""
|
| 59 |
+
u_nbrs = set(G_u[u])
|
| 60 |
+
ST = {n for n in G_u[v] if n in u_nbrs}
|
| 61 |
+
set_uv = {u, v}
|
| 62 |
+
# all possible ties of connections that u and b share
|
| 63 |
+
possib = combinations(ST, 2)
|
| 64 |
+
total = 0
|
| 65 |
+
for s, t in possib:
|
| 66 |
+
# neighbors of s that are in G_u, not including u and v
|
| 67 |
+
nbrs_s = u_nbrs.intersection(G_u[s]) - set_uv
|
| 68 |
+
# s and t are not directly connected
|
| 69 |
+
if t not in nbrs_s:
|
| 70 |
+
# s and t do not share a connection
|
| 71 |
+
if nbrs_s.isdisjoint(G_u[t]):
|
| 72 |
+
# tick for disp(u, v)
|
| 73 |
+
total += 1
|
| 74 |
+
# neighbors that u and v share
|
| 75 |
+
embeddedness = len(ST)
|
| 76 |
+
|
| 77 |
+
dispersion_val = total
|
| 78 |
+
if normalized:
|
| 79 |
+
dispersion_val = (total + b) ** alpha
|
| 80 |
+
if embeddedness + c != 0:
|
| 81 |
+
dispersion_val /= embeddedness + c
|
| 82 |
+
|
| 83 |
+
return dispersion_val
|
| 84 |
+
|
| 85 |
+
if u is None:
|
| 86 |
+
# v and u are not specified
|
| 87 |
+
if v is None:
|
| 88 |
+
results = {n: {} for n in G}
|
| 89 |
+
for u in G:
|
| 90 |
+
for v in G[u]:
|
| 91 |
+
results[u][v] = _dispersion(G, u, v)
|
| 92 |
+
# u is not specified, but v is
|
| 93 |
+
else:
|
| 94 |
+
results = dict.fromkeys(G[v], {})
|
| 95 |
+
for u in G[v]:
|
| 96 |
+
results[u] = _dispersion(G, v, u)
|
| 97 |
+
else:
|
| 98 |
+
# u is specified with no target v
|
| 99 |
+
if v is None:
|
| 100 |
+
results = dict.fromkeys(G[u], {})
|
| 101 |
+
for v in G[u]:
|
| 102 |
+
results[v] = _dispersion(G, u, v)
|
| 103 |
+
# both u and v are specified
|
| 104 |
+
else:
|
| 105 |
+
results = _dispersion(G, u, v)
|
| 106 |
+
|
| 107 |
+
return results
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/eigenvector.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for computing eigenvector centrality."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = ["eigenvector_centrality", "eigenvector_centrality_numpy"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@not_implemented_for("multigraph")
|
| 12 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 13 |
+
def eigenvector_centrality(G, max_iter=100, tol=1.0e-6, nstart=None, weight=None):
|
| 14 |
+
r"""Compute the eigenvector centrality for the graph G.
|
| 15 |
+
|
| 16 |
+
Eigenvector centrality computes the centrality for a node by adding
|
| 17 |
+
the centrality of its predecessors. The centrality for node $i$ is the
|
| 18 |
+
$i$-th element of a left eigenvector associated with the eigenvalue $\lambda$
|
| 19 |
+
of maximum modulus that is positive. Such an eigenvector $x$ is
|
| 20 |
+
defined up to a multiplicative constant by the equation
|
| 21 |
+
|
| 22 |
+
.. math::
|
| 23 |
+
|
| 24 |
+
\lambda x^T = x^T A,
|
| 25 |
+
|
| 26 |
+
where $A$ is the adjacency matrix of the graph G. By definition of
|
| 27 |
+
row-column product, the equation above is equivalent to
|
| 28 |
+
|
| 29 |
+
.. math::
|
| 30 |
+
|
| 31 |
+
\lambda x_i = \sum_{j\to i}x_j.
|
| 32 |
+
|
| 33 |
+
That is, adding the eigenvector centralities of the predecessors of
|
| 34 |
+
$i$ one obtains the eigenvector centrality of $i$ multiplied by
|
| 35 |
+
$\lambda$. In the case of undirected graphs, $x$ also solves the familiar
|
| 36 |
+
right-eigenvector equation $Ax = \lambda x$.
|
| 37 |
+
|
| 38 |
+
By virtue of the Perron–Frobenius theorem [1]_, if G is strongly
|
| 39 |
+
connected there is a unique eigenvector $x$, and all its entries
|
| 40 |
+
are strictly positive.
|
| 41 |
+
|
| 42 |
+
If G is not strongly connected there might be several left
|
| 43 |
+
eigenvectors associated with $\lambda$, and some of their elements
|
| 44 |
+
might be zero.
|
| 45 |
+
|
| 46 |
+
Parameters
|
| 47 |
+
----------
|
| 48 |
+
G : graph
|
| 49 |
+
A networkx graph.
|
| 50 |
+
|
| 51 |
+
max_iter : integer, optional (default=100)
|
| 52 |
+
Maximum number of power iterations.
|
| 53 |
+
|
| 54 |
+
tol : float, optional (default=1.0e-6)
|
| 55 |
+
Error tolerance (in Euclidean norm) used to check convergence in
|
| 56 |
+
power iteration.
|
| 57 |
+
|
| 58 |
+
nstart : dictionary, optional (default=None)
|
| 59 |
+
Starting value of power iteration for each node. Must have a nonzero
|
| 60 |
+
projection on the desired eigenvector for the power method to converge.
|
| 61 |
+
If None, this implementation uses an all-ones vector, which is a safe
|
| 62 |
+
choice.
|
| 63 |
+
|
| 64 |
+
weight : None or string, optional (default=None)
|
| 65 |
+
If None, all edge weights are considered equal. Otherwise holds the
|
| 66 |
+
name of the edge attribute used as weight. In this measure the
|
| 67 |
+
weight is interpreted as the connection strength.
|
| 68 |
+
|
| 69 |
+
Returns
|
| 70 |
+
-------
|
| 71 |
+
nodes : dictionary
|
| 72 |
+
Dictionary of nodes with eigenvector centrality as the value. The
|
| 73 |
+
associated vector has unit Euclidean norm and the values are
|
| 74 |
+
nonegative.
|
| 75 |
+
|
| 76 |
+
Examples
|
| 77 |
+
--------
|
| 78 |
+
>>> G = nx.path_graph(4)
|
| 79 |
+
>>> centrality = nx.eigenvector_centrality(G)
|
| 80 |
+
>>> sorted((v, f"{c:0.2f}") for v, c in centrality.items())
|
| 81 |
+
[(0, '0.37'), (1, '0.60'), (2, '0.60'), (3, '0.37')]
|
| 82 |
+
|
| 83 |
+
Raises
|
| 84 |
+
------
|
| 85 |
+
NetworkXPointlessConcept
|
| 86 |
+
If the graph G is the null graph.
|
| 87 |
+
|
| 88 |
+
NetworkXError
|
| 89 |
+
If each value in `nstart` is zero.
|
| 90 |
+
|
| 91 |
+
PowerIterationFailedConvergence
|
| 92 |
+
If the algorithm fails to converge to the specified tolerance
|
| 93 |
+
within the specified number of iterations of the power iteration
|
| 94 |
+
method.
|
| 95 |
+
|
| 96 |
+
See Also
|
| 97 |
+
--------
|
| 98 |
+
eigenvector_centrality_numpy
|
| 99 |
+
:func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
|
| 100 |
+
:func:`~networkx.algorithms.link_analysis.hits_alg.hits`
|
| 101 |
+
|
| 102 |
+
Notes
|
| 103 |
+
-----
|
| 104 |
+
Eigenvector centrality was introduced by Landau [2]_ for chess
|
| 105 |
+
tournaments. It was later rediscovered by Wei [3]_ and then
|
| 106 |
+
popularized by Kendall [4]_ in the context of sport ranking. Berge
|
| 107 |
+
introduced a general definition for graphs based on social connections
|
| 108 |
+
[5]_. Bonacich [6]_ reintroduced again eigenvector centrality and made
|
| 109 |
+
it popular in link analysis.
|
| 110 |
+
|
| 111 |
+
This function computes the left dominant eigenvector, which corresponds
|
| 112 |
+
to adding the centrality of predecessors: this is the usual approach.
|
| 113 |
+
To add the centrality of successors first reverse the graph with
|
| 114 |
+
``G.reverse()``.
|
| 115 |
+
|
| 116 |
+
The implementation uses power iteration [7]_ to compute a dominant
|
| 117 |
+
eigenvector starting from the provided vector `nstart`. Convergence is
|
| 118 |
+
guaranteed as long as `nstart` has a nonzero projection on a dominant
|
| 119 |
+
eigenvector, which certainly happens using the default value.
|
| 120 |
+
|
| 121 |
+
The method stops when the change in the computed vector between two
|
| 122 |
+
iterations is smaller than an error tolerance of ``G.number_of_nodes()
|
| 123 |
+
* tol`` or after ``max_iter`` iterations, but in the second case it
|
| 124 |
+
raises an exception.
|
| 125 |
+
|
| 126 |
+
This implementation uses $(A + I)$ rather than the adjacency matrix
|
| 127 |
+
$A$ because the change preserves eigenvectors, but it shifts the
|
| 128 |
+
spectrum, thus guaranteeing convergence even for networks with
|
| 129 |
+
negative eigenvalues of maximum modulus.
|
| 130 |
+
|
| 131 |
+
References
|
| 132 |
+
----------
|
| 133 |
+
.. [1] Abraham Berman and Robert J. Plemmons.
|
| 134 |
+
"Nonnegative Matrices in the Mathematical Sciences."
|
| 135 |
+
Classics in Applied Mathematics. SIAM, 1994.
|
| 136 |
+
|
| 137 |
+
.. [2] Edmund Landau.
|
| 138 |
+
"Zur relativen Wertbemessung der Turnierresultate."
|
| 139 |
+
Deutsches Wochenschach, 11:366–369, 1895.
|
| 140 |
+
|
| 141 |
+
.. [3] Teh-Hsing Wei.
|
| 142 |
+
"The Algebraic Foundations of Ranking Theory."
|
| 143 |
+
PhD thesis, University of Cambridge, 1952.
|
| 144 |
+
|
| 145 |
+
.. [4] Maurice G. Kendall.
|
| 146 |
+
"Further contributions to the theory of paired comparisons."
|
| 147 |
+
Biometrics, 11(1):43–62, 1955.
|
| 148 |
+
https://www.jstor.org/stable/3001479
|
| 149 |
+
|
| 150 |
+
.. [5] Claude Berge
|
| 151 |
+
"Théorie des graphes et ses applications."
|
| 152 |
+
Dunod, Paris, France, 1958.
|
| 153 |
+
|
| 154 |
+
.. [6] Phillip Bonacich.
|
| 155 |
+
"Technique for analyzing overlapping memberships."
|
| 156 |
+
Sociological Methodology, 4:176–185, 1972.
|
| 157 |
+
https://www.jstor.org/stable/270732
|
| 158 |
+
|
| 159 |
+
.. [7] Power iteration:: https://en.wikipedia.org/wiki/Power_iteration
|
| 160 |
+
|
| 161 |
+
"""
|
| 162 |
+
if len(G) == 0:
|
| 163 |
+
raise nx.NetworkXPointlessConcept(
|
| 164 |
+
"cannot compute centrality for the null graph"
|
| 165 |
+
)
|
| 166 |
+
# If no initial vector is provided, start with the all-ones vector.
|
| 167 |
+
if nstart is None:
|
| 168 |
+
nstart = dict.fromkeys(G, 1)
|
| 169 |
+
if all(v == 0 for v in nstart.values()):
|
| 170 |
+
raise nx.NetworkXError("initial vector cannot have all zero values")
|
| 171 |
+
# Normalize the initial vector so that each entry is in [0, 1]. This is
|
| 172 |
+
# guaranteed to never have a divide-by-zero error by the previous line.
|
| 173 |
+
nstart_sum = sum(nstart.values())
|
| 174 |
+
x = {k: v / nstart_sum for k, v in nstart.items()}
|
| 175 |
+
nnodes = G.number_of_nodes()
|
| 176 |
+
# make up to max_iter iterations
|
| 177 |
+
for _ in range(max_iter):
|
| 178 |
+
xlast = x
|
| 179 |
+
x = xlast.copy() # Start with xlast times I to iterate with (A+I)
|
| 180 |
+
# do the multiplication y^T = x^T A (left eigenvector)
|
| 181 |
+
for n in x:
|
| 182 |
+
for nbr in G[n]:
|
| 183 |
+
w = G[n][nbr].get(weight, 1) if weight else 1
|
| 184 |
+
x[nbr] += xlast[n] * w
|
| 185 |
+
# Normalize the vector. The normalization denominator `norm`
|
| 186 |
+
# should never be zero by the Perron--Frobenius
|
| 187 |
+
# theorem. However, in case it is due to numerical error, we
|
| 188 |
+
# assume the norm to be one instead.
|
| 189 |
+
norm = math.hypot(*x.values()) or 1
|
| 190 |
+
x = {k: v / norm for k, v in x.items()}
|
| 191 |
+
# Check for convergence (in the L_1 norm).
|
| 192 |
+
if sum(abs(x[n] - xlast[n]) for n in x) < nnodes * tol:
|
| 193 |
+
return x
|
| 194 |
+
raise nx.PowerIterationFailedConvergence(max_iter)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 198 |
+
def eigenvector_centrality_numpy(G, weight=None, max_iter=50, tol=0):
|
| 199 |
+
r"""Compute the eigenvector centrality for the graph `G`.
|
| 200 |
+
|
| 201 |
+
Eigenvector centrality computes the centrality for a node by adding
|
| 202 |
+
the centrality of its predecessors. The centrality for node $i$ is the
|
| 203 |
+
$i$-th element of a left eigenvector associated with the eigenvalue $\lambda$
|
| 204 |
+
of maximum modulus that is positive. Such an eigenvector $x$ is
|
| 205 |
+
defined up to a multiplicative constant by the equation
|
| 206 |
+
|
| 207 |
+
.. math::
|
| 208 |
+
|
| 209 |
+
\lambda x^T = x^T A,
|
| 210 |
+
|
| 211 |
+
where $A$ is the adjacency matrix of the graph `G`. By definition of
|
| 212 |
+
row-column product, the equation above is equivalent to
|
| 213 |
+
|
| 214 |
+
.. math::
|
| 215 |
+
|
| 216 |
+
\lambda x_i = \sum_{j\to i}x_j.
|
| 217 |
+
|
| 218 |
+
That is, adding the eigenvector centralities of the predecessors of
|
| 219 |
+
$i$ one obtains the eigenvector centrality of $i$ multiplied by
|
| 220 |
+
$\lambda$. In the case of undirected graphs, $x$ also solves the familiar
|
| 221 |
+
right-eigenvector equation $Ax = \lambda x$.
|
| 222 |
+
|
| 223 |
+
By virtue of the Perron--Frobenius theorem [1]_, if `G` is (strongly)
|
| 224 |
+
connected, there is a unique eigenvector $x$, and all its entries
|
| 225 |
+
are strictly positive.
|
| 226 |
+
|
| 227 |
+
However, if `G` is not (strongly) connected, there might be several left
|
| 228 |
+
eigenvectors associated with $\lambda$, and some of their elements
|
| 229 |
+
might be zero.
|
| 230 |
+
Depending on the method used to choose eigenvectors, round-off error can affect
|
| 231 |
+
which of the infinitely many eigenvectors is reported.
|
| 232 |
+
This can lead to inconsistent results for the same graph,
|
| 233 |
+
which the underlying implementation is not robust to.
|
| 234 |
+
For this reason, only (strongly) connected graphs are accepted.
|
| 235 |
+
|
| 236 |
+
Parameters
|
| 237 |
+
----------
|
| 238 |
+
G : graph
|
| 239 |
+
A connected NetworkX graph.
|
| 240 |
+
|
| 241 |
+
weight : None or string, optional (default=None)
|
| 242 |
+
If ``None``, all edge weights are considered equal. Otherwise holds the
|
| 243 |
+
name of the edge attribute used as weight. In this measure the
|
| 244 |
+
weight is interpreted as the connection strength.
|
| 245 |
+
|
| 246 |
+
max_iter : integer, optional (default=50)
|
| 247 |
+
Maximum number of Arnoldi update iterations allowed.
|
| 248 |
+
|
| 249 |
+
tol : float, optional (default=0)
|
| 250 |
+
Relative accuracy for eigenvalues (stopping criterion).
|
| 251 |
+
The default value of 0 implies machine precision.
|
| 252 |
+
|
| 253 |
+
Returns
|
| 254 |
+
-------
|
| 255 |
+
nodes : dict of nodes
|
| 256 |
+
Dictionary of nodes with eigenvector centrality as the value. The
|
| 257 |
+
associated vector has unit Euclidean norm and the values are
|
| 258 |
+
nonnegative.
|
| 259 |
+
|
| 260 |
+
Examples
|
| 261 |
+
--------
|
| 262 |
+
>>> G = nx.path_graph(4)
|
| 263 |
+
>>> centrality = nx.eigenvector_centrality_numpy(G)
|
| 264 |
+
>>> print([f"{node} {centrality[node]:0.2f}" for node in centrality])
|
| 265 |
+
['0 0.37', '1 0.60', '2 0.60', '3 0.37']
|
| 266 |
+
|
| 267 |
+
Raises
|
| 268 |
+
------
|
| 269 |
+
NetworkXPointlessConcept
|
| 270 |
+
If the graph `G` is the null graph.
|
| 271 |
+
|
| 272 |
+
ArpackNoConvergence
|
| 273 |
+
When the requested convergence is not obtained. The currently
|
| 274 |
+
converged eigenvalues and eigenvectors can be found as
|
| 275 |
+
eigenvalues and eigenvectors attributes of the exception object.
|
| 276 |
+
|
| 277 |
+
AmbiguousSolution
|
| 278 |
+
If `G` is not connected.
|
| 279 |
+
|
| 280 |
+
See Also
|
| 281 |
+
--------
|
| 282 |
+
:func:`scipy.sparse.linalg.eigs`
|
| 283 |
+
eigenvector_centrality
|
| 284 |
+
:func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
|
| 285 |
+
:func:`~networkx.algorithms.link_analysis.hits_alg.hits`
|
| 286 |
+
|
| 287 |
+
Notes
|
| 288 |
+
-----
|
| 289 |
+
Eigenvector centrality was introduced by Landau [2]_ for chess
|
| 290 |
+
tournaments. It was later rediscovered by Wei [3]_ and then
|
| 291 |
+
popularized by Kendall [4]_ in the context of sport ranking. Berge
|
| 292 |
+
introduced a general definition for graphs based on social connections
|
| 293 |
+
[5]_. Bonacich [6]_ reintroduced again eigenvector centrality and made
|
| 294 |
+
it popular in link analysis.
|
| 295 |
+
|
| 296 |
+
This function computes the left dominant eigenvector, which corresponds
|
| 297 |
+
to adding the centrality of predecessors: this is the usual approach.
|
| 298 |
+
To add the centrality of successors first reverse the graph with
|
| 299 |
+
``G.reverse()``.
|
| 300 |
+
|
| 301 |
+
This implementation uses the
|
| 302 |
+
:func:`SciPy sparse eigenvalue solver<scipy.sparse.linalg.eigs>` (ARPACK)
|
| 303 |
+
to find the largest eigenvalue/eigenvector pair using Arnoldi iterations
|
| 304 |
+
[7]_.
|
| 305 |
+
|
| 306 |
+
References
|
| 307 |
+
----------
|
| 308 |
+
.. [1] Abraham Berman and Robert J. Plemmons.
|
| 309 |
+
"Nonnegative Matrices in the Mathematical Sciences".
|
| 310 |
+
Classics in Applied Mathematics. SIAM, 1994.
|
| 311 |
+
|
| 312 |
+
.. [2] Edmund Landau.
|
| 313 |
+
"Zur relativen Wertbemessung der Turnierresultate".
|
| 314 |
+
Deutsches Wochenschach, 11:366--369, 1895.
|
| 315 |
+
|
| 316 |
+
.. [3] Teh-Hsing Wei.
|
| 317 |
+
"The Algebraic Foundations of Ranking Theory".
|
| 318 |
+
PhD thesis, University of Cambridge, 1952.
|
| 319 |
+
|
| 320 |
+
.. [4] Maurice G. Kendall.
|
| 321 |
+
"Further contributions to the theory of paired comparisons".
|
| 322 |
+
Biometrics, 11(1):43--62, 1955.
|
| 323 |
+
https://www.jstor.org/stable/3001479
|
| 324 |
+
|
| 325 |
+
.. [5] Claude Berge.
|
| 326 |
+
"Théorie des graphes et ses applications".
|
| 327 |
+
Dunod, Paris, France, 1958.
|
| 328 |
+
|
| 329 |
+
.. [6] Phillip Bonacich.
|
| 330 |
+
"Technique for analyzing overlapping memberships".
|
| 331 |
+
Sociological Methodology, 4:176--185, 1972.
|
| 332 |
+
https://www.jstor.org/stable/270732
|
| 333 |
+
|
| 334 |
+
.. [7] Arnoldi, W. E. (1951).
|
| 335 |
+
"The principle of minimized iterations in the solution of the matrix eigenvalue problem".
|
| 336 |
+
Quarterly of Applied Mathematics. 9 (1): 17--29.
|
| 337 |
+
https://doi.org/10.1090/qam/42792
|
| 338 |
+
"""
|
| 339 |
+
import numpy as np
|
| 340 |
+
import scipy as sp
|
| 341 |
+
|
| 342 |
+
if len(G) == 0:
|
| 343 |
+
raise nx.NetworkXPointlessConcept(
|
| 344 |
+
"cannot compute centrality for the null graph"
|
| 345 |
+
)
|
| 346 |
+
connected = nx.is_strongly_connected(G) if G.is_directed() else nx.is_connected(G)
|
| 347 |
+
if not connected: # See gh-6888.
|
| 348 |
+
raise nx.AmbiguousSolution(
|
| 349 |
+
"`eigenvector_centrality_numpy` does not give consistent results for disconnected graphs"
|
| 350 |
+
)
|
| 351 |
+
M = nx.to_scipy_sparse_array(G, nodelist=list(G), weight=weight, dtype=float)
|
| 352 |
+
_, eigenvector = sp.sparse.linalg.eigs(
|
| 353 |
+
M.T, k=1, which="LR", maxiter=max_iter, tol=tol
|
| 354 |
+
)
|
| 355 |
+
largest = eigenvector.flatten().real
|
| 356 |
+
norm = np.sign(largest.sum()) * sp.linalg.norm(largest)
|
| 357 |
+
return dict(zip(G, (largest / norm).tolist()))
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/flow_matrix.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Helpers for current-flow betweenness and current-flow closeness
|
| 2 |
+
# Lazy computations for inverse Laplacian and flow-matrix rows.
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 7 |
+
def flow_matrix_row(G, weight=None, dtype=float, solver="lu"):
|
| 8 |
+
# Generate a row of the current-flow matrix
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
solvername = {
|
| 12 |
+
"full": FullInverseLaplacian,
|
| 13 |
+
"lu": SuperLUInverseLaplacian,
|
| 14 |
+
"cg": CGInverseLaplacian,
|
| 15 |
+
}
|
| 16 |
+
n = G.number_of_nodes()
|
| 17 |
+
L = nx.laplacian_matrix(G, nodelist=range(n), weight=weight).asformat("csc")
|
| 18 |
+
L = L.astype(dtype)
|
| 19 |
+
C = solvername[solver](L, dtype=dtype) # initialize solver
|
| 20 |
+
w = C.w # w is the Laplacian matrix width
|
| 21 |
+
# row-by-row flow matrix
|
| 22 |
+
for u, v in sorted(sorted((u, v)) for u, v in G.edges()):
|
| 23 |
+
B = np.zeros(w, dtype=dtype)
|
| 24 |
+
c = G[u][v].get(weight, 1.0)
|
| 25 |
+
B[u % w] = c
|
| 26 |
+
B[v % w] = -c
|
| 27 |
+
# get only the rows needed in the inverse laplacian
|
| 28 |
+
# and multiply to get the flow matrix row
|
| 29 |
+
row = B @ C.get_rows(u, v)
|
| 30 |
+
yield row, (u, v)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# Class to compute the inverse laplacian only for specified rows
|
| 34 |
+
# Allows computation of the current-flow matrix without storing entire
|
| 35 |
+
# inverse laplacian matrix
|
| 36 |
+
class InverseLaplacian:
|
| 37 |
+
def __init__(self, L, width=None, dtype=None):
|
| 38 |
+
global np
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
(n, n) = L.shape
|
| 42 |
+
self.dtype = dtype
|
| 43 |
+
self.n = n
|
| 44 |
+
if width is None:
|
| 45 |
+
self.w = self.width(L)
|
| 46 |
+
else:
|
| 47 |
+
self.w = width
|
| 48 |
+
self.C = np.zeros((self.w, n), dtype=dtype)
|
| 49 |
+
self.L1 = L[1:, 1:]
|
| 50 |
+
self.init_solver(L)
|
| 51 |
+
|
| 52 |
+
def init_solver(self, L):
|
| 53 |
+
pass
|
| 54 |
+
|
| 55 |
+
def solve(self, r):
|
| 56 |
+
raise nx.NetworkXError("Implement solver")
|
| 57 |
+
|
| 58 |
+
def solve_inverse(self, r):
|
| 59 |
+
raise nx.NetworkXError("Implement solver")
|
| 60 |
+
|
| 61 |
+
def get_rows(self, r1, r2):
|
| 62 |
+
for r in range(r1, r2 + 1):
|
| 63 |
+
self.C[r % self.w, 1:] = self.solve_inverse(r)
|
| 64 |
+
return self.C
|
| 65 |
+
|
| 66 |
+
def get_row(self, r):
|
| 67 |
+
self.C[r % self.w, 1:] = self.solve_inverse(r)
|
| 68 |
+
return self.C[r % self.w]
|
| 69 |
+
|
| 70 |
+
def width(self, L):
|
| 71 |
+
m = 0
|
| 72 |
+
for i, row in enumerate(L):
|
| 73 |
+
w = 0
|
| 74 |
+
y = np.nonzero(row)[-1]
|
| 75 |
+
if len(y) > 0:
|
| 76 |
+
v = y - i
|
| 77 |
+
w = v.max() - v.min() + 1
|
| 78 |
+
m = max(w, m)
|
| 79 |
+
return m
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class FullInverseLaplacian(InverseLaplacian):
|
| 83 |
+
def init_solver(self, L):
|
| 84 |
+
self.IL = np.zeros(L.shape, dtype=self.dtype)
|
| 85 |
+
self.IL[1:, 1:] = np.linalg.inv(self.L1.todense())
|
| 86 |
+
|
| 87 |
+
def solve(self, rhs):
|
| 88 |
+
s = np.zeros(rhs.shape, dtype=self.dtype)
|
| 89 |
+
s = self.IL @ rhs
|
| 90 |
+
return s
|
| 91 |
+
|
| 92 |
+
def solve_inverse(self, r):
|
| 93 |
+
return self.IL[r, 1:]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class SuperLUInverseLaplacian(InverseLaplacian):
|
| 97 |
+
def init_solver(self, L):
|
| 98 |
+
import scipy as sp
|
| 99 |
+
|
| 100 |
+
self.lusolve = sp.sparse.linalg.factorized(self.L1.tocsc())
|
| 101 |
+
|
| 102 |
+
def solve_inverse(self, r):
|
| 103 |
+
rhs = np.zeros(self.n, dtype=self.dtype)
|
| 104 |
+
rhs[r] = 1
|
| 105 |
+
return self.lusolve(rhs[1:])
|
| 106 |
+
|
| 107 |
+
def solve(self, rhs):
|
| 108 |
+
s = np.zeros(rhs.shape, dtype=self.dtype)
|
| 109 |
+
s[1:] = self.lusolve(rhs[1:])
|
| 110 |
+
return s
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class CGInverseLaplacian(InverseLaplacian):
|
| 114 |
+
def init_solver(self, L):
|
| 115 |
+
global sp
|
| 116 |
+
import scipy as sp
|
| 117 |
+
|
| 118 |
+
ilu = sp.sparse.linalg.spilu(self.L1.tocsc())
|
| 119 |
+
n = self.n - 1
|
| 120 |
+
self.M = sp.sparse.linalg.LinearOperator(shape=(n, n), matvec=ilu.solve)
|
| 121 |
+
|
| 122 |
+
def solve(self, rhs):
|
| 123 |
+
s = np.zeros(rhs.shape, dtype=self.dtype)
|
| 124 |
+
s[1:] = sp.sparse.linalg.cg(self.L1, rhs[1:], M=self.M, atol=0)[0]
|
| 125 |
+
return s
|
| 126 |
+
|
| 127 |
+
def solve_inverse(self, r):
|
| 128 |
+
rhs = np.zeros(self.n, self.dtype)
|
| 129 |
+
rhs[r] = 1
|
| 130 |
+
return sp.sparse.linalg.cg(self.L1, rhs[1:], M=self.M, atol=0)[0]
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/group.py
ADDED
|
@@ -0,0 +1,787 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Group centrality measures."""
|
| 2 |
+
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.algorithms.centrality.betweenness import (
|
| 7 |
+
_accumulate_endpoints,
|
| 8 |
+
_single_source_dijkstra_path_basic,
|
| 9 |
+
_single_source_shortest_path_basic,
|
| 10 |
+
)
|
| 11 |
+
from networkx.utils.decorators import not_implemented_for
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
"group_betweenness_centrality",
|
| 15 |
+
"group_closeness_centrality",
|
| 16 |
+
"group_degree_centrality",
|
| 17 |
+
"group_in_degree_centrality",
|
| 18 |
+
"group_out_degree_centrality",
|
| 19 |
+
"prominent_group",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 24 |
+
def group_betweenness_centrality(G, C, normalized=True, weight=None, endpoints=False):
|
| 25 |
+
r"""Compute the group betweenness centrality for a group of nodes.
|
| 26 |
+
|
| 27 |
+
Group betweenness centrality of a group of nodes $C$ is the sum of the
|
| 28 |
+
fraction of all-pairs shortest paths that pass through any vertex in $C$
|
| 29 |
+
|
| 30 |
+
.. math::
|
| 31 |
+
|
| 32 |
+
c_B(v) =\sum_{s,t \in V} \frac{\sigma(s, t|v)}{\sigma(s, t)}
|
| 33 |
+
|
| 34 |
+
where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
|
| 35 |
+
shortest $(s, t)$-paths, and $\sigma(s, t|C)$ is the number of
|
| 36 |
+
those paths passing through some node in group $C$. Note that
|
| 37 |
+
$(s, t)$ are not members of the group ($V-C$ is the set of nodes
|
| 38 |
+
in $V$ that are not in $C$).
|
| 39 |
+
|
| 40 |
+
Parameters
|
| 41 |
+
----------
|
| 42 |
+
G : graph
|
| 43 |
+
A NetworkX graph.
|
| 44 |
+
|
| 45 |
+
C : list or set or list of lists or list of sets
|
| 46 |
+
A group or a list of groups containing nodes which belong to G, for which group betweenness
|
| 47 |
+
centrality is to be calculated.
|
| 48 |
+
|
| 49 |
+
normalized : bool, optional (default=True)
|
| 50 |
+
If True, group betweenness is normalized by `1/((|V|-|C|)(|V|-|C|-1))`
|
| 51 |
+
where `|V|` is the number of nodes in G and `|C|` is the number of nodes in C.
|
| 52 |
+
|
| 53 |
+
weight : None or string, optional (default=None)
|
| 54 |
+
If None, all edge weights are considered equal.
|
| 55 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 56 |
+
The weight of an edge is treated as the length or distance between the two sides.
|
| 57 |
+
|
| 58 |
+
endpoints : bool, optional (default=False)
|
| 59 |
+
If True include the endpoints in the shortest path counts.
|
| 60 |
+
|
| 61 |
+
Raises
|
| 62 |
+
------
|
| 63 |
+
NodeNotFound
|
| 64 |
+
If node(s) in C are not present in G.
|
| 65 |
+
|
| 66 |
+
Returns
|
| 67 |
+
-------
|
| 68 |
+
betweenness : list of floats or float
|
| 69 |
+
If C is a single group then return a float. If C is a list with
|
| 70 |
+
several groups then return a list of group betweenness centralities.
|
| 71 |
+
|
| 72 |
+
See Also
|
| 73 |
+
--------
|
| 74 |
+
betweenness_centrality
|
| 75 |
+
|
| 76 |
+
Notes
|
| 77 |
+
-----
|
| 78 |
+
Group betweenness centrality is described in [1]_ and its importance discussed in [3]_.
|
| 79 |
+
The initial implementation of the algorithm is mentioned in [2]_. This function uses
|
| 80 |
+
an improved algorithm presented in [4]_.
|
| 81 |
+
|
| 82 |
+
The number of nodes in the group must be a maximum of n - 2 where `n`
|
| 83 |
+
is the total number of nodes in the graph.
|
| 84 |
+
|
| 85 |
+
For weighted graphs the edge weights must be greater than zero.
|
| 86 |
+
Zero edge weights can produce an infinite number of equal length
|
| 87 |
+
paths between pairs of nodes.
|
| 88 |
+
|
| 89 |
+
The total number of paths between source and target is counted
|
| 90 |
+
differently for directed and undirected graphs. Directed paths
|
| 91 |
+
between "u" and "v" are counted as two possible paths (one each
|
| 92 |
+
direction) while undirected paths between "u" and "v" are counted
|
| 93 |
+
as one path. Said another way, the sum in the expression above is
|
| 94 |
+
over all ``s != t`` for directed graphs and for ``s < t`` for undirected graphs.
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
References
|
| 98 |
+
----------
|
| 99 |
+
.. [1] M G Everett and S P Borgatti:
|
| 100 |
+
The Centrality of Groups and Classes.
|
| 101 |
+
Journal of Mathematical Sociology. 23(3): 181-201. 1999.
|
| 102 |
+
http://www.analytictech.com/borgatti/group_centrality.htm
|
| 103 |
+
.. [2] Ulrik Brandes:
|
| 104 |
+
On Variants of Shortest-Path Betweenness
|
| 105 |
+
Centrality and their Generic Computation.
|
| 106 |
+
Social Networks 30(2):136-145, 2008.
|
| 107 |
+
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.72.9610&rep=rep1&type=pdf
|
| 108 |
+
.. [3] Sourav Medya et. al.:
|
| 109 |
+
Group Centrality Maximization via Network Design.
|
| 110 |
+
SIAM International Conference on Data Mining, SDM 2018, 126–134.
|
| 111 |
+
https://sites.cs.ucsb.edu/~arlei/pubs/sdm18.pdf
|
| 112 |
+
.. [4] Rami Puzis, Yuval Elovici, and Shlomi Dolev.
|
| 113 |
+
"Fast algorithm for successive computation of group betweenness centrality."
|
| 114 |
+
https://journals.aps.org/pre/pdf/10.1103/PhysRevE.76.056709
|
| 115 |
+
|
| 116 |
+
"""
|
| 117 |
+
GBC = [] # initialize betweenness
|
| 118 |
+
list_of_groups = True
|
| 119 |
+
# check weather C contains one or many groups
|
| 120 |
+
if any(el in G for el in C):
|
| 121 |
+
C = [C]
|
| 122 |
+
list_of_groups = False
|
| 123 |
+
set_v = {node for group in C for node in group}
|
| 124 |
+
if set_v - G.nodes: # element(s) of C not in G
|
| 125 |
+
raise nx.NodeNotFound(f"The node(s) {set_v - G.nodes} are in C but not in G.")
|
| 126 |
+
|
| 127 |
+
# pre-processing
|
| 128 |
+
PB, sigma, D = _group_preprocessing(G, set_v, weight)
|
| 129 |
+
|
| 130 |
+
# the algorithm for each group
|
| 131 |
+
for group in C:
|
| 132 |
+
group = set(group) # set of nodes in group
|
| 133 |
+
# initialize the matrices of the sigma and the PB
|
| 134 |
+
GBC_group = 0
|
| 135 |
+
sigma_m = deepcopy(sigma)
|
| 136 |
+
PB_m = deepcopy(PB)
|
| 137 |
+
sigma_m_v = deepcopy(sigma_m)
|
| 138 |
+
PB_m_v = deepcopy(PB_m)
|
| 139 |
+
for v in group:
|
| 140 |
+
GBC_group += PB_m[v][v]
|
| 141 |
+
for x in group:
|
| 142 |
+
for y in group:
|
| 143 |
+
dxvy = 0
|
| 144 |
+
dxyv = 0
|
| 145 |
+
dvxy = 0
|
| 146 |
+
if not (
|
| 147 |
+
sigma_m[x][y] == 0 or sigma_m[x][v] == 0 or sigma_m[v][y] == 0
|
| 148 |
+
):
|
| 149 |
+
if D[x][v] == D[x][y] + D[y][v]:
|
| 150 |
+
dxyv = sigma_m[x][y] * sigma_m[y][v] / sigma_m[x][v]
|
| 151 |
+
if D[x][y] == D[x][v] + D[v][y]:
|
| 152 |
+
dxvy = sigma_m[x][v] * sigma_m[v][y] / sigma_m[x][y]
|
| 153 |
+
if D[v][y] == D[v][x] + D[x][y]:
|
| 154 |
+
dvxy = sigma_m[v][x] * sigma[x][y] / sigma[v][y]
|
| 155 |
+
sigma_m_v[x][y] = sigma_m[x][y] * (1 - dxvy)
|
| 156 |
+
PB_m_v[x][y] = PB_m[x][y] - PB_m[x][y] * dxvy
|
| 157 |
+
if y != v:
|
| 158 |
+
PB_m_v[x][y] -= PB_m[x][v] * dxyv
|
| 159 |
+
if x != v:
|
| 160 |
+
PB_m_v[x][y] -= PB_m[v][y] * dvxy
|
| 161 |
+
sigma_m, sigma_m_v = sigma_m_v, sigma_m
|
| 162 |
+
PB_m, PB_m_v = PB_m_v, PB_m
|
| 163 |
+
|
| 164 |
+
# endpoints
|
| 165 |
+
v, c = len(G), len(group)
|
| 166 |
+
if not endpoints:
|
| 167 |
+
scale = 0
|
| 168 |
+
# if the graph is connected then subtract the endpoints from
|
| 169 |
+
# the count for all the nodes in the graph. else count how many
|
| 170 |
+
# nodes are connected to the group's nodes and subtract that.
|
| 171 |
+
if nx.is_directed(G):
|
| 172 |
+
if nx.is_strongly_connected(G):
|
| 173 |
+
scale = c * (2 * v - c - 1)
|
| 174 |
+
elif nx.is_connected(G):
|
| 175 |
+
scale = c * (2 * v - c - 1)
|
| 176 |
+
if scale == 0:
|
| 177 |
+
for group_node1 in group:
|
| 178 |
+
for node in D[group_node1]:
|
| 179 |
+
if node != group_node1:
|
| 180 |
+
if node in group:
|
| 181 |
+
scale += 1
|
| 182 |
+
else:
|
| 183 |
+
scale += 2
|
| 184 |
+
GBC_group -= scale
|
| 185 |
+
|
| 186 |
+
# normalized
|
| 187 |
+
if normalized:
|
| 188 |
+
scale = 1 / ((v - c) * (v - c - 1))
|
| 189 |
+
GBC_group *= scale
|
| 190 |
+
|
| 191 |
+
# If undirected than count only the undirected edges
|
| 192 |
+
elif not G.is_directed():
|
| 193 |
+
GBC_group /= 2
|
| 194 |
+
|
| 195 |
+
GBC.append(GBC_group)
|
| 196 |
+
if list_of_groups:
|
| 197 |
+
return GBC
|
| 198 |
+
return GBC[0]
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _group_preprocessing(G, set_v, weight):
|
| 202 |
+
sigma = {}
|
| 203 |
+
delta = {}
|
| 204 |
+
D = {}
|
| 205 |
+
betweenness = dict.fromkeys(G, 0)
|
| 206 |
+
for s in G:
|
| 207 |
+
if weight is None: # use BFS
|
| 208 |
+
S, P, sigma[s], D[s] = _single_source_shortest_path_basic(G, s)
|
| 209 |
+
else: # use Dijkstra's algorithm
|
| 210 |
+
S, P, sigma[s], D[s] = _single_source_dijkstra_path_basic(G, s, weight)
|
| 211 |
+
betweenness, delta[s] = _accumulate_endpoints(betweenness, S, P, sigma[s], s)
|
| 212 |
+
for i in delta[s]: # add the paths from s to i and rescale sigma
|
| 213 |
+
if s != i:
|
| 214 |
+
delta[s][i] += 1
|
| 215 |
+
if weight is not None:
|
| 216 |
+
sigma[s][i] = sigma[s][i] / 2
|
| 217 |
+
# building the path betweenness matrix only for nodes that appear in the group
|
| 218 |
+
PB = dict.fromkeys(G)
|
| 219 |
+
for group_node1 in set_v:
|
| 220 |
+
PB[group_node1] = dict.fromkeys(G, 0.0)
|
| 221 |
+
for group_node2 in set_v:
|
| 222 |
+
if group_node2 not in D[group_node1]:
|
| 223 |
+
continue
|
| 224 |
+
for node in G:
|
| 225 |
+
# if node is connected to the two group nodes than continue
|
| 226 |
+
if group_node2 in D[node] and group_node1 in D[node]:
|
| 227 |
+
if (
|
| 228 |
+
D[node][group_node2]
|
| 229 |
+
== D[node][group_node1] + D[group_node1][group_node2]
|
| 230 |
+
):
|
| 231 |
+
PB[group_node1][group_node2] += (
|
| 232 |
+
delta[node][group_node2]
|
| 233 |
+
* sigma[node][group_node1]
|
| 234 |
+
* sigma[group_node1][group_node2]
|
| 235 |
+
/ sigma[node][group_node2]
|
| 236 |
+
)
|
| 237 |
+
return PB, sigma, D
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 241 |
+
def prominent_group(
|
| 242 |
+
G, k, weight=None, C=None, endpoints=False, normalized=True, greedy=False
|
| 243 |
+
):
|
| 244 |
+
r"""Find the prominent group of size $k$ in graph $G$. The prominence of the
|
| 245 |
+
group is evaluated by the group betweenness centrality.
|
| 246 |
+
|
| 247 |
+
Group betweenness centrality of a group of nodes $C$ is the sum of the
|
| 248 |
+
fraction of all-pairs shortest paths that pass through any vertex in $C$
|
| 249 |
+
|
| 250 |
+
.. math::
|
| 251 |
+
|
| 252 |
+
c_B(v) =\sum_{s,t \in V} \frac{\sigma(s, t|v)}{\sigma(s, t)}
|
| 253 |
+
|
| 254 |
+
where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
|
| 255 |
+
shortest $(s, t)$-paths, and $\sigma(s, t|C)$ is the number of
|
| 256 |
+
those paths passing through some node in group $C$. Note that
|
| 257 |
+
$(s, t)$ are not members of the group ($V-C$ is the set of nodes
|
| 258 |
+
in $V$ that are not in $C$).
|
| 259 |
+
|
| 260 |
+
Parameters
|
| 261 |
+
----------
|
| 262 |
+
G : graph
|
| 263 |
+
A NetworkX graph.
|
| 264 |
+
|
| 265 |
+
k : int
|
| 266 |
+
The number of nodes in the group.
|
| 267 |
+
|
| 268 |
+
normalized : bool, optional (default=True)
|
| 269 |
+
If True, group betweenness is normalized by ``1/((|V|-|C|)(|V|-|C|-1))``
|
| 270 |
+
where ``|V|`` is the number of nodes in G and ``|C|`` is the number of
|
| 271 |
+
nodes in C.
|
| 272 |
+
|
| 273 |
+
weight : None or string, optional (default=None)
|
| 274 |
+
If None, all edge weights are considered equal.
|
| 275 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 276 |
+
The weight of an edge is treated as the length or distance between the two sides.
|
| 277 |
+
|
| 278 |
+
endpoints : bool, optional (default=False)
|
| 279 |
+
If True include the endpoints in the shortest path counts.
|
| 280 |
+
|
| 281 |
+
C : list or set, optional (default=None)
|
| 282 |
+
list of nodes which won't be candidates of the prominent group.
|
| 283 |
+
|
| 284 |
+
greedy : bool, optional (default=False)
|
| 285 |
+
Using a naive greedy algorithm in order to find non-optimal prominent
|
| 286 |
+
group. For scale free networks the results are negligibly below the optimal
|
| 287 |
+
results.
|
| 288 |
+
|
| 289 |
+
Raises
|
| 290 |
+
------
|
| 291 |
+
NodeNotFound
|
| 292 |
+
If node(s) in C are not present in G.
|
| 293 |
+
|
| 294 |
+
Returns
|
| 295 |
+
-------
|
| 296 |
+
max_GBC : float
|
| 297 |
+
The group betweenness centrality of the prominent group.
|
| 298 |
+
|
| 299 |
+
max_group : list
|
| 300 |
+
The list of nodes in the prominent group.
|
| 301 |
+
|
| 302 |
+
See Also
|
| 303 |
+
--------
|
| 304 |
+
betweenness_centrality, group_betweenness_centrality
|
| 305 |
+
|
| 306 |
+
Notes
|
| 307 |
+
-----
|
| 308 |
+
Group betweenness centrality is described in [1]_ and its importance discussed in [3]_.
|
| 309 |
+
The algorithm is described in [2]_ and is based on techniques mentioned in [4]_.
|
| 310 |
+
|
| 311 |
+
The number of nodes in the group must be a maximum of ``n - 2`` where ``n``
|
| 312 |
+
is the total number of nodes in the graph.
|
| 313 |
+
|
| 314 |
+
For weighted graphs the edge weights must be greater than zero.
|
| 315 |
+
Zero edge weights can produce an infinite number of equal length
|
| 316 |
+
paths between pairs of nodes.
|
| 317 |
+
|
| 318 |
+
The total number of paths between source and target is counted
|
| 319 |
+
differently for directed and undirected graphs. Directed paths
|
| 320 |
+
between "u" and "v" are counted as two possible paths (one each
|
| 321 |
+
direction) while undirected paths between "u" and "v" are counted
|
| 322 |
+
as one path. Said another way, the sum in the expression above is
|
| 323 |
+
over all ``s != t`` for directed graphs and for ``s < t`` for undirected graphs.
|
| 324 |
+
|
| 325 |
+
References
|
| 326 |
+
----------
|
| 327 |
+
.. [1] M G Everett and S P Borgatti:
|
| 328 |
+
The Centrality of Groups and Classes.
|
| 329 |
+
Journal of Mathematical Sociology. 23(3): 181-201. 1999.
|
| 330 |
+
http://www.analytictech.com/borgatti/group_centrality.htm
|
| 331 |
+
.. [2] Rami Puzis, Yuval Elovici, and Shlomi Dolev:
|
| 332 |
+
"Finding the Most Prominent Group in Complex Networks"
|
| 333 |
+
AI communications 20(4): 287-296, 2007.
|
| 334 |
+
https://www.researchgate.net/profile/Rami_Puzis2/publication/220308855
|
| 335 |
+
.. [3] Sourav Medya et. al.:
|
| 336 |
+
Group Centrality Maximization via Network Design.
|
| 337 |
+
SIAM International Conference on Data Mining, SDM 2018, 126–134.
|
| 338 |
+
https://sites.cs.ucsb.edu/~arlei/pubs/sdm18.pdf
|
| 339 |
+
.. [4] Rami Puzis, Yuval Elovici, and Shlomi Dolev.
|
| 340 |
+
"Fast algorithm for successive computation of group betweenness centrality."
|
| 341 |
+
https://journals.aps.org/pre/pdf/10.1103/PhysRevE.76.056709
|
| 342 |
+
"""
|
| 343 |
+
import numpy as np
|
| 344 |
+
import pandas as pd
|
| 345 |
+
|
| 346 |
+
if C is not None:
|
| 347 |
+
C = set(C)
|
| 348 |
+
if C - G.nodes: # element(s) of C not in G
|
| 349 |
+
raise nx.NodeNotFound(f"The node(s) {C - G.nodes} are in C but not in G.")
|
| 350 |
+
nodes = list(G.nodes - C)
|
| 351 |
+
else:
|
| 352 |
+
nodes = list(G.nodes)
|
| 353 |
+
DF_tree = nx.Graph()
|
| 354 |
+
DF_tree.__networkx_cache__ = None # Disable caching
|
| 355 |
+
PB, sigma, D = _group_preprocessing(G, nodes, weight)
|
| 356 |
+
betweenness = pd.DataFrame.from_dict(PB)
|
| 357 |
+
if C is not None:
|
| 358 |
+
for node in C:
|
| 359 |
+
# remove from the betweenness all the nodes not part of the group
|
| 360 |
+
betweenness = betweenness.drop(index=node)
|
| 361 |
+
betweenness = betweenness.drop(columns=node)
|
| 362 |
+
CL = [node for _, node in sorted(zip(np.diag(betweenness), nodes), reverse=True)]
|
| 363 |
+
max_GBC = 0
|
| 364 |
+
max_group = []
|
| 365 |
+
DF_tree.add_node(
|
| 366 |
+
1,
|
| 367 |
+
CL=CL,
|
| 368 |
+
betweenness=betweenness,
|
| 369 |
+
GBC=0,
|
| 370 |
+
GM=[],
|
| 371 |
+
sigma=sigma,
|
| 372 |
+
cont=dict(zip(nodes, np.diag(betweenness))),
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
# the algorithm
|
| 376 |
+
DF_tree.nodes[1]["heu"] = 0
|
| 377 |
+
for i in range(k):
|
| 378 |
+
DF_tree.nodes[1]["heu"] += DF_tree.nodes[1]["cont"][DF_tree.nodes[1]["CL"][i]]
|
| 379 |
+
max_GBC, DF_tree, max_group = _dfbnb(
|
| 380 |
+
G, k, DF_tree, max_GBC, 1, D, max_group, nodes, greedy
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
v = len(G)
|
| 384 |
+
if not endpoints:
|
| 385 |
+
scale = 0
|
| 386 |
+
# if the graph is connected then subtract the endpoints from
|
| 387 |
+
# the count for all the nodes in the graph. else count how many
|
| 388 |
+
# nodes are connected to the group's nodes and subtract that.
|
| 389 |
+
if nx.is_directed(G):
|
| 390 |
+
if nx.is_strongly_connected(G):
|
| 391 |
+
scale = k * (2 * v - k - 1)
|
| 392 |
+
elif nx.is_connected(G):
|
| 393 |
+
scale = k * (2 * v - k - 1)
|
| 394 |
+
if scale == 0:
|
| 395 |
+
for group_node1 in max_group:
|
| 396 |
+
for node in D[group_node1]:
|
| 397 |
+
if node != group_node1:
|
| 398 |
+
if node in max_group:
|
| 399 |
+
scale += 1
|
| 400 |
+
else:
|
| 401 |
+
scale += 2
|
| 402 |
+
max_GBC -= scale
|
| 403 |
+
|
| 404 |
+
# normalized
|
| 405 |
+
if normalized:
|
| 406 |
+
scale = 1 / ((v - k) * (v - k - 1))
|
| 407 |
+
max_GBC *= scale
|
| 408 |
+
|
| 409 |
+
# If undirected then count only the undirected edges
|
| 410 |
+
elif not G.is_directed():
|
| 411 |
+
max_GBC /= 2
|
| 412 |
+
max_GBC = float(f"{max_GBC:.2f}")
|
| 413 |
+
return max_GBC, max_group
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def _dfbnb(G, k, DF_tree, max_GBC, root, D, max_group, nodes, greedy):
|
| 417 |
+
# stopping condition - if we found a group of size k and with higher GBC then prune
|
| 418 |
+
if len(DF_tree.nodes[root]["GM"]) == k and DF_tree.nodes[root]["GBC"] > max_GBC:
|
| 419 |
+
return DF_tree.nodes[root]["GBC"], DF_tree, DF_tree.nodes[root]["GM"]
|
| 420 |
+
# stopping condition - if the size of group members equal to k or there are less than
|
| 421 |
+
# k - |GM| in the candidate list or the heuristic function plus the GBC is below the
|
| 422 |
+
# maximal GBC found then prune
|
| 423 |
+
if (
|
| 424 |
+
len(DF_tree.nodes[root]["GM"]) == k
|
| 425 |
+
or len(DF_tree.nodes[root]["CL"]) <= k - len(DF_tree.nodes[root]["GM"])
|
| 426 |
+
or DF_tree.nodes[root]["GBC"] + DF_tree.nodes[root]["heu"] <= max_GBC
|
| 427 |
+
):
|
| 428 |
+
return max_GBC, DF_tree, max_group
|
| 429 |
+
|
| 430 |
+
# finding the heuristic of both children
|
| 431 |
+
node_p, node_m, DF_tree = _heuristic(k, root, DF_tree, D, nodes, greedy)
|
| 432 |
+
|
| 433 |
+
# finding the child with the bigger heuristic + GBC and expand
|
| 434 |
+
# that node first if greedy then only expand the plus node
|
| 435 |
+
if greedy:
|
| 436 |
+
max_GBC, DF_tree, max_group = _dfbnb(
|
| 437 |
+
G, k, DF_tree, max_GBC, node_p, D, max_group, nodes, greedy
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
elif (
|
| 441 |
+
DF_tree.nodes[node_p]["GBC"] + DF_tree.nodes[node_p]["heu"]
|
| 442 |
+
> DF_tree.nodes[node_m]["GBC"] + DF_tree.nodes[node_m]["heu"]
|
| 443 |
+
):
|
| 444 |
+
max_GBC, DF_tree, max_group = _dfbnb(
|
| 445 |
+
G, k, DF_tree, max_GBC, node_p, D, max_group, nodes, greedy
|
| 446 |
+
)
|
| 447 |
+
max_GBC, DF_tree, max_group = _dfbnb(
|
| 448 |
+
G, k, DF_tree, max_GBC, node_m, D, max_group, nodes, greedy
|
| 449 |
+
)
|
| 450 |
+
else:
|
| 451 |
+
max_GBC, DF_tree, max_group = _dfbnb(
|
| 452 |
+
G, k, DF_tree, max_GBC, node_m, D, max_group, nodes, greedy
|
| 453 |
+
)
|
| 454 |
+
max_GBC, DF_tree, max_group = _dfbnb(
|
| 455 |
+
G, k, DF_tree, max_GBC, node_p, D, max_group, nodes, greedy
|
| 456 |
+
)
|
| 457 |
+
return max_GBC, DF_tree, max_group
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def _heuristic(k, root, DF_tree, D, nodes, greedy):
|
| 461 |
+
import numpy as np
|
| 462 |
+
|
| 463 |
+
# This helper function add two nodes to DF_tree - one left son and the
|
| 464 |
+
# other right son, finds their heuristic, CL, GBC, and GM
|
| 465 |
+
node_p = DF_tree.number_of_nodes() + 1
|
| 466 |
+
node_m = DF_tree.number_of_nodes() + 2
|
| 467 |
+
added_node = DF_tree.nodes[root]["CL"][0]
|
| 468 |
+
|
| 469 |
+
# adding the plus node
|
| 470 |
+
DF_tree.add_nodes_from([(node_p, deepcopy(DF_tree.nodes[root]))])
|
| 471 |
+
DF_tree.nodes[node_p]["GM"].append(added_node)
|
| 472 |
+
DF_tree.nodes[node_p]["GBC"] += DF_tree.nodes[node_p]["cont"][added_node]
|
| 473 |
+
root_node = DF_tree.nodes[root]
|
| 474 |
+
for x in nodes:
|
| 475 |
+
for y in nodes:
|
| 476 |
+
dxvy = 0
|
| 477 |
+
dxyv = 0
|
| 478 |
+
dvxy = 0
|
| 479 |
+
if not (
|
| 480 |
+
root_node["sigma"][x][y] == 0
|
| 481 |
+
or root_node["sigma"][x][added_node] == 0
|
| 482 |
+
or root_node["sigma"][added_node][y] == 0
|
| 483 |
+
):
|
| 484 |
+
if D[x][added_node] == D[x][y] + D[y][added_node]:
|
| 485 |
+
dxyv = (
|
| 486 |
+
root_node["sigma"][x][y]
|
| 487 |
+
* root_node["sigma"][y][added_node]
|
| 488 |
+
/ root_node["sigma"][x][added_node]
|
| 489 |
+
)
|
| 490 |
+
if D[x][y] == D[x][added_node] + D[added_node][y]:
|
| 491 |
+
dxvy = (
|
| 492 |
+
root_node["sigma"][x][added_node]
|
| 493 |
+
* root_node["sigma"][added_node][y]
|
| 494 |
+
/ root_node["sigma"][x][y]
|
| 495 |
+
)
|
| 496 |
+
if D[added_node][y] == D[added_node][x] + D[x][y]:
|
| 497 |
+
dvxy = (
|
| 498 |
+
root_node["sigma"][added_node][x]
|
| 499 |
+
* root_node["sigma"][x][y]
|
| 500 |
+
/ root_node["sigma"][added_node][y]
|
| 501 |
+
)
|
| 502 |
+
DF_tree.nodes[node_p]["sigma"][x][y] = root_node["sigma"][x][y] * (1 - dxvy)
|
| 503 |
+
DF_tree.nodes[node_p]["betweenness"].loc[y, x] = (
|
| 504 |
+
root_node["betweenness"][x][y] - root_node["betweenness"][x][y] * dxvy
|
| 505 |
+
)
|
| 506 |
+
if y != added_node:
|
| 507 |
+
DF_tree.nodes[node_p]["betweenness"].loc[y, x] -= (
|
| 508 |
+
root_node["betweenness"][x][added_node] * dxyv
|
| 509 |
+
)
|
| 510 |
+
if x != added_node:
|
| 511 |
+
DF_tree.nodes[node_p]["betweenness"].loc[y, x] -= (
|
| 512 |
+
root_node["betweenness"][added_node][y] * dvxy
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
DF_tree.nodes[node_p]["CL"] = [
|
| 516 |
+
node
|
| 517 |
+
for _, node in sorted(
|
| 518 |
+
zip(np.diag(DF_tree.nodes[node_p]["betweenness"]), nodes), reverse=True
|
| 519 |
+
)
|
| 520 |
+
if node not in DF_tree.nodes[node_p]["GM"]
|
| 521 |
+
]
|
| 522 |
+
DF_tree.nodes[node_p]["cont"] = dict(
|
| 523 |
+
zip(nodes, np.diag(DF_tree.nodes[node_p]["betweenness"]))
|
| 524 |
+
)
|
| 525 |
+
DF_tree.nodes[node_p]["heu"] = 0
|
| 526 |
+
for i in range(k - len(DF_tree.nodes[node_p]["GM"])):
|
| 527 |
+
DF_tree.nodes[node_p]["heu"] += DF_tree.nodes[node_p]["cont"][
|
| 528 |
+
DF_tree.nodes[node_p]["CL"][i]
|
| 529 |
+
]
|
| 530 |
+
|
| 531 |
+
# adding the minus node - don't insert the first node in the CL to GM
|
| 532 |
+
# Insert minus node only if isn't greedy type algorithm
|
| 533 |
+
if not greedy:
|
| 534 |
+
DF_tree.add_nodes_from([(node_m, deepcopy(DF_tree.nodes[root]))])
|
| 535 |
+
DF_tree.nodes[node_m]["CL"].pop(0)
|
| 536 |
+
DF_tree.nodes[node_m]["cont"].pop(added_node)
|
| 537 |
+
DF_tree.nodes[node_m]["heu"] = 0
|
| 538 |
+
for i in range(k - len(DF_tree.nodes[node_m]["GM"])):
|
| 539 |
+
DF_tree.nodes[node_m]["heu"] += DF_tree.nodes[node_m]["cont"][
|
| 540 |
+
DF_tree.nodes[node_m]["CL"][i]
|
| 541 |
+
]
|
| 542 |
+
else:
|
| 543 |
+
node_m = None
|
| 544 |
+
|
| 545 |
+
return node_p, node_m, DF_tree
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 549 |
+
def group_closeness_centrality(G, S, weight=None):
|
| 550 |
+
r"""Compute the group closeness centrality for a group of nodes.
|
| 551 |
+
|
| 552 |
+
Group closeness centrality of a group of nodes $S$ is a measure
|
| 553 |
+
of how close the group is to the other nodes in the graph.
|
| 554 |
+
|
| 555 |
+
.. math::
|
| 556 |
+
|
| 557 |
+
c_{close}(S) = \frac{|V-S|}{\sum_{v \in V-S} d_{S, v}}
|
| 558 |
+
|
| 559 |
+
d_{S, v} = min_{u \in S} (d_{u, v})
|
| 560 |
+
|
| 561 |
+
where $V$ is the set of nodes, $d_{S, v}$ is the distance of
|
| 562 |
+
the group $S$ from $v$ defined as above. ($V-S$ is the set of nodes
|
| 563 |
+
in $V$ that are not in $S$).
|
| 564 |
+
|
| 565 |
+
Parameters
|
| 566 |
+
----------
|
| 567 |
+
G : graph
|
| 568 |
+
A NetworkX graph.
|
| 569 |
+
|
| 570 |
+
S : list or set
|
| 571 |
+
S is a group of nodes which belong to G, for which group closeness
|
| 572 |
+
centrality is to be calculated.
|
| 573 |
+
|
| 574 |
+
weight : None or string, optional (default=None)
|
| 575 |
+
If None, all edge weights are considered equal.
|
| 576 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 577 |
+
The weight of an edge is treated as the length or distance between the two sides.
|
| 578 |
+
|
| 579 |
+
Raises
|
| 580 |
+
------
|
| 581 |
+
NodeNotFound
|
| 582 |
+
If node(s) in S are not present in G.
|
| 583 |
+
|
| 584 |
+
Returns
|
| 585 |
+
-------
|
| 586 |
+
closeness : float
|
| 587 |
+
Group closeness centrality of the group S.
|
| 588 |
+
|
| 589 |
+
See Also
|
| 590 |
+
--------
|
| 591 |
+
closeness_centrality
|
| 592 |
+
|
| 593 |
+
Notes
|
| 594 |
+
-----
|
| 595 |
+
The measure was introduced in [1]_.
|
| 596 |
+
The formula implemented here is described in [2]_.
|
| 597 |
+
|
| 598 |
+
Higher values of closeness indicate greater centrality.
|
| 599 |
+
|
| 600 |
+
It is assumed that 1 / 0 is 0 (required in the case of directed graphs,
|
| 601 |
+
or when a shortest path length is 0).
|
| 602 |
+
|
| 603 |
+
The number of nodes in the group must be a maximum of n - 1 where `n`
|
| 604 |
+
is the total number of nodes in the graph.
|
| 605 |
+
|
| 606 |
+
For directed graphs, the incoming distance is utilized here. To use the
|
| 607 |
+
outward distance, act on `G.reverse()`.
|
| 608 |
+
|
| 609 |
+
For weighted graphs the edge weights must be greater than zero.
|
| 610 |
+
Zero edge weights can produce an infinite number of equal length
|
| 611 |
+
paths between pairs of nodes.
|
| 612 |
+
|
| 613 |
+
References
|
| 614 |
+
----------
|
| 615 |
+
.. [1] M G Everett and S P Borgatti:
|
| 616 |
+
The Centrality of Groups and Classes.
|
| 617 |
+
Journal of Mathematical Sociology. 23(3): 181-201. 1999.
|
| 618 |
+
http://www.analytictech.com/borgatti/group_centrality.htm
|
| 619 |
+
.. [2] J. Zhao et. al.:
|
| 620 |
+
Measuring and Maximizing Group Closeness Centrality over
|
| 621 |
+
Disk Resident Graphs.
|
| 622 |
+
WWWConference Proceedings, 2014. 689-694.
|
| 623 |
+
https://doi.org/10.1145/2567948.2579356
|
| 624 |
+
"""
|
| 625 |
+
if G.is_directed():
|
| 626 |
+
G = G.reverse() # reverse view
|
| 627 |
+
closeness = 0 # initialize to 0
|
| 628 |
+
V = set(G) # set of nodes in G
|
| 629 |
+
S = set(S) # set of nodes in group S
|
| 630 |
+
V_S = V - S # set of nodes in V but not S
|
| 631 |
+
shortest_path_lengths = nx.multi_source_dijkstra_path_length(G, S, weight=weight)
|
| 632 |
+
# accumulation
|
| 633 |
+
for v in V_S:
|
| 634 |
+
try:
|
| 635 |
+
closeness += shortest_path_lengths[v]
|
| 636 |
+
except KeyError: # no path exists
|
| 637 |
+
closeness += 0
|
| 638 |
+
try:
|
| 639 |
+
closeness = len(V_S) / closeness
|
| 640 |
+
except ZeroDivisionError: # 1 / 0 assumed as 0
|
| 641 |
+
closeness = 0
|
| 642 |
+
return closeness
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
@nx._dispatchable
|
| 646 |
+
def group_degree_centrality(G, S):
|
| 647 |
+
"""Compute the group degree centrality for a group of nodes.
|
| 648 |
+
|
| 649 |
+
Group degree centrality of a group of nodes $S$ is the fraction
|
| 650 |
+
of non-group members connected to group members.
|
| 651 |
+
|
| 652 |
+
Parameters
|
| 653 |
+
----------
|
| 654 |
+
G : graph
|
| 655 |
+
A NetworkX graph.
|
| 656 |
+
|
| 657 |
+
S : list or set
|
| 658 |
+
S is a group of nodes which belong to G, for which group degree
|
| 659 |
+
centrality is to be calculated.
|
| 660 |
+
|
| 661 |
+
Raises
|
| 662 |
+
------
|
| 663 |
+
NetworkXError
|
| 664 |
+
If node(s) in S are not in G.
|
| 665 |
+
|
| 666 |
+
Returns
|
| 667 |
+
-------
|
| 668 |
+
centrality : float
|
| 669 |
+
Group degree centrality of the group S.
|
| 670 |
+
|
| 671 |
+
See Also
|
| 672 |
+
--------
|
| 673 |
+
degree_centrality
|
| 674 |
+
group_in_degree_centrality
|
| 675 |
+
group_out_degree_centrality
|
| 676 |
+
|
| 677 |
+
Notes
|
| 678 |
+
-----
|
| 679 |
+
The measure was introduced in [1]_.
|
| 680 |
+
|
| 681 |
+
The number of nodes in the group must be a maximum of n - 1 where `n`
|
| 682 |
+
is the total number of nodes in the graph.
|
| 683 |
+
|
| 684 |
+
References
|
| 685 |
+
----------
|
| 686 |
+
.. [1] M G Everett and S P Borgatti:
|
| 687 |
+
The Centrality of Groups and Classes.
|
| 688 |
+
Journal of Mathematical Sociology. 23(3): 181-201. 1999.
|
| 689 |
+
http://www.analytictech.com/borgatti/group_centrality.htm
|
| 690 |
+
"""
|
| 691 |
+
centrality = len(set().union(*[set(G.neighbors(i)) for i in S]) - set(S))
|
| 692 |
+
centrality /= len(G.nodes()) - len(S)
|
| 693 |
+
return centrality
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
@not_implemented_for("undirected")
|
| 697 |
+
@nx._dispatchable
|
| 698 |
+
def group_in_degree_centrality(G, S):
|
| 699 |
+
"""Compute the group in-degree centrality for a group of nodes.
|
| 700 |
+
|
| 701 |
+
Group in-degree centrality of a group of nodes $S$ is the fraction
|
| 702 |
+
of non-group members connected to group members by incoming edges.
|
| 703 |
+
|
| 704 |
+
Parameters
|
| 705 |
+
----------
|
| 706 |
+
G : graph
|
| 707 |
+
A NetworkX graph.
|
| 708 |
+
|
| 709 |
+
S : list or set
|
| 710 |
+
S is a group of nodes which belong to G, for which group in-degree
|
| 711 |
+
centrality is to be calculated.
|
| 712 |
+
|
| 713 |
+
Returns
|
| 714 |
+
-------
|
| 715 |
+
centrality : float
|
| 716 |
+
Group in-degree centrality of the group S.
|
| 717 |
+
|
| 718 |
+
Raises
|
| 719 |
+
------
|
| 720 |
+
NetworkXNotImplemented
|
| 721 |
+
If G is undirected.
|
| 722 |
+
|
| 723 |
+
NodeNotFound
|
| 724 |
+
If node(s) in S are not in G.
|
| 725 |
+
|
| 726 |
+
See Also
|
| 727 |
+
--------
|
| 728 |
+
degree_centrality
|
| 729 |
+
group_degree_centrality
|
| 730 |
+
group_out_degree_centrality
|
| 731 |
+
|
| 732 |
+
Notes
|
| 733 |
+
-----
|
| 734 |
+
The number of nodes in the group must be a maximum of n - 1 where `n`
|
| 735 |
+
is the total number of nodes in the graph.
|
| 736 |
+
|
| 737 |
+
`G.neighbors(i)` gives nodes with an outward edge from i, in a DiGraph,
|
| 738 |
+
so for group in-degree centrality, the reverse graph is used.
|
| 739 |
+
"""
|
| 740 |
+
return group_degree_centrality(G.reverse(), S)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
@not_implemented_for("undirected")
|
| 744 |
+
@nx._dispatchable
|
| 745 |
+
def group_out_degree_centrality(G, S):
|
| 746 |
+
"""Compute the group out-degree centrality for a group of nodes.
|
| 747 |
+
|
| 748 |
+
Group out-degree centrality of a group of nodes $S$ is the fraction
|
| 749 |
+
of non-group members connected to group members by outgoing edges.
|
| 750 |
+
|
| 751 |
+
Parameters
|
| 752 |
+
----------
|
| 753 |
+
G : graph
|
| 754 |
+
A NetworkX graph.
|
| 755 |
+
|
| 756 |
+
S : list or set
|
| 757 |
+
S is a group of nodes which belong to G, for which group in-degree
|
| 758 |
+
centrality is to be calculated.
|
| 759 |
+
|
| 760 |
+
Returns
|
| 761 |
+
-------
|
| 762 |
+
centrality : float
|
| 763 |
+
Group out-degree centrality of the group S.
|
| 764 |
+
|
| 765 |
+
Raises
|
| 766 |
+
------
|
| 767 |
+
NetworkXNotImplemented
|
| 768 |
+
If G is undirected.
|
| 769 |
+
|
| 770 |
+
NodeNotFound
|
| 771 |
+
If node(s) in S are not in G.
|
| 772 |
+
|
| 773 |
+
See Also
|
| 774 |
+
--------
|
| 775 |
+
degree_centrality
|
| 776 |
+
group_degree_centrality
|
| 777 |
+
group_in_degree_centrality
|
| 778 |
+
|
| 779 |
+
Notes
|
| 780 |
+
-----
|
| 781 |
+
The number of nodes in the group must be a maximum of n - 1 where `n`
|
| 782 |
+
is the total number of nodes in the graph.
|
| 783 |
+
|
| 784 |
+
`G.neighbors(i)` gives nodes with an outward edge from i, in a DiGraph,
|
| 785 |
+
so for group out-degree centrality, the graph itself is used.
|
| 786 |
+
"""
|
| 787 |
+
return group_degree_centrality(G, S)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/harmonic.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for computing the harmonic centrality of a graph."""
|
| 2 |
+
|
| 3 |
+
from functools import partial
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
__all__ = ["harmonic_centrality"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@nx._dispatchable(edge_attrs="distance")
|
| 11 |
+
def harmonic_centrality(G, nbunch=None, distance=None, sources=None):
|
| 12 |
+
r"""Compute harmonic centrality for nodes.
|
| 13 |
+
|
| 14 |
+
Harmonic centrality [1]_ of a node `u` is the sum of the reciprocal
|
| 15 |
+
of the shortest path distances from all other nodes to `u`
|
| 16 |
+
|
| 17 |
+
.. math::
|
| 18 |
+
|
| 19 |
+
C(u) = \sum_{v \neq u} \frac{1}{d(v, u)}
|
| 20 |
+
|
| 21 |
+
where `d(v, u)` is the shortest-path distance between `v` and `u`.
|
| 22 |
+
|
| 23 |
+
If `sources` is given as an argument, the returned harmonic centrality
|
| 24 |
+
values are calculated as the sum of the reciprocals of the shortest
|
| 25 |
+
path distances from the nodes specified in `sources` to `u` instead
|
| 26 |
+
of from all nodes to `u`.
|
| 27 |
+
|
| 28 |
+
Notice that higher values indicate higher centrality.
|
| 29 |
+
|
| 30 |
+
Parameters
|
| 31 |
+
----------
|
| 32 |
+
G : graph
|
| 33 |
+
A NetworkX graph
|
| 34 |
+
|
| 35 |
+
nbunch : container (default: all nodes in G)
|
| 36 |
+
Container of nodes for which harmonic centrality values are calculated.
|
| 37 |
+
|
| 38 |
+
sources : container (default: all nodes in G)
|
| 39 |
+
Container of nodes `v` over which reciprocal distances are computed.
|
| 40 |
+
Nodes not in `G` are silently ignored.
|
| 41 |
+
|
| 42 |
+
distance : edge attribute key, optional (default=None)
|
| 43 |
+
Use the specified edge attribute as the edge distance in shortest
|
| 44 |
+
path calculations. If `None`, then each edge will have distance equal to 1.
|
| 45 |
+
|
| 46 |
+
Returns
|
| 47 |
+
-------
|
| 48 |
+
nodes : dictionary
|
| 49 |
+
Dictionary of nodes with harmonic centrality as the value.
|
| 50 |
+
|
| 51 |
+
See Also
|
| 52 |
+
--------
|
| 53 |
+
betweenness_centrality, load_centrality, eigenvector_centrality,
|
| 54 |
+
degree_centrality, closeness_centrality
|
| 55 |
+
|
| 56 |
+
Notes
|
| 57 |
+
-----
|
| 58 |
+
If the 'distance' keyword is set to an edge attribute key then the
|
| 59 |
+
shortest-path length will be computed using Dijkstra's algorithm with
|
| 60 |
+
that edge attribute as the edge weight.
|
| 61 |
+
|
| 62 |
+
References
|
| 63 |
+
----------
|
| 64 |
+
.. [1] Boldi, Paolo, and Sebastiano Vigna. "Axioms for centrality."
|
| 65 |
+
Internet Mathematics 10.3-4 (2014): 222-262.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
nbunch = set(G.nbunch_iter(nbunch) if nbunch is not None else G.nodes)
|
| 69 |
+
sources = set(G.nbunch_iter(sources) if sources is not None else G.nodes)
|
| 70 |
+
|
| 71 |
+
centrality = dict.fromkeys(nbunch, 0)
|
| 72 |
+
|
| 73 |
+
transposed = False
|
| 74 |
+
if len(nbunch) < len(sources):
|
| 75 |
+
transposed = True
|
| 76 |
+
nbunch, sources = sources, nbunch
|
| 77 |
+
if nx.is_directed(G):
|
| 78 |
+
G = nx.reverse(G, copy=False)
|
| 79 |
+
|
| 80 |
+
spl = partial(nx.shortest_path_length, G, weight=distance)
|
| 81 |
+
for v in sources:
|
| 82 |
+
dist = spl(v)
|
| 83 |
+
for u in nbunch.intersection(dist):
|
| 84 |
+
d = dist[u]
|
| 85 |
+
if d == 0: # handle u == v and edges with 0 weight
|
| 86 |
+
continue
|
| 87 |
+
centrality[v if transposed else u] += 1 / d
|
| 88 |
+
|
| 89 |
+
return centrality
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/katz.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Katz centrality."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = ["katz_centrality", "katz_centrality_numpy"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@not_implemented_for("multigraph")
|
| 12 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 13 |
+
def katz_centrality(
|
| 14 |
+
G,
|
| 15 |
+
alpha=0.1,
|
| 16 |
+
beta=1.0,
|
| 17 |
+
max_iter=1000,
|
| 18 |
+
tol=1.0e-6,
|
| 19 |
+
nstart=None,
|
| 20 |
+
normalized=True,
|
| 21 |
+
weight=None,
|
| 22 |
+
):
|
| 23 |
+
r"""Compute the Katz centrality for the nodes of the graph G.
|
| 24 |
+
|
| 25 |
+
Katz centrality computes the centrality for a node based on the centrality
|
| 26 |
+
of its neighbors. It is a generalization of the eigenvector centrality. The
|
| 27 |
+
Katz centrality for node $i$ is
|
| 28 |
+
|
| 29 |
+
.. math::
|
| 30 |
+
|
| 31 |
+
x_i = \alpha \sum_{j} A_{ij} x_j + \beta,
|
| 32 |
+
|
| 33 |
+
where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.
|
| 34 |
+
|
| 35 |
+
The parameter $\beta$ controls the initial centrality and
|
| 36 |
+
|
| 37 |
+
.. math::
|
| 38 |
+
|
| 39 |
+
\alpha < \frac{1}{\lambda_{\max}}.
|
| 40 |
+
|
| 41 |
+
Katz centrality computes the relative influence of a node within a
|
| 42 |
+
network by measuring the number of the immediate neighbors (first
|
| 43 |
+
degree nodes) and also all other nodes in the network that connect
|
| 44 |
+
to the node under consideration through these immediate neighbors.
|
| 45 |
+
|
| 46 |
+
Extra weight can be provided to immediate neighbors through the
|
| 47 |
+
parameter $\beta$. Connections made with distant neighbors
|
| 48 |
+
are, however, penalized by an attenuation factor $\alpha$ which
|
| 49 |
+
should be strictly less than the inverse largest eigenvalue of the
|
| 50 |
+
adjacency matrix in order for the Katz centrality to be computed
|
| 51 |
+
correctly. More information is provided in [1]_.
|
| 52 |
+
|
| 53 |
+
Parameters
|
| 54 |
+
----------
|
| 55 |
+
G : graph
|
| 56 |
+
A NetworkX graph.
|
| 57 |
+
|
| 58 |
+
alpha : float, optional (default=0.1)
|
| 59 |
+
Attenuation factor
|
| 60 |
+
|
| 61 |
+
beta : scalar or dictionary, optional (default=1.0)
|
| 62 |
+
Weight attributed to the immediate neighborhood. If not a scalar, the
|
| 63 |
+
dictionary must have a value for every node.
|
| 64 |
+
|
| 65 |
+
max_iter : integer, optional (default=1000)
|
| 66 |
+
Maximum number of iterations in power method.
|
| 67 |
+
|
| 68 |
+
tol : float, optional (default=1.0e-6)
|
| 69 |
+
Error tolerance used to check convergence in power method iteration.
|
| 70 |
+
|
| 71 |
+
nstart : dictionary, optional
|
| 72 |
+
Starting value of Katz iteration for each node.
|
| 73 |
+
|
| 74 |
+
normalized : bool, optional (default=True)
|
| 75 |
+
If True normalize the resulting values.
|
| 76 |
+
|
| 77 |
+
weight : None or string, optional (default=None)
|
| 78 |
+
If None, all edge weights are considered equal.
|
| 79 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 80 |
+
In this measure the weight is interpreted as the connection strength.
|
| 81 |
+
|
| 82 |
+
Returns
|
| 83 |
+
-------
|
| 84 |
+
nodes : dictionary
|
| 85 |
+
Dictionary of nodes with Katz centrality as the value.
|
| 86 |
+
|
| 87 |
+
Raises
|
| 88 |
+
------
|
| 89 |
+
NetworkXError
|
| 90 |
+
If the parameter `beta` is not a scalar but lacks a value for at least
|
| 91 |
+
one node
|
| 92 |
+
|
| 93 |
+
PowerIterationFailedConvergence
|
| 94 |
+
If the algorithm fails to converge to the specified tolerance
|
| 95 |
+
within the specified number of iterations of the power iteration
|
| 96 |
+
method.
|
| 97 |
+
|
| 98 |
+
Examples
|
| 99 |
+
--------
|
| 100 |
+
>>> import math
|
| 101 |
+
>>> G = nx.path_graph(4)
|
| 102 |
+
>>> phi = (1 + math.sqrt(5)) / 2.0 # largest eigenvalue of adj matrix
|
| 103 |
+
>>> centrality = nx.katz_centrality(G, 1 / phi - 0.01)
|
| 104 |
+
>>> for n, c in sorted(centrality.items()):
|
| 105 |
+
... print(f"{n} {c:.2f}")
|
| 106 |
+
0 0.37
|
| 107 |
+
1 0.60
|
| 108 |
+
2 0.60
|
| 109 |
+
3 0.37
|
| 110 |
+
|
| 111 |
+
See Also
|
| 112 |
+
--------
|
| 113 |
+
katz_centrality_numpy
|
| 114 |
+
eigenvector_centrality
|
| 115 |
+
eigenvector_centrality_numpy
|
| 116 |
+
:func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
|
| 117 |
+
:func:`~networkx.algorithms.link_analysis.hits_alg.hits`
|
| 118 |
+
|
| 119 |
+
Notes
|
| 120 |
+
-----
|
| 121 |
+
Katz centrality was introduced by [2]_.
|
| 122 |
+
|
| 123 |
+
This algorithm it uses the power method to find the eigenvector
|
| 124 |
+
corresponding to the largest eigenvalue of the adjacency matrix of ``G``.
|
| 125 |
+
The parameter ``alpha`` should be strictly less than the inverse of largest
|
| 126 |
+
eigenvalue of the adjacency matrix for the algorithm to converge.
|
| 127 |
+
You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
|
| 128 |
+
eigenvalue of the adjacency matrix.
|
| 129 |
+
The iteration will stop after ``max_iter`` iterations or an error tolerance of
|
| 130 |
+
``number_of_nodes(G) * tol`` has been reached.
|
| 131 |
+
|
| 132 |
+
For strongly connected graphs, as $\alpha \to 1/\lambda_{\max}$, and $\beta > 0$,
|
| 133 |
+
Katz centrality approaches the results for eigenvector centrality.
|
| 134 |
+
|
| 135 |
+
For directed graphs this finds "left" eigenvectors which corresponds
|
| 136 |
+
to the in-edges in the graph. For out-edges Katz centrality,
|
| 137 |
+
first reverse the graph with ``G.reverse()``.
|
| 138 |
+
|
| 139 |
+
References
|
| 140 |
+
----------
|
| 141 |
+
.. [1] Mark E. J. Newman:
|
| 142 |
+
Networks: An Introduction.
|
| 143 |
+
Oxford University Press, USA, 2010, p. 720.
|
| 144 |
+
.. [2] Leo Katz:
|
| 145 |
+
A New Status Index Derived from Sociometric Index.
|
| 146 |
+
Psychometrika 18(1):39–43, 1953
|
| 147 |
+
https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
|
| 148 |
+
"""
|
| 149 |
+
if len(G) == 0:
|
| 150 |
+
return {}
|
| 151 |
+
|
| 152 |
+
nnodes = G.number_of_nodes()
|
| 153 |
+
|
| 154 |
+
if nstart is None:
|
| 155 |
+
# choose starting vector with entries of 0
|
| 156 |
+
x = dict.fromkeys(G, 0)
|
| 157 |
+
else:
|
| 158 |
+
x = nstart
|
| 159 |
+
|
| 160 |
+
try:
|
| 161 |
+
b = dict.fromkeys(G, float(beta))
|
| 162 |
+
except (TypeError, ValueError, AttributeError) as err:
|
| 163 |
+
b = beta
|
| 164 |
+
if set(beta) != set(G):
|
| 165 |
+
raise nx.NetworkXError(
|
| 166 |
+
"beta dictionary must have a value for every node"
|
| 167 |
+
) from err
|
| 168 |
+
|
| 169 |
+
# make up to max_iter iterations
|
| 170 |
+
for _ in range(max_iter):
|
| 171 |
+
xlast = x
|
| 172 |
+
x = dict.fromkeys(xlast, 0)
|
| 173 |
+
# do the multiplication y^T = Alpha * x^T A + Beta
|
| 174 |
+
for n in x:
|
| 175 |
+
for nbr in G[n]:
|
| 176 |
+
x[nbr] += xlast[n] * G[n][nbr].get(weight, 1)
|
| 177 |
+
for n in x:
|
| 178 |
+
x[n] = alpha * x[n] + b[n]
|
| 179 |
+
|
| 180 |
+
# check convergence
|
| 181 |
+
error = sum(abs(x[n] - xlast[n]) for n in x)
|
| 182 |
+
if error < nnodes * tol:
|
| 183 |
+
if normalized:
|
| 184 |
+
# normalize vector
|
| 185 |
+
try:
|
| 186 |
+
s = 1.0 / math.hypot(*x.values())
|
| 187 |
+
except ZeroDivisionError:
|
| 188 |
+
s = 1.0
|
| 189 |
+
else:
|
| 190 |
+
s = 1
|
| 191 |
+
for n in x:
|
| 192 |
+
x[n] *= s
|
| 193 |
+
return x
|
| 194 |
+
raise nx.PowerIterationFailedConvergence(max_iter)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
@not_implemented_for("multigraph")
|
| 198 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 199 |
+
def katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True, weight=None):
|
| 200 |
+
r"""Compute the Katz centrality for the graph G.
|
| 201 |
+
|
| 202 |
+
Katz centrality computes the centrality for a node based on the centrality
|
| 203 |
+
of its neighbors. It is a generalization of the eigenvector centrality. The
|
| 204 |
+
Katz centrality for node $i$ is
|
| 205 |
+
|
| 206 |
+
.. math::
|
| 207 |
+
|
| 208 |
+
x_i = \alpha \sum_{j} A_{ij} x_j + \beta,
|
| 209 |
+
|
| 210 |
+
where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.
|
| 211 |
+
|
| 212 |
+
The parameter $\beta$ controls the initial centrality and
|
| 213 |
+
|
| 214 |
+
.. math::
|
| 215 |
+
|
| 216 |
+
\alpha < \frac{1}{\lambda_{\max}}.
|
| 217 |
+
|
| 218 |
+
Katz centrality computes the relative influence of a node within a
|
| 219 |
+
network by measuring the number of the immediate neighbors (first
|
| 220 |
+
degree nodes) and also all other nodes in the network that connect
|
| 221 |
+
to the node under consideration through these immediate neighbors.
|
| 222 |
+
|
| 223 |
+
Extra weight can be provided to immediate neighbors through the
|
| 224 |
+
parameter $\beta$. Connections made with distant neighbors
|
| 225 |
+
are, however, penalized by an attenuation factor $\alpha$ which
|
| 226 |
+
should be strictly less than the inverse largest eigenvalue of the
|
| 227 |
+
adjacency matrix in order for the Katz centrality to be computed
|
| 228 |
+
correctly. More information is provided in [1]_.
|
| 229 |
+
|
| 230 |
+
Parameters
|
| 231 |
+
----------
|
| 232 |
+
G : graph
|
| 233 |
+
A NetworkX graph
|
| 234 |
+
|
| 235 |
+
alpha : float
|
| 236 |
+
Attenuation factor
|
| 237 |
+
|
| 238 |
+
beta : scalar or dictionary, optional (default=1.0)
|
| 239 |
+
Weight attributed to the immediate neighborhood. If not a scalar the
|
| 240 |
+
dictionary must have an value for every node.
|
| 241 |
+
|
| 242 |
+
normalized : bool
|
| 243 |
+
If True normalize the resulting values.
|
| 244 |
+
|
| 245 |
+
weight : None or string, optional
|
| 246 |
+
If None, all edge weights are considered equal.
|
| 247 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 248 |
+
In this measure the weight is interpreted as the connection strength.
|
| 249 |
+
|
| 250 |
+
Returns
|
| 251 |
+
-------
|
| 252 |
+
nodes : dictionary
|
| 253 |
+
Dictionary of nodes with Katz centrality as the value.
|
| 254 |
+
|
| 255 |
+
Raises
|
| 256 |
+
------
|
| 257 |
+
NetworkXError
|
| 258 |
+
If the parameter `beta` is not a scalar but lacks a value for at least
|
| 259 |
+
one node
|
| 260 |
+
|
| 261 |
+
Examples
|
| 262 |
+
--------
|
| 263 |
+
>>> import math
|
| 264 |
+
>>> G = nx.path_graph(4)
|
| 265 |
+
>>> phi = (1 + math.sqrt(5)) / 2.0 # largest eigenvalue of adj matrix
|
| 266 |
+
>>> centrality = nx.katz_centrality_numpy(G, 1 / phi)
|
| 267 |
+
>>> for n, c in sorted(centrality.items()):
|
| 268 |
+
... print(f"{n} {c:.2f}")
|
| 269 |
+
0 0.37
|
| 270 |
+
1 0.60
|
| 271 |
+
2 0.60
|
| 272 |
+
3 0.37
|
| 273 |
+
|
| 274 |
+
See Also
|
| 275 |
+
--------
|
| 276 |
+
katz_centrality
|
| 277 |
+
eigenvector_centrality_numpy
|
| 278 |
+
eigenvector_centrality
|
| 279 |
+
:func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
|
| 280 |
+
:func:`~networkx.algorithms.link_analysis.hits_alg.hits`
|
| 281 |
+
|
| 282 |
+
Notes
|
| 283 |
+
-----
|
| 284 |
+
Katz centrality was introduced by [2]_.
|
| 285 |
+
|
| 286 |
+
This algorithm uses a direct linear solver to solve the above equation.
|
| 287 |
+
The parameter ``alpha`` should be strictly less than the inverse of largest
|
| 288 |
+
eigenvalue of the adjacency matrix for there to be a solution.
|
| 289 |
+
You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
|
| 290 |
+
eigenvalue of the adjacency matrix.
|
| 291 |
+
|
| 292 |
+
For strongly connected graphs, as $\alpha \to 1/\lambda_{\max}$, and $\beta > 0$,
|
| 293 |
+
Katz centrality approaches the results for eigenvector centrality.
|
| 294 |
+
|
| 295 |
+
For directed graphs this finds "left" eigenvectors which corresponds
|
| 296 |
+
to the in-edges in the graph. For out-edges Katz centrality,
|
| 297 |
+
first reverse the graph with ``G.reverse()``.
|
| 298 |
+
|
| 299 |
+
References
|
| 300 |
+
----------
|
| 301 |
+
.. [1] Mark E. J. Newman:
|
| 302 |
+
Networks: An Introduction.
|
| 303 |
+
Oxford University Press, USA, 2010, p. 173.
|
| 304 |
+
.. [2] Leo Katz:
|
| 305 |
+
A New Status Index Derived from Sociometric Index.
|
| 306 |
+
Psychometrika 18(1):39–43, 1953
|
| 307 |
+
https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
|
| 308 |
+
"""
|
| 309 |
+
import numpy as np
|
| 310 |
+
|
| 311 |
+
if len(G) == 0:
|
| 312 |
+
return {}
|
| 313 |
+
try:
|
| 314 |
+
nodelist = beta.keys()
|
| 315 |
+
if set(nodelist) != set(G):
|
| 316 |
+
raise nx.NetworkXError("beta dictionary must have a value for every node")
|
| 317 |
+
b = np.array(list(beta.values()), dtype=float)
|
| 318 |
+
except AttributeError:
|
| 319 |
+
nodelist = list(G)
|
| 320 |
+
try:
|
| 321 |
+
b = np.ones((len(nodelist), 1)) * beta
|
| 322 |
+
except (TypeError, ValueError, AttributeError) as err:
|
| 323 |
+
raise nx.NetworkXError("beta must be a number") from err
|
| 324 |
+
|
| 325 |
+
A = nx.adjacency_matrix(G, nodelist=nodelist, weight=weight).todense().T
|
| 326 |
+
n = A.shape[0]
|
| 327 |
+
centrality = np.linalg.solve(np.eye(n, n) - (alpha * A), b).squeeze()
|
| 328 |
+
|
| 329 |
+
# Normalize: rely on truediv to cast to float, then tolist to make Python numbers
|
| 330 |
+
norm = np.sign(sum(centrality)) * np.linalg.norm(centrality) if normalized else 1
|
| 331 |
+
return dict(zip(nodelist, (centrality / norm).tolist()))
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/laplacian.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Laplacian centrality measures.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
__all__ = ["laplacian_centrality"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 11 |
+
def laplacian_centrality(
|
| 12 |
+
G, normalized=True, nodelist=None, weight="weight", walk_type=None, alpha=0.95
|
| 13 |
+
):
|
| 14 |
+
r"""Compute the Laplacian centrality for nodes in the graph `G`.
|
| 15 |
+
|
| 16 |
+
The Laplacian Centrality of a node ``i`` is measured by the drop in the
|
| 17 |
+
Laplacian Energy after deleting node ``i`` from the graph. The Laplacian Energy
|
| 18 |
+
is the sum of the squared eigenvalues of a graph's Laplacian matrix.
|
| 19 |
+
|
| 20 |
+
.. math::
|
| 21 |
+
|
| 22 |
+
C_L(u_i,G) = \frac{(\Delta E)_i}{E_L (G)} = \frac{E_L (G)-E_L (G_i)}{E_L (G)}
|
| 23 |
+
|
| 24 |
+
E_L (G) = \sum_{i=0}^n \lambda_i^2
|
| 25 |
+
|
| 26 |
+
Where $E_L (G)$ is the Laplacian energy of graph `G`,
|
| 27 |
+
E_L (G_i) is the Laplacian energy of graph `G` after deleting node ``i``
|
| 28 |
+
and $\lambda_i$ are the eigenvalues of `G`'s Laplacian matrix.
|
| 29 |
+
This formula shows the normalized value. Without normalization,
|
| 30 |
+
the numerator on the right side is returned.
|
| 31 |
+
|
| 32 |
+
Parameters
|
| 33 |
+
----------
|
| 34 |
+
G : graph
|
| 35 |
+
A networkx graph
|
| 36 |
+
|
| 37 |
+
normalized : bool (default = True)
|
| 38 |
+
If True the centrality score is scaled so the sum over all nodes is 1.
|
| 39 |
+
If False the centrality score for each node is the drop in Laplacian
|
| 40 |
+
energy when that node is removed.
|
| 41 |
+
|
| 42 |
+
nodelist : list, optional (default = None)
|
| 43 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
| 44 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
| 45 |
+
|
| 46 |
+
weight: string or None, optional (default=`weight`)
|
| 47 |
+
Optional parameter `weight` to compute the Laplacian matrix.
|
| 48 |
+
The edge data key used to compute each value in the matrix.
|
| 49 |
+
If None, then each edge has weight 1.
|
| 50 |
+
|
| 51 |
+
walk_type : string or None, optional (default=None)
|
| 52 |
+
Optional parameter `walk_type` used when calling
|
| 53 |
+
:func:`directed_laplacian_matrix <networkx.directed_laplacian_matrix>`.
|
| 54 |
+
One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
|
| 55 |
+
(the default), then a value is selected according to the properties of `G`:
|
| 56 |
+
- ``walk_type="random"`` if `G` is strongly connected and aperiodic
|
| 57 |
+
- ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
|
| 58 |
+
- ``walk_type="pagerank"`` for all other cases.
|
| 59 |
+
|
| 60 |
+
alpha : real (default = 0.95)
|
| 61 |
+
Optional parameter `alpha` used when calling
|
| 62 |
+
:func:`directed_laplacian_matrix <networkx.directed_laplacian_matrix>`.
|
| 63 |
+
(1 - alpha) is the teleportation probability used with pagerank.
|
| 64 |
+
|
| 65 |
+
Returns
|
| 66 |
+
-------
|
| 67 |
+
nodes : dictionary
|
| 68 |
+
Dictionary of nodes with Laplacian centrality as the value.
|
| 69 |
+
|
| 70 |
+
Examples
|
| 71 |
+
--------
|
| 72 |
+
>>> G = nx.Graph()
|
| 73 |
+
>>> edges = [(0, 1, 4), (0, 2, 2), (2, 1, 1), (1, 3, 2), (1, 4, 2), (4, 5, 1)]
|
| 74 |
+
>>> G.add_weighted_edges_from(edges)
|
| 75 |
+
>>> sorted((v, f"{c:0.2f}") for v, c in laplacian_centrality(G).items())
|
| 76 |
+
[(0, '0.70'), (1, '0.90'), (2, '0.28'), (3, '0.22'), (4, '0.26'), (5, '0.04')]
|
| 77 |
+
|
| 78 |
+
Notes
|
| 79 |
+
-----
|
| 80 |
+
The algorithm is implemented based on [1]_ with an extension to directed graphs
|
| 81 |
+
using the ``directed_laplacian_matrix`` function.
|
| 82 |
+
|
| 83 |
+
Raises
|
| 84 |
+
------
|
| 85 |
+
NetworkXPointlessConcept
|
| 86 |
+
If the graph `G` is the null graph.
|
| 87 |
+
ZeroDivisionError
|
| 88 |
+
If the graph `G` has no edges (is empty) and normalization is requested.
|
| 89 |
+
|
| 90 |
+
References
|
| 91 |
+
----------
|
| 92 |
+
.. [1] Qi, X., Fuller, E., Wu, Q., Wu, Y., and Zhang, C.-Q. (2012).
|
| 93 |
+
Laplacian centrality: A new centrality measure for weighted networks.
|
| 94 |
+
Information Sciences, 194:240-253.
|
| 95 |
+
https://math.wvu.edu/~cqzhang/Publication-files/my-paper/INS-2012-Laplacian-W.pdf
|
| 96 |
+
|
| 97 |
+
See Also
|
| 98 |
+
--------
|
| 99 |
+
:func:`~networkx.linalg.laplacianmatrix.directed_laplacian_matrix`
|
| 100 |
+
:func:`~networkx.linalg.laplacianmatrix.laplacian_matrix`
|
| 101 |
+
"""
|
| 102 |
+
import numpy as np
|
| 103 |
+
import scipy as sp
|
| 104 |
+
|
| 105 |
+
if len(G) == 0:
|
| 106 |
+
raise nx.NetworkXPointlessConcept("null graph has no centrality defined")
|
| 107 |
+
if G.size(weight=weight) == 0:
|
| 108 |
+
if normalized:
|
| 109 |
+
raise ZeroDivisionError("graph with no edges has zero full energy")
|
| 110 |
+
return dict.fromkeys(G, 0)
|
| 111 |
+
|
| 112 |
+
if nodelist is not None:
|
| 113 |
+
nodeset = set(G.nbunch_iter(nodelist))
|
| 114 |
+
if len(nodeset) != len(nodelist):
|
| 115 |
+
raise nx.NetworkXError("nodelist has duplicate nodes or nodes not in G")
|
| 116 |
+
nodes = nodelist + [n for n in G if n not in nodeset]
|
| 117 |
+
else:
|
| 118 |
+
nodelist = nodes = list(G)
|
| 119 |
+
|
| 120 |
+
if G.is_directed():
|
| 121 |
+
lap_matrix = nx.directed_laplacian_matrix(G, nodes, weight, walk_type, alpha)
|
| 122 |
+
else:
|
| 123 |
+
lap_matrix = nx.laplacian_matrix(G, nodes, weight).toarray()
|
| 124 |
+
|
| 125 |
+
full_energy = np.sum(lap_matrix**2)
|
| 126 |
+
|
| 127 |
+
# calculate laplacian centrality
|
| 128 |
+
laplace_centralities_dict = {}
|
| 129 |
+
for i, node in enumerate(nodelist):
|
| 130 |
+
# remove row and col i from lap_matrix
|
| 131 |
+
all_but_i = list(np.arange(lap_matrix.shape[0]))
|
| 132 |
+
all_but_i.remove(i)
|
| 133 |
+
A_2 = lap_matrix[all_but_i, :][:, all_but_i]
|
| 134 |
+
|
| 135 |
+
# Adjust diagonal for removed row
|
| 136 |
+
new_diag = lap_matrix.diagonal() - abs(lap_matrix[:, i])
|
| 137 |
+
np.fill_diagonal(A_2, new_diag[all_but_i])
|
| 138 |
+
|
| 139 |
+
if len(all_but_i) > 0: # catches degenerate case of single node
|
| 140 |
+
new_energy = np.sum(A_2**2)
|
| 141 |
+
else:
|
| 142 |
+
new_energy = 0.0
|
| 143 |
+
|
| 144 |
+
lapl_cent = full_energy - new_energy
|
| 145 |
+
if normalized:
|
| 146 |
+
lapl_cent = lapl_cent / full_energy
|
| 147 |
+
|
| 148 |
+
laplace_centralities_dict[node] = float(lapl_cent)
|
| 149 |
+
|
| 150 |
+
return laplace_centralities_dict
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/load.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load centrality."""
|
| 2 |
+
|
| 3 |
+
from operator import itemgetter
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
__all__ = ["load_centrality", "edge_load_centrality"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 11 |
+
def newman_betweenness_centrality(G, v=None, cutoff=None, normalized=True, weight=None):
|
| 12 |
+
"""Compute load centrality for nodes.
|
| 13 |
+
|
| 14 |
+
The load centrality of a node is the fraction of all shortest
|
| 15 |
+
paths that pass through that node.
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
----------
|
| 19 |
+
G : graph
|
| 20 |
+
A networkx graph.
|
| 21 |
+
|
| 22 |
+
normalized : bool, optional (default=True)
|
| 23 |
+
If True the betweenness values are normalized by b=b/(n-1)(n-2) where
|
| 24 |
+
n is the number of nodes in G.
|
| 25 |
+
|
| 26 |
+
weight : None or string, optional (default=None)
|
| 27 |
+
If None, edge weights are ignored.
|
| 28 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 29 |
+
The weight of an edge is treated as the length or distance between the two sides.
|
| 30 |
+
|
| 31 |
+
cutoff : bool, optional (default=None)
|
| 32 |
+
If specified, only consider paths of length <= cutoff.
|
| 33 |
+
|
| 34 |
+
Returns
|
| 35 |
+
-------
|
| 36 |
+
nodes : dictionary
|
| 37 |
+
Dictionary of nodes with centrality as the value.
|
| 38 |
+
|
| 39 |
+
See Also
|
| 40 |
+
--------
|
| 41 |
+
betweenness_centrality
|
| 42 |
+
|
| 43 |
+
Notes
|
| 44 |
+
-----
|
| 45 |
+
Load centrality is slightly different than betweenness. It was originally
|
| 46 |
+
introduced by [2]_. For this load algorithm see [1]_.
|
| 47 |
+
|
| 48 |
+
References
|
| 49 |
+
----------
|
| 50 |
+
.. [1] Mark E. J. Newman:
|
| 51 |
+
Scientific collaboration networks. II.
|
| 52 |
+
Shortest paths, weighted networks, and centrality.
|
| 53 |
+
Physical Review E 64, 016132, 2001.
|
| 54 |
+
http://journals.aps.org/pre/abstract/10.1103/PhysRevE.64.016132
|
| 55 |
+
.. [2] Kwang-Il Goh, Byungnam Kahng and Doochul Kim
|
| 56 |
+
Universal behavior of Load Distribution in Scale-Free Networks.
|
| 57 |
+
Physical Review Letters 87(27):1–4, 2001.
|
| 58 |
+
https://doi.org/10.1103/PhysRevLett.87.278701
|
| 59 |
+
"""
|
| 60 |
+
if v is not None: # only one node
|
| 61 |
+
betweenness = 0.0
|
| 62 |
+
for source in G:
|
| 63 |
+
ubetween = _node_betweenness(G, source, cutoff, False, weight)
|
| 64 |
+
betweenness += ubetween[v] if v in ubetween else 0
|
| 65 |
+
if normalized:
|
| 66 |
+
order = G.order()
|
| 67 |
+
if order <= 2:
|
| 68 |
+
return betweenness # no normalization b=0 for all nodes
|
| 69 |
+
betweenness *= 1.0 / ((order - 1) * (order - 2))
|
| 70 |
+
else:
|
| 71 |
+
betweenness = {}.fromkeys(G, 0.0)
|
| 72 |
+
for source in betweenness:
|
| 73 |
+
ubetween = _node_betweenness(G, source, cutoff, False, weight)
|
| 74 |
+
for vk in ubetween:
|
| 75 |
+
betweenness[vk] += ubetween[vk]
|
| 76 |
+
if normalized:
|
| 77 |
+
order = G.order()
|
| 78 |
+
if order <= 2:
|
| 79 |
+
return betweenness # no normalization b=0 for all nodes
|
| 80 |
+
scale = 1.0 / ((order - 1) * (order - 2))
|
| 81 |
+
for v in betweenness:
|
| 82 |
+
betweenness[v] *= scale
|
| 83 |
+
return betweenness # all nodes
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _node_betweenness(G, source, cutoff=False, normalized=True, weight=None):
|
| 87 |
+
"""Node betweenness_centrality helper:
|
| 88 |
+
|
| 89 |
+
See betweenness_centrality for what you probably want.
|
| 90 |
+
This actually computes "load" and not betweenness.
|
| 91 |
+
See https://networkx.lanl.gov/ticket/103
|
| 92 |
+
|
| 93 |
+
This calculates the load of each node for paths from a single source.
|
| 94 |
+
(The fraction of number of shortests paths from source that go
|
| 95 |
+
through each node.)
|
| 96 |
+
|
| 97 |
+
To get the load for a node you need to do all-pairs shortest paths.
|
| 98 |
+
|
| 99 |
+
If weight is not None then use Dijkstra for finding shortest paths.
|
| 100 |
+
"""
|
| 101 |
+
# get the predecessor and path length data
|
| 102 |
+
if weight is None:
|
| 103 |
+
(pred, length) = nx.predecessor(G, source, cutoff=cutoff, return_seen=True)
|
| 104 |
+
else:
|
| 105 |
+
(pred, length) = nx.dijkstra_predecessor_and_distance(G, source, cutoff, weight)
|
| 106 |
+
|
| 107 |
+
# order the nodes by path length
|
| 108 |
+
onodes = [(l, vert) for (vert, l) in length.items()]
|
| 109 |
+
onodes.sort()
|
| 110 |
+
onodes[:] = [vert for (l, vert) in onodes if l > 0]
|
| 111 |
+
|
| 112 |
+
# initialize betweenness
|
| 113 |
+
between = {}.fromkeys(length, 1.0)
|
| 114 |
+
|
| 115 |
+
while onodes:
|
| 116 |
+
v = onodes.pop()
|
| 117 |
+
if v in pred:
|
| 118 |
+
num_paths = len(pred[v]) # Discount betweenness if more than
|
| 119 |
+
for x in pred[v]: # one shortest path.
|
| 120 |
+
if x == source: # stop if hit source because all remaining v
|
| 121 |
+
break # also have pred[v]==[source]
|
| 122 |
+
between[x] += between[v] / num_paths
|
| 123 |
+
# remove source
|
| 124 |
+
for v in between:
|
| 125 |
+
between[v] -= 1
|
| 126 |
+
# rescale to be between 0 and 1
|
| 127 |
+
if normalized:
|
| 128 |
+
l = len(between)
|
| 129 |
+
if l > 2:
|
| 130 |
+
# scale by 1/the number of possible paths
|
| 131 |
+
scale = 1 / ((l - 1) * (l - 2))
|
| 132 |
+
for v in between:
|
| 133 |
+
between[v] *= scale
|
| 134 |
+
return between
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
load_centrality = newman_betweenness_centrality
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@nx._dispatchable
|
| 141 |
+
def edge_load_centrality(G, cutoff=False):
|
| 142 |
+
"""Compute edge load.
|
| 143 |
+
|
| 144 |
+
WARNING: This concept of edge load has not been analysed
|
| 145 |
+
or discussed outside of NetworkX that we know of.
|
| 146 |
+
It is based loosely on load_centrality in the sense that
|
| 147 |
+
it counts the number of shortest paths which cross each edge.
|
| 148 |
+
This function is for demonstration and testing purposes.
|
| 149 |
+
|
| 150 |
+
Parameters
|
| 151 |
+
----------
|
| 152 |
+
G : graph
|
| 153 |
+
A networkx graph
|
| 154 |
+
|
| 155 |
+
cutoff : bool, optional (default=False)
|
| 156 |
+
If specified, only consider paths of length <= cutoff.
|
| 157 |
+
|
| 158 |
+
Returns
|
| 159 |
+
-------
|
| 160 |
+
A dict keyed by edge 2-tuple to the number of shortest paths
|
| 161 |
+
which use that edge. Where more than one path is shortest
|
| 162 |
+
the count is divided equally among paths.
|
| 163 |
+
"""
|
| 164 |
+
betweenness = {}
|
| 165 |
+
for u, v in G.edges():
|
| 166 |
+
betweenness[(u, v)] = 0.0
|
| 167 |
+
betweenness[(v, u)] = 0.0
|
| 168 |
+
|
| 169 |
+
for source in G:
|
| 170 |
+
ubetween = _edge_betweenness(G, source, cutoff=cutoff)
|
| 171 |
+
for e, ubetweenv in ubetween.items():
|
| 172 |
+
betweenness[e] += ubetweenv # cumulative total
|
| 173 |
+
return betweenness
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _edge_betweenness(G, source, nodes=None, cutoff=False):
|
| 177 |
+
"""Edge betweenness helper."""
|
| 178 |
+
# get the predecessor data
|
| 179 |
+
(pred, length) = nx.predecessor(G, source, cutoff=cutoff, return_seen=True)
|
| 180 |
+
# order the nodes by path length
|
| 181 |
+
onodes = [n for n, d in sorted(length.items(), key=itemgetter(1))]
|
| 182 |
+
# initialize betweenness, doesn't account for any edge weights
|
| 183 |
+
between = {}
|
| 184 |
+
for u, v in G.edges(nodes):
|
| 185 |
+
between[(u, v)] = 1.0
|
| 186 |
+
between[(v, u)] = 1.0
|
| 187 |
+
|
| 188 |
+
while onodes: # work through all paths
|
| 189 |
+
v = onodes.pop()
|
| 190 |
+
if v in pred:
|
| 191 |
+
# Discount betweenness if more than one shortest path.
|
| 192 |
+
num_paths = len(pred[v])
|
| 193 |
+
for w in pred[v]:
|
| 194 |
+
if w in pred:
|
| 195 |
+
# Discount betweenness, mult path
|
| 196 |
+
num_paths = len(pred[w])
|
| 197 |
+
for x in pred[w]:
|
| 198 |
+
between[(w, x)] += between[(v, w)] / num_paths
|
| 199 |
+
between[(x, w)] += between[(w, v)] / num_paths
|
| 200 |
+
return between
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/percolation.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Percolation centrality measures."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.algorithms.centrality.betweenness import (
|
| 5 |
+
_single_source_dijkstra_path_basic as dijkstra,
|
| 6 |
+
)
|
| 7 |
+
from networkx.algorithms.centrality.betweenness import (
|
| 8 |
+
_single_source_shortest_path_basic as shortest_path,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
__all__ = ["percolation_centrality"]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@nx._dispatchable(node_attrs="attribute", edge_attrs="weight")
|
| 15 |
+
def percolation_centrality(G, attribute="percolation", states=None, weight=None):
|
| 16 |
+
r"""Compute the percolation centrality for nodes.
|
| 17 |
+
|
| 18 |
+
Percolation centrality of a node $v$, at a given time, is defined
|
| 19 |
+
as the proportion of ‘percolated paths’ that go through that node.
|
| 20 |
+
|
| 21 |
+
This measure quantifies relative impact of nodes based on their
|
| 22 |
+
topological connectivity, as well as their percolation states.
|
| 23 |
+
|
| 24 |
+
Percolation states of nodes are used to depict network percolation
|
| 25 |
+
scenarios (such as during infection transmission in a social network
|
| 26 |
+
of individuals, spreading of computer viruses on computer networks, or
|
| 27 |
+
transmission of disease over a network of towns) over time. In this
|
| 28 |
+
measure usually the percolation state is expressed as a decimal
|
| 29 |
+
between 0.0 and 1.0.
|
| 30 |
+
|
| 31 |
+
When all nodes are in the same percolated state this measure is
|
| 32 |
+
equivalent to betweenness centrality.
|
| 33 |
+
|
| 34 |
+
Parameters
|
| 35 |
+
----------
|
| 36 |
+
G : graph
|
| 37 |
+
A NetworkX graph.
|
| 38 |
+
|
| 39 |
+
attribute : None or string, optional (default='percolation')
|
| 40 |
+
Name of the node attribute to use for percolation state, used
|
| 41 |
+
if `states` is None. If a node does not set the attribute the
|
| 42 |
+
state of that node will be set to the default value of 1.
|
| 43 |
+
If all nodes do not have the attribute all nodes will be set to
|
| 44 |
+
1 and the centrality measure will be equivalent to betweenness centrality.
|
| 45 |
+
|
| 46 |
+
states : None or dict, optional (default=None)
|
| 47 |
+
Specify percolation states for the nodes, nodes as keys states
|
| 48 |
+
as values.
|
| 49 |
+
|
| 50 |
+
weight : None or string, optional (default=None)
|
| 51 |
+
If None, all edge weights are considered equal.
|
| 52 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 53 |
+
The weight of an edge is treated as the length or distance between the two sides.
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
Returns
|
| 57 |
+
-------
|
| 58 |
+
nodes : dictionary
|
| 59 |
+
Dictionary of nodes with percolation centrality as the value.
|
| 60 |
+
|
| 61 |
+
See Also
|
| 62 |
+
--------
|
| 63 |
+
betweenness_centrality
|
| 64 |
+
|
| 65 |
+
Notes
|
| 66 |
+
-----
|
| 67 |
+
The algorithm is from Mahendra Piraveenan, Mikhail Prokopenko, and
|
| 68 |
+
Liaquat Hossain [1]_
|
| 69 |
+
Pair dependencies are calculated and accumulated using [2]_
|
| 70 |
+
|
| 71 |
+
For weighted graphs the edge weights must be greater than zero.
|
| 72 |
+
Zero edge weights can produce an infinite number of equal length
|
| 73 |
+
paths between pairs of nodes.
|
| 74 |
+
|
| 75 |
+
References
|
| 76 |
+
----------
|
| 77 |
+
.. [1] Mahendra Piraveenan, Mikhail Prokopenko, Liaquat Hossain
|
| 78 |
+
Percolation Centrality: Quantifying Graph-Theoretic Impact of Nodes
|
| 79 |
+
during Percolation in Networks
|
| 80 |
+
http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0053095
|
| 81 |
+
.. [2] Ulrik Brandes:
|
| 82 |
+
A Faster Algorithm for Betweenness Centrality.
|
| 83 |
+
Journal of Mathematical Sociology 25(2):163-177, 2001.
|
| 84 |
+
https://doi.org/10.1080/0022250X.2001.9990249
|
| 85 |
+
"""
|
| 86 |
+
percolation = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
|
| 87 |
+
|
| 88 |
+
nodes = G
|
| 89 |
+
|
| 90 |
+
if states is None:
|
| 91 |
+
states = nx.get_node_attributes(nodes, attribute, default=1)
|
| 92 |
+
|
| 93 |
+
# sum of all percolation states
|
| 94 |
+
p_sigma_x_t = 0.0
|
| 95 |
+
for v in states.values():
|
| 96 |
+
p_sigma_x_t += v
|
| 97 |
+
|
| 98 |
+
for s in nodes:
|
| 99 |
+
# single source shortest paths
|
| 100 |
+
if weight is None: # use BFS
|
| 101 |
+
S, P, sigma, _ = shortest_path(G, s)
|
| 102 |
+
else: # use Dijkstra's algorithm
|
| 103 |
+
S, P, sigma, _ = dijkstra(G, s, weight)
|
| 104 |
+
# accumulation
|
| 105 |
+
percolation = _accumulate_percolation(
|
| 106 |
+
percolation, S, P, sigma, s, states, p_sigma_x_t
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
n = len(G)
|
| 110 |
+
|
| 111 |
+
for v in percolation:
|
| 112 |
+
percolation[v] *= 1 / (n - 2)
|
| 113 |
+
|
| 114 |
+
return percolation
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _accumulate_percolation(percolation, S, P, sigma, s, states, p_sigma_x_t):
|
| 118 |
+
delta = dict.fromkeys(S, 0)
|
| 119 |
+
while S:
|
| 120 |
+
w = S.pop()
|
| 121 |
+
coeff = (1 + delta[w]) / sigma[w]
|
| 122 |
+
for v in P[w]:
|
| 123 |
+
delta[v] += sigma[v] * coeff
|
| 124 |
+
if w != s:
|
| 125 |
+
# percolation weight
|
| 126 |
+
pw_s_w = states[s] / (p_sigma_x_t - states[w])
|
| 127 |
+
percolation[w] += delta[w] * pw_s_w
|
| 128 |
+
return percolation
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/reaching.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for computing reaching centrality of a node or a graph."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.utils import pairwise
|
| 5 |
+
|
| 6 |
+
__all__ = ["global_reaching_centrality", "local_reaching_centrality"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _average_weight(G, path, weight=None):
|
| 10 |
+
"""Returns the average weight of an edge in a weighted path.
|
| 11 |
+
|
| 12 |
+
Parameters
|
| 13 |
+
----------
|
| 14 |
+
G : graph
|
| 15 |
+
A networkx graph.
|
| 16 |
+
|
| 17 |
+
path: list
|
| 18 |
+
A list of vertices that define the path.
|
| 19 |
+
|
| 20 |
+
weight : None or string, optional (default=None)
|
| 21 |
+
If None, edge weights are ignored. Then the average weight of an edge
|
| 22 |
+
is assumed to be the multiplicative inverse of the length of the path.
|
| 23 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 24 |
+
"""
|
| 25 |
+
path_length = len(path) - 1
|
| 26 |
+
if path_length <= 0:
|
| 27 |
+
return 0
|
| 28 |
+
if weight is None:
|
| 29 |
+
return 1 / path_length
|
| 30 |
+
total_weight = sum(G.edges[i, j][weight] for i, j in pairwise(path))
|
| 31 |
+
return total_weight / path_length
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 35 |
+
def global_reaching_centrality(G, weight=None, normalized=True):
|
| 36 |
+
"""Returns the global reaching centrality of a directed graph.
|
| 37 |
+
|
| 38 |
+
The *global reaching centrality* of a weighted directed graph is the
|
| 39 |
+
average over all nodes of the difference between the local reaching
|
| 40 |
+
centrality of the node and the greatest local reaching centrality of
|
| 41 |
+
any node in the graph [1]_. For more information on the local
|
| 42 |
+
reaching centrality, see :func:`local_reaching_centrality`.
|
| 43 |
+
Informally, the local reaching centrality is the proportion of the
|
| 44 |
+
graph that is reachable from the neighbors of the node.
|
| 45 |
+
|
| 46 |
+
Parameters
|
| 47 |
+
----------
|
| 48 |
+
G : DiGraph
|
| 49 |
+
A networkx DiGraph.
|
| 50 |
+
|
| 51 |
+
weight : None or string, optional (default=None)
|
| 52 |
+
Attribute to use for edge weights. If ``None``, each edge weight
|
| 53 |
+
is assumed to be one. A higher weight implies a stronger
|
| 54 |
+
connection between nodes and a *shorter* path length.
|
| 55 |
+
|
| 56 |
+
normalized : bool, optional (default=True)
|
| 57 |
+
Whether to normalize the edge weights by the total sum of edge
|
| 58 |
+
weights.
|
| 59 |
+
|
| 60 |
+
Returns
|
| 61 |
+
-------
|
| 62 |
+
h : float
|
| 63 |
+
The global reaching centrality of the graph.
|
| 64 |
+
|
| 65 |
+
Examples
|
| 66 |
+
--------
|
| 67 |
+
>>> G = nx.DiGraph()
|
| 68 |
+
>>> G.add_edge(1, 2)
|
| 69 |
+
>>> G.add_edge(1, 3)
|
| 70 |
+
>>> nx.global_reaching_centrality(G)
|
| 71 |
+
1.0
|
| 72 |
+
>>> G.add_edge(3, 2)
|
| 73 |
+
>>> nx.global_reaching_centrality(G)
|
| 74 |
+
0.75
|
| 75 |
+
|
| 76 |
+
See also
|
| 77 |
+
--------
|
| 78 |
+
local_reaching_centrality
|
| 79 |
+
|
| 80 |
+
References
|
| 81 |
+
----------
|
| 82 |
+
.. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek.
|
| 83 |
+
"Hierarchy Measure for Complex Networks."
|
| 84 |
+
*PLoS ONE* 7.3 (2012): e33799.
|
| 85 |
+
https://doi.org/10.1371/journal.pone.0033799
|
| 86 |
+
"""
|
| 87 |
+
if nx.is_negatively_weighted(G, weight=weight):
|
| 88 |
+
raise nx.NetworkXError("edge weights must be positive")
|
| 89 |
+
total_weight = G.size(weight=weight)
|
| 90 |
+
if total_weight <= 0:
|
| 91 |
+
raise nx.NetworkXError("Size of G must be positive")
|
| 92 |
+
# If provided, weights must be interpreted as connection strength
|
| 93 |
+
# (so higher weights are more likely to be chosen). However, the
|
| 94 |
+
# shortest path algorithms in NetworkX assume the provided "weight"
|
| 95 |
+
# is actually a distance (so edges with higher weight are less
|
| 96 |
+
# likely to be chosen). Therefore we need to invert the weights when
|
| 97 |
+
# computing shortest paths.
|
| 98 |
+
#
|
| 99 |
+
# If weight is None, we leave it as-is so that the shortest path
|
| 100 |
+
# algorithm can use a faster, unweighted algorithm.
|
| 101 |
+
if weight is not None:
|
| 102 |
+
|
| 103 |
+
def as_distance(u, v, d):
|
| 104 |
+
return total_weight / d.get(weight, 1)
|
| 105 |
+
|
| 106 |
+
shortest_paths = dict(nx.shortest_path(G, weight=as_distance))
|
| 107 |
+
else:
|
| 108 |
+
shortest_paths = dict(nx.shortest_path(G))
|
| 109 |
+
|
| 110 |
+
centrality = local_reaching_centrality
|
| 111 |
+
# TODO This can be trivially parallelized.
|
| 112 |
+
lrc = [
|
| 113 |
+
centrality(G, node, paths=paths, weight=weight, normalized=normalized)
|
| 114 |
+
for node, paths in shortest_paths.items()
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
max_lrc = max(lrc)
|
| 118 |
+
return sum(max_lrc - c for c in lrc) / (len(G) - 1)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 122 |
+
def local_reaching_centrality(G, v, paths=None, weight=None, normalized=True):
|
| 123 |
+
"""Returns the local reaching centrality of a node in a directed
|
| 124 |
+
graph.
|
| 125 |
+
|
| 126 |
+
The *local reaching centrality* of a node in a directed graph is the
|
| 127 |
+
proportion of other nodes reachable from that node [1]_.
|
| 128 |
+
|
| 129 |
+
Parameters
|
| 130 |
+
----------
|
| 131 |
+
G : DiGraph
|
| 132 |
+
A NetworkX DiGraph.
|
| 133 |
+
|
| 134 |
+
v : node
|
| 135 |
+
A node in the directed graph `G`.
|
| 136 |
+
|
| 137 |
+
paths : dictionary (default=None)
|
| 138 |
+
If this is not `None` it must be a dictionary representation
|
| 139 |
+
of single-source shortest paths, as computed by, for example,
|
| 140 |
+
:func:`networkx.shortest_path` with source node `v`. Use this
|
| 141 |
+
keyword argument if you intend to invoke this function many
|
| 142 |
+
times but don't want the paths to be recomputed each time.
|
| 143 |
+
|
| 144 |
+
weight : None or string, optional (default=None)
|
| 145 |
+
Attribute to use for edge weights. If `None`, each edge weight
|
| 146 |
+
is assumed to be one. A higher weight implies a stronger
|
| 147 |
+
connection between nodes and a *shorter* path length.
|
| 148 |
+
|
| 149 |
+
normalized : bool, optional (default=True)
|
| 150 |
+
Whether to normalize the edge weights by the total sum of edge
|
| 151 |
+
weights.
|
| 152 |
+
|
| 153 |
+
Returns
|
| 154 |
+
-------
|
| 155 |
+
h : float
|
| 156 |
+
The local reaching centrality of the node ``v`` in the graph
|
| 157 |
+
``G``.
|
| 158 |
+
|
| 159 |
+
Examples
|
| 160 |
+
--------
|
| 161 |
+
>>> G = nx.DiGraph()
|
| 162 |
+
>>> G.add_edges_from([(1, 2), (1, 3)])
|
| 163 |
+
>>> nx.local_reaching_centrality(G, 3)
|
| 164 |
+
0.0
|
| 165 |
+
>>> G.add_edge(3, 2)
|
| 166 |
+
>>> nx.local_reaching_centrality(G, 3)
|
| 167 |
+
0.5
|
| 168 |
+
|
| 169 |
+
See also
|
| 170 |
+
--------
|
| 171 |
+
global_reaching_centrality
|
| 172 |
+
|
| 173 |
+
References
|
| 174 |
+
----------
|
| 175 |
+
.. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek.
|
| 176 |
+
"Hierarchy Measure for Complex Networks."
|
| 177 |
+
*PLoS ONE* 7.3 (2012): e33799.
|
| 178 |
+
https://doi.org/10.1371/journal.pone.0033799
|
| 179 |
+
"""
|
| 180 |
+
# Corner case: graph with single node containing a self-loop
|
| 181 |
+
if (total_weight := G.size(weight=weight)) > 0 and len(G) == 1:
|
| 182 |
+
raise nx.NetworkXError(
|
| 183 |
+
"local_reaching_centrality of a single node with self-loop not well-defined"
|
| 184 |
+
)
|
| 185 |
+
if paths is None:
|
| 186 |
+
if nx.is_negatively_weighted(G, weight=weight):
|
| 187 |
+
raise nx.NetworkXError("edge weights must be positive")
|
| 188 |
+
if total_weight <= 0:
|
| 189 |
+
raise nx.NetworkXError("Size of G must be positive")
|
| 190 |
+
if weight is not None:
|
| 191 |
+
# Interpret weights as lengths.
|
| 192 |
+
def as_distance(u, v, d):
|
| 193 |
+
return total_weight / d.get(weight, 1)
|
| 194 |
+
|
| 195 |
+
paths = nx.shortest_path(G, source=v, weight=as_distance)
|
| 196 |
+
else:
|
| 197 |
+
paths = nx.shortest_path(G, source=v)
|
| 198 |
+
# If the graph is unweighted, simply return the proportion of nodes
|
| 199 |
+
# reachable from the source node ``v``.
|
| 200 |
+
if weight is None and G.is_directed():
|
| 201 |
+
return (len(paths) - 1) / (len(G) - 1)
|
| 202 |
+
if normalized and weight is not None:
|
| 203 |
+
norm = G.size(weight=weight) / G.size()
|
| 204 |
+
else:
|
| 205 |
+
norm = 1
|
| 206 |
+
# TODO This can be trivially parallelized.
|
| 207 |
+
avgw = (_average_weight(G, path, weight=weight) for path in paths.values())
|
| 208 |
+
sum_avg_weight = sum(avgw) / norm
|
| 209 |
+
return sum_avg_weight / (len(G) - 1)
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/second_order.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Copyright (c) 2015 – Thomson Licensing, SAS
|
| 2 |
+
|
| 3 |
+
Redistribution and use in source and binary forms, with or without
|
| 4 |
+
modification, are permitted (subject to the limitations in the
|
| 5 |
+
disclaimer below) provided that the following conditions are met:
|
| 6 |
+
|
| 7 |
+
* Redistributions of source code must retain the above copyright
|
| 8 |
+
notice, this list of conditions and the following disclaimer.
|
| 9 |
+
|
| 10 |
+
* Redistributions in binary form must reproduce the above copyright
|
| 11 |
+
notice, this list of conditions and the following disclaimer in the
|
| 12 |
+
documentation and/or other materials provided with the distribution.
|
| 13 |
+
|
| 14 |
+
* Neither the name of Thomson Licensing, or Technicolor, nor the names
|
| 15 |
+
of its contributors may be used to endorse or promote products derived
|
| 16 |
+
from this software without specific prior written permission.
|
| 17 |
+
|
| 18 |
+
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
|
| 19 |
+
GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
|
| 20 |
+
HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
|
| 21 |
+
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
| 22 |
+
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 23 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
| 24 |
+
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
| 25 |
+
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
| 26 |
+
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
| 27 |
+
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
| 28 |
+
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
|
| 29 |
+
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
|
| 30 |
+
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
import networkx as nx
|
| 34 |
+
from networkx.utils import not_implemented_for
|
| 35 |
+
|
| 36 |
+
# Authors: Erwan Le Merrer (erwan.lemerrer@technicolor.com)
|
| 37 |
+
|
| 38 |
+
__all__ = ["second_order_centrality"]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@not_implemented_for("directed")
|
| 42 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 43 |
+
def second_order_centrality(G, weight="weight"):
|
| 44 |
+
"""Compute the second order centrality for nodes of G.
|
| 45 |
+
|
| 46 |
+
The second order centrality of a given node is the standard deviation of
|
| 47 |
+
the return times to that node of a perpetual random walk on G:
|
| 48 |
+
|
| 49 |
+
Parameters
|
| 50 |
+
----------
|
| 51 |
+
G : graph
|
| 52 |
+
A NetworkX connected and undirected graph.
|
| 53 |
+
|
| 54 |
+
weight : string or None, optional (default="weight")
|
| 55 |
+
The name of an edge attribute that holds the numerical value
|
| 56 |
+
used as a weight. If None then each edge has weight 1.
|
| 57 |
+
|
| 58 |
+
Returns
|
| 59 |
+
-------
|
| 60 |
+
nodes : dictionary
|
| 61 |
+
Dictionary keyed by node with second order centrality as the value.
|
| 62 |
+
|
| 63 |
+
Examples
|
| 64 |
+
--------
|
| 65 |
+
>>> G = nx.star_graph(10)
|
| 66 |
+
>>> soc = nx.second_order_centrality(G)
|
| 67 |
+
>>> print(sorted(soc.items(), key=lambda x: x[1])[0][0]) # pick first id
|
| 68 |
+
0
|
| 69 |
+
|
| 70 |
+
Raises
|
| 71 |
+
------
|
| 72 |
+
NetworkXException
|
| 73 |
+
If the graph G is empty, non connected or has negative weights.
|
| 74 |
+
|
| 75 |
+
See Also
|
| 76 |
+
--------
|
| 77 |
+
betweenness_centrality
|
| 78 |
+
|
| 79 |
+
Notes
|
| 80 |
+
-----
|
| 81 |
+
Lower values of second order centrality indicate higher centrality.
|
| 82 |
+
|
| 83 |
+
The algorithm is from Kermarrec, Le Merrer, Sericola and Trédan [1]_.
|
| 84 |
+
|
| 85 |
+
This code implements the analytical version of the algorithm, i.e.,
|
| 86 |
+
there is no simulation of a random walk process involved. The random walk
|
| 87 |
+
is here unbiased (corresponding to eq 6 of the paper [1]_), thus the
|
| 88 |
+
centrality values are the standard deviations for random walk return times
|
| 89 |
+
on the transformed input graph G (equal in-degree at each nodes by adding
|
| 90 |
+
self-loops).
|
| 91 |
+
|
| 92 |
+
Complexity of this implementation, made to run locally on a single machine,
|
| 93 |
+
is O(n^3), with n the size of G, which makes it viable only for small
|
| 94 |
+
graphs.
|
| 95 |
+
|
| 96 |
+
References
|
| 97 |
+
----------
|
| 98 |
+
.. [1] Anne-Marie Kermarrec, Erwan Le Merrer, Bruno Sericola, Gilles Trédan
|
| 99 |
+
"Second order centrality: Distributed assessment of nodes criticity in
|
| 100 |
+
complex networks", Elsevier Computer Communications 34(5):619-628, 2011.
|
| 101 |
+
"""
|
| 102 |
+
import numpy as np
|
| 103 |
+
|
| 104 |
+
n = len(G)
|
| 105 |
+
|
| 106 |
+
if n == 0:
|
| 107 |
+
raise nx.NetworkXException("Empty graph.")
|
| 108 |
+
if not nx.is_connected(G):
|
| 109 |
+
raise nx.NetworkXException("Non connected graph.")
|
| 110 |
+
if any(d.get(weight, 0) < 0 for u, v, d in G.edges(data=True)):
|
| 111 |
+
raise nx.NetworkXException("Graph has negative edge weights.")
|
| 112 |
+
|
| 113 |
+
# balancing G for Metropolis-Hastings random walks
|
| 114 |
+
G = nx.DiGraph(G)
|
| 115 |
+
in_deg = dict(G.in_degree(weight=weight))
|
| 116 |
+
d_max = max(in_deg.values())
|
| 117 |
+
for i, deg in in_deg.items():
|
| 118 |
+
if deg < d_max:
|
| 119 |
+
G.add_edge(i, i, weight=d_max - deg)
|
| 120 |
+
|
| 121 |
+
P = nx.to_numpy_array(G)
|
| 122 |
+
P /= P.sum(axis=1)[:, np.newaxis] # to transition probability matrix
|
| 123 |
+
|
| 124 |
+
def _Qj(P, j):
|
| 125 |
+
P = P.copy()
|
| 126 |
+
P[:, j] = 0
|
| 127 |
+
return P
|
| 128 |
+
|
| 129 |
+
M = np.empty([n, n])
|
| 130 |
+
|
| 131 |
+
for i in range(n):
|
| 132 |
+
M[:, i] = np.linalg.solve(
|
| 133 |
+
np.identity(n) - _Qj(P, i), np.ones([n, 1])[:, 0]
|
| 134 |
+
) # eq 3
|
| 135 |
+
|
| 136 |
+
return dict(
|
| 137 |
+
zip(
|
| 138 |
+
G.nodes,
|
| 139 |
+
(float(np.sqrt(2 * np.sum(M[:, i]) - n * (n + 1))) for i in range(n)),
|
| 140 |
+
)
|
| 141 |
+
) # eq 6
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/centrality/subgraph_alg.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Subraph centrality and communicability betweenness.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"subgraph_centrality_exp",
|
| 10 |
+
"subgraph_centrality",
|
| 11 |
+
"communicability_betweenness_centrality",
|
| 12 |
+
"estrada_index",
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@not_implemented_for("directed")
|
| 17 |
+
@not_implemented_for("multigraph")
|
| 18 |
+
@nx._dispatchable
|
| 19 |
+
def subgraph_centrality_exp(G):
|
| 20 |
+
r"""Returns the subgraph centrality for each node of G.
|
| 21 |
+
|
| 22 |
+
Subgraph centrality of a node `n` is the sum of weighted closed
|
| 23 |
+
walks of all lengths starting and ending at node `n`. The weights
|
| 24 |
+
decrease with path length. Each closed walk is associated with a
|
| 25 |
+
connected subgraph ([1]_).
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
G: graph
|
| 30 |
+
|
| 31 |
+
Returns
|
| 32 |
+
-------
|
| 33 |
+
nodes:dictionary
|
| 34 |
+
Dictionary of nodes with subgraph centrality as the value.
|
| 35 |
+
|
| 36 |
+
Raises
|
| 37 |
+
------
|
| 38 |
+
NetworkXError
|
| 39 |
+
If the graph is not undirected and simple.
|
| 40 |
+
|
| 41 |
+
See Also
|
| 42 |
+
--------
|
| 43 |
+
subgraph_centrality:
|
| 44 |
+
Alternative algorithm of the subgraph centrality for each node of G.
|
| 45 |
+
|
| 46 |
+
Notes
|
| 47 |
+
-----
|
| 48 |
+
This version of the algorithm exponentiates the adjacency matrix.
|
| 49 |
+
|
| 50 |
+
The subgraph centrality of a node `u` in G can be found using
|
| 51 |
+
the matrix exponential of the adjacency matrix of G [1]_,
|
| 52 |
+
|
| 53 |
+
.. math::
|
| 54 |
+
|
| 55 |
+
SC(u)=(e^A)_{uu} .
|
| 56 |
+
|
| 57 |
+
References
|
| 58 |
+
----------
|
| 59 |
+
.. [1] Ernesto Estrada, Juan A. Rodriguez-Velazquez,
|
| 60 |
+
"Subgraph centrality in complex networks",
|
| 61 |
+
Physical Review E 71, 056103 (2005).
|
| 62 |
+
https://arxiv.org/abs/cond-mat/0504730
|
| 63 |
+
|
| 64 |
+
Examples
|
| 65 |
+
--------
|
| 66 |
+
(Example from [1]_)
|
| 67 |
+
|
| 68 |
+
>>> G = nx.Graph(
|
| 69 |
+
... [
|
| 70 |
+
... (1, 2),
|
| 71 |
+
... (1, 5),
|
| 72 |
+
... (1, 8),
|
| 73 |
+
... (2, 3),
|
| 74 |
+
... (2, 8),
|
| 75 |
+
... (3, 4),
|
| 76 |
+
... (3, 6),
|
| 77 |
+
... (4, 5),
|
| 78 |
+
... (4, 7),
|
| 79 |
+
... (5, 6),
|
| 80 |
+
... (6, 7),
|
| 81 |
+
... (7, 8),
|
| 82 |
+
... ]
|
| 83 |
+
... )
|
| 84 |
+
>>> sc = nx.subgraph_centrality_exp(G)
|
| 85 |
+
>>> print([f"{node} {sc[node]:0.2f}" for node in sorted(sc)])
|
| 86 |
+
['1 3.90', '2 3.90', '3 3.64', '4 3.71', '5 3.64', '6 3.71', '7 3.64', '8 3.90']
|
| 87 |
+
"""
|
| 88 |
+
# alternative implementation that calculates the matrix exponential
|
| 89 |
+
import scipy as sp
|
| 90 |
+
|
| 91 |
+
nodelist = list(G) # ordering of nodes in matrix
|
| 92 |
+
A = nx.to_numpy_array(G, nodelist)
|
| 93 |
+
# convert to 0-1 matrix
|
| 94 |
+
A[A != 0.0] = 1
|
| 95 |
+
expA = sp.linalg.expm(A)
|
| 96 |
+
# convert diagonal to dictionary keyed by node
|
| 97 |
+
sc = dict(zip(nodelist, map(float, expA.diagonal())))
|
| 98 |
+
return sc
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@not_implemented_for("directed")
|
| 102 |
+
@not_implemented_for("multigraph")
|
| 103 |
+
@nx._dispatchable
|
| 104 |
+
def subgraph_centrality(G):
|
| 105 |
+
r"""Returns subgraph centrality for each node in G.
|
| 106 |
+
|
| 107 |
+
Subgraph centrality of a node `n` is the sum of weighted closed
|
| 108 |
+
walks of all lengths starting and ending at node `n`. The weights
|
| 109 |
+
decrease with path length. Each closed walk is associated with a
|
| 110 |
+
connected subgraph ([1]_).
|
| 111 |
+
|
| 112 |
+
Parameters
|
| 113 |
+
----------
|
| 114 |
+
G: graph
|
| 115 |
+
|
| 116 |
+
Returns
|
| 117 |
+
-------
|
| 118 |
+
nodes : dictionary
|
| 119 |
+
Dictionary of nodes with subgraph centrality as the value.
|
| 120 |
+
|
| 121 |
+
Raises
|
| 122 |
+
------
|
| 123 |
+
NetworkXError
|
| 124 |
+
If the graph is not undirected and simple.
|
| 125 |
+
|
| 126 |
+
See Also
|
| 127 |
+
--------
|
| 128 |
+
subgraph_centrality_exp:
|
| 129 |
+
Alternative algorithm of the subgraph centrality for each node of G.
|
| 130 |
+
|
| 131 |
+
Notes
|
| 132 |
+
-----
|
| 133 |
+
This version of the algorithm computes eigenvalues and eigenvectors
|
| 134 |
+
of the adjacency matrix.
|
| 135 |
+
|
| 136 |
+
Subgraph centrality of a node `u` in G can be found using
|
| 137 |
+
a spectral decomposition of the adjacency matrix [1]_,
|
| 138 |
+
|
| 139 |
+
.. math::
|
| 140 |
+
|
| 141 |
+
SC(u)=\sum_{j=1}^{N}(v_{j}^{u})^2 e^{\lambda_{j}},
|
| 142 |
+
|
| 143 |
+
where `v_j` is an eigenvector of the adjacency matrix `A` of G
|
| 144 |
+
corresponding to the eigenvalue `\lambda_j`.
|
| 145 |
+
|
| 146 |
+
Examples
|
| 147 |
+
--------
|
| 148 |
+
(Example from [1]_)
|
| 149 |
+
|
| 150 |
+
>>> G = nx.Graph(
|
| 151 |
+
... [
|
| 152 |
+
... (1, 2),
|
| 153 |
+
... (1, 5),
|
| 154 |
+
... (1, 8),
|
| 155 |
+
... (2, 3),
|
| 156 |
+
... (2, 8),
|
| 157 |
+
... (3, 4),
|
| 158 |
+
... (3, 6),
|
| 159 |
+
... (4, 5),
|
| 160 |
+
... (4, 7),
|
| 161 |
+
... (5, 6),
|
| 162 |
+
... (6, 7),
|
| 163 |
+
... (7, 8),
|
| 164 |
+
... ]
|
| 165 |
+
... )
|
| 166 |
+
>>> sc = nx.subgraph_centrality(G)
|
| 167 |
+
>>> print([f"{node} {sc[node]:0.2f}" for node in sorted(sc)])
|
| 168 |
+
['1 3.90', '2 3.90', '3 3.64', '4 3.71', '5 3.64', '6 3.71', '7 3.64', '8 3.90']
|
| 169 |
+
|
| 170 |
+
References
|
| 171 |
+
----------
|
| 172 |
+
.. [1] Ernesto Estrada, Juan A. Rodriguez-Velazquez,
|
| 173 |
+
"Subgraph centrality in complex networks",
|
| 174 |
+
Physical Review E 71, 056103 (2005).
|
| 175 |
+
https://arxiv.org/abs/cond-mat/0504730
|
| 176 |
+
|
| 177 |
+
"""
|
| 178 |
+
import numpy as np
|
| 179 |
+
|
| 180 |
+
nodelist = list(G) # ordering of nodes in matrix
|
| 181 |
+
A = nx.to_numpy_array(G, nodelist)
|
| 182 |
+
# convert to 0-1 matrix
|
| 183 |
+
A[np.nonzero(A)] = 1
|
| 184 |
+
w, v = np.linalg.eigh(A)
|
| 185 |
+
vsquare = np.array(v) ** 2
|
| 186 |
+
expw = np.exp(w)
|
| 187 |
+
xg = vsquare @ expw
|
| 188 |
+
# convert vector dictionary keyed by node
|
| 189 |
+
sc = dict(zip(nodelist, map(float, xg)))
|
| 190 |
+
return sc
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@not_implemented_for("directed")
|
| 194 |
+
@not_implemented_for("multigraph")
|
| 195 |
+
@nx._dispatchable
|
| 196 |
+
def communicability_betweenness_centrality(G):
|
| 197 |
+
r"""Returns subgraph communicability for all pairs of nodes in G.
|
| 198 |
+
|
| 199 |
+
Communicability betweenness measure makes use of the number of walks
|
| 200 |
+
connecting every pair of nodes as the basis of a betweenness centrality
|
| 201 |
+
measure.
|
| 202 |
+
|
| 203 |
+
Parameters
|
| 204 |
+
----------
|
| 205 |
+
G: graph
|
| 206 |
+
|
| 207 |
+
Returns
|
| 208 |
+
-------
|
| 209 |
+
nodes : dictionary
|
| 210 |
+
Dictionary of nodes with communicability betweenness as the value.
|
| 211 |
+
|
| 212 |
+
Raises
|
| 213 |
+
------
|
| 214 |
+
NetworkXError
|
| 215 |
+
If the graph is not undirected and simple.
|
| 216 |
+
|
| 217 |
+
Notes
|
| 218 |
+
-----
|
| 219 |
+
Let `G=(V,E)` be a simple undirected graph with `n` nodes and `m` edges,
|
| 220 |
+
and `A` denote the adjacency matrix of `G`.
|
| 221 |
+
|
| 222 |
+
Let `G(r)=(V,E(r))` be the graph resulting from
|
| 223 |
+
removing all edges connected to node `r` but not the node itself.
|
| 224 |
+
|
| 225 |
+
The adjacency matrix for `G(r)` is `A+E(r)`, where `E(r)` has nonzeros
|
| 226 |
+
only in row and column `r`.
|
| 227 |
+
|
| 228 |
+
The subraph betweenness of a node `r` is [1]_
|
| 229 |
+
|
| 230 |
+
.. math::
|
| 231 |
+
|
| 232 |
+
\omega_{r} = \frac{1}{C}\sum_{p}\sum_{q}\frac{G_{prq}}{G_{pq}},
|
| 233 |
+
p\neq q, q\neq r,
|
| 234 |
+
|
| 235 |
+
where
|
| 236 |
+
`G_{prq}=(e^{A}_{pq} - (e^{A+E(r)})_{pq}` is the number of walks
|
| 237 |
+
involving node r,
|
| 238 |
+
`G_{pq}=(e^{A})_{pq}` is the number of closed walks starting
|
| 239 |
+
at node `p` and ending at node `q`,
|
| 240 |
+
and `C=(n-1)^{2}-(n-1)` is a normalization factor equal to the
|
| 241 |
+
number of terms in the sum.
|
| 242 |
+
|
| 243 |
+
The resulting `\omega_{r}` takes values between zero and one.
|
| 244 |
+
The lower bound cannot be attained for a connected
|
| 245 |
+
graph, and the upper bound is attained in the star graph.
|
| 246 |
+
|
| 247 |
+
References
|
| 248 |
+
----------
|
| 249 |
+
.. [1] Ernesto Estrada, Desmond J. Higham, Naomichi Hatano,
|
| 250 |
+
"Communicability Betweenness in Complex Networks"
|
| 251 |
+
Physica A 388 (2009) 764-774.
|
| 252 |
+
https://arxiv.org/abs/0905.4102
|
| 253 |
+
|
| 254 |
+
Examples
|
| 255 |
+
--------
|
| 256 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
|
| 257 |
+
>>> cbc = nx.communicability_betweenness_centrality(G)
|
| 258 |
+
>>> print([f"{node} {cbc[node]:0.2f}" for node in sorted(cbc)])
|
| 259 |
+
['0 0.03', '1 0.45', '2 0.51', '3 0.45', '4 0.40', '5 0.19', '6 0.03']
|
| 260 |
+
"""
|
| 261 |
+
import numpy as np
|
| 262 |
+
import scipy as sp
|
| 263 |
+
|
| 264 |
+
nodelist = list(G) # ordering of nodes in matrix
|
| 265 |
+
n = len(nodelist)
|
| 266 |
+
A = nx.to_numpy_array(G, nodelist)
|
| 267 |
+
# convert to 0-1 matrix
|
| 268 |
+
A[np.nonzero(A)] = 1
|
| 269 |
+
expA = sp.linalg.expm(A)
|
| 270 |
+
mapping = dict(zip(nodelist, range(n)))
|
| 271 |
+
cbc = {}
|
| 272 |
+
for v in G:
|
| 273 |
+
# remove row and col of node v
|
| 274 |
+
i = mapping[v]
|
| 275 |
+
row = A[i, :].copy()
|
| 276 |
+
col = A[:, i].copy()
|
| 277 |
+
A[i, :] = 0
|
| 278 |
+
A[:, i] = 0
|
| 279 |
+
B = (expA - sp.linalg.expm(A)) / expA
|
| 280 |
+
# sum with row/col of node v and diag set to zero
|
| 281 |
+
B[i, :] = 0
|
| 282 |
+
B[:, i] = 0
|
| 283 |
+
B -= np.diag(np.diag(B))
|
| 284 |
+
cbc[v] = float(B.sum())
|
| 285 |
+
# put row and col back
|
| 286 |
+
A[i, :] = row
|
| 287 |
+
A[:, i] = col
|
| 288 |
+
# rescale when more than two nodes
|
| 289 |
+
order = len(cbc)
|
| 290 |
+
if order > 2:
|
| 291 |
+
scale = 1.0 / ((order - 1.0) ** 2 - (order - 1.0))
|
| 292 |
+
cbc = {node: value * scale for node, value in cbc.items()}
|
| 293 |
+
return cbc
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
@nx._dispatchable
|
| 297 |
+
def estrada_index(G):
|
| 298 |
+
r"""Returns the Estrada index of a the graph G.
|
| 299 |
+
|
| 300 |
+
The Estrada Index is a topological index of folding or 3D "compactness" ([1]_).
|
| 301 |
+
|
| 302 |
+
Parameters
|
| 303 |
+
----------
|
| 304 |
+
G: graph
|
| 305 |
+
|
| 306 |
+
Returns
|
| 307 |
+
-------
|
| 308 |
+
estrada index: float
|
| 309 |
+
|
| 310 |
+
Raises
|
| 311 |
+
------
|
| 312 |
+
NetworkXError
|
| 313 |
+
If the graph is not undirected and simple.
|
| 314 |
+
|
| 315 |
+
Notes
|
| 316 |
+
-----
|
| 317 |
+
Let `G=(V,E)` be a simple undirected graph with `n` nodes and let
|
| 318 |
+
`\lambda_{1}\leq\lambda_{2}\leq\cdots\lambda_{n}`
|
| 319 |
+
be a non-increasing ordering of the eigenvalues of its adjacency
|
| 320 |
+
matrix `A`. The Estrada index is ([1]_, [2]_)
|
| 321 |
+
|
| 322 |
+
.. math::
|
| 323 |
+
EE(G)=\sum_{j=1}^n e^{\lambda _j}.
|
| 324 |
+
|
| 325 |
+
References
|
| 326 |
+
----------
|
| 327 |
+
.. [1] E. Estrada, "Characterization of 3D molecular structure",
|
| 328 |
+
Chem. Phys. Lett. 319, 713 (2000).
|
| 329 |
+
https://doi.org/10.1016/S0009-2614(00)00158-5
|
| 330 |
+
.. [2] José Antonio de la Peñaa, Ivan Gutman, Juan Rada,
|
| 331 |
+
"Estimating the Estrada index",
|
| 332 |
+
Linear Algebra and its Applications. 427, 1 (2007).
|
| 333 |
+
https://doi.org/10.1016/j.laa.2007.06.020
|
| 334 |
+
|
| 335 |
+
Examples
|
| 336 |
+
--------
|
| 337 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
|
| 338 |
+
>>> ei = nx.estrada_index(G)
|
| 339 |
+
>>> print(f"{ei:0.5}")
|
| 340 |
+
20.55
|
| 341 |
+
"""
|
| 342 |
+
return sum(subgraph_centrality(G).values())
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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())))
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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"]
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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}
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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()}
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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.centrality import *
|
| 18 |
+
from networkx.algorithms.community.divisive import *
|
| 19 |
+
from networkx.algorithms.community.kclique import *
|
| 20 |
+
from networkx.algorithms.community.kernighan_lin 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 *
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/networkx/algorithms/community/asyn_fluid.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Initialization
|
| 80 |
+
max_density = 1.0
|
| 81 |
+
vertices = list(G)
|
| 82 |
+
seed.shuffle(vertices)
|
| 83 |
+
communities = {n: i for i, n in enumerate(vertices[:k])}
|
| 84 |
+
density = {}
|
| 85 |
+
com_to_numvertices = {}
|
| 86 |
+
for vertex in communities:
|
| 87 |
+
com_to_numvertices[communities[vertex]] = 1
|
| 88 |
+
density[communities[vertex]] = max_density
|
| 89 |
+
# Set up control variables and start iterating
|
| 90 |
+
iter_count = 0
|
| 91 |
+
cont = True
|
| 92 |
+
while cont:
|
| 93 |
+
cont = False
|
| 94 |
+
iter_count += 1
|
| 95 |
+
# Loop over all vertices in graph in a random order
|
| 96 |
+
vertices = list(G)
|
| 97 |
+
seed.shuffle(vertices)
|
| 98 |
+
for vertex in vertices:
|
| 99 |
+
# Updating rule
|
| 100 |
+
com_counter = Counter()
|
| 101 |
+
# Take into account self vertex community
|
| 102 |
+
try:
|
| 103 |
+
com_counter.update({communities[vertex]: density[communities[vertex]]})
|
| 104 |
+
except KeyError:
|
| 105 |
+
pass
|
| 106 |
+
# Gather neighbor vertex communities
|
| 107 |
+
for v in G[vertex]:
|
| 108 |
+
try:
|
| 109 |
+
com_counter.update({communities[v]: density[communities[v]]})
|
| 110 |
+
except KeyError:
|
| 111 |
+
continue
|
| 112 |
+
# Check which is the community with highest density
|
| 113 |
+
new_com = -1
|
| 114 |
+
if len(com_counter.keys()) > 0:
|
| 115 |
+
max_freq = max(com_counter.values())
|
| 116 |
+
best_communities = [
|
| 117 |
+
com
|
| 118 |
+
for com, freq in com_counter.items()
|
| 119 |
+
if (max_freq - freq) < 0.0001
|
| 120 |
+
]
|
| 121 |
+
# If actual vertex com in best communities, it is preserved
|
| 122 |
+
try:
|
| 123 |
+
if communities[vertex] in best_communities:
|
| 124 |
+
new_com = communities[vertex]
|
| 125 |
+
except KeyError:
|
| 126 |
+
pass
|
| 127 |
+
# If vertex community changes...
|
| 128 |
+
if new_com == -1:
|
| 129 |
+
# Set flag of non-convergence
|
| 130 |
+
cont = True
|
| 131 |
+
# Randomly chose a new community from candidates
|
| 132 |
+
new_com = seed.choice(best_communities)
|
| 133 |
+
# Update previous community status
|
| 134 |
+
try:
|
| 135 |
+
com_to_numvertices[communities[vertex]] -= 1
|
| 136 |
+
density[communities[vertex]] = (
|
| 137 |
+
max_density / com_to_numvertices[communities[vertex]]
|
| 138 |
+
)
|
| 139 |
+
except KeyError:
|
| 140 |
+
pass
|
| 141 |
+
# Update new community status
|
| 142 |
+
communities[vertex] = new_com
|
| 143 |
+
com_to_numvertices[communities[vertex]] += 1
|
| 144 |
+
density[communities[vertex]] = (
|
| 145 |
+
max_density / com_to_numvertices[communities[vertex]]
|
| 146 |
+
)
|
| 147 |
+
# If maximum iterations reached --> output actual results
|
| 148 |
+
if iter_count > max_iter:
|
| 149 |
+
break
|
| 150 |
+
# Return results by grouping communities as list of vertices
|
| 151 |
+
return iter(groups(communities).values())
|
platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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
|