Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txt +37 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/__init__.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/conftest.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/convert.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/convert_matrix.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/exception.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/lazy_imports.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/relabel.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/__init__.py +134 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/asteroidal.py +164 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/boundary.py +168 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/bridges.py +205 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/broadcasting.py +164 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/chains.py +172 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/chordal.py +443 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/clique.py +818 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/cluster.py +732 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/communicability_alg.py +163 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/core.py +588 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/covering.py +142 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/cuts.py +416 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/cycles.py +1234 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/d_separation.py +677 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/dag.py +1392 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/distance_measures.py +1095 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/distance_regular.py +272 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/dominance.py +142 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/dominating.py +268 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/efficiency_measures.py +167 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/euler.py +470 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/graph_hashing.py +435 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/graphical.py +483 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/hierarchy.py +57 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/hybrid.py +196 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/isolate.py +107 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/link_prediction.py +687 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/lowest_common_ancestors.py +280 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/matching.py +1148 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/mis.py +78 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/moral.py +59 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/node_classification.py +219 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/non_randomness.py +155 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/perfect_graph.py +73 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/planar_drawing.py +464 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/planarity.py +1463 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/polynomials.py +306 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/reciprocity.py +98 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/regular.py +167 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/richclub.py +138 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/similarity.py +2107 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txt
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NetworkX is distributed with the 3-clause BSD license.
|
| 2 |
+
|
| 3 |
+
::
|
| 4 |
+
|
| 5 |
+
Copyright (c) 2004-2025, NetworkX Developers
|
| 6 |
+
Aric Hagberg <hagberg@lanl.gov>
|
| 7 |
+
Dan Schult <dschult@colgate.edu>
|
| 8 |
+
Pieter Swart <swart@lanl.gov>
|
| 9 |
+
All rights reserved.
|
| 10 |
+
|
| 11 |
+
Redistribution and use in source and binary forms, with or without
|
| 12 |
+
modification, are permitted provided that the following conditions are
|
| 13 |
+
met:
|
| 14 |
+
|
| 15 |
+
* Redistributions of source code must retain the above copyright
|
| 16 |
+
notice, this list of conditions and the following disclaimer.
|
| 17 |
+
|
| 18 |
+
* Redistributions in binary form must reproduce the above
|
| 19 |
+
copyright notice, this list of conditions and the following
|
| 20 |
+
disclaimer in the documentation and/or other materials provided
|
| 21 |
+
with the distribution.
|
| 22 |
+
|
| 23 |
+
* Neither the name of the NetworkX Developers nor the names of its
|
| 24 |
+
contributors may be used to endorse or promote products derived
|
| 25 |
+
from this software without specific prior written permission.
|
| 26 |
+
|
| 27 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 28 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 29 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 30 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 31 |
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 32 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
| 33 |
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
| 34 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
| 35 |
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 36 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 37 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (2.24 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/conftest.cpython-311.pyc
ADDED
|
Binary file (8.9 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/convert.cpython-311.pyc
ADDED
|
Binary file (20.6 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/convert_matrix.cpython-311.pyc
ADDED
|
Binary file (54.9 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/exception.cpython-311.pyc
ADDED
|
Binary file (6.33 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/lazy_imports.cpython-311.pyc
ADDED
|
Binary file (8 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/__pycache__/relabel.cpython-311.pyc
ADDED
|
Binary file (16.2 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/__init__.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from networkx.algorithms.assortativity import *
|
| 2 |
+
from networkx.algorithms.asteroidal import *
|
| 3 |
+
from networkx.algorithms.boundary import *
|
| 4 |
+
from networkx.algorithms.broadcasting import *
|
| 5 |
+
from networkx.algorithms.bridges import *
|
| 6 |
+
from networkx.algorithms.chains import *
|
| 7 |
+
from networkx.algorithms.centrality import *
|
| 8 |
+
from networkx.algorithms.chordal import *
|
| 9 |
+
from networkx.algorithms.cluster import *
|
| 10 |
+
from networkx.algorithms.clique import *
|
| 11 |
+
from networkx.algorithms.communicability_alg import *
|
| 12 |
+
from networkx.algorithms.components import *
|
| 13 |
+
from networkx.algorithms.coloring import *
|
| 14 |
+
from networkx.algorithms.core import *
|
| 15 |
+
from networkx.algorithms.covering import *
|
| 16 |
+
from networkx.algorithms.cycles import *
|
| 17 |
+
from networkx.algorithms.cuts import *
|
| 18 |
+
from networkx.algorithms.d_separation import *
|
| 19 |
+
from networkx.algorithms.dag import *
|
| 20 |
+
from networkx.algorithms.distance_measures import *
|
| 21 |
+
from networkx.algorithms.distance_regular import *
|
| 22 |
+
from networkx.algorithms.dominance import *
|
| 23 |
+
from networkx.algorithms.dominating import *
|
| 24 |
+
from networkx.algorithms.efficiency_measures import *
|
| 25 |
+
from networkx.algorithms.euler import *
|
| 26 |
+
from networkx.algorithms.graphical import *
|
| 27 |
+
from networkx.algorithms.hierarchy import *
|
| 28 |
+
from networkx.algorithms.hybrid import *
|
| 29 |
+
from networkx.algorithms.link_analysis import *
|
| 30 |
+
from networkx.algorithms.link_prediction import *
|
| 31 |
+
from networkx.algorithms.lowest_common_ancestors import *
|
| 32 |
+
from networkx.algorithms.isolate import *
|
| 33 |
+
from networkx.algorithms.matching import *
|
| 34 |
+
from networkx.algorithms.minors import *
|
| 35 |
+
from networkx.algorithms.mis import *
|
| 36 |
+
from networkx.algorithms.moral import *
|
| 37 |
+
from networkx.algorithms.non_randomness import *
|
| 38 |
+
from networkx.algorithms.operators import *
|
| 39 |
+
from networkx.algorithms.planarity import *
|
| 40 |
+
from networkx.algorithms.planar_drawing import *
|
| 41 |
+
from networkx.algorithms.polynomials import *
|
| 42 |
+
from networkx.algorithms.perfect_graph import *
|
| 43 |
+
from networkx.algorithms.reciprocity import *
|
| 44 |
+
from networkx.algorithms.regular import *
|
| 45 |
+
from networkx.algorithms.richclub import *
|
| 46 |
+
from networkx.algorithms.shortest_paths import *
|
| 47 |
+
from networkx.algorithms.similarity import *
|
| 48 |
+
from networkx.algorithms.graph_hashing import *
|
| 49 |
+
from networkx.algorithms.simple_paths import *
|
| 50 |
+
from networkx.algorithms.smallworld import *
|
| 51 |
+
from networkx.algorithms.smetric import *
|
| 52 |
+
from networkx.algorithms.structuralholes import *
|
| 53 |
+
from networkx.algorithms.sparsifiers import *
|
| 54 |
+
from networkx.algorithms.summarization import *
|
| 55 |
+
from networkx.algorithms.swap import *
|
| 56 |
+
from networkx.algorithms.time_dependent import *
|
| 57 |
+
from networkx.algorithms.traversal import *
|
| 58 |
+
from networkx.algorithms.triads import *
|
| 59 |
+
from networkx.algorithms.vitality import *
|
| 60 |
+
from networkx.algorithms.voronoi import *
|
| 61 |
+
from networkx.algorithms.walks import *
|
| 62 |
+
from networkx.algorithms.wiener import *
|
| 63 |
+
|
| 64 |
+
# Make certain subpackages available to the user as direct imports from
|
| 65 |
+
# the `networkx` namespace.
|
| 66 |
+
from networkx.algorithms import approximation
|
| 67 |
+
from networkx.algorithms import assortativity
|
| 68 |
+
from networkx.algorithms import bipartite
|
| 69 |
+
from networkx.algorithms import node_classification
|
| 70 |
+
from networkx.algorithms import centrality
|
| 71 |
+
from networkx.algorithms import chordal
|
| 72 |
+
from networkx.algorithms import cluster
|
| 73 |
+
from networkx.algorithms import clique
|
| 74 |
+
from networkx.algorithms import components
|
| 75 |
+
from networkx.algorithms import connectivity
|
| 76 |
+
from networkx.algorithms import community
|
| 77 |
+
from networkx.algorithms import coloring
|
| 78 |
+
from networkx.algorithms import flow
|
| 79 |
+
from networkx.algorithms import isomorphism
|
| 80 |
+
from networkx.algorithms import link_analysis
|
| 81 |
+
from networkx.algorithms import lowest_common_ancestors
|
| 82 |
+
from networkx.algorithms import operators
|
| 83 |
+
from networkx.algorithms import shortest_paths
|
| 84 |
+
from networkx.algorithms import tournament
|
| 85 |
+
from networkx.algorithms import traversal
|
| 86 |
+
from networkx.algorithms import tree
|
| 87 |
+
|
| 88 |
+
# Make certain functions from some of the previous subpackages available
|
| 89 |
+
# to the user as direct imports from the `networkx` namespace.
|
| 90 |
+
from networkx.algorithms.bipartite import complete_bipartite_graph
|
| 91 |
+
from networkx.algorithms.bipartite import is_bipartite
|
| 92 |
+
from networkx.algorithms.bipartite import projected_graph
|
| 93 |
+
from networkx.algorithms.connectivity import all_pairs_node_connectivity
|
| 94 |
+
from networkx.algorithms.connectivity import all_node_cuts
|
| 95 |
+
from networkx.algorithms.connectivity import average_node_connectivity
|
| 96 |
+
from networkx.algorithms.connectivity import edge_connectivity
|
| 97 |
+
from networkx.algorithms.connectivity import edge_disjoint_paths
|
| 98 |
+
from networkx.algorithms.connectivity import k_components
|
| 99 |
+
from networkx.algorithms.connectivity import k_edge_components
|
| 100 |
+
from networkx.algorithms.connectivity import k_edge_subgraphs
|
| 101 |
+
from networkx.algorithms.connectivity import k_edge_augmentation
|
| 102 |
+
from networkx.algorithms.connectivity import is_k_edge_connected
|
| 103 |
+
from networkx.algorithms.connectivity import minimum_edge_cut
|
| 104 |
+
from networkx.algorithms.connectivity import minimum_node_cut
|
| 105 |
+
from networkx.algorithms.connectivity import node_connectivity
|
| 106 |
+
from networkx.algorithms.connectivity import node_disjoint_paths
|
| 107 |
+
from networkx.algorithms.connectivity import stoer_wagner
|
| 108 |
+
from networkx.algorithms.flow import capacity_scaling
|
| 109 |
+
from networkx.algorithms.flow import cost_of_flow
|
| 110 |
+
from networkx.algorithms.flow import gomory_hu_tree
|
| 111 |
+
from networkx.algorithms.flow import max_flow_min_cost
|
| 112 |
+
from networkx.algorithms.flow import maximum_flow
|
| 113 |
+
from networkx.algorithms.flow import maximum_flow_value
|
| 114 |
+
from networkx.algorithms.flow import min_cost_flow
|
| 115 |
+
from networkx.algorithms.flow import min_cost_flow_cost
|
| 116 |
+
from networkx.algorithms.flow import minimum_cut
|
| 117 |
+
from networkx.algorithms.flow import minimum_cut_value
|
| 118 |
+
from networkx.algorithms.flow import network_simplex
|
| 119 |
+
from networkx.algorithms.isomorphism import could_be_isomorphic
|
| 120 |
+
from networkx.algorithms.isomorphism import fast_could_be_isomorphic
|
| 121 |
+
from networkx.algorithms.isomorphism import faster_could_be_isomorphic
|
| 122 |
+
from networkx.algorithms.isomorphism import is_isomorphic
|
| 123 |
+
from networkx.algorithms.isomorphism.vf2pp import *
|
| 124 |
+
from networkx.algorithms.tree.branchings import maximum_branching
|
| 125 |
+
from networkx.algorithms.tree.branchings import maximum_spanning_arborescence
|
| 126 |
+
from networkx.algorithms.tree.branchings import minimum_branching
|
| 127 |
+
from networkx.algorithms.tree.branchings import minimum_spanning_arborescence
|
| 128 |
+
from networkx.algorithms.tree.branchings import ArborescenceIterator
|
| 129 |
+
from networkx.algorithms.tree.coding import *
|
| 130 |
+
from networkx.algorithms.tree.decomposition import *
|
| 131 |
+
from networkx.algorithms.tree.mst import *
|
| 132 |
+
from networkx.algorithms.tree.operations import *
|
| 133 |
+
from networkx.algorithms.tree.recognition import *
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Algorithms for asteroidal triples and asteroidal numbers in graphs.
|
| 3 |
+
|
| 4 |
+
An asteroidal triple in a graph G is a set of three non-adjacent vertices
|
| 5 |
+
u, v and w such that there exist a path between any two of them that avoids
|
| 6 |
+
closed neighborhood of the third. More formally, v_j, v_k belongs to the same
|
| 7 |
+
connected component of G - N[v_i], where N[v_i] denotes the closed neighborhood
|
| 8 |
+
of v_i. A graph which does not contain any asteroidal triples is called
|
| 9 |
+
an AT-free graph. The class of AT-free graphs is a graph class for which
|
| 10 |
+
many NP-complete problems are solvable in polynomial time. Amongst them,
|
| 11 |
+
independent set and coloring.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import networkx as nx
|
| 15 |
+
from networkx.utils import not_implemented_for
|
| 16 |
+
|
| 17 |
+
__all__ = ["is_at_free", "find_asteroidal_triple"]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@not_implemented_for("directed")
|
| 21 |
+
@not_implemented_for("multigraph")
|
| 22 |
+
@nx._dispatchable
|
| 23 |
+
def find_asteroidal_triple(G):
|
| 24 |
+
r"""Find an asteroidal triple in the given graph.
|
| 25 |
+
|
| 26 |
+
An asteroidal triple is a triple of non-adjacent vertices such that
|
| 27 |
+
there exists a path between any two of them which avoids the closed
|
| 28 |
+
neighborhood of the third. It checks all independent triples of vertices
|
| 29 |
+
and whether they are an asteroidal triple or not. This is done with the
|
| 30 |
+
help of a data structure called a component structure.
|
| 31 |
+
A component structure encodes information about which vertices belongs to
|
| 32 |
+
the same connected component when the closed neighborhood of a given vertex
|
| 33 |
+
is removed from the graph. The algorithm used to check is the trivial
|
| 34 |
+
one, outlined in [1]_, which has a runtime of
|
| 35 |
+
:math:`O(|V||\overline{E} + |V||E|)`, where the second term is the
|
| 36 |
+
creation of the component structure.
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
G : NetworkX Graph
|
| 41 |
+
The graph to check whether is AT-free or not
|
| 42 |
+
|
| 43 |
+
Returns
|
| 44 |
+
-------
|
| 45 |
+
list or None
|
| 46 |
+
An asteroidal triple is returned as a list of nodes. If no asteroidal
|
| 47 |
+
triple exists, i.e. the graph is AT-free, then None is returned.
|
| 48 |
+
|
| 49 |
+
Notes
|
| 50 |
+
-----
|
| 51 |
+
The component structure and the algorithm is described in [1]_. The current
|
| 52 |
+
implementation implements the trivial algorithm for simple graphs.
|
| 53 |
+
|
| 54 |
+
References
|
| 55 |
+
----------
|
| 56 |
+
.. [1] Ekkehard Köhler,
|
| 57 |
+
"Recognizing Graphs without asteroidal triples",
|
| 58 |
+
Journal of Discrete Algorithms 2, pages 439-452, 2004.
|
| 59 |
+
https://www.sciencedirect.com/science/article/pii/S157086670400019X
|
| 60 |
+
"""
|
| 61 |
+
V = set(G.nodes)
|
| 62 |
+
|
| 63 |
+
if len(V) < 6:
|
| 64 |
+
# An asteroidal triple cannot exist in a graph with 5 or less vertices.
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
component_structure = create_component_structure(G)
|
| 68 |
+
|
| 69 |
+
for u, v in nx.non_edges(G):
|
| 70 |
+
u_neighborhood = set(G[u]).union([u])
|
| 71 |
+
v_neighborhood = set(G[v]).union([v])
|
| 72 |
+
union_of_neighborhoods = u_neighborhood.union(v_neighborhood)
|
| 73 |
+
for w in V - union_of_neighborhoods:
|
| 74 |
+
# Check for each pair of vertices whether they belong to the
|
| 75 |
+
# same connected component when the closed neighborhood of the
|
| 76 |
+
# third is removed.
|
| 77 |
+
if (
|
| 78 |
+
component_structure[u][v] == component_structure[u][w]
|
| 79 |
+
and component_structure[v][u] == component_structure[v][w]
|
| 80 |
+
and component_structure[w][u] == component_structure[w][v]
|
| 81 |
+
):
|
| 82 |
+
return [u, v, w]
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@not_implemented_for("directed")
|
| 87 |
+
@not_implemented_for("multigraph")
|
| 88 |
+
@nx._dispatchable
|
| 89 |
+
def is_at_free(G):
|
| 90 |
+
"""Check if a graph is AT-free.
|
| 91 |
+
|
| 92 |
+
The method uses the `find_asteroidal_triple` method to recognize
|
| 93 |
+
an AT-free graph. If no asteroidal triple is found the graph is
|
| 94 |
+
AT-free and True is returned. If at least one asteroidal triple is
|
| 95 |
+
found the graph is not AT-free and False is returned.
|
| 96 |
+
|
| 97 |
+
Parameters
|
| 98 |
+
----------
|
| 99 |
+
G : NetworkX Graph
|
| 100 |
+
The graph to check whether is AT-free or not.
|
| 101 |
+
|
| 102 |
+
Returns
|
| 103 |
+
-------
|
| 104 |
+
bool
|
| 105 |
+
True if G is AT-free and False otherwise.
|
| 106 |
+
|
| 107 |
+
Examples
|
| 108 |
+
--------
|
| 109 |
+
>>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
|
| 110 |
+
>>> nx.is_at_free(G)
|
| 111 |
+
True
|
| 112 |
+
|
| 113 |
+
>>> G = nx.cycle_graph(6)
|
| 114 |
+
>>> nx.is_at_free(G)
|
| 115 |
+
False
|
| 116 |
+
"""
|
| 117 |
+
return find_asteroidal_triple(G) is None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@not_implemented_for("directed")
|
| 121 |
+
@not_implemented_for("multigraph")
|
| 122 |
+
@nx._dispatchable
|
| 123 |
+
def create_component_structure(G):
|
| 124 |
+
r"""Create component structure for G.
|
| 125 |
+
|
| 126 |
+
A *component structure* is an `nxn` array, denoted `c`, where `n` is
|
| 127 |
+
the number of vertices, where each row and column corresponds to a vertex.
|
| 128 |
+
|
| 129 |
+
.. math::
|
| 130 |
+
c_{uv} = \begin{cases} 0, if v \in N[u] \\
|
| 131 |
+
k, if v \in component k of G \setminus N[u] \end{cases}
|
| 132 |
+
|
| 133 |
+
Where `k` is an arbitrary label for each component. The structure is used
|
| 134 |
+
to simplify the detection of asteroidal triples.
|
| 135 |
+
|
| 136 |
+
Parameters
|
| 137 |
+
----------
|
| 138 |
+
G : NetworkX Graph
|
| 139 |
+
Undirected, simple graph.
|
| 140 |
+
|
| 141 |
+
Returns
|
| 142 |
+
-------
|
| 143 |
+
component_structure : dictionary
|
| 144 |
+
A dictionary of dictionaries, keyed by pairs of vertices.
|
| 145 |
+
|
| 146 |
+
"""
|
| 147 |
+
V = set(G.nodes)
|
| 148 |
+
component_structure = {}
|
| 149 |
+
for v in V:
|
| 150 |
+
label = 0
|
| 151 |
+
closed_neighborhood = set(G[v]).union({v})
|
| 152 |
+
row_dict = {}
|
| 153 |
+
for u in closed_neighborhood:
|
| 154 |
+
row_dict[u] = 0
|
| 155 |
+
|
| 156 |
+
G_reduced = G.subgraph(set(G.nodes) - closed_neighborhood)
|
| 157 |
+
for cc in nx.connected_components(G_reduced):
|
| 158 |
+
label += 1
|
| 159 |
+
for u in cc:
|
| 160 |
+
row_dict[u] = label
|
| 161 |
+
|
| 162 |
+
component_structure[v] = row_dict
|
| 163 |
+
|
| 164 |
+
return component_structure
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/boundary.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Routines to find the boundary of a set of nodes.
|
| 2 |
+
|
| 3 |
+
An edge boundary is a set of edges, each of which has exactly one
|
| 4 |
+
endpoint in a given set of nodes (or, in the case of directed graphs,
|
| 5 |
+
the set of edges whose source node is in the set).
|
| 6 |
+
|
| 7 |
+
A node boundary of a set *S* of nodes is the set of (out-)neighbors of
|
| 8 |
+
nodes in *S* that are outside *S*.
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from itertools import chain
|
| 13 |
+
|
| 14 |
+
import networkx as nx
|
| 15 |
+
|
| 16 |
+
__all__ = ["edge_boundary", "node_boundary"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@nx._dispatchable(edge_attrs={"data": "default"}, preserve_edge_attrs="data")
|
| 20 |
+
def edge_boundary(G, nbunch1, nbunch2=None, data=False, keys=False, default=None):
|
| 21 |
+
"""Returns the edge boundary of `nbunch1`.
|
| 22 |
+
|
| 23 |
+
The *edge boundary* of a set *S* with respect to a set *T* is the
|
| 24 |
+
set of edges (*u*, *v*) such that *u* is in *S* and *v* is in *T*.
|
| 25 |
+
If *T* is not specified, it is assumed to be the set of all nodes
|
| 26 |
+
not in *S*.
|
| 27 |
+
|
| 28 |
+
Parameters
|
| 29 |
+
----------
|
| 30 |
+
G : NetworkX graph
|
| 31 |
+
|
| 32 |
+
nbunch1 : iterable
|
| 33 |
+
Iterable of nodes in the graph representing the set of nodes
|
| 34 |
+
whose edge boundary will be returned. (This is the set *S* from
|
| 35 |
+
the definition above.)
|
| 36 |
+
|
| 37 |
+
nbunch2 : iterable
|
| 38 |
+
Iterable of nodes representing the target (or "exterior") set of
|
| 39 |
+
nodes. (This is the set *T* from the definition above.) If not
|
| 40 |
+
specified, this is assumed to be the set of all nodes in `G`
|
| 41 |
+
not in `nbunch1`.
|
| 42 |
+
|
| 43 |
+
keys : bool
|
| 44 |
+
This parameter has the same meaning as in
|
| 45 |
+
:meth:`MultiGraph.edges`.
|
| 46 |
+
|
| 47 |
+
data : bool or object
|
| 48 |
+
This parameter has the same meaning as in
|
| 49 |
+
:meth:`MultiGraph.edges`.
|
| 50 |
+
|
| 51 |
+
default : object
|
| 52 |
+
This parameter has the same meaning as in
|
| 53 |
+
:meth:`MultiGraph.edges`.
|
| 54 |
+
|
| 55 |
+
Returns
|
| 56 |
+
-------
|
| 57 |
+
iterator
|
| 58 |
+
An iterator over the edges in the boundary of `nbunch1` with
|
| 59 |
+
respect to `nbunch2`. If `keys`, `data`, or `default`
|
| 60 |
+
are specified and `G` is a multigraph, then edges are returned
|
| 61 |
+
with keys and/or data, as in :meth:`MultiGraph.edges`.
|
| 62 |
+
|
| 63 |
+
Examples
|
| 64 |
+
--------
|
| 65 |
+
>>> G = nx.wheel_graph(6)
|
| 66 |
+
|
| 67 |
+
When nbunch2=None:
|
| 68 |
+
|
| 69 |
+
>>> list(nx.edge_boundary(G, (1, 3)))
|
| 70 |
+
[(1, 0), (1, 2), (1, 5), (3, 0), (3, 2), (3, 4)]
|
| 71 |
+
|
| 72 |
+
When nbunch2 is given:
|
| 73 |
+
|
| 74 |
+
>>> list(nx.edge_boundary(G, (1, 3), (2, 0)))
|
| 75 |
+
[(1, 0), (1, 2), (3, 0), (3, 2)]
|
| 76 |
+
|
| 77 |
+
Notes
|
| 78 |
+
-----
|
| 79 |
+
Any element of `nbunch` that is not in the graph `G` will be
|
| 80 |
+
ignored.
|
| 81 |
+
|
| 82 |
+
`nbunch1` and `nbunch2` are usually meant to be disjoint, but in
|
| 83 |
+
the interest of speed and generality, that is not required here.
|
| 84 |
+
|
| 85 |
+
"""
|
| 86 |
+
nset1 = {n for n in nbunch1 if n in G}
|
| 87 |
+
# Here we create an iterator over edges incident to nodes in the set
|
| 88 |
+
# `nset1`. The `Graph.edges()` method does not provide a guarantee
|
| 89 |
+
# on the orientation of the edges, so our algorithm below must
|
| 90 |
+
# handle the case in which exactly one orientation, either (u, v) or
|
| 91 |
+
# (v, u), appears in this iterable.
|
| 92 |
+
if G.is_multigraph():
|
| 93 |
+
edges = G.edges(nset1, data=data, keys=keys, default=default)
|
| 94 |
+
else:
|
| 95 |
+
edges = G.edges(nset1, data=data, default=default)
|
| 96 |
+
# If `nbunch2` is not provided, then it is assumed to be the set
|
| 97 |
+
# complement of `nbunch1`. For the sake of efficiency, this is
|
| 98 |
+
# implemented by using the `not in` operator, instead of by creating
|
| 99 |
+
# an additional set and using the `in` operator.
|
| 100 |
+
if nbunch2 is None:
|
| 101 |
+
return (e for e in edges if (e[0] in nset1) ^ (e[1] in nset1))
|
| 102 |
+
nset2 = set(nbunch2)
|
| 103 |
+
return (
|
| 104 |
+
e
|
| 105 |
+
for e in edges
|
| 106 |
+
if (e[0] in nset1 and e[1] in nset2) or (e[1] in nset1 and e[0] in nset2)
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@nx._dispatchable
|
| 111 |
+
def node_boundary(G, nbunch1, nbunch2=None):
|
| 112 |
+
"""Returns the node boundary of `nbunch1`.
|
| 113 |
+
|
| 114 |
+
The *node boundary* of a set *S* with respect to a set *T* is the
|
| 115 |
+
set of nodes *v* in *T* such that for some *u* in *S*, there is an
|
| 116 |
+
edge joining *u* to *v*. If *T* is not specified, it is assumed to
|
| 117 |
+
be the set of all nodes not in *S*.
|
| 118 |
+
|
| 119 |
+
Parameters
|
| 120 |
+
----------
|
| 121 |
+
G : NetworkX graph
|
| 122 |
+
|
| 123 |
+
nbunch1 : iterable
|
| 124 |
+
Iterable of nodes in the graph representing the set of nodes
|
| 125 |
+
whose node boundary will be returned. (This is the set *S* from
|
| 126 |
+
the definition above.)
|
| 127 |
+
|
| 128 |
+
nbunch2 : iterable
|
| 129 |
+
Iterable of nodes representing the target (or "exterior") set of
|
| 130 |
+
nodes. (This is the set *T* from the definition above.) If not
|
| 131 |
+
specified, this is assumed to be the set of all nodes in `G`
|
| 132 |
+
not in `nbunch1`.
|
| 133 |
+
|
| 134 |
+
Returns
|
| 135 |
+
-------
|
| 136 |
+
set
|
| 137 |
+
The node boundary of `nbunch1` with respect to `nbunch2`.
|
| 138 |
+
|
| 139 |
+
Examples
|
| 140 |
+
--------
|
| 141 |
+
>>> G = nx.wheel_graph(6)
|
| 142 |
+
|
| 143 |
+
When nbunch2=None:
|
| 144 |
+
|
| 145 |
+
>>> list(nx.node_boundary(G, (3, 4)))
|
| 146 |
+
[0, 2, 5]
|
| 147 |
+
|
| 148 |
+
When nbunch2 is given:
|
| 149 |
+
|
| 150 |
+
>>> list(nx.node_boundary(G, (3, 4), (0, 1, 5)))
|
| 151 |
+
[0, 5]
|
| 152 |
+
|
| 153 |
+
Notes
|
| 154 |
+
-----
|
| 155 |
+
Any element of `nbunch` that is not in the graph `G` will be
|
| 156 |
+
ignored.
|
| 157 |
+
|
| 158 |
+
`nbunch1` and `nbunch2` are usually meant to be disjoint, but in
|
| 159 |
+
the interest of speed and generality, that is not required here.
|
| 160 |
+
|
| 161 |
+
"""
|
| 162 |
+
nset1 = {n for n in nbunch1 if n in G}
|
| 163 |
+
bdy = set(chain.from_iterable(G[v] for v in nset1)) - nset1
|
| 164 |
+
# If `nbunch2` is not specified, it is assumed to be the set
|
| 165 |
+
# complement of `nbunch1`.
|
| 166 |
+
if nbunch2 is not None:
|
| 167 |
+
bdy &= set(nbunch2)
|
| 168 |
+
return bdy
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/bridges.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bridge-finding algorithms."""
|
| 2 |
+
|
| 3 |
+
from itertools import chain
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = ["bridges", "has_bridges", "local_bridges"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@not_implemented_for("directed")
|
| 12 |
+
@nx._dispatchable
|
| 13 |
+
def bridges(G, root=None):
|
| 14 |
+
"""Generate all bridges in a graph.
|
| 15 |
+
|
| 16 |
+
A *bridge* in a graph is an edge whose removal causes the number of
|
| 17 |
+
connected components of the graph to increase. Equivalently, a bridge is an
|
| 18 |
+
edge that does not belong to any cycle. Bridges are also known as cut-edges,
|
| 19 |
+
isthmuses, or cut arcs.
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
G : undirected graph
|
| 24 |
+
|
| 25 |
+
root : node (optional)
|
| 26 |
+
A node in the graph `G`. If specified, only the bridges in the
|
| 27 |
+
connected component containing this node will be returned.
|
| 28 |
+
|
| 29 |
+
Yields
|
| 30 |
+
------
|
| 31 |
+
e : edge
|
| 32 |
+
An edge in the graph whose removal disconnects the graph (or
|
| 33 |
+
causes the number of connected components to increase).
|
| 34 |
+
|
| 35 |
+
Raises
|
| 36 |
+
------
|
| 37 |
+
NodeNotFound
|
| 38 |
+
If `root` is not in the graph `G`.
|
| 39 |
+
|
| 40 |
+
NetworkXNotImplemented
|
| 41 |
+
If `G` is a directed graph.
|
| 42 |
+
|
| 43 |
+
Examples
|
| 44 |
+
--------
|
| 45 |
+
The barbell graph with parameter zero has a single bridge:
|
| 46 |
+
|
| 47 |
+
>>> G = nx.barbell_graph(10, 0)
|
| 48 |
+
>>> list(nx.bridges(G))
|
| 49 |
+
[(9, 10)]
|
| 50 |
+
|
| 51 |
+
Notes
|
| 52 |
+
-----
|
| 53 |
+
This is an implementation of the algorithm described in [1]_. An edge is a
|
| 54 |
+
bridge if and only if it is not contained in any chain. Chains are found
|
| 55 |
+
using the :func:`networkx.chain_decomposition` function.
|
| 56 |
+
|
| 57 |
+
The algorithm described in [1]_ requires a simple graph. If the provided
|
| 58 |
+
graph is a multigraph, we convert it to a simple graph and verify that any
|
| 59 |
+
bridges discovered by the chain decomposition algorithm are not multi-edges.
|
| 60 |
+
|
| 61 |
+
Ignoring polylogarithmic factors, the worst-case time complexity is the
|
| 62 |
+
same as the :func:`networkx.chain_decomposition` function,
|
| 63 |
+
$O(m + n)$, where $n$ is the number of nodes in the graph and $m$ is
|
| 64 |
+
the number of edges.
|
| 65 |
+
|
| 66 |
+
References
|
| 67 |
+
----------
|
| 68 |
+
.. [1] https://en.wikipedia.org/wiki/Bridge_%28graph_theory%29#Bridge-Finding_with_Chain_Decompositions
|
| 69 |
+
"""
|
| 70 |
+
multigraph = G.is_multigraph()
|
| 71 |
+
H = nx.Graph(G) if multigraph else G
|
| 72 |
+
chains = nx.chain_decomposition(H, root=root)
|
| 73 |
+
chain_edges = set(chain.from_iterable(chains))
|
| 74 |
+
if root is not None:
|
| 75 |
+
H = H.subgraph(nx.node_connected_component(H, root)).copy()
|
| 76 |
+
for u, v in H.edges():
|
| 77 |
+
if (u, v) not in chain_edges and (v, u) not in chain_edges:
|
| 78 |
+
if multigraph and len(G[u][v]) > 1:
|
| 79 |
+
continue
|
| 80 |
+
yield u, v
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@not_implemented_for("directed")
|
| 84 |
+
@nx._dispatchable
|
| 85 |
+
def has_bridges(G, root=None):
|
| 86 |
+
"""Decide whether a graph has any bridges.
|
| 87 |
+
|
| 88 |
+
A *bridge* in a graph is an edge whose removal causes the number of
|
| 89 |
+
connected components of the graph to increase.
|
| 90 |
+
|
| 91 |
+
Parameters
|
| 92 |
+
----------
|
| 93 |
+
G : undirected graph
|
| 94 |
+
|
| 95 |
+
root : node (optional)
|
| 96 |
+
A node in the graph `G`. If specified, only the bridges in the
|
| 97 |
+
connected component containing this node will be considered.
|
| 98 |
+
|
| 99 |
+
Returns
|
| 100 |
+
-------
|
| 101 |
+
bool
|
| 102 |
+
Whether the graph (or the connected component containing `root`)
|
| 103 |
+
has any bridges.
|
| 104 |
+
|
| 105 |
+
Raises
|
| 106 |
+
------
|
| 107 |
+
NodeNotFound
|
| 108 |
+
If `root` is not in the graph `G`.
|
| 109 |
+
|
| 110 |
+
NetworkXNotImplemented
|
| 111 |
+
If `G` is a directed graph.
|
| 112 |
+
|
| 113 |
+
Examples
|
| 114 |
+
--------
|
| 115 |
+
The barbell graph with parameter zero has a single bridge::
|
| 116 |
+
|
| 117 |
+
>>> G = nx.barbell_graph(10, 0)
|
| 118 |
+
>>> nx.has_bridges(G)
|
| 119 |
+
True
|
| 120 |
+
|
| 121 |
+
On the other hand, the cycle graph has no bridges::
|
| 122 |
+
|
| 123 |
+
>>> G = nx.cycle_graph(5)
|
| 124 |
+
>>> nx.has_bridges(G)
|
| 125 |
+
False
|
| 126 |
+
|
| 127 |
+
Notes
|
| 128 |
+
-----
|
| 129 |
+
This implementation uses the :func:`networkx.bridges` function, so
|
| 130 |
+
it shares its worst-case time complexity, $O(m + n)$, ignoring
|
| 131 |
+
polylogarithmic factors, where $n$ is the number of nodes in the
|
| 132 |
+
graph and $m$ is the number of edges.
|
| 133 |
+
|
| 134 |
+
"""
|
| 135 |
+
try:
|
| 136 |
+
next(bridges(G, root=root))
|
| 137 |
+
except StopIteration:
|
| 138 |
+
return False
|
| 139 |
+
else:
|
| 140 |
+
return True
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@not_implemented_for("multigraph")
|
| 144 |
+
@not_implemented_for("directed")
|
| 145 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 146 |
+
def local_bridges(G, with_span=True, weight=None):
|
| 147 |
+
"""Iterate over local bridges of `G` optionally computing the span
|
| 148 |
+
|
| 149 |
+
A *local bridge* is an edge whose endpoints have no common neighbors.
|
| 150 |
+
That is, the edge is not part of a triangle in the graph.
|
| 151 |
+
|
| 152 |
+
The *span* of a *local bridge* is the shortest path length between
|
| 153 |
+
the endpoints if the local bridge is removed.
|
| 154 |
+
|
| 155 |
+
Parameters
|
| 156 |
+
----------
|
| 157 |
+
G : undirected graph
|
| 158 |
+
|
| 159 |
+
with_span : bool
|
| 160 |
+
If True, yield a 3-tuple `(u, v, span)`
|
| 161 |
+
|
| 162 |
+
weight : function, string or None (default: None)
|
| 163 |
+
If function, used to compute edge weights for the span.
|
| 164 |
+
If string, the edge data attribute used in calculating span.
|
| 165 |
+
If None, all edges have weight 1.
|
| 166 |
+
|
| 167 |
+
Yields
|
| 168 |
+
------
|
| 169 |
+
e : edge
|
| 170 |
+
The local bridges as an edge 2-tuple of nodes `(u, v)` or
|
| 171 |
+
as a 3-tuple `(u, v, span)` when `with_span is True`.
|
| 172 |
+
|
| 173 |
+
Raises
|
| 174 |
+
------
|
| 175 |
+
NetworkXNotImplemented
|
| 176 |
+
If `G` is a directed graph or multigraph.
|
| 177 |
+
|
| 178 |
+
Examples
|
| 179 |
+
--------
|
| 180 |
+
A cycle graph has every edge a local bridge with span N-1.
|
| 181 |
+
|
| 182 |
+
>>> G = nx.cycle_graph(9)
|
| 183 |
+
>>> (0, 8, 8) in set(nx.local_bridges(G))
|
| 184 |
+
True
|
| 185 |
+
"""
|
| 186 |
+
if with_span is not True:
|
| 187 |
+
for u, v in G.edges:
|
| 188 |
+
if not (set(G[u]) & set(G[v])):
|
| 189 |
+
yield u, v
|
| 190 |
+
else:
|
| 191 |
+
wt = nx.weighted._weight_function(G, weight)
|
| 192 |
+
for u, v in G.edges:
|
| 193 |
+
if not (set(G[u]) & set(G[v])):
|
| 194 |
+
enodes = {u, v}
|
| 195 |
+
|
| 196 |
+
def hide_edge(n, nbr, d):
|
| 197 |
+
if n not in enodes or nbr not in enodes:
|
| 198 |
+
return wt(n, nbr, d)
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
try:
|
| 202 |
+
span = nx.shortest_path_length(G, u, v, weight=hide_edge)
|
| 203 |
+
yield u, v, span
|
| 204 |
+
except nx.NetworkXNoPath:
|
| 205 |
+
yield u, v, float("inf")
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/broadcasting.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Routines to calculate the broadcast time of certain graphs.
|
| 2 |
+
|
| 3 |
+
Broadcasting is an information dissemination problem in which a node in a graph,
|
| 4 |
+
called the originator, must distribute a message to all other nodes by placing
|
| 5 |
+
a series of calls along the edges of the graph. Once informed, other nodes aid
|
| 6 |
+
the originator in distributing the message.
|
| 7 |
+
|
| 8 |
+
The broadcasting must be completed as quickly as possible subject to the
|
| 9 |
+
following constraints:
|
| 10 |
+
- Each call requires one unit of time.
|
| 11 |
+
- A node can only participate in one call per unit of time.
|
| 12 |
+
- Each call only involves two adjacent nodes: a sender and a receiver.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import networkx as nx
|
| 16 |
+
from networkx.utils import not_implemented_for
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"tree_broadcast_center",
|
| 20 |
+
"tree_broadcast_time",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _get_max_broadcast_value(G, U, v, values):
|
| 25 |
+
adj = sorted(set(G.neighbors(v)) & U, key=values.get, reverse=True)
|
| 26 |
+
return max(values[u] + i for i, u in enumerate(adj, start=1))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _get_broadcast_centers(G, v, values, target):
|
| 30 |
+
adj = sorted(G.neighbors(v), key=values.get, reverse=True)
|
| 31 |
+
j = next(i for i, u in enumerate(adj, start=1) if values[u] + i == target)
|
| 32 |
+
return set([v] + adj[:j])
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@not_implemented_for("directed")
|
| 36 |
+
@not_implemented_for("multigraph")
|
| 37 |
+
@nx._dispatchable
|
| 38 |
+
def tree_broadcast_center(G):
|
| 39 |
+
"""Return the broadcast center of a tree.
|
| 40 |
+
|
| 41 |
+
The broadcast center of a graph `G` denotes the set of nodes having
|
| 42 |
+
minimum broadcast time [1]_. This function implements a linear algorithm
|
| 43 |
+
for determining the broadcast center of a tree with ``n`` nodes. As a
|
| 44 |
+
by-product, it also determines the broadcast time from the broadcast center.
|
| 45 |
+
|
| 46 |
+
Parameters
|
| 47 |
+
----------
|
| 48 |
+
G : Graph
|
| 49 |
+
The graph should be an undirected tree.
|
| 50 |
+
|
| 51 |
+
Returns
|
| 52 |
+
-------
|
| 53 |
+
b_T, b_C : (int, set) tuple
|
| 54 |
+
Minimum broadcast time of the broadcast center in `G`, set of nodes
|
| 55 |
+
in the broadcast center.
|
| 56 |
+
|
| 57 |
+
Raises
|
| 58 |
+
------
|
| 59 |
+
NetworkXNotImplemented
|
| 60 |
+
If `G` is directed or is a multigraph.
|
| 61 |
+
|
| 62 |
+
NotATree
|
| 63 |
+
If `G` is not a tree.
|
| 64 |
+
|
| 65 |
+
References
|
| 66 |
+
----------
|
| 67 |
+
.. [1] Slater, P.J., Cockayne, E.J., Hedetniemi, S.T,
|
| 68 |
+
Information dissemination in trees. SIAM J.Comput. 10(4), 692–701 (1981)
|
| 69 |
+
"""
|
| 70 |
+
# Assert that the graph G is a tree
|
| 71 |
+
if not nx.is_tree(G):
|
| 72 |
+
raise nx.NotATree("G is not a tree")
|
| 73 |
+
# step 0
|
| 74 |
+
if (n := len(G)) < 3:
|
| 75 |
+
return n - 1, set(G)
|
| 76 |
+
|
| 77 |
+
# step 1
|
| 78 |
+
U = {node for node, deg in G.degree if deg == 1}
|
| 79 |
+
values = {n: 0 for n in U}
|
| 80 |
+
T = G.copy()
|
| 81 |
+
T.remove_nodes_from(U)
|
| 82 |
+
|
| 83 |
+
# step 2
|
| 84 |
+
W = {node for node, deg in T.degree if deg == 1}
|
| 85 |
+
values.update((w, G.degree[w] - 1) for w in W)
|
| 86 |
+
|
| 87 |
+
# step 3
|
| 88 |
+
while len(T) >= 2:
|
| 89 |
+
# step 4
|
| 90 |
+
w = min(W, key=values.get)
|
| 91 |
+
v = next(T.neighbors(w))
|
| 92 |
+
|
| 93 |
+
# step 5
|
| 94 |
+
U.add(w)
|
| 95 |
+
W.remove(w)
|
| 96 |
+
T.remove_node(w)
|
| 97 |
+
|
| 98 |
+
# step 6
|
| 99 |
+
if T.degree(v) == 1:
|
| 100 |
+
# update t(v)
|
| 101 |
+
values.update({v: _get_max_broadcast_value(G, U, v, values)})
|
| 102 |
+
W.add(v)
|
| 103 |
+
|
| 104 |
+
# step 7
|
| 105 |
+
v = nx.utils.arbitrary_element(T)
|
| 106 |
+
b_T = _get_max_broadcast_value(G, U, v, values)
|
| 107 |
+
return b_T, _get_broadcast_centers(G, v, values, b_T)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@not_implemented_for("directed")
|
| 111 |
+
@not_implemented_for("multigraph")
|
| 112 |
+
@nx._dispatchable
|
| 113 |
+
def tree_broadcast_time(G, node=None):
|
| 114 |
+
"""Return the minimum broadcast time of a (node in a) tree.
|
| 115 |
+
|
| 116 |
+
The minimum broadcast time of a node is defined as the minimum amount
|
| 117 |
+
of time required to complete broadcasting starting from that node.
|
| 118 |
+
The broadcast time of a graph is the maximum over
|
| 119 |
+
all nodes of the minimum broadcast time from that node [1]_.
|
| 120 |
+
This function returns the minimum broadcast time of `node`.
|
| 121 |
+
If `node` is `None`, the broadcast time for the graph is returned.
|
| 122 |
+
|
| 123 |
+
Parameters
|
| 124 |
+
----------
|
| 125 |
+
G : Graph
|
| 126 |
+
The graph should be an undirected tree.
|
| 127 |
+
|
| 128 |
+
node : node, optional (default=None)
|
| 129 |
+
Starting node for the broadcasting. If `None`, the algorithm
|
| 130 |
+
returns the broadcast time of the graph instead.
|
| 131 |
+
|
| 132 |
+
Returns
|
| 133 |
+
-------
|
| 134 |
+
int
|
| 135 |
+
Minimum broadcast time of `node` in `G`, or broadcast time of `G`
|
| 136 |
+
if no node is provided.
|
| 137 |
+
|
| 138 |
+
Raises
|
| 139 |
+
------
|
| 140 |
+
NetworkXNotImplemented
|
| 141 |
+
If `G` is directed or is a multigraph.
|
| 142 |
+
|
| 143 |
+
NodeNotFound
|
| 144 |
+
If `node` is not a node in `G`.
|
| 145 |
+
|
| 146 |
+
NotATree
|
| 147 |
+
If `G` is not a tree.
|
| 148 |
+
|
| 149 |
+
References
|
| 150 |
+
----------
|
| 151 |
+
.. [1] Harutyunyan, H. A. and Li, Z.
|
| 152 |
+
"A Simple Construction of Broadcast Graphs."
|
| 153 |
+
In Computing and Combinatorics. COCOON 2019
|
| 154 |
+
(Ed. D. Z. Du and C. Tian.) Springer, pp. 240-253, 2019.
|
| 155 |
+
"""
|
| 156 |
+
if node is not None and node not in G:
|
| 157 |
+
err = f"node {node} not in G"
|
| 158 |
+
raise nx.NodeNotFound(err)
|
| 159 |
+
b_T, b_C = tree_broadcast_center(G)
|
| 160 |
+
if node is None:
|
| 161 |
+
return b_T + sum(1 for _ in nx.bfs_layers(G, b_C)) - 1
|
| 162 |
+
return b_T + next(
|
| 163 |
+
d for d, layer in enumerate(n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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for finding chains in a graph."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.utils import not_implemented_for
|
| 5 |
+
|
| 6 |
+
__all__ = ["chain_decomposition"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@not_implemented_for("directed")
|
| 10 |
+
@not_implemented_for("multigraph")
|
| 11 |
+
@nx._dispatchable
|
| 12 |
+
def chain_decomposition(G, root=None):
|
| 13 |
+
"""Returns the chain decomposition of a graph.
|
| 14 |
+
|
| 15 |
+
The *chain decomposition* of a graph with respect a depth-first
|
| 16 |
+
search tree is a set of cycles or paths derived from the set of
|
| 17 |
+
fundamental cycles of the tree in the following manner. Consider
|
| 18 |
+
each fundamental cycle with respect to the given tree, represented
|
| 19 |
+
as a list of edges beginning with the nontree edge oriented away
|
| 20 |
+
from the root of the tree. For each fundamental cycle, if it
|
| 21 |
+
overlaps with any previous fundamental cycle, just take the initial
|
| 22 |
+
non-overlapping segment, which is a path instead of a cycle. Each
|
| 23 |
+
cycle or path is called a *chain*. For more information, see [1]_.
|
| 24 |
+
|
| 25 |
+
Parameters
|
| 26 |
+
----------
|
| 27 |
+
G : undirected graph
|
| 28 |
+
|
| 29 |
+
root : node (optional)
|
| 30 |
+
A node in the graph `G`. If specified, only the chain
|
| 31 |
+
decomposition for the connected component containing this node
|
| 32 |
+
will be returned. This node indicates the root of the depth-first
|
| 33 |
+
search tree.
|
| 34 |
+
|
| 35 |
+
Yields
|
| 36 |
+
------
|
| 37 |
+
chain : list
|
| 38 |
+
A list of edges representing a chain. There is no guarantee on
|
| 39 |
+
the orientation of the edges in each chain (for example, if a
|
| 40 |
+
chain includes the edge joining nodes 1 and 2, the chain may
|
| 41 |
+
include either (1, 2) or (2, 1)).
|
| 42 |
+
|
| 43 |
+
Raises
|
| 44 |
+
------
|
| 45 |
+
NodeNotFound
|
| 46 |
+
If `root` is not in the graph `G`.
|
| 47 |
+
|
| 48 |
+
Examples
|
| 49 |
+
--------
|
| 50 |
+
>>> G = nx.Graph([(0, 1), (1, 4), (3, 4), (3, 5), (4, 5)])
|
| 51 |
+
>>> list(nx.chain_decomposition(G))
|
| 52 |
+
[[(4, 5), (5, 3), (3, 4)]]
|
| 53 |
+
|
| 54 |
+
Notes
|
| 55 |
+
-----
|
| 56 |
+
The worst-case running time of this implementation is linear in the
|
| 57 |
+
number of nodes and number of edges [1]_.
|
| 58 |
+
|
| 59 |
+
References
|
| 60 |
+
----------
|
| 61 |
+
.. [1] Jens M. Schmidt (2013). "A simple test on 2-vertex-
|
| 62 |
+
and 2-edge-connectivity." *Information Processing Letters*,
|
| 63 |
+
113, 241–244. Elsevier. <https://doi.org/10.1016/j.ipl.2013.01.016>
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def _dfs_cycle_forest(G, root=None):
|
| 68 |
+
"""Builds a directed graph composed of cycles from the given graph.
|
| 69 |
+
|
| 70 |
+
`G` is an undirected simple graph. `root` is a node in the graph
|
| 71 |
+
from which the depth-first search is started.
|
| 72 |
+
|
| 73 |
+
This function returns both the depth-first search cycle graph
|
| 74 |
+
(as a :class:`~networkx.DiGraph`) and the list of nodes in
|
| 75 |
+
depth-first preorder. The depth-first search cycle graph is a
|
| 76 |
+
directed graph whose edges are the edges of `G` oriented toward
|
| 77 |
+
the root if the edge is a tree edge and away from the root if
|
| 78 |
+
the edge is a non-tree edge. If `root` is not specified, this
|
| 79 |
+
performs a depth-first search on each connected component of `G`
|
| 80 |
+
and returns a directed forest instead.
|
| 81 |
+
|
| 82 |
+
If `root` is not in the graph, this raises :exc:`KeyError`.
|
| 83 |
+
|
| 84 |
+
"""
|
| 85 |
+
# Create a directed graph from the depth-first search tree with
|
| 86 |
+
# root node `root` in which tree edges are directed toward the
|
| 87 |
+
# root and nontree edges are directed away from the root. For
|
| 88 |
+
# each node with an incident nontree edge, this creates a
|
| 89 |
+
# directed cycle starting with the nontree edge and returning to
|
| 90 |
+
# that node.
|
| 91 |
+
#
|
| 92 |
+
# The `parent` node attribute stores the parent of each node in
|
| 93 |
+
# the DFS tree. The `nontree` edge attribute indicates whether
|
| 94 |
+
# the edge is a tree edge or a nontree edge.
|
| 95 |
+
#
|
| 96 |
+
# We also store the order of the nodes found in the depth-first
|
| 97 |
+
# search in the `nodes` list.
|
| 98 |
+
H = nx.DiGraph()
|
| 99 |
+
nodes = []
|
| 100 |
+
for u, v, d in nx.dfs_labeled_edges(G, source=root):
|
| 101 |
+
if d == "forward":
|
| 102 |
+
# `dfs_labeled_edges()` yields (root, root, 'forward')
|
| 103 |
+
# if it is beginning the search on a new connected
|
| 104 |
+
# component.
|
| 105 |
+
if u == v:
|
| 106 |
+
H.add_node(v, parent=None)
|
| 107 |
+
nodes.append(v)
|
| 108 |
+
else:
|
| 109 |
+
H.add_node(v, parent=u)
|
| 110 |
+
H.add_edge(v, u, nontree=False)
|
| 111 |
+
nodes.append(v)
|
| 112 |
+
# `dfs_labeled_edges` considers nontree edges in both
|
| 113 |
+
# orientations, so we need to not add the edge if it its
|
| 114 |
+
# other orientation has been added.
|
| 115 |
+
elif d == "nontree" and v not in H[u]:
|
| 116 |
+
H.add_edge(v, u, nontree=True)
|
| 117 |
+
else:
|
| 118 |
+
# Do nothing on 'reverse' edges; we only care about
|
| 119 |
+
# forward and nontree edges.
|
| 120 |
+
pass
|
| 121 |
+
return H, nodes
|
| 122 |
+
|
| 123 |
+
def _build_chain(G, u, v, visited):
|
| 124 |
+
"""Generate the chain starting from the given nontree edge.
|
| 125 |
+
|
| 126 |
+
`G` is a DFS cycle graph as constructed by
|
| 127 |
+
:func:`_dfs_cycle_graph`. The edge (`u`, `v`) is a nontree edge
|
| 128 |
+
that begins a chain. `visited` is a set representing the nodes
|
| 129 |
+
in `G` that have already been visited.
|
| 130 |
+
|
| 131 |
+
This function yields the edges in an initial segment of the
|
| 132 |
+
fundamental cycle of `G` starting with the nontree edge (`u`,
|
| 133 |
+
`v`) that includes all the edges up until the first node that
|
| 134 |
+
appears in `visited`. The tree edges are given by the 'parent'
|
| 135 |
+
node attribute. The `visited` set is updated to add each node in
|
| 136 |
+
an edge yielded by this function.
|
| 137 |
+
|
| 138 |
+
"""
|
| 139 |
+
while v not in visited:
|
| 140 |
+
yield u, v
|
| 141 |
+
visited.add(v)
|
| 142 |
+
u, v = v, G.nodes[v]["parent"]
|
| 143 |
+
yield u, v
|
| 144 |
+
|
| 145 |
+
# Check if the root is in the graph G. If not, raise NodeNotFound
|
| 146 |
+
if root is not None and root not in G:
|
| 147 |
+
raise nx.NodeNotFound(f"Root node {root} is not in graph")
|
| 148 |
+
|
| 149 |
+
# Create a directed version of H that has the DFS edges directed
|
| 150 |
+
# toward the root and the nontree edges directed away from the root
|
| 151 |
+
# (in each connected component).
|
| 152 |
+
H, nodes = _dfs_cycle_forest(G, root)
|
| 153 |
+
|
| 154 |
+
# Visit the nodes again in DFS order. For each node, and for each
|
| 155 |
+
# nontree edge leaving that node, compute the fundamental cycle for
|
| 156 |
+
# that nontree edge starting with that edge. If the fundamental
|
| 157 |
+
# cycle overlaps with any visited nodes, just take the prefix of the
|
| 158 |
+
# cycle up to the point of visited nodes.
|
| 159 |
+
#
|
| 160 |
+
# We repeat this process for each connected component (implicitly,
|
| 161 |
+
# since `nodes` already has a list of the nodes grouped by connected
|
| 162 |
+
# component).
|
| 163 |
+
visited = set()
|
| 164 |
+
for u in nodes:
|
| 165 |
+
visited.add(u)
|
| 166 |
+
# For each nontree edge going out of node u...
|
| 167 |
+
edges = ((u, v) for u, v, d in H.out_edges(u, data="nontree") if d)
|
| 168 |
+
for u, v in edges:
|
| 169 |
+
# Create the cycle or cycle prefix starting with the
|
| 170 |
+
# nontree edge.
|
| 171 |
+
chain = list(_build_chain(H, u, v, visited))
|
| 172 |
+
yield chain
|
micromamba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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Algorithms for chordal graphs.
|
| 3 |
+
|
| 4 |
+
A graph is chordal if every cycle of length at least 4 has a chord
|
| 5 |
+
(an edge joining two nodes not adjacent in the cycle).
|
| 6 |
+
https://en.wikipedia.org/wiki/Chordal_graph
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
import networkx as nx
|
| 12 |
+
from networkx.algorithms.components import connected_components
|
| 13 |
+
from networkx.utils import arbitrary_element, not_implemented_for
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
"is_chordal",
|
| 17 |
+
"find_induced_nodes",
|
| 18 |
+
"chordal_graph_cliques",
|
| 19 |
+
"chordal_graph_treewidth",
|
| 20 |
+
"NetworkXTreewidthBoundExceeded",
|
| 21 |
+
"complete_to_chordal_graph",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class NetworkXTreewidthBoundExceeded(nx.NetworkXException):
|
| 26 |
+
"""Exception raised when a treewidth bound has been provided and it has
|
| 27 |
+
been exceeded"""
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@not_implemented_for("directed")
|
| 31 |
+
@not_implemented_for("multigraph")
|
| 32 |
+
@nx._dispatchable
|
| 33 |
+
def is_chordal(G):
|
| 34 |
+
"""Checks whether G is a chordal graph.
|
| 35 |
+
|
| 36 |
+
A graph is chordal if every cycle of length at least 4 has a chord
|
| 37 |
+
(an edge joining two nodes not adjacent in the cycle).
|
| 38 |
+
|
| 39 |
+
Parameters
|
| 40 |
+
----------
|
| 41 |
+
G : graph
|
| 42 |
+
A NetworkX graph.
|
| 43 |
+
|
| 44 |
+
Returns
|
| 45 |
+
-------
|
| 46 |
+
chordal : bool
|
| 47 |
+
True if G is a chordal graph and False otherwise.
|
| 48 |
+
|
| 49 |
+
Raises
|
| 50 |
+
------
|
| 51 |
+
NetworkXNotImplemented
|
| 52 |
+
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
|
| 53 |
+
|
| 54 |
+
Examples
|
| 55 |
+
--------
|
| 56 |
+
>>> e = [
|
| 57 |
+
... (1, 2),
|
| 58 |
+
... (1, 3),
|
| 59 |
+
... (2, 3),
|
| 60 |
+
... (2, 4),
|
| 61 |
+
... (3, 4),
|
| 62 |
+
... (3, 5),
|
| 63 |
+
... (3, 6),
|
| 64 |
+
... (4, 5),
|
| 65 |
+
... (4, 6),
|
| 66 |
+
... (5, 6),
|
| 67 |
+
... ]
|
| 68 |
+
>>> G = nx.Graph(e)
|
| 69 |
+
>>> nx.is_chordal(G)
|
| 70 |
+
True
|
| 71 |
+
|
| 72 |
+
Notes
|
| 73 |
+
-----
|
| 74 |
+
The routine tries to go through every node following maximum cardinality
|
| 75 |
+
search. It returns False when it finds that the separator for any node
|
| 76 |
+
is not a clique. Based on the algorithms in [1]_.
|
| 77 |
+
|
| 78 |
+
Self loops are ignored.
|
| 79 |
+
|
| 80 |
+
References
|
| 81 |
+
----------
|
| 82 |
+
.. [1] R. E. Tarjan and M. Yannakakis, Simple linear-time algorithms
|
| 83 |
+
to test chordality of graphs, test acyclicity of hypergraphs, and
|
| 84 |
+
selectively reduce acyclic hypergraphs, SIAM J. Comput., 13 (1984),
|
| 85 |
+
pp. 566–579.
|
| 86 |
+
"""
|
| 87 |
+
if len(G.nodes) <= 3:
|
| 88 |
+
return True
|
| 89 |
+
return len(_find_chordality_breaker(G)) == 0
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@nx._dispatchable
|
| 93 |
+
def find_induced_nodes(G, s, t, treewidth_bound=sys.maxsize):
|
| 94 |
+
"""Returns the set of induced nodes in the path from s to t.
|
| 95 |
+
|
| 96 |
+
Parameters
|
| 97 |
+
----------
|
| 98 |
+
G : graph
|
| 99 |
+
A chordal NetworkX graph
|
| 100 |
+
s : node
|
| 101 |
+
Source node to look for induced nodes
|
| 102 |
+
t : node
|
| 103 |
+
Destination node to look for induced nodes
|
| 104 |
+
treewidth_bound: float
|
| 105 |
+
Maximum treewidth acceptable for the graph H. The search
|
| 106 |
+
for induced nodes will end as soon as the treewidth_bound is exceeded.
|
| 107 |
+
|
| 108 |
+
Returns
|
| 109 |
+
-------
|
| 110 |
+
induced_nodes : Set of nodes
|
| 111 |
+
The set of induced nodes in the path from s to t in G
|
| 112 |
+
|
| 113 |
+
Raises
|
| 114 |
+
------
|
| 115 |
+
NetworkXError
|
| 116 |
+
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
|
| 117 |
+
If the input graph is an instance of one of these classes, a
|
| 118 |
+
:exc:`NetworkXError` is raised.
|
| 119 |
+
The algorithm can only be applied to chordal graphs. If the input
|
| 120 |
+
graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
|
| 121 |
+
|
| 122 |
+
Examples
|
| 123 |
+
--------
|
| 124 |
+
>>> G = nx.Graph()
|
| 125 |
+
>>> G = nx.generators.classic.path_graph(10)
|
| 126 |
+
>>> induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
|
| 127 |
+
>>> sorted(induced_nodes)
|
| 128 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9]
|
| 129 |
+
|
| 130 |
+
Notes
|
| 131 |
+
-----
|
| 132 |
+
G must be a chordal graph and (s,t) an edge that is not in G.
|
| 133 |
+
|
| 134 |
+
If a treewidth_bound is provided, the search for induced nodes will end
|
| 135 |
+
as soon as the treewidth_bound is exceeded.
|
| 136 |
+
|
| 137 |
+
The algorithm is inspired by Algorithm 4 in [1]_.
|
| 138 |
+
A formal definition of induced node can also be found on that reference.
|
| 139 |
+
|
| 140 |
+
Self Loops are ignored
|
| 141 |
+
|
| 142 |
+
References
|
| 143 |
+
----------
|
| 144 |
+
.. [1] Learning Bounded Treewidth Bayesian Networks.
|
| 145 |
+
Gal Elidan, Stephen Gould; JMLR, 9(Dec):2699--2731, 2008.
|
| 146 |
+
http://jmlr.csail.mit.edu/papers/volume9/elidan08a/elidan08a.pdf
|
| 147 |
+
"""
|
| 148 |
+
if not is_chordal(G):
|
| 149 |
+
raise nx.NetworkXError("Input graph is not chordal.")
|
| 150 |
+
|
| 151 |
+
H = nx.Graph(G)
|
| 152 |
+
H.add_edge(s, t)
|
| 153 |
+
induced_nodes = set()
|
| 154 |
+
triplet = _find_chordality_breaker(H, s, treewidth_bound)
|
| 155 |
+
while triplet:
|
| 156 |
+
(u, v, w) = triplet
|
| 157 |
+
induced_nodes.update(triplet)
|
| 158 |
+
for n in triplet:
|
| 159 |
+
if n != s:
|
| 160 |
+
H.add_edge(s, n)
|
| 161 |
+
triplet = _find_chordality_breaker(H, s, treewidth_bound)
|
| 162 |
+
if induced_nodes:
|
| 163 |
+
# Add t and the second node in the induced path from s to t.
|
| 164 |
+
induced_nodes.add(t)
|
| 165 |
+
for u in G[s]:
|
| 166 |
+
if len(induced_nodes & set(G[u])) == 2:
|
| 167 |
+
induced_nodes.add(u)
|
| 168 |
+
break
|
| 169 |
+
return induced_nodes
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@nx._dispatchable
|
| 173 |
+
def chordal_graph_cliques(G):
|
| 174 |
+
"""Returns all maximal cliques of a chordal graph.
|
| 175 |
+
|
| 176 |
+
The algorithm breaks the graph in connected components and performs a
|
| 177 |
+
maximum cardinality search in each component to get the cliques.
|
| 178 |
+
|
| 179 |
+
Parameters
|
| 180 |
+
----------
|
| 181 |
+
G : graph
|
| 182 |
+
A NetworkX graph
|
| 183 |
+
|
| 184 |
+
Yields
|
| 185 |
+
------
|
| 186 |
+
frozenset of nodes
|
| 187 |
+
Maximal cliques, each of which is a frozenset of
|
| 188 |
+
nodes in `G`. The order of cliques is arbitrary.
|
| 189 |
+
|
| 190 |
+
Raises
|
| 191 |
+
------
|
| 192 |
+
NetworkXError
|
| 193 |
+
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
|
| 194 |
+
The algorithm can only be applied to chordal graphs. If the input
|
| 195 |
+
graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
|
| 196 |
+
|
| 197 |
+
Examples
|
| 198 |
+
--------
|
| 199 |
+
>>> e = [
|
| 200 |
+
... (1, 2),
|
| 201 |
+
... (1, 3),
|
| 202 |
+
... (2, 3),
|
| 203 |
+
... (2, 4),
|
| 204 |
+
... (3, 4),
|
| 205 |
+
... (3, 5),
|
| 206 |
+
... (3, 6),
|
| 207 |
+
... (4, 5),
|
| 208 |
+
... (4, 6),
|
| 209 |
+
... (5, 6),
|
| 210 |
+
... (7, 8),
|
| 211 |
+
... ]
|
| 212 |
+
>>> G = nx.Graph(e)
|
| 213 |
+
>>> G.add_node(9)
|
| 214 |
+
>>> cliques = [c for c in chordal_graph_cliques(G)]
|
| 215 |
+
>>> cliques[0]
|
| 216 |
+
frozenset({1, 2, 3})
|
| 217 |
+
"""
|
| 218 |
+
for C in (G.subgraph(c).copy() for c in connected_components(G)):
|
| 219 |
+
if C.number_of_nodes() == 1:
|
| 220 |
+
if nx.number_of_selfloops(C) > 0:
|
| 221 |
+
raise nx.NetworkXError("Input graph is not chordal.")
|
| 222 |
+
yield frozenset(C.nodes())
|
| 223 |
+
else:
|
| 224 |
+
unnumbered = set(C.nodes())
|
| 225 |
+
v = arbitrary_element(C)
|
| 226 |
+
unnumbered.remove(v)
|
| 227 |
+
numbered = {v}
|
| 228 |
+
clique_wanna_be = {v}
|
| 229 |
+
while unnumbered:
|
| 230 |
+
v = _max_cardinality_node(C, unnumbered, numbered)
|
| 231 |
+
unnumbered.remove(v)
|
| 232 |
+
numbered.add(v)
|
| 233 |
+
new_clique_wanna_be = set(C.neighbors(v)) & numbered
|
| 234 |
+
sg = C.subgraph(clique_wanna_be)
|
| 235 |
+
if _is_complete_graph(sg):
|
| 236 |
+
new_clique_wanna_be.add(v)
|
| 237 |
+
if not new_clique_wanna_be >= clique_wanna_be:
|
| 238 |
+
yield frozenset(clique_wanna_be)
|
| 239 |
+
clique_wanna_be = new_clique_wanna_be
|
| 240 |
+
else:
|
| 241 |
+
raise nx.NetworkXError("Input graph is not chordal.")
|
| 242 |
+
yield frozenset(clique_wanna_be)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@nx._dispatchable
|
| 246 |
+
def chordal_graph_treewidth(G):
|
| 247 |
+
"""Returns the treewidth of the chordal graph G.
|
| 248 |
+
|
| 249 |
+
Parameters
|
| 250 |
+
----------
|
| 251 |
+
G : graph
|
| 252 |
+
A NetworkX graph
|
| 253 |
+
|
| 254 |
+
Returns
|
| 255 |
+
-------
|
| 256 |
+
treewidth : int
|
| 257 |
+
The size of the largest clique in the graph minus one.
|
| 258 |
+
|
| 259 |
+
Raises
|
| 260 |
+
------
|
| 261 |
+
NetworkXError
|
| 262 |
+
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
|
| 263 |
+
The algorithm can only be applied to chordal graphs. If the input
|
| 264 |
+
graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
|
| 265 |
+
|
| 266 |
+
Examples
|
| 267 |
+
--------
|
| 268 |
+
>>> e = [
|
| 269 |
+
... (1, 2),
|
| 270 |
+
... (1, 3),
|
| 271 |
+
... (2, 3),
|
| 272 |
+
... (2, 4),
|
| 273 |
+
... (3, 4),
|
| 274 |
+
... (3, 5),
|
| 275 |
+
... (3, 6),
|
| 276 |
+
... (4, 5),
|
| 277 |
+
... (4, 6),
|
| 278 |
+
... (5, 6),
|
| 279 |
+
... (7, 8),
|
| 280 |
+
... ]
|
| 281 |
+
>>> G = nx.Graph(e)
|
| 282 |
+
>>> G.add_node(9)
|
| 283 |
+
>>> nx.chordal_graph_treewidth(G)
|
| 284 |
+
3
|
| 285 |
+
|
| 286 |
+
References
|
| 287 |
+
----------
|
| 288 |
+
.. [1] https://en.wikipedia.org/wiki/Tree_decomposition#Treewidth
|
| 289 |
+
"""
|
| 290 |
+
if not is_chordal(G):
|
| 291 |
+
raise nx.NetworkXError("Input graph is not chordal.")
|
| 292 |
+
|
| 293 |
+
max_clique = -1
|
| 294 |
+
for clique in nx.chordal_graph_cliques(G):
|
| 295 |
+
max_clique = max(max_clique, len(clique))
|
| 296 |
+
return max_clique - 1
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def _is_complete_graph(G):
|
| 300 |
+
"""Returns True if G is a complete graph."""
|
| 301 |
+
if nx.number_of_selfloops(G) > 0:
|
| 302 |
+
raise nx.NetworkXError("Self loop found in _is_complete_graph()")
|
| 303 |
+
n = G.number_of_nodes()
|
| 304 |
+
if n < 2:
|
| 305 |
+
return True
|
| 306 |
+
e = G.number_of_edges()
|
| 307 |
+
max_edges = (n * (n - 1)) / 2
|
| 308 |
+
return e == max_edges
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _find_missing_edge(G):
|
| 312 |
+
"""Given a non-complete graph G, returns a missing edge."""
|
| 313 |
+
nodes = set(G)
|
| 314 |
+
for u in G:
|
| 315 |
+
missing = nodes - set(list(G[u].keys()) + [u])
|
| 316 |
+
if missing:
|
| 317 |
+
return (u, missing.pop())
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _max_cardinality_node(G, choices, wanna_connect):
|
| 321 |
+
"""Returns a the node in choices that has more connections in G
|
| 322 |
+
to nodes in wanna_connect.
|
| 323 |
+
"""
|
| 324 |
+
max_number = -1
|
| 325 |
+
for x in choices:
|
| 326 |
+
number = len([y for y in G[x] if y in wanna_connect])
|
| 327 |
+
if number > max_number:
|
| 328 |
+
max_number = number
|
| 329 |
+
max_cardinality_node = x
|
| 330 |
+
return max_cardinality_node
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _find_chordality_breaker(G, s=None, treewidth_bound=sys.maxsize):
|
| 334 |
+
"""Given a graph G, starts a max cardinality search
|
| 335 |
+
(starting from s if s is given and from an arbitrary node otherwise)
|
| 336 |
+
trying to find a non-chordal cycle.
|
| 337 |
+
|
| 338 |
+
If it does find one, it returns (u,v,w) where u,v,w are the three
|
| 339 |
+
nodes that together with s are involved in the cycle.
|
| 340 |
+
|
| 341 |
+
It ignores any self loops.
|
| 342 |
+
"""
|
| 343 |
+
if len(G) == 0:
|
| 344 |
+
raise nx.NetworkXPointlessConcept("Graph has no nodes.")
|
| 345 |
+
unnumbered = set(G)
|
| 346 |
+
if s is None:
|
| 347 |
+
s = arbitrary_element(G)
|
| 348 |
+
unnumbered.remove(s)
|
| 349 |
+
numbered = {s}
|
| 350 |
+
current_treewidth = -1
|
| 351 |
+
while unnumbered: # and current_treewidth <= treewidth_bound:
|
| 352 |
+
v = _max_cardinality_node(G, unnumbered, numbered)
|
| 353 |
+
unnumbered.remove(v)
|
| 354 |
+
numbered.add(v)
|
| 355 |
+
clique_wanna_be = set(G[v]) & numbered
|
| 356 |
+
sg = G.subgraph(clique_wanna_be)
|
| 357 |
+
if _is_complete_graph(sg):
|
| 358 |
+
# The graph seems to be chordal by now. We update the treewidth
|
| 359 |
+
current_treewidth = max(current_treewidth, len(clique_wanna_be))
|
| 360 |
+
if current_treewidth > treewidth_bound:
|
| 361 |
+
raise nx.NetworkXTreewidthBoundExceeded(
|
| 362 |
+
f"treewidth_bound exceeded: {current_treewidth}"
|
| 363 |
+
)
|
| 364 |
+
else:
|
| 365 |
+
# sg is not a clique,
|
| 366 |
+
# look for an edge that is not included in sg
|
| 367 |
+
(u, w) = _find_missing_edge(sg)
|
| 368 |
+
return (u, v, w)
|
| 369 |
+
return ()
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
@not_implemented_for("directed")
|
| 373 |
+
@nx._dispatchable(returns_graph=True)
|
| 374 |
+
def complete_to_chordal_graph(G):
|
| 375 |
+
"""Return a copy of G completed to a chordal graph
|
| 376 |
+
|
| 377 |
+
Adds edges to a copy of G to create a chordal graph. A graph G=(V,E) is
|
| 378 |
+
called chordal if for each cycle with length bigger than 3, there exist
|
| 379 |
+
two non-adjacent nodes connected by an edge (called a chord).
|
| 380 |
+
|
| 381 |
+
Parameters
|
| 382 |
+
----------
|
| 383 |
+
G : NetworkX graph
|
| 384 |
+
Undirected graph
|
| 385 |
+
|
| 386 |
+
Returns
|
| 387 |
+
-------
|
| 388 |
+
H : NetworkX graph
|
| 389 |
+
The chordal enhancement of G
|
| 390 |
+
alpha : Dictionary
|
| 391 |
+
The elimination ordering of nodes of G
|
| 392 |
+
|
| 393 |
+
Notes
|
| 394 |
+
-----
|
| 395 |
+
There are different approaches to calculate the chordal
|
| 396 |
+
enhancement of a graph. The algorithm used here is called
|
| 397 |
+
MCS-M and gives at least minimal (local) triangulation of graph. Note
|
| 398 |
+
that this triangulation is not necessarily a global minimum.
|
| 399 |
+
|
| 400 |
+
https://en.wikipedia.org/wiki/Chordal_graph
|
| 401 |
+
|
| 402 |
+
References
|
| 403 |
+
----------
|
| 404 |
+
.. [1] Berry, Anne & Blair, Jean & Heggernes, Pinar & Peyton, Barry. (2004)
|
| 405 |
+
Maximum Cardinality Search for Computing Minimal Triangulations of
|
| 406 |
+
Graphs. Algorithmica. 39. 287-298. 10.1007/s00453-004-1084-3.
|
| 407 |
+
|
| 408 |
+
Examples
|
| 409 |
+
--------
|
| 410 |
+
>>> from networkx.algorithms.chordal import complete_to_chordal_graph
|
| 411 |
+
>>> G = nx.wheel_graph(10)
|
| 412 |
+
>>> H, alpha = complete_to_chordal_graph(G)
|
| 413 |
+
"""
|
| 414 |
+
H = G.copy()
|
| 415 |
+
alpha = {node: 0 for node in H}
|
| 416 |
+
if nx.is_chordal(H):
|
| 417 |
+
return H, alpha
|
| 418 |
+
chords = set()
|
| 419 |
+
weight = {node: 0 for node in H.nodes()}
|
| 420 |
+
unnumbered_nodes = list(H.nodes())
|
| 421 |
+
for i in range(len(H.nodes()), 0, -1):
|
| 422 |
+
# get the node in unnumbered_nodes with the maximum weight
|
| 423 |
+
z = max(unnumbered_nodes, key=lambda node: weight[node])
|
| 424 |
+
unnumbered_nodes.remove(z)
|
| 425 |
+
alpha[z] = i
|
| 426 |
+
update_nodes = []
|
| 427 |
+
for y in unnumbered_nodes:
|
| 428 |
+
if G.has_edge(y, z):
|
| 429 |
+
update_nodes.append(y)
|
| 430 |
+
else:
|
| 431 |
+
# y_weight will be bigger than node weights between y and z
|
| 432 |
+
y_weight = weight[y]
|
| 433 |
+
lower_nodes = [
|
| 434 |
+
node for node in unnumbered_nodes if weight[node] < y_weight
|
| 435 |
+
]
|
| 436 |
+
if nx.has_path(H.subgraph(lower_nodes + [z, y]), y, z):
|
| 437 |
+
update_nodes.append(y)
|
| 438 |
+
chords.add((z, y))
|
| 439 |
+
# during calculation of paths the weights should not be updated
|
| 440 |
+
for node in update_nodes:
|
| 441 |
+
weight[node] += 1
|
| 442 |
+
H.add_edges_from(chords)
|
| 443 |
+
return H, alpha
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/clique.py
ADDED
|
@@ -0,0 +1,818 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for finding and manipulating cliques.
|
| 2 |
+
|
| 3 |
+
Finding the largest clique in a graph is NP-complete problem, so most of
|
| 4 |
+
these algorithms have an exponential running time; for more information,
|
| 5 |
+
see the Wikipedia article on the clique problem [1]_.
|
| 6 |
+
|
| 7 |
+
.. [1] clique problem:: https://en.wikipedia.org/wiki/Clique_problem
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from collections import Counter, defaultdict, deque
|
| 12 |
+
from itertools import chain, combinations, islice
|
| 13 |
+
|
| 14 |
+
import networkx as nx
|
| 15 |
+
from networkx.utils import not_implemented_for
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"find_cliques",
|
| 19 |
+
"find_cliques_recursive",
|
| 20 |
+
"make_max_clique_graph",
|
| 21 |
+
"make_clique_bipartite",
|
| 22 |
+
"node_clique_number",
|
| 23 |
+
"number_of_cliques",
|
| 24 |
+
"enumerate_all_cliques",
|
| 25 |
+
"max_weight_clique",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@not_implemented_for("directed")
|
| 30 |
+
@nx._dispatchable
|
| 31 |
+
def enumerate_all_cliques(G):
|
| 32 |
+
"""Returns all cliques in an undirected graph.
|
| 33 |
+
|
| 34 |
+
This function returns an iterator over cliques, each of which is a
|
| 35 |
+
list of nodes. The iteration is ordered by cardinality of the
|
| 36 |
+
cliques: first all cliques of size one, then all cliques of size
|
| 37 |
+
two, etc.
|
| 38 |
+
|
| 39 |
+
Parameters
|
| 40 |
+
----------
|
| 41 |
+
G : NetworkX graph
|
| 42 |
+
An undirected graph.
|
| 43 |
+
|
| 44 |
+
Returns
|
| 45 |
+
-------
|
| 46 |
+
iterator
|
| 47 |
+
An iterator over cliques, each of which is a list of nodes in
|
| 48 |
+
`G`. The cliques are ordered according to size.
|
| 49 |
+
|
| 50 |
+
Notes
|
| 51 |
+
-----
|
| 52 |
+
To obtain a list of all cliques, use
|
| 53 |
+
`list(enumerate_all_cliques(G))`. However, be aware that in the
|
| 54 |
+
worst-case, the length of this list can be exponential in the number
|
| 55 |
+
of nodes in the graph (for example, when the graph is the complete
|
| 56 |
+
graph). This function avoids storing all cliques in memory by only
|
| 57 |
+
keeping current candidate node lists in memory during its search.
|
| 58 |
+
|
| 59 |
+
The implementation is adapted from the algorithm by Zhang, et
|
| 60 |
+
al. (2005) [1]_ to output all cliques discovered.
|
| 61 |
+
|
| 62 |
+
This algorithm ignores self-loops and parallel edges, since cliques
|
| 63 |
+
are not conventionally defined with such edges.
|
| 64 |
+
|
| 65 |
+
References
|
| 66 |
+
----------
|
| 67 |
+
.. [1] Yun Zhang, Abu-Khzam, F.N., Baldwin, N.E., Chesler, E.J.,
|
| 68 |
+
Langston, M.A., Samatova, N.F.,
|
| 69 |
+
"Genome-Scale Computational Approaches to Memory-Intensive
|
| 70 |
+
Applications in Systems Biology".
|
| 71 |
+
*Supercomputing*, 2005. Proceedings of the ACM/IEEE SC 2005
|
| 72 |
+
Conference, pp. 12, 12--18 Nov. 2005.
|
| 73 |
+
<https://doi.org/10.1109/SC.2005.29>.
|
| 74 |
+
|
| 75 |
+
"""
|
| 76 |
+
index = {}
|
| 77 |
+
nbrs = {}
|
| 78 |
+
for u in G:
|
| 79 |
+
index[u] = len(index)
|
| 80 |
+
# Neighbors of u that appear after u in the iteration order of G.
|
| 81 |
+
nbrs[u] = {v for v in G[u] if v not in index}
|
| 82 |
+
|
| 83 |
+
queue = deque(([u], sorted(nbrs[u], key=index.__getitem__)) for u in G)
|
| 84 |
+
# Loop invariants:
|
| 85 |
+
# 1. len(base) is nondecreasing.
|
| 86 |
+
# 2. (base + cnbrs) is sorted with respect to the iteration order of G.
|
| 87 |
+
# 3. cnbrs is a set of common neighbors of nodes in base.
|
| 88 |
+
while queue:
|
| 89 |
+
base, cnbrs = map(list, queue.popleft())
|
| 90 |
+
yield base
|
| 91 |
+
for i, u in enumerate(cnbrs):
|
| 92 |
+
# Use generators to reduce memory consumption.
|
| 93 |
+
queue.append(
|
| 94 |
+
(
|
| 95 |
+
chain(base, [u]),
|
| 96 |
+
filter(nbrs[u].__contains__, islice(cnbrs, i + 1, None)),
|
| 97 |
+
)
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@not_implemented_for("directed")
|
| 102 |
+
@nx._dispatchable
|
| 103 |
+
def find_cliques(G, nodes=None):
|
| 104 |
+
"""Returns all maximal cliques in an undirected graph.
|
| 105 |
+
|
| 106 |
+
For each node *n*, a *maximal clique for n* is a largest complete
|
| 107 |
+
subgraph containing *n*. The largest maximal clique is sometimes
|
| 108 |
+
called the *maximum clique*.
|
| 109 |
+
|
| 110 |
+
This function returns an iterator over cliques, each of which is a
|
| 111 |
+
list of nodes. It is an iterative implementation, so should not
|
| 112 |
+
suffer from recursion depth issues.
|
| 113 |
+
|
| 114 |
+
This function accepts a list of `nodes` and only the maximal cliques
|
| 115 |
+
containing all of these `nodes` are returned. It can considerably speed up
|
| 116 |
+
the running time if some specific cliques are desired.
|
| 117 |
+
|
| 118 |
+
Parameters
|
| 119 |
+
----------
|
| 120 |
+
G : NetworkX graph
|
| 121 |
+
An undirected graph.
|
| 122 |
+
|
| 123 |
+
nodes : list, optional (default=None)
|
| 124 |
+
If provided, only yield *maximal cliques* containing all nodes in `nodes`.
|
| 125 |
+
If `nodes` isn't a clique itself, a ValueError is raised.
|
| 126 |
+
|
| 127 |
+
Returns
|
| 128 |
+
-------
|
| 129 |
+
iterator
|
| 130 |
+
An iterator over maximal cliques, each of which is a list of
|
| 131 |
+
nodes in `G`. If `nodes` is provided, only the maximal cliques
|
| 132 |
+
containing all the nodes in `nodes` are returned. The order of
|
| 133 |
+
cliques is arbitrary.
|
| 134 |
+
|
| 135 |
+
Raises
|
| 136 |
+
------
|
| 137 |
+
ValueError
|
| 138 |
+
If `nodes` is not a clique.
|
| 139 |
+
|
| 140 |
+
Examples
|
| 141 |
+
--------
|
| 142 |
+
>>> from pprint import pprint # For nice dict formatting
|
| 143 |
+
>>> G = nx.karate_club_graph()
|
| 144 |
+
>>> sum(1 for c in nx.find_cliques(G)) # The number of maximal cliques in G
|
| 145 |
+
36
|
| 146 |
+
>>> max(nx.find_cliques(G), key=len) # The largest maximal clique in G
|
| 147 |
+
[0, 1, 2, 3, 13]
|
| 148 |
+
|
| 149 |
+
The size of the largest maximal clique is known as the *clique number* of
|
| 150 |
+
the graph, which can be found directly with:
|
| 151 |
+
|
| 152 |
+
>>> max(len(c) for c in nx.find_cliques(G))
|
| 153 |
+
5
|
| 154 |
+
|
| 155 |
+
One can also compute the number of maximal cliques in `G` that contain a given
|
| 156 |
+
node. The following produces a dictionary keyed by node whose
|
| 157 |
+
values are the number of maximal cliques in `G` that contain the node:
|
| 158 |
+
|
| 159 |
+
>>> from collections import Counter
|
| 160 |
+
>>> from itertools import chain
|
| 161 |
+
>>> counts = Counter(chain.from_iterable(nx.find_cliques(G)))
|
| 162 |
+
>>> pprint(dict(counts))
|
| 163 |
+
{0: 13,
|
| 164 |
+
1: 6,
|
| 165 |
+
2: 7,
|
| 166 |
+
3: 3,
|
| 167 |
+
4: 2,
|
| 168 |
+
5: 3,
|
| 169 |
+
6: 3,
|
| 170 |
+
7: 1,
|
| 171 |
+
8: 3,
|
| 172 |
+
9: 2,
|
| 173 |
+
10: 2,
|
| 174 |
+
11: 1,
|
| 175 |
+
12: 1,
|
| 176 |
+
13: 2,
|
| 177 |
+
14: 1,
|
| 178 |
+
15: 1,
|
| 179 |
+
16: 1,
|
| 180 |
+
17: 1,
|
| 181 |
+
18: 1,
|
| 182 |
+
19: 2,
|
| 183 |
+
20: 1,
|
| 184 |
+
21: 1,
|
| 185 |
+
22: 1,
|
| 186 |
+
23: 3,
|
| 187 |
+
24: 2,
|
| 188 |
+
25: 2,
|
| 189 |
+
26: 1,
|
| 190 |
+
27: 3,
|
| 191 |
+
28: 2,
|
| 192 |
+
29: 2,
|
| 193 |
+
30: 2,
|
| 194 |
+
31: 4,
|
| 195 |
+
32: 9,
|
| 196 |
+
33: 14}
|
| 197 |
+
|
| 198 |
+
Or, similarly, the maximal cliques in `G` that contain a given node.
|
| 199 |
+
For example, the 4 maximal cliques that contain node 31:
|
| 200 |
+
|
| 201 |
+
>>> [c for c in nx.find_cliques(G) if 31 in c]
|
| 202 |
+
[[0, 31], [33, 32, 31], [33, 28, 31], [24, 25, 31]]
|
| 203 |
+
|
| 204 |
+
See Also
|
| 205 |
+
--------
|
| 206 |
+
find_cliques_recursive
|
| 207 |
+
A recursive version of the same algorithm.
|
| 208 |
+
|
| 209 |
+
Notes
|
| 210 |
+
-----
|
| 211 |
+
To obtain a list of all maximal cliques, use
|
| 212 |
+
`list(find_cliques(G))`. However, be aware that in the worst-case,
|
| 213 |
+
the length of this list can be exponential in the number of nodes in
|
| 214 |
+
the graph. This function avoids storing all cliques in memory by
|
| 215 |
+
only keeping current candidate node lists in memory during its search.
|
| 216 |
+
|
| 217 |
+
This implementation is based on the algorithm published by Bron and
|
| 218 |
+
Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi
|
| 219 |
+
(2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. It
|
| 220 |
+
essentially unrolls the recursion used in the references to avoid
|
| 221 |
+
issues of recursion stack depth (for a recursive implementation, see
|
| 222 |
+
:func:`find_cliques_recursive`).
|
| 223 |
+
|
| 224 |
+
This algorithm ignores self-loops and parallel edges, since cliques
|
| 225 |
+
are not conventionally defined with such edges.
|
| 226 |
+
|
| 227 |
+
References
|
| 228 |
+
----------
|
| 229 |
+
.. [1] Bron, C. and Kerbosch, J.
|
| 230 |
+
"Algorithm 457: finding all cliques of an undirected graph".
|
| 231 |
+
*Communications of the ACM* 16, 9 (Sep. 1973), 575--577.
|
| 232 |
+
<http://portal.acm.org/citation.cfm?doid=362342.362367>
|
| 233 |
+
|
| 234 |
+
.. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi,
|
| 235 |
+
"The worst-case time complexity for generating all maximal
|
| 236 |
+
cliques and computational experiments",
|
| 237 |
+
*Theoretical Computer Science*, Volume 363, Issue 1,
|
| 238 |
+
Computing and Combinatorics,
|
| 239 |
+
10th Annual International Conference on
|
| 240 |
+
Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42
|
| 241 |
+
<https://doi.org/10.1016/j.tcs.2006.06.015>
|
| 242 |
+
|
| 243 |
+
.. [3] F. Cazals, C. Karande,
|
| 244 |
+
"A note on the problem of reporting maximal cliques",
|
| 245 |
+
*Theoretical Computer Science*,
|
| 246 |
+
Volume 407, Issues 1--3, 6 November 2008, Pages 564--568,
|
| 247 |
+
<https://doi.org/10.1016/j.tcs.2008.05.010>
|
| 248 |
+
|
| 249 |
+
"""
|
| 250 |
+
if len(G) == 0:
|
| 251 |
+
return
|
| 252 |
+
|
| 253 |
+
adj = {u: {v for v in G[u] if v != u} for u in G}
|
| 254 |
+
|
| 255 |
+
# Initialize Q with the given nodes and subg, cand with their nbrs
|
| 256 |
+
Q = nodes[:] if nodes is not None else []
|
| 257 |
+
cand = set(G)
|
| 258 |
+
for node in Q:
|
| 259 |
+
if node not in cand:
|
| 260 |
+
raise ValueError(f"The given `nodes` {nodes} do not form a clique")
|
| 261 |
+
cand &= adj[node]
|
| 262 |
+
|
| 263 |
+
if not cand:
|
| 264 |
+
yield Q[:]
|
| 265 |
+
return
|
| 266 |
+
|
| 267 |
+
subg = cand.copy()
|
| 268 |
+
stack = []
|
| 269 |
+
Q.append(None)
|
| 270 |
+
|
| 271 |
+
u = max(subg, key=lambda u: len(cand & adj[u]))
|
| 272 |
+
ext_u = cand - adj[u]
|
| 273 |
+
|
| 274 |
+
try:
|
| 275 |
+
while True:
|
| 276 |
+
if ext_u:
|
| 277 |
+
q = ext_u.pop()
|
| 278 |
+
cand.remove(q)
|
| 279 |
+
Q[-1] = q
|
| 280 |
+
adj_q = adj[q]
|
| 281 |
+
subg_q = subg & adj_q
|
| 282 |
+
if not subg_q:
|
| 283 |
+
yield Q[:]
|
| 284 |
+
else:
|
| 285 |
+
cand_q = cand & adj_q
|
| 286 |
+
if cand_q:
|
| 287 |
+
stack.append((subg, cand, ext_u))
|
| 288 |
+
Q.append(None)
|
| 289 |
+
subg = subg_q
|
| 290 |
+
cand = cand_q
|
| 291 |
+
u = max(subg, key=lambda u: len(cand & adj[u]))
|
| 292 |
+
ext_u = cand - adj[u]
|
| 293 |
+
else:
|
| 294 |
+
Q.pop()
|
| 295 |
+
subg, cand, ext_u = stack.pop()
|
| 296 |
+
except IndexError:
|
| 297 |
+
pass
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
@not_implemented_for("directed")
|
| 301 |
+
@nx._dispatchable
|
| 302 |
+
def find_cliques_recursive(G, nodes=None):
|
| 303 |
+
"""Returns all maximal cliques in a graph.
|
| 304 |
+
|
| 305 |
+
For each node *v*, a *maximal clique for v* is a largest complete
|
| 306 |
+
subgraph containing *v*. The largest maximal clique is sometimes
|
| 307 |
+
called the *maximum clique*.
|
| 308 |
+
|
| 309 |
+
This function returns an iterator over cliques, each of which is a
|
| 310 |
+
list of nodes. It is a recursive implementation, so may suffer from
|
| 311 |
+
recursion depth issues, but is included for pedagogical reasons.
|
| 312 |
+
For a non-recursive implementation, see :func:`find_cliques`.
|
| 313 |
+
|
| 314 |
+
This function accepts a list of `nodes` and only the maximal cliques
|
| 315 |
+
containing all of these `nodes` are returned. It can considerably speed up
|
| 316 |
+
the running time if some specific cliques are desired.
|
| 317 |
+
|
| 318 |
+
Parameters
|
| 319 |
+
----------
|
| 320 |
+
G : NetworkX graph
|
| 321 |
+
An undirected graph.
|
| 322 |
+
|
| 323 |
+
nodes : list, optional (default=None)
|
| 324 |
+
If provided, only yield *maximal cliques* containing all nodes in `nodes`.
|
| 325 |
+
If `nodes` isn't a clique itself, a ValueError is raised.
|
| 326 |
+
|
| 327 |
+
Returns
|
| 328 |
+
-------
|
| 329 |
+
iterator
|
| 330 |
+
An iterator over maximal cliques, each of which is a list of
|
| 331 |
+
nodes in `G`. If `nodes` is provided, only the maximal cliques
|
| 332 |
+
containing all the nodes in `nodes` are yielded. The order of
|
| 333 |
+
cliques is arbitrary.
|
| 334 |
+
|
| 335 |
+
Raises
|
| 336 |
+
------
|
| 337 |
+
NetworkXNotImplemented
|
| 338 |
+
If `G` is directed.
|
| 339 |
+
|
| 340 |
+
ValueError
|
| 341 |
+
If `nodes` is not a clique.
|
| 342 |
+
|
| 343 |
+
See Also
|
| 344 |
+
--------
|
| 345 |
+
find_cliques
|
| 346 |
+
An iterative version of the same algorithm. See docstring for examples.
|
| 347 |
+
|
| 348 |
+
Notes
|
| 349 |
+
-----
|
| 350 |
+
To obtain a list of all maximal cliques, use
|
| 351 |
+
`list(find_cliques_recursive(G))`. However, be aware that in the
|
| 352 |
+
worst-case, the length of this list can be exponential in the number
|
| 353 |
+
of nodes in the graph. This function avoids storing all cliques in memory
|
| 354 |
+
by only keeping current candidate node lists in memory during its search.
|
| 355 |
+
|
| 356 |
+
This implementation is based on the algorithm published by Bron and
|
| 357 |
+
Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi
|
| 358 |
+
(2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. For a
|
| 359 |
+
non-recursive implementation, see :func:`find_cliques`.
|
| 360 |
+
|
| 361 |
+
This algorithm ignores self-loops and parallel edges, since cliques
|
| 362 |
+
are not conventionally defined with such edges.
|
| 363 |
+
|
| 364 |
+
References
|
| 365 |
+
----------
|
| 366 |
+
.. [1] Bron, C. and Kerbosch, J.
|
| 367 |
+
"Algorithm 457: finding all cliques of an undirected graph".
|
| 368 |
+
*Communications of the ACM* 16, 9 (Sep. 1973), 575--577.
|
| 369 |
+
<http://portal.acm.org/citation.cfm?doid=362342.362367>
|
| 370 |
+
|
| 371 |
+
.. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi,
|
| 372 |
+
"The worst-case time complexity for generating all maximal
|
| 373 |
+
cliques and computational experiments",
|
| 374 |
+
*Theoretical Computer Science*, Volume 363, Issue 1,
|
| 375 |
+
Computing and Combinatorics,
|
| 376 |
+
10th Annual International Conference on
|
| 377 |
+
Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42
|
| 378 |
+
<https://doi.org/10.1016/j.tcs.2006.06.015>
|
| 379 |
+
|
| 380 |
+
.. [3] F. Cazals, C. Karande,
|
| 381 |
+
"A note on the problem of reporting maximal cliques",
|
| 382 |
+
*Theoretical Computer Science*,
|
| 383 |
+
Volume 407, Issues 1--3, 6 November 2008, Pages 564--568,
|
| 384 |
+
<https://doi.org/10.1016/j.tcs.2008.05.010>
|
| 385 |
+
|
| 386 |
+
"""
|
| 387 |
+
if len(G) == 0:
|
| 388 |
+
return iter([])
|
| 389 |
+
|
| 390 |
+
adj = {u: {v for v in G[u] if v != u} for u in G}
|
| 391 |
+
|
| 392 |
+
# Initialize Q with the given nodes and subg, cand with their nbrs
|
| 393 |
+
Q = nodes[:] if nodes is not None else []
|
| 394 |
+
cand_init = set(G)
|
| 395 |
+
for node in Q:
|
| 396 |
+
if node not in cand_init:
|
| 397 |
+
raise ValueError(f"The given `nodes` {nodes} do not form a clique")
|
| 398 |
+
cand_init &= adj[node]
|
| 399 |
+
|
| 400 |
+
if not cand_init:
|
| 401 |
+
return iter([Q])
|
| 402 |
+
|
| 403 |
+
subg_init = cand_init.copy()
|
| 404 |
+
|
| 405 |
+
def expand(subg, cand):
|
| 406 |
+
u = max(subg, key=lambda u: len(cand & adj[u]))
|
| 407 |
+
for q in cand - adj[u]:
|
| 408 |
+
cand.remove(q)
|
| 409 |
+
Q.append(q)
|
| 410 |
+
adj_q = adj[q]
|
| 411 |
+
subg_q = subg & adj_q
|
| 412 |
+
if not subg_q:
|
| 413 |
+
yield Q[:]
|
| 414 |
+
else:
|
| 415 |
+
cand_q = cand & adj_q
|
| 416 |
+
if cand_q:
|
| 417 |
+
yield from expand(subg_q, cand_q)
|
| 418 |
+
Q.pop()
|
| 419 |
+
|
| 420 |
+
return expand(subg_init, cand_init)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
@nx._dispatchable(returns_graph=True)
|
| 424 |
+
def make_max_clique_graph(G, create_using=None):
|
| 425 |
+
"""Returns the maximal clique graph of the given graph.
|
| 426 |
+
|
| 427 |
+
The nodes of the maximal clique graph of `G` are the cliques of
|
| 428 |
+
`G` and an edge joins two cliques if the cliques are not disjoint.
|
| 429 |
+
|
| 430 |
+
Parameters
|
| 431 |
+
----------
|
| 432 |
+
G : NetworkX graph
|
| 433 |
+
|
| 434 |
+
create_using : NetworkX graph constructor, optional (default=nx.Graph)
|
| 435 |
+
Graph type to create. If graph instance, then cleared before populated.
|
| 436 |
+
|
| 437 |
+
Returns
|
| 438 |
+
-------
|
| 439 |
+
NetworkX graph
|
| 440 |
+
A graph whose nodes are the cliques of `G` and whose edges
|
| 441 |
+
join two cliques if they are not disjoint.
|
| 442 |
+
|
| 443 |
+
Notes
|
| 444 |
+
-----
|
| 445 |
+
This function behaves like the following code::
|
| 446 |
+
|
| 447 |
+
import networkx as nx
|
| 448 |
+
|
| 449 |
+
G = nx.make_clique_bipartite(G)
|
| 450 |
+
cliques = [v for v in G.nodes() if G.nodes[v]["bipartite"] == 0]
|
| 451 |
+
G = nx.bipartite.projected_graph(G, cliques)
|
| 452 |
+
G = nx.relabel_nodes(G, {-v: v - 1 for v in G})
|
| 453 |
+
|
| 454 |
+
It should be faster, though, since it skips all the intermediate
|
| 455 |
+
steps.
|
| 456 |
+
|
| 457 |
+
"""
|
| 458 |
+
if create_using is None:
|
| 459 |
+
B = G.__class__()
|
| 460 |
+
else:
|
| 461 |
+
B = nx.empty_graph(0, create_using)
|
| 462 |
+
cliques = list(enumerate(set(c) for c in find_cliques(G)))
|
| 463 |
+
# Add a numbered node for each clique.
|
| 464 |
+
B.add_nodes_from(i for i, c in cliques)
|
| 465 |
+
# Join cliques by an edge if they share a node.
|
| 466 |
+
clique_pairs = combinations(cliques, 2)
|
| 467 |
+
B.add_edges_from((i, j) for (i, c1), (j, c2) in clique_pairs if c1 & c2)
|
| 468 |
+
return B
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
@nx._dispatchable(returns_graph=True)
|
| 472 |
+
def make_clique_bipartite(G, fpos=None, create_using=None, name=None):
|
| 473 |
+
"""Returns the bipartite clique graph corresponding to `G`.
|
| 474 |
+
|
| 475 |
+
In the returned bipartite graph, the "bottom" nodes are the nodes of
|
| 476 |
+
`G` and the "top" nodes represent the maximal cliques of `G`.
|
| 477 |
+
There is an edge from node *v* to clique *C* in the returned graph
|
| 478 |
+
if and only if *v* is an element of *C*.
|
| 479 |
+
|
| 480 |
+
Parameters
|
| 481 |
+
----------
|
| 482 |
+
G : NetworkX graph
|
| 483 |
+
An undirected graph.
|
| 484 |
+
|
| 485 |
+
fpos : bool
|
| 486 |
+
If True or not None, the returned graph will have an
|
| 487 |
+
additional attribute, `pos`, a dictionary mapping node to
|
| 488 |
+
position in the Euclidean plane.
|
| 489 |
+
|
| 490 |
+
create_using : NetworkX graph constructor, optional (default=nx.Graph)
|
| 491 |
+
Graph type to create. If graph instance, then cleared before populated.
|
| 492 |
+
|
| 493 |
+
Returns
|
| 494 |
+
-------
|
| 495 |
+
NetworkX graph
|
| 496 |
+
A bipartite graph whose "bottom" set is the nodes of the graph
|
| 497 |
+
`G`, whose "top" set is the cliques of `G`, and whose edges
|
| 498 |
+
join nodes of `G` to the cliques that contain them.
|
| 499 |
+
|
| 500 |
+
The nodes of the graph `G` have the node attribute
|
| 501 |
+
'bipartite' set to 1 and the nodes representing cliques
|
| 502 |
+
have the node attribute 'bipartite' set to 0, as is the
|
| 503 |
+
convention for bipartite graphs in NetworkX.
|
| 504 |
+
|
| 505 |
+
"""
|
| 506 |
+
B = nx.empty_graph(0, create_using)
|
| 507 |
+
B.clear()
|
| 508 |
+
# The "bottom" nodes in the bipartite graph are the nodes of the
|
| 509 |
+
# original graph, G.
|
| 510 |
+
B.add_nodes_from(G, bipartite=1)
|
| 511 |
+
for i, cl in enumerate(find_cliques(G)):
|
| 512 |
+
# The "top" nodes in the bipartite graph are the cliques. These
|
| 513 |
+
# nodes get negative numbers as labels.
|
| 514 |
+
name = -i - 1
|
| 515 |
+
B.add_node(name, bipartite=0)
|
| 516 |
+
B.add_edges_from((v, name) for v in cl)
|
| 517 |
+
return B
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
@nx._dispatchable
|
| 521 |
+
def node_clique_number(G, nodes=None, cliques=None, separate_nodes=False):
|
| 522 |
+
"""Returns the size of the largest maximal clique containing each given node.
|
| 523 |
+
|
| 524 |
+
Returns a single or list depending on input nodes.
|
| 525 |
+
An optional list of cliques can be input if already computed.
|
| 526 |
+
|
| 527 |
+
Parameters
|
| 528 |
+
----------
|
| 529 |
+
G : NetworkX graph
|
| 530 |
+
An undirected graph.
|
| 531 |
+
|
| 532 |
+
cliques : list, optional (default=None)
|
| 533 |
+
A list of cliques, each of which is itself a list of nodes.
|
| 534 |
+
If not specified, the list of all cliques will be computed
|
| 535 |
+
using :func:`find_cliques`.
|
| 536 |
+
|
| 537 |
+
Returns
|
| 538 |
+
-------
|
| 539 |
+
int or dict
|
| 540 |
+
If `nodes` is a single node, returns the size of the
|
| 541 |
+
largest maximal clique in `G` containing that node.
|
| 542 |
+
Otherwise return a dict keyed by node to the size
|
| 543 |
+
of the largest maximal clique containing that node.
|
| 544 |
+
|
| 545 |
+
See Also
|
| 546 |
+
--------
|
| 547 |
+
find_cliques
|
| 548 |
+
find_cliques yields the maximal cliques of G.
|
| 549 |
+
It accepts a `nodes` argument which restricts consideration to
|
| 550 |
+
maximal cliques containing all the given `nodes`.
|
| 551 |
+
The search for the cliques is optimized for `nodes`.
|
| 552 |
+
number_of_cliques
|
| 553 |
+
"""
|
| 554 |
+
if cliques is None:
|
| 555 |
+
if nodes is not None:
|
| 556 |
+
# Use ego_graph to decrease size of graph
|
| 557 |
+
# check for single node
|
| 558 |
+
if nodes in G:
|
| 559 |
+
return max(len(c) for c in find_cliques(nx.ego_graph(G, nodes)))
|
| 560 |
+
# handle multiple nodes
|
| 561 |
+
return {
|
| 562 |
+
n: max(len(c) for c in find_cliques(nx.ego_graph(G, n))) for n in nodes
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
# nodes is None--find all cliques
|
| 566 |
+
cliques = list(find_cliques(G))
|
| 567 |
+
|
| 568 |
+
# single node requested
|
| 569 |
+
if nodes in G:
|
| 570 |
+
return max(len(c) for c in cliques if nodes in c)
|
| 571 |
+
|
| 572 |
+
# multiple nodes requested
|
| 573 |
+
# preprocess all nodes (faster than one at a time for even 2 nodes)
|
| 574 |
+
size_for_n = defaultdict(int)
|
| 575 |
+
for c in cliques:
|
| 576 |
+
size_of_c = len(c)
|
| 577 |
+
for n in c:
|
| 578 |
+
if size_for_n[n] < size_of_c:
|
| 579 |
+
size_for_n[n] = size_of_c
|
| 580 |
+
if nodes is None:
|
| 581 |
+
return size_for_n
|
| 582 |
+
return {n: size_for_n[n] for n in nodes}
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def number_of_cliques(G, nodes=None, cliques=None):
|
| 586 |
+
"""Return the number of maximal cliques each node is part of.
|
| 587 |
+
|
| 588 |
+
Output is a single value or dict depending on `nodes`.
|
| 589 |
+
Optional list of cliques can be input if already computed.
|
| 590 |
+
|
| 591 |
+
Parameters
|
| 592 |
+
----------
|
| 593 |
+
G : NetworkX graph
|
| 594 |
+
An undirected graph.
|
| 595 |
+
|
| 596 |
+
nodes : list or None, optional (default=None)
|
| 597 |
+
A list of nodes to return the number of maximal cliques for.
|
| 598 |
+
If `None`, return the number of maximal cliques for all nodes.
|
| 599 |
+
|
| 600 |
+
cliques : list or None, optional (default=None)
|
| 601 |
+
A precomputed list of maximal cliques to use for the calculation.
|
| 602 |
+
|
| 603 |
+
Returns
|
| 604 |
+
-------
|
| 605 |
+
int or dict
|
| 606 |
+
If `nodes` is a single node, return the number of maximal cliques it is
|
| 607 |
+
part of. If `nodes` is a list, return a dictionary keyed by node to the
|
| 608 |
+
number of maximal cliques it is part of.
|
| 609 |
+
|
| 610 |
+
Raises
|
| 611 |
+
------
|
| 612 |
+
NetworkXNotImplemented
|
| 613 |
+
If `G` is directed.
|
| 614 |
+
|
| 615 |
+
See Also
|
| 616 |
+
--------
|
| 617 |
+
find_cliques
|
| 618 |
+
node_clique_number
|
| 619 |
+
|
| 620 |
+
Examples
|
| 621 |
+
--------
|
| 622 |
+
Compute the number of maximal cliques a node is part of:
|
| 623 |
+
|
| 624 |
+
>>> G = nx.complete_graph(3)
|
| 625 |
+
>>> nx.add_cycle(G, [0, 3, 4])
|
| 626 |
+
>>> nx.number_of_cliques(G, nodes=0)
|
| 627 |
+
2
|
| 628 |
+
>>> nx.number_of_cliques(G, nodes=1)
|
| 629 |
+
1
|
| 630 |
+
|
| 631 |
+
Or, for a list of nodes:
|
| 632 |
+
|
| 633 |
+
>>> nx.number_of_cliques(G, nodes=[0, 1])
|
| 634 |
+
{0: 2, 1: 1}
|
| 635 |
+
|
| 636 |
+
If no explicit `nodes` are provided, all nodes are considered:
|
| 637 |
+
|
| 638 |
+
>>> nx.number_of_cliques(G)
|
| 639 |
+
{0: 2, 1: 1, 2: 1, 3: 1, 4: 1}
|
| 640 |
+
|
| 641 |
+
The list of maximal cliques can also be precomputed:
|
| 642 |
+
|
| 643 |
+
>>> cl = list(nx.find_cliques(G))
|
| 644 |
+
>>> nx.number_of_cliques(G, cliques=cl)
|
| 645 |
+
{0: 2, 1: 1, 2: 1, 3: 1, 4: 1}
|
| 646 |
+
"""
|
| 647 |
+
if cliques is None:
|
| 648 |
+
cliques = find_cliques(G)
|
| 649 |
+
|
| 650 |
+
if nodes is None:
|
| 651 |
+
nodes = list(G.nodes()) # none, get entire graph
|
| 652 |
+
|
| 653 |
+
if not isinstance(nodes, list): # check for a list
|
| 654 |
+
v = nodes
|
| 655 |
+
# assume it is a single value
|
| 656 |
+
numcliq = sum(1 for c in cliques if v in c)
|
| 657 |
+
else:
|
| 658 |
+
numcliq = Counter(chain.from_iterable(cliques))
|
| 659 |
+
numcliq = {v: numcliq[v] for v in nodes} # return a dict
|
| 660 |
+
return numcliq
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
class MaxWeightClique:
|
| 664 |
+
"""A class for the maximum weight clique algorithm.
|
| 665 |
+
|
| 666 |
+
This class is a helper for the `max_weight_clique` function. The class
|
| 667 |
+
should not normally be used directly.
|
| 668 |
+
|
| 669 |
+
Parameters
|
| 670 |
+
----------
|
| 671 |
+
G : NetworkX graph
|
| 672 |
+
The undirected graph for which a maximum weight clique is sought
|
| 673 |
+
weight : string or None, optional (default='weight')
|
| 674 |
+
The node attribute that holds the integer value used as a weight.
|
| 675 |
+
If None, then each node has weight 1.
|
| 676 |
+
|
| 677 |
+
Attributes
|
| 678 |
+
----------
|
| 679 |
+
G : NetworkX graph
|
| 680 |
+
The undirected graph for which a maximum weight clique is sought
|
| 681 |
+
node_weights: dict
|
| 682 |
+
The weight of each node
|
| 683 |
+
incumbent_nodes : list
|
| 684 |
+
The nodes of the incumbent clique (the best clique found so far)
|
| 685 |
+
incumbent_weight: int
|
| 686 |
+
The weight of the incumbent clique
|
| 687 |
+
"""
|
| 688 |
+
|
| 689 |
+
def __init__(self, G, weight):
|
| 690 |
+
self.G = G
|
| 691 |
+
self.incumbent_nodes = []
|
| 692 |
+
self.incumbent_weight = 0
|
| 693 |
+
|
| 694 |
+
if weight is None:
|
| 695 |
+
self.node_weights = {v: 1 for v in G.nodes()}
|
| 696 |
+
else:
|
| 697 |
+
for v in G.nodes():
|
| 698 |
+
if weight not in G.nodes[v]:
|
| 699 |
+
errmsg = f"Node {v!r} does not have the requested weight field."
|
| 700 |
+
raise KeyError(errmsg)
|
| 701 |
+
if not isinstance(G.nodes[v][weight], int):
|
| 702 |
+
errmsg = f"The {weight!r} field of node {v!r} is not an integer."
|
| 703 |
+
raise ValueError(errmsg)
|
| 704 |
+
self.node_weights = {v: G.nodes[v][weight] for v in G.nodes()}
|
| 705 |
+
|
| 706 |
+
def update_incumbent_if_improved(self, C, C_weight):
|
| 707 |
+
"""Update the incumbent if the node set C has greater weight.
|
| 708 |
+
|
| 709 |
+
C is assumed to be a clique.
|
| 710 |
+
"""
|
| 711 |
+
if C_weight > self.incumbent_weight:
|
| 712 |
+
self.incumbent_nodes = C[:]
|
| 713 |
+
self.incumbent_weight = C_weight
|
| 714 |
+
|
| 715 |
+
def greedily_find_independent_set(self, P):
|
| 716 |
+
"""Greedily find an independent set of nodes from a set of
|
| 717 |
+
nodes P."""
|
| 718 |
+
independent_set = []
|
| 719 |
+
P = P[:]
|
| 720 |
+
while P:
|
| 721 |
+
v = P[0]
|
| 722 |
+
independent_set.append(v)
|
| 723 |
+
P = [w for w in P if v != w and not self.G.has_edge(v, w)]
|
| 724 |
+
return independent_set
|
| 725 |
+
|
| 726 |
+
def find_branching_nodes(self, P, target):
|
| 727 |
+
"""Find a set of nodes to branch on."""
|
| 728 |
+
residual_wt = {v: self.node_weights[v] for v in P}
|
| 729 |
+
total_wt = 0
|
| 730 |
+
P = P[:]
|
| 731 |
+
while P:
|
| 732 |
+
independent_set = self.greedily_find_independent_set(P)
|
| 733 |
+
min_wt_in_class = min(residual_wt[v] for v in independent_set)
|
| 734 |
+
total_wt += min_wt_in_class
|
| 735 |
+
if total_wt > target:
|
| 736 |
+
break
|
| 737 |
+
for v in independent_set:
|
| 738 |
+
residual_wt[v] -= min_wt_in_class
|
| 739 |
+
P = [v for v in P if residual_wt[v] != 0]
|
| 740 |
+
return P
|
| 741 |
+
|
| 742 |
+
def expand(self, C, C_weight, P):
|
| 743 |
+
"""Look for the best clique that contains all the nodes in C and zero or
|
| 744 |
+
more of the nodes in P, backtracking if it can be shown that no such
|
| 745 |
+
clique has greater weight than the incumbent.
|
| 746 |
+
"""
|
| 747 |
+
self.update_incumbent_if_improved(C, C_weight)
|
| 748 |
+
branching_nodes = self.find_branching_nodes(P, self.incumbent_weight - C_weight)
|
| 749 |
+
while branching_nodes:
|
| 750 |
+
v = branching_nodes.pop()
|
| 751 |
+
P.remove(v)
|
| 752 |
+
new_C = C + [v]
|
| 753 |
+
new_C_weight = C_weight + self.node_weights[v]
|
| 754 |
+
new_P = [w for w in P if self.G.has_edge(v, w)]
|
| 755 |
+
self.expand(new_C, new_C_weight, new_P)
|
| 756 |
+
|
| 757 |
+
def find_max_weight_clique(self):
|
| 758 |
+
"""Find a maximum weight clique."""
|
| 759 |
+
# Sort nodes in reverse order of degree for speed
|
| 760 |
+
nodes = sorted(self.G.nodes(), key=lambda v: self.G.degree(v), reverse=True)
|
| 761 |
+
nodes = [v for v in nodes if self.node_weights[v] > 0]
|
| 762 |
+
self.expand([], 0, nodes)
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
@not_implemented_for("directed")
|
| 766 |
+
@nx._dispatchable(node_attrs="weight")
|
| 767 |
+
def max_weight_clique(G, weight="weight"):
|
| 768 |
+
"""Find a maximum weight clique in G.
|
| 769 |
+
|
| 770 |
+
A *clique* in a graph is a set of nodes such that every two distinct nodes
|
| 771 |
+
are adjacent. The *weight* of a clique is the sum of the weights of its
|
| 772 |
+
nodes. A *maximum weight clique* of graph G is a clique C in G such that
|
| 773 |
+
no clique in G has weight greater than the weight of C.
|
| 774 |
+
|
| 775 |
+
Parameters
|
| 776 |
+
----------
|
| 777 |
+
G : NetworkX graph
|
| 778 |
+
Undirected graph
|
| 779 |
+
weight : string or None, optional (default='weight')
|
| 780 |
+
The node attribute that holds the integer value used as a weight.
|
| 781 |
+
If None, then each node has weight 1.
|
| 782 |
+
|
| 783 |
+
Returns
|
| 784 |
+
-------
|
| 785 |
+
clique : list
|
| 786 |
+
the nodes of a maximum weight clique
|
| 787 |
+
weight : int
|
| 788 |
+
the weight of a maximum weight clique
|
| 789 |
+
|
| 790 |
+
Notes
|
| 791 |
+
-----
|
| 792 |
+
The implementation is recursive, and therefore it may run into recursion
|
| 793 |
+
depth issues if G contains a clique whose number of nodes is close to the
|
| 794 |
+
recursion depth limit.
|
| 795 |
+
|
| 796 |
+
At each search node, the algorithm greedily constructs a weighted
|
| 797 |
+
independent set cover of part of the graph in order to find a small set of
|
| 798 |
+
nodes on which to branch. The algorithm is very similar to the algorithm
|
| 799 |
+
of Tavares et al. [1]_, other than the fact that the NetworkX version does
|
| 800 |
+
not use bitsets. This style of algorithm for maximum weight clique (and
|
| 801 |
+
maximum weight independent set, which is the same problem but on the
|
| 802 |
+
complement graph) has a decades-long history. See Algorithm B of Warren
|
| 803 |
+
and Hicks [2]_ and the references in that paper.
|
| 804 |
+
|
| 805 |
+
References
|
| 806 |
+
----------
|
| 807 |
+
.. [1] Tavares, W.A., Neto, M.B.C., Rodrigues, C.D., Michelon, P.: Um
|
| 808 |
+
algoritmo de branch and bound para o problema da clique máxima
|
| 809 |
+
ponderada. Proceedings of XLVII SBPO 1 (2015).
|
| 810 |
+
|
| 811 |
+
.. [2] Warren, Jeffrey S, Hicks, Illya V.: Combinatorial Branch-and-Bound
|
| 812 |
+
for the Maximum Weight Independent Set Problem. Technical Report,
|
| 813 |
+
Texas A&M University (2016).
|
| 814 |
+
"""
|
| 815 |
+
|
| 816 |
+
mwc = MaxWeightClique(G, weight)
|
| 817 |
+
mwc.find_max_weight_clique()
|
| 818 |
+
return mwc.incumbent_nodes, mwc.incumbent_weight
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/cluster.py
ADDED
|
@@ -0,0 +1,732 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Algorithms to characterize the number of triangles in a graph."""
|
| 2 |
+
|
| 3 |
+
from collections import Counter
|
| 4 |
+
from itertools import chain, combinations
|
| 5 |
+
|
| 6 |
+
import networkx as nx
|
| 7 |
+
from networkx.utils import not_implemented_for
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
"triangles",
|
| 11 |
+
"all_triangles",
|
| 12 |
+
"average_clustering",
|
| 13 |
+
"clustering",
|
| 14 |
+
"transitivity",
|
| 15 |
+
"square_clustering",
|
| 16 |
+
"generalized_degree",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@not_implemented_for("directed")
|
| 21 |
+
@nx._dispatchable
|
| 22 |
+
def triangles(G, nodes=None):
|
| 23 |
+
"""Compute the number of triangles.
|
| 24 |
+
|
| 25 |
+
Finds the number of triangles that include a node as one vertex.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
G : graph
|
| 30 |
+
A networkx graph
|
| 31 |
+
|
| 32 |
+
nodes : node, iterable of nodes, or None (default=None)
|
| 33 |
+
If a singleton node, return the number of triangles for that node.
|
| 34 |
+
If an iterable, compute the number of triangles for each of those nodes.
|
| 35 |
+
If `None` (the default) compute the number of triangles for all nodes in `G`.
|
| 36 |
+
|
| 37 |
+
Returns
|
| 38 |
+
-------
|
| 39 |
+
out : dict or int
|
| 40 |
+
If `nodes` is a container of nodes, returns number of triangles keyed by node (dict).
|
| 41 |
+
If `nodes` is a specific node, returns number of triangles for the node (int).
|
| 42 |
+
|
| 43 |
+
Examples
|
| 44 |
+
--------
|
| 45 |
+
>>> G = nx.complete_graph(5)
|
| 46 |
+
>>> print(nx.triangles(G, 0))
|
| 47 |
+
6
|
| 48 |
+
>>> print(nx.triangles(G))
|
| 49 |
+
{0: 6, 1: 6, 2: 6, 3: 6, 4: 6}
|
| 50 |
+
>>> print(list(nx.triangles(G, [0, 1]).values()))
|
| 51 |
+
[6, 6]
|
| 52 |
+
|
| 53 |
+
The total number of unique triangles in `G` can be determined by summing
|
| 54 |
+
the number of triangles for each node and dividing by 3 (because a given
|
| 55 |
+
triangle gets counted three times, once for each of its nodes).
|
| 56 |
+
|
| 57 |
+
>>> sum(nx.triangles(G).values()) // 3
|
| 58 |
+
10
|
| 59 |
+
|
| 60 |
+
Notes
|
| 61 |
+
-----
|
| 62 |
+
Self loops are ignored.
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
if nodes is not None:
|
| 66 |
+
# If `nodes` represents a single node, return only its number of triangles
|
| 67 |
+
if nodes in G:
|
| 68 |
+
return next(_triangles_and_degree_iter(G, nodes))[2] // 2
|
| 69 |
+
|
| 70 |
+
# if `nodes` is a container of nodes, then return a
|
| 71 |
+
# dictionary mapping node to number of triangles.
|
| 72 |
+
return {v: t // 2 for v, d, t, _ in _triangles_and_degree_iter(G, nodes)}
|
| 73 |
+
|
| 74 |
+
# if nodes is None, then compute triangles for the complete graph
|
| 75 |
+
|
| 76 |
+
# dict used to avoid visiting the same nodes twice
|
| 77 |
+
# this allows calculating/counting each triangle only once
|
| 78 |
+
later_nbrs = {}
|
| 79 |
+
|
| 80 |
+
# iterate over the nodes in a graph
|
| 81 |
+
for node, neighbors in G.adjacency():
|
| 82 |
+
later_nbrs[node] = {n for n in neighbors if n not in later_nbrs and n != node}
|
| 83 |
+
|
| 84 |
+
# instantiate Counter for each node to include isolated nodes
|
| 85 |
+
# add 1 to the count if a nodes neighbor's neighbor is also a neighbor
|
| 86 |
+
triangle_counts = Counter(dict.fromkeys(G, 0))
|
| 87 |
+
for node1, neighbors in later_nbrs.items():
|
| 88 |
+
for node2 in neighbors:
|
| 89 |
+
third_nodes = neighbors & later_nbrs[node2]
|
| 90 |
+
m = len(third_nodes)
|
| 91 |
+
triangle_counts[node1] += m
|
| 92 |
+
triangle_counts[node2] += m
|
| 93 |
+
triangle_counts.update(third_nodes)
|
| 94 |
+
|
| 95 |
+
return dict(triangle_counts)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@not_implemented_for("multigraph")
|
| 99 |
+
def _triangles_and_degree_iter(G, nodes=None):
|
| 100 |
+
"""Return an iterator of (node, degree, triangles, generalized degree).
|
| 101 |
+
|
| 102 |
+
This double counts triangles so you may want to divide by 2.
|
| 103 |
+
See degree(), triangles() and generalized_degree() for definitions
|
| 104 |
+
and details.
|
| 105 |
+
|
| 106 |
+
"""
|
| 107 |
+
if nodes is None:
|
| 108 |
+
nodes_nbrs = G.adj.items()
|
| 109 |
+
else:
|
| 110 |
+
nodes_nbrs = ((n, G[n]) for n in G.nbunch_iter(nodes))
|
| 111 |
+
|
| 112 |
+
for v, v_nbrs in nodes_nbrs:
|
| 113 |
+
vs = set(v_nbrs) - {v}
|
| 114 |
+
gen_degree = Counter(len(vs & (set(G[w]) - {w})) for w in vs)
|
| 115 |
+
ntriangles = sum(k * val for k, val in gen_degree.items())
|
| 116 |
+
yield (v, len(vs), ntriangles, gen_degree)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@not_implemented_for("multigraph")
|
| 120 |
+
def _weighted_triangles_and_degree_iter(G, nodes=None, weight="weight"):
|
| 121 |
+
"""Return an iterator of (node, degree, weighted_triangles).
|
| 122 |
+
|
| 123 |
+
Used for weighted clustering.
|
| 124 |
+
Note: this returns the geometric average weight of edges in the triangle.
|
| 125 |
+
Also, each triangle is counted twice (each direction).
|
| 126 |
+
So you may want to divide by 2.
|
| 127 |
+
|
| 128 |
+
"""
|
| 129 |
+
import numpy as np
|
| 130 |
+
|
| 131 |
+
if weight is None or G.number_of_edges() == 0:
|
| 132 |
+
max_weight = 1
|
| 133 |
+
else:
|
| 134 |
+
max_weight = max(d.get(weight, 1) for u, v, d in G.edges(data=True))
|
| 135 |
+
if nodes is None:
|
| 136 |
+
nodes_nbrs = G.adj.items()
|
| 137 |
+
else:
|
| 138 |
+
nodes_nbrs = ((n, G[n]) for n in G.nbunch_iter(nodes))
|
| 139 |
+
|
| 140 |
+
def wt(u, v):
|
| 141 |
+
return G[u][v].get(weight, 1) / max_weight
|
| 142 |
+
|
| 143 |
+
for i, nbrs in nodes_nbrs:
|
| 144 |
+
inbrs = set(nbrs) - {i}
|
| 145 |
+
weighted_triangles = 0
|
| 146 |
+
seen = set()
|
| 147 |
+
for j in inbrs:
|
| 148 |
+
seen.add(j)
|
| 149 |
+
# This avoids counting twice -- we double at the end.
|
| 150 |
+
jnbrs = set(G[j]) - seen
|
| 151 |
+
# Only compute the edge weight once, before the inner inner
|
| 152 |
+
# loop.
|
| 153 |
+
wij = wt(i, j)
|
| 154 |
+
weighted_triangles += np.cbrt(
|
| 155 |
+
[(wij * wt(j, k) * wt(k, i)) for k in inbrs & jnbrs]
|
| 156 |
+
).sum()
|
| 157 |
+
yield (i, len(inbrs), 2 * float(weighted_triangles))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@not_implemented_for("multigraph")
|
| 161 |
+
def _directed_triangles_and_degree_iter(G, nodes=None):
|
| 162 |
+
"""Return an iterator of
|
| 163 |
+
(node, total_degree, reciprocal_degree, directed_triangles).
|
| 164 |
+
|
| 165 |
+
Used for directed clustering.
|
| 166 |
+
Note that unlike `_triangles_and_degree_iter()`, this function counts
|
| 167 |
+
directed triangles so does not count triangles twice.
|
| 168 |
+
|
| 169 |
+
"""
|
| 170 |
+
nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))
|
| 171 |
+
|
| 172 |
+
for i, preds, succs in nodes_nbrs:
|
| 173 |
+
ipreds = set(preds) - {i}
|
| 174 |
+
isuccs = set(succs) - {i}
|
| 175 |
+
|
| 176 |
+
directed_triangles = 0
|
| 177 |
+
for j in chain(ipreds, isuccs):
|
| 178 |
+
jpreds = set(G._pred[j]) - {j}
|
| 179 |
+
jsuccs = set(G._succ[j]) - {j}
|
| 180 |
+
directed_triangles += sum(
|
| 181 |
+
1
|
| 182 |
+
for k in chain(
|
| 183 |
+
(ipreds & jpreds),
|
| 184 |
+
(ipreds & jsuccs),
|
| 185 |
+
(isuccs & jpreds),
|
| 186 |
+
(isuccs & jsuccs),
|
| 187 |
+
)
|
| 188 |
+
)
|
| 189 |
+
dtotal = len(ipreds) + len(isuccs)
|
| 190 |
+
dbidirectional = len(ipreds & isuccs)
|
| 191 |
+
yield (i, dtotal, dbidirectional, directed_triangles)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@not_implemented_for("multigraph")
|
| 195 |
+
def _directed_weighted_triangles_and_degree_iter(G, nodes=None, weight="weight"):
|
| 196 |
+
"""Return an iterator of
|
| 197 |
+
(node, total_degree, reciprocal_degree, directed_weighted_triangles).
|
| 198 |
+
|
| 199 |
+
Used for directed weighted clustering.
|
| 200 |
+
Note that unlike `_weighted_triangles_and_degree_iter()`, this function counts
|
| 201 |
+
directed triangles so does not count triangles twice.
|
| 202 |
+
|
| 203 |
+
"""
|
| 204 |
+
import numpy as np
|
| 205 |
+
|
| 206 |
+
if weight is None or G.number_of_edges() == 0:
|
| 207 |
+
max_weight = 1
|
| 208 |
+
else:
|
| 209 |
+
max_weight = max(d.get(weight, 1) for u, v, d in G.edges(data=True))
|
| 210 |
+
|
| 211 |
+
nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))
|
| 212 |
+
|
| 213 |
+
def wt(u, v):
|
| 214 |
+
return G[u][v].get(weight, 1) / max_weight
|
| 215 |
+
|
| 216 |
+
for i, preds, succs in nodes_nbrs:
|
| 217 |
+
ipreds = set(preds) - {i}
|
| 218 |
+
isuccs = set(succs) - {i}
|
| 219 |
+
|
| 220 |
+
directed_triangles = 0
|
| 221 |
+
for j in ipreds:
|
| 222 |
+
jpreds = set(G._pred[j]) - {j}
|
| 223 |
+
jsuccs = set(G._succ[j]) - {j}
|
| 224 |
+
directed_triangles += np.cbrt(
|
| 225 |
+
[(wt(j, i) * wt(k, i) * wt(k, j)) for k in ipreds & jpreds]
|
| 226 |
+
).sum()
|
| 227 |
+
directed_triangles += np.cbrt(
|
| 228 |
+
[(wt(j, i) * wt(k, i) * wt(j, k)) for k in ipreds & jsuccs]
|
| 229 |
+
).sum()
|
| 230 |
+
directed_triangles += np.cbrt(
|
| 231 |
+
[(wt(j, i) * wt(i, k) * wt(k, j)) for k in isuccs & jpreds]
|
| 232 |
+
).sum()
|
| 233 |
+
directed_triangles += np.cbrt(
|
| 234 |
+
[(wt(j, i) * wt(i, k) * wt(j, k)) for k in isuccs & jsuccs]
|
| 235 |
+
).sum()
|
| 236 |
+
|
| 237 |
+
for j in isuccs:
|
| 238 |
+
jpreds = set(G._pred[j]) - {j}
|
| 239 |
+
jsuccs = set(G._succ[j]) - {j}
|
| 240 |
+
directed_triangles += np.cbrt(
|
| 241 |
+
[(wt(i, j) * wt(k, i) * wt(k, j)) for k in ipreds & jpreds]
|
| 242 |
+
).sum()
|
| 243 |
+
directed_triangles += np.cbrt(
|
| 244 |
+
[(wt(i, j) * wt(k, i) * wt(j, k)) for k in ipreds & jsuccs]
|
| 245 |
+
).sum()
|
| 246 |
+
directed_triangles += np.cbrt(
|
| 247 |
+
[(wt(i, j) * wt(i, k) * wt(k, j)) for k in isuccs & jpreds]
|
| 248 |
+
).sum()
|
| 249 |
+
directed_triangles += np.cbrt(
|
| 250 |
+
[(wt(i, j) * wt(i, k) * wt(j, k)) for k in isuccs & jsuccs]
|
| 251 |
+
).sum()
|
| 252 |
+
|
| 253 |
+
dtotal = len(ipreds) + len(isuccs)
|
| 254 |
+
dbidirectional = len(ipreds & isuccs)
|
| 255 |
+
yield (i, dtotal, dbidirectional, float(directed_triangles))
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@not_implemented_for("directed")
|
| 259 |
+
@nx._dispatchable
|
| 260 |
+
def all_triangles(G, nbunch=None):
|
| 261 |
+
"""
|
| 262 |
+
Yields all unique triangles in an undirected graph.
|
| 263 |
+
|
| 264 |
+
A triangle is a set of three distinct nodes where each node is connected to
|
| 265 |
+
the other two.
|
| 266 |
+
|
| 267 |
+
Parameters
|
| 268 |
+
----------
|
| 269 |
+
G : NetworkX graph
|
| 270 |
+
An undirected graph.
|
| 271 |
+
|
| 272 |
+
nbunch : node, iterable of nodes, or None (default=None)
|
| 273 |
+
If a node or iterable of nodes, only triangles involving at least one
|
| 274 |
+
node in `nbunch` are yielded.
|
| 275 |
+
If ``None``, yields all unique triangles in the graph.
|
| 276 |
+
|
| 277 |
+
Yields
|
| 278 |
+
------
|
| 279 |
+
tuple
|
| 280 |
+
A tuple of three nodes forming a triangle ``(u, v, w)``.
|
| 281 |
+
|
| 282 |
+
Examples
|
| 283 |
+
--------
|
| 284 |
+
>>> G = nx.complete_graph(4)
|
| 285 |
+
>>> sorted([sorted(t) for t in all_triangles(G)])
|
| 286 |
+
[[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]
|
| 287 |
+
|
| 288 |
+
Notes
|
| 289 |
+
-----
|
| 290 |
+
This algorithm ensures each triangle is yielded once using an internal node ordering.
|
| 291 |
+
In multigraphs, triangles are identified by their unique set of nodes,
|
| 292 |
+
ignoring multiple edges between the same nodes. Self-loops are ignored.
|
| 293 |
+
Runs in ``O(m * d)`` time in the worst case, where ``m`` the number of edges
|
| 294 |
+
and ``d`` the maximum degree.
|
| 295 |
+
|
| 296 |
+
See Also
|
| 297 |
+
--------
|
| 298 |
+
:func:`~networkx.algorithms.triads.all_triads` : related function for directed graphs
|
| 299 |
+
"""
|
| 300 |
+
if nbunch is None:
|
| 301 |
+
nbunch = relevant_nodes = G
|
| 302 |
+
else:
|
| 303 |
+
nbunch = dict.fromkeys(G.nbunch_iter(nbunch))
|
| 304 |
+
relevant_nodes = chain(
|
| 305 |
+
nbunch,
|
| 306 |
+
(nbr for node in nbunch for nbr in G.neighbors(node) if nbr not in nbunch),
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
node_to_id = {node: i for i, node in enumerate(relevant_nodes)}
|
| 310 |
+
|
| 311 |
+
for u in nbunch:
|
| 312 |
+
u_id = node_to_id[u]
|
| 313 |
+
u_nbrs = G._adj[u].keys()
|
| 314 |
+
for v in u_nbrs:
|
| 315 |
+
v_id = node_to_id.get(v, -1)
|
| 316 |
+
if v_id <= u_id:
|
| 317 |
+
continue
|
| 318 |
+
v_nbrs = G._adj[v].keys()
|
| 319 |
+
for w in v_nbrs & u_nbrs:
|
| 320 |
+
if node_to_id.get(w, -1) > v_id:
|
| 321 |
+
yield u, v, w
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 325 |
+
def average_clustering(G, nodes=None, weight=None, count_zeros=True):
|
| 326 |
+
r"""Compute the average clustering coefficient for the graph G.
|
| 327 |
+
|
| 328 |
+
The clustering coefficient for the graph is the average,
|
| 329 |
+
|
| 330 |
+
.. math::
|
| 331 |
+
|
| 332 |
+
C = \frac{1}{n}\sum_{v \in G} c_v,
|
| 333 |
+
|
| 334 |
+
where :math:`n` is the number of nodes in `G`.
|
| 335 |
+
|
| 336 |
+
Parameters
|
| 337 |
+
----------
|
| 338 |
+
G : graph
|
| 339 |
+
|
| 340 |
+
nodes : container of nodes, optional (default=all nodes in G)
|
| 341 |
+
Compute average clustering for nodes in this container.
|
| 342 |
+
|
| 343 |
+
weight : string or None, optional (default=None)
|
| 344 |
+
The edge attribute that holds the numerical value used as a weight.
|
| 345 |
+
If None, then each edge has weight 1.
|
| 346 |
+
|
| 347 |
+
count_zeros : bool
|
| 348 |
+
If False include only the nodes with nonzero clustering in the average.
|
| 349 |
+
|
| 350 |
+
Returns
|
| 351 |
+
-------
|
| 352 |
+
avg : float
|
| 353 |
+
Average clustering
|
| 354 |
+
|
| 355 |
+
Examples
|
| 356 |
+
--------
|
| 357 |
+
>>> G = nx.complete_graph(5)
|
| 358 |
+
>>> print(nx.average_clustering(G))
|
| 359 |
+
1.0
|
| 360 |
+
|
| 361 |
+
Notes
|
| 362 |
+
-----
|
| 363 |
+
This is a space saving routine; it might be faster
|
| 364 |
+
to use the clustering function to get a list and then take the average.
|
| 365 |
+
|
| 366 |
+
Self loops are ignored.
|
| 367 |
+
|
| 368 |
+
References
|
| 369 |
+
----------
|
| 370 |
+
.. [1] Generalizations of the clustering coefficient to weighted
|
| 371 |
+
complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
|
| 372 |
+
K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
|
| 373 |
+
http://jponnela.com/web_documents/a9.pdf
|
| 374 |
+
.. [2] Marcus Kaiser, Mean clustering coefficients: the role of isolated
|
| 375 |
+
nodes and leafs on clustering measures for small-world networks.
|
| 376 |
+
https://arxiv.org/abs/0802.2512
|
| 377 |
+
"""
|
| 378 |
+
c = clustering(G, nodes, weight=weight).values()
|
| 379 |
+
if not count_zeros:
|
| 380 |
+
c = [v for v in c if abs(v) > 0]
|
| 381 |
+
return sum(c) / len(c)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 385 |
+
def clustering(G, nodes=None, weight=None):
|
| 386 |
+
r"""Compute the clustering coefficient for nodes.
|
| 387 |
+
|
| 388 |
+
For unweighted graphs, the clustering of a node :math:`u`
|
| 389 |
+
is the fraction of possible triangles through that node that exist,
|
| 390 |
+
|
| 391 |
+
.. math::
|
| 392 |
+
|
| 393 |
+
c_u = \frac{2 T(u)}{deg(u)(deg(u)-1)},
|
| 394 |
+
|
| 395 |
+
where :math:`T(u)` is the number of triangles through node :math:`u` and
|
| 396 |
+
:math:`deg(u)` is the degree of :math:`u`.
|
| 397 |
+
|
| 398 |
+
For weighted graphs, there are several ways to define clustering [1]_.
|
| 399 |
+
the one used here is defined
|
| 400 |
+
as the geometric average of the subgraph edge weights [2]_,
|
| 401 |
+
|
| 402 |
+
.. math::
|
| 403 |
+
|
| 404 |
+
c_u = \frac{1}{deg(u)(deg(u)-1))}
|
| 405 |
+
\sum_{vw} (\hat{w}_{uv} \hat{w}_{uw} \hat{w}_{vw})^{1/3}.
|
| 406 |
+
|
| 407 |
+
The edge weights :math:`\hat{w}_{uv}` are normalized by the maximum weight
|
| 408 |
+
in the network :math:`\hat{w}_{uv} = w_{uv}/\max(w)`.
|
| 409 |
+
|
| 410 |
+
The value of :math:`c_u` is assigned to 0 if :math:`deg(u) < 2`.
|
| 411 |
+
|
| 412 |
+
Additionally, this weighted definition has been generalized to support negative edge weights [3]_.
|
| 413 |
+
|
| 414 |
+
For directed graphs, the clustering is similarly defined as the fraction
|
| 415 |
+
of all possible directed triangles or geometric average of the subgraph
|
| 416 |
+
edge weights for unweighted and weighted directed graph respectively [4]_.
|
| 417 |
+
|
| 418 |
+
.. math::
|
| 419 |
+
|
| 420 |
+
c_u = \frac{T(u)}{2(deg^{tot}(u)(deg^{tot}(u)-1) - 2deg^{\leftrightarrow}(u))},
|
| 421 |
+
|
| 422 |
+
where :math:`T(u)` is the number of directed triangles through node
|
| 423 |
+
:math:`u`, :math:`deg^{tot}(u)` is the sum of in degree and out degree of
|
| 424 |
+
:math:`u` and :math:`deg^{\leftrightarrow}(u)` is the reciprocal degree of
|
| 425 |
+
:math:`u`.
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
Parameters
|
| 429 |
+
----------
|
| 430 |
+
G : graph
|
| 431 |
+
|
| 432 |
+
nodes : node, iterable of nodes, or None (default=None)
|
| 433 |
+
If a singleton node, return the number of triangles for that node.
|
| 434 |
+
If an iterable, compute the number of triangles for each of those nodes.
|
| 435 |
+
If `None` (the default) compute the number of triangles for all nodes in `G`.
|
| 436 |
+
|
| 437 |
+
weight : string or None, optional (default=None)
|
| 438 |
+
The edge attribute that holds the numerical value used as a weight.
|
| 439 |
+
If None, then each edge has weight 1.
|
| 440 |
+
|
| 441 |
+
Returns
|
| 442 |
+
-------
|
| 443 |
+
out : float, or dictionary
|
| 444 |
+
Clustering coefficient at specified nodes
|
| 445 |
+
|
| 446 |
+
Examples
|
| 447 |
+
--------
|
| 448 |
+
>>> G = nx.complete_graph(5)
|
| 449 |
+
>>> print(nx.clustering(G, 0))
|
| 450 |
+
1.0
|
| 451 |
+
>>> print(nx.clustering(G))
|
| 452 |
+
{0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
|
| 453 |
+
|
| 454 |
+
Notes
|
| 455 |
+
-----
|
| 456 |
+
Self loops are ignored.
|
| 457 |
+
|
| 458 |
+
References
|
| 459 |
+
----------
|
| 460 |
+
.. [1] Generalizations of the clustering coefficient to weighted
|
| 461 |
+
complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
|
| 462 |
+
K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
|
| 463 |
+
http://jponnela.com/web_documents/a9.pdf
|
| 464 |
+
.. [2] Intensity and coherence of motifs in weighted complex
|
| 465 |
+
networks by J. P. Onnela, J. Saramäki, J. Kertész, and K. Kaski,
|
| 466 |
+
Physical Review E, 71(6), 065103 (2005).
|
| 467 |
+
.. [3] Generalization of Clustering Coefficients to Signed Correlation Networks
|
| 468 |
+
by G. Costantini and M. Perugini, PloS one, 9(2), e88669 (2014).
|
| 469 |
+
.. [4] Clustering in complex directed networks by G. Fagiolo,
|
| 470 |
+
Physical Review E, 76(2), 026107 (2007).
|
| 471 |
+
"""
|
| 472 |
+
if G.is_directed():
|
| 473 |
+
if weight is not None:
|
| 474 |
+
td_iter = _directed_weighted_triangles_and_degree_iter(G, nodes, weight)
|
| 475 |
+
clusterc = {
|
| 476 |
+
v: 0 if t == 0 else t / ((dt * (dt - 1) - 2 * db) * 2)
|
| 477 |
+
for v, dt, db, t in td_iter
|
| 478 |
+
}
|
| 479 |
+
else:
|
| 480 |
+
td_iter = _directed_triangles_and_degree_iter(G, nodes)
|
| 481 |
+
clusterc = {
|
| 482 |
+
v: 0 if t == 0 else t / ((dt * (dt - 1) - 2 * db) * 2)
|
| 483 |
+
for v, dt, db, t in td_iter
|
| 484 |
+
}
|
| 485 |
+
else:
|
| 486 |
+
# The formula 2*T/(d*(d-1)) from docs is t/(d*(d-1)) here b/c t==2*T
|
| 487 |
+
if weight is not None:
|
| 488 |
+
td_iter = _weighted_triangles_and_degree_iter(G, nodes, weight)
|
| 489 |
+
clusterc = {v: 0 if t == 0 else t / (d * (d - 1)) for v, d, t in td_iter}
|
| 490 |
+
else:
|
| 491 |
+
td_iter = _triangles_and_degree_iter(G, nodes)
|
| 492 |
+
clusterc = {v: 0 if t == 0 else t / (d * (d - 1)) for v, d, t, _ in td_iter}
|
| 493 |
+
if nodes in G:
|
| 494 |
+
# Return the value of the sole entry in the dictionary.
|
| 495 |
+
return clusterc[nodes]
|
| 496 |
+
return clusterc
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
@nx._dispatchable
|
| 500 |
+
def transitivity(G):
|
| 501 |
+
r"""Compute graph transitivity, the fraction of all possible triangles
|
| 502 |
+
present in G.
|
| 503 |
+
|
| 504 |
+
Possible triangles are identified by the number of "triads"
|
| 505 |
+
(two edges with a shared vertex).
|
| 506 |
+
|
| 507 |
+
The transitivity is
|
| 508 |
+
|
| 509 |
+
.. math::
|
| 510 |
+
|
| 511 |
+
T = 3\frac{\#triangles}{\#triads}.
|
| 512 |
+
|
| 513 |
+
Parameters
|
| 514 |
+
----------
|
| 515 |
+
G : graph
|
| 516 |
+
|
| 517 |
+
Returns
|
| 518 |
+
-------
|
| 519 |
+
out : float
|
| 520 |
+
Transitivity
|
| 521 |
+
|
| 522 |
+
Notes
|
| 523 |
+
-----
|
| 524 |
+
Self loops are ignored.
|
| 525 |
+
|
| 526 |
+
Examples
|
| 527 |
+
--------
|
| 528 |
+
>>> G = nx.complete_graph(5)
|
| 529 |
+
>>> print(nx.transitivity(G))
|
| 530 |
+
1.0
|
| 531 |
+
"""
|
| 532 |
+
triangles_contri = [
|
| 533 |
+
(t, d * (d - 1)) for v, d, t, _ in _triangles_and_degree_iter(G)
|
| 534 |
+
]
|
| 535 |
+
# If the graph is empty
|
| 536 |
+
if len(triangles_contri) == 0:
|
| 537 |
+
return 0
|
| 538 |
+
triangles, contri = map(sum, zip(*triangles_contri))
|
| 539 |
+
return 0 if triangles == 0 else triangles / contri
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
@nx._dispatchable
|
| 543 |
+
def square_clustering(G, nodes=None):
|
| 544 |
+
r"""Compute the squares clustering coefficient for nodes.
|
| 545 |
+
|
| 546 |
+
For each node return the fraction of possible squares that exist at
|
| 547 |
+
the node [1]_
|
| 548 |
+
|
| 549 |
+
.. math::
|
| 550 |
+
C_4(v) = \frac{ \sum_{u=1}^{k_v}
|
| 551 |
+
\sum_{w=u+1}^{k_v} q_v(u,w) }{ \sum_{u=1}^{k_v}
|
| 552 |
+
\sum_{w=u+1}^{k_v} [a_v(u,w) + q_v(u,w)]},
|
| 553 |
+
|
| 554 |
+
where :math:`q_v(u,w)` are the number of common neighbors of :math:`u` and
|
| 555 |
+
:math:`w` other than :math:`v` (ie squares), and :math:`a_v(u,w) = (k_u -
|
| 556 |
+
(1+q_v(u,w)+\theta_{uv})) + (k_w - (1+q_v(u,w)+\theta_{uw}))`, where
|
| 557 |
+
:math:`\theta_{uw} = 1` if :math:`u` and :math:`w` are connected and 0
|
| 558 |
+
otherwise. [2]_
|
| 559 |
+
|
| 560 |
+
Parameters
|
| 561 |
+
----------
|
| 562 |
+
G : graph
|
| 563 |
+
|
| 564 |
+
nodes : container of nodes, optional (default=all nodes in G)
|
| 565 |
+
Compute clustering for nodes in this container.
|
| 566 |
+
|
| 567 |
+
Returns
|
| 568 |
+
-------
|
| 569 |
+
c4 : dictionary
|
| 570 |
+
A dictionary keyed by node with the square clustering coefficient value.
|
| 571 |
+
|
| 572 |
+
Examples
|
| 573 |
+
--------
|
| 574 |
+
>>> G = nx.complete_graph(5)
|
| 575 |
+
>>> print(nx.square_clustering(G, 0))
|
| 576 |
+
1.0
|
| 577 |
+
>>> print(nx.square_clustering(G))
|
| 578 |
+
{0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
|
| 579 |
+
|
| 580 |
+
Notes
|
| 581 |
+
-----
|
| 582 |
+
Self loops are ignored.
|
| 583 |
+
|
| 584 |
+
While :math:`C_3(v)` (triangle clustering) gives the probability that
|
| 585 |
+
two neighbors of node v are connected with each other, :math:`C_4(v)` is
|
| 586 |
+
the probability that two neighbors of node v share a common
|
| 587 |
+
neighbor different from v. This algorithm can be applied to both
|
| 588 |
+
bipartite and unipartite networks.
|
| 589 |
+
|
| 590 |
+
References
|
| 591 |
+
----------
|
| 592 |
+
.. [1] Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005
|
| 593 |
+
Cycles and clustering in bipartite networks.
|
| 594 |
+
Physical Review E (72) 056127.
|
| 595 |
+
.. [2] Zhang, Peng et al. Clustering Coefficient and Community Structure of
|
| 596 |
+
Bipartite Networks. Physica A: Statistical Mechanics and its Applications 387.27 (2008): 6869–6875.
|
| 597 |
+
https://arxiv.org/abs/0710.0117v1
|
| 598 |
+
"""
|
| 599 |
+
if nodes is None:
|
| 600 |
+
node_iter = G
|
| 601 |
+
else:
|
| 602 |
+
node_iter = G.nbunch_iter(nodes)
|
| 603 |
+
clustering = {}
|
| 604 |
+
_G_adj = G._adj
|
| 605 |
+
|
| 606 |
+
class GAdj(dict):
|
| 607 |
+
"""Calculate (and cache) node neighbor sets excluding self-loops."""
|
| 608 |
+
|
| 609 |
+
def __missing__(self, v):
|
| 610 |
+
v_neighbors = self[v] = set(_G_adj[v])
|
| 611 |
+
v_neighbors.discard(v) # Ignore self-loops
|
| 612 |
+
return v_neighbors
|
| 613 |
+
|
| 614 |
+
G_adj = GAdj() # Values are sets of neighbors (no self-loops)
|
| 615 |
+
|
| 616 |
+
for v in node_iter:
|
| 617 |
+
v_neighbors = G_adj[v]
|
| 618 |
+
v_degrees_m1 = len(v_neighbors) - 1 # degrees[v] - 1 (used below)
|
| 619 |
+
if v_degrees_m1 <= 0:
|
| 620 |
+
# Can't form a square without at least two neighbors
|
| 621 |
+
clustering[v] = 0
|
| 622 |
+
continue
|
| 623 |
+
|
| 624 |
+
# Count squares with nodes u-v-w-x from the current node v.
|
| 625 |
+
# Terms of the denominator: potential = uw_degrees - uw_count - triangles - squares
|
| 626 |
+
# uw_degrees: degrees[u] + degrees[w] for each u-w combo
|
| 627 |
+
uw_degrees = 0
|
| 628 |
+
# uw_count: 1 for each u and 1 for each w for all combos (degrees * (degrees - 1))
|
| 629 |
+
uw_count = len(v_neighbors) * v_degrees_m1
|
| 630 |
+
# triangles: 1 for each edge where u-w or w-u are connected (i.e. triangles)
|
| 631 |
+
triangles = 0
|
| 632 |
+
# squares: the number of squares (also the numerator)
|
| 633 |
+
squares = 0
|
| 634 |
+
|
| 635 |
+
# Iterate over all neighbors
|
| 636 |
+
for u in v_neighbors:
|
| 637 |
+
u_neighbors = G_adj[u]
|
| 638 |
+
uw_degrees += len(u_neighbors) * v_degrees_m1
|
| 639 |
+
# P2 from https://arxiv.org/abs/2007.11111
|
| 640 |
+
p2 = len(u_neighbors & v_neighbors)
|
| 641 |
+
# triangles is C_3, sigma_4 from https://arxiv.org/abs/2007.11111
|
| 642 |
+
# This double-counts triangles compared to `triangles` function
|
| 643 |
+
triangles += p2
|
| 644 |
+
# squares is C_4, sigma_12 from https://arxiv.org/abs/2007.11111
|
| 645 |
+
# Include this term, b/c a neighbor u can also be a neighbor of neighbor x
|
| 646 |
+
squares += p2 * (p2 - 1) # Will divide by 2 later
|
| 647 |
+
|
| 648 |
+
# And iterate over all neighbors of neighbors.
|
| 649 |
+
# These nodes x may be the corners opposite v in squares u-v-w-x.
|
| 650 |
+
two_hop_neighbors = set.union(*(G_adj[u] for u in v_neighbors))
|
| 651 |
+
two_hop_neighbors -= v_neighbors # Neighbors already counted above
|
| 652 |
+
two_hop_neighbors.discard(v)
|
| 653 |
+
for x in two_hop_neighbors:
|
| 654 |
+
p2 = len(v_neighbors & G_adj[x])
|
| 655 |
+
squares += p2 * (p2 - 1) # Will divide by 2 later
|
| 656 |
+
|
| 657 |
+
squares //= 2
|
| 658 |
+
potential = uw_degrees - uw_count - triangles - squares
|
| 659 |
+
if potential > 0:
|
| 660 |
+
clustering[v] = squares / potential
|
| 661 |
+
else:
|
| 662 |
+
clustering[v] = 0
|
| 663 |
+
if nodes in G:
|
| 664 |
+
# Return the value of the sole entry in the dictionary.
|
| 665 |
+
return clustering[nodes]
|
| 666 |
+
return clustering
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
@not_implemented_for("directed")
|
| 670 |
+
@nx._dispatchable
|
| 671 |
+
def generalized_degree(G, nodes=None):
|
| 672 |
+
r"""Compute the generalized degree for nodes.
|
| 673 |
+
|
| 674 |
+
For each node, the generalized degree shows how many edges of given
|
| 675 |
+
triangle multiplicity the node is connected to. The triangle multiplicity
|
| 676 |
+
of an edge is the number of triangles an edge participates in. The
|
| 677 |
+
generalized degree of node :math:`i` can be written as a vector
|
| 678 |
+
:math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc, k_i^{(N-2)})` where
|
| 679 |
+
:math:`k_i^{(j)}` is the number of edges attached to node :math:`i` that
|
| 680 |
+
participate in :math:`j` triangles.
|
| 681 |
+
|
| 682 |
+
Parameters
|
| 683 |
+
----------
|
| 684 |
+
G : graph
|
| 685 |
+
|
| 686 |
+
nodes : container of nodes, optional (default=all nodes in G)
|
| 687 |
+
Compute the generalized degree for nodes in this container.
|
| 688 |
+
|
| 689 |
+
Returns
|
| 690 |
+
-------
|
| 691 |
+
out : Counter, or dictionary of Counters
|
| 692 |
+
Generalized degree of specified nodes. The Counter is keyed by edge
|
| 693 |
+
triangle multiplicity.
|
| 694 |
+
|
| 695 |
+
Examples
|
| 696 |
+
--------
|
| 697 |
+
>>> G = nx.complete_graph(5)
|
| 698 |
+
>>> print(nx.generalized_degree(G, 0))
|
| 699 |
+
Counter({3: 4})
|
| 700 |
+
>>> print(nx.generalized_degree(G))
|
| 701 |
+
{0: Counter({3: 4}), 1: Counter({3: 4}), 2: Counter({3: 4}), 3: Counter({3: 4}), 4: Counter({3: 4})}
|
| 702 |
+
|
| 703 |
+
To recover the number of triangles attached to a node:
|
| 704 |
+
|
| 705 |
+
>>> k1 = nx.generalized_degree(G, 0)
|
| 706 |
+
>>> sum([k * v for k, v in k1.items()]) / 2 == nx.triangles(G, 0)
|
| 707 |
+
True
|
| 708 |
+
|
| 709 |
+
Notes
|
| 710 |
+
-----
|
| 711 |
+
Self loops are ignored.
|
| 712 |
+
|
| 713 |
+
In a network of N nodes, the highest triangle multiplicity an edge can have
|
| 714 |
+
is N-2.
|
| 715 |
+
|
| 716 |
+
The return value does not include a `zero` entry if no edges of a
|
| 717 |
+
particular triangle multiplicity are present.
|
| 718 |
+
|
| 719 |
+
The number of triangles node :math:`i` is attached to can be recovered from
|
| 720 |
+
the generalized degree :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc,
|
| 721 |
+
k_i^{(N-2)})` by :math:`(k_i^{(1)}+2k_i^{(2)}+\dotsc +(N-2)k_i^{(N-2)})/2`.
|
| 722 |
+
|
| 723 |
+
References
|
| 724 |
+
----------
|
| 725 |
+
.. [1] Networks with arbitrary edge multiplicities by V. Zlatić,
|
| 726 |
+
D. Garlaschelli and G. Caldarelli, EPL (Europhysics Letters),
|
| 727 |
+
Volume 97, Number 2 (2012).
|
| 728 |
+
https://iopscience.iop.org/article/10.1209/0295-5075/97/28005
|
| 729 |
+
"""
|
| 730 |
+
if nodes in G:
|
| 731 |
+
return next(_triangles_and_degree_iter(G, nodes))[3]
|
| 732 |
+
return {v: gd for v, d, t, gd in _triangles_and_degree_iter(G, nodes)}
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/communicability_alg.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Communicability.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = ["communicability", "communicability_exp"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@not_implemented_for("directed")
|
| 12 |
+
@not_implemented_for("multigraph")
|
| 13 |
+
@nx._dispatchable
|
| 14 |
+
def communicability(G):
|
| 15 |
+
r"""Returns communicability between all pairs of nodes in G.
|
| 16 |
+
|
| 17 |
+
The communicability between pairs of nodes in G is the sum of
|
| 18 |
+
walks of different lengths starting at node u and ending at node v.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
G: graph
|
| 23 |
+
|
| 24 |
+
Returns
|
| 25 |
+
-------
|
| 26 |
+
comm: dictionary of dictionaries
|
| 27 |
+
Dictionary of dictionaries keyed by nodes with communicability
|
| 28 |
+
as the value.
|
| 29 |
+
|
| 30 |
+
Raises
|
| 31 |
+
------
|
| 32 |
+
NetworkXError
|
| 33 |
+
If the graph is not undirected and simple.
|
| 34 |
+
|
| 35 |
+
See Also
|
| 36 |
+
--------
|
| 37 |
+
communicability_exp:
|
| 38 |
+
Communicability between all pairs of nodes in G using spectral
|
| 39 |
+
decomposition.
|
| 40 |
+
communicability_betweenness_centrality:
|
| 41 |
+
Communicability betweenness centrality for each node in G.
|
| 42 |
+
|
| 43 |
+
Notes
|
| 44 |
+
-----
|
| 45 |
+
This algorithm uses a spectral decomposition of the adjacency matrix.
|
| 46 |
+
Let G=(V,E) be a simple undirected graph. Using the connection between
|
| 47 |
+
the powers of the adjacency matrix and the number of walks in the graph,
|
| 48 |
+
the communicability between nodes `u` and `v` based on the graph spectrum
|
| 49 |
+
is [1]_
|
| 50 |
+
|
| 51 |
+
.. math::
|
| 52 |
+
C(u,v)=\sum_{j=1}^{n}\phi_{j}(u)\phi_{j}(v)e^{\lambda_{j}},
|
| 53 |
+
|
| 54 |
+
where `\phi_{j}(u)` is the `u\rm{th}` element of the `j\rm{th}` orthonormal
|
| 55 |
+
eigenvector of the adjacency matrix associated with the eigenvalue
|
| 56 |
+
`\lambda_{j}`.
|
| 57 |
+
|
| 58 |
+
References
|
| 59 |
+
----------
|
| 60 |
+
.. [1] Ernesto Estrada, Naomichi Hatano,
|
| 61 |
+
"Communicability in complex networks",
|
| 62 |
+
Phys. Rev. E 77, 036111 (2008).
|
| 63 |
+
https://arxiv.org/abs/0707.0756
|
| 64 |
+
|
| 65 |
+
Examples
|
| 66 |
+
--------
|
| 67 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
|
| 68 |
+
>>> c = nx.communicability(G)
|
| 69 |
+
"""
|
| 70 |
+
import numpy as np
|
| 71 |
+
|
| 72 |
+
nodelist = list(G) # ordering of nodes in matrix
|
| 73 |
+
A = nx.to_numpy_array(G, nodelist)
|
| 74 |
+
# convert to 0-1 matrix
|
| 75 |
+
A[A != 0.0] = 1
|
| 76 |
+
w, vec = np.linalg.eigh(A)
|
| 77 |
+
expw = np.exp(w)
|
| 78 |
+
mapping = dict(zip(nodelist, range(len(nodelist))))
|
| 79 |
+
c = {}
|
| 80 |
+
# computing communicabilities
|
| 81 |
+
for u in G:
|
| 82 |
+
c[u] = {}
|
| 83 |
+
for v in G:
|
| 84 |
+
s = 0
|
| 85 |
+
p = mapping[u]
|
| 86 |
+
q = mapping[v]
|
| 87 |
+
for j in range(len(nodelist)):
|
| 88 |
+
s += vec[:, j][p] * vec[:, j][q] * expw[j]
|
| 89 |
+
c[u][v] = float(s)
|
| 90 |
+
return c
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@not_implemented_for("directed")
|
| 94 |
+
@not_implemented_for("multigraph")
|
| 95 |
+
@nx._dispatchable
|
| 96 |
+
def communicability_exp(G):
|
| 97 |
+
r"""Returns communicability between all pairs of nodes in G.
|
| 98 |
+
|
| 99 |
+
Communicability between pair of node (u,v) of node in G is the sum of
|
| 100 |
+
walks of different lengths starting at node u and ending at node v.
|
| 101 |
+
|
| 102 |
+
Parameters
|
| 103 |
+
----------
|
| 104 |
+
G: graph
|
| 105 |
+
|
| 106 |
+
Returns
|
| 107 |
+
-------
|
| 108 |
+
comm: dictionary of dictionaries
|
| 109 |
+
Dictionary of dictionaries keyed by nodes with communicability
|
| 110 |
+
as the value.
|
| 111 |
+
|
| 112 |
+
Raises
|
| 113 |
+
------
|
| 114 |
+
NetworkXError
|
| 115 |
+
If the graph is not undirected and simple.
|
| 116 |
+
|
| 117 |
+
See Also
|
| 118 |
+
--------
|
| 119 |
+
communicability:
|
| 120 |
+
Communicability between pairs of nodes in G.
|
| 121 |
+
communicability_betweenness_centrality:
|
| 122 |
+
Communicability betweenness centrality for each node in G.
|
| 123 |
+
|
| 124 |
+
Notes
|
| 125 |
+
-----
|
| 126 |
+
This algorithm uses matrix exponentiation of the adjacency matrix.
|
| 127 |
+
|
| 128 |
+
Let G=(V,E) be a simple undirected graph. Using the connection between
|
| 129 |
+
the powers of the adjacency matrix and the number of walks in the graph,
|
| 130 |
+
the communicability between nodes u and v is [1]_,
|
| 131 |
+
|
| 132 |
+
.. math::
|
| 133 |
+
C(u,v) = (e^A)_{uv},
|
| 134 |
+
|
| 135 |
+
where `A` is the adjacency matrix of G.
|
| 136 |
+
|
| 137 |
+
References
|
| 138 |
+
----------
|
| 139 |
+
.. [1] Ernesto Estrada, Naomichi Hatano,
|
| 140 |
+
"Communicability in complex networks",
|
| 141 |
+
Phys. Rev. E 77, 036111 (2008).
|
| 142 |
+
https://arxiv.org/abs/0707.0756
|
| 143 |
+
|
| 144 |
+
Examples
|
| 145 |
+
--------
|
| 146 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
|
| 147 |
+
>>> c = nx.communicability_exp(G)
|
| 148 |
+
"""
|
| 149 |
+
import scipy as sp
|
| 150 |
+
|
| 151 |
+
nodelist = list(G) # ordering of nodes in matrix
|
| 152 |
+
A = nx.to_numpy_array(G, nodelist)
|
| 153 |
+
# convert to 0-1 matrix
|
| 154 |
+
A[A != 0.0] = 1
|
| 155 |
+
# communicability matrix
|
| 156 |
+
expA = sp.linalg.expm(A)
|
| 157 |
+
mapping = dict(zip(nodelist, range(len(nodelist))))
|
| 158 |
+
c = {}
|
| 159 |
+
for u in G:
|
| 160 |
+
c[u] = {}
|
| 161 |
+
for v in G:
|
| 162 |
+
c[u][v] = float(expA[mapping[u], mapping[v]])
|
| 163 |
+
return c
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/core.py
ADDED
|
@@ -0,0 +1,588 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Find the k-cores of a graph.
|
| 3 |
+
|
| 4 |
+
The k-core is found by recursively pruning nodes with degrees less than k.
|
| 5 |
+
|
| 6 |
+
See the following references for details:
|
| 7 |
+
|
| 8 |
+
An O(m) Algorithm for Cores Decomposition of Networks
|
| 9 |
+
Vladimir Batagelj and Matjaz Zaversnik, 2003.
|
| 10 |
+
https://arxiv.org/abs/cs.DS/0310049
|
| 11 |
+
|
| 12 |
+
Generalized Cores
|
| 13 |
+
Vladimir Batagelj and Matjaz Zaversnik, 2002.
|
| 14 |
+
https://arxiv.org/pdf/cs/0202039
|
| 15 |
+
|
| 16 |
+
For directed graphs a more general notion is that of D-cores which
|
| 17 |
+
looks at (k, l) restrictions on (in, out) degree. The (k, k) D-core
|
| 18 |
+
is the k-core.
|
| 19 |
+
|
| 20 |
+
D-cores: Measuring Collaboration of Directed Graphs Based on Degeneracy
|
| 21 |
+
Christos Giatsidis, Dimitrios M. Thilikos, Michalis Vazirgiannis, ICDM 2011.
|
| 22 |
+
http://www.graphdegeneracy.org/dcores_ICDM_2011.pdf
|
| 23 |
+
|
| 24 |
+
Multi-scale structure and topological anomaly detection via a new network \
|
| 25 |
+
statistic: The onion decomposition
|
| 26 |
+
L. Hébert-Dufresne, J. A. Grochow, and A. Allard
|
| 27 |
+
Scientific Reports 6, 31708 (2016)
|
| 28 |
+
http://doi.org/10.1038/srep31708
|
| 29 |
+
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
import networkx as nx
|
| 33 |
+
|
| 34 |
+
__all__ = [
|
| 35 |
+
"core_number",
|
| 36 |
+
"k_core",
|
| 37 |
+
"k_shell",
|
| 38 |
+
"k_crust",
|
| 39 |
+
"k_corona",
|
| 40 |
+
"k_truss",
|
| 41 |
+
"onion_layers",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 46 |
+
@nx._dispatchable
|
| 47 |
+
def core_number(G):
|
| 48 |
+
"""Returns the core number for each node.
|
| 49 |
+
|
| 50 |
+
A k-core is a maximal subgraph that contains nodes of degree k or more.
|
| 51 |
+
|
| 52 |
+
The core number of a node is the largest value k of a k-core containing
|
| 53 |
+
that node.
|
| 54 |
+
|
| 55 |
+
Parameters
|
| 56 |
+
----------
|
| 57 |
+
G : NetworkX graph
|
| 58 |
+
An undirected or directed graph
|
| 59 |
+
|
| 60 |
+
Returns
|
| 61 |
+
-------
|
| 62 |
+
core_number : dictionary
|
| 63 |
+
A dictionary keyed by node to the core number.
|
| 64 |
+
|
| 65 |
+
Raises
|
| 66 |
+
------
|
| 67 |
+
NetworkXNotImplemented
|
| 68 |
+
If `G` is a multigraph or contains self loops.
|
| 69 |
+
|
| 70 |
+
Notes
|
| 71 |
+
-----
|
| 72 |
+
For directed graphs the node degree is defined to be the
|
| 73 |
+
in-degree + out-degree.
|
| 74 |
+
|
| 75 |
+
Examples
|
| 76 |
+
--------
|
| 77 |
+
>>> degrees = [0, 1, 2, 2, 2, 2, 3]
|
| 78 |
+
>>> H = nx.havel_hakimi_graph(degrees)
|
| 79 |
+
>>> nx.core_number(H)
|
| 80 |
+
{0: 1, 1: 2, 2: 2, 3: 2, 4: 1, 5: 2, 6: 0}
|
| 81 |
+
>>> G = nx.DiGraph()
|
| 82 |
+
>>> G.add_edges_from([(1, 2), (2, 1), (2, 3), (2, 4), (3, 4), (4, 3)])
|
| 83 |
+
>>> nx.core_number(G)
|
| 84 |
+
{1: 2, 2: 2, 3: 2, 4: 2}
|
| 85 |
+
|
| 86 |
+
References
|
| 87 |
+
----------
|
| 88 |
+
.. [1] An O(m) Algorithm for Cores Decomposition of Networks
|
| 89 |
+
Vladimir Batagelj and Matjaz Zaversnik, 2003.
|
| 90 |
+
https://arxiv.org/abs/cs.DS/0310049
|
| 91 |
+
"""
|
| 92 |
+
if nx.number_of_selfloops(G) > 0:
|
| 93 |
+
msg = (
|
| 94 |
+
"Input graph has self loops which is not permitted; "
|
| 95 |
+
"Consider using G.remove_edges_from(nx.selfloop_edges(G))."
|
| 96 |
+
)
|
| 97 |
+
raise nx.NetworkXNotImplemented(msg)
|
| 98 |
+
degrees = dict(G.degree())
|
| 99 |
+
# Sort nodes by degree.
|
| 100 |
+
nodes = sorted(degrees, key=degrees.get)
|
| 101 |
+
bin_boundaries = [0]
|
| 102 |
+
curr_degree = 0
|
| 103 |
+
for i, v in enumerate(nodes):
|
| 104 |
+
if degrees[v] > curr_degree:
|
| 105 |
+
bin_boundaries.extend([i] * (degrees[v] - curr_degree))
|
| 106 |
+
curr_degree = degrees[v]
|
| 107 |
+
node_pos = {v: pos for pos, v in enumerate(nodes)}
|
| 108 |
+
# The initial guess for the core number of a node is its degree.
|
| 109 |
+
core = degrees
|
| 110 |
+
nbrs = {v: list(nx.all_neighbors(G, v)) for v in G}
|
| 111 |
+
for v in nodes:
|
| 112 |
+
for u in nbrs[v]:
|
| 113 |
+
if core[u] > core[v]:
|
| 114 |
+
nbrs[u].remove(v)
|
| 115 |
+
pos = node_pos[u]
|
| 116 |
+
bin_start = bin_boundaries[core[u]]
|
| 117 |
+
node_pos[u] = bin_start
|
| 118 |
+
node_pos[nodes[bin_start]] = pos
|
| 119 |
+
nodes[bin_start], nodes[pos] = nodes[pos], nodes[bin_start]
|
| 120 |
+
bin_boundaries[core[u]] += 1
|
| 121 |
+
core[u] -= 1
|
| 122 |
+
return core
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _core_subgraph(G, k_filter, k=None, core=None):
|
| 126 |
+
"""Returns the subgraph induced by nodes passing filter `k_filter`.
|
| 127 |
+
|
| 128 |
+
Parameters
|
| 129 |
+
----------
|
| 130 |
+
G : NetworkX graph
|
| 131 |
+
The graph or directed graph to process
|
| 132 |
+
k_filter : filter function
|
| 133 |
+
This function filters the nodes chosen. It takes three inputs:
|
| 134 |
+
A node of G, the filter's cutoff, and the core dict of the graph.
|
| 135 |
+
The function should return a Boolean value.
|
| 136 |
+
k : int, optional
|
| 137 |
+
The order of the core. If not specified use the max core number.
|
| 138 |
+
This value is used as the cutoff for the filter.
|
| 139 |
+
core : dict, optional
|
| 140 |
+
Precomputed core numbers keyed by node for the graph `G`.
|
| 141 |
+
If not specified, the core numbers will be computed from `G`.
|
| 142 |
+
|
| 143 |
+
"""
|
| 144 |
+
if core is None:
|
| 145 |
+
core = core_number(G)
|
| 146 |
+
if k is None:
|
| 147 |
+
k = max(core.values())
|
| 148 |
+
nodes = (v for v in core if k_filter(v, k, core))
|
| 149 |
+
return G.subgraph(nodes).copy()
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 153 |
+
@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
|
| 154 |
+
def k_core(G, k=None, core_number=None):
|
| 155 |
+
"""Returns the k-core of G.
|
| 156 |
+
|
| 157 |
+
A k-core is a maximal subgraph that contains nodes of degree `k` or more.
|
| 158 |
+
|
| 159 |
+
Parameters
|
| 160 |
+
----------
|
| 161 |
+
G : NetworkX graph
|
| 162 |
+
A graph or directed graph
|
| 163 |
+
k : int, optional
|
| 164 |
+
The order of the core. If not specified return the main core.
|
| 165 |
+
core_number : dictionary, optional
|
| 166 |
+
Precomputed core numbers for the graph G.
|
| 167 |
+
|
| 168 |
+
Returns
|
| 169 |
+
-------
|
| 170 |
+
G : NetworkX graph
|
| 171 |
+
The k-core subgraph
|
| 172 |
+
|
| 173 |
+
Raises
|
| 174 |
+
------
|
| 175 |
+
NetworkXNotImplemented
|
| 176 |
+
The k-core is not defined for multigraphs or graphs with self loops.
|
| 177 |
+
|
| 178 |
+
Notes
|
| 179 |
+
-----
|
| 180 |
+
The main core is the core with `k` as the largest core_number.
|
| 181 |
+
|
| 182 |
+
For directed graphs the node degree is defined to be the
|
| 183 |
+
in-degree + out-degree.
|
| 184 |
+
|
| 185 |
+
Graph, node, and edge attributes are copied to the subgraph.
|
| 186 |
+
|
| 187 |
+
Examples
|
| 188 |
+
--------
|
| 189 |
+
>>> degrees = [0, 1, 2, 2, 2, 2, 3]
|
| 190 |
+
>>> H = nx.havel_hakimi_graph(degrees)
|
| 191 |
+
>>> H.degree
|
| 192 |
+
DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
|
| 193 |
+
>>> nx.k_core(H).nodes
|
| 194 |
+
NodeView((1, 2, 3, 5))
|
| 195 |
+
|
| 196 |
+
See Also
|
| 197 |
+
--------
|
| 198 |
+
core_number
|
| 199 |
+
|
| 200 |
+
References
|
| 201 |
+
----------
|
| 202 |
+
.. [1] An O(m) Algorithm for Cores Decomposition of Networks
|
| 203 |
+
Vladimir Batagelj and Matjaz Zaversnik, 2003.
|
| 204 |
+
https://arxiv.org/abs/cs.DS/0310049
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
def k_filter(v, k, c):
|
| 208 |
+
return c[v] >= k
|
| 209 |
+
|
| 210 |
+
return _core_subgraph(G, k_filter, k, core_number)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 214 |
+
@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
|
| 215 |
+
def k_shell(G, k=None, core_number=None):
|
| 216 |
+
"""Returns the k-shell of G.
|
| 217 |
+
|
| 218 |
+
The k-shell is the subgraph induced by nodes with core number k.
|
| 219 |
+
That is, nodes in the k-core that are not in the (k+1)-core.
|
| 220 |
+
|
| 221 |
+
Parameters
|
| 222 |
+
----------
|
| 223 |
+
G : NetworkX graph
|
| 224 |
+
A graph or directed graph.
|
| 225 |
+
k : int, optional
|
| 226 |
+
The order of the shell. If not specified return the outer shell.
|
| 227 |
+
core_number : dictionary, optional
|
| 228 |
+
Precomputed core numbers for the graph G.
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
Returns
|
| 232 |
+
-------
|
| 233 |
+
G : NetworkX graph
|
| 234 |
+
The k-shell subgraph
|
| 235 |
+
|
| 236 |
+
Raises
|
| 237 |
+
------
|
| 238 |
+
NetworkXNotImplemented
|
| 239 |
+
The k-shell is not implemented for multigraphs or graphs with self loops.
|
| 240 |
+
|
| 241 |
+
Notes
|
| 242 |
+
-----
|
| 243 |
+
This is similar to k_corona but in that case only neighbors in the
|
| 244 |
+
k-core are considered.
|
| 245 |
+
|
| 246 |
+
For directed graphs the node degree is defined to be the
|
| 247 |
+
in-degree + out-degree.
|
| 248 |
+
|
| 249 |
+
Graph, node, and edge attributes are copied to the subgraph.
|
| 250 |
+
|
| 251 |
+
Examples
|
| 252 |
+
--------
|
| 253 |
+
>>> degrees = [0, 1, 2, 2, 2, 2, 3]
|
| 254 |
+
>>> H = nx.havel_hakimi_graph(degrees)
|
| 255 |
+
>>> H.degree
|
| 256 |
+
DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
|
| 257 |
+
>>> nx.k_shell(H, k=1).nodes
|
| 258 |
+
NodeView((0, 4))
|
| 259 |
+
|
| 260 |
+
See Also
|
| 261 |
+
--------
|
| 262 |
+
core_number
|
| 263 |
+
k_corona
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
References
|
| 267 |
+
----------
|
| 268 |
+
.. [1] A model of Internet topology using k-shell decomposition
|
| 269 |
+
Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval Shavitt,
|
| 270 |
+
and Eran Shir, PNAS July 3, 2007 vol. 104 no. 27 11150-11154
|
| 271 |
+
http://www.pnas.org/content/104/27/11150.full
|
| 272 |
+
"""
|
| 273 |
+
|
| 274 |
+
def k_filter(v, k, c):
|
| 275 |
+
return c[v] == k
|
| 276 |
+
|
| 277 |
+
return _core_subgraph(G, k_filter, k, core_number)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 281 |
+
@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
|
| 282 |
+
def k_crust(G, k=None, core_number=None):
|
| 283 |
+
"""Returns the k-crust of G.
|
| 284 |
+
|
| 285 |
+
The k-crust is the graph G with the edges of the k-core removed
|
| 286 |
+
and isolated nodes found after the removal of edges are also removed.
|
| 287 |
+
|
| 288 |
+
Parameters
|
| 289 |
+
----------
|
| 290 |
+
G : NetworkX graph
|
| 291 |
+
A graph or directed graph.
|
| 292 |
+
k : int, optional
|
| 293 |
+
The order of the shell. If not specified return the main crust.
|
| 294 |
+
core_number : dictionary, optional
|
| 295 |
+
Precomputed core numbers for the graph G.
|
| 296 |
+
|
| 297 |
+
Returns
|
| 298 |
+
-------
|
| 299 |
+
G : NetworkX graph
|
| 300 |
+
The k-crust subgraph
|
| 301 |
+
|
| 302 |
+
Raises
|
| 303 |
+
------
|
| 304 |
+
NetworkXNotImplemented
|
| 305 |
+
The k-crust is not implemented for multigraphs or graphs with self loops.
|
| 306 |
+
|
| 307 |
+
Notes
|
| 308 |
+
-----
|
| 309 |
+
This definition of k-crust is different than the definition in [1]_.
|
| 310 |
+
The k-crust in [1]_ is equivalent to the k+1 crust of this algorithm.
|
| 311 |
+
|
| 312 |
+
For directed graphs the node degree is defined to be the
|
| 313 |
+
in-degree + out-degree.
|
| 314 |
+
|
| 315 |
+
Graph, node, and edge attributes are copied to the subgraph.
|
| 316 |
+
|
| 317 |
+
Examples
|
| 318 |
+
--------
|
| 319 |
+
>>> degrees = [0, 1, 2, 2, 2, 2, 3]
|
| 320 |
+
>>> H = nx.havel_hakimi_graph(degrees)
|
| 321 |
+
>>> H.degree
|
| 322 |
+
DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
|
| 323 |
+
>>> nx.k_crust(H, k=1).nodes
|
| 324 |
+
NodeView((0, 4, 6))
|
| 325 |
+
|
| 326 |
+
See Also
|
| 327 |
+
--------
|
| 328 |
+
core_number
|
| 329 |
+
|
| 330 |
+
References
|
| 331 |
+
----------
|
| 332 |
+
.. [1] A model of Internet topology using k-shell decomposition
|
| 333 |
+
Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval Shavitt,
|
| 334 |
+
and Eran Shir, PNAS July 3, 2007 vol. 104 no. 27 11150-11154
|
| 335 |
+
http://www.pnas.org/content/104/27/11150.full
|
| 336 |
+
"""
|
| 337 |
+
# Default for k is one less than in _core_subgraph, so just inline.
|
| 338 |
+
# Filter is c[v] <= k
|
| 339 |
+
if core_number is None:
|
| 340 |
+
core_number = nx.core_number(G)
|
| 341 |
+
if k is None:
|
| 342 |
+
k = max(core_number.values()) - 1
|
| 343 |
+
nodes = (v for v in core_number if core_number[v] <= k)
|
| 344 |
+
return G.subgraph(nodes).copy()
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 348 |
+
@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
|
| 349 |
+
def k_corona(G, k, core_number=None):
|
| 350 |
+
"""Returns the k-corona of G.
|
| 351 |
+
|
| 352 |
+
The k-corona is the subgraph of nodes in the k-core which have
|
| 353 |
+
exactly k neighbors in the k-core.
|
| 354 |
+
|
| 355 |
+
Parameters
|
| 356 |
+
----------
|
| 357 |
+
G : NetworkX graph
|
| 358 |
+
A graph or directed graph
|
| 359 |
+
k : int
|
| 360 |
+
The order of the corona.
|
| 361 |
+
core_number : dictionary, optional
|
| 362 |
+
Precomputed core numbers for the graph G.
|
| 363 |
+
|
| 364 |
+
Returns
|
| 365 |
+
-------
|
| 366 |
+
G : NetworkX graph
|
| 367 |
+
The k-corona subgraph
|
| 368 |
+
|
| 369 |
+
Raises
|
| 370 |
+
------
|
| 371 |
+
NetworkXNotImplemented
|
| 372 |
+
The k-corona is not defined for multigraphs or graphs with self loops.
|
| 373 |
+
|
| 374 |
+
Notes
|
| 375 |
+
-----
|
| 376 |
+
For directed graphs the node degree is defined to be the
|
| 377 |
+
in-degree + out-degree.
|
| 378 |
+
|
| 379 |
+
Graph, node, and edge attributes are copied to the subgraph.
|
| 380 |
+
|
| 381 |
+
Examples
|
| 382 |
+
--------
|
| 383 |
+
>>> degrees = [0, 1, 2, 2, 2, 2, 3]
|
| 384 |
+
>>> H = nx.havel_hakimi_graph(degrees)
|
| 385 |
+
>>> H.degree
|
| 386 |
+
DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
|
| 387 |
+
>>> nx.k_corona(H, k=2).nodes
|
| 388 |
+
NodeView((1, 2, 3, 5))
|
| 389 |
+
|
| 390 |
+
See Also
|
| 391 |
+
--------
|
| 392 |
+
core_number
|
| 393 |
+
|
| 394 |
+
References
|
| 395 |
+
----------
|
| 396 |
+
.. [1] k -core (bootstrap) percolation on complex networks:
|
| 397 |
+
Critical phenomena and nonlocal effects,
|
| 398 |
+
A. V. Goltsev, S. N. Dorogovtsev, and J. F. F. Mendes,
|
| 399 |
+
Phys. Rev. E 73, 056101 (2006)
|
| 400 |
+
http://link.aps.org/doi/10.1103/PhysRevE.73.056101
|
| 401 |
+
"""
|
| 402 |
+
|
| 403 |
+
def func(v, k, c):
|
| 404 |
+
return c[v] == k and k == sum(1 for w in G[v] if c[w] >= k)
|
| 405 |
+
|
| 406 |
+
return _core_subgraph(G, func, k, core_number)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@nx.utils.not_implemented_for("directed")
|
| 410 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 411 |
+
@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
|
| 412 |
+
def k_truss(G, k):
|
| 413 |
+
"""Returns the k-truss of `G`.
|
| 414 |
+
|
| 415 |
+
The k-truss is the maximal induced subgraph of `G` which contains at least
|
| 416 |
+
three vertices where every edge is incident to at least `k-2` triangles.
|
| 417 |
+
|
| 418 |
+
Parameters
|
| 419 |
+
----------
|
| 420 |
+
G : NetworkX graph
|
| 421 |
+
An undirected graph
|
| 422 |
+
k : int
|
| 423 |
+
The order of the truss
|
| 424 |
+
|
| 425 |
+
Returns
|
| 426 |
+
-------
|
| 427 |
+
H : NetworkX graph
|
| 428 |
+
The k-truss subgraph
|
| 429 |
+
|
| 430 |
+
Raises
|
| 431 |
+
------
|
| 432 |
+
NetworkXNotImplemented
|
| 433 |
+
If `G` is a multigraph or directed graph or if it contains self loops.
|
| 434 |
+
|
| 435 |
+
Notes
|
| 436 |
+
-----
|
| 437 |
+
A k-clique is a (k-2)-truss and a k-truss is a (k+1)-core.
|
| 438 |
+
|
| 439 |
+
Graph, node, and edge attributes are copied to the subgraph.
|
| 440 |
+
|
| 441 |
+
K-trusses were originally defined in [2] which states that the k-truss
|
| 442 |
+
is the maximal induced subgraph where each edge belongs to at least
|
| 443 |
+
`k-2` triangles. A more recent paper, [1], uses a slightly different
|
| 444 |
+
definition requiring that each edge belong to at least `k` triangles.
|
| 445 |
+
This implementation uses the original definition of `k-2` triangles.
|
| 446 |
+
|
| 447 |
+
Examples
|
| 448 |
+
--------
|
| 449 |
+
>>> degrees = [0, 1, 2, 2, 2, 2, 3]
|
| 450 |
+
>>> H = nx.havel_hakimi_graph(degrees)
|
| 451 |
+
>>> H.degree
|
| 452 |
+
DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
|
| 453 |
+
>>> nx.k_truss(H, k=2).nodes
|
| 454 |
+
NodeView((0, 1, 2, 3, 4, 5))
|
| 455 |
+
|
| 456 |
+
References
|
| 457 |
+
----------
|
| 458 |
+
.. [1] Bounds and Algorithms for k-truss. Paul Burkhardt, Vance Faber,
|
| 459 |
+
David G. Harris, 2018. https://arxiv.org/abs/1806.05523v2
|
| 460 |
+
.. [2] Trusses: Cohesive Subgraphs for Social Network Analysis. Jonathan
|
| 461 |
+
Cohen, 2005.
|
| 462 |
+
"""
|
| 463 |
+
if nx.number_of_selfloops(G) > 0:
|
| 464 |
+
msg = (
|
| 465 |
+
"Input graph has self loops which is not permitted; "
|
| 466 |
+
"Consider using G.remove_edges_from(nx.selfloop_edges(G))."
|
| 467 |
+
)
|
| 468 |
+
raise nx.NetworkXNotImplemented(msg)
|
| 469 |
+
|
| 470 |
+
H = G.copy()
|
| 471 |
+
|
| 472 |
+
n_dropped = 1
|
| 473 |
+
while n_dropped > 0:
|
| 474 |
+
n_dropped = 0
|
| 475 |
+
to_drop = []
|
| 476 |
+
seen = set()
|
| 477 |
+
for u in H:
|
| 478 |
+
nbrs_u = set(H[u])
|
| 479 |
+
seen.add(u)
|
| 480 |
+
new_nbrs = [v for v in nbrs_u if v not in seen]
|
| 481 |
+
for v in new_nbrs:
|
| 482 |
+
if len(nbrs_u & set(H[v])) < (k - 2):
|
| 483 |
+
to_drop.append((u, v))
|
| 484 |
+
H.remove_edges_from(to_drop)
|
| 485 |
+
n_dropped = len(to_drop)
|
| 486 |
+
H.remove_nodes_from(list(nx.isolates(H)))
|
| 487 |
+
|
| 488 |
+
return H
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 492 |
+
@nx.utils.not_implemented_for("directed")
|
| 493 |
+
@nx._dispatchable
|
| 494 |
+
def onion_layers(G):
|
| 495 |
+
"""Returns the layer of each vertex in an onion decomposition of the graph.
|
| 496 |
+
|
| 497 |
+
The onion decomposition refines the k-core decomposition by providing
|
| 498 |
+
information on the internal organization of each k-shell. It is usually
|
| 499 |
+
used alongside the `core numbers`.
|
| 500 |
+
|
| 501 |
+
Parameters
|
| 502 |
+
----------
|
| 503 |
+
G : NetworkX graph
|
| 504 |
+
An undirected graph without self loops.
|
| 505 |
+
|
| 506 |
+
Returns
|
| 507 |
+
-------
|
| 508 |
+
od_layers : dictionary
|
| 509 |
+
A dictionary keyed by node to the onion layer. The layers are
|
| 510 |
+
contiguous integers starting at 1.
|
| 511 |
+
|
| 512 |
+
Raises
|
| 513 |
+
------
|
| 514 |
+
NetworkXNotImplemented
|
| 515 |
+
If `G` is a multigraph or directed graph or if it contains self loops.
|
| 516 |
+
|
| 517 |
+
Examples
|
| 518 |
+
--------
|
| 519 |
+
>>> degrees = [0, 1, 2, 2, 2, 2, 3]
|
| 520 |
+
>>> H = nx.havel_hakimi_graph(degrees)
|
| 521 |
+
>>> H.degree
|
| 522 |
+
DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
|
| 523 |
+
>>> nx.onion_layers(H)
|
| 524 |
+
{6: 1, 0: 2, 4: 3, 1: 4, 2: 4, 3: 4, 5: 4}
|
| 525 |
+
|
| 526 |
+
See Also
|
| 527 |
+
--------
|
| 528 |
+
core_number
|
| 529 |
+
|
| 530 |
+
References
|
| 531 |
+
----------
|
| 532 |
+
.. [1] Multi-scale structure and topological anomaly detection via a new
|
| 533 |
+
network statistic: The onion decomposition
|
| 534 |
+
L. Hébert-Dufresne, J. A. Grochow, and A. Allard
|
| 535 |
+
Scientific Reports 6, 31708 (2016)
|
| 536 |
+
http://doi.org/10.1038/srep31708
|
| 537 |
+
.. [2] Percolation and the effective structure of complex networks
|
| 538 |
+
A. Allard and L. Hébert-Dufresne
|
| 539 |
+
Physical Review X 9, 011023 (2019)
|
| 540 |
+
http://doi.org/10.1103/PhysRevX.9.011023
|
| 541 |
+
"""
|
| 542 |
+
if nx.number_of_selfloops(G) > 0:
|
| 543 |
+
msg = (
|
| 544 |
+
"Input graph contains self loops which is not permitted; "
|
| 545 |
+
"Consider using G.remove_edges_from(nx.selfloop_edges(G))."
|
| 546 |
+
)
|
| 547 |
+
raise nx.NetworkXNotImplemented(msg)
|
| 548 |
+
# Dictionaries to register the k-core/onion decompositions.
|
| 549 |
+
od_layers = {}
|
| 550 |
+
# Adjacency list
|
| 551 |
+
neighbors = {v: list(nx.all_neighbors(G, v)) for v in G}
|
| 552 |
+
# Effective degree of nodes.
|
| 553 |
+
degrees = dict(G.degree())
|
| 554 |
+
# Performs the onion decomposition.
|
| 555 |
+
current_core = 1
|
| 556 |
+
current_layer = 1
|
| 557 |
+
# Sets vertices of degree 0 to layer 1, if any.
|
| 558 |
+
isolated_nodes = list(nx.isolates(G))
|
| 559 |
+
if len(isolated_nodes) > 0:
|
| 560 |
+
for v in isolated_nodes:
|
| 561 |
+
od_layers[v] = current_layer
|
| 562 |
+
degrees.pop(v)
|
| 563 |
+
current_layer = 2
|
| 564 |
+
# Finds the layer for the remaining nodes.
|
| 565 |
+
while len(degrees) > 0:
|
| 566 |
+
# Sets the order for looking at nodes.
|
| 567 |
+
nodes = sorted(degrees, key=degrees.get)
|
| 568 |
+
# Sets properly the current core.
|
| 569 |
+
min_degree = degrees[nodes[0]]
|
| 570 |
+
if min_degree > current_core:
|
| 571 |
+
current_core = min_degree
|
| 572 |
+
# Identifies vertices in the current layer.
|
| 573 |
+
this_layer = []
|
| 574 |
+
for n in nodes:
|
| 575 |
+
if degrees[n] > current_core:
|
| 576 |
+
break
|
| 577 |
+
this_layer.append(n)
|
| 578 |
+
# Identifies the core/layer of the vertices in the current layer.
|
| 579 |
+
for v in this_layer:
|
| 580 |
+
od_layers[v] = current_layer
|
| 581 |
+
for n in neighbors[v]:
|
| 582 |
+
neighbors[n].remove(v)
|
| 583 |
+
degrees[n] = degrees[n] - 1
|
| 584 |
+
degrees.pop(v)
|
| 585 |
+
# Updates the layer count.
|
| 586 |
+
current_layer = current_layer + 1
|
| 587 |
+
# Returns the dictionaries containing the onion layer of each vertices.
|
| 588 |
+
return od_layers
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/covering.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions related to graph covers."""
|
| 2 |
+
|
| 3 |
+
from functools import partial
|
| 4 |
+
from itertools import chain
|
| 5 |
+
|
| 6 |
+
import networkx as nx
|
| 7 |
+
from networkx.utils import arbitrary_element, not_implemented_for
|
| 8 |
+
|
| 9 |
+
__all__ = ["min_edge_cover", "is_edge_cover"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@not_implemented_for("directed")
|
| 13 |
+
@not_implemented_for("multigraph")
|
| 14 |
+
@nx._dispatchable
|
| 15 |
+
def min_edge_cover(G, matching_algorithm=None):
|
| 16 |
+
"""Returns the min cardinality edge cover of the graph as a set of edges.
|
| 17 |
+
|
| 18 |
+
A 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. This function follows that process. A maximum matching
|
| 21 |
+
algorithm can be specified for the first step of the algorithm.
|
| 22 |
+
The resulting set may return a set with one 2-tuple for each edge,
|
| 23 |
+
(the usual case) or with both 2-tuples `(u, v)` and `(v, u)` for
|
| 24 |
+
each edge. The latter is only done when a bipartite matching algorithm
|
| 25 |
+
is specified as `matching_algorithm`.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
G : NetworkX graph
|
| 30 |
+
An undirected graph.
|
| 31 |
+
|
| 32 |
+
matching_algorithm : function
|
| 33 |
+
A function that returns a maximum cardinality matching for `G`.
|
| 34 |
+
The function must take one input, the graph `G`, and return
|
| 35 |
+
either a set of edges (with only one direction for the pair of nodes)
|
| 36 |
+
or a dictionary mapping each node to its mate. If not specified,
|
| 37 |
+
:func:`~networkx.algorithms.matching.max_weight_matching` is used.
|
| 38 |
+
Common bipartite matching functions include
|
| 39 |
+
:func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching`
|
| 40 |
+
or
|
| 41 |
+
:func:`~networkx.algorithms.bipartite.matching.eppstein_matching`.
|
| 42 |
+
|
| 43 |
+
Returns
|
| 44 |
+
-------
|
| 45 |
+
min_cover : set
|
| 46 |
+
|
| 47 |
+
A set of the edges in a minimum edge cover in the form of tuples.
|
| 48 |
+
It contains only one of the equivalent 2-tuples `(u, v)` and `(v, u)`
|
| 49 |
+
for each edge. If a bipartite method is used to compute the matching,
|
| 50 |
+
the returned set contains both the 2-tuples `(u, v)` and `(v, u)`
|
| 51 |
+
for each edge of a minimum edge cover.
|
| 52 |
+
|
| 53 |
+
Examples
|
| 54 |
+
--------
|
| 55 |
+
>>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
|
| 56 |
+
>>> sorted(nx.min_edge_cover(G))
|
| 57 |
+
[(2, 1), (3, 0)]
|
| 58 |
+
|
| 59 |
+
Notes
|
| 60 |
+
-----
|
| 61 |
+
An edge cover of a graph is a set of edges such that every node of
|
| 62 |
+
the graph is incident to at least one edge of the set.
|
| 63 |
+
The minimum edge cover is an edge covering of smallest cardinality.
|
| 64 |
+
|
| 65 |
+
Due to its implementation, the worst-case running time of this algorithm
|
| 66 |
+
is bounded by the worst-case running time of the function
|
| 67 |
+
``matching_algorithm``.
|
| 68 |
+
|
| 69 |
+
Minimum edge cover for `G` can also be found using
|
| 70 |
+
:func:`~networkx.algorithms.bipartite.covering.min_edge_covering` which is
|
| 71 |
+
simply this function with a default matching algorithm of
|
| 72 |
+
:func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching`
|
| 73 |
+
"""
|
| 74 |
+
if len(G) == 0:
|
| 75 |
+
return set()
|
| 76 |
+
if nx.number_of_isolates(G) > 0:
|
| 77 |
+
# ``min_cover`` does not exist as there is an isolated node
|
| 78 |
+
raise nx.NetworkXException(
|
| 79 |
+
"Graph has a node with no edge incident on it, so no edge cover exists."
|
| 80 |
+
)
|
| 81 |
+
if matching_algorithm is None:
|
| 82 |
+
matching_algorithm = partial(nx.max_weight_matching, maxcardinality=True)
|
| 83 |
+
maximum_matching = matching_algorithm(G)
|
| 84 |
+
# ``min_cover`` is superset of ``maximum_matching``
|
| 85 |
+
try:
|
| 86 |
+
# bipartite matching algs return dict so convert if needed
|
| 87 |
+
min_cover = set(maximum_matching.items())
|
| 88 |
+
bipartite_cover = True
|
| 89 |
+
except AttributeError:
|
| 90 |
+
min_cover = maximum_matching
|
| 91 |
+
bipartite_cover = False
|
| 92 |
+
# iterate for uncovered nodes
|
| 93 |
+
uncovered_nodes = set(G) - {v for u, v in min_cover} - {u for u, v in min_cover}
|
| 94 |
+
for v in uncovered_nodes:
|
| 95 |
+
# Since `v` is uncovered, each edge incident to `v` will join it
|
| 96 |
+
# with a covered node (otherwise, if there were an edge joining
|
| 97 |
+
# uncovered nodes `u` and `v`, the maximum matching algorithm
|
| 98 |
+
# would have found it), so we can choose an arbitrary edge
|
| 99 |
+
# incident to `v`. (This applies only in a simple graph, not a
|
| 100 |
+
# multigraph.)
|
| 101 |
+
u = arbitrary_element(G[v])
|
| 102 |
+
min_cover.add((u, v))
|
| 103 |
+
if bipartite_cover:
|
| 104 |
+
min_cover.add((v, u))
|
| 105 |
+
return min_cover
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@not_implemented_for("directed")
|
| 109 |
+
@nx._dispatchable
|
| 110 |
+
def is_edge_cover(G, cover):
|
| 111 |
+
"""Decides whether a set of edges is a valid edge cover of the graph.
|
| 112 |
+
|
| 113 |
+
Given a set of edges, whether it is an edge covering can
|
| 114 |
+
be decided if we just check whether all nodes of the graph
|
| 115 |
+
has an edge from the set, incident on it.
|
| 116 |
+
|
| 117 |
+
Parameters
|
| 118 |
+
----------
|
| 119 |
+
G : NetworkX graph
|
| 120 |
+
An undirected bipartite graph.
|
| 121 |
+
|
| 122 |
+
cover : set
|
| 123 |
+
Set of edges to be checked.
|
| 124 |
+
|
| 125 |
+
Returns
|
| 126 |
+
-------
|
| 127 |
+
bool
|
| 128 |
+
Whether the set of edges is a valid edge cover of the graph.
|
| 129 |
+
|
| 130 |
+
Examples
|
| 131 |
+
--------
|
| 132 |
+
>>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
|
| 133 |
+
>>> cover = {(2, 1), (3, 0)}
|
| 134 |
+
>>> nx.is_edge_cover(G, cover)
|
| 135 |
+
True
|
| 136 |
+
|
| 137 |
+
Notes
|
| 138 |
+
-----
|
| 139 |
+
An edge cover of a graph is a set of edges such that every node of
|
| 140 |
+
the graph is incident to at least one edge of the set.
|
| 141 |
+
"""
|
| 142 |
+
return set(G) <= set(chain.from_iterable(cover))
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/cuts.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for finding and evaluating cuts in a graph."""
|
| 2 |
+
|
| 3 |
+
from itertools import chain
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"boundary_expansion",
|
| 9 |
+
"conductance",
|
| 10 |
+
"cut_size",
|
| 11 |
+
"edge_expansion",
|
| 12 |
+
"mixing_expansion",
|
| 13 |
+
"node_expansion",
|
| 14 |
+
"normalized_cut_size",
|
| 15 |
+
"volume",
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# TODO STILL NEED TO UPDATE ALL THE DOCUMENTATION!
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 23 |
+
def cut_size(G, S, T=None, weight=None):
|
| 24 |
+
"""Returns the size of the cut between two sets of nodes.
|
| 25 |
+
|
| 26 |
+
A *cut* is a partition of the nodes of a graph into two sets. The
|
| 27 |
+
*cut size* is the sum of the weights of the edges "between" the two
|
| 28 |
+
sets of nodes.
|
| 29 |
+
|
| 30 |
+
Parameters
|
| 31 |
+
----------
|
| 32 |
+
G : NetworkX graph
|
| 33 |
+
|
| 34 |
+
S : collection
|
| 35 |
+
A collection of nodes in `G`.
|
| 36 |
+
|
| 37 |
+
T : collection
|
| 38 |
+
A collection of nodes in `G`. If not specified, this is taken to
|
| 39 |
+
be the set complement of `S`.
|
| 40 |
+
|
| 41 |
+
weight : object
|
| 42 |
+
Edge attribute key to use as weight. If not specified, edges
|
| 43 |
+
have weight one.
|
| 44 |
+
|
| 45 |
+
Returns
|
| 46 |
+
-------
|
| 47 |
+
number
|
| 48 |
+
Total weight of all edges from nodes in set `S` to nodes in
|
| 49 |
+
set `T` (and, in the case of directed graphs, all edges from
|
| 50 |
+
nodes in `T` to nodes in `S`).
|
| 51 |
+
|
| 52 |
+
Examples
|
| 53 |
+
--------
|
| 54 |
+
In the graph with two cliques joined by a single edges, the natural
|
| 55 |
+
bipartition of the graph into two blocks, one for each clique,
|
| 56 |
+
yields a cut of weight one:
|
| 57 |
+
|
| 58 |
+
>>> G = nx.barbell_graph(3, 0)
|
| 59 |
+
>>> S = {0, 1, 2}
|
| 60 |
+
>>> T = {3, 4, 5}
|
| 61 |
+
>>> nx.cut_size(G, S, T)
|
| 62 |
+
1
|
| 63 |
+
|
| 64 |
+
Each parallel edge in a multigraph is counted when determining the
|
| 65 |
+
cut size:
|
| 66 |
+
|
| 67 |
+
>>> G = nx.MultiGraph(["ab", "ab"])
|
| 68 |
+
>>> S = {"a"}
|
| 69 |
+
>>> T = {"b"}
|
| 70 |
+
>>> nx.cut_size(G, S, T)
|
| 71 |
+
2
|
| 72 |
+
|
| 73 |
+
Notes
|
| 74 |
+
-----
|
| 75 |
+
In a multigraph, the cut size is the total weight of edges including
|
| 76 |
+
multiplicity.
|
| 77 |
+
|
| 78 |
+
"""
|
| 79 |
+
edges = nx.edge_boundary(G, S, T, data=weight, default=1)
|
| 80 |
+
if G.is_directed():
|
| 81 |
+
edges = chain(edges, nx.edge_boundary(G, T, S, data=weight, default=1))
|
| 82 |
+
return sum(weight for u, v, weight in edges)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 86 |
+
def volume(G, S, weight=None):
|
| 87 |
+
"""Returns the volume of a set of nodes.
|
| 88 |
+
|
| 89 |
+
The *volume* of a set *S* is the sum of the (out-)degrees of nodes
|
| 90 |
+
in *S* (taking into account parallel edges in multigraphs). [1]
|
| 91 |
+
|
| 92 |
+
Parameters
|
| 93 |
+
----------
|
| 94 |
+
G : NetworkX graph
|
| 95 |
+
|
| 96 |
+
S : collection
|
| 97 |
+
A collection of nodes in `G`.
|
| 98 |
+
|
| 99 |
+
weight : object
|
| 100 |
+
Edge attribute key to use as weight. If not specified, edges
|
| 101 |
+
have weight one.
|
| 102 |
+
|
| 103 |
+
Returns
|
| 104 |
+
-------
|
| 105 |
+
number
|
| 106 |
+
The volume of the set of nodes represented by `S` in the graph
|
| 107 |
+
`G`.
|
| 108 |
+
|
| 109 |
+
See also
|
| 110 |
+
--------
|
| 111 |
+
conductance
|
| 112 |
+
cut_size
|
| 113 |
+
edge_expansion
|
| 114 |
+
edge_boundary
|
| 115 |
+
normalized_cut_size
|
| 116 |
+
|
| 117 |
+
References
|
| 118 |
+
----------
|
| 119 |
+
.. [1] David Gleich.
|
| 120 |
+
*Hierarchical Directed Spectral Graph Partitioning*.
|
| 121 |
+
<https://www.cs.purdue.edu/homes/dgleich/publications/Gleich%202005%20-%20hierarchical%20directed%20spectral.pdf>
|
| 122 |
+
|
| 123 |
+
"""
|
| 124 |
+
degree = G.out_degree if G.is_directed() else G.degree
|
| 125 |
+
return sum(d for v, d in degree(S, weight=weight))
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 129 |
+
def normalized_cut_size(G, S, T=None, weight=None):
|
| 130 |
+
"""Returns the normalized size of the cut between two sets of nodes.
|
| 131 |
+
|
| 132 |
+
The *normalized cut size* is the cut size times the sum of the
|
| 133 |
+
reciprocal sizes of the volumes of the two sets. [1]
|
| 134 |
+
|
| 135 |
+
Parameters
|
| 136 |
+
----------
|
| 137 |
+
G : NetworkX graph
|
| 138 |
+
|
| 139 |
+
S : collection
|
| 140 |
+
A collection of nodes in `G`.
|
| 141 |
+
|
| 142 |
+
T : collection
|
| 143 |
+
A collection of nodes in `G`.
|
| 144 |
+
|
| 145 |
+
weight : object
|
| 146 |
+
Edge attribute key to use as weight. If not specified, edges
|
| 147 |
+
have weight one.
|
| 148 |
+
|
| 149 |
+
Returns
|
| 150 |
+
-------
|
| 151 |
+
number
|
| 152 |
+
The normalized cut size between the two sets `S` and `T`.
|
| 153 |
+
|
| 154 |
+
Notes
|
| 155 |
+
-----
|
| 156 |
+
In a multigraph, the cut size is the total weight of edges including
|
| 157 |
+
multiplicity.
|
| 158 |
+
|
| 159 |
+
See also
|
| 160 |
+
--------
|
| 161 |
+
conductance
|
| 162 |
+
cut_size
|
| 163 |
+
edge_expansion
|
| 164 |
+
volume
|
| 165 |
+
|
| 166 |
+
References
|
| 167 |
+
----------
|
| 168 |
+
.. [1] David Gleich.
|
| 169 |
+
*Hierarchical Directed Spectral Graph Partitioning*.
|
| 170 |
+
<https://www.cs.purdue.edu/homes/dgleich/publications/Gleich%202005%20-%20hierarchical%20directed%20spectral.pdf>
|
| 171 |
+
|
| 172 |
+
"""
|
| 173 |
+
if T is None:
|
| 174 |
+
T = set(G) - set(S)
|
| 175 |
+
num_cut_edges = cut_size(G, S, T=T, weight=weight)
|
| 176 |
+
volume_S = volume(G, S, weight=weight)
|
| 177 |
+
volume_T = volume(G, T, weight=weight)
|
| 178 |
+
return num_cut_edges * ((1 / volume_S) + (1 / volume_T))
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 182 |
+
def conductance(G, S, T=None, weight=None):
|
| 183 |
+
"""Returns the conductance of two sets of nodes.
|
| 184 |
+
|
| 185 |
+
The *conductance* is the quotient of the cut size and the smaller of
|
| 186 |
+
the volumes of the two sets. [1]
|
| 187 |
+
|
| 188 |
+
Parameters
|
| 189 |
+
----------
|
| 190 |
+
G : NetworkX graph
|
| 191 |
+
|
| 192 |
+
S : collection
|
| 193 |
+
A collection of nodes in `G`.
|
| 194 |
+
|
| 195 |
+
T : collection
|
| 196 |
+
A collection of nodes in `G`.
|
| 197 |
+
|
| 198 |
+
weight : object
|
| 199 |
+
Edge attribute key to use as weight. If not specified, edges
|
| 200 |
+
have weight one.
|
| 201 |
+
|
| 202 |
+
Returns
|
| 203 |
+
-------
|
| 204 |
+
number
|
| 205 |
+
The conductance between the two sets `S` and `T`.
|
| 206 |
+
|
| 207 |
+
See also
|
| 208 |
+
--------
|
| 209 |
+
cut_size
|
| 210 |
+
edge_expansion
|
| 211 |
+
normalized_cut_size
|
| 212 |
+
volume
|
| 213 |
+
|
| 214 |
+
References
|
| 215 |
+
----------
|
| 216 |
+
.. [1] David Gleich.
|
| 217 |
+
*Hierarchical Directed Spectral Graph Partitioning*.
|
| 218 |
+
<https://www.cs.purdue.edu/homes/dgleich/publications/Gleich%202005%20-%20hierarchical%20directed%20spectral.pdf>
|
| 219 |
+
|
| 220 |
+
"""
|
| 221 |
+
if T is None:
|
| 222 |
+
T = set(G) - set(S)
|
| 223 |
+
num_cut_edges = cut_size(G, S, T, weight=weight)
|
| 224 |
+
volume_S = volume(G, S, weight=weight)
|
| 225 |
+
volume_T = volume(G, T, weight=weight)
|
| 226 |
+
return num_cut_edges / min(volume_S, volume_T)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 230 |
+
def edge_expansion(G, S, T=None, weight=None):
|
| 231 |
+
"""Returns the edge expansion between two node sets.
|
| 232 |
+
|
| 233 |
+
The *edge expansion* is the quotient of the cut size and the smaller
|
| 234 |
+
of the cardinalities of the two sets. [1]
|
| 235 |
+
|
| 236 |
+
Parameters
|
| 237 |
+
----------
|
| 238 |
+
G : NetworkX graph
|
| 239 |
+
|
| 240 |
+
S : collection
|
| 241 |
+
A collection of nodes in `G`.
|
| 242 |
+
|
| 243 |
+
T : collection
|
| 244 |
+
A collection of nodes in `G`.
|
| 245 |
+
|
| 246 |
+
weight : object
|
| 247 |
+
Edge attribute key to use as weight. If not specified, edges
|
| 248 |
+
have weight one.
|
| 249 |
+
|
| 250 |
+
Returns
|
| 251 |
+
-------
|
| 252 |
+
number
|
| 253 |
+
The edge expansion between the two sets `S` and `T`.
|
| 254 |
+
|
| 255 |
+
See also
|
| 256 |
+
--------
|
| 257 |
+
boundary_expansion
|
| 258 |
+
mixing_expansion
|
| 259 |
+
node_expansion
|
| 260 |
+
|
| 261 |
+
References
|
| 262 |
+
----------
|
| 263 |
+
.. [1] Fan Chung.
|
| 264 |
+
*Spectral Graph Theory*.
|
| 265 |
+
(CBMS Regional Conference Series in Mathematics, No. 92),
|
| 266 |
+
American Mathematical Society, 1997, ISBN 0-8218-0315-8
|
| 267 |
+
<http://www.math.ucsd.edu/~fan/research/revised.html>
|
| 268 |
+
|
| 269 |
+
"""
|
| 270 |
+
if T is None:
|
| 271 |
+
T = set(G) - set(S)
|
| 272 |
+
num_cut_edges = cut_size(G, S, T=T, weight=weight)
|
| 273 |
+
return num_cut_edges / min(len(S), len(T))
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 277 |
+
def mixing_expansion(G, S, T=None, weight=None):
|
| 278 |
+
"""Returns the mixing expansion between two node sets.
|
| 279 |
+
|
| 280 |
+
The *mixing expansion* is the quotient of the cut size and twice the
|
| 281 |
+
number of edges in the graph. [1]
|
| 282 |
+
|
| 283 |
+
Parameters
|
| 284 |
+
----------
|
| 285 |
+
G : NetworkX graph
|
| 286 |
+
|
| 287 |
+
S : collection
|
| 288 |
+
A collection of nodes in `G`.
|
| 289 |
+
|
| 290 |
+
T : collection
|
| 291 |
+
A collection of nodes in `G`.
|
| 292 |
+
|
| 293 |
+
weight : object
|
| 294 |
+
Edge attribute key to use as weight. If not specified, edges
|
| 295 |
+
have weight one.
|
| 296 |
+
|
| 297 |
+
Returns
|
| 298 |
+
-------
|
| 299 |
+
number
|
| 300 |
+
The mixing expansion between the two sets `S` and `T`.
|
| 301 |
+
|
| 302 |
+
See also
|
| 303 |
+
--------
|
| 304 |
+
boundary_expansion
|
| 305 |
+
edge_expansion
|
| 306 |
+
node_expansion
|
| 307 |
+
|
| 308 |
+
References
|
| 309 |
+
----------
|
| 310 |
+
.. [1] Vadhan, Salil P.
|
| 311 |
+
"Pseudorandomness."
|
| 312 |
+
*Foundations and Trends
|
| 313 |
+
in Theoretical Computer Science* 7.1–3 (2011): 1–336.
|
| 314 |
+
<https://doi.org/10.1561/0400000010>
|
| 315 |
+
|
| 316 |
+
"""
|
| 317 |
+
num_cut_edges = cut_size(G, S, T=T, weight=weight)
|
| 318 |
+
num_total_edges = G.number_of_edges()
|
| 319 |
+
return num_cut_edges / (2 * num_total_edges)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
# TODO What is the generalization to two arguments, S and T? Does the
|
| 323 |
+
# denominator become `min(len(S), len(T))`?
|
| 324 |
+
@nx._dispatchable
|
| 325 |
+
def node_expansion(G, S):
|
| 326 |
+
"""Returns the node expansion of the set `S`.
|
| 327 |
+
|
| 328 |
+
The *node expansion* is the quotient of the size of the node
|
| 329 |
+
boundary of *S* and the cardinality of *S*. [1]
|
| 330 |
+
|
| 331 |
+
Parameters
|
| 332 |
+
----------
|
| 333 |
+
G : NetworkX graph
|
| 334 |
+
|
| 335 |
+
S : collection
|
| 336 |
+
A collection of nodes in `G`.
|
| 337 |
+
|
| 338 |
+
Returns
|
| 339 |
+
-------
|
| 340 |
+
number
|
| 341 |
+
The node expansion of the set `S`.
|
| 342 |
+
|
| 343 |
+
See also
|
| 344 |
+
--------
|
| 345 |
+
boundary_expansion
|
| 346 |
+
edge_expansion
|
| 347 |
+
mixing_expansion
|
| 348 |
+
|
| 349 |
+
References
|
| 350 |
+
----------
|
| 351 |
+
.. [1] Vadhan, Salil P.
|
| 352 |
+
"Pseudorandomness."
|
| 353 |
+
*Foundations and Trends
|
| 354 |
+
in Theoretical Computer Science* 7.1–3 (2011): 1–336.
|
| 355 |
+
<https://doi.org/10.1561/0400000010>
|
| 356 |
+
|
| 357 |
+
"""
|
| 358 |
+
neighborhood = set(chain.from_iterable(G.neighbors(v) for v in S))
|
| 359 |
+
return len(neighborhood) / len(S)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@nx._dispatchable
|
| 363 |
+
def boundary_expansion(G, S):
|
| 364 |
+
"""Returns the boundary expansion of the set `S`.
|
| 365 |
+
|
| 366 |
+
The *boundary expansion* of a set `S` is the ratio between the size of its
|
| 367 |
+
node boundary and the cardinality of the set itself [1]_ .
|
| 368 |
+
|
| 369 |
+
Parameters
|
| 370 |
+
----------
|
| 371 |
+
G : NetworkX graph
|
| 372 |
+
The input graph.
|
| 373 |
+
|
| 374 |
+
S : collection
|
| 375 |
+
A collection of nodes in `G`.
|
| 376 |
+
|
| 377 |
+
Returns
|
| 378 |
+
-------
|
| 379 |
+
number
|
| 380 |
+
The boundary expansion ratio: size of node boundary / size of `S`.
|
| 381 |
+
|
| 382 |
+
Examples
|
| 383 |
+
--------
|
| 384 |
+
The node boundary is {2, 3} (size 2), divided by ``|S|=2``:
|
| 385 |
+
|
| 386 |
+
>>> G = nx.cycle_graph(4)
|
| 387 |
+
>>> S = {0, 1}
|
| 388 |
+
>>> nx.boundary_expansion(G, S)
|
| 389 |
+
1.0
|
| 390 |
+
|
| 391 |
+
For disconnected sets, e.g. here where the node boundary is ``{1, 3, 5}``:
|
| 392 |
+
|
| 393 |
+
>>> G = nx.cycle_graph(6)
|
| 394 |
+
>>> S = {0, 2, 4}
|
| 395 |
+
>>> nx.boundary_expansion(G, S)
|
| 396 |
+
1.0
|
| 397 |
+
|
| 398 |
+
See also
|
| 399 |
+
--------
|
| 400 |
+
:func:`~networkx.algorithms.boundary.node_boundary`
|
| 401 |
+
edge_expansion
|
| 402 |
+
mixing_expansion
|
| 403 |
+
node_expansion
|
| 404 |
+
|
| 405 |
+
Notes
|
| 406 |
+
-----
|
| 407 |
+
The node boundary is defined as all nodes not in `S` that are adjacent to
|
| 408 |
+
nodes in `S`.
|
| 409 |
+
|
| 410 |
+
References
|
| 411 |
+
----------
|
| 412 |
+
.. [1] Vadhan, Salil P.
|
| 413 |
+
"Pseudorandomness." *Foundations and Trends in Theoretical Computer Science*
|
| 414 |
+
7.1–3 (2011): 1–336. <https://doi.org/10.1561/0400000010>
|
| 415 |
+
"""
|
| 416 |
+
return len(nx.node_boundary(G, S)) / len(S)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/cycles.py
ADDED
|
@@ -0,0 +1,1234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
========================
|
| 3 |
+
Cycle finding algorithms
|
| 4 |
+
========================
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from itertools import combinations, product
|
| 9 |
+
from math import inf
|
| 10 |
+
|
| 11 |
+
import networkx as nx
|
| 12 |
+
from networkx.utils import not_implemented_for, pairwise
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"cycle_basis",
|
| 16 |
+
"simple_cycles",
|
| 17 |
+
"recursive_simple_cycles",
|
| 18 |
+
"find_cycle",
|
| 19 |
+
"minimum_cycle_basis",
|
| 20 |
+
"chordless_cycles",
|
| 21 |
+
"girth",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@not_implemented_for("directed")
|
| 26 |
+
@not_implemented_for("multigraph")
|
| 27 |
+
@nx._dispatchable
|
| 28 |
+
def cycle_basis(G, root=None):
|
| 29 |
+
"""Returns a list of cycles which form a basis for cycles of G.
|
| 30 |
+
|
| 31 |
+
A basis for cycles of a network is a minimal collection of
|
| 32 |
+
cycles such that any cycle in the network can be written
|
| 33 |
+
as a sum of cycles in the basis. Here summation of cycles
|
| 34 |
+
is defined as "exclusive or" of the edges. Cycle bases are
|
| 35 |
+
useful, e.g. when deriving equations for electric circuits
|
| 36 |
+
using Kirchhoff's Laws.
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
G : NetworkX Graph
|
| 41 |
+
root : node, optional
|
| 42 |
+
Specify starting node for basis.
|
| 43 |
+
|
| 44 |
+
Returns
|
| 45 |
+
-------
|
| 46 |
+
A list of cycle lists. Each cycle list is a list of nodes
|
| 47 |
+
which forms a cycle (loop) in G.
|
| 48 |
+
|
| 49 |
+
Examples
|
| 50 |
+
--------
|
| 51 |
+
>>> G = nx.Graph()
|
| 52 |
+
>>> nx.add_cycle(G, [0, 1, 2, 3])
|
| 53 |
+
>>> nx.add_cycle(G, [0, 3, 4, 5])
|
| 54 |
+
>>> nx.cycle_basis(G, 0)
|
| 55 |
+
[[3, 4, 5, 0], [1, 2, 3, 0]]
|
| 56 |
+
|
| 57 |
+
Notes
|
| 58 |
+
-----
|
| 59 |
+
This is adapted from algorithm CACM 491 [1]_.
|
| 60 |
+
|
| 61 |
+
References
|
| 62 |
+
----------
|
| 63 |
+
.. [1] Paton, K. An algorithm for finding a fundamental set of
|
| 64 |
+
cycles of a graph. Comm. ACM 12, 9 (Sept 1969), 514-518.
|
| 65 |
+
|
| 66 |
+
See Also
|
| 67 |
+
--------
|
| 68 |
+
simple_cycles
|
| 69 |
+
minimum_cycle_basis
|
| 70 |
+
"""
|
| 71 |
+
gnodes = dict.fromkeys(G) # set-like object that maintains node order
|
| 72 |
+
cycles = []
|
| 73 |
+
while gnodes: # loop over connected components
|
| 74 |
+
if root is None:
|
| 75 |
+
root = gnodes.popitem()[0]
|
| 76 |
+
stack = [root]
|
| 77 |
+
pred = {root: root}
|
| 78 |
+
used = {root: set()}
|
| 79 |
+
while stack: # walk the spanning tree finding cycles
|
| 80 |
+
z = stack.pop() # use last-in so cycles easier to find
|
| 81 |
+
zused = used[z]
|
| 82 |
+
for nbr in G[z]:
|
| 83 |
+
if nbr not in used: # new node
|
| 84 |
+
pred[nbr] = z
|
| 85 |
+
stack.append(nbr)
|
| 86 |
+
used[nbr] = {z}
|
| 87 |
+
elif nbr == z: # self loops
|
| 88 |
+
cycles.append([z])
|
| 89 |
+
elif nbr not in zused: # found a cycle
|
| 90 |
+
pn = used[nbr]
|
| 91 |
+
cycle = [nbr, z]
|
| 92 |
+
p = pred[z]
|
| 93 |
+
while p not in pn:
|
| 94 |
+
cycle.append(p)
|
| 95 |
+
p = pred[p]
|
| 96 |
+
cycle.append(p)
|
| 97 |
+
cycles.append(cycle)
|
| 98 |
+
used[nbr].add(z)
|
| 99 |
+
for node in pred:
|
| 100 |
+
gnodes.pop(node, None)
|
| 101 |
+
root = None
|
| 102 |
+
return cycles
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@nx._dispatchable
|
| 106 |
+
def simple_cycles(G, length_bound=None):
|
| 107 |
+
"""Find simple cycles (elementary circuits) of a graph.
|
| 108 |
+
|
| 109 |
+
A "simple cycle", or "elementary circuit", is a closed path where
|
| 110 |
+
no node appears twice. In a directed graph, two simple cycles are distinct
|
| 111 |
+
if they are not cyclic permutations of each other. In an undirected graph,
|
| 112 |
+
two simple cycles are distinct if they are not cyclic permutations of each
|
| 113 |
+
other nor of the other's reversal.
|
| 114 |
+
|
| 115 |
+
Optionally, the cycles are bounded in length. In the unbounded case, we use
|
| 116 |
+
a nonrecursive, iterator/generator version of Johnson's algorithm [1]_. In
|
| 117 |
+
the bounded case, we use a version of the algorithm of Gupta and
|
| 118 |
+
Suzumura [2]_. There may be better algorithms for some cases [3]_ [4]_ [5]_.
|
| 119 |
+
|
| 120 |
+
The algorithms of Johnson, and Gupta and Suzumura, are enhanced by some
|
| 121 |
+
well-known preprocessing techniques. When `G` is directed, we restrict our
|
| 122 |
+
attention to strongly connected components of `G`, generate all simple cycles
|
| 123 |
+
containing a certain node, remove that node, and further decompose the
|
| 124 |
+
remainder into strongly connected components. When `G` is undirected, we
|
| 125 |
+
restrict our attention to biconnected components, generate all simple cycles
|
| 126 |
+
containing a particular edge, remove that edge, and further decompose the
|
| 127 |
+
remainder into biconnected components.
|
| 128 |
+
|
| 129 |
+
Note that multigraphs are supported by this function -- and in undirected
|
| 130 |
+
multigraphs, a pair of parallel edges is considered a cycle of length 2.
|
| 131 |
+
Likewise, self-loops are considered to be cycles of length 1. We define
|
| 132 |
+
cycles as sequences of nodes; so the presence of loops and parallel edges
|
| 133 |
+
does not change the number of simple cycles in a graph.
|
| 134 |
+
|
| 135 |
+
Parameters
|
| 136 |
+
----------
|
| 137 |
+
G : NetworkX Graph
|
| 138 |
+
A networkx graph. Undirected, directed, and multigraphs are all supported.
|
| 139 |
+
|
| 140 |
+
length_bound : int or None, optional (default=None)
|
| 141 |
+
If `length_bound` is an int, generate all simple cycles of `G` with length at
|
| 142 |
+
most `length_bound`. Otherwise, generate all simple cycles of `G`.
|
| 143 |
+
|
| 144 |
+
Yields
|
| 145 |
+
------
|
| 146 |
+
list of nodes
|
| 147 |
+
Each cycle is represented by a list of nodes along the cycle.
|
| 148 |
+
|
| 149 |
+
Examples
|
| 150 |
+
--------
|
| 151 |
+
>>> G = nx.DiGraph([(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)])
|
| 152 |
+
>>> sorted(nx.simple_cycles(G))
|
| 153 |
+
[[0], [0, 1, 2], [0, 2], [1, 2], [2]]
|
| 154 |
+
|
| 155 |
+
To filter the cycles so that they don't include certain nodes or edges,
|
| 156 |
+
copy your graph and eliminate those nodes or edges before calling.
|
| 157 |
+
For example, to exclude self-loops from the above example:
|
| 158 |
+
|
| 159 |
+
>>> H = G.copy()
|
| 160 |
+
>>> H.remove_edges_from(nx.selfloop_edges(G))
|
| 161 |
+
>>> sorted(nx.simple_cycles(H))
|
| 162 |
+
[[0, 1, 2], [0, 2], [1, 2]]
|
| 163 |
+
|
| 164 |
+
Notes
|
| 165 |
+
-----
|
| 166 |
+
When `length_bound` is None, the time complexity is $O((n+e)(c+1))$ for $n$
|
| 167 |
+
nodes, $e$ edges and $c$ simple circuits. Otherwise, when ``length_bound > 1``,
|
| 168 |
+
the time complexity is $O((c+n)(k-1)d^k)$ where $d$ is the average degree of
|
| 169 |
+
the nodes of `G` and $k$ = `length_bound`.
|
| 170 |
+
|
| 171 |
+
Raises
|
| 172 |
+
------
|
| 173 |
+
ValueError
|
| 174 |
+
when ``length_bound < 0``.
|
| 175 |
+
|
| 176 |
+
References
|
| 177 |
+
----------
|
| 178 |
+
.. [1] Finding all the elementary circuits of a directed graph.
|
| 179 |
+
D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975.
|
| 180 |
+
https://doi.org/10.1137/0204007
|
| 181 |
+
.. [2] Finding All Bounded-Length Simple Cycles in a Directed Graph
|
| 182 |
+
A. Gupta and T. Suzumura https://arxiv.org/abs/2105.10094
|
| 183 |
+
.. [3] Enumerating the cycles of a digraph: a new preprocessing strategy.
|
| 184 |
+
G. Loizou and P. Thanish, Information Sciences, v. 27, 163-182, 1982.
|
| 185 |
+
.. [4] A search strategy for the elementary cycles of a directed graph.
|
| 186 |
+
J.L. Szwarcfiter and P.E. Lauer, BIT NUMERICAL MATHEMATICS,
|
| 187 |
+
v. 16, no. 2, 192-204, 1976.
|
| 188 |
+
.. [5] Optimal Listing of Cycles and st-Paths in Undirected Graphs
|
| 189 |
+
R. Ferreira and R. Grossi and A. Marino and N. Pisanti and R. Rizzi and
|
| 190 |
+
G. Sacomoto https://arxiv.org/abs/1205.2766
|
| 191 |
+
|
| 192 |
+
See Also
|
| 193 |
+
--------
|
| 194 |
+
cycle_basis
|
| 195 |
+
chordless_cycles
|
| 196 |
+
"""
|
| 197 |
+
|
| 198 |
+
if length_bound is not None:
|
| 199 |
+
if length_bound == 0:
|
| 200 |
+
return
|
| 201 |
+
elif length_bound < 0:
|
| 202 |
+
raise ValueError("length bound must be non-negative")
|
| 203 |
+
|
| 204 |
+
directed = G.is_directed()
|
| 205 |
+
yield from ([v] for v, Gv in G.adj.items() if v in Gv)
|
| 206 |
+
|
| 207 |
+
if length_bound is not None and length_bound == 1:
|
| 208 |
+
return
|
| 209 |
+
|
| 210 |
+
if G.is_multigraph() and not directed:
|
| 211 |
+
visited = set()
|
| 212 |
+
for u, Gu in G.adj.items():
|
| 213 |
+
multiplicity = ((v, len(Guv)) for v, Guv in Gu.items() if v in visited)
|
| 214 |
+
yield from ([u, v] for v, m in multiplicity if m > 1)
|
| 215 |
+
visited.add(u)
|
| 216 |
+
|
| 217 |
+
# explicitly filter out loops; implicitly filter out parallel edges
|
| 218 |
+
if directed:
|
| 219 |
+
G = nx.DiGraph((u, v) for u, Gu in G.adj.items() for v in Gu if v != u)
|
| 220 |
+
else:
|
| 221 |
+
G = nx.Graph((u, v) for u, Gu in G.adj.items() for v in Gu if v != u)
|
| 222 |
+
|
| 223 |
+
# this case is not strictly necessary but improves performance
|
| 224 |
+
if length_bound is not None and length_bound == 2:
|
| 225 |
+
if directed:
|
| 226 |
+
visited = set()
|
| 227 |
+
for u, Gu in G.adj.items():
|
| 228 |
+
yield from (
|
| 229 |
+
[v, u] for v in visited.intersection(Gu) if G.has_edge(v, u)
|
| 230 |
+
)
|
| 231 |
+
visited.add(u)
|
| 232 |
+
return
|
| 233 |
+
|
| 234 |
+
if directed:
|
| 235 |
+
yield from _directed_cycle_search(G, length_bound)
|
| 236 |
+
else:
|
| 237 |
+
yield from _undirected_cycle_search(G, length_bound)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _directed_cycle_search(G, length_bound):
|
| 241 |
+
"""A dispatch function for `simple_cycles` for directed graphs.
|
| 242 |
+
|
| 243 |
+
We generate all cycles of G through binary partition.
|
| 244 |
+
|
| 245 |
+
1. Pick a node v in G which belongs to at least one cycle
|
| 246 |
+
a. Generate all cycles of G which contain the node v.
|
| 247 |
+
b. Recursively generate all cycles of G \\ v.
|
| 248 |
+
|
| 249 |
+
This is accomplished through the following:
|
| 250 |
+
|
| 251 |
+
1. Compute the strongly connected components SCC of G.
|
| 252 |
+
2. Select and remove a biconnected component C from BCC. Select a
|
| 253 |
+
non-tree edge (u, v) of a depth-first search of G[C].
|
| 254 |
+
3. For each simple cycle P containing v in G[C], yield P.
|
| 255 |
+
4. Add the biconnected components of G[C \\ v] to BCC.
|
| 256 |
+
|
| 257 |
+
If the parameter length_bound is not None, then step 3 will be limited to
|
| 258 |
+
simple cycles of length at most length_bound.
|
| 259 |
+
|
| 260 |
+
Parameters
|
| 261 |
+
----------
|
| 262 |
+
G : NetworkX DiGraph
|
| 263 |
+
A directed graph
|
| 264 |
+
|
| 265 |
+
length_bound : int or None
|
| 266 |
+
If length_bound is an int, generate all simple cycles of G with length at most length_bound.
|
| 267 |
+
Otherwise, generate all simple cycles of G.
|
| 268 |
+
|
| 269 |
+
Yields
|
| 270 |
+
------
|
| 271 |
+
list of nodes
|
| 272 |
+
Each cycle is represented by a list of nodes along the cycle.
|
| 273 |
+
"""
|
| 274 |
+
|
| 275 |
+
scc = nx.strongly_connected_components
|
| 276 |
+
components = [c for c in scc(G) if len(c) >= 2]
|
| 277 |
+
while components:
|
| 278 |
+
c = components.pop()
|
| 279 |
+
Gc = G.subgraph(c)
|
| 280 |
+
v = next(iter(c))
|
| 281 |
+
if length_bound is None:
|
| 282 |
+
yield from _johnson_cycle_search(Gc, [v])
|
| 283 |
+
else:
|
| 284 |
+
yield from _bounded_cycle_search(Gc, [v], length_bound)
|
| 285 |
+
# delete v after searching G, to make sure we can find v
|
| 286 |
+
G.remove_node(v)
|
| 287 |
+
components.extend(c for c in scc(Gc) if len(c) >= 2)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _undirected_cycle_search(G, length_bound):
|
| 291 |
+
"""A dispatch function for `simple_cycles` for undirected graphs.
|
| 292 |
+
|
| 293 |
+
We generate all cycles of G through binary partition.
|
| 294 |
+
|
| 295 |
+
1. Pick an edge (u, v) in G which belongs to at least one cycle
|
| 296 |
+
a. Generate all cycles of G which contain the edge (u, v)
|
| 297 |
+
b. Recursively generate all cycles of G \\ (u, v)
|
| 298 |
+
|
| 299 |
+
This is accomplished through the following:
|
| 300 |
+
|
| 301 |
+
1. Compute the biconnected components BCC of G.
|
| 302 |
+
2. Select and remove a biconnected component C from BCC. Select a
|
| 303 |
+
non-tree edge (u, v) of a depth-first search of G[C].
|
| 304 |
+
3. For each (v -> u) path P remaining in G[C] \\ (u, v), yield P.
|
| 305 |
+
4. Add the biconnected components of G[C] \\ (u, v) to BCC.
|
| 306 |
+
|
| 307 |
+
If the parameter length_bound is not None, then step 3 will be limited to simple paths
|
| 308 |
+
of length at most length_bound.
|
| 309 |
+
|
| 310 |
+
Parameters
|
| 311 |
+
----------
|
| 312 |
+
G : NetworkX Graph
|
| 313 |
+
An undirected graph
|
| 314 |
+
|
| 315 |
+
length_bound : int or None
|
| 316 |
+
If length_bound is an int, generate all simple cycles of G with length at most length_bound.
|
| 317 |
+
Otherwise, generate all simple cycles of G.
|
| 318 |
+
|
| 319 |
+
Yields
|
| 320 |
+
------
|
| 321 |
+
list of nodes
|
| 322 |
+
Each cycle is represented by a list of nodes along the cycle.
|
| 323 |
+
"""
|
| 324 |
+
|
| 325 |
+
bcc = nx.biconnected_components
|
| 326 |
+
components = [c for c in bcc(G) if len(c) >= 3]
|
| 327 |
+
while components:
|
| 328 |
+
c = components.pop()
|
| 329 |
+
Gc = G.subgraph(c)
|
| 330 |
+
uv = list(next(iter(Gc.edges)))
|
| 331 |
+
G.remove_edge(*uv)
|
| 332 |
+
# delete (u, v) before searching G, to avoid fake 3-cycles [u, v, u]
|
| 333 |
+
if length_bound is None:
|
| 334 |
+
yield from _johnson_cycle_search(Gc, uv)
|
| 335 |
+
else:
|
| 336 |
+
yield from _bounded_cycle_search(Gc, uv, length_bound)
|
| 337 |
+
components.extend(c for c in bcc(Gc) if len(c) >= 3)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class _NeighborhoodCache(dict):
|
| 341 |
+
"""Very lightweight graph wrapper which caches neighborhoods as list.
|
| 342 |
+
|
| 343 |
+
This dict subclass uses the __missing__ functionality to query graphs for
|
| 344 |
+
their neighborhoods, and store the result as a list. This is used to avoid
|
| 345 |
+
the performance penalty incurred by subgraph views.
|
| 346 |
+
"""
|
| 347 |
+
|
| 348 |
+
def __init__(self, G):
|
| 349 |
+
self.G = G
|
| 350 |
+
|
| 351 |
+
def __missing__(self, v):
|
| 352 |
+
Gv = self[v] = list(self.G[v])
|
| 353 |
+
return Gv
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def _johnson_cycle_search(G, path):
|
| 357 |
+
"""The main loop of the cycle-enumeration algorithm of Johnson.
|
| 358 |
+
|
| 359 |
+
Parameters
|
| 360 |
+
----------
|
| 361 |
+
G : NetworkX Graph or DiGraph
|
| 362 |
+
A graph
|
| 363 |
+
|
| 364 |
+
path : list
|
| 365 |
+
A cycle prefix. All cycles generated will begin with this prefix.
|
| 366 |
+
|
| 367 |
+
Yields
|
| 368 |
+
------
|
| 369 |
+
list of nodes
|
| 370 |
+
Each cycle is represented by a list of nodes along the cycle.
|
| 371 |
+
|
| 372 |
+
References
|
| 373 |
+
----------
|
| 374 |
+
.. [1] Finding all the elementary circuits of a directed graph.
|
| 375 |
+
D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975.
|
| 376 |
+
https://doi.org/10.1137/0204007
|
| 377 |
+
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
G = _NeighborhoodCache(G)
|
| 381 |
+
blocked = set(path)
|
| 382 |
+
B = defaultdict(set) # graph portions that yield no elementary circuit
|
| 383 |
+
start = path[0]
|
| 384 |
+
stack = [iter(G[path[-1]])]
|
| 385 |
+
closed = [False]
|
| 386 |
+
while stack:
|
| 387 |
+
nbrs = stack[-1]
|
| 388 |
+
for w in nbrs:
|
| 389 |
+
if w == start:
|
| 390 |
+
yield path[:]
|
| 391 |
+
closed[-1] = True
|
| 392 |
+
elif w not in blocked:
|
| 393 |
+
path.append(w)
|
| 394 |
+
closed.append(False)
|
| 395 |
+
stack.append(iter(G[w]))
|
| 396 |
+
blocked.add(w)
|
| 397 |
+
break
|
| 398 |
+
else: # no more nbrs
|
| 399 |
+
stack.pop()
|
| 400 |
+
v = path.pop()
|
| 401 |
+
if closed.pop():
|
| 402 |
+
if closed:
|
| 403 |
+
closed[-1] = True
|
| 404 |
+
unblock_stack = {v}
|
| 405 |
+
while unblock_stack:
|
| 406 |
+
u = unblock_stack.pop()
|
| 407 |
+
if u in blocked:
|
| 408 |
+
blocked.remove(u)
|
| 409 |
+
unblock_stack.update(B[u])
|
| 410 |
+
B[u].clear()
|
| 411 |
+
else:
|
| 412 |
+
for w in G[v]:
|
| 413 |
+
B[w].add(v)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def _bounded_cycle_search(G, path, length_bound):
|
| 417 |
+
"""The main loop of the cycle-enumeration algorithm of Gupta and Suzumura.
|
| 418 |
+
|
| 419 |
+
Parameters
|
| 420 |
+
----------
|
| 421 |
+
G : NetworkX Graph or DiGraph
|
| 422 |
+
A graph
|
| 423 |
+
|
| 424 |
+
path : list
|
| 425 |
+
A cycle prefix. All cycles generated will begin with this prefix.
|
| 426 |
+
|
| 427 |
+
length_bound: int
|
| 428 |
+
A length bound. All cycles generated will have length at most length_bound.
|
| 429 |
+
|
| 430 |
+
Yields
|
| 431 |
+
------
|
| 432 |
+
list of nodes
|
| 433 |
+
Each cycle is represented by a list of nodes along the cycle.
|
| 434 |
+
|
| 435 |
+
References
|
| 436 |
+
----------
|
| 437 |
+
.. [1] Finding All Bounded-Length Simple Cycles in a Directed Graph
|
| 438 |
+
A. Gupta and T. Suzumura https://arxiv.org/abs/2105.10094
|
| 439 |
+
|
| 440 |
+
"""
|
| 441 |
+
G = _NeighborhoodCache(G)
|
| 442 |
+
lock = {v: 0 for v in path}
|
| 443 |
+
B = defaultdict(set)
|
| 444 |
+
start = path[0]
|
| 445 |
+
stack = [iter(G[path[-1]])]
|
| 446 |
+
blen = [length_bound]
|
| 447 |
+
while stack:
|
| 448 |
+
nbrs = stack[-1]
|
| 449 |
+
for w in nbrs:
|
| 450 |
+
if w == start:
|
| 451 |
+
yield path[:]
|
| 452 |
+
blen[-1] = 1
|
| 453 |
+
elif len(path) < lock.get(w, length_bound):
|
| 454 |
+
path.append(w)
|
| 455 |
+
blen.append(length_bound)
|
| 456 |
+
lock[w] = len(path)
|
| 457 |
+
stack.append(iter(G[w]))
|
| 458 |
+
break
|
| 459 |
+
else:
|
| 460 |
+
stack.pop()
|
| 461 |
+
v = path.pop()
|
| 462 |
+
bl = blen.pop()
|
| 463 |
+
if blen:
|
| 464 |
+
blen[-1] = min(blen[-1], bl)
|
| 465 |
+
if bl < length_bound:
|
| 466 |
+
relax_stack = [(bl, v)]
|
| 467 |
+
while relax_stack:
|
| 468 |
+
bl, u = relax_stack.pop()
|
| 469 |
+
if lock.get(u, length_bound) < length_bound - bl + 1:
|
| 470 |
+
lock[u] = length_bound - bl + 1
|
| 471 |
+
relax_stack.extend((bl + 1, w) for w in B[u].difference(path))
|
| 472 |
+
else:
|
| 473 |
+
for w in G[v]:
|
| 474 |
+
B[w].add(v)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
@nx._dispatchable
|
| 478 |
+
def chordless_cycles(G, length_bound=None):
|
| 479 |
+
"""Find simple chordless cycles of a graph.
|
| 480 |
+
|
| 481 |
+
A `simple cycle` is a closed path where no node appears twice. In a simple
|
| 482 |
+
cycle, a `chord` is an additional edge between two nodes in the cycle. A
|
| 483 |
+
`chordless cycle` is a simple cycle without chords. Said differently, a
|
| 484 |
+
chordless cycle is a cycle C in a graph G where the number of edges in the
|
| 485 |
+
induced graph G[C] is equal to the length of `C`.
|
| 486 |
+
|
| 487 |
+
Note that some care must be taken in the case that G is not a simple graph
|
| 488 |
+
nor a simple digraph. Some authors limit the definition of chordless cycles
|
| 489 |
+
to have a prescribed minimum length; we do not.
|
| 490 |
+
|
| 491 |
+
1. We interpret self-loops to be chordless cycles, except in multigraphs
|
| 492 |
+
with multiple loops in parallel. Likewise, in a chordless cycle of
|
| 493 |
+
length greater than 1, there can be no nodes with self-loops.
|
| 494 |
+
|
| 495 |
+
2. We interpret directed two-cycles to be chordless cycles, except in
|
| 496 |
+
multi-digraphs when any edge in a two-cycle has a parallel copy.
|
| 497 |
+
|
| 498 |
+
3. We interpret parallel pairs of undirected edges as two-cycles, except
|
| 499 |
+
when a third (or more) parallel edge exists between the two nodes.
|
| 500 |
+
|
| 501 |
+
4. Generalizing the above, edges with parallel clones may not occur in
|
| 502 |
+
chordless cycles.
|
| 503 |
+
|
| 504 |
+
In a directed graph, two chordless cycles are distinct if they are not
|
| 505 |
+
cyclic permutations of each other. In an undirected graph, two chordless
|
| 506 |
+
cycles are distinct if they are not cyclic permutations of each other nor of
|
| 507 |
+
the other's reversal.
|
| 508 |
+
|
| 509 |
+
Optionally, the cycles are bounded in length.
|
| 510 |
+
|
| 511 |
+
We use an algorithm strongly inspired by that of Dias et al [1]_. It has
|
| 512 |
+
been modified in the following ways:
|
| 513 |
+
|
| 514 |
+
1. Recursion is avoided, per Python's limitations.
|
| 515 |
+
|
| 516 |
+
2. The labeling function is not necessary, because the starting paths
|
| 517 |
+
are chosen (and deleted from the host graph) to prevent multiple
|
| 518 |
+
occurrences of the same path.
|
| 519 |
+
|
| 520 |
+
3. The search is optionally bounded at a specified length.
|
| 521 |
+
|
| 522 |
+
4. Support for directed graphs is provided by extending cycles along
|
| 523 |
+
forward edges, and blocking nodes along forward and reverse edges.
|
| 524 |
+
|
| 525 |
+
5. Support for multigraphs is provided by omitting digons from the set
|
| 526 |
+
of forward edges.
|
| 527 |
+
|
| 528 |
+
Parameters
|
| 529 |
+
----------
|
| 530 |
+
G : NetworkX DiGraph
|
| 531 |
+
A directed graph
|
| 532 |
+
|
| 533 |
+
length_bound : int or None, optional (default=None)
|
| 534 |
+
If length_bound is an int, generate all simple cycles of G with length at
|
| 535 |
+
most length_bound. Otherwise, generate all simple cycles of G.
|
| 536 |
+
|
| 537 |
+
Yields
|
| 538 |
+
------
|
| 539 |
+
list of nodes
|
| 540 |
+
Each cycle is represented by a list of nodes along the cycle.
|
| 541 |
+
|
| 542 |
+
Examples
|
| 543 |
+
--------
|
| 544 |
+
>>> sorted(list(nx.chordless_cycles(nx.complete_graph(4))))
|
| 545 |
+
[[1, 0, 2], [1, 0, 3], [2, 0, 3], [2, 1, 3]]
|
| 546 |
+
|
| 547 |
+
Notes
|
| 548 |
+
-----
|
| 549 |
+
When length_bound is None, and the graph is simple, the time complexity is
|
| 550 |
+
$O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$ chordless cycles.
|
| 551 |
+
|
| 552 |
+
Raises
|
| 553 |
+
------
|
| 554 |
+
ValueError
|
| 555 |
+
when length_bound < 0.
|
| 556 |
+
|
| 557 |
+
References
|
| 558 |
+
----------
|
| 559 |
+
.. [1] Efficient enumeration of chordless cycles
|
| 560 |
+
E. Dias and D. Castonguay and H. Longo and W.A.R. Jradi
|
| 561 |
+
https://arxiv.org/abs/1309.1051
|
| 562 |
+
|
| 563 |
+
See Also
|
| 564 |
+
--------
|
| 565 |
+
simple_cycles
|
| 566 |
+
"""
|
| 567 |
+
|
| 568 |
+
if length_bound is not None:
|
| 569 |
+
if length_bound == 0:
|
| 570 |
+
return
|
| 571 |
+
elif length_bound < 0:
|
| 572 |
+
raise ValueError("length bound must be non-negative")
|
| 573 |
+
|
| 574 |
+
directed = G.is_directed()
|
| 575 |
+
multigraph = G.is_multigraph()
|
| 576 |
+
|
| 577 |
+
if multigraph:
|
| 578 |
+
yield from ([v] for v, Gv in G.adj.items() if len(Gv.get(v, ())) == 1)
|
| 579 |
+
else:
|
| 580 |
+
yield from ([v] for v, Gv in G.adj.items() if v in Gv)
|
| 581 |
+
|
| 582 |
+
if length_bound is not None and length_bound == 1:
|
| 583 |
+
return
|
| 584 |
+
|
| 585 |
+
# Nodes with loops cannot belong to longer cycles. Let's delete them here.
|
| 586 |
+
# also, we implicitly reduce the multiplicity of edges down to 1 in the case
|
| 587 |
+
# of multiedges.
|
| 588 |
+
loops = set(nx.nodes_with_selfloops(G))
|
| 589 |
+
edges = ((u, v) for u in G if u not in loops for v in G._adj[u] if v not in loops)
|
| 590 |
+
if directed:
|
| 591 |
+
F = nx.DiGraph(edges)
|
| 592 |
+
B = F.to_undirected(as_view=False)
|
| 593 |
+
else:
|
| 594 |
+
F = nx.Graph(edges)
|
| 595 |
+
B = None
|
| 596 |
+
|
| 597 |
+
# If we're given a multigraph, we have a few cases to consider with parallel
|
| 598 |
+
# edges.
|
| 599 |
+
#
|
| 600 |
+
# 1. If we have 2 or more edges in parallel between the nodes (u, v), we
|
| 601 |
+
# must not construct longer cycles along (u, v).
|
| 602 |
+
# 2. If G is not directed, then a pair of parallel edges between (u, v) is a
|
| 603 |
+
# chordless cycle unless there exists a third (or more) parallel edge.
|
| 604 |
+
# 3. If G is directed, then parallel edges do not form cycles, but do
|
| 605 |
+
# preclude back-edges from forming cycles (handled in the next section),
|
| 606 |
+
# Thus, if an edge (u, v) is duplicated and the reverse (v, u) is also
|
| 607 |
+
# present, then we remove both from F.
|
| 608 |
+
#
|
| 609 |
+
# In directed graphs, we need to consider both directions that edges can
|
| 610 |
+
# take, so iterate over all edges (u, v) and possibly (v, u). In undirected
|
| 611 |
+
# graphs, we need to be a little careful to only consider every edge once,
|
| 612 |
+
# so we use a "visited" set to emulate node-order comparisons.
|
| 613 |
+
|
| 614 |
+
if multigraph:
|
| 615 |
+
if not directed:
|
| 616 |
+
B = F.copy()
|
| 617 |
+
visited = set()
|
| 618 |
+
for u, Gu in G.adj.items():
|
| 619 |
+
if u in loops:
|
| 620 |
+
continue
|
| 621 |
+
if directed:
|
| 622 |
+
multiplicity = ((v, len(Guv)) for v, Guv in Gu.items())
|
| 623 |
+
for v, m in multiplicity:
|
| 624 |
+
if m > 1:
|
| 625 |
+
F.remove_edges_from(((u, v), (v, u)))
|
| 626 |
+
else:
|
| 627 |
+
multiplicity = ((v, len(Guv)) for v, Guv in Gu.items() if v in visited)
|
| 628 |
+
for v, m in multiplicity:
|
| 629 |
+
if m == 2:
|
| 630 |
+
yield [u, v]
|
| 631 |
+
if m > 1:
|
| 632 |
+
F.remove_edge(u, v)
|
| 633 |
+
visited.add(u)
|
| 634 |
+
|
| 635 |
+
# If we're given a directed graphs, we need to think about digons. If we
|
| 636 |
+
# have two edges (u, v) and (v, u), then that's a two-cycle. If either edge
|
| 637 |
+
# was duplicated above, then we removed both from F. So, any digons we find
|
| 638 |
+
# here are chordless. After finding digons, we remove their edges from F
|
| 639 |
+
# to avoid traversing them in the search for chordless cycles.
|
| 640 |
+
if directed:
|
| 641 |
+
for u, Fu in F.adj.items():
|
| 642 |
+
digons = [[u, v] for v in Fu if F.has_edge(v, u)]
|
| 643 |
+
yield from digons
|
| 644 |
+
F.remove_edges_from(digons)
|
| 645 |
+
F.remove_edges_from(e[::-1] for e in digons)
|
| 646 |
+
|
| 647 |
+
if length_bound is not None and length_bound == 2:
|
| 648 |
+
return
|
| 649 |
+
|
| 650 |
+
# Now, we prepare to search for cycles. We have removed all cycles of
|
| 651 |
+
# lengths 1 and 2, so F is a simple graph or simple digraph. We repeatedly
|
| 652 |
+
# separate digraphs into their strongly connected components, and undirected
|
| 653 |
+
# graphs into their biconnected components. For each component, we pick a
|
| 654 |
+
# node v, search for chordless cycles based at each "stem" (u, v, w), and
|
| 655 |
+
# then remove v from that component before separating the graph again.
|
| 656 |
+
if directed:
|
| 657 |
+
separate = nx.strongly_connected_components
|
| 658 |
+
|
| 659 |
+
# Directed stems look like (u -> v -> w), so we use the product of
|
| 660 |
+
# predecessors of v with successors of v.
|
| 661 |
+
def stems(C, v):
|
| 662 |
+
for u, w in product(C.pred[v], C.succ[v]):
|
| 663 |
+
if not G.has_edge(u, w): # omit stems with acyclic chords
|
| 664 |
+
yield [u, v, w], F.has_edge(w, u)
|
| 665 |
+
|
| 666 |
+
else:
|
| 667 |
+
separate = nx.biconnected_components
|
| 668 |
+
|
| 669 |
+
# Undirected stems look like (u ~ v ~ w), but we must not also search
|
| 670 |
+
# (w ~ v ~ u), so we use combinations of v's neighbors of length 2.
|
| 671 |
+
def stems(C, v):
|
| 672 |
+
yield from (([u, v, w], F.has_edge(w, u)) for u, w in combinations(C[v], 2))
|
| 673 |
+
|
| 674 |
+
components = [c for c in separate(F) if len(c) > 2]
|
| 675 |
+
while components:
|
| 676 |
+
c = components.pop()
|
| 677 |
+
v = next(iter(c))
|
| 678 |
+
Fc = F.subgraph(c)
|
| 679 |
+
Fcc = Bcc = None
|
| 680 |
+
for S, is_triangle in stems(Fc, v):
|
| 681 |
+
if is_triangle:
|
| 682 |
+
yield S
|
| 683 |
+
else:
|
| 684 |
+
if Fcc is None:
|
| 685 |
+
Fcc = _NeighborhoodCache(Fc)
|
| 686 |
+
Bcc = Fcc if B is None else _NeighborhoodCache(B.subgraph(c))
|
| 687 |
+
yield from _chordless_cycle_search(Fcc, Bcc, S, length_bound)
|
| 688 |
+
|
| 689 |
+
components.extend(c for c in separate(F.subgraph(c - {v})) if len(c) > 2)
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
def _chordless_cycle_search(F, B, path, length_bound):
|
| 693 |
+
"""The main loop for chordless cycle enumeration.
|
| 694 |
+
|
| 695 |
+
This algorithm is strongly inspired by that of Dias et al [1]_. It has been
|
| 696 |
+
modified in the following ways:
|
| 697 |
+
|
| 698 |
+
1. Recursion is avoided, per Python's limitations
|
| 699 |
+
|
| 700 |
+
2. The labeling function is not necessary, because the starting paths
|
| 701 |
+
are chosen (and deleted from the host graph) to prevent multiple
|
| 702 |
+
occurrences of the same path
|
| 703 |
+
|
| 704 |
+
3. The search is optionally bounded at a specified length
|
| 705 |
+
|
| 706 |
+
4. Support for directed graphs is provided by extending cycles along
|
| 707 |
+
forward edges, and blocking nodes along forward and reverse edges
|
| 708 |
+
|
| 709 |
+
5. Support for multigraphs is provided by omitting digons from the set
|
| 710 |
+
of forward edges
|
| 711 |
+
|
| 712 |
+
Parameters
|
| 713 |
+
----------
|
| 714 |
+
F : _NeighborhoodCache
|
| 715 |
+
A graph of forward edges to follow in constructing cycles
|
| 716 |
+
|
| 717 |
+
B : _NeighborhoodCache
|
| 718 |
+
A graph of blocking edges to prevent the production of chordless cycles
|
| 719 |
+
|
| 720 |
+
path : list
|
| 721 |
+
A cycle prefix. All cycles generated will begin with this prefix.
|
| 722 |
+
|
| 723 |
+
length_bound : int
|
| 724 |
+
A length bound. All cycles generated will have length at most length_bound.
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
Yields
|
| 728 |
+
------
|
| 729 |
+
list of nodes
|
| 730 |
+
Each cycle is represented by a list of nodes along the cycle.
|
| 731 |
+
|
| 732 |
+
References
|
| 733 |
+
----------
|
| 734 |
+
.. [1] Efficient enumeration of chordless cycles
|
| 735 |
+
E. Dias and D. Castonguay and H. Longo and W.A.R. Jradi
|
| 736 |
+
https://arxiv.org/abs/1309.1051
|
| 737 |
+
|
| 738 |
+
"""
|
| 739 |
+
blocked = defaultdict(int)
|
| 740 |
+
target = path[0]
|
| 741 |
+
blocked[path[1]] = 1
|
| 742 |
+
for w in path[1:]:
|
| 743 |
+
for v in B[w]:
|
| 744 |
+
blocked[v] += 1
|
| 745 |
+
|
| 746 |
+
stack = [iter(F[path[2]])]
|
| 747 |
+
while stack:
|
| 748 |
+
nbrs = stack[-1]
|
| 749 |
+
for w in nbrs:
|
| 750 |
+
if blocked[w] == 1 and (length_bound is None or len(path) < length_bound):
|
| 751 |
+
Fw = F[w]
|
| 752 |
+
if target in Fw:
|
| 753 |
+
yield path + [w]
|
| 754 |
+
else:
|
| 755 |
+
Bw = B[w]
|
| 756 |
+
if target in Bw:
|
| 757 |
+
continue
|
| 758 |
+
for v in Bw:
|
| 759 |
+
blocked[v] += 1
|
| 760 |
+
path.append(w)
|
| 761 |
+
stack.append(iter(Fw))
|
| 762 |
+
break
|
| 763 |
+
else:
|
| 764 |
+
stack.pop()
|
| 765 |
+
for v in B[path.pop()]:
|
| 766 |
+
blocked[v] -= 1
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
@not_implemented_for("undirected")
|
| 770 |
+
@nx._dispatchable(mutates_input=True)
|
| 771 |
+
def recursive_simple_cycles(G):
|
| 772 |
+
"""Find simple cycles (elementary circuits) of a directed graph.
|
| 773 |
+
|
| 774 |
+
A `simple cycle`, or `elementary circuit`, is a closed path where
|
| 775 |
+
no node appears twice. Two elementary circuits are distinct if they
|
| 776 |
+
are not cyclic permutations of each other.
|
| 777 |
+
|
| 778 |
+
This version uses a recursive algorithm to build a list of cycles.
|
| 779 |
+
You should probably use the iterator version called simple_cycles().
|
| 780 |
+
Warning: This recursive version uses lots of RAM!
|
| 781 |
+
It appears in NetworkX for pedagogical value.
|
| 782 |
+
|
| 783 |
+
Parameters
|
| 784 |
+
----------
|
| 785 |
+
G : NetworkX DiGraph
|
| 786 |
+
A directed graph
|
| 787 |
+
|
| 788 |
+
Returns
|
| 789 |
+
-------
|
| 790 |
+
A list of cycles, where each cycle is represented by a list of nodes
|
| 791 |
+
along the cycle.
|
| 792 |
+
|
| 793 |
+
Example:
|
| 794 |
+
|
| 795 |
+
>>> edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
|
| 796 |
+
>>> G = nx.DiGraph(edges)
|
| 797 |
+
>>> nx.recursive_simple_cycles(G)
|
| 798 |
+
[[0], [2], [0, 1, 2], [0, 2], [1, 2]]
|
| 799 |
+
|
| 800 |
+
Notes
|
| 801 |
+
-----
|
| 802 |
+
The implementation follows pp. 79-80 in [1]_.
|
| 803 |
+
|
| 804 |
+
The time complexity is $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$
|
| 805 |
+
elementary circuits.
|
| 806 |
+
|
| 807 |
+
References
|
| 808 |
+
----------
|
| 809 |
+
.. [1] Finding all the elementary circuits of a directed graph.
|
| 810 |
+
D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975.
|
| 811 |
+
https://doi.org/10.1137/0204007
|
| 812 |
+
|
| 813 |
+
See Also
|
| 814 |
+
--------
|
| 815 |
+
simple_cycles, cycle_basis
|
| 816 |
+
"""
|
| 817 |
+
|
| 818 |
+
# Jon Olav Vik, 2010-08-09
|
| 819 |
+
def _unblock(thisnode):
|
| 820 |
+
"""Recursively unblock and remove nodes from B[thisnode]."""
|
| 821 |
+
if blocked[thisnode]:
|
| 822 |
+
blocked[thisnode] = False
|
| 823 |
+
while B[thisnode]:
|
| 824 |
+
_unblock(B[thisnode].pop())
|
| 825 |
+
|
| 826 |
+
def circuit(thisnode, startnode, component):
|
| 827 |
+
closed = False # set to True if elementary path is closed
|
| 828 |
+
path.append(thisnode)
|
| 829 |
+
blocked[thisnode] = True
|
| 830 |
+
for nextnode in component[thisnode]: # direct successors of thisnode
|
| 831 |
+
if nextnode == startnode:
|
| 832 |
+
result.append(path[:])
|
| 833 |
+
closed = True
|
| 834 |
+
elif not blocked[nextnode]:
|
| 835 |
+
if circuit(nextnode, startnode, component):
|
| 836 |
+
closed = True
|
| 837 |
+
if closed:
|
| 838 |
+
_unblock(thisnode)
|
| 839 |
+
else:
|
| 840 |
+
for nextnode in component[thisnode]:
|
| 841 |
+
if thisnode not in B[nextnode]: # TODO: use set for speedup?
|
| 842 |
+
B[nextnode].append(thisnode)
|
| 843 |
+
path.pop() # remove thisnode from path
|
| 844 |
+
return closed
|
| 845 |
+
|
| 846 |
+
path = [] # stack of nodes in current path
|
| 847 |
+
blocked = defaultdict(bool) # vertex: blocked from search?
|
| 848 |
+
B = defaultdict(list) # graph portions that yield no elementary circuit
|
| 849 |
+
result = [] # list to accumulate the circuits found
|
| 850 |
+
|
| 851 |
+
# Johnson's algorithm exclude self cycle edges like (v, v)
|
| 852 |
+
# To be backward compatible, we record those cycles in advance
|
| 853 |
+
# and then remove from subG
|
| 854 |
+
for v in G:
|
| 855 |
+
if G.has_edge(v, v):
|
| 856 |
+
result.append([v])
|
| 857 |
+
G.remove_edge(v, v)
|
| 858 |
+
|
| 859 |
+
# Johnson's algorithm requires some ordering of the nodes.
|
| 860 |
+
# They might not be sortable so we assign an arbitrary ordering.
|
| 861 |
+
ordering = dict(zip(G, range(len(G))))
|
| 862 |
+
for s in ordering:
|
| 863 |
+
# Build the subgraph induced by s and following nodes in the ordering
|
| 864 |
+
subgraph = G.subgraph(node for node in G if ordering[node] >= ordering[s])
|
| 865 |
+
# Find the strongly connected component in the subgraph
|
| 866 |
+
# that contains the least node according to the ordering
|
| 867 |
+
strongcomp = nx.strongly_connected_components(subgraph)
|
| 868 |
+
mincomp = min(strongcomp, key=lambda ns: min(ordering[n] for n in ns))
|
| 869 |
+
component = G.subgraph(mincomp)
|
| 870 |
+
if len(component) > 1:
|
| 871 |
+
# smallest node in the component according to the ordering
|
| 872 |
+
startnode = min(component, key=ordering.__getitem__)
|
| 873 |
+
for node in component:
|
| 874 |
+
blocked[node] = False
|
| 875 |
+
B[node][:] = []
|
| 876 |
+
dummy = circuit(startnode, startnode, component)
|
| 877 |
+
return result
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
@nx._dispatchable
|
| 881 |
+
def find_cycle(G, source=None, orientation=None):
|
| 882 |
+
"""Returns a cycle found via depth-first traversal.
|
| 883 |
+
|
| 884 |
+
The cycle is a list of edges indicating the cyclic path.
|
| 885 |
+
Orientation of directed edges is controlled by `orientation`.
|
| 886 |
+
|
| 887 |
+
Parameters
|
| 888 |
+
----------
|
| 889 |
+
G : graph
|
| 890 |
+
A directed/undirected graph/multigraph.
|
| 891 |
+
|
| 892 |
+
source : node, list of nodes
|
| 893 |
+
The node from which the traversal begins. If None, then a source
|
| 894 |
+
is chosen arbitrarily and repeatedly until all edges from each node in
|
| 895 |
+
the graph are searched.
|
| 896 |
+
|
| 897 |
+
orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
|
| 898 |
+
For directed graphs and directed multigraphs, edge traversals need not
|
| 899 |
+
respect the original orientation of the edges.
|
| 900 |
+
When set to 'reverse' every edge is traversed in the reverse direction.
|
| 901 |
+
When set to 'ignore', every edge is treated as undirected.
|
| 902 |
+
When set to 'original', every edge is treated as directed.
|
| 903 |
+
In all three cases, the yielded edge tuples add a last entry to
|
| 904 |
+
indicate the direction in which that edge was traversed.
|
| 905 |
+
If orientation is None, the yielded edge has no direction indicated.
|
| 906 |
+
The direction is respected, but not reported.
|
| 907 |
+
|
| 908 |
+
Returns
|
| 909 |
+
-------
|
| 910 |
+
edges : directed edges
|
| 911 |
+
A list of directed edges indicating the path taken for the loop.
|
| 912 |
+
If no cycle is found, then an exception is raised.
|
| 913 |
+
For graphs, an edge is of the form `(u, v)` where `u` and `v`
|
| 914 |
+
are the tail and head of the edge as determined by the traversal.
|
| 915 |
+
For multigraphs, an edge is of the form `(u, v, key)`, where `key` is
|
| 916 |
+
the key of the edge. When the graph is directed, then `u` and `v`
|
| 917 |
+
are always in the order of the actual directed edge.
|
| 918 |
+
If orientation is not None then the edge tuple is extended to include
|
| 919 |
+
the direction of traversal ('forward' or 'reverse') on that edge.
|
| 920 |
+
|
| 921 |
+
Raises
|
| 922 |
+
------
|
| 923 |
+
NetworkXNoCycle
|
| 924 |
+
If no cycle was found.
|
| 925 |
+
|
| 926 |
+
Examples
|
| 927 |
+
--------
|
| 928 |
+
In this example, we construct a DAG and find, in the first call, that there
|
| 929 |
+
are no directed cycles, and so an exception is raised. In the second call,
|
| 930 |
+
we ignore edge orientations and find that there is an undirected cycle.
|
| 931 |
+
Note that the second call finds a directed cycle while effectively
|
| 932 |
+
traversing an undirected graph, and so, we found an "undirected cycle".
|
| 933 |
+
This means that this DAG structure does not form a directed tree (which
|
| 934 |
+
is also known as a polytree).
|
| 935 |
+
|
| 936 |
+
>>> G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
|
| 937 |
+
>>> nx.find_cycle(G, orientation="original")
|
| 938 |
+
Traceback (most recent call last):
|
| 939 |
+
...
|
| 940 |
+
networkx.exception.NetworkXNoCycle: No cycle found.
|
| 941 |
+
>>> list(nx.find_cycle(G, orientation="ignore"))
|
| 942 |
+
[(0, 1, 'forward'), (1, 2, 'forward'), (0, 2, 'reverse')]
|
| 943 |
+
|
| 944 |
+
See Also
|
| 945 |
+
--------
|
| 946 |
+
simple_cycles
|
| 947 |
+
"""
|
| 948 |
+
if not G.is_directed() or orientation in (None, "original"):
|
| 949 |
+
|
| 950 |
+
def tailhead(edge):
|
| 951 |
+
return edge[:2]
|
| 952 |
+
|
| 953 |
+
elif orientation == "reverse":
|
| 954 |
+
|
| 955 |
+
def tailhead(edge):
|
| 956 |
+
return edge[1], edge[0]
|
| 957 |
+
|
| 958 |
+
elif orientation == "ignore":
|
| 959 |
+
|
| 960 |
+
def tailhead(edge):
|
| 961 |
+
if edge[-1] == "reverse":
|
| 962 |
+
return edge[1], edge[0]
|
| 963 |
+
return edge[:2]
|
| 964 |
+
|
| 965 |
+
explored = set()
|
| 966 |
+
cycle = []
|
| 967 |
+
final_node = None
|
| 968 |
+
for start_node in G.nbunch_iter(source):
|
| 969 |
+
if start_node in explored:
|
| 970 |
+
# No loop is possible.
|
| 971 |
+
continue
|
| 972 |
+
|
| 973 |
+
edges = []
|
| 974 |
+
# All nodes seen in this iteration of edge_dfs
|
| 975 |
+
seen = {start_node}
|
| 976 |
+
# Nodes in active path.
|
| 977 |
+
active_nodes = {start_node}
|
| 978 |
+
previous_head = None
|
| 979 |
+
|
| 980 |
+
for edge in nx.edge_dfs(G, start_node, orientation):
|
| 981 |
+
# Determine if this edge is a continuation of the active path.
|
| 982 |
+
tail, head = tailhead(edge)
|
| 983 |
+
if head in explored:
|
| 984 |
+
# Then we've already explored it. No loop is possible.
|
| 985 |
+
continue
|
| 986 |
+
if previous_head is not None and tail != previous_head:
|
| 987 |
+
# This edge results from backtracking.
|
| 988 |
+
# Pop until we get a node whose head equals the current tail.
|
| 989 |
+
# So for example, we might have:
|
| 990 |
+
# (0, 1), (1, 2), (2, 3), (1, 4)
|
| 991 |
+
# which must become:
|
| 992 |
+
# (0, 1), (1, 4)
|
| 993 |
+
while True:
|
| 994 |
+
try:
|
| 995 |
+
popped_edge = edges.pop()
|
| 996 |
+
except IndexError:
|
| 997 |
+
edges = []
|
| 998 |
+
active_nodes = {tail}
|
| 999 |
+
break
|
| 1000 |
+
else:
|
| 1001 |
+
popped_head = tailhead(popped_edge)[1]
|
| 1002 |
+
active_nodes.remove(popped_head)
|
| 1003 |
+
|
| 1004 |
+
if edges:
|
| 1005 |
+
last_head = tailhead(edges[-1])[1]
|
| 1006 |
+
if tail == last_head:
|
| 1007 |
+
break
|
| 1008 |
+
edges.append(edge)
|
| 1009 |
+
|
| 1010 |
+
if head in active_nodes:
|
| 1011 |
+
# We have a loop!
|
| 1012 |
+
cycle.extend(edges)
|
| 1013 |
+
final_node = head
|
| 1014 |
+
break
|
| 1015 |
+
else:
|
| 1016 |
+
seen.add(head)
|
| 1017 |
+
active_nodes.add(head)
|
| 1018 |
+
previous_head = head
|
| 1019 |
+
|
| 1020 |
+
if cycle:
|
| 1021 |
+
break
|
| 1022 |
+
else:
|
| 1023 |
+
explored.update(seen)
|
| 1024 |
+
|
| 1025 |
+
else:
|
| 1026 |
+
assert len(cycle) == 0
|
| 1027 |
+
raise nx.exception.NetworkXNoCycle("No cycle found.")
|
| 1028 |
+
|
| 1029 |
+
# We now have a list of edges which ends on a cycle.
|
| 1030 |
+
# So we need to remove from the beginning edges that are not relevant.
|
| 1031 |
+
|
| 1032 |
+
for i, edge in enumerate(cycle):
|
| 1033 |
+
tail, head = tailhead(edge)
|
| 1034 |
+
if tail == final_node:
|
| 1035 |
+
break
|
| 1036 |
+
|
| 1037 |
+
return cycle[i:]
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
@not_implemented_for("directed")
|
| 1041 |
+
@not_implemented_for("multigraph")
|
| 1042 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 1043 |
+
def minimum_cycle_basis(G, weight=None):
|
| 1044 |
+
"""Returns a minimum weight cycle basis for G
|
| 1045 |
+
|
| 1046 |
+
Minimum weight means a cycle basis for which the total weight
|
| 1047 |
+
(length for unweighted graphs) of all the cycles is minimum.
|
| 1048 |
+
|
| 1049 |
+
Parameters
|
| 1050 |
+
----------
|
| 1051 |
+
G : NetworkX Graph
|
| 1052 |
+
weight: string
|
| 1053 |
+
name of the edge attribute to use for edge weights
|
| 1054 |
+
|
| 1055 |
+
Returns
|
| 1056 |
+
-------
|
| 1057 |
+
A list of cycle lists. Each cycle list is a list of nodes
|
| 1058 |
+
which forms a cycle (loop) in G. Note that the nodes are not
|
| 1059 |
+
necessarily returned in a order by which they appear in the cycle
|
| 1060 |
+
|
| 1061 |
+
Examples
|
| 1062 |
+
--------
|
| 1063 |
+
>>> G = nx.Graph()
|
| 1064 |
+
>>> nx.add_cycle(G, [0, 1, 2, 3])
|
| 1065 |
+
>>> nx.add_cycle(G, [0, 3, 4, 5])
|
| 1066 |
+
>>> nx.minimum_cycle_basis(G)
|
| 1067 |
+
[[5, 4, 3, 0], [3, 2, 1, 0]]
|
| 1068 |
+
|
| 1069 |
+
References:
|
| 1070 |
+
[1] Kavitha, Telikepalli, et al. "An O(m^2n) Algorithm for
|
| 1071 |
+
Minimum Cycle Basis of Graphs."
|
| 1072 |
+
http://link.springer.com/article/10.1007/s00453-007-9064-z
|
| 1073 |
+
[2] de Pina, J. 1995. Applications of shortest path methods.
|
| 1074 |
+
Ph.D. thesis, University of Amsterdam, Netherlands
|
| 1075 |
+
|
| 1076 |
+
See Also
|
| 1077 |
+
--------
|
| 1078 |
+
simple_cycles, cycle_basis
|
| 1079 |
+
"""
|
| 1080 |
+
# We first split the graph in connected subgraphs
|
| 1081 |
+
return sum(
|
| 1082 |
+
(_min_cycle_basis(G.subgraph(c), weight) for c in nx.connected_components(G)),
|
| 1083 |
+
[],
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
|
| 1087 |
+
def _min_cycle_basis(G, weight):
|
| 1088 |
+
cb = []
|
| 1089 |
+
# We extract the edges not in a spanning tree. We do not really need a
|
| 1090 |
+
# *minimum* spanning tree. That is why we call the next function with
|
| 1091 |
+
# weight=None. Depending on implementation, it may be faster as well
|
| 1092 |
+
tree_edges = list(nx.minimum_spanning_edges(G, weight=None, data=False))
|
| 1093 |
+
chords = G.edges - tree_edges - {(v, u) for u, v in tree_edges}
|
| 1094 |
+
|
| 1095 |
+
# We maintain a set of vectors orthogonal to sofar found cycles
|
| 1096 |
+
set_orth = [{edge} for edge in chords]
|
| 1097 |
+
while set_orth:
|
| 1098 |
+
base = set_orth.pop()
|
| 1099 |
+
# kth cycle is "parallel" to kth vector in set_orth
|
| 1100 |
+
cycle_edges = _min_cycle(G, base, weight)
|
| 1101 |
+
cb.append([v for u, v in cycle_edges])
|
| 1102 |
+
|
| 1103 |
+
# now update set_orth so that k+1,k+2... th elements are
|
| 1104 |
+
# orthogonal to the newly found cycle, as per [p. 336, 1]
|
| 1105 |
+
set_orth = [
|
| 1106 |
+
(
|
| 1107 |
+
{e for e in orth if e not in base if e[::-1] not in base}
|
| 1108 |
+
| {e for e in base if e not in orth if e[::-1] not in orth}
|
| 1109 |
+
)
|
| 1110 |
+
if sum((e in orth or e[::-1] in orth) for e in cycle_edges) % 2
|
| 1111 |
+
else orth
|
| 1112 |
+
for orth in set_orth
|
| 1113 |
+
]
|
| 1114 |
+
return cb
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
def _min_cycle(G, orth, weight):
|
| 1118 |
+
"""
|
| 1119 |
+
Computes the minimum weight cycle in G,
|
| 1120 |
+
orthogonal to the vector orth as per [p. 338, 1]
|
| 1121 |
+
Use (u, 1) to indicate the lifted copy of u (denoted u' in paper).
|
| 1122 |
+
"""
|
| 1123 |
+
Gi = nx.Graph()
|
| 1124 |
+
|
| 1125 |
+
# Add 2 copies of each edge in G to Gi.
|
| 1126 |
+
# If edge is in orth, add cross edge; otherwise in-plane edge
|
| 1127 |
+
for u, v, wt in G.edges(data=weight, default=1):
|
| 1128 |
+
if (u, v) in orth or (v, u) in orth:
|
| 1129 |
+
Gi.add_edges_from([(u, (v, 1)), ((u, 1), v)], Gi_weight=wt)
|
| 1130 |
+
else:
|
| 1131 |
+
Gi.add_edges_from([(u, v), ((u, 1), (v, 1))], Gi_weight=wt)
|
| 1132 |
+
|
| 1133 |
+
# find the shortest length in Gi between n and (n, 1) for each n
|
| 1134 |
+
# Note: Use "Gi_weight" for name of weight attribute
|
| 1135 |
+
spl = nx.shortest_path_length
|
| 1136 |
+
lift = {n: spl(Gi, source=n, target=(n, 1), weight="Gi_weight") for n in G}
|
| 1137 |
+
|
| 1138 |
+
# Now compute that short path in Gi, which translates to a cycle in G
|
| 1139 |
+
start = min(lift, key=lift.get)
|
| 1140 |
+
end = (start, 1)
|
| 1141 |
+
min_path_i = nx.shortest_path(Gi, source=start, target=end, weight="Gi_weight")
|
| 1142 |
+
|
| 1143 |
+
# Now we obtain the actual path, re-map nodes in Gi to those in G
|
| 1144 |
+
min_path = [n if n in G else n[0] for n in min_path_i]
|
| 1145 |
+
|
| 1146 |
+
# Now remove the edges that occur two times
|
| 1147 |
+
# two passes: flag which edges get kept, then build it
|
| 1148 |
+
edgelist = list(pairwise(min_path))
|
| 1149 |
+
edgeset = set()
|
| 1150 |
+
for e in edgelist:
|
| 1151 |
+
if e in edgeset:
|
| 1152 |
+
edgeset.remove(e)
|
| 1153 |
+
elif e[::-1] in edgeset:
|
| 1154 |
+
edgeset.remove(e[::-1])
|
| 1155 |
+
else:
|
| 1156 |
+
edgeset.add(e)
|
| 1157 |
+
|
| 1158 |
+
min_edgelist = []
|
| 1159 |
+
for e in edgelist:
|
| 1160 |
+
if e in edgeset:
|
| 1161 |
+
min_edgelist.append(e)
|
| 1162 |
+
edgeset.remove(e)
|
| 1163 |
+
elif e[::-1] in edgeset:
|
| 1164 |
+
min_edgelist.append(e[::-1])
|
| 1165 |
+
edgeset.remove(e[::-1])
|
| 1166 |
+
|
| 1167 |
+
return min_edgelist
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
@not_implemented_for("directed")
|
| 1171 |
+
@not_implemented_for("multigraph")
|
| 1172 |
+
@nx._dispatchable
|
| 1173 |
+
def girth(G):
|
| 1174 |
+
"""Returns the girth of the graph.
|
| 1175 |
+
|
| 1176 |
+
The girth of a graph is the length of its shortest cycle, or infinity if
|
| 1177 |
+
the graph is acyclic. The algorithm follows the description given on the
|
| 1178 |
+
Wikipedia page [1]_, and runs in time O(mn) on a graph with m edges and n
|
| 1179 |
+
nodes.
|
| 1180 |
+
|
| 1181 |
+
Parameters
|
| 1182 |
+
----------
|
| 1183 |
+
G : NetworkX Graph
|
| 1184 |
+
|
| 1185 |
+
Returns
|
| 1186 |
+
-------
|
| 1187 |
+
int or math.inf
|
| 1188 |
+
|
| 1189 |
+
Examples
|
| 1190 |
+
--------
|
| 1191 |
+
All examples below (except P_5) can easily be checked using Wikipedia,
|
| 1192 |
+
which has a page for each of these famous graphs.
|
| 1193 |
+
|
| 1194 |
+
>>> nx.girth(nx.chvatal_graph())
|
| 1195 |
+
4
|
| 1196 |
+
>>> nx.girth(nx.tutte_graph())
|
| 1197 |
+
4
|
| 1198 |
+
>>> nx.girth(nx.petersen_graph())
|
| 1199 |
+
5
|
| 1200 |
+
>>> nx.girth(nx.heawood_graph())
|
| 1201 |
+
6
|
| 1202 |
+
>>> nx.girth(nx.pappus_graph())
|
| 1203 |
+
6
|
| 1204 |
+
>>> nx.girth(nx.path_graph(5))
|
| 1205 |
+
inf
|
| 1206 |
+
|
| 1207 |
+
References
|
| 1208 |
+
----------
|
| 1209 |
+
.. [1] `Wikipedia: Girth <https://en.wikipedia.org/wiki/Girth_(graph_theory)>`_
|
| 1210 |
+
|
| 1211 |
+
"""
|
| 1212 |
+
girth = depth_limit = inf
|
| 1213 |
+
tree_edge = nx.algorithms.traversal.breadth_first_search.TREE_EDGE
|
| 1214 |
+
level_edge = nx.algorithms.traversal.breadth_first_search.LEVEL_EDGE
|
| 1215 |
+
for n in G:
|
| 1216 |
+
# run a BFS from source n, keeping track of distances; since we want
|
| 1217 |
+
# the shortest cycle, no need to explore beyond the current minimum length
|
| 1218 |
+
depth = {n: 0}
|
| 1219 |
+
for u, v, label in nx.bfs_labeled_edges(G, n):
|
| 1220 |
+
du = depth[u]
|
| 1221 |
+
if du > depth_limit:
|
| 1222 |
+
break
|
| 1223 |
+
if label is tree_edge:
|
| 1224 |
+
depth[v] = du + 1
|
| 1225 |
+
else:
|
| 1226 |
+
# if (u, v) is a level edge, the length is du + du + 1 (odd)
|
| 1227 |
+
# otherwise, it's a forward edge; length is du + (du + 1) + 1 (even)
|
| 1228 |
+
delta = label is level_edge
|
| 1229 |
+
length = du + du + 2 - delta
|
| 1230 |
+
if length < girth:
|
| 1231 |
+
girth = length
|
| 1232 |
+
depth_limit = du - delta
|
| 1233 |
+
|
| 1234 |
+
return girth
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/d_separation.py
ADDED
|
@@ -0,0 +1,677 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Algorithm for testing d-separation in DAGs.
|
| 3 |
+
|
| 4 |
+
*d-separation* is a test for conditional independence in probability
|
| 5 |
+
distributions that can be factorized using DAGs. It is a purely
|
| 6 |
+
graphical test that uses the underlying graph and makes no reference
|
| 7 |
+
to the actual distribution parameters. See [1]_ for a formal
|
| 8 |
+
definition.
|
| 9 |
+
|
| 10 |
+
The implementation is based on the conceptually simple linear time
|
| 11 |
+
algorithm presented in [2]_. Refer to [3]_, [4]_ for a couple of
|
| 12 |
+
alternative algorithms.
|
| 13 |
+
|
| 14 |
+
The functional interface in NetworkX consists of three functions:
|
| 15 |
+
|
| 16 |
+
- `find_minimal_d_separator` returns a minimal d-separator set ``z``.
|
| 17 |
+
That is, removing any node or nodes from it makes it no longer a d-separator.
|
| 18 |
+
- `is_d_separator` checks if a given set is a d-separator.
|
| 19 |
+
- `is_minimal_d_separator` checks if a given set is a minimal d-separator.
|
| 20 |
+
|
| 21 |
+
D-separators
|
| 22 |
+
------------
|
| 23 |
+
|
| 24 |
+
Here, we provide a brief overview of d-separation and related concepts that
|
| 25 |
+
are relevant for understanding it:
|
| 26 |
+
|
| 27 |
+
The ideas of d-separation and d-connection relate to paths being open or blocked.
|
| 28 |
+
|
| 29 |
+
- A "path" is a sequence of nodes connected in order by edges. Unlike for most
|
| 30 |
+
graph theory analysis, the direction of the edges is ignored. Thus the path
|
| 31 |
+
can be thought of as a traditional path on the undirected version of the graph.
|
| 32 |
+
- A "candidate d-separator" ``z`` is a set of nodes being considered as
|
| 33 |
+
possibly blocking all paths between two prescribed sets ``x`` and ``y`` of nodes.
|
| 34 |
+
We refer to each node in the candidate d-separator as "known".
|
| 35 |
+
- A "collider" node on a path is a node that is a successor of its two neighbor
|
| 36 |
+
nodes on the path. That is, ``c`` is a collider if the edge directions
|
| 37 |
+
along the path look like ``... u -> c <- v ...``.
|
| 38 |
+
- If a collider node or any of its descendants are "known", the collider
|
| 39 |
+
is called an "open collider". Otherwise it is a "blocking collider".
|
| 40 |
+
- Any path can be "blocked" in two ways. If the path contains a "known" node
|
| 41 |
+
that is not a collider, the path is blocked. Also, if the path contains a
|
| 42 |
+
collider that is not a "known" node, the path is blocked.
|
| 43 |
+
- A path is "open" if it is not blocked. That is, it is open if every node is
|
| 44 |
+
either an open collider or not a "known". Said another way, every
|
| 45 |
+
"known" in the path is a collider and every collider is open (has a
|
| 46 |
+
"known" as a inclusive descendant). The concept of "open path" is meant to
|
| 47 |
+
demonstrate a probabilistic conditional dependence between two nodes given
|
| 48 |
+
prescribed knowledge ("known" nodes).
|
| 49 |
+
- Two sets ``x`` and ``y`` of nodes are "d-separated" by a set of nodes ``z``
|
| 50 |
+
if all paths between nodes in ``x`` and nodes in ``y`` are blocked. That is,
|
| 51 |
+
if there are no open paths from any node in ``x`` to any node in ``y``.
|
| 52 |
+
Such a set ``z`` is a "d-separator" of ``x`` and ``y``.
|
| 53 |
+
- A "minimal d-separator" is a d-separator ``z`` for which no node or subset
|
| 54 |
+
of nodes can be removed with it still being a d-separator.
|
| 55 |
+
|
| 56 |
+
The d-separator blocks some paths between ``x`` and ``y`` but opens others.
|
| 57 |
+
Nodes in the d-separator block paths if the nodes are not colliders.
|
| 58 |
+
But if a collider or its descendant nodes are in the d-separation set, the
|
| 59 |
+
colliders are open, allowing a path through that collider.
|
| 60 |
+
|
| 61 |
+
Illustration of D-separation with examples
|
| 62 |
+
------------------------------------------
|
| 63 |
+
|
| 64 |
+
A pair of two nodes, ``u`` and ``v``, are d-connected if there is a path
|
| 65 |
+
from ``u`` to ``v`` that is not blocked. That means, there is an open
|
| 66 |
+
path from ``u`` to ``v``.
|
| 67 |
+
|
| 68 |
+
For example, if the d-separating set is the empty set, then the following paths are
|
| 69 |
+
open between ``u`` and ``v``:
|
| 70 |
+
|
| 71 |
+
- u <- n -> v
|
| 72 |
+
- u -> w -> ... -> n -> v
|
| 73 |
+
|
| 74 |
+
If on the other hand, ``n`` is in the d-separating set, then ``n`` blocks
|
| 75 |
+
those paths between ``u`` and ``v``.
|
| 76 |
+
|
| 77 |
+
Colliders block a path if they and their descendants are not included
|
| 78 |
+
in the d-separating set. An example of a path that is blocked when the
|
| 79 |
+
d-separating set is empty is:
|
| 80 |
+
|
| 81 |
+
- u -> w -> ... -> n <- v
|
| 82 |
+
|
| 83 |
+
The node ``n`` is a collider in this path and is not in the d-separating set.
|
| 84 |
+
So ``n`` blocks this path. However, if ``n`` or a descendant of ``n`` is
|
| 85 |
+
included in the d-separating set, then the path through the collider
|
| 86 |
+
at ``n`` (... -> n <- ...) is "open".
|
| 87 |
+
|
| 88 |
+
D-separation is concerned with blocking all paths between nodes from ``x`` to ``y``.
|
| 89 |
+
A d-separating set between ``x`` and ``y`` is one where all paths are blocked.
|
| 90 |
+
|
| 91 |
+
D-separation and its applications in probability
|
| 92 |
+
------------------------------------------------
|
| 93 |
+
|
| 94 |
+
D-separation is commonly used in probabilistic causal-graph models. D-separation
|
| 95 |
+
connects the idea of probabilistic "dependence" with separation in a graph. If
|
| 96 |
+
one assumes the causal Markov condition [5]_, (every node is conditionally
|
| 97 |
+
independent of its non-descendants, given its parents) then d-separation implies
|
| 98 |
+
conditional independence in probability distributions.
|
| 99 |
+
Symmetrically, d-connection implies dependence.
|
| 100 |
+
|
| 101 |
+
The intuition is as follows. The edges on a causal graph indicate which nodes
|
| 102 |
+
influence the outcome of other nodes directly. An edge from u to v
|
| 103 |
+
implies that the outcome of event ``u`` influences the probabilities for
|
| 104 |
+
the outcome of event ``v``. Certainly knowing ``u`` changes predictions for ``v``.
|
| 105 |
+
But also knowing ``v`` changes predictions for ``u``. The outcomes are dependent.
|
| 106 |
+
Furthermore, an edge from ``v`` to ``w`` would mean that ``w`` and ``v`` are dependent
|
| 107 |
+
and thus that ``u`` could indirectly influence ``w``.
|
| 108 |
+
|
| 109 |
+
Without any knowledge about the system (candidate d-separating set is empty)
|
| 110 |
+
a causal graph ``u -> v -> w`` allows all three nodes to be dependent. But
|
| 111 |
+
if we know the outcome of ``v``, the conditional probabilities of outcomes for
|
| 112 |
+
``u`` and ``w`` are independent of each other. That is, once we know the outcome
|
| 113 |
+
for ``v``, the probabilities for ``w`` do not depend on the outcome for ``u``.
|
| 114 |
+
This is the idea behind ``v`` blocking the path if it is "known" (in the candidate
|
| 115 |
+
d-separating set).
|
| 116 |
+
|
| 117 |
+
The same argument works whether the direction of the edges are both
|
| 118 |
+
left-going and when both arrows head out from the middle. Having a "known"
|
| 119 |
+
node on a path blocks the collider-free path because those relationships
|
| 120 |
+
make the conditional probabilities independent.
|
| 121 |
+
|
| 122 |
+
The direction of the causal edges does impact dependence precisely in the
|
| 123 |
+
case of a collider e.g. ``u -> v <- w``. In that situation, both ``u`` and ``w``
|
| 124 |
+
influence ``v``. But they do not directly influence each other. So without any
|
| 125 |
+
knowledge of any outcomes, ``u`` and ``w`` are independent. That is the idea behind
|
| 126 |
+
colliders blocking the path. But, if ``v`` is known, the conditional probabilities
|
| 127 |
+
of ``u`` and ``w`` can be dependent. This is the heart of Berkson's Paradox [6]_.
|
| 128 |
+
For example, suppose ``u`` and ``w`` are boolean events (they either happen or do not)
|
| 129 |
+
and ``v`` represents the outcome "at least one of ``u`` and ``w`` occur". Then knowing
|
| 130 |
+
``v`` is true makes the conditional probabilities of ``u`` and ``w`` dependent.
|
| 131 |
+
Essentially, knowing that at least one of them is true raises the probability of
|
| 132 |
+
each. But further knowledge that ``w`` is true (or false) change the conditional
|
| 133 |
+
probability of ``u`` to either the original value or 1. So the conditional
|
| 134 |
+
probability of ``u`` depends on the outcome of ``w`` even though there is no
|
| 135 |
+
causal relationship between them. When a collider is known, dependence can
|
| 136 |
+
occur across paths through that collider. This is the reason open colliders
|
| 137 |
+
do not block paths.
|
| 138 |
+
|
| 139 |
+
Furthermore, even if ``v`` is not "known", if one of its descendants is "known"
|
| 140 |
+
we can use that information to know more about ``v`` which again makes
|
| 141 |
+
``u`` and ``w`` potentially dependent. Suppose the chance of ``n`` occurring
|
| 142 |
+
is much higher when ``v`` occurs ("at least one of ``u`` and ``w`` occur").
|
| 143 |
+
Then if we know ``n`` occurred, it is more likely that ``v`` occurred and that
|
| 144 |
+
makes the chance of ``u`` and ``w`` dependent. This is the idea behind why
|
| 145 |
+
a collider does no block a path if any descendant of the collider is "known".
|
| 146 |
+
|
| 147 |
+
When two sets of nodes ``x`` and ``y`` are d-separated by a set ``z``,
|
| 148 |
+
it means that given the outcomes of the nodes in ``z``, the probabilities
|
| 149 |
+
of outcomes of the nodes in ``x`` are independent of the outcomes of the
|
| 150 |
+
nodes in ``y`` and vice versa.
|
| 151 |
+
|
| 152 |
+
Examples
|
| 153 |
+
--------
|
| 154 |
+
A Hidden Markov Model with 5 observed states and 5 hidden states
|
| 155 |
+
where the hidden states have causal relationships resulting in
|
| 156 |
+
a path results in the following causal network. We check that
|
| 157 |
+
early states along the path are separated from late state in
|
| 158 |
+
the path by the d-separator of the middle hidden state.
|
| 159 |
+
Thus if we condition on the middle hidden state, the early
|
| 160 |
+
state probabilities are independent of the late state outcomes.
|
| 161 |
+
|
| 162 |
+
>>> G = nx.DiGraph()
|
| 163 |
+
>>> G.add_edges_from(
|
| 164 |
+
... [
|
| 165 |
+
... ("H1", "H2"),
|
| 166 |
+
... ("H2", "H3"),
|
| 167 |
+
... ("H3", "H4"),
|
| 168 |
+
... ("H4", "H5"),
|
| 169 |
+
... ("H1", "O1"),
|
| 170 |
+
... ("H2", "O2"),
|
| 171 |
+
... ("H3", "O3"),
|
| 172 |
+
... ("H4", "O4"),
|
| 173 |
+
... ("H5", "O5"),
|
| 174 |
+
... ]
|
| 175 |
+
... )
|
| 176 |
+
>>> x, y, z = ({"H1", "O1"}, {"H5", "O5"}, {"H3"})
|
| 177 |
+
>>> nx.is_d_separator(G, x, y, z)
|
| 178 |
+
True
|
| 179 |
+
>>> nx.is_minimal_d_separator(G, x, y, z)
|
| 180 |
+
True
|
| 181 |
+
>>> nx.is_minimal_d_separator(G, x, y, z | {"O3"})
|
| 182 |
+
False
|
| 183 |
+
>>> z = nx.find_minimal_d_separator(G, x | y, {"O2", "O3", "O4"})
|
| 184 |
+
>>> z == {"H2", "H4"}
|
| 185 |
+
True
|
| 186 |
+
|
| 187 |
+
If no minimal_d_separator exists, `None` is returned
|
| 188 |
+
|
| 189 |
+
>>> other_z = nx.find_minimal_d_separator(G, x | y, {"H2", "H3"})
|
| 190 |
+
>>> other_z is None
|
| 191 |
+
True
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
References
|
| 195 |
+
----------
|
| 196 |
+
|
| 197 |
+
.. [1] Pearl, J. (2009). Causality. Cambridge: Cambridge University Press.
|
| 198 |
+
|
| 199 |
+
.. [2] Darwiche, A. (2009). Modeling and reasoning with Bayesian networks.
|
| 200 |
+
Cambridge: Cambridge University Press.
|
| 201 |
+
|
| 202 |
+
.. [3] Shachter, Ross D. "Bayes-ball: The rational pastime (for
|
| 203 |
+
determining irrelevance and requisite information in belief networks
|
| 204 |
+
and influence diagrams)." In Proceedings of the Fourteenth Conference
|
| 205 |
+
on Uncertainty in Artificial Intelligence (UAI), (pp. 480–487). 1998.
|
| 206 |
+
|
| 207 |
+
.. [4] Koller, D., & Friedman, N. (2009).
|
| 208 |
+
Probabilistic graphical models: principles and techniques. The MIT Press.
|
| 209 |
+
|
| 210 |
+
.. [5] https://en.wikipedia.org/wiki/Causal_Markov_condition
|
| 211 |
+
|
| 212 |
+
.. [6] https://en.wikipedia.org/wiki/Berkson%27s_paradox
|
| 213 |
+
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
from collections import deque
|
| 217 |
+
from itertools import chain
|
| 218 |
+
|
| 219 |
+
import networkx as nx
|
| 220 |
+
from networkx.utils import UnionFind, not_implemented_for
|
| 221 |
+
|
| 222 |
+
__all__ = [
|
| 223 |
+
"is_d_separator",
|
| 224 |
+
"is_minimal_d_separator",
|
| 225 |
+
"find_minimal_d_separator",
|
| 226 |
+
]
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@not_implemented_for("undirected")
|
| 230 |
+
@nx._dispatchable
|
| 231 |
+
def is_d_separator(G, x, y, z):
|
| 232 |
+
"""Return whether node sets `x` and `y` are d-separated by `z`.
|
| 233 |
+
|
| 234 |
+
Parameters
|
| 235 |
+
----------
|
| 236 |
+
G : nx.DiGraph
|
| 237 |
+
A NetworkX DAG.
|
| 238 |
+
|
| 239 |
+
x : node or set of nodes
|
| 240 |
+
First node or set of nodes in `G`.
|
| 241 |
+
|
| 242 |
+
y : node or set of nodes
|
| 243 |
+
Second node or set of nodes in `G`.
|
| 244 |
+
|
| 245 |
+
z : node or set of nodes
|
| 246 |
+
Potential separator (set of conditioning nodes in `G`). Can be empty set.
|
| 247 |
+
|
| 248 |
+
Returns
|
| 249 |
+
-------
|
| 250 |
+
b : bool
|
| 251 |
+
A boolean that is true if `x` is d-separated from `y` given `z` in `G`.
|
| 252 |
+
|
| 253 |
+
Raises
|
| 254 |
+
------
|
| 255 |
+
NetworkXError
|
| 256 |
+
The *d-separation* test is commonly used on disjoint sets of
|
| 257 |
+
nodes in acyclic directed graphs. Accordingly, the algorithm
|
| 258 |
+
raises a :exc:`NetworkXError` if the node sets are not
|
| 259 |
+
disjoint or if the input graph is not a DAG.
|
| 260 |
+
|
| 261 |
+
NodeNotFound
|
| 262 |
+
If any of the input nodes are not found in the graph,
|
| 263 |
+
a :exc:`NodeNotFound` exception is raised
|
| 264 |
+
|
| 265 |
+
Notes
|
| 266 |
+
-----
|
| 267 |
+
A d-separating set in a DAG is a set of nodes that
|
| 268 |
+
blocks all paths between the two sets. Nodes in `z`
|
| 269 |
+
block a path if they are part of the path and are not a collider,
|
| 270 |
+
or a descendant of a collider. Also colliders that are not in `z`
|
| 271 |
+
block a path. A collider structure along a path
|
| 272 |
+
is ``... -> c <- ...`` where ``c`` is the collider node.
|
| 273 |
+
|
| 274 |
+
https://en.wikipedia.org/wiki/Bayesian_network#d-separation
|
| 275 |
+
"""
|
| 276 |
+
try:
|
| 277 |
+
x = {x} if x in G else x
|
| 278 |
+
y = {y} if y in G else y
|
| 279 |
+
z = {z} if z in G else z
|
| 280 |
+
|
| 281 |
+
intersection = x & y or x & z or y & z
|
| 282 |
+
if intersection:
|
| 283 |
+
raise nx.NetworkXError(
|
| 284 |
+
f"The sets are not disjoint, with intersection {intersection}"
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
set_v = x | y | z
|
| 288 |
+
if set_v - G.nodes:
|
| 289 |
+
raise nx.NodeNotFound(f"The node(s) {set_v - G.nodes} are not found in G")
|
| 290 |
+
except TypeError:
|
| 291 |
+
raise nx.NodeNotFound("One of x, y, or z is not a node or a set of nodes in G")
|
| 292 |
+
|
| 293 |
+
if not nx.is_directed_acyclic_graph(G):
|
| 294 |
+
raise nx.NetworkXError("graph should be directed acyclic")
|
| 295 |
+
|
| 296 |
+
# contains -> and <-> edges from starting node T
|
| 297 |
+
forward_deque = deque([])
|
| 298 |
+
forward_visited = set()
|
| 299 |
+
|
| 300 |
+
# contains <- and - edges from starting node T
|
| 301 |
+
backward_deque = deque(x)
|
| 302 |
+
backward_visited = set()
|
| 303 |
+
|
| 304 |
+
ancestors_or_z = set().union(*[nx.ancestors(G, node) for node in x]) | z | x
|
| 305 |
+
|
| 306 |
+
while forward_deque or backward_deque:
|
| 307 |
+
if backward_deque:
|
| 308 |
+
node = backward_deque.popleft()
|
| 309 |
+
backward_visited.add(node)
|
| 310 |
+
if node in y:
|
| 311 |
+
return False
|
| 312 |
+
if node in z:
|
| 313 |
+
continue
|
| 314 |
+
|
| 315 |
+
# add <- edges to backward deque
|
| 316 |
+
backward_deque.extend(G.pred[node].keys() - backward_visited)
|
| 317 |
+
# add -> edges to forward deque
|
| 318 |
+
forward_deque.extend(G.succ[node].keys() - forward_visited)
|
| 319 |
+
|
| 320 |
+
if forward_deque:
|
| 321 |
+
node = forward_deque.popleft()
|
| 322 |
+
forward_visited.add(node)
|
| 323 |
+
if node in y:
|
| 324 |
+
return False
|
| 325 |
+
|
| 326 |
+
# Consider if -> node <- is opened due to ancestor of node in z
|
| 327 |
+
if node in ancestors_or_z:
|
| 328 |
+
# add <- edges to backward deque
|
| 329 |
+
backward_deque.extend(G.pred[node].keys() - backward_visited)
|
| 330 |
+
if node not in z:
|
| 331 |
+
# add -> edges to forward deque
|
| 332 |
+
forward_deque.extend(G.succ[node].keys() - forward_visited)
|
| 333 |
+
|
| 334 |
+
return True
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
@not_implemented_for("undirected")
|
| 338 |
+
@nx._dispatchable
|
| 339 |
+
def find_minimal_d_separator(G, x, y, *, included=None, restricted=None):
|
| 340 |
+
"""Returns a minimal d-separating set between `x` and `y` if possible
|
| 341 |
+
|
| 342 |
+
A d-separating set in a DAG is a set of nodes that blocks all
|
| 343 |
+
paths between the two sets of nodes, `x` and `y`. This function
|
| 344 |
+
constructs a d-separating set that is "minimal", meaning no nodes can
|
| 345 |
+
be removed without it losing the d-separating property for `x` and `y`.
|
| 346 |
+
If no d-separating sets exist for `x` and `y`, this returns `None`.
|
| 347 |
+
|
| 348 |
+
In a DAG there may be more than one minimal d-separator between two
|
| 349 |
+
sets of nodes. Minimal d-separators are not always unique. This function
|
| 350 |
+
returns one minimal d-separator, or `None` if no d-separator exists.
|
| 351 |
+
|
| 352 |
+
Uses the algorithm presented in [1]_. The complexity of the algorithm
|
| 353 |
+
is :math:`O(m)`, where :math:`m` stands for the number of edges in
|
| 354 |
+
the subgraph of G consisting of only the ancestors of `x` and `y`.
|
| 355 |
+
For full details, see [1]_.
|
| 356 |
+
|
| 357 |
+
Parameters
|
| 358 |
+
----------
|
| 359 |
+
G : graph
|
| 360 |
+
A networkx DAG.
|
| 361 |
+
x : set | node
|
| 362 |
+
A node or set of nodes in the graph.
|
| 363 |
+
y : set | node
|
| 364 |
+
A node or set of nodes in the graph.
|
| 365 |
+
included : set | node | None
|
| 366 |
+
A node or set of nodes which must be included in the found separating set,
|
| 367 |
+
default is None, which means the empty set.
|
| 368 |
+
restricted : set | node | None
|
| 369 |
+
Restricted node or set of nodes to consider. Only these nodes can be in
|
| 370 |
+
the found separating set, default is None meaning all nodes in ``G``.
|
| 371 |
+
|
| 372 |
+
Returns
|
| 373 |
+
-------
|
| 374 |
+
z : set | None
|
| 375 |
+
The minimal d-separating set, if at least one d-separating set exists,
|
| 376 |
+
otherwise None.
|
| 377 |
+
|
| 378 |
+
Raises
|
| 379 |
+
------
|
| 380 |
+
NetworkXError
|
| 381 |
+
Raises a :exc:`NetworkXError` if the input graph is not a DAG
|
| 382 |
+
or if node sets `x`, `y`, and `included` are not disjoint.
|
| 383 |
+
|
| 384 |
+
NodeNotFound
|
| 385 |
+
If any of the input nodes are not found in the graph,
|
| 386 |
+
a :exc:`NodeNotFound` exception is raised.
|
| 387 |
+
|
| 388 |
+
References
|
| 389 |
+
----------
|
| 390 |
+
.. [1] van der Zander, Benito, and Maciej Liśkiewicz. "Finding
|
| 391 |
+
minimal d-separators in linear time and applications." In
|
| 392 |
+
Uncertainty in Artificial Intelligence, pp. 637-647. PMLR, 2020.
|
| 393 |
+
"""
|
| 394 |
+
if not nx.is_directed_acyclic_graph(G):
|
| 395 |
+
raise nx.NetworkXError("graph should be directed acyclic")
|
| 396 |
+
|
| 397 |
+
try:
|
| 398 |
+
x = {x} if x in G else x
|
| 399 |
+
y = {y} if y in G else y
|
| 400 |
+
|
| 401 |
+
if included is None:
|
| 402 |
+
included = set()
|
| 403 |
+
elif included in G:
|
| 404 |
+
included = {included}
|
| 405 |
+
|
| 406 |
+
if restricted is None:
|
| 407 |
+
restricted = set(G)
|
| 408 |
+
elif restricted in G:
|
| 409 |
+
restricted = {restricted}
|
| 410 |
+
|
| 411 |
+
set_y = x | y | included | restricted
|
| 412 |
+
if set_y - G.nodes:
|
| 413 |
+
raise nx.NodeNotFound(f"The node(s) {set_y - G.nodes} are not found in G")
|
| 414 |
+
except TypeError:
|
| 415 |
+
raise nx.NodeNotFound(
|
| 416 |
+
"One of x, y, included or restricted is not a node or set of nodes in G"
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
if not included <= restricted:
|
| 420 |
+
raise nx.NetworkXError(
|
| 421 |
+
f"Included nodes {included} must be in restricted nodes {restricted}"
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
intersection = x & y or x & included or y & included
|
| 425 |
+
if intersection:
|
| 426 |
+
raise nx.NetworkXError(
|
| 427 |
+
f"The sets x, y, included are not disjoint. Overlap: {intersection}"
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
nodeset = x | y | included
|
| 431 |
+
ancestors_x_y_included = nodeset.union(*[nx.ancestors(G, node) for node in nodeset])
|
| 432 |
+
|
| 433 |
+
z_init = restricted & (ancestors_x_y_included - (x | y))
|
| 434 |
+
|
| 435 |
+
x_closure = _reachable(G, x, ancestors_x_y_included, z_init)
|
| 436 |
+
if x_closure & y:
|
| 437 |
+
return None
|
| 438 |
+
|
| 439 |
+
z_updated = z_init & (x_closure | included)
|
| 440 |
+
y_closure = _reachable(G, y, ancestors_x_y_included, z_updated)
|
| 441 |
+
return z_updated & (y_closure | included)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
@not_implemented_for("undirected")
|
| 445 |
+
@nx._dispatchable
|
| 446 |
+
def is_minimal_d_separator(G, x, y, z, *, included=None, restricted=None):
|
| 447 |
+
"""Determine if `z` is a minimal d-separator for `x` and `y`.
|
| 448 |
+
|
| 449 |
+
A d-separator, `z`, in a DAG is a set of nodes that blocks
|
| 450 |
+
all paths from nodes in set `x` to nodes in set `y`.
|
| 451 |
+
A minimal d-separator is a d-separator `z` such that removing
|
| 452 |
+
any subset of nodes makes it no longer a d-separator.
|
| 453 |
+
|
| 454 |
+
Note: This function checks whether `z` is a d-separator AND is
|
| 455 |
+
minimal. One can use the function `is_d_separator` to only check if
|
| 456 |
+
`z` is a d-separator. See examples below.
|
| 457 |
+
|
| 458 |
+
Parameters
|
| 459 |
+
----------
|
| 460 |
+
G : nx.DiGraph
|
| 461 |
+
A NetworkX DAG.
|
| 462 |
+
x : node | set
|
| 463 |
+
A node or set of nodes in the graph.
|
| 464 |
+
y : node | set
|
| 465 |
+
A node or set of nodes in the graph.
|
| 466 |
+
z : node | set
|
| 467 |
+
The node or set of nodes to check if it is a minimal d-separating set.
|
| 468 |
+
The function :func:`is_d_separator` is called inside this function
|
| 469 |
+
to verify that `z` is in fact a d-separator.
|
| 470 |
+
included : set | node | None
|
| 471 |
+
A node or set of nodes which must be included in the found separating set,
|
| 472 |
+
default is ``None``, which means the empty set.
|
| 473 |
+
restricted : set | node | None
|
| 474 |
+
Restricted node or set of nodes to consider. Only these nodes can be in
|
| 475 |
+
the found separating set, default is ``None`` meaning all nodes in ``G``.
|
| 476 |
+
|
| 477 |
+
Returns
|
| 478 |
+
-------
|
| 479 |
+
bool
|
| 480 |
+
Whether or not the set `z` is a minimal d-separator subject to
|
| 481 |
+
`restricted` nodes and `included` node constraints.
|
| 482 |
+
|
| 483 |
+
Examples
|
| 484 |
+
--------
|
| 485 |
+
>>> G = nx.path_graph([0, 1, 2, 3], create_using=nx.DiGraph)
|
| 486 |
+
>>> G.add_node(4)
|
| 487 |
+
>>> nx.is_minimal_d_separator(G, 0, 2, {1})
|
| 488 |
+
True
|
| 489 |
+
>>> # since {1} is the minimal d-separator, {1, 3, 4} is not minimal
|
| 490 |
+
>>> nx.is_minimal_d_separator(G, 0, 2, {1, 3, 4})
|
| 491 |
+
False
|
| 492 |
+
>>> # alternatively, if we only want to check that {1, 3, 4} is a d-separator
|
| 493 |
+
>>> nx.is_d_separator(G, 0, 2, {1, 3, 4})
|
| 494 |
+
True
|
| 495 |
+
|
| 496 |
+
Raises
|
| 497 |
+
------
|
| 498 |
+
NetworkXError
|
| 499 |
+
Raises a :exc:`NetworkXError` if the input graph is not a DAG.
|
| 500 |
+
|
| 501 |
+
NodeNotFound
|
| 502 |
+
If any of the input nodes are not found in the graph,
|
| 503 |
+
a :exc:`NodeNotFound` exception is raised.
|
| 504 |
+
|
| 505 |
+
References
|
| 506 |
+
----------
|
| 507 |
+
.. [1] van der Zander, Benito, and Maciej Liśkiewicz. "Finding
|
| 508 |
+
minimal d-separators in linear time and applications." In
|
| 509 |
+
Uncertainty in Artificial Intelligence, pp. 637-647. PMLR, 2020.
|
| 510 |
+
|
| 511 |
+
Notes
|
| 512 |
+
-----
|
| 513 |
+
This function works on verifying that a set is minimal and
|
| 514 |
+
d-separating between two nodes. Uses criterion (a), (b), (c) on
|
| 515 |
+
page 4 of [1]_. a) closure(`x`) and `y` are disjoint. b) `z` contains
|
| 516 |
+
all nodes from `included` and is contained in the `restricted`
|
| 517 |
+
nodes and in the union of ancestors of `x`, `y`, and `included`.
|
| 518 |
+
c) the nodes in `z` not in `included` are contained in both
|
| 519 |
+
closure(x) and closure(y). The closure of a set is the set of nodes
|
| 520 |
+
connected to the set by a directed path in G.
|
| 521 |
+
|
| 522 |
+
The complexity is :math:`O(m)`, where :math:`m` stands for the
|
| 523 |
+
number of edges in the subgraph of G consisting of only the
|
| 524 |
+
ancestors of `x` and `y`.
|
| 525 |
+
|
| 526 |
+
For full details, see [1]_.
|
| 527 |
+
"""
|
| 528 |
+
if not nx.is_directed_acyclic_graph(G):
|
| 529 |
+
raise nx.NetworkXError("graph should be directed acyclic")
|
| 530 |
+
|
| 531 |
+
try:
|
| 532 |
+
x = {x} if x in G else x
|
| 533 |
+
y = {y} if y in G else y
|
| 534 |
+
z = {z} if z in G else z
|
| 535 |
+
|
| 536 |
+
if included is None:
|
| 537 |
+
included = set()
|
| 538 |
+
elif included in G:
|
| 539 |
+
included = {included}
|
| 540 |
+
|
| 541 |
+
if restricted is None:
|
| 542 |
+
restricted = set(G)
|
| 543 |
+
elif restricted in G:
|
| 544 |
+
restricted = {restricted}
|
| 545 |
+
|
| 546 |
+
set_y = x | y | included | restricted
|
| 547 |
+
if set_y - G.nodes:
|
| 548 |
+
raise nx.NodeNotFound(f"The node(s) {set_y - G.nodes} are not found in G")
|
| 549 |
+
except TypeError:
|
| 550 |
+
raise nx.NodeNotFound(
|
| 551 |
+
"One of x, y, z, included or restricted is not a node or set of nodes in G"
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
if not included <= z:
|
| 555 |
+
raise nx.NetworkXError(
|
| 556 |
+
f"Included nodes {included} must be in proposed separating set z {x}"
|
| 557 |
+
)
|
| 558 |
+
if not z <= restricted:
|
| 559 |
+
raise nx.NetworkXError(
|
| 560 |
+
f"Separating set {z} must be contained in restricted set {restricted}"
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
intersection = x.intersection(y) or x.intersection(z) or y.intersection(z)
|
| 564 |
+
if intersection:
|
| 565 |
+
raise nx.NetworkXError(
|
| 566 |
+
f"The sets are not disjoint, with intersection {intersection}"
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
nodeset = x | y | included
|
| 570 |
+
ancestors_x_y_included = nodeset.union(*[nx.ancestors(G, n) for n in nodeset])
|
| 571 |
+
|
| 572 |
+
# criterion (a) -- check that z is actually a separator
|
| 573 |
+
x_closure = _reachable(G, x, ancestors_x_y_included, z)
|
| 574 |
+
if x_closure & y:
|
| 575 |
+
return False
|
| 576 |
+
|
| 577 |
+
# criterion (b) -- basic constraint; included and restricted already checked above
|
| 578 |
+
if not (z <= ancestors_x_y_included):
|
| 579 |
+
return False
|
| 580 |
+
|
| 581 |
+
# criterion (c) -- check that z is minimal
|
| 582 |
+
y_closure = _reachable(G, y, ancestors_x_y_included, z)
|
| 583 |
+
if not ((z - included) <= (x_closure & y_closure)):
|
| 584 |
+
return False
|
| 585 |
+
return True
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
@not_implemented_for("undirected")
|
| 589 |
+
def _reachable(G, x, a, z):
|
| 590 |
+
"""Modified Bayes-Ball algorithm for finding d-connected nodes.
|
| 591 |
+
|
| 592 |
+
Find all nodes in `a` that are d-connected to those in `x` by
|
| 593 |
+
those in `z`. This is an implementation of the function
|
| 594 |
+
`REACHABLE` in [1]_ (which is itself a modification of the
|
| 595 |
+
Bayes-Ball algorithm [2]_) when restricted to DAGs.
|
| 596 |
+
|
| 597 |
+
Parameters
|
| 598 |
+
----------
|
| 599 |
+
G : nx.DiGraph
|
| 600 |
+
A NetworkX DAG.
|
| 601 |
+
x : node | set
|
| 602 |
+
A node in the DAG, or a set of nodes.
|
| 603 |
+
a : node | set
|
| 604 |
+
A (set of) node(s) in the DAG containing the ancestors of `x`.
|
| 605 |
+
z : node | set
|
| 606 |
+
The node or set of nodes conditioned on when checking d-connectedness.
|
| 607 |
+
|
| 608 |
+
Returns
|
| 609 |
+
-------
|
| 610 |
+
w : set
|
| 611 |
+
The closure of `x` in `a` with respect to d-connectedness
|
| 612 |
+
given `z`.
|
| 613 |
+
|
| 614 |
+
References
|
| 615 |
+
----------
|
| 616 |
+
.. [1] van der Zander, Benito, and Maciej Liśkiewicz. "Finding
|
| 617 |
+
minimal d-separators in linear time and applications." In
|
| 618 |
+
Uncertainty in Artificial Intelligence, pp. 637-647. PMLR, 2020.
|
| 619 |
+
|
| 620 |
+
.. [2] Shachter, Ross D. "Bayes-ball: The rational pastime
|
| 621 |
+
(for determining irrelevance and requisite information in
|
| 622 |
+
belief networks and influence diagrams)." In Proceedings of the
|
| 623 |
+
Fourteenth Conference on Uncertainty in Artificial Intelligence
|
| 624 |
+
(UAI), (pp. 480–487). 1998.
|
| 625 |
+
"""
|
| 626 |
+
|
| 627 |
+
def _pass(e, v, f, n):
|
| 628 |
+
"""Whether a ball entering node `v` along edge `e` passes to `n` along `f`.
|
| 629 |
+
|
| 630 |
+
Boolean function defined on page 6 of [1]_.
|
| 631 |
+
|
| 632 |
+
Parameters
|
| 633 |
+
----------
|
| 634 |
+
e : bool
|
| 635 |
+
Directed edge by which the ball got to node `v`; `True` iff directed into `v`.
|
| 636 |
+
v : node
|
| 637 |
+
Node where the ball is.
|
| 638 |
+
f : bool
|
| 639 |
+
Directed edge connecting nodes `v` and `n`; `True` iff directed `n`.
|
| 640 |
+
n : node
|
| 641 |
+
Checking whether the ball passes to this node.
|
| 642 |
+
|
| 643 |
+
Returns
|
| 644 |
+
-------
|
| 645 |
+
b : bool
|
| 646 |
+
Whether the ball passes or not.
|
| 647 |
+
|
| 648 |
+
References
|
| 649 |
+
----------
|
| 650 |
+
.. [1] van der Zander, Benito, and Maciej Liśkiewicz. "Finding
|
| 651 |
+
minimal d-separators in linear time and applications." In
|
| 652 |
+
Uncertainty in Artificial Intelligence, pp. 637-647. PMLR, 2020.
|
| 653 |
+
"""
|
| 654 |
+
is_element_of_A = n in a
|
| 655 |
+
# almost_definite_status = True # always true for DAGs; not so for RCGs
|
| 656 |
+
collider_if_in_Z = v not in z or (e and not f)
|
| 657 |
+
return is_element_of_A and collider_if_in_Z # and almost_definite_status
|
| 658 |
+
|
| 659 |
+
queue = deque([])
|
| 660 |
+
for node in x:
|
| 661 |
+
if bool(G.pred[node]):
|
| 662 |
+
queue.append((True, node))
|
| 663 |
+
if bool(G.succ[node]):
|
| 664 |
+
queue.append((False, node))
|
| 665 |
+
processed = queue.copy()
|
| 666 |
+
|
| 667 |
+
while any(queue):
|
| 668 |
+
e, v = queue.popleft()
|
| 669 |
+
preds = ((False, n) for n in G.pred[v])
|
| 670 |
+
succs = ((True, n) for n in G.succ[v])
|
| 671 |
+
f_n_pairs = chain(preds, succs)
|
| 672 |
+
for f, n in f_n_pairs:
|
| 673 |
+
if (f, n) not in processed and _pass(e, v, f, n):
|
| 674 |
+
queue.append((f, n))
|
| 675 |
+
processed.append((f, n))
|
| 676 |
+
|
| 677 |
+
return {w for (_, w) in processed}
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/dag.py
ADDED
|
@@ -0,0 +1,1392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Algorithms for directed acyclic graphs (DAGs).
|
| 2 |
+
|
| 3 |
+
Note that most of these functions are only guaranteed to work for DAGs.
|
| 4 |
+
In general, these functions do not check for acyclic-ness, so it is up
|
| 5 |
+
to the user to check for that.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import heapq
|
| 9 |
+
from collections import deque
|
| 10 |
+
from functools import partial
|
| 11 |
+
from itertools import chain, combinations, product, starmap
|
| 12 |
+
from math import gcd
|
| 13 |
+
|
| 14 |
+
import networkx as nx
|
| 15 |
+
from networkx.utils import arbitrary_element, not_implemented_for, pairwise
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"descendants",
|
| 19 |
+
"ancestors",
|
| 20 |
+
"topological_sort",
|
| 21 |
+
"lexicographical_topological_sort",
|
| 22 |
+
"all_topological_sorts",
|
| 23 |
+
"topological_generations",
|
| 24 |
+
"is_directed_acyclic_graph",
|
| 25 |
+
"is_aperiodic",
|
| 26 |
+
"transitive_closure",
|
| 27 |
+
"transitive_closure_dag",
|
| 28 |
+
"transitive_reduction",
|
| 29 |
+
"antichains",
|
| 30 |
+
"dag_longest_path",
|
| 31 |
+
"dag_longest_path_length",
|
| 32 |
+
"dag_to_branching",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
chaini = chain.from_iterable
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@nx._dispatchable
|
| 39 |
+
def descendants(G, source):
|
| 40 |
+
"""Returns all nodes reachable from `source` in `G`.
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
----------
|
| 44 |
+
G : NetworkX Graph
|
| 45 |
+
source : node in `G`
|
| 46 |
+
|
| 47 |
+
Returns
|
| 48 |
+
-------
|
| 49 |
+
set()
|
| 50 |
+
The descendants of `source` in `G`
|
| 51 |
+
|
| 52 |
+
Raises
|
| 53 |
+
------
|
| 54 |
+
NetworkXError
|
| 55 |
+
If node `source` is not in `G`.
|
| 56 |
+
|
| 57 |
+
Examples
|
| 58 |
+
--------
|
| 59 |
+
>>> DG = nx.path_graph(5, create_using=nx.DiGraph)
|
| 60 |
+
>>> sorted(nx.descendants(DG, 2))
|
| 61 |
+
[3, 4]
|
| 62 |
+
|
| 63 |
+
The `source` node is not a descendant of itself, but can be included manually:
|
| 64 |
+
|
| 65 |
+
>>> sorted(nx.descendants(DG, 2) | {2})
|
| 66 |
+
[2, 3, 4]
|
| 67 |
+
|
| 68 |
+
See also
|
| 69 |
+
--------
|
| 70 |
+
ancestors
|
| 71 |
+
"""
|
| 72 |
+
return {child for parent, child in nx.bfs_edges(G, source)}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@nx._dispatchable
|
| 76 |
+
def ancestors(G, source):
|
| 77 |
+
"""Returns all nodes having a path to `source` in `G`.
|
| 78 |
+
|
| 79 |
+
Parameters
|
| 80 |
+
----------
|
| 81 |
+
G : NetworkX Graph
|
| 82 |
+
source : node in `G`
|
| 83 |
+
|
| 84 |
+
Returns
|
| 85 |
+
-------
|
| 86 |
+
set()
|
| 87 |
+
The ancestors of `source` in `G`
|
| 88 |
+
|
| 89 |
+
Raises
|
| 90 |
+
------
|
| 91 |
+
NetworkXError
|
| 92 |
+
If node `source` is not in `G`.
|
| 93 |
+
|
| 94 |
+
Examples
|
| 95 |
+
--------
|
| 96 |
+
>>> DG = nx.path_graph(5, create_using=nx.DiGraph)
|
| 97 |
+
>>> sorted(nx.ancestors(DG, 2))
|
| 98 |
+
[0, 1]
|
| 99 |
+
|
| 100 |
+
The `source` node is not an ancestor of itself, but can be included manually:
|
| 101 |
+
|
| 102 |
+
>>> sorted(nx.ancestors(DG, 2) | {2})
|
| 103 |
+
[0, 1, 2]
|
| 104 |
+
|
| 105 |
+
See also
|
| 106 |
+
--------
|
| 107 |
+
descendants
|
| 108 |
+
"""
|
| 109 |
+
return {child for parent, child in nx.bfs_edges(G, source, reverse=True)}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@nx._dispatchable
|
| 113 |
+
def has_cycle(G):
|
| 114 |
+
"""Decides whether the directed graph has a cycle."""
|
| 115 |
+
try:
|
| 116 |
+
# Feed the entire iterator into a zero-length deque.
|
| 117 |
+
deque(topological_sort(G), maxlen=0)
|
| 118 |
+
except nx.NetworkXUnfeasible:
|
| 119 |
+
return True
|
| 120 |
+
else:
|
| 121 |
+
return False
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@nx._dispatchable
|
| 125 |
+
def is_directed_acyclic_graph(G):
|
| 126 |
+
"""Returns True if the graph `G` is a directed acyclic graph (DAG) or
|
| 127 |
+
False if not.
|
| 128 |
+
|
| 129 |
+
Parameters
|
| 130 |
+
----------
|
| 131 |
+
G : NetworkX graph
|
| 132 |
+
|
| 133 |
+
Returns
|
| 134 |
+
-------
|
| 135 |
+
bool
|
| 136 |
+
True if `G` is a DAG, False otherwise
|
| 137 |
+
|
| 138 |
+
Examples
|
| 139 |
+
--------
|
| 140 |
+
Undirected graph::
|
| 141 |
+
|
| 142 |
+
>>> G = nx.Graph([(1, 2), (2, 3)])
|
| 143 |
+
>>> nx.is_directed_acyclic_graph(G)
|
| 144 |
+
False
|
| 145 |
+
|
| 146 |
+
Directed graph with cycle::
|
| 147 |
+
|
| 148 |
+
>>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
|
| 149 |
+
>>> nx.is_directed_acyclic_graph(G)
|
| 150 |
+
False
|
| 151 |
+
|
| 152 |
+
Directed acyclic graph::
|
| 153 |
+
|
| 154 |
+
>>> G = nx.DiGraph([(1, 2), (2, 3)])
|
| 155 |
+
>>> nx.is_directed_acyclic_graph(G)
|
| 156 |
+
True
|
| 157 |
+
|
| 158 |
+
See also
|
| 159 |
+
--------
|
| 160 |
+
topological_sort
|
| 161 |
+
"""
|
| 162 |
+
return G.is_directed() and not has_cycle(G)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@nx._dispatchable
|
| 166 |
+
def topological_generations(G):
|
| 167 |
+
"""Stratifies a DAG into generations.
|
| 168 |
+
|
| 169 |
+
A topological generation is node collection in which ancestors of a node in each
|
| 170 |
+
generation are guaranteed to be in a previous generation, and any descendants of
|
| 171 |
+
a node are guaranteed to be in a following generation. Nodes are guaranteed to
|
| 172 |
+
be in the earliest possible generation that they can belong to.
|
| 173 |
+
|
| 174 |
+
Parameters
|
| 175 |
+
----------
|
| 176 |
+
G : NetworkX digraph
|
| 177 |
+
A directed acyclic graph (DAG)
|
| 178 |
+
|
| 179 |
+
Yields
|
| 180 |
+
------
|
| 181 |
+
sets of nodes
|
| 182 |
+
Yields sets of nodes representing each generation.
|
| 183 |
+
|
| 184 |
+
Raises
|
| 185 |
+
------
|
| 186 |
+
NetworkXError
|
| 187 |
+
Generations are defined for directed graphs only. If the graph
|
| 188 |
+
`G` is undirected, a :exc:`NetworkXError` is raised.
|
| 189 |
+
|
| 190 |
+
NetworkXUnfeasible
|
| 191 |
+
If `G` is not a directed acyclic graph (DAG) no topological generations
|
| 192 |
+
exist and a :exc:`NetworkXUnfeasible` exception is raised. This can also
|
| 193 |
+
be raised if `G` is changed while the returned iterator is being processed
|
| 194 |
+
|
| 195 |
+
RuntimeError
|
| 196 |
+
If `G` is changed while the returned iterator is being processed.
|
| 197 |
+
|
| 198 |
+
Examples
|
| 199 |
+
--------
|
| 200 |
+
>>> DG = nx.DiGraph([(2, 1), (3, 1)])
|
| 201 |
+
>>> [sorted(generation) for generation in nx.topological_generations(DG)]
|
| 202 |
+
[[2, 3], [1]]
|
| 203 |
+
|
| 204 |
+
Notes
|
| 205 |
+
-----
|
| 206 |
+
The generation in which a node resides can also be determined by taking the
|
| 207 |
+
max-path-distance from the node to the farthest leaf node. That value can
|
| 208 |
+
be obtained with this function using `enumerate(topological_generations(G))`.
|
| 209 |
+
|
| 210 |
+
See also
|
| 211 |
+
--------
|
| 212 |
+
topological_sort
|
| 213 |
+
"""
|
| 214 |
+
if not G.is_directed():
|
| 215 |
+
raise nx.NetworkXError("Topological sort not defined on undirected graphs.")
|
| 216 |
+
|
| 217 |
+
multigraph = G.is_multigraph()
|
| 218 |
+
indegree_map = {v: d for v, d in G.in_degree() if d > 0}
|
| 219 |
+
zero_indegree = [v for v, d in G.in_degree() if d == 0]
|
| 220 |
+
|
| 221 |
+
while zero_indegree:
|
| 222 |
+
this_generation = zero_indegree
|
| 223 |
+
zero_indegree = []
|
| 224 |
+
for node in this_generation:
|
| 225 |
+
if node not in G:
|
| 226 |
+
raise RuntimeError("Graph changed during iteration")
|
| 227 |
+
for child in G.neighbors(node):
|
| 228 |
+
try:
|
| 229 |
+
indegree_map[child] -= len(G[node][child]) if multigraph else 1
|
| 230 |
+
except KeyError as err:
|
| 231 |
+
raise RuntimeError("Graph changed during iteration") from err
|
| 232 |
+
if indegree_map[child] == 0:
|
| 233 |
+
zero_indegree.append(child)
|
| 234 |
+
del indegree_map[child]
|
| 235 |
+
yield this_generation
|
| 236 |
+
|
| 237 |
+
if indegree_map:
|
| 238 |
+
raise nx.NetworkXUnfeasible(
|
| 239 |
+
"Graph contains a cycle or graph changed during iteration"
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@nx._dispatchable
|
| 244 |
+
def topological_sort(G):
|
| 245 |
+
"""Returns a generator of nodes in topologically sorted order.
|
| 246 |
+
|
| 247 |
+
A topological sort is a nonunique permutation of the nodes of a
|
| 248 |
+
directed graph such that an edge from u to v implies that u
|
| 249 |
+
appears before v in the topological sort order. This ordering is
|
| 250 |
+
valid only if the graph has no directed cycles.
|
| 251 |
+
|
| 252 |
+
Parameters
|
| 253 |
+
----------
|
| 254 |
+
G : NetworkX digraph
|
| 255 |
+
A directed acyclic graph (DAG)
|
| 256 |
+
|
| 257 |
+
Yields
|
| 258 |
+
------
|
| 259 |
+
nodes
|
| 260 |
+
Yields the nodes in topological sorted order.
|
| 261 |
+
|
| 262 |
+
Raises
|
| 263 |
+
------
|
| 264 |
+
NetworkXError
|
| 265 |
+
Topological sort is defined for directed graphs only. If the graph `G`
|
| 266 |
+
is undirected, a :exc:`NetworkXError` is raised.
|
| 267 |
+
|
| 268 |
+
NetworkXUnfeasible
|
| 269 |
+
If `G` is not a directed acyclic graph (DAG) no topological sort exists
|
| 270 |
+
and a :exc:`NetworkXUnfeasible` exception is raised. This can also be
|
| 271 |
+
raised if `G` is changed while the returned iterator is being processed
|
| 272 |
+
|
| 273 |
+
RuntimeError
|
| 274 |
+
If `G` is changed while the returned iterator is being processed.
|
| 275 |
+
|
| 276 |
+
Examples
|
| 277 |
+
--------
|
| 278 |
+
To get the reverse order of the topological sort:
|
| 279 |
+
|
| 280 |
+
>>> DG = nx.DiGraph([(1, 2), (2, 3)])
|
| 281 |
+
>>> list(reversed(list(nx.topological_sort(DG))))
|
| 282 |
+
[3, 2, 1]
|
| 283 |
+
|
| 284 |
+
If your DiGraph naturally has the edges representing tasks/inputs
|
| 285 |
+
and nodes representing people/processes that initiate tasks, then
|
| 286 |
+
topological_sort is not quite what you need. You will have to change
|
| 287 |
+
the tasks to nodes with dependence reflected by edges. The result is
|
| 288 |
+
a kind of topological sort of the edges. This can be done
|
| 289 |
+
with :func:`networkx.line_graph` as follows:
|
| 290 |
+
|
| 291 |
+
>>> list(nx.topological_sort(nx.line_graph(DG)))
|
| 292 |
+
[(1, 2), (2, 3)]
|
| 293 |
+
|
| 294 |
+
Notes
|
| 295 |
+
-----
|
| 296 |
+
This algorithm is based on a description and proof in
|
| 297 |
+
"Introduction to Algorithms: A Creative Approach" [1]_ .
|
| 298 |
+
|
| 299 |
+
See also
|
| 300 |
+
--------
|
| 301 |
+
is_directed_acyclic_graph, lexicographical_topological_sort
|
| 302 |
+
|
| 303 |
+
References
|
| 304 |
+
----------
|
| 305 |
+
.. [1] Manber, U. (1989).
|
| 306 |
+
*Introduction to Algorithms - A Creative Approach.* Addison-Wesley.
|
| 307 |
+
"""
|
| 308 |
+
for generation in nx.topological_generations(G):
|
| 309 |
+
yield from generation
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@nx._dispatchable
|
| 313 |
+
def lexicographical_topological_sort(G, key=None):
|
| 314 |
+
"""Generate the nodes in the unique lexicographical topological sort order.
|
| 315 |
+
|
| 316 |
+
Generates a unique ordering of nodes by first sorting topologically (for which there are often
|
| 317 |
+
multiple valid orderings) and then additionally by sorting lexicographically.
|
| 318 |
+
|
| 319 |
+
A topological sort arranges the nodes of a directed graph so that the
|
| 320 |
+
upstream node of each directed edge precedes the downstream node.
|
| 321 |
+
It is always possible to find a solution for directed graphs that have no cycles.
|
| 322 |
+
There may be more than one valid solution.
|
| 323 |
+
|
| 324 |
+
Lexicographical sorting is just sorting alphabetically. It is used here to break ties in the
|
| 325 |
+
topological sort and to determine a single, unique ordering. This can be useful in comparing
|
| 326 |
+
sort results.
|
| 327 |
+
|
| 328 |
+
The lexicographical order can be customized by providing a function to the `key=` parameter.
|
| 329 |
+
The definition of the key function is the same as used in python's built-in `sort()`.
|
| 330 |
+
The function takes a single argument and returns a key to use for sorting purposes.
|
| 331 |
+
|
| 332 |
+
Lexicographical sorting can fail if the node names are un-sortable. See the example below.
|
| 333 |
+
The solution is to provide a function to the `key=` argument that returns sortable keys.
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
Parameters
|
| 337 |
+
----------
|
| 338 |
+
G : NetworkX digraph
|
| 339 |
+
A directed acyclic graph (DAG)
|
| 340 |
+
|
| 341 |
+
key : function, optional
|
| 342 |
+
A function of one argument that converts a node name to a comparison key.
|
| 343 |
+
It defines and resolves ambiguities in the sort order. Defaults to the identity function.
|
| 344 |
+
|
| 345 |
+
Yields
|
| 346 |
+
------
|
| 347 |
+
nodes
|
| 348 |
+
Yields the nodes of G in lexicographical topological sort order.
|
| 349 |
+
|
| 350 |
+
Raises
|
| 351 |
+
------
|
| 352 |
+
NetworkXError
|
| 353 |
+
Topological sort is defined for directed graphs only. If the graph `G`
|
| 354 |
+
is undirected, a :exc:`NetworkXError` is raised.
|
| 355 |
+
|
| 356 |
+
NetworkXUnfeasible
|
| 357 |
+
If `G` is not a directed acyclic graph (DAG) no topological sort exists
|
| 358 |
+
and a :exc:`NetworkXUnfeasible` exception is raised. This can also be
|
| 359 |
+
raised if `G` is changed while the returned iterator is being processed
|
| 360 |
+
|
| 361 |
+
RuntimeError
|
| 362 |
+
If `G` is changed while the returned iterator is being processed.
|
| 363 |
+
|
| 364 |
+
TypeError
|
| 365 |
+
Results from un-sortable node names.
|
| 366 |
+
Consider using `key=` parameter to resolve ambiguities in the sort order.
|
| 367 |
+
|
| 368 |
+
Examples
|
| 369 |
+
--------
|
| 370 |
+
>>> DG = nx.DiGraph([(2, 1), (2, 5), (1, 3), (1, 4), (5, 4)])
|
| 371 |
+
>>> list(nx.lexicographical_topological_sort(DG))
|
| 372 |
+
[2, 1, 3, 5, 4]
|
| 373 |
+
>>> list(nx.lexicographical_topological_sort(DG, key=lambda x: -x))
|
| 374 |
+
[2, 5, 1, 4, 3]
|
| 375 |
+
|
| 376 |
+
The sort will fail for any graph with integer and string nodes. Comparison of integer to strings
|
| 377 |
+
is not defined in python. Is 3 greater or less than 'red'?
|
| 378 |
+
|
| 379 |
+
>>> DG = nx.DiGraph([(1, "red"), (3, "red"), (1, "green"), (2, "blue")])
|
| 380 |
+
>>> list(nx.lexicographical_topological_sort(DG))
|
| 381 |
+
Traceback (most recent call last):
|
| 382 |
+
...
|
| 383 |
+
TypeError: '<' not supported between instances of 'str' and 'int'
|
| 384 |
+
...
|
| 385 |
+
|
| 386 |
+
Incomparable nodes can be resolved using a `key` function. This example function
|
| 387 |
+
allows comparison of integers and strings by returning a tuple where the first
|
| 388 |
+
element is True for `str`, False otherwise. The second element is the node name.
|
| 389 |
+
This groups the strings and integers separately so they can be compared only among themselves.
|
| 390 |
+
|
| 391 |
+
>>> key = lambda node: (isinstance(node, str), node)
|
| 392 |
+
>>> list(nx.lexicographical_topological_sort(DG, key=key))
|
| 393 |
+
[1, 2, 3, 'blue', 'green', 'red']
|
| 394 |
+
|
| 395 |
+
Notes
|
| 396 |
+
-----
|
| 397 |
+
This algorithm is based on a description and proof in
|
| 398 |
+
"Introduction to Algorithms: A Creative Approach" [1]_ .
|
| 399 |
+
|
| 400 |
+
See also
|
| 401 |
+
--------
|
| 402 |
+
topological_sort
|
| 403 |
+
|
| 404 |
+
References
|
| 405 |
+
----------
|
| 406 |
+
.. [1] Manber, U. (1989).
|
| 407 |
+
*Introduction to Algorithms - A Creative Approach.* Addison-Wesley.
|
| 408 |
+
"""
|
| 409 |
+
if not G.is_directed():
|
| 410 |
+
msg = "Topological sort not defined on undirected graphs."
|
| 411 |
+
raise nx.NetworkXError(msg)
|
| 412 |
+
|
| 413 |
+
if key is None:
|
| 414 |
+
|
| 415 |
+
def key(node):
|
| 416 |
+
return node
|
| 417 |
+
|
| 418 |
+
nodeid_map = {n: i for i, n in enumerate(G)}
|
| 419 |
+
|
| 420 |
+
def create_tuple(node):
|
| 421 |
+
return key(node), nodeid_map[node], node
|
| 422 |
+
|
| 423 |
+
indegree_map = {v: d for v, d in G.in_degree() if d > 0}
|
| 424 |
+
# These nodes have zero indegree and ready to be returned.
|
| 425 |
+
zero_indegree = [create_tuple(v) for v, d in G.in_degree() if d == 0]
|
| 426 |
+
heapq.heapify(zero_indegree)
|
| 427 |
+
|
| 428 |
+
while zero_indegree:
|
| 429 |
+
_, _, node = heapq.heappop(zero_indegree)
|
| 430 |
+
|
| 431 |
+
if node not in G:
|
| 432 |
+
raise RuntimeError("Graph changed during iteration")
|
| 433 |
+
for _, child in G.edges(node):
|
| 434 |
+
try:
|
| 435 |
+
indegree_map[child] -= 1
|
| 436 |
+
except KeyError as err:
|
| 437 |
+
raise RuntimeError("Graph changed during iteration") from err
|
| 438 |
+
if indegree_map[child] == 0:
|
| 439 |
+
try:
|
| 440 |
+
heapq.heappush(zero_indegree, create_tuple(child))
|
| 441 |
+
except TypeError as err:
|
| 442 |
+
raise TypeError(
|
| 443 |
+
f"{err}\nConsider using `key=` parameter to resolve ambiguities in the sort order."
|
| 444 |
+
)
|
| 445 |
+
del indegree_map[child]
|
| 446 |
+
|
| 447 |
+
yield node
|
| 448 |
+
|
| 449 |
+
if indegree_map:
|
| 450 |
+
msg = "Graph contains a cycle or graph changed during iteration"
|
| 451 |
+
raise nx.NetworkXUnfeasible(msg)
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
@not_implemented_for("undirected")
|
| 455 |
+
@nx._dispatchable
|
| 456 |
+
def all_topological_sorts(G):
|
| 457 |
+
"""Returns a generator of _all_ topological sorts of the directed graph G.
|
| 458 |
+
|
| 459 |
+
A topological sort is a nonunique permutation of the nodes such that an
|
| 460 |
+
edge from u to v implies that u appears before v in the topological sort
|
| 461 |
+
order.
|
| 462 |
+
|
| 463 |
+
Parameters
|
| 464 |
+
----------
|
| 465 |
+
G : NetworkX DiGraph
|
| 466 |
+
A directed graph
|
| 467 |
+
|
| 468 |
+
Yields
|
| 469 |
+
------
|
| 470 |
+
topological_sort_order : list
|
| 471 |
+
a list of nodes in `G`, representing one of the topological sort orders
|
| 472 |
+
|
| 473 |
+
Raises
|
| 474 |
+
------
|
| 475 |
+
NetworkXNotImplemented
|
| 476 |
+
If `G` is not directed
|
| 477 |
+
NetworkXUnfeasible
|
| 478 |
+
If `G` is not acyclic
|
| 479 |
+
|
| 480 |
+
Examples
|
| 481 |
+
--------
|
| 482 |
+
To enumerate all topological sorts of directed graph:
|
| 483 |
+
|
| 484 |
+
>>> DG = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
|
| 485 |
+
>>> list(nx.all_topological_sorts(DG))
|
| 486 |
+
[[1, 2, 4, 3], [1, 2, 3, 4]]
|
| 487 |
+
|
| 488 |
+
Notes
|
| 489 |
+
-----
|
| 490 |
+
Implements an iterative version of the algorithm given in [1].
|
| 491 |
+
|
| 492 |
+
References
|
| 493 |
+
----------
|
| 494 |
+
.. [1] Knuth, Donald E., Szwarcfiter, Jayme L. (1974).
|
| 495 |
+
"A Structured Program to Generate All Topological Sorting Arrangements"
|
| 496 |
+
Information Processing Letters, Volume 2, Issue 6, 1974, Pages 153-157,
|
| 497 |
+
ISSN 0020-0190,
|
| 498 |
+
https://doi.org/10.1016/0020-0190(74)90001-5.
|
| 499 |
+
Elsevier (North-Holland), Amsterdam
|
| 500 |
+
"""
|
| 501 |
+
if not G.is_directed():
|
| 502 |
+
raise nx.NetworkXError("Topological sort not defined on undirected graphs.")
|
| 503 |
+
|
| 504 |
+
# the names of count and D are chosen to match the global variables in [1]
|
| 505 |
+
# number of edges originating in a vertex v
|
| 506 |
+
count = dict(G.in_degree())
|
| 507 |
+
# vertices with indegree 0
|
| 508 |
+
D = deque([v for v, d in G.in_degree() if d == 0])
|
| 509 |
+
# stack of first value chosen at a position k in the topological sort
|
| 510 |
+
bases = []
|
| 511 |
+
current_sort = []
|
| 512 |
+
|
| 513 |
+
# do-while construct
|
| 514 |
+
while True:
|
| 515 |
+
assert all(count[v] == 0 for v in D)
|
| 516 |
+
|
| 517 |
+
if len(current_sort) == len(G):
|
| 518 |
+
yield list(current_sort)
|
| 519 |
+
|
| 520 |
+
# clean-up stack
|
| 521 |
+
while len(current_sort) > 0:
|
| 522 |
+
assert len(bases) == len(current_sort)
|
| 523 |
+
q = current_sort.pop()
|
| 524 |
+
|
| 525 |
+
# "restores" all edges (q, x)
|
| 526 |
+
# NOTE: it is important to iterate over edges instead
|
| 527 |
+
# of successors, so count is updated correctly in multigraphs
|
| 528 |
+
for _, j in G.out_edges(q):
|
| 529 |
+
count[j] += 1
|
| 530 |
+
assert count[j] >= 0
|
| 531 |
+
# remove entries from D
|
| 532 |
+
while len(D) > 0 and count[D[-1]] > 0:
|
| 533 |
+
D.pop()
|
| 534 |
+
|
| 535 |
+
# corresponds to a circular shift of the values in D
|
| 536 |
+
# if the first value chosen (the base) is in the first
|
| 537 |
+
# position of D again, we are done and need to consider the
|
| 538 |
+
# previous condition
|
| 539 |
+
D.appendleft(q)
|
| 540 |
+
if D[-1] == bases[-1]:
|
| 541 |
+
# all possible values have been chosen at current position
|
| 542 |
+
# remove corresponding marker
|
| 543 |
+
bases.pop()
|
| 544 |
+
else:
|
| 545 |
+
# there are still elements that have not been fixed
|
| 546 |
+
# at the current position in the topological sort
|
| 547 |
+
# stop removing elements, escape inner loop
|
| 548 |
+
break
|
| 549 |
+
|
| 550 |
+
else:
|
| 551 |
+
if len(D) == 0:
|
| 552 |
+
raise nx.NetworkXUnfeasible("Graph contains a cycle.")
|
| 553 |
+
|
| 554 |
+
# choose next node
|
| 555 |
+
q = D.pop()
|
| 556 |
+
# "erase" all edges (q, x)
|
| 557 |
+
# NOTE: it is important to iterate over edges instead
|
| 558 |
+
# of successors, so count is updated correctly in multigraphs
|
| 559 |
+
for _, j in G.out_edges(q):
|
| 560 |
+
count[j] -= 1
|
| 561 |
+
assert count[j] >= 0
|
| 562 |
+
if count[j] == 0:
|
| 563 |
+
D.append(j)
|
| 564 |
+
current_sort.append(q)
|
| 565 |
+
|
| 566 |
+
# base for current position might _not_ be fixed yet
|
| 567 |
+
if len(bases) < len(current_sort):
|
| 568 |
+
bases.append(q)
|
| 569 |
+
|
| 570 |
+
if len(bases) == 0:
|
| 571 |
+
break
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
@nx._dispatchable
|
| 575 |
+
def is_aperiodic(G):
|
| 576 |
+
"""Returns True if `G` is aperiodic.
|
| 577 |
+
|
| 578 |
+
A strongly connected directed graph is aperiodic if there is no integer ``k > 1``
|
| 579 |
+
that divides the length of every cycle in the graph.
|
| 580 |
+
|
| 581 |
+
This function requires the graph `G` to be strongly connected and will raise
|
| 582 |
+
an error if it's not. For graphs that are not strongly connected, you should
|
| 583 |
+
first identify their strongly connected components
|
| 584 |
+
(using :func:`~networkx.algorithms.components.strongly_connected_components`)
|
| 585 |
+
or attracting components
|
| 586 |
+
(using :func:`~networkx.algorithms.components.attracting_components`),
|
| 587 |
+
and then apply this function to those individual components.
|
| 588 |
+
|
| 589 |
+
Parameters
|
| 590 |
+
----------
|
| 591 |
+
G : NetworkX DiGraph
|
| 592 |
+
A directed graph
|
| 593 |
+
|
| 594 |
+
Returns
|
| 595 |
+
-------
|
| 596 |
+
bool
|
| 597 |
+
True if the graph is aperiodic False otherwise
|
| 598 |
+
|
| 599 |
+
Raises
|
| 600 |
+
------
|
| 601 |
+
NetworkXError
|
| 602 |
+
If `G` is not directed
|
| 603 |
+
NetworkXError
|
| 604 |
+
If `G` is not strongly connected
|
| 605 |
+
NetworkXPointlessConcept
|
| 606 |
+
If `G` has no nodes
|
| 607 |
+
|
| 608 |
+
Examples
|
| 609 |
+
--------
|
| 610 |
+
A graph consisting of one cycle, the length of which is 2. Therefore ``k = 2``
|
| 611 |
+
divides the length of every cycle in the graph and thus the graph
|
| 612 |
+
is *not aperiodic*::
|
| 613 |
+
|
| 614 |
+
>>> DG = nx.DiGraph([(1, 2), (2, 1)])
|
| 615 |
+
>>> nx.is_aperiodic(DG)
|
| 616 |
+
False
|
| 617 |
+
|
| 618 |
+
A graph consisting of two cycles: one of length 2 and the other of length 3.
|
| 619 |
+
The cycle lengths are coprime, so there is no single value of k where ``k > 1``
|
| 620 |
+
that divides each cycle length and therefore the graph is *aperiodic*::
|
| 621 |
+
|
| 622 |
+
>>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1), (1, 4), (4, 1)])
|
| 623 |
+
>>> nx.is_aperiodic(DG)
|
| 624 |
+
True
|
| 625 |
+
|
| 626 |
+
A graph created from cycles of the same length can still be aperiodic since
|
| 627 |
+
the cycles can overlap and form new cycles of different lengths. For example,
|
| 628 |
+
the following graph contains a cycle ``[4, 2, 3, 1]`` of length 4, which is coprime
|
| 629 |
+
with the explicitly added cycles of length 3, so the graph is aperiodic::
|
| 630 |
+
|
| 631 |
+
>>> DG = nx.DiGraph()
|
| 632 |
+
>>> nx.add_cycle(DG, [1, 2, 3])
|
| 633 |
+
>>> nx.add_cycle(DG, [2, 1, 4])
|
| 634 |
+
>>> nx.is_aperiodic(DG)
|
| 635 |
+
True
|
| 636 |
+
|
| 637 |
+
A single-node graph's aperiodicity depends on whether it has a self-loop:
|
| 638 |
+
it is aperiodic if a self-loop exists, and periodic otherwise::
|
| 639 |
+
|
| 640 |
+
>>> G = nx.DiGraph()
|
| 641 |
+
>>> G.add_node(1)
|
| 642 |
+
>>> nx.is_aperiodic(G)
|
| 643 |
+
False
|
| 644 |
+
>>> G.add_edge(1, 1)
|
| 645 |
+
>>> nx.is_aperiodic(G)
|
| 646 |
+
True
|
| 647 |
+
|
| 648 |
+
A Markov chain can be modeled as a directed graph, with nodes representing
|
| 649 |
+
states and edges representing transitions with non-zero probability.
|
| 650 |
+
Aperiodicity is typically considered for irreducible Markov chains,
|
| 651 |
+
which are those that are *strongly connected* as graphs.
|
| 652 |
+
|
| 653 |
+
The following Markov chain is irreducible and aperiodic, and thus
|
| 654 |
+
ergodic. It is guaranteed to have a unique stationary distribution::
|
| 655 |
+
|
| 656 |
+
>>> G = nx.DiGraph()
|
| 657 |
+
>>> nx.add_cycle(G, [1, 2, 3, 4])
|
| 658 |
+
>>> G.add_edge(1, 3)
|
| 659 |
+
>>> nx.is_aperiodic(G)
|
| 660 |
+
True
|
| 661 |
+
|
| 662 |
+
Reducible Markov chains can sometimes have a unique stationary distribution.
|
| 663 |
+
This occurs if the chain has exactly one closed communicating class and
|
| 664 |
+
that class itself is aperiodic (see [1]_). You can use
|
| 665 |
+
:func:`~networkx.algorithms.components.attracting_components`
|
| 666 |
+
to find these closed communicating classes::
|
| 667 |
+
|
| 668 |
+
>>> G = nx.DiGraph([(1, 3), (2, 3)])
|
| 669 |
+
>>> nx.add_cycle(G, [3, 4, 5, 6])
|
| 670 |
+
>>> nx.add_cycle(G, [3, 5, 6])
|
| 671 |
+
>>> communicating_classes = list(nx.strongly_connected_components(G))
|
| 672 |
+
>>> len(communicating_classes)
|
| 673 |
+
3
|
| 674 |
+
>>> closed_communicating_classes = list(nx.attracting_components(G))
|
| 675 |
+
>>> len(closed_communicating_classes)
|
| 676 |
+
1
|
| 677 |
+
>>> nx.is_aperiodic(G.subgraph(closed_communicating_classes[0]))
|
| 678 |
+
True
|
| 679 |
+
|
| 680 |
+
Notes
|
| 681 |
+
-----
|
| 682 |
+
This uses the method outlined in [1]_, which runs in $O(m)$ time
|
| 683 |
+
given $m$ edges in `G`.
|
| 684 |
+
|
| 685 |
+
References
|
| 686 |
+
----------
|
| 687 |
+
.. [1] Jarvis, J. P.; Shier, D. R. (1996),
|
| 688 |
+
"Graph-theoretic analysis of finite Markov chains,"
|
| 689 |
+
in Shier, D. R.; Wallenius, K. T., Applied Mathematical Modeling:
|
| 690 |
+
A Multidisciplinary Approach, CRC Press.
|
| 691 |
+
"""
|
| 692 |
+
if not G.is_directed():
|
| 693 |
+
raise nx.NetworkXError("is_aperiodic not defined for undirected graphs")
|
| 694 |
+
if len(G) == 0:
|
| 695 |
+
raise nx.NetworkXPointlessConcept("Graph has no nodes.")
|
| 696 |
+
if not nx.is_strongly_connected(G):
|
| 697 |
+
raise nx.NetworkXError("Graph is not strongly connected.")
|
| 698 |
+
s = arbitrary_element(G)
|
| 699 |
+
levels = {s: 0}
|
| 700 |
+
this_level = [s]
|
| 701 |
+
g = 0
|
| 702 |
+
lev = 1
|
| 703 |
+
while this_level:
|
| 704 |
+
next_level = []
|
| 705 |
+
for u in this_level:
|
| 706 |
+
for v in G[u]:
|
| 707 |
+
if v in levels: # Non-Tree Edge
|
| 708 |
+
g = gcd(g, levels[u] - levels[v] + 1)
|
| 709 |
+
else: # Tree Edge
|
| 710 |
+
next_level.append(v)
|
| 711 |
+
levels[v] = lev
|
| 712 |
+
this_level = next_level
|
| 713 |
+
lev += 1
|
| 714 |
+
return g == 1
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
|
| 718 |
+
def transitive_closure(G, reflexive=False):
|
| 719 |
+
"""Returns transitive closure of a graph
|
| 720 |
+
|
| 721 |
+
The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
|
| 722 |
+
for all v, w in V there is an edge (v, w) in E+ if and only if there
|
| 723 |
+
is a path from v to w in G.
|
| 724 |
+
|
| 725 |
+
Handling of paths from v to v has some flexibility within this definition.
|
| 726 |
+
A reflexive transitive closure creates a self-loop for the path
|
| 727 |
+
from v to v of length 0. The usual transitive closure creates a
|
| 728 |
+
self-loop only if a cycle exists (a path from v to v with length > 0).
|
| 729 |
+
We also allow an option for no self-loops.
|
| 730 |
+
|
| 731 |
+
Parameters
|
| 732 |
+
----------
|
| 733 |
+
G : NetworkX Graph
|
| 734 |
+
A directed/undirected graph/multigraph.
|
| 735 |
+
reflexive : Bool or None, optional (default: False)
|
| 736 |
+
Determines when cycles create self-loops in the Transitive Closure.
|
| 737 |
+
If True, trivial cycles (length 0) create self-loops. The result
|
| 738 |
+
is a reflexive transitive closure of G.
|
| 739 |
+
If False (the default) non-trivial cycles create self-loops.
|
| 740 |
+
If None, self-loops are not created.
|
| 741 |
+
|
| 742 |
+
Returns
|
| 743 |
+
-------
|
| 744 |
+
NetworkX graph
|
| 745 |
+
The transitive closure of `G`
|
| 746 |
+
|
| 747 |
+
Raises
|
| 748 |
+
------
|
| 749 |
+
NetworkXError
|
| 750 |
+
If `reflexive` not in `{None, True, False}`
|
| 751 |
+
|
| 752 |
+
Examples
|
| 753 |
+
--------
|
| 754 |
+
The treatment of trivial (i.e. length 0) cycles is controlled by the
|
| 755 |
+
`reflexive` parameter.
|
| 756 |
+
|
| 757 |
+
Trivial (i.e. length 0) cycles do not create self-loops when
|
| 758 |
+
``reflexive=False`` (the default)::
|
| 759 |
+
|
| 760 |
+
>>> DG = nx.DiGraph([(1, 2), (2, 3)])
|
| 761 |
+
>>> TC = nx.transitive_closure(DG, reflexive=False)
|
| 762 |
+
>>> TC.edges()
|
| 763 |
+
OutEdgeView([(1, 2), (1, 3), (2, 3)])
|
| 764 |
+
|
| 765 |
+
However, nontrivial (i.e. length greater than 0) cycles create self-loops
|
| 766 |
+
when ``reflexive=False`` (the default)::
|
| 767 |
+
|
| 768 |
+
>>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
|
| 769 |
+
>>> TC = nx.transitive_closure(DG, reflexive=False)
|
| 770 |
+
>>> TC.edges()
|
| 771 |
+
OutEdgeView([(1, 2), (1, 3), (1, 1), (2, 3), (2, 1), (2, 2), (3, 1), (3, 2), (3, 3)])
|
| 772 |
+
|
| 773 |
+
Trivial cycles (length 0) create self-loops when ``reflexive=True``::
|
| 774 |
+
|
| 775 |
+
>>> DG = nx.DiGraph([(1, 2), (2, 3)])
|
| 776 |
+
>>> TC = nx.transitive_closure(DG, reflexive=True)
|
| 777 |
+
>>> TC.edges()
|
| 778 |
+
OutEdgeView([(1, 2), (1, 1), (1, 3), (2, 3), (2, 2), (3, 3)])
|
| 779 |
+
|
| 780 |
+
And the third option is not to create self-loops at all when ``reflexive=None``::
|
| 781 |
+
|
| 782 |
+
>>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
|
| 783 |
+
>>> TC = nx.transitive_closure(DG, reflexive=None)
|
| 784 |
+
>>> TC.edges()
|
| 785 |
+
OutEdgeView([(1, 2), (1, 3), (2, 3), (2, 1), (3, 1), (3, 2)])
|
| 786 |
+
|
| 787 |
+
References
|
| 788 |
+
----------
|
| 789 |
+
.. [1] https://www.ics.uci.edu/~eppstein/PADS/PartialOrder.py
|
| 790 |
+
"""
|
| 791 |
+
TC = G.copy()
|
| 792 |
+
|
| 793 |
+
if reflexive not in {None, True, False}:
|
| 794 |
+
raise nx.NetworkXError("Incorrect value for the parameter `reflexive`")
|
| 795 |
+
|
| 796 |
+
for v in G:
|
| 797 |
+
if reflexive is None:
|
| 798 |
+
TC.add_edges_from((v, u) for u in nx.descendants(G, v) if u not in TC[v])
|
| 799 |
+
elif reflexive is True:
|
| 800 |
+
TC.add_edges_from(
|
| 801 |
+
(v, u) for u in nx.descendants(G, v) | {v} if u not in TC[v]
|
| 802 |
+
)
|
| 803 |
+
elif reflexive is False:
|
| 804 |
+
TC.add_edges_from((v, e[1]) for e in nx.edge_bfs(G, v) if e[1] not in TC[v])
|
| 805 |
+
|
| 806 |
+
return TC
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
@not_implemented_for("undirected")
|
| 810 |
+
@nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
|
| 811 |
+
def transitive_closure_dag(G, topo_order=None):
|
| 812 |
+
"""Returns the transitive closure of a directed acyclic graph.
|
| 813 |
+
|
| 814 |
+
This function is faster than the function `transitive_closure`, but fails
|
| 815 |
+
if the graph has a cycle.
|
| 816 |
+
|
| 817 |
+
The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
|
| 818 |
+
for all v, w in V there is an edge (v, w) in E+ if and only if there
|
| 819 |
+
is a non-null path from v to w in G.
|
| 820 |
+
|
| 821 |
+
Parameters
|
| 822 |
+
----------
|
| 823 |
+
G : NetworkX DiGraph
|
| 824 |
+
A directed acyclic graph (DAG)
|
| 825 |
+
|
| 826 |
+
topo_order: list or tuple, optional
|
| 827 |
+
A topological order for G (if None, the function will compute one)
|
| 828 |
+
|
| 829 |
+
Returns
|
| 830 |
+
-------
|
| 831 |
+
NetworkX DiGraph
|
| 832 |
+
The transitive closure of `G`
|
| 833 |
+
|
| 834 |
+
Raises
|
| 835 |
+
------
|
| 836 |
+
NetworkXNotImplemented
|
| 837 |
+
If `G` is not directed
|
| 838 |
+
NetworkXUnfeasible
|
| 839 |
+
If `G` has a cycle
|
| 840 |
+
|
| 841 |
+
Examples
|
| 842 |
+
--------
|
| 843 |
+
>>> DG = nx.DiGraph([(1, 2), (2, 3)])
|
| 844 |
+
>>> TC = nx.transitive_closure_dag(DG)
|
| 845 |
+
>>> TC.edges()
|
| 846 |
+
OutEdgeView([(1, 2), (1, 3), (2, 3)])
|
| 847 |
+
|
| 848 |
+
Notes
|
| 849 |
+
-----
|
| 850 |
+
This algorithm is probably simple enough to be well-known but I didn't find
|
| 851 |
+
a mention in the literature.
|
| 852 |
+
"""
|
| 853 |
+
if topo_order is None:
|
| 854 |
+
topo_order = list(topological_sort(G))
|
| 855 |
+
|
| 856 |
+
TC = G.copy()
|
| 857 |
+
|
| 858 |
+
# idea: traverse vertices following a reverse topological order, connecting
|
| 859 |
+
# each vertex to its descendants at distance 2 as we go
|
| 860 |
+
for v in reversed(topo_order):
|
| 861 |
+
TC.add_edges_from((v, u) for u in nx.descendants_at_distance(TC, v, 2))
|
| 862 |
+
|
| 863 |
+
return TC
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
@not_implemented_for("undirected")
|
| 867 |
+
@nx._dispatchable(returns_graph=True)
|
| 868 |
+
def transitive_reduction(G):
|
| 869 |
+
"""Returns transitive reduction of a directed graph
|
| 870 |
+
|
| 871 |
+
The transitive reduction of G = (V,E) is a graph G- = (V,E-) such that
|
| 872 |
+
for all v,w in V there is an edge (v,w) in E- if and only if (v,w) is
|
| 873 |
+
in E and there is no path from v to w in G with length greater than 1.
|
| 874 |
+
|
| 875 |
+
Parameters
|
| 876 |
+
----------
|
| 877 |
+
G : NetworkX DiGraph
|
| 878 |
+
A directed acyclic graph (DAG)
|
| 879 |
+
|
| 880 |
+
Returns
|
| 881 |
+
-------
|
| 882 |
+
NetworkX DiGraph
|
| 883 |
+
The transitive reduction of `G`
|
| 884 |
+
|
| 885 |
+
Raises
|
| 886 |
+
------
|
| 887 |
+
NetworkXError
|
| 888 |
+
If `G` is not a directed acyclic graph (DAG) transitive reduction is
|
| 889 |
+
not uniquely defined and a :exc:`NetworkXError` exception is raised.
|
| 890 |
+
|
| 891 |
+
Examples
|
| 892 |
+
--------
|
| 893 |
+
To perform transitive reduction on a DiGraph:
|
| 894 |
+
|
| 895 |
+
>>> DG = nx.DiGraph([(1, 2), (2, 3), (1, 3)])
|
| 896 |
+
>>> TR = nx.transitive_reduction(DG)
|
| 897 |
+
>>> list(TR.edges)
|
| 898 |
+
[(1, 2), (2, 3)]
|
| 899 |
+
|
| 900 |
+
To avoid unnecessary data copies, this implementation does not return a
|
| 901 |
+
DiGraph with node/edge data.
|
| 902 |
+
To perform transitive reduction on a DiGraph and transfer node/edge data:
|
| 903 |
+
|
| 904 |
+
>>> DG = nx.DiGraph()
|
| 905 |
+
>>> DG.add_edges_from([(1, 2), (2, 3), (1, 3)], color="red")
|
| 906 |
+
>>> TR = nx.transitive_reduction(DG)
|
| 907 |
+
>>> TR.add_nodes_from(DG.nodes(data=True))
|
| 908 |
+
>>> TR.add_edges_from((u, v, DG.edges[u, v]) for u, v in TR.edges)
|
| 909 |
+
>>> list(TR.edges(data=True))
|
| 910 |
+
[(1, 2, {'color': 'red'}), (2, 3, {'color': 'red'})]
|
| 911 |
+
|
| 912 |
+
References
|
| 913 |
+
----------
|
| 914 |
+
https://en.wikipedia.org/wiki/Transitive_reduction
|
| 915 |
+
|
| 916 |
+
"""
|
| 917 |
+
if not is_directed_acyclic_graph(G):
|
| 918 |
+
msg = "Directed Acyclic Graph required for transitive_reduction"
|
| 919 |
+
raise nx.NetworkXError(msg)
|
| 920 |
+
TR = nx.DiGraph()
|
| 921 |
+
TR.add_nodes_from(G.nodes())
|
| 922 |
+
descendants = {}
|
| 923 |
+
# count before removing set stored in descendants
|
| 924 |
+
check_count = dict(G.in_degree)
|
| 925 |
+
for u in G:
|
| 926 |
+
u_nbrs = set(G[u])
|
| 927 |
+
for v in G[u]:
|
| 928 |
+
if v in u_nbrs:
|
| 929 |
+
if v not in descendants:
|
| 930 |
+
descendants[v] = {y for x, y in nx.dfs_edges(G, v)}
|
| 931 |
+
u_nbrs -= descendants[v]
|
| 932 |
+
check_count[v] -= 1
|
| 933 |
+
if check_count[v] == 0:
|
| 934 |
+
del descendants[v]
|
| 935 |
+
TR.add_edges_from((u, v) for v in u_nbrs)
|
| 936 |
+
return TR
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
@not_implemented_for("undirected")
|
| 940 |
+
@nx._dispatchable
|
| 941 |
+
def antichains(G, topo_order=None):
|
| 942 |
+
"""Generates antichains from a directed acyclic graph (DAG).
|
| 943 |
+
|
| 944 |
+
An antichain is a subset of a partially ordered set such that any
|
| 945 |
+
two elements in the subset are incomparable.
|
| 946 |
+
|
| 947 |
+
Parameters
|
| 948 |
+
----------
|
| 949 |
+
G : NetworkX DiGraph
|
| 950 |
+
A directed acyclic graph (DAG)
|
| 951 |
+
|
| 952 |
+
topo_order: list or tuple, optional
|
| 953 |
+
A topological order for G (if None, the function will compute one)
|
| 954 |
+
|
| 955 |
+
Yields
|
| 956 |
+
------
|
| 957 |
+
antichain : list
|
| 958 |
+
a list of nodes in `G` representing an antichain
|
| 959 |
+
|
| 960 |
+
Raises
|
| 961 |
+
------
|
| 962 |
+
NetworkXNotImplemented
|
| 963 |
+
If `G` is not directed
|
| 964 |
+
|
| 965 |
+
NetworkXUnfeasible
|
| 966 |
+
If `G` contains a cycle
|
| 967 |
+
|
| 968 |
+
Examples
|
| 969 |
+
--------
|
| 970 |
+
>>> DG = nx.DiGraph([(1, 2), (1, 3)])
|
| 971 |
+
>>> list(nx.antichains(DG))
|
| 972 |
+
[[], [3], [2], [2, 3], [1]]
|
| 973 |
+
|
| 974 |
+
Notes
|
| 975 |
+
-----
|
| 976 |
+
This function was originally developed by Peter Jipsen and Franco Saliola
|
| 977 |
+
for the SAGE project. It's included in NetworkX with permission from the
|
| 978 |
+
authors. Original SAGE code at:
|
| 979 |
+
|
| 980 |
+
https://github.com/sagemath/sage/blob/master/src/sage/combinat/posets/hasse_diagram.py
|
| 981 |
+
|
| 982 |
+
References
|
| 983 |
+
----------
|
| 984 |
+
.. [1] Free Lattices, by R. Freese, J. Jezek and J. B. Nation,
|
| 985 |
+
AMS, Vol 42, 1995, p. 226.
|
| 986 |
+
"""
|
| 987 |
+
if topo_order is None:
|
| 988 |
+
topo_order = list(nx.topological_sort(G))
|
| 989 |
+
|
| 990 |
+
TC = nx.transitive_closure_dag(G, topo_order)
|
| 991 |
+
antichains_stacks = [([], list(reversed(topo_order)))]
|
| 992 |
+
|
| 993 |
+
while antichains_stacks:
|
| 994 |
+
(antichain, stack) = antichains_stacks.pop()
|
| 995 |
+
# Invariant:
|
| 996 |
+
# - the elements of antichain are independent
|
| 997 |
+
# - the elements of stack are independent from those of antichain
|
| 998 |
+
yield antichain
|
| 999 |
+
while stack:
|
| 1000 |
+
x = stack.pop()
|
| 1001 |
+
new_antichain = antichain + [x]
|
| 1002 |
+
new_stack = [t for t in stack if not ((t in TC[x]) or (x in TC[t]))]
|
| 1003 |
+
antichains_stacks.append((new_antichain, new_stack))
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
@not_implemented_for("undirected")
|
| 1007 |
+
@nx._dispatchable(edge_attrs={"weight": "default_weight"})
|
| 1008 |
+
def dag_longest_path(G, weight="weight", default_weight=1, topo_order=None):
|
| 1009 |
+
"""Returns the longest path in a directed acyclic graph (DAG).
|
| 1010 |
+
|
| 1011 |
+
If `G` has edges with `weight` attribute the edge data are used as
|
| 1012 |
+
weight values.
|
| 1013 |
+
|
| 1014 |
+
Parameters
|
| 1015 |
+
----------
|
| 1016 |
+
G : NetworkX DiGraph
|
| 1017 |
+
A directed acyclic graph (DAG)
|
| 1018 |
+
|
| 1019 |
+
weight : str, optional
|
| 1020 |
+
Edge data key to use for weight
|
| 1021 |
+
|
| 1022 |
+
default_weight : int, optional
|
| 1023 |
+
The weight of edges that do not have a weight attribute
|
| 1024 |
+
|
| 1025 |
+
topo_order: list or tuple, optional
|
| 1026 |
+
A topological order for `G` (if None, the function will compute one)
|
| 1027 |
+
|
| 1028 |
+
Returns
|
| 1029 |
+
-------
|
| 1030 |
+
list
|
| 1031 |
+
Longest path
|
| 1032 |
+
|
| 1033 |
+
Raises
|
| 1034 |
+
------
|
| 1035 |
+
NetworkXNotImplemented
|
| 1036 |
+
If `G` is not directed
|
| 1037 |
+
|
| 1038 |
+
Examples
|
| 1039 |
+
--------
|
| 1040 |
+
>>> DG = nx.DiGraph(
|
| 1041 |
+
... [(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})]
|
| 1042 |
+
... )
|
| 1043 |
+
>>> list(nx.all_simple_paths(DG, 0, 2))
|
| 1044 |
+
[[0, 1, 2], [0, 2]]
|
| 1045 |
+
>>> nx.dag_longest_path(DG)
|
| 1046 |
+
[0, 1, 2]
|
| 1047 |
+
>>> nx.dag_longest_path(DG, weight="cost")
|
| 1048 |
+
[0, 2]
|
| 1049 |
+
|
| 1050 |
+
In the case where multiple valid topological orderings exist, `topo_order`
|
| 1051 |
+
can be used to specify a specific ordering:
|
| 1052 |
+
|
| 1053 |
+
>>> DG = nx.DiGraph([(0, 1), (0, 2)])
|
| 1054 |
+
>>> sorted(nx.all_topological_sorts(DG)) # Valid topological orderings
|
| 1055 |
+
[[0, 1, 2], [0, 2, 1]]
|
| 1056 |
+
>>> nx.dag_longest_path(DG, topo_order=[0, 1, 2])
|
| 1057 |
+
[0, 1]
|
| 1058 |
+
>>> nx.dag_longest_path(DG, topo_order=[0, 2, 1])
|
| 1059 |
+
[0, 2]
|
| 1060 |
+
|
| 1061 |
+
See also
|
| 1062 |
+
--------
|
| 1063 |
+
dag_longest_path_length
|
| 1064 |
+
|
| 1065 |
+
"""
|
| 1066 |
+
if not G:
|
| 1067 |
+
return []
|
| 1068 |
+
|
| 1069 |
+
if topo_order is None:
|
| 1070 |
+
topo_order = nx.topological_sort(G)
|
| 1071 |
+
|
| 1072 |
+
dist = {} # stores {v : (length, u)}
|
| 1073 |
+
for v in topo_order:
|
| 1074 |
+
us = [
|
| 1075 |
+
(
|
| 1076 |
+
dist[u][0]
|
| 1077 |
+
+ (
|
| 1078 |
+
max(data.values(), key=lambda x: x.get(weight, default_weight))
|
| 1079 |
+
if G.is_multigraph()
|
| 1080 |
+
else data
|
| 1081 |
+
).get(weight, default_weight),
|
| 1082 |
+
u,
|
| 1083 |
+
)
|
| 1084 |
+
for u, data in G.pred[v].items()
|
| 1085 |
+
]
|
| 1086 |
+
|
| 1087 |
+
# Use the best predecessor if there is one and its distance is
|
| 1088 |
+
# non-negative, otherwise terminate.
|
| 1089 |
+
maxu = max(us, key=lambda x: x[0]) if us else (0, v)
|
| 1090 |
+
dist[v] = maxu if maxu[0] >= 0 else (0, v)
|
| 1091 |
+
|
| 1092 |
+
u = None
|
| 1093 |
+
v = max(dist, key=lambda x: dist[x][0])
|
| 1094 |
+
path = []
|
| 1095 |
+
while u != v:
|
| 1096 |
+
path.append(v)
|
| 1097 |
+
u = v
|
| 1098 |
+
v = dist[v][1]
|
| 1099 |
+
|
| 1100 |
+
path.reverse()
|
| 1101 |
+
return path
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
@not_implemented_for("undirected")
|
| 1105 |
+
@nx._dispatchable(edge_attrs={"weight": "default_weight"})
|
| 1106 |
+
def dag_longest_path_length(G, weight="weight", default_weight=1):
|
| 1107 |
+
"""Returns the longest path length in a DAG
|
| 1108 |
+
|
| 1109 |
+
Parameters
|
| 1110 |
+
----------
|
| 1111 |
+
G : NetworkX DiGraph
|
| 1112 |
+
A directed acyclic graph (DAG)
|
| 1113 |
+
|
| 1114 |
+
weight : string, optional
|
| 1115 |
+
Edge data key to use for weight
|
| 1116 |
+
|
| 1117 |
+
default_weight : int, optional
|
| 1118 |
+
The weight of edges that do not have a weight attribute
|
| 1119 |
+
|
| 1120 |
+
Returns
|
| 1121 |
+
-------
|
| 1122 |
+
int
|
| 1123 |
+
Longest path length
|
| 1124 |
+
|
| 1125 |
+
Raises
|
| 1126 |
+
------
|
| 1127 |
+
NetworkXNotImplemented
|
| 1128 |
+
If `G` is not directed
|
| 1129 |
+
|
| 1130 |
+
Examples
|
| 1131 |
+
--------
|
| 1132 |
+
>>> DG = nx.DiGraph(
|
| 1133 |
+
... [(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})]
|
| 1134 |
+
... )
|
| 1135 |
+
>>> list(nx.all_simple_paths(DG, 0, 2))
|
| 1136 |
+
[[0, 1, 2], [0, 2]]
|
| 1137 |
+
>>> nx.dag_longest_path_length(DG)
|
| 1138 |
+
2
|
| 1139 |
+
>>> nx.dag_longest_path_length(DG, weight="cost")
|
| 1140 |
+
42
|
| 1141 |
+
|
| 1142 |
+
See also
|
| 1143 |
+
--------
|
| 1144 |
+
dag_longest_path
|
| 1145 |
+
"""
|
| 1146 |
+
path = nx.dag_longest_path(G, weight, default_weight)
|
| 1147 |
+
path_length = 0
|
| 1148 |
+
if G.is_multigraph():
|
| 1149 |
+
for u, v in pairwise(path):
|
| 1150 |
+
i = max(G[u][v], key=lambda x: G[u][v][x].get(weight, default_weight))
|
| 1151 |
+
path_length += G[u][v][i].get(weight, default_weight)
|
| 1152 |
+
else:
|
| 1153 |
+
for u, v in pairwise(path):
|
| 1154 |
+
path_length += G[u][v].get(weight, default_weight)
|
| 1155 |
+
|
| 1156 |
+
return path_length
|
| 1157 |
+
|
| 1158 |
+
|
| 1159 |
+
@nx._dispatchable
|
| 1160 |
+
def root_to_leaf_paths(G):
|
| 1161 |
+
"""Yields root-to-leaf paths in a directed acyclic graph.
|
| 1162 |
+
|
| 1163 |
+
`G` must be a directed acyclic graph. If not, the behavior of this
|
| 1164 |
+
function is undefined. A "root" in this graph is a node of in-degree
|
| 1165 |
+
zero and a "leaf" a node of out-degree zero.
|
| 1166 |
+
|
| 1167 |
+
When invoked, this function iterates over each path from any root to
|
| 1168 |
+
any leaf. A path is a list of nodes.
|
| 1169 |
+
|
| 1170 |
+
"""
|
| 1171 |
+
roots = (v for v, d in G.in_degree() if d == 0)
|
| 1172 |
+
leaves = (v for v, d in G.out_degree() if d == 0)
|
| 1173 |
+
all_paths = partial(nx.all_simple_paths, G)
|
| 1174 |
+
# TODO In Python 3, this would be better as `yield from ...`.
|
| 1175 |
+
return chaini(starmap(all_paths, product(roots, leaves)))
|
| 1176 |
+
|
| 1177 |
+
|
| 1178 |
+
@not_implemented_for("multigraph")
|
| 1179 |
+
@not_implemented_for("undirected")
|
| 1180 |
+
@nx._dispatchable(returns_graph=True)
|
| 1181 |
+
def dag_to_branching(G):
|
| 1182 |
+
"""Returns a branching representing all (overlapping) paths from
|
| 1183 |
+
root nodes to leaf nodes in the given directed acyclic graph.
|
| 1184 |
+
|
| 1185 |
+
As described in :mod:`networkx.algorithms.tree.recognition`, a
|
| 1186 |
+
*branching* is a directed forest in which each node has at most one
|
| 1187 |
+
parent. In other words, a branching is a disjoint union of
|
| 1188 |
+
*arborescences*. For this function, each node of in-degree zero in
|
| 1189 |
+
`G` becomes a root of one of the arborescences, and there will be
|
| 1190 |
+
one leaf node for each distinct path from that root to a leaf node
|
| 1191 |
+
in `G`.
|
| 1192 |
+
|
| 1193 |
+
Each node `v` in `G` with *k* parents becomes *k* distinct nodes in
|
| 1194 |
+
the returned branching, one for each parent, and the sub-DAG rooted
|
| 1195 |
+
at `v` is duplicated for each copy. The algorithm then recurses on
|
| 1196 |
+
the children of each copy of `v`.
|
| 1197 |
+
|
| 1198 |
+
Parameters
|
| 1199 |
+
----------
|
| 1200 |
+
G : NetworkX graph
|
| 1201 |
+
A directed acyclic graph.
|
| 1202 |
+
|
| 1203 |
+
Returns
|
| 1204 |
+
-------
|
| 1205 |
+
DiGraph
|
| 1206 |
+
The branching in which there is a bijection between root-to-leaf
|
| 1207 |
+
paths in `G` (in which multiple paths may share the same leaf)
|
| 1208 |
+
and root-to-leaf paths in the branching (in which there is a
|
| 1209 |
+
unique path from a root to a leaf).
|
| 1210 |
+
|
| 1211 |
+
Each node has an attribute 'source' whose value is the original
|
| 1212 |
+
node to which this node corresponds. No other graph, node, or
|
| 1213 |
+
edge attributes are copied into this new graph.
|
| 1214 |
+
|
| 1215 |
+
Raises
|
| 1216 |
+
------
|
| 1217 |
+
NetworkXNotImplemented
|
| 1218 |
+
If `G` is not directed, or if `G` is a multigraph.
|
| 1219 |
+
|
| 1220 |
+
HasACycle
|
| 1221 |
+
If `G` is not acyclic.
|
| 1222 |
+
|
| 1223 |
+
Examples
|
| 1224 |
+
--------
|
| 1225 |
+
To examine which nodes in the returned branching were produced by
|
| 1226 |
+
which original node in the directed acyclic graph, we can collect
|
| 1227 |
+
the mapping from source node to new nodes into a dictionary. For
|
| 1228 |
+
example, consider the directed diamond graph::
|
| 1229 |
+
|
| 1230 |
+
>>> from collections import defaultdict
|
| 1231 |
+
>>> from operator import itemgetter
|
| 1232 |
+
>>>
|
| 1233 |
+
>>> G = nx.DiGraph(nx.utils.pairwise("abd"))
|
| 1234 |
+
>>> G.add_edges_from(nx.utils.pairwise("acd"))
|
| 1235 |
+
>>> B = nx.dag_to_branching(G)
|
| 1236 |
+
>>>
|
| 1237 |
+
>>> sources = defaultdict(set)
|
| 1238 |
+
>>> for v, source in B.nodes(data="source"):
|
| 1239 |
+
... sources[source].add(v)
|
| 1240 |
+
>>> len(sources["a"])
|
| 1241 |
+
1
|
| 1242 |
+
>>> len(sources["d"])
|
| 1243 |
+
2
|
| 1244 |
+
|
| 1245 |
+
To copy node attributes from the original graph to the new graph,
|
| 1246 |
+
you can use a dictionary like the one constructed in the above
|
| 1247 |
+
example::
|
| 1248 |
+
|
| 1249 |
+
>>> for source, nodes in sources.items():
|
| 1250 |
+
... for v in nodes:
|
| 1251 |
+
... B.nodes[v].update(G.nodes[source])
|
| 1252 |
+
|
| 1253 |
+
Notes
|
| 1254 |
+
-----
|
| 1255 |
+
This function is not idempotent in the sense that the node labels in
|
| 1256 |
+
the returned branching may be uniquely generated each time the
|
| 1257 |
+
function is invoked. In fact, the node labels may not be integers;
|
| 1258 |
+
in order to relabel the nodes to be more readable, you can use the
|
| 1259 |
+
:func:`networkx.convert_node_labels_to_integers` function.
|
| 1260 |
+
|
| 1261 |
+
The current implementation of this function uses
|
| 1262 |
+
:func:`networkx.prefix_tree`, so it is subject to the limitations of
|
| 1263 |
+
that function.
|
| 1264 |
+
|
| 1265 |
+
"""
|
| 1266 |
+
if has_cycle(G):
|
| 1267 |
+
msg = "dag_to_branching is only defined for acyclic graphs"
|
| 1268 |
+
raise nx.HasACycle(msg)
|
| 1269 |
+
paths = root_to_leaf_paths(G)
|
| 1270 |
+
B = nx.prefix_tree(paths)
|
| 1271 |
+
# Remove the synthetic `root`(0) and `NIL`(-1) nodes from the tree
|
| 1272 |
+
B.remove_node(0)
|
| 1273 |
+
B.remove_node(-1)
|
| 1274 |
+
return B
|
| 1275 |
+
|
| 1276 |
+
|
| 1277 |
+
@not_implemented_for("undirected")
|
| 1278 |
+
@nx._dispatchable
|
| 1279 |
+
def v_structures(G):
|
| 1280 |
+
"""Yields 3-node tuples that represent the v-structures in `G`.
|
| 1281 |
+
|
| 1282 |
+
Colliders are triples in the directed acyclic graph (DAG) where two parent nodes
|
| 1283 |
+
point to the same child node. V-structures are colliders where the two parent
|
| 1284 |
+
nodes are not adjacent. In a causal graph setting, the parents do not directly
|
| 1285 |
+
depend on each other, but conditioning on the child node provides an association.
|
| 1286 |
+
|
| 1287 |
+
Parameters
|
| 1288 |
+
----------
|
| 1289 |
+
G : graph
|
| 1290 |
+
A networkx `~networkx.DiGraph`.
|
| 1291 |
+
|
| 1292 |
+
Yields
|
| 1293 |
+
------
|
| 1294 |
+
A 3-tuple representation of a v-structure
|
| 1295 |
+
Each v-structure is a 3-tuple with the parent, collider, and other parent.
|
| 1296 |
+
|
| 1297 |
+
Raises
|
| 1298 |
+
------
|
| 1299 |
+
NetworkXNotImplemented
|
| 1300 |
+
If `G` is an undirected graph.
|
| 1301 |
+
|
| 1302 |
+
Examples
|
| 1303 |
+
--------
|
| 1304 |
+
>>> G = nx.DiGraph([(1, 2), (0, 4), (3, 1), (2, 4), (0, 5), (4, 5), (1, 5)])
|
| 1305 |
+
>>> nx.is_directed_acyclic_graph(G)
|
| 1306 |
+
True
|
| 1307 |
+
>>> list(nx.dag.v_structures(G))
|
| 1308 |
+
[(0, 4, 2), (0, 5, 1), (4, 5, 1)]
|
| 1309 |
+
|
| 1310 |
+
See Also
|
| 1311 |
+
--------
|
| 1312 |
+
colliders
|
| 1313 |
+
|
| 1314 |
+
Notes
|
| 1315 |
+
-----
|
| 1316 |
+
This function was written to be used on DAGs, however it works on cyclic graphs
|
| 1317 |
+
too. Since colliders are referred to in the cyclic causal graph literature
|
| 1318 |
+
[2]_ we allow cyclic graphs in this function. It is suggested that you test if
|
| 1319 |
+
your input graph is acyclic as in the example if you want that property.
|
| 1320 |
+
|
| 1321 |
+
References
|
| 1322 |
+
----------
|
| 1323 |
+
.. [1] `Pearl's PRIMER <https://bayes.cs.ucla.edu/PRIMER/primer-ch2.pdf>`_
|
| 1324 |
+
Ch-2 page 50: v-structures def.
|
| 1325 |
+
.. [2] A Hyttinen, P.O. Hoyer, F. Eberhardt, M J ̈arvisalo, (2013)
|
| 1326 |
+
"Discovering cyclic causal models with latent variables:
|
| 1327 |
+
a general SAT-based procedure", UAI'13: Proceedings of the Twenty-Ninth
|
| 1328 |
+
Conference on Uncertainty in Artificial Intelligence, pg 301–310,
|
| 1329 |
+
`doi:10.5555/3023638.3023669 <https://dl.acm.org/doi/10.5555/3023638.3023669>`_
|
| 1330 |
+
"""
|
| 1331 |
+
for p1, c, p2 in colliders(G):
|
| 1332 |
+
if not (G.has_edge(p1, p2) or G.has_edge(p2, p1)):
|
| 1333 |
+
yield (p1, c, p2)
|
| 1334 |
+
|
| 1335 |
+
|
| 1336 |
+
@not_implemented_for("undirected")
|
| 1337 |
+
@nx._dispatchable
|
| 1338 |
+
def colliders(G):
|
| 1339 |
+
"""Yields 3-node tuples that represent the colliders in `G`.
|
| 1340 |
+
|
| 1341 |
+
In a Directed Acyclic Graph (DAG), if you have three nodes A, B, and C, and
|
| 1342 |
+
there are edges from A to C and from B to C, then C is a collider [1]_ . In
|
| 1343 |
+
a causal graph setting, this means that both events A and B are "causing" C,
|
| 1344 |
+
and conditioning on C provide an association between A and B even if
|
| 1345 |
+
no direct causal relationship exists between A and B.
|
| 1346 |
+
|
| 1347 |
+
Parameters
|
| 1348 |
+
----------
|
| 1349 |
+
G : graph
|
| 1350 |
+
A networkx `~networkx.DiGraph`.
|
| 1351 |
+
|
| 1352 |
+
Yields
|
| 1353 |
+
------
|
| 1354 |
+
A 3-tuple representation of a collider
|
| 1355 |
+
Each collider is a 3-tuple with the parent, collider, and other parent.
|
| 1356 |
+
|
| 1357 |
+
Raises
|
| 1358 |
+
------
|
| 1359 |
+
NetworkXNotImplemented
|
| 1360 |
+
If `G` is an undirected graph.
|
| 1361 |
+
|
| 1362 |
+
Examples
|
| 1363 |
+
--------
|
| 1364 |
+
>>> G = nx.DiGraph([(1, 2), (0, 4), (3, 1), (2, 4), (0, 5), (4, 5), (1, 5)])
|
| 1365 |
+
>>> nx.is_directed_acyclic_graph(G)
|
| 1366 |
+
True
|
| 1367 |
+
>>> list(nx.dag.colliders(G))
|
| 1368 |
+
[(0, 4, 2), (0, 5, 4), (0, 5, 1), (4, 5, 1)]
|
| 1369 |
+
|
| 1370 |
+
See Also
|
| 1371 |
+
--------
|
| 1372 |
+
v_structures
|
| 1373 |
+
|
| 1374 |
+
Notes
|
| 1375 |
+
-----
|
| 1376 |
+
This function was written to be used on DAGs, however it works on cyclic graphs
|
| 1377 |
+
too. Since colliders are referred to in the cyclic causal graph literature
|
| 1378 |
+
[2]_ we allow cyclic graphs in this function. It is suggested that you test if
|
| 1379 |
+
your input graph is acyclic as in the example if you want that property.
|
| 1380 |
+
|
| 1381 |
+
References
|
| 1382 |
+
----------
|
| 1383 |
+
.. [1] `Wikipedia: Collider in causal graphs <https://en.wikipedia.org/wiki/Collider_(statistics)>`_
|
| 1384 |
+
.. [2] A Hyttinen, P.O. Hoyer, F. Eberhardt, M J ̈arvisalo, (2013)
|
| 1385 |
+
"Discovering cyclic causal models with latent variables:
|
| 1386 |
+
a general SAT-based procedure", UAI'13: Proceedings of the Twenty-Ninth
|
| 1387 |
+
Conference on Uncertainty in Artificial Intelligence, pg 301–310,
|
| 1388 |
+
`doi:10.5555/3023638.3023669 <https://dl.acm.org/doi/10.5555/3023638.3023669>`_
|
| 1389 |
+
"""
|
| 1390 |
+
for node in G.nodes:
|
| 1391 |
+
for p1, p2 in combinations(G.predecessors(node), 2):
|
| 1392 |
+
yield (p1, node, p2)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/distance_measures.py
ADDED
|
@@ -0,0 +1,1095 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"eccentricity",
|
| 10 |
+
"diameter",
|
| 11 |
+
"harmonic_diameter",
|
| 12 |
+
"radius",
|
| 13 |
+
"periphery",
|
| 14 |
+
"center",
|
| 15 |
+
"barycenter",
|
| 16 |
+
"resistance_distance",
|
| 17 |
+
"kemeny_constant",
|
| 18 |
+
"effective_graph_resistance",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _extrema_bounding(G, compute="diameter", weight=None):
|
| 23 |
+
"""Compute requested extreme distance metric of undirected graph G
|
| 24 |
+
|
| 25 |
+
Computation is based on smart lower and upper bounds, and in practice
|
| 26 |
+
linear in the number of nodes, rather than quadratic (except for some
|
| 27 |
+
border cases such as complete graphs or circle shaped graphs).
|
| 28 |
+
|
| 29 |
+
Parameters
|
| 30 |
+
----------
|
| 31 |
+
G : NetworkX graph
|
| 32 |
+
An undirected graph
|
| 33 |
+
|
| 34 |
+
compute : string denoting the requesting metric
|
| 35 |
+
"diameter" for the maximal eccentricity value,
|
| 36 |
+
"radius" for the minimal eccentricity value,
|
| 37 |
+
"periphery" for the set of nodes with eccentricity equal to the diameter,
|
| 38 |
+
"center" for the set of nodes with eccentricity equal to the radius,
|
| 39 |
+
"eccentricities" for the maximum distance from each node to all other nodes in G
|
| 40 |
+
|
| 41 |
+
weight : string, function, or None
|
| 42 |
+
If this is a string, then edge weights will be accessed via the
|
| 43 |
+
edge attribute with this key (that is, the weight of the edge
|
| 44 |
+
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
|
| 45 |
+
such edge attribute exists, the weight of the edge is assumed to
|
| 46 |
+
be one.
|
| 47 |
+
|
| 48 |
+
If this is a function, the weight of an edge is the value
|
| 49 |
+
returned by the function. The function must accept exactly three
|
| 50 |
+
positional arguments: the two endpoints of an edge and the
|
| 51 |
+
dictionary of edge attributes for that edge. The function must
|
| 52 |
+
return a number.
|
| 53 |
+
|
| 54 |
+
If this is None, every edge has weight/distance/cost 1.
|
| 55 |
+
|
| 56 |
+
Weights stored as floating point values can lead to small round-off
|
| 57 |
+
errors in distances. Use integer weights to avoid this.
|
| 58 |
+
|
| 59 |
+
Weights should be positive, since they are distances.
|
| 60 |
+
|
| 61 |
+
Returns
|
| 62 |
+
-------
|
| 63 |
+
value : value of the requested metric
|
| 64 |
+
int for "diameter" and "radius" or
|
| 65 |
+
list of nodes for "center" and "periphery" or
|
| 66 |
+
dictionary of eccentricity values keyed by node for "eccentricities"
|
| 67 |
+
|
| 68 |
+
Raises
|
| 69 |
+
------
|
| 70 |
+
NetworkXError
|
| 71 |
+
If the graph consists of multiple components
|
| 72 |
+
ValueError
|
| 73 |
+
If `compute` is not one of "diameter", "radius", "periphery", "center", or "eccentricities".
|
| 74 |
+
|
| 75 |
+
Notes
|
| 76 |
+
-----
|
| 77 |
+
This algorithm was proposed in [1]_ and discussed further in [2]_ and [3]_.
|
| 78 |
+
|
| 79 |
+
References
|
| 80 |
+
----------
|
| 81 |
+
.. [1] F. W. Takes, W. A. Kosters,
|
| 82 |
+
"Determining the diameter of small world networks."
|
| 83 |
+
Proceedings of the 20th ACM international conference on Information and
|
| 84 |
+
knowledge management, 2011
|
| 85 |
+
https://dl.acm.org/doi/abs/10.1145/2063576.2063748
|
| 86 |
+
.. [2] F. W. Takes, W. A. Kosters,
|
| 87 |
+
"Computing the Eccentricity Distribution of Large Graphs."
|
| 88 |
+
Algorithms, 2013
|
| 89 |
+
https://www.mdpi.com/1999-4893/6/1/100
|
| 90 |
+
.. [3] M. Borassi, P. Crescenzi, M. Habib, W. A. Kosters, A. Marino, F. W. Takes,
|
| 91 |
+
"Fast diameter and radius BFS-based computation in (weakly connected)
|
| 92 |
+
real-world graphs: With an application to the six degrees of separation
|
| 93 |
+
games."
|
| 94 |
+
Theoretical Computer Science, 2015
|
| 95 |
+
https://www.sciencedirect.com/science/article/pii/S0304397515001644
|
| 96 |
+
"""
|
| 97 |
+
# init variables
|
| 98 |
+
degrees = dict(G.degree()) # start with the highest degree node
|
| 99 |
+
minlowernode = max(degrees, key=degrees.get)
|
| 100 |
+
N = len(degrees) # number of nodes
|
| 101 |
+
# alternate between smallest lower and largest upper bound
|
| 102 |
+
high = False
|
| 103 |
+
# status variables
|
| 104 |
+
ecc_lower = dict.fromkeys(G, 0)
|
| 105 |
+
ecc_upper = dict.fromkeys(G, math.inf)
|
| 106 |
+
candidates = set(G)
|
| 107 |
+
|
| 108 |
+
# (re)set bound extremes
|
| 109 |
+
minlower = math.inf
|
| 110 |
+
maxlower = 0
|
| 111 |
+
minupper = math.inf
|
| 112 |
+
maxupper = 0
|
| 113 |
+
|
| 114 |
+
# repeat the following until there are no more candidates
|
| 115 |
+
while candidates:
|
| 116 |
+
if high:
|
| 117 |
+
current = maxuppernode # select node with largest upper bound
|
| 118 |
+
else:
|
| 119 |
+
current = minlowernode # select node with smallest lower bound
|
| 120 |
+
high = not high
|
| 121 |
+
|
| 122 |
+
# get distances from/to current node and derive eccentricity
|
| 123 |
+
dist = nx.shortest_path_length(G, source=current, weight=weight)
|
| 124 |
+
|
| 125 |
+
if len(dist) != N:
|
| 126 |
+
msg = "Cannot compute metric because graph is not connected."
|
| 127 |
+
raise nx.NetworkXError(msg)
|
| 128 |
+
current_ecc = max(dist.values())
|
| 129 |
+
|
| 130 |
+
# print status update
|
| 131 |
+
# print ("ecc of " + str(current) + " (" + str(ecc_lower[current]) + "/"
|
| 132 |
+
# + str(ecc_upper[current]) + ", deg: " + str(dist[current]) + ") is "
|
| 133 |
+
# + str(current_ecc))
|
| 134 |
+
# print(ecc_upper)
|
| 135 |
+
|
| 136 |
+
# (re)set bound extremes
|
| 137 |
+
maxuppernode = None
|
| 138 |
+
minlowernode = None
|
| 139 |
+
|
| 140 |
+
# update node bounds
|
| 141 |
+
for i in candidates:
|
| 142 |
+
# update eccentricity bounds
|
| 143 |
+
d = dist[i]
|
| 144 |
+
ecc_lower[i] = low = max(ecc_lower[i], max(d, (current_ecc - d)))
|
| 145 |
+
ecc_upper[i] = upp = min(ecc_upper[i], current_ecc + d)
|
| 146 |
+
|
| 147 |
+
# update min/max values of lower and upper bounds
|
| 148 |
+
minlower = min(ecc_lower[i], minlower)
|
| 149 |
+
maxlower = max(ecc_lower[i], maxlower)
|
| 150 |
+
minupper = min(ecc_upper[i], minupper)
|
| 151 |
+
maxupper = max(ecc_upper[i], maxupper)
|
| 152 |
+
|
| 153 |
+
# update candidate set
|
| 154 |
+
if compute == "diameter":
|
| 155 |
+
ruled_out = {
|
| 156 |
+
i
|
| 157 |
+
for i in candidates
|
| 158 |
+
if ecc_upper[i] <= maxlower and 2 * ecc_lower[i] >= maxupper
|
| 159 |
+
}
|
| 160 |
+
elif compute == "radius":
|
| 161 |
+
ruled_out = {
|
| 162 |
+
i
|
| 163 |
+
for i in candidates
|
| 164 |
+
if ecc_lower[i] >= minupper and ecc_upper[i] + 1 <= 2 * minlower
|
| 165 |
+
}
|
| 166 |
+
elif compute == "periphery":
|
| 167 |
+
ruled_out = {
|
| 168 |
+
i
|
| 169 |
+
for i in candidates
|
| 170 |
+
if ecc_upper[i] < maxlower
|
| 171 |
+
and (maxlower == maxupper or ecc_lower[i] > maxupper)
|
| 172 |
+
}
|
| 173 |
+
elif compute == "center":
|
| 174 |
+
ruled_out = {
|
| 175 |
+
i
|
| 176 |
+
for i in candidates
|
| 177 |
+
if ecc_lower[i] > minupper
|
| 178 |
+
and (minlower == minupper or ecc_upper[i] + 1 < 2 * minlower)
|
| 179 |
+
}
|
| 180 |
+
elif compute == "eccentricities":
|
| 181 |
+
ruled_out = set()
|
| 182 |
+
else:
|
| 183 |
+
msg = "compute must be one of 'diameter', 'radius', 'periphery', 'center', 'eccentricities'"
|
| 184 |
+
raise ValueError(msg)
|
| 185 |
+
|
| 186 |
+
ruled_out.update(i for i in candidates if ecc_lower[i] == ecc_upper[i])
|
| 187 |
+
candidates -= ruled_out
|
| 188 |
+
|
| 189 |
+
# for i in ruled_out:
|
| 190 |
+
# print("removing %g: ecc_u: %g maxl: %g ecc_l: %g maxu: %g"%
|
| 191 |
+
# (i,ecc_upper[i],maxlower,ecc_lower[i],maxupper))
|
| 192 |
+
# print("node %g: ecc_u: %g maxl: %g ecc_l: %g maxu: %g"%
|
| 193 |
+
# (4,ecc_upper[4],maxlower,ecc_lower[4],maxupper))
|
| 194 |
+
# print("NODE 4: %g"%(ecc_upper[4] <= maxlower))
|
| 195 |
+
# print("NODE 4: %g"%(2 * ecc_lower[4] >= maxupper))
|
| 196 |
+
# print("NODE 4: %g"%(ecc_upper[4] <= maxlower
|
| 197 |
+
# and 2 * ecc_lower[4] >= maxupper))
|
| 198 |
+
|
| 199 |
+
# updating maxuppernode and minlowernode for selection in next round
|
| 200 |
+
for i in candidates:
|
| 201 |
+
if (
|
| 202 |
+
minlowernode is None
|
| 203 |
+
or (
|
| 204 |
+
ecc_lower[i] == ecc_lower[minlowernode]
|
| 205 |
+
and degrees[i] > degrees[minlowernode]
|
| 206 |
+
)
|
| 207 |
+
or (ecc_lower[i] < ecc_lower[minlowernode])
|
| 208 |
+
):
|
| 209 |
+
minlowernode = i
|
| 210 |
+
|
| 211 |
+
if (
|
| 212 |
+
maxuppernode is None
|
| 213 |
+
or (
|
| 214 |
+
ecc_upper[i] == ecc_upper[maxuppernode]
|
| 215 |
+
and degrees[i] > degrees[maxuppernode]
|
| 216 |
+
)
|
| 217 |
+
or (ecc_upper[i] > ecc_upper[maxuppernode])
|
| 218 |
+
):
|
| 219 |
+
maxuppernode = i
|
| 220 |
+
|
| 221 |
+
# print status update
|
| 222 |
+
# print (" min=" + str(minlower) + "/" + str(minupper) +
|
| 223 |
+
# " max=" + str(maxlower) + "/" + str(maxupper) +
|
| 224 |
+
# " candidates: " + str(len(candidates)))
|
| 225 |
+
# print("cand:",candidates)
|
| 226 |
+
# print("ecc_l",ecc_lower)
|
| 227 |
+
# print("ecc_u",ecc_upper)
|
| 228 |
+
# wait = input("press Enter to continue")
|
| 229 |
+
|
| 230 |
+
# return the correct value of the requested metric
|
| 231 |
+
if compute == "diameter":
|
| 232 |
+
return maxlower
|
| 233 |
+
if compute == "radius":
|
| 234 |
+
return minupper
|
| 235 |
+
if compute == "periphery":
|
| 236 |
+
p = [v for v in G if ecc_lower[v] == maxlower]
|
| 237 |
+
return p
|
| 238 |
+
if compute == "center":
|
| 239 |
+
c = [v for v in G if ecc_upper[v] == minupper]
|
| 240 |
+
return c
|
| 241 |
+
if compute == "eccentricities":
|
| 242 |
+
return ecc_lower
|
| 243 |
+
return None
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 247 |
+
def eccentricity(G, v=None, sp=None, weight=None):
|
| 248 |
+
"""Returns the eccentricity of nodes in G.
|
| 249 |
+
|
| 250 |
+
The eccentricity of a node v is the maximum distance from v to
|
| 251 |
+
all other nodes in G.
|
| 252 |
+
|
| 253 |
+
Parameters
|
| 254 |
+
----------
|
| 255 |
+
G : NetworkX graph
|
| 256 |
+
A graph
|
| 257 |
+
|
| 258 |
+
v : node, optional
|
| 259 |
+
Return value of specified node
|
| 260 |
+
|
| 261 |
+
sp : dict of dicts, optional
|
| 262 |
+
All pairs shortest path lengths as a dictionary of dictionaries
|
| 263 |
+
|
| 264 |
+
weight : string, function, or None (default=None)
|
| 265 |
+
If this is a string, then edge weights will be accessed via the
|
| 266 |
+
edge attribute with this key (that is, the weight of the edge
|
| 267 |
+
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
|
| 268 |
+
such edge attribute exists, the weight of the edge is assumed to
|
| 269 |
+
be one.
|
| 270 |
+
|
| 271 |
+
If this is a function, the weight of an edge is the value
|
| 272 |
+
returned by the function. The function must accept exactly three
|
| 273 |
+
positional arguments: the two endpoints of an edge and the
|
| 274 |
+
dictionary of edge attributes for that edge. The function must
|
| 275 |
+
return a number.
|
| 276 |
+
|
| 277 |
+
If this is None, every edge has weight/distance/cost 1.
|
| 278 |
+
|
| 279 |
+
Weights stored as floating point values can lead to small round-off
|
| 280 |
+
errors in distances. Use integer weights to avoid this.
|
| 281 |
+
|
| 282 |
+
Weights should be positive, since they are distances.
|
| 283 |
+
|
| 284 |
+
Returns
|
| 285 |
+
-------
|
| 286 |
+
ecc : dictionary
|
| 287 |
+
A dictionary of eccentricity values keyed by node.
|
| 288 |
+
|
| 289 |
+
Examples
|
| 290 |
+
--------
|
| 291 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
|
| 292 |
+
>>> dict(nx.eccentricity(G))
|
| 293 |
+
{1: 2, 2: 3, 3: 2, 4: 2, 5: 3}
|
| 294 |
+
|
| 295 |
+
>>> dict(
|
| 296 |
+
... nx.eccentricity(G, v=[1, 5])
|
| 297 |
+
... ) # This returns the eccentricity of node 1 & 5
|
| 298 |
+
{1: 2, 5: 3}
|
| 299 |
+
|
| 300 |
+
"""
|
| 301 |
+
# if v is None: # none, use entire graph
|
| 302 |
+
# nodes=G.nodes()
|
| 303 |
+
# elif v in G: # is v a single node
|
| 304 |
+
# nodes=[v]
|
| 305 |
+
# else: # assume v is a container of nodes
|
| 306 |
+
# nodes=v
|
| 307 |
+
order = G.order()
|
| 308 |
+
e = {}
|
| 309 |
+
for n in G.nbunch_iter(v):
|
| 310 |
+
if sp is None:
|
| 311 |
+
length = nx.shortest_path_length(G, source=n, weight=weight)
|
| 312 |
+
|
| 313 |
+
L = len(length)
|
| 314 |
+
else:
|
| 315 |
+
try:
|
| 316 |
+
length = sp[n]
|
| 317 |
+
L = len(length)
|
| 318 |
+
except TypeError as err:
|
| 319 |
+
raise nx.NetworkXError('Format of "sp" is invalid.') from err
|
| 320 |
+
if L != order:
|
| 321 |
+
if G.is_directed():
|
| 322 |
+
msg = (
|
| 323 |
+
"Found infinite path length because the digraph is not"
|
| 324 |
+
" strongly connected"
|
| 325 |
+
)
|
| 326 |
+
else:
|
| 327 |
+
msg = "Found infinite path length because the graph is not connected"
|
| 328 |
+
raise nx.NetworkXError(msg)
|
| 329 |
+
|
| 330 |
+
e[n] = max(length.values())
|
| 331 |
+
|
| 332 |
+
if v in G:
|
| 333 |
+
return e[v] # return single value
|
| 334 |
+
return e
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 338 |
+
def diameter(G, e=None, usebounds=False, weight=None):
|
| 339 |
+
"""Returns the diameter of the graph G.
|
| 340 |
+
|
| 341 |
+
The diameter is the maximum eccentricity.
|
| 342 |
+
|
| 343 |
+
Parameters
|
| 344 |
+
----------
|
| 345 |
+
G : NetworkX graph
|
| 346 |
+
A graph
|
| 347 |
+
|
| 348 |
+
e : eccentricity dictionary, optional
|
| 349 |
+
A precomputed dictionary of eccentricities.
|
| 350 |
+
|
| 351 |
+
usebounds : bool, optional
|
| 352 |
+
If `True`, use extrema bounding (see Notes) when computing the diameter
|
| 353 |
+
for undirected graphs. Extrema bounding may accelerate the
|
| 354 |
+
distance calculation for some graphs. `usebounds` is ignored if `G` is
|
| 355 |
+
directed or if `e` is not `None`. Default is `False`.
|
| 356 |
+
|
| 357 |
+
weight : string, function, or None
|
| 358 |
+
If this is a string, then edge weights will be accessed via the
|
| 359 |
+
edge attribute with this key (that is, the weight of the edge
|
| 360 |
+
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
|
| 361 |
+
such edge attribute exists, the weight of the edge is assumed to
|
| 362 |
+
be one.
|
| 363 |
+
|
| 364 |
+
If this is a function, the weight of an edge is the value
|
| 365 |
+
returned by the function. The function must accept exactly three
|
| 366 |
+
positional arguments: the two endpoints of an edge and the
|
| 367 |
+
dictionary of edge attributes for that edge. The function must
|
| 368 |
+
return a number.
|
| 369 |
+
|
| 370 |
+
If this is None, every edge has weight/distance/cost 1.
|
| 371 |
+
|
| 372 |
+
Weights stored as floating point values can lead to small round-off
|
| 373 |
+
errors in distances. Use integer weights to avoid this.
|
| 374 |
+
|
| 375 |
+
Weights should be positive, since they are distances.
|
| 376 |
+
|
| 377 |
+
Returns
|
| 378 |
+
-------
|
| 379 |
+
d : integer
|
| 380 |
+
Diameter of graph
|
| 381 |
+
|
| 382 |
+
Notes
|
| 383 |
+
-----
|
| 384 |
+
When ``usebounds=True``, the computation makes use of smart lower
|
| 385 |
+
and upper bounds and is often linear in the number of nodes, rather than
|
| 386 |
+
quadratic (except for some border cases such as complete graphs or circle
|
| 387 |
+
shaped-graphs).
|
| 388 |
+
|
| 389 |
+
Examples
|
| 390 |
+
--------
|
| 391 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
|
| 392 |
+
>>> nx.diameter(G)
|
| 393 |
+
3
|
| 394 |
+
|
| 395 |
+
See Also
|
| 396 |
+
--------
|
| 397 |
+
eccentricity
|
| 398 |
+
"""
|
| 399 |
+
if usebounds is True and e is None and not G.is_directed():
|
| 400 |
+
return _extrema_bounding(G, compute="diameter", weight=weight)
|
| 401 |
+
if e is None:
|
| 402 |
+
e = eccentricity(G, weight=weight)
|
| 403 |
+
return max(e.values())
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 407 |
+
def harmonic_diameter(G, sp=None, *, weight=None):
|
| 408 |
+
"""Returns the harmonic diameter of the graph G.
|
| 409 |
+
|
| 410 |
+
The harmonic diameter of a graph is the harmonic mean of the distances
|
| 411 |
+
between all pairs of distinct vertices. Graphs that are not strongly
|
| 412 |
+
connected have infinite diameter and mean distance, making such
|
| 413 |
+
measures not useful. Restricting the diameter or mean distance to
|
| 414 |
+
finite distances yields paradoxical values (e.g., a perfect match
|
| 415 |
+
would have diameter one). The harmonic mean handles gracefully
|
| 416 |
+
infinite distances (e.g., a perfect match has harmonic diameter equal
|
| 417 |
+
to the number of vertices minus one), making it possible to assign a
|
| 418 |
+
meaningful value to all graphs.
|
| 419 |
+
|
| 420 |
+
Note that in [1] the harmonic diameter is called "connectivity length":
|
| 421 |
+
however, "harmonic diameter" is a more standard name from the
|
| 422 |
+
theory of metric spaces. The name "harmonic mean distance" is perhaps
|
| 423 |
+
a more descriptive name, but is not used in the literature, so we use the
|
| 424 |
+
name "harmonic diameter" here.
|
| 425 |
+
|
| 426 |
+
Parameters
|
| 427 |
+
----------
|
| 428 |
+
G : NetworkX graph
|
| 429 |
+
A graph
|
| 430 |
+
|
| 431 |
+
sp : dict of dicts, optional
|
| 432 |
+
All-pairs shortest path lengths as a dictionary of dictionaries
|
| 433 |
+
|
| 434 |
+
weight : string, function, or None (default=None)
|
| 435 |
+
If None, every edge has weight/distance 1.
|
| 436 |
+
If a string, use this edge attribute as the edge weight.
|
| 437 |
+
Any edge attribute not present defaults to 1.
|
| 438 |
+
If a function, the weight of an edge is the value returned by the function.
|
| 439 |
+
The function must accept exactly three positional arguments:
|
| 440 |
+
the two endpoints of an edge and the dictionary of edge attributes for
|
| 441 |
+
that edge. The function must return a number.
|
| 442 |
+
|
| 443 |
+
Returns
|
| 444 |
+
-------
|
| 445 |
+
hd : float
|
| 446 |
+
Harmonic diameter of graph
|
| 447 |
+
|
| 448 |
+
References
|
| 449 |
+
----------
|
| 450 |
+
.. [1] Massimo Marchiori and Vito Latora, "Harmony in the small-world".
|
| 451 |
+
*Physica A: Statistical Mechanics and Its Applications*
|
| 452 |
+
285(3-4), pages 539-546, 2000.
|
| 453 |
+
<https://doi.org/10.1016/S0378-4371(00)00311-3>
|
| 454 |
+
"""
|
| 455 |
+
order = G.order()
|
| 456 |
+
|
| 457 |
+
sum_invd = 0
|
| 458 |
+
for n in G:
|
| 459 |
+
if sp is None:
|
| 460 |
+
length = nx.single_source_dijkstra_path_length(G, n, weight=weight)
|
| 461 |
+
else:
|
| 462 |
+
try:
|
| 463 |
+
length = sp[n]
|
| 464 |
+
L = len(length)
|
| 465 |
+
except TypeError as err:
|
| 466 |
+
raise nx.NetworkXError('Format of "sp" is invalid.') from err
|
| 467 |
+
|
| 468 |
+
for d in length.values():
|
| 469 |
+
# Note that this will skip the zero distance from n to itself,
|
| 470 |
+
# as it should be, but also zero-weight paths in weighted graphs.
|
| 471 |
+
if d != 0:
|
| 472 |
+
sum_invd += 1 / d
|
| 473 |
+
|
| 474 |
+
if sum_invd != 0:
|
| 475 |
+
return order * (order - 1) / sum_invd
|
| 476 |
+
if order > 1:
|
| 477 |
+
return math.inf
|
| 478 |
+
return math.nan
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 482 |
+
def periphery(G, e=None, usebounds=False, weight=None):
|
| 483 |
+
"""Returns the periphery of the graph G.
|
| 484 |
+
|
| 485 |
+
The periphery is the set of nodes with eccentricity equal to the diameter.
|
| 486 |
+
|
| 487 |
+
Parameters
|
| 488 |
+
----------
|
| 489 |
+
G : NetworkX graph
|
| 490 |
+
A graph
|
| 491 |
+
|
| 492 |
+
e : eccentricity dictionary, optional
|
| 493 |
+
A precomputed dictionary of eccentricities.
|
| 494 |
+
|
| 495 |
+
usebounds : bool, optional
|
| 496 |
+
If `True`, use extrema bounding (see Notes) when computing the periphery
|
| 497 |
+
for undirected graphs. Extrema bounding may accelerate the
|
| 498 |
+
distance calculation for some graphs. `usebounds` is ignored if `G` is
|
| 499 |
+
directed or if `e` is not `None`. Default is `False`.
|
| 500 |
+
|
| 501 |
+
weight : string, function, or None
|
| 502 |
+
If this is a string, then edge weights will be accessed via the
|
| 503 |
+
edge attribute with this key (that is, the weight of the edge
|
| 504 |
+
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
|
| 505 |
+
such edge attribute exists, the weight of the edge is assumed to
|
| 506 |
+
be one.
|
| 507 |
+
|
| 508 |
+
If this is a function, the weight of an edge is the value
|
| 509 |
+
returned by the function. The function must accept exactly three
|
| 510 |
+
positional arguments: the two endpoints of an edge and the
|
| 511 |
+
dictionary of edge attributes for that edge. The function must
|
| 512 |
+
return a number.
|
| 513 |
+
|
| 514 |
+
If this is None, every edge has weight/distance/cost 1.
|
| 515 |
+
|
| 516 |
+
Weights stored as floating point values can lead to small round-off
|
| 517 |
+
errors in distances. Use integer weights to avoid this.
|
| 518 |
+
|
| 519 |
+
Weights should be positive, since they are distances.
|
| 520 |
+
|
| 521 |
+
Returns
|
| 522 |
+
-------
|
| 523 |
+
p : list
|
| 524 |
+
List of nodes in periphery
|
| 525 |
+
|
| 526 |
+
Notes
|
| 527 |
+
-----
|
| 528 |
+
When ``usebounds=True``, the computation makes use of smart lower
|
| 529 |
+
and upper bounds and is often linear in the number of nodes, rather than
|
| 530 |
+
quadratic (except for some border cases such as complete graphs or circle
|
| 531 |
+
shaped-graphs).
|
| 532 |
+
|
| 533 |
+
Examples
|
| 534 |
+
--------
|
| 535 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
|
| 536 |
+
>>> nx.periphery(G)
|
| 537 |
+
[2, 5]
|
| 538 |
+
|
| 539 |
+
See Also
|
| 540 |
+
--------
|
| 541 |
+
barycenter
|
| 542 |
+
center
|
| 543 |
+
"""
|
| 544 |
+
if usebounds is True and e is None and not G.is_directed():
|
| 545 |
+
return _extrema_bounding(G, compute="periphery", weight=weight)
|
| 546 |
+
if e is None:
|
| 547 |
+
e = eccentricity(G, weight=weight)
|
| 548 |
+
diameter = max(e.values())
|
| 549 |
+
p = [v for v in e if e[v] == diameter]
|
| 550 |
+
return p
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 554 |
+
def radius(G, e=None, usebounds=False, weight=None):
|
| 555 |
+
"""Returns the radius of the graph G.
|
| 556 |
+
|
| 557 |
+
The radius is the minimum eccentricity.
|
| 558 |
+
|
| 559 |
+
Parameters
|
| 560 |
+
----------
|
| 561 |
+
G : NetworkX graph
|
| 562 |
+
A graph
|
| 563 |
+
|
| 564 |
+
e : eccentricity dictionary, optional
|
| 565 |
+
A precomputed dictionary of eccentricities.
|
| 566 |
+
|
| 567 |
+
usebounds : bool, optional
|
| 568 |
+
If `True`, use extrema bounding (see Notes) when computing the radius
|
| 569 |
+
for undirected graphs. Extrema bounding may accelerate the
|
| 570 |
+
distance calculation for some graphs. `usebounds` is ignored if `G` is
|
| 571 |
+
directed or if `e` is not `None`. Default is `False`.
|
| 572 |
+
|
| 573 |
+
weight : string, function, or None
|
| 574 |
+
If this is a string, then edge weights will be accessed via the
|
| 575 |
+
edge attribute with this key (that is, the weight of the edge
|
| 576 |
+
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
|
| 577 |
+
such edge attribute exists, the weight of the edge is assumed to
|
| 578 |
+
be one.
|
| 579 |
+
|
| 580 |
+
If this is a function, the weight of an edge is the value
|
| 581 |
+
returned by the function. The function must accept exactly three
|
| 582 |
+
positional arguments: the two endpoints of an edge and the
|
| 583 |
+
dictionary of edge attributes for that edge. The function must
|
| 584 |
+
return a number.
|
| 585 |
+
|
| 586 |
+
If this is None, every edge has weight/distance/cost 1.
|
| 587 |
+
|
| 588 |
+
Weights stored as floating point values can lead to small round-off
|
| 589 |
+
errors in distances. Use integer weights to avoid this.
|
| 590 |
+
|
| 591 |
+
Weights should be positive, since they are distances.
|
| 592 |
+
|
| 593 |
+
Returns
|
| 594 |
+
-------
|
| 595 |
+
r : integer
|
| 596 |
+
Radius of graph
|
| 597 |
+
|
| 598 |
+
Notes
|
| 599 |
+
-----
|
| 600 |
+
When ``usebounds=True``, the computation makes use of smart lower
|
| 601 |
+
and upper bounds and is often linear in the number of nodes, rather than
|
| 602 |
+
quadratic (except for some border cases such as complete graphs or circle
|
| 603 |
+
shaped-graphs).
|
| 604 |
+
|
| 605 |
+
Examples
|
| 606 |
+
--------
|
| 607 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
|
| 608 |
+
>>> nx.radius(G)
|
| 609 |
+
2
|
| 610 |
+
|
| 611 |
+
"""
|
| 612 |
+
if usebounds is True and e is None and not G.is_directed():
|
| 613 |
+
return _extrema_bounding(G, compute="radius", weight=weight)
|
| 614 |
+
if e is None:
|
| 615 |
+
e = eccentricity(G, weight=weight)
|
| 616 |
+
return min(e.values())
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 620 |
+
def center(G, e=None, usebounds=False, weight=None):
|
| 621 |
+
"""Returns the center of the graph G.
|
| 622 |
+
|
| 623 |
+
The center is the set of nodes with eccentricity equal to radius.
|
| 624 |
+
|
| 625 |
+
Parameters
|
| 626 |
+
----------
|
| 627 |
+
G : NetworkX graph
|
| 628 |
+
A graph
|
| 629 |
+
|
| 630 |
+
e : eccentricity dictionary, optional
|
| 631 |
+
A precomputed dictionary of eccentricities.
|
| 632 |
+
|
| 633 |
+
usebounds : bool, optional
|
| 634 |
+
If `True`, use extrema bounding (see Notes) when computing the center
|
| 635 |
+
for undirected graphs. Extrema bounding may accelerate the
|
| 636 |
+
distance calculation for some graphs. `usebounds` is ignored if `G` is
|
| 637 |
+
directed or if `e` is not `None`. Default is `False`.
|
| 638 |
+
|
| 639 |
+
weight : string, function, or None
|
| 640 |
+
If this is a string, then edge weights will be accessed via the
|
| 641 |
+
edge attribute with this key (that is, the weight of the edge
|
| 642 |
+
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
|
| 643 |
+
such edge attribute exists, the weight of the edge is assumed to
|
| 644 |
+
be one.
|
| 645 |
+
|
| 646 |
+
If this is a function, the weight of an edge is the value
|
| 647 |
+
returned by the function. The function must accept exactly three
|
| 648 |
+
positional arguments: the two endpoints of an edge and the
|
| 649 |
+
dictionary of edge attributes for that edge. The function must
|
| 650 |
+
return a number.
|
| 651 |
+
|
| 652 |
+
If this is None, every edge has weight/distance/cost 1.
|
| 653 |
+
|
| 654 |
+
Weights stored as floating point values can lead to small round-off
|
| 655 |
+
errors in distances. Use integer weights to avoid this.
|
| 656 |
+
|
| 657 |
+
Weights should be positive, since they are distances.
|
| 658 |
+
|
| 659 |
+
Returns
|
| 660 |
+
-------
|
| 661 |
+
c : list
|
| 662 |
+
List of nodes in center
|
| 663 |
+
|
| 664 |
+
Notes
|
| 665 |
+
-----
|
| 666 |
+
When ``usebounds=True``, the computation makes use of smart lower
|
| 667 |
+
and upper bounds and is often linear in the number of nodes, rather than
|
| 668 |
+
quadratic (except for some border cases such as complete graphs or circle
|
| 669 |
+
shaped-graphs).
|
| 670 |
+
|
| 671 |
+
Examples
|
| 672 |
+
--------
|
| 673 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
|
| 674 |
+
>>> list(nx.center(G))
|
| 675 |
+
[1, 3, 4]
|
| 676 |
+
|
| 677 |
+
See Also
|
| 678 |
+
--------
|
| 679 |
+
:func:`~networkx.algorithms.tree.distance_measures.center` : tree center
|
| 680 |
+
barycenter
|
| 681 |
+
periphery
|
| 682 |
+
:func:`~networkx.algorithms.tree.distance_measures.centroid` : tree centroid
|
| 683 |
+
"""
|
| 684 |
+
if usebounds is True and e is None and not G.is_directed():
|
| 685 |
+
return _extrema_bounding(G, compute="center", weight=weight)
|
| 686 |
+
if e is None and weight is None and not G.is_directed() and nx.is_tree(G):
|
| 687 |
+
return nx.tree.center(G)
|
| 688 |
+
if e is None:
|
| 689 |
+
e = eccentricity(G, weight=weight)
|
| 690 |
+
radius = min(e.values())
|
| 691 |
+
p = [v for v in e if e[v] == radius]
|
| 692 |
+
return p
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
@nx._dispatchable(edge_attrs="weight", mutates_input={"attr": 2})
|
| 696 |
+
def barycenter(G, weight=None, attr=None, sp=None):
|
| 697 |
+
r"""Calculate barycenter of a connected graph, optionally with edge weights.
|
| 698 |
+
|
| 699 |
+
The :dfn:`barycenter` a
|
| 700 |
+
:func:`connected <networkx.algorithms.components.is_connected>` graph
|
| 701 |
+
:math:`G` is the subgraph induced by the set of its nodes :math:`v`
|
| 702 |
+
minimizing the objective function
|
| 703 |
+
|
| 704 |
+
.. math::
|
| 705 |
+
|
| 706 |
+
\sum_{u \in V(G)} d_G(u, v),
|
| 707 |
+
|
| 708 |
+
where :math:`d_G` is the (possibly weighted) :func:`path length
|
| 709 |
+
<networkx.algorithms.shortest_paths.generic.shortest_path_length>`.
|
| 710 |
+
The barycenter is also called the :dfn:`median`. See [West01]_, p. 78.
|
| 711 |
+
|
| 712 |
+
Parameters
|
| 713 |
+
----------
|
| 714 |
+
G : :class:`networkx.Graph`
|
| 715 |
+
The connected graph :math:`G`.
|
| 716 |
+
weight : :class:`str`, optional
|
| 717 |
+
Passed through to
|
| 718 |
+
:func:`~networkx.algorithms.shortest_paths.generic.shortest_path_length`.
|
| 719 |
+
attr : :class:`str`, optional
|
| 720 |
+
If given, write the value of the objective function to each node's
|
| 721 |
+
`attr` attribute. Otherwise do not store the value.
|
| 722 |
+
sp : dict of dicts, optional
|
| 723 |
+
All pairs shortest path lengths as a dictionary of dictionaries
|
| 724 |
+
|
| 725 |
+
Returns
|
| 726 |
+
-------
|
| 727 |
+
list
|
| 728 |
+
Nodes of `G` that induce the barycenter of `G`.
|
| 729 |
+
|
| 730 |
+
Raises
|
| 731 |
+
------
|
| 732 |
+
NetworkXNoPath
|
| 733 |
+
If `G` is disconnected. `G` may appear disconnected to
|
| 734 |
+
:func:`barycenter` if `sp` is given but is missing shortest path
|
| 735 |
+
lengths for any pairs.
|
| 736 |
+
ValueError
|
| 737 |
+
If `sp` and `weight` are both given.
|
| 738 |
+
|
| 739 |
+
Examples
|
| 740 |
+
--------
|
| 741 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
|
| 742 |
+
>>> nx.barycenter(G)
|
| 743 |
+
[1, 3, 4]
|
| 744 |
+
|
| 745 |
+
See Also
|
| 746 |
+
--------
|
| 747 |
+
center
|
| 748 |
+
periphery
|
| 749 |
+
:func:`~networkx.algorithms.tree.distance_measures.centroid` : tree centroid
|
| 750 |
+
"""
|
| 751 |
+
if weight is None and attr is None and sp is None:
|
| 752 |
+
if not G.is_directed() and nx.is_tree(G):
|
| 753 |
+
return nx.tree.centroid(G)
|
| 754 |
+
|
| 755 |
+
if sp is None:
|
| 756 |
+
sp = nx.shortest_path_length(G, weight=weight)
|
| 757 |
+
else:
|
| 758 |
+
sp = sp.items()
|
| 759 |
+
if weight is not None:
|
| 760 |
+
raise ValueError("Cannot use both sp, weight arguments together")
|
| 761 |
+
smallest, barycenter_vertices, n = float("inf"), [], len(G)
|
| 762 |
+
for v, dists in sp:
|
| 763 |
+
if len(dists) < n:
|
| 764 |
+
raise nx.NetworkXNoPath(
|
| 765 |
+
f"Input graph {G} is disconnected, so every induced subgraph "
|
| 766 |
+
"has infinite barycentricity."
|
| 767 |
+
)
|
| 768 |
+
barycentricity = sum(dists.values())
|
| 769 |
+
if attr is not None:
|
| 770 |
+
G.nodes[v][attr] = barycentricity
|
| 771 |
+
if barycentricity < smallest:
|
| 772 |
+
smallest = barycentricity
|
| 773 |
+
barycenter_vertices = [v]
|
| 774 |
+
elif barycentricity == smallest:
|
| 775 |
+
barycenter_vertices.append(v)
|
| 776 |
+
if attr is not None:
|
| 777 |
+
nx._clear_cache(G)
|
| 778 |
+
return barycenter_vertices
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
@not_implemented_for("directed")
|
| 782 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 783 |
+
def resistance_distance(G, nodeA=None, nodeB=None, weight=None, invert_weight=True):
|
| 784 |
+
"""Returns the resistance distance between pairs of nodes in graph G.
|
| 785 |
+
|
| 786 |
+
The resistance distance between two nodes of a graph is akin to treating
|
| 787 |
+
the graph as a grid of resistors with a resistance equal to the provided
|
| 788 |
+
weight [1]_, [2]_.
|
| 789 |
+
|
| 790 |
+
If weight is not provided, then a weight of 1 is used for all edges.
|
| 791 |
+
|
| 792 |
+
If two nodes are the same, the resistance distance is zero.
|
| 793 |
+
|
| 794 |
+
Parameters
|
| 795 |
+
----------
|
| 796 |
+
G : NetworkX graph
|
| 797 |
+
A graph
|
| 798 |
+
|
| 799 |
+
nodeA : node or None, optional (default=None)
|
| 800 |
+
A node within graph G.
|
| 801 |
+
If None, compute resistance distance using all nodes as source nodes.
|
| 802 |
+
|
| 803 |
+
nodeB : node or None, optional (default=None)
|
| 804 |
+
A node within graph G.
|
| 805 |
+
If None, compute resistance distance using all nodes as target nodes.
|
| 806 |
+
|
| 807 |
+
weight : string or None, optional (default=None)
|
| 808 |
+
The edge data key used to compute the resistance distance.
|
| 809 |
+
If None, then each edge has weight 1.
|
| 810 |
+
|
| 811 |
+
invert_weight : boolean (default=True)
|
| 812 |
+
Proper calculation of resistance distance requires building the
|
| 813 |
+
Laplacian matrix with the reciprocal of the weight. Not required
|
| 814 |
+
if the weight is already inverted. Weight cannot be zero.
|
| 815 |
+
|
| 816 |
+
Returns
|
| 817 |
+
-------
|
| 818 |
+
rd : dict or float
|
| 819 |
+
If `nodeA` and `nodeB` are given, resistance distance between `nodeA`
|
| 820 |
+
and `nodeB`. If `nodeA` or `nodeB` is unspecified (the default), a
|
| 821 |
+
dictionary of nodes with resistance distances as the value.
|
| 822 |
+
|
| 823 |
+
Raises
|
| 824 |
+
------
|
| 825 |
+
NetworkXNotImplemented
|
| 826 |
+
If `G` is a directed graph.
|
| 827 |
+
|
| 828 |
+
NetworkXError
|
| 829 |
+
If `G` is not connected, or contains no nodes,
|
| 830 |
+
or `nodeA` is not in `G` or `nodeB` is not in `G`.
|
| 831 |
+
|
| 832 |
+
Examples
|
| 833 |
+
--------
|
| 834 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
|
| 835 |
+
>>> round(nx.resistance_distance(G, 1, 3), 10)
|
| 836 |
+
0.625
|
| 837 |
+
|
| 838 |
+
Notes
|
| 839 |
+
-----
|
| 840 |
+
The implementation is based on Theorem A in [2]_. Self-loops are ignored.
|
| 841 |
+
Multi-edges are contracted in one edge with weight equal to the harmonic sum of the weights.
|
| 842 |
+
|
| 843 |
+
References
|
| 844 |
+
----------
|
| 845 |
+
.. [1] Wikipedia
|
| 846 |
+
"Resistance distance."
|
| 847 |
+
https://en.wikipedia.org/wiki/Resistance_distance
|
| 848 |
+
.. [2] D. J. Klein and M. Randic.
|
| 849 |
+
Resistance distance.
|
| 850 |
+
J. of Math. Chem. 12:81-95, 1993.
|
| 851 |
+
"""
|
| 852 |
+
import numpy as np
|
| 853 |
+
|
| 854 |
+
if len(G) == 0:
|
| 855 |
+
raise nx.NetworkXError("Graph G must contain at least one node.")
|
| 856 |
+
if not nx.is_connected(G):
|
| 857 |
+
raise nx.NetworkXError("Graph G must be strongly connected.")
|
| 858 |
+
if nodeA is not None and nodeA not in G:
|
| 859 |
+
raise nx.NetworkXError("Node A is not in graph G.")
|
| 860 |
+
if nodeB is not None and nodeB not in G:
|
| 861 |
+
raise nx.NetworkXError("Node B is not in graph G.")
|
| 862 |
+
|
| 863 |
+
G = G.copy()
|
| 864 |
+
node_list = list(G)
|
| 865 |
+
|
| 866 |
+
# Invert weights
|
| 867 |
+
if invert_weight and weight is not None:
|
| 868 |
+
if G.is_multigraph():
|
| 869 |
+
for u, v, k, d in G.edges(keys=True, data=True):
|
| 870 |
+
d[weight] = 1 / d[weight]
|
| 871 |
+
else:
|
| 872 |
+
for u, v, d in G.edges(data=True):
|
| 873 |
+
d[weight] = 1 / d[weight]
|
| 874 |
+
|
| 875 |
+
# Compute resistance distance using the Pseudo-inverse of the Laplacian
|
| 876 |
+
# Self-loops are ignored
|
| 877 |
+
L = nx.laplacian_matrix(G, weight=weight).todense()
|
| 878 |
+
Linv = np.linalg.pinv(L, hermitian=True)
|
| 879 |
+
|
| 880 |
+
# Return relevant distances
|
| 881 |
+
if nodeA is not None and nodeB is not None:
|
| 882 |
+
i = node_list.index(nodeA)
|
| 883 |
+
j = node_list.index(nodeB)
|
| 884 |
+
return Linv.item(i, i) + Linv.item(j, j) - Linv.item(i, j) - Linv.item(j, i)
|
| 885 |
+
|
| 886 |
+
elif nodeA is not None:
|
| 887 |
+
i = node_list.index(nodeA)
|
| 888 |
+
d = {}
|
| 889 |
+
for n in G:
|
| 890 |
+
j = node_list.index(n)
|
| 891 |
+
d[n] = Linv.item(i, i) + Linv.item(j, j) - Linv.item(i, j) - Linv.item(j, i)
|
| 892 |
+
return d
|
| 893 |
+
|
| 894 |
+
elif nodeB is not None:
|
| 895 |
+
j = node_list.index(nodeB)
|
| 896 |
+
d = {}
|
| 897 |
+
for n in G:
|
| 898 |
+
i = node_list.index(n)
|
| 899 |
+
d[n] = Linv.item(i, i) + Linv.item(j, j) - Linv.item(i, j) - Linv.item(j, i)
|
| 900 |
+
return d
|
| 901 |
+
|
| 902 |
+
else:
|
| 903 |
+
d = {}
|
| 904 |
+
for n in G:
|
| 905 |
+
i = node_list.index(n)
|
| 906 |
+
d[n] = {}
|
| 907 |
+
for n2 in G:
|
| 908 |
+
j = node_list.index(n2)
|
| 909 |
+
d[n][n2] = (
|
| 910 |
+
Linv.item(i, i)
|
| 911 |
+
+ Linv.item(j, j)
|
| 912 |
+
- Linv.item(i, j)
|
| 913 |
+
- Linv.item(j, i)
|
| 914 |
+
)
|
| 915 |
+
return d
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
@not_implemented_for("directed")
|
| 919 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 920 |
+
def effective_graph_resistance(G, weight=None, invert_weight=True):
|
| 921 |
+
"""Returns the Effective graph resistance of G.
|
| 922 |
+
|
| 923 |
+
Also known as the Kirchhoff index.
|
| 924 |
+
|
| 925 |
+
The effective graph resistance is defined as the sum
|
| 926 |
+
of the resistance distance of every node pair in G [1]_.
|
| 927 |
+
|
| 928 |
+
If weight is not provided, then a weight of 1 is used for all edges.
|
| 929 |
+
|
| 930 |
+
The effective graph resistance of a disconnected graph is infinite.
|
| 931 |
+
|
| 932 |
+
Parameters
|
| 933 |
+
----------
|
| 934 |
+
G : NetworkX graph
|
| 935 |
+
A graph
|
| 936 |
+
|
| 937 |
+
weight : string or None, optional (default=None)
|
| 938 |
+
The edge data key used to compute the effective graph resistance.
|
| 939 |
+
If None, then each edge has weight 1.
|
| 940 |
+
|
| 941 |
+
invert_weight : boolean (default=True)
|
| 942 |
+
Proper calculation of resistance distance requires building the
|
| 943 |
+
Laplacian matrix with the reciprocal of the weight. Not required
|
| 944 |
+
if the weight is already inverted. Weight cannot be zero.
|
| 945 |
+
|
| 946 |
+
Returns
|
| 947 |
+
-------
|
| 948 |
+
RG : float
|
| 949 |
+
The effective graph resistance of `G`.
|
| 950 |
+
|
| 951 |
+
Raises
|
| 952 |
+
------
|
| 953 |
+
NetworkXNotImplemented
|
| 954 |
+
If `G` is a directed graph.
|
| 955 |
+
|
| 956 |
+
NetworkXError
|
| 957 |
+
If `G` does not contain any nodes.
|
| 958 |
+
|
| 959 |
+
Examples
|
| 960 |
+
--------
|
| 961 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
|
| 962 |
+
>>> round(nx.effective_graph_resistance(G), 10)
|
| 963 |
+
10.25
|
| 964 |
+
|
| 965 |
+
Notes
|
| 966 |
+
-----
|
| 967 |
+
The implementation is based on Theorem 2.2 in [2]_. Self-loops are ignored.
|
| 968 |
+
Multi-edges are contracted in one edge with weight equal to the harmonic sum of the weights.
|
| 969 |
+
|
| 970 |
+
References
|
| 971 |
+
----------
|
| 972 |
+
.. [1] Wolfram
|
| 973 |
+
"Kirchhoff Index."
|
| 974 |
+
https://mathworld.wolfram.com/KirchhoffIndex.html
|
| 975 |
+
.. [2] W. Ellens, F. M. Spieksma, P. Van Mieghem, A. Jamakovic, R. E. Kooij.
|
| 976 |
+
Effective graph resistance.
|
| 977 |
+
Lin. Alg. Appl. 435:2491-2506, 2011.
|
| 978 |
+
"""
|
| 979 |
+
import numpy as np
|
| 980 |
+
|
| 981 |
+
if len(G) == 0:
|
| 982 |
+
raise nx.NetworkXError("Graph G must contain at least one node.")
|
| 983 |
+
|
| 984 |
+
# Disconnected graphs have infinite Effective graph resistance
|
| 985 |
+
if not nx.is_connected(G):
|
| 986 |
+
return float("inf")
|
| 987 |
+
|
| 988 |
+
# Invert weights
|
| 989 |
+
G = G.copy()
|
| 990 |
+
if invert_weight and weight is not None:
|
| 991 |
+
if G.is_multigraph():
|
| 992 |
+
for u, v, k, d in G.edges(keys=True, data=True):
|
| 993 |
+
d[weight] = 1 / d[weight]
|
| 994 |
+
else:
|
| 995 |
+
for u, v, d in G.edges(data=True):
|
| 996 |
+
d[weight] = 1 / d[weight]
|
| 997 |
+
|
| 998 |
+
# Get Laplacian eigenvalues
|
| 999 |
+
mu = np.sort(nx.laplacian_spectrum(G, weight=weight))
|
| 1000 |
+
|
| 1001 |
+
# Compute Effective graph resistance based on spectrum of the Laplacian
|
| 1002 |
+
# Self-loops are ignored
|
| 1003 |
+
return float(np.sum(1 / mu[1:]) * G.number_of_nodes())
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
@nx.utils.not_implemented_for("directed")
|
| 1007 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 1008 |
+
def kemeny_constant(G, *, weight=None):
|
| 1009 |
+
"""Returns the Kemeny constant of the given graph.
|
| 1010 |
+
|
| 1011 |
+
The *Kemeny constant* (or Kemeny's constant) of a graph `G`
|
| 1012 |
+
can be computed by regarding the graph as a Markov chain.
|
| 1013 |
+
The Kemeny constant is then the expected number of time steps
|
| 1014 |
+
to transition from a starting state i to a random destination state
|
| 1015 |
+
sampled from the Markov chain's stationary distribution.
|
| 1016 |
+
The Kemeny constant is independent of the chosen initial state [1]_.
|
| 1017 |
+
|
| 1018 |
+
The Kemeny constant measures the time needed for spreading
|
| 1019 |
+
across a graph. Low values indicate a closely connected graph
|
| 1020 |
+
whereas high values indicate a spread-out graph.
|
| 1021 |
+
|
| 1022 |
+
If weight is not provided, then a weight of 1 is used for all edges.
|
| 1023 |
+
|
| 1024 |
+
Since `G` represents a Markov chain, the weights must be positive.
|
| 1025 |
+
|
| 1026 |
+
Parameters
|
| 1027 |
+
----------
|
| 1028 |
+
G : NetworkX graph
|
| 1029 |
+
|
| 1030 |
+
weight : string or None, optional (default=None)
|
| 1031 |
+
The edge data key used to compute the Kemeny constant.
|
| 1032 |
+
If None, then each edge has weight 1.
|
| 1033 |
+
|
| 1034 |
+
Returns
|
| 1035 |
+
-------
|
| 1036 |
+
float
|
| 1037 |
+
The Kemeny constant of the graph `G`.
|
| 1038 |
+
|
| 1039 |
+
Raises
|
| 1040 |
+
------
|
| 1041 |
+
NetworkXNotImplemented
|
| 1042 |
+
If the graph `G` is directed.
|
| 1043 |
+
|
| 1044 |
+
NetworkXError
|
| 1045 |
+
If the graph `G` is not connected, or contains no nodes,
|
| 1046 |
+
or has edges with negative weights.
|
| 1047 |
+
|
| 1048 |
+
Examples
|
| 1049 |
+
--------
|
| 1050 |
+
>>> G = nx.complete_graph(5)
|
| 1051 |
+
>>> round(nx.kemeny_constant(G), 10)
|
| 1052 |
+
3.2
|
| 1053 |
+
|
| 1054 |
+
Notes
|
| 1055 |
+
-----
|
| 1056 |
+
The implementation is based on equation (3.3) in [2]_.
|
| 1057 |
+
Self-loops are allowed and indicate a Markov chain where
|
| 1058 |
+
the state can remain the same. Multi-edges are contracted
|
| 1059 |
+
in one edge with weight equal to the sum of the weights.
|
| 1060 |
+
|
| 1061 |
+
References
|
| 1062 |
+
----------
|
| 1063 |
+
.. [1] Wikipedia
|
| 1064 |
+
"Kemeny's constant."
|
| 1065 |
+
https://en.wikipedia.org/wiki/Kemeny%27s_constant
|
| 1066 |
+
.. [2] Lovász L.
|
| 1067 |
+
Random walks on graphs: A survey.
|
| 1068 |
+
Paul Erdös is Eighty, vol. 2, Bolyai Society,
|
| 1069 |
+
Mathematical Studies, Keszthely, Hungary (1993), pp. 1-46
|
| 1070 |
+
"""
|
| 1071 |
+
import numpy as np
|
| 1072 |
+
import scipy as sp
|
| 1073 |
+
|
| 1074 |
+
if len(G) == 0:
|
| 1075 |
+
raise nx.NetworkXError("Graph G must contain at least one node.")
|
| 1076 |
+
if not nx.is_connected(G):
|
| 1077 |
+
raise nx.NetworkXError("Graph G must be connected.")
|
| 1078 |
+
if nx.is_negatively_weighted(G, weight=weight):
|
| 1079 |
+
raise nx.NetworkXError("The weights of graph G must be nonnegative.")
|
| 1080 |
+
|
| 1081 |
+
# Compute matrix H = D^-1/2 A D^-1/2
|
| 1082 |
+
A = nx.adjacency_matrix(G, weight=weight)
|
| 1083 |
+
n, m = A.shape
|
| 1084 |
+
diags = A.sum(axis=1)
|
| 1085 |
+
with np.errstate(divide="ignore"):
|
| 1086 |
+
diags_sqrt = 1.0 / np.sqrt(diags)
|
| 1087 |
+
diags_sqrt[np.isinf(diags_sqrt)] = 0
|
| 1088 |
+
DH = sp.sparse.dia_array((diags_sqrt, 0), shape=(m, n)).tocsr()
|
| 1089 |
+
H = DH @ (A @ DH)
|
| 1090 |
+
|
| 1091 |
+
# Compute eigenvalues of H
|
| 1092 |
+
eig = np.sort(sp.linalg.eigvalsh(H.todense()))
|
| 1093 |
+
|
| 1094 |
+
# Compute the Kemeny constant
|
| 1095 |
+
return float(np.sum(1 / (1 - eig[:-1])))
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/distance_regular.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
=======================
|
| 3 |
+
Distance-regular graphs
|
| 4 |
+
=======================
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from itertools import combinations_with_replacement
|
| 9 |
+
from math import log
|
| 10 |
+
|
| 11 |
+
import networkx as nx
|
| 12 |
+
from networkx.utils import not_implemented_for
|
| 13 |
+
|
| 14 |
+
from .distance_measures import diameter
|
| 15 |
+
|
| 16 |
+
__all__ = [
|
| 17 |
+
"is_distance_regular",
|
| 18 |
+
"is_strongly_regular",
|
| 19 |
+
"intersection_array",
|
| 20 |
+
"global_parameters",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@nx._dispatchable
|
| 25 |
+
def is_distance_regular(G):
|
| 26 |
+
"""Returns True if the graph is distance regular, False otherwise.
|
| 27 |
+
|
| 28 |
+
A connected graph G is distance-regular if for any nodes x,y
|
| 29 |
+
and any integers i,j=0,1,...,d (where d is the graph
|
| 30 |
+
diameter), the number of vertices at distance i from x and
|
| 31 |
+
distance j from y depends only on i,j and the graph distance
|
| 32 |
+
between x and y, independently of the choice of x and y.
|
| 33 |
+
|
| 34 |
+
Parameters
|
| 35 |
+
----------
|
| 36 |
+
G: Networkx graph (undirected)
|
| 37 |
+
|
| 38 |
+
Returns
|
| 39 |
+
-------
|
| 40 |
+
bool
|
| 41 |
+
True if the graph is Distance Regular, False otherwise
|
| 42 |
+
|
| 43 |
+
Examples
|
| 44 |
+
--------
|
| 45 |
+
>>> G = nx.hypercube_graph(6)
|
| 46 |
+
>>> nx.is_distance_regular(G)
|
| 47 |
+
True
|
| 48 |
+
|
| 49 |
+
See Also
|
| 50 |
+
--------
|
| 51 |
+
intersection_array, global_parameters
|
| 52 |
+
|
| 53 |
+
Notes
|
| 54 |
+
-----
|
| 55 |
+
For undirected and simple graphs only
|
| 56 |
+
|
| 57 |
+
References
|
| 58 |
+
----------
|
| 59 |
+
.. [1] Brouwer, A. E.; Cohen, A. M.; and Neumaier, A.
|
| 60 |
+
Distance-Regular Graphs. New York: Springer-Verlag, 1989.
|
| 61 |
+
.. [2] Weisstein, Eric W. "Distance-Regular Graph."
|
| 62 |
+
http://mathworld.wolfram.com/Distance-RegularGraph.html
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
try:
|
| 66 |
+
intersection_array(G)
|
| 67 |
+
return True
|
| 68 |
+
except nx.NetworkXError:
|
| 69 |
+
return False
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def global_parameters(b, c):
|
| 73 |
+
"""Returns global parameters for a given intersection array.
|
| 74 |
+
|
| 75 |
+
Given a distance-regular graph G with diameter d and integers b_i,
|
| 76 |
+
c_i,i = 0,....,d such that for any 2 vertices x,y in G at a distance
|
| 77 |
+
i=d(x,y), there are exactly c_i neighbors of y at a distance of i-1 from x
|
| 78 |
+
and b_i neighbors of y at a distance of i+1 from x.
|
| 79 |
+
|
| 80 |
+
Thus, a distance regular graph has the global parameters,
|
| 81 |
+
[[c_0,a_0,b_0],[c_1,a_1,b_1],......,[c_d,a_d,b_d]] for the
|
| 82 |
+
intersection array [b_0,b_1,.....b_{d-1};c_1,c_2,.....c_d]
|
| 83 |
+
where a_i+b_i+c_i=k , k= degree of every vertex.
|
| 84 |
+
|
| 85 |
+
Parameters
|
| 86 |
+
----------
|
| 87 |
+
b : list
|
| 88 |
+
|
| 89 |
+
c : list
|
| 90 |
+
|
| 91 |
+
Returns
|
| 92 |
+
-------
|
| 93 |
+
iterable
|
| 94 |
+
An iterable over three tuples.
|
| 95 |
+
|
| 96 |
+
Examples
|
| 97 |
+
--------
|
| 98 |
+
>>> G = nx.dodecahedral_graph()
|
| 99 |
+
>>> b, c = nx.intersection_array(G)
|
| 100 |
+
>>> list(nx.global_parameters(b, c))
|
| 101 |
+
[(0, 0, 3), (1, 0, 2), (1, 1, 1), (1, 1, 1), (2, 0, 1), (3, 0, 0)]
|
| 102 |
+
|
| 103 |
+
References
|
| 104 |
+
----------
|
| 105 |
+
.. [1] Weisstein, Eric W. "Global Parameters."
|
| 106 |
+
From MathWorld--A Wolfram Web Resource.
|
| 107 |
+
http://mathworld.wolfram.com/GlobalParameters.html
|
| 108 |
+
|
| 109 |
+
See Also
|
| 110 |
+
--------
|
| 111 |
+
intersection_array
|
| 112 |
+
"""
|
| 113 |
+
return ((y, b[0] - x - y, x) for x, y in zip(b + [0], [0] + c))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@not_implemented_for("directed")
|
| 117 |
+
@not_implemented_for("multigraph")
|
| 118 |
+
@nx._dispatchable
|
| 119 |
+
def intersection_array(G):
|
| 120 |
+
"""Returns the intersection array of a distance-regular graph.
|
| 121 |
+
|
| 122 |
+
Given a distance-regular graph G with integers b_i, c_i,i = 0,....,d
|
| 123 |
+
such that for any 2 vertices x,y in G at a distance i=d(x,y), there
|
| 124 |
+
are exactly c_i neighbors of y at a distance of i-1 from x and b_i
|
| 125 |
+
neighbors of y at a distance of i+1 from x.
|
| 126 |
+
|
| 127 |
+
A distance regular graph's intersection array is given by,
|
| 128 |
+
[b_0,b_1,.....b_{d-1};c_1,c_2,.....c_d]
|
| 129 |
+
|
| 130 |
+
Parameters
|
| 131 |
+
----------
|
| 132 |
+
G: Networkx graph (undirected)
|
| 133 |
+
|
| 134 |
+
Returns
|
| 135 |
+
-------
|
| 136 |
+
b,c: tuple of lists
|
| 137 |
+
|
| 138 |
+
Examples
|
| 139 |
+
--------
|
| 140 |
+
>>> G = nx.icosahedral_graph()
|
| 141 |
+
>>> nx.intersection_array(G)
|
| 142 |
+
([5, 2, 1], [1, 2, 5])
|
| 143 |
+
|
| 144 |
+
References
|
| 145 |
+
----------
|
| 146 |
+
.. [1] Weisstein, Eric W. "Intersection Array."
|
| 147 |
+
From MathWorld--A Wolfram Web Resource.
|
| 148 |
+
http://mathworld.wolfram.com/IntersectionArray.html
|
| 149 |
+
|
| 150 |
+
See Also
|
| 151 |
+
--------
|
| 152 |
+
global_parameters
|
| 153 |
+
"""
|
| 154 |
+
# the input graph is very unlikely to be distance-regular: here are the
|
| 155 |
+
# number a(n) of connected simple graphs, and the number b(n) of
|
| 156 |
+
# distance-regular graphs among them:
|
| 157 |
+
#
|
| 158 |
+
# n | 1 2 3 4 5 6 7 8 9 10
|
| 159 |
+
# -----+------------------------------------------------------------------
|
| 160 |
+
# a(n) | 1 1 2 6 21 112 853 11117 261080 11716571 https://oeis.org/A001349
|
| 161 |
+
# b(n) | 1 1 1 2 2 4 2 5 4 7 https://oeis.org/A241814
|
| 162 |
+
#
|
| 163 |
+
# in light of this, let's compute shortest path lengths as we go instead of
|
| 164 |
+
# precomputing them all
|
| 165 |
+
# test for regular graph (all degrees must be equal)
|
| 166 |
+
if not nx.is_regular(G) or not nx.is_connected(G):
|
| 167 |
+
raise nx.NetworkXError("Graph is not distance regular.")
|
| 168 |
+
|
| 169 |
+
path_length = defaultdict(dict)
|
| 170 |
+
bint = {} # 'b' intersection array
|
| 171 |
+
cint = {} # 'c' intersection array
|
| 172 |
+
|
| 173 |
+
# see https://doi.org/10.1016/j.ejc.2004.07.004, Theorem 1.5, page 81:
|
| 174 |
+
# the diameter of a distance-regular graph is at most (8 log_2 n) / 3,
|
| 175 |
+
# so let's compute it as we go in the hope that we can stop early
|
| 176 |
+
diam = 0
|
| 177 |
+
max_diameter_for_dr_graphs = (8 * log(len(G), 2)) / 3
|
| 178 |
+
for u, v in combinations_with_replacement(G, 2):
|
| 179 |
+
# compute needed shortest path lengths
|
| 180 |
+
pl_u = path_length[u]
|
| 181 |
+
if v not in pl_u:
|
| 182 |
+
pl_u.update(nx.single_source_shortest_path_length(G, u))
|
| 183 |
+
for x, distance in pl_u.items():
|
| 184 |
+
path_length[x][u] = distance
|
| 185 |
+
|
| 186 |
+
i = path_length[u][v]
|
| 187 |
+
diam = max(diam, i)
|
| 188 |
+
|
| 189 |
+
# diameter too large: graph can't be distance-regular
|
| 190 |
+
if diam > max_diameter_for_dr_graphs:
|
| 191 |
+
raise nx.NetworkXError("Graph is not distance regular.")
|
| 192 |
+
|
| 193 |
+
vnbrs = G[v]
|
| 194 |
+
# compute needed path lengths
|
| 195 |
+
for n in vnbrs:
|
| 196 |
+
pl_n = path_length[n]
|
| 197 |
+
if u not in pl_n:
|
| 198 |
+
pl_n.update(nx.single_source_shortest_path_length(G, n))
|
| 199 |
+
for x, distance in pl_n.items():
|
| 200 |
+
path_length[x][n] = distance
|
| 201 |
+
|
| 202 |
+
# number of neighbors of v at a distance of i-1 from u
|
| 203 |
+
c = sum(1 for n in vnbrs if pl_u[n] == i - 1)
|
| 204 |
+
# number of neighbors of v at a distance of i+1 from u
|
| 205 |
+
b = sum(1 for n in vnbrs if pl_u[n] == i + 1)
|
| 206 |
+
# b, c are independent of u and v
|
| 207 |
+
if cint.get(i, c) != c or bint.get(i, b) != b:
|
| 208 |
+
raise nx.NetworkXError("Graph is not distance regular")
|
| 209 |
+
bint[i] = b
|
| 210 |
+
cint[i] = c
|
| 211 |
+
|
| 212 |
+
return (
|
| 213 |
+
[bint.get(j, 0) for j in range(diam)],
|
| 214 |
+
[cint.get(j + 1, 0) for j in range(diam)],
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# TODO There is a definition for directed strongly regular graphs.
|
| 219 |
+
@not_implemented_for("directed")
|
| 220 |
+
@not_implemented_for("multigraph")
|
| 221 |
+
@nx._dispatchable
|
| 222 |
+
def is_strongly_regular(G):
|
| 223 |
+
"""Returns True if and only if the given graph is strongly
|
| 224 |
+
regular.
|
| 225 |
+
|
| 226 |
+
An undirected graph is *strongly regular* if
|
| 227 |
+
|
| 228 |
+
* it is regular,
|
| 229 |
+
* each pair of adjacent vertices has the same number of neighbors in
|
| 230 |
+
common,
|
| 231 |
+
* each pair of nonadjacent vertices has the same number of neighbors
|
| 232 |
+
in common.
|
| 233 |
+
|
| 234 |
+
Each strongly regular graph is a distance-regular graph.
|
| 235 |
+
Conversely, if a distance-regular graph has diameter two, then it is
|
| 236 |
+
a strongly regular graph. For more information on distance-regular
|
| 237 |
+
graphs, see :func:`is_distance_regular`.
|
| 238 |
+
|
| 239 |
+
Parameters
|
| 240 |
+
----------
|
| 241 |
+
G : NetworkX graph
|
| 242 |
+
An undirected graph.
|
| 243 |
+
|
| 244 |
+
Returns
|
| 245 |
+
-------
|
| 246 |
+
bool
|
| 247 |
+
Whether `G` is strongly regular.
|
| 248 |
+
|
| 249 |
+
Examples
|
| 250 |
+
--------
|
| 251 |
+
|
| 252 |
+
The cycle graph on five vertices is strongly regular. It is
|
| 253 |
+
two-regular, each pair of adjacent vertices has no shared neighbors,
|
| 254 |
+
and each pair of nonadjacent vertices has one shared neighbor::
|
| 255 |
+
|
| 256 |
+
>>> G = nx.cycle_graph(5)
|
| 257 |
+
>>> nx.is_strongly_regular(G)
|
| 258 |
+
True
|
| 259 |
+
|
| 260 |
+
"""
|
| 261 |
+
# Here is an alternate implementation based directly on the
|
| 262 |
+
# definition of strongly regular graphs:
|
| 263 |
+
#
|
| 264 |
+
# return (all_equal(G.degree().values())
|
| 265 |
+
# and all_equal(len(common_neighbors(G, u, v))
|
| 266 |
+
# for u, v in G.edges())
|
| 267 |
+
# and all_equal(len(common_neighbors(G, u, v))
|
| 268 |
+
# for u, v in non_edges(G)))
|
| 269 |
+
#
|
| 270 |
+
# We instead use the fact that a distance-regular graph of diameter
|
| 271 |
+
# two is strongly regular.
|
| 272 |
+
return is_distance_regular(G) and diameter(G) == 2
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/dominance.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dominance algorithms.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from functools import reduce
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx.utils import not_implemented_for
|
| 9 |
+
|
| 10 |
+
__all__ = ["immediate_dominators", "dominance_frontiers"]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@not_implemented_for("undirected")
|
| 14 |
+
@nx._dispatchable
|
| 15 |
+
def immediate_dominators(G, start):
|
| 16 |
+
"""Returns the immediate dominators of all nodes of a directed graph.
|
| 17 |
+
|
| 18 |
+
Parameters
|
| 19 |
+
----------
|
| 20 |
+
G : a DiGraph or MultiDiGraph
|
| 21 |
+
The graph where dominance is to be computed.
|
| 22 |
+
|
| 23 |
+
start : node
|
| 24 |
+
The start node of dominance computation.
|
| 25 |
+
|
| 26 |
+
Returns
|
| 27 |
+
-------
|
| 28 |
+
idom : dict keyed by nodes
|
| 29 |
+
A dict containing the immediate dominators of each node reachable from
|
| 30 |
+
`start`, except for `start` itself.
|
| 31 |
+
|
| 32 |
+
Raises
|
| 33 |
+
------
|
| 34 |
+
NetworkXNotImplemented
|
| 35 |
+
If `G` is undirected.
|
| 36 |
+
|
| 37 |
+
NetworkXError
|
| 38 |
+
If `start` is not in `G`.
|
| 39 |
+
|
| 40 |
+
Notes
|
| 41 |
+
-----
|
| 42 |
+
The immediate dominators are the parents of their corresponding nodes in
|
| 43 |
+
the dominator tree. Every node reachable from `start` has an immediate
|
| 44 |
+
dominator, except for `start` itself.
|
| 45 |
+
|
| 46 |
+
Examples
|
| 47 |
+
--------
|
| 48 |
+
>>> G = nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])
|
| 49 |
+
>>> sorted(nx.immediate_dominators(G, 1).items())
|
| 50 |
+
[(2, 1), (3, 1), (4, 3), (5, 1)]
|
| 51 |
+
|
| 52 |
+
References
|
| 53 |
+
----------
|
| 54 |
+
.. [1] Cooper, Keith D., Harvey, Timothy J. and Kennedy, Ken.
|
| 55 |
+
"A simple, fast dominance algorithm." (2006).
|
| 56 |
+
https://hdl.handle.net/1911/96345
|
| 57 |
+
.. [2] Lengauer, Thomas; Tarjan, Robert Endre (July 1979).
|
| 58 |
+
"A fast algorithm for finding dominators in a flowgraph".
|
| 59 |
+
ACM Transactions on Programming Languages and Systems. 1 (1): 121--141.
|
| 60 |
+
https://dl.acm.org/doi/10.1145/357062.357071
|
| 61 |
+
"""
|
| 62 |
+
if start not in G:
|
| 63 |
+
raise nx.NetworkXError("start is not in G")
|
| 64 |
+
|
| 65 |
+
idom = {start: None}
|
| 66 |
+
|
| 67 |
+
order = list(nx.dfs_postorder_nodes(G, start))
|
| 68 |
+
dfn = {u: i for i, u in enumerate(order)}
|
| 69 |
+
order.pop()
|
| 70 |
+
order.reverse()
|
| 71 |
+
|
| 72 |
+
def intersect(u, v):
|
| 73 |
+
while u != v:
|
| 74 |
+
while dfn[u] < dfn[v]:
|
| 75 |
+
u = idom[u]
|
| 76 |
+
while dfn[u] > dfn[v]:
|
| 77 |
+
v = idom[v]
|
| 78 |
+
return u
|
| 79 |
+
|
| 80 |
+
changed = True
|
| 81 |
+
while changed:
|
| 82 |
+
changed = False
|
| 83 |
+
for u in order:
|
| 84 |
+
new_idom = reduce(intersect, (v for v in G.pred[u] if v in idom))
|
| 85 |
+
if u not in idom or idom[u] != new_idom:
|
| 86 |
+
idom[u] = new_idom
|
| 87 |
+
changed = True
|
| 88 |
+
|
| 89 |
+
del idom[start]
|
| 90 |
+
return idom
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@not_implemented_for("undirected")
|
| 94 |
+
@nx._dispatchable
|
| 95 |
+
def dominance_frontiers(G, start):
|
| 96 |
+
"""Returns the dominance frontiers of all nodes of a directed graph.
|
| 97 |
+
|
| 98 |
+
Parameters
|
| 99 |
+
----------
|
| 100 |
+
G : a DiGraph or MultiDiGraph
|
| 101 |
+
The graph where dominance is to be computed.
|
| 102 |
+
|
| 103 |
+
start : node
|
| 104 |
+
The start node of dominance computation.
|
| 105 |
+
|
| 106 |
+
Returns
|
| 107 |
+
-------
|
| 108 |
+
df : dict keyed by nodes
|
| 109 |
+
A dict containing the dominance frontiers of each node reachable from
|
| 110 |
+
`start` as lists.
|
| 111 |
+
|
| 112 |
+
Raises
|
| 113 |
+
------
|
| 114 |
+
NetworkXNotImplemented
|
| 115 |
+
If `G` is undirected.
|
| 116 |
+
|
| 117 |
+
NetworkXError
|
| 118 |
+
If `start` is not in `G`.
|
| 119 |
+
|
| 120 |
+
Examples
|
| 121 |
+
--------
|
| 122 |
+
>>> G = nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])
|
| 123 |
+
>>> sorted((u, sorted(df)) for u, df in nx.dominance_frontiers(G, 1).items())
|
| 124 |
+
[(1, []), (2, [5]), (3, [5]), (4, [5]), (5, [])]
|
| 125 |
+
|
| 126 |
+
References
|
| 127 |
+
----------
|
| 128 |
+
.. [1] Cooper, Keith D., Harvey, Timothy J. and Kennedy, Ken.
|
| 129 |
+
"A simple, fast dominance algorithm." (2006).
|
| 130 |
+
https://hdl.handle.net/1911/96345
|
| 131 |
+
"""
|
| 132 |
+
idom = nx.immediate_dominators(G, start) | {start: None}
|
| 133 |
+
|
| 134 |
+
df = {u: set() for u in idom}
|
| 135 |
+
for u in idom:
|
| 136 |
+
if u == start or len(G.pred[u]) >= 2:
|
| 137 |
+
for v in G.pred[u]:
|
| 138 |
+
if v in idom:
|
| 139 |
+
while v != idom[u]:
|
| 140 |
+
df[v].add(u)
|
| 141 |
+
v = idom[v]
|
| 142 |
+
return df
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/dominating.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for computing dominating sets in a graph."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from heapq import heappop, heappush
|
| 5 |
+
from itertools import chain, count
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
"dominating_set",
|
| 11 |
+
"is_dominating_set",
|
| 12 |
+
"connected_dominating_set",
|
| 13 |
+
"is_connected_dominating_set",
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@nx._dispatchable
|
| 18 |
+
def dominating_set(G, start_with=None):
|
| 19 |
+
r"""Finds a dominating set for the graph G.
|
| 20 |
+
|
| 21 |
+
A *dominating set* for a graph with node set *V* is a subset *D* of
|
| 22 |
+
*V* such that every node not in *D* is adjacent to at least one
|
| 23 |
+
member of *D* [1]_.
|
| 24 |
+
|
| 25 |
+
Parameters
|
| 26 |
+
----------
|
| 27 |
+
G : NetworkX graph
|
| 28 |
+
|
| 29 |
+
start_with : node (default=None)
|
| 30 |
+
Node to use as a starting point for the algorithm.
|
| 31 |
+
|
| 32 |
+
Returns
|
| 33 |
+
-------
|
| 34 |
+
D : set
|
| 35 |
+
A dominating set for G.
|
| 36 |
+
|
| 37 |
+
Notes
|
| 38 |
+
-----
|
| 39 |
+
This function is an implementation of algorithm 7 in [2]_ which
|
| 40 |
+
finds some dominating set, not necessarily the smallest one.
|
| 41 |
+
|
| 42 |
+
See also
|
| 43 |
+
--------
|
| 44 |
+
is_dominating_set
|
| 45 |
+
|
| 46 |
+
References
|
| 47 |
+
----------
|
| 48 |
+
.. [1] https://en.wikipedia.org/wiki/Dominating_set
|
| 49 |
+
|
| 50 |
+
.. [2] Abdol-Hossein Esfahanian. Connectivity Algorithms.
|
| 51 |
+
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
|
| 52 |
+
|
| 53 |
+
"""
|
| 54 |
+
all_nodes = set(G)
|
| 55 |
+
if start_with is None:
|
| 56 |
+
start_with = nx.utils.arbitrary_element(all_nodes)
|
| 57 |
+
if start_with not in G:
|
| 58 |
+
raise nx.NetworkXError(f"node {start_with} is not in G")
|
| 59 |
+
dominating_set = {start_with}
|
| 60 |
+
dominated_nodes = set(G[start_with])
|
| 61 |
+
remaining_nodes = all_nodes - dominated_nodes - dominating_set
|
| 62 |
+
while remaining_nodes:
|
| 63 |
+
# Choose an arbitrary node and determine its undominated neighbors.
|
| 64 |
+
v = remaining_nodes.pop()
|
| 65 |
+
undominated_nbrs = set(G[v]) - dominating_set
|
| 66 |
+
# Add the node to the dominating set and the neighbors to the
|
| 67 |
+
# dominated set. Finally, remove all of those nodes from the set
|
| 68 |
+
# of remaining nodes.
|
| 69 |
+
dominating_set.add(v)
|
| 70 |
+
dominated_nodes |= undominated_nbrs
|
| 71 |
+
remaining_nodes -= undominated_nbrs
|
| 72 |
+
return dominating_set
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@nx._dispatchable
|
| 76 |
+
def is_dominating_set(G, nbunch):
|
| 77 |
+
"""Checks if `nbunch` is a dominating set for `G`.
|
| 78 |
+
|
| 79 |
+
A *dominating set* for a graph with node set *V* is a subset *D* of
|
| 80 |
+
*V* such that every node not in *D* is adjacent to at least one
|
| 81 |
+
member of *D* [1]_.
|
| 82 |
+
|
| 83 |
+
Parameters
|
| 84 |
+
----------
|
| 85 |
+
G : NetworkX graph
|
| 86 |
+
|
| 87 |
+
nbunch : iterable
|
| 88 |
+
An iterable of nodes in the graph `G`.
|
| 89 |
+
|
| 90 |
+
Returns
|
| 91 |
+
-------
|
| 92 |
+
dominating : bool
|
| 93 |
+
True if `nbunch` is a dominating set of `G`, false otherwise.
|
| 94 |
+
|
| 95 |
+
See also
|
| 96 |
+
--------
|
| 97 |
+
dominating_set
|
| 98 |
+
|
| 99 |
+
References
|
| 100 |
+
----------
|
| 101 |
+
.. [1] https://en.wikipedia.org/wiki/Dominating_set
|
| 102 |
+
|
| 103 |
+
"""
|
| 104 |
+
testset = {n for n in nbunch if n in G}
|
| 105 |
+
nbrs = set(chain.from_iterable(G[n] for n in testset))
|
| 106 |
+
return len(set(G) - testset - nbrs) == 0
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@nx.utils.not_implemented_for("directed")
|
| 110 |
+
@nx._dispatchable
|
| 111 |
+
def connected_dominating_set(G):
|
| 112 |
+
"""Returns a connected dominating set.
|
| 113 |
+
|
| 114 |
+
A *dominating set* for a graph *G* with node set *V* is a subset *D* of *V*
|
| 115 |
+
such that every node not in *D* is adjacent to at least one member of *D*
|
| 116 |
+
[1]_. A *connected dominating set* is a dominating set *C* that induces a
|
| 117 |
+
connected subgraph of *G* [2]_.
|
| 118 |
+
Note that connected dominating sets are not unique in general and that there
|
| 119 |
+
may be other connected dominating sets.
|
| 120 |
+
|
| 121 |
+
Parameters
|
| 122 |
+
----------
|
| 123 |
+
G : NewtorkX graph
|
| 124 |
+
Undirected connected graph.
|
| 125 |
+
|
| 126 |
+
Returns
|
| 127 |
+
-------
|
| 128 |
+
connected_dominating_set : set
|
| 129 |
+
A dominating set of nodes which induces a connected subgraph of G.
|
| 130 |
+
|
| 131 |
+
Raises
|
| 132 |
+
------
|
| 133 |
+
NetworkXNotImplemented
|
| 134 |
+
If G is directed.
|
| 135 |
+
|
| 136 |
+
NetworkXError
|
| 137 |
+
If G is disconnected.
|
| 138 |
+
|
| 139 |
+
Examples
|
| 140 |
+
________
|
| 141 |
+
>>> G = nx.Graph(
|
| 142 |
+
... [
|
| 143 |
+
... (1, 2),
|
| 144 |
+
... (1, 3),
|
| 145 |
+
... (1, 4),
|
| 146 |
+
... (1, 5),
|
| 147 |
+
... (1, 6),
|
| 148 |
+
... (2, 7),
|
| 149 |
+
... (3, 8),
|
| 150 |
+
... (4, 9),
|
| 151 |
+
... (5, 10),
|
| 152 |
+
... (6, 11),
|
| 153 |
+
... (7, 12),
|
| 154 |
+
... (8, 12),
|
| 155 |
+
... (9, 12),
|
| 156 |
+
... (10, 12),
|
| 157 |
+
... (11, 12),
|
| 158 |
+
... ]
|
| 159 |
+
... )
|
| 160 |
+
>>> nx.connected_dominating_set(G)
|
| 161 |
+
{1, 2, 3, 4, 5, 6, 7}
|
| 162 |
+
|
| 163 |
+
Notes
|
| 164 |
+
-----
|
| 165 |
+
This function implements Algorithm I in its basic version as described
|
| 166 |
+
in [3]_. The idea behind the algorithm is the following: grow a tree *T*,
|
| 167 |
+
starting from a node with maximum degree. Throughout the growing process,
|
| 168 |
+
nonleaf nodes in *T* are our connected dominating set (CDS), leaf nodes in
|
| 169 |
+
*T* are marked as "seen" and nodes in G that are not yet in *T* are marked as
|
| 170 |
+
"unseen". We maintain a max-heap of all "seen" nodes, and track the number
|
| 171 |
+
of "unseen" neighbors for each node. At each step we pop the heap top -- a
|
| 172 |
+
"seen" (leaf) node with maximal number of "unseen" neighbors, add it to the
|
| 173 |
+
CDS and mark all its "unseen" neighbors as "seen". For each one of the newly
|
| 174 |
+
created "seen" nodes, we also decrement the number of "unseen" neighbors for
|
| 175 |
+
all its neighbors. The algorithm terminates when there are no more "unseen"
|
| 176 |
+
nodes.
|
| 177 |
+
Runtime complexity of this implementation is $O(|E|*log|V|)$ (amortized).
|
| 178 |
+
|
| 179 |
+
References
|
| 180 |
+
----------
|
| 181 |
+
.. [1] https://en.wikipedia.org/wiki/Dominating_set
|
| 182 |
+
.. [2] https://en.wikipedia.org/wiki/Connected_dominating_set
|
| 183 |
+
.. [3] Guha, S. and Khuller, S.
|
| 184 |
+
*Approximation Algorithms for Connected Dominating Sets*,
|
| 185 |
+
Algorithmica, 20, 374-387, 1998.
|
| 186 |
+
|
| 187 |
+
"""
|
| 188 |
+
if len(G) == 0:
|
| 189 |
+
return set()
|
| 190 |
+
|
| 191 |
+
if not nx.is_connected(G):
|
| 192 |
+
raise nx.NetworkXError("G must be a connected graph")
|
| 193 |
+
|
| 194 |
+
if len(G) == 1:
|
| 195 |
+
return set(G)
|
| 196 |
+
|
| 197 |
+
G_succ = G._adj # For speed-up
|
| 198 |
+
|
| 199 |
+
# Use the count c to avoid comparing nodes
|
| 200 |
+
c = count()
|
| 201 |
+
|
| 202 |
+
# Keep track of the number of unseen nodes adjacent to each node
|
| 203 |
+
unseen_degree = dict(G.degree)
|
| 204 |
+
|
| 205 |
+
# Find node with highest degree and update its neighbors
|
| 206 |
+
(max_deg_node, max_deg) = max(unseen_degree.items(), key=lambda x: x[1])
|
| 207 |
+
for nbr in G_succ[max_deg_node]:
|
| 208 |
+
unseen_degree[nbr] -= 1
|
| 209 |
+
|
| 210 |
+
# Initially all nodes except max_deg_node are unseen
|
| 211 |
+
unseen = set(G) - {max_deg_node}
|
| 212 |
+
|
| 213 |
+
# We want a max-heap of the unseen-degree using heapq, which is a min-heap
|
| 214 |
+
# So we store the negative of the unseen-degree
|
| 215 |
+
seen = [(-max_deg, next(c), max_deg_node)]
|
| 216 |
+
|
| 217 |
+
connected_dominating_set = set()
|
| 218 |
+
|
| 219 |
+
# Main loop
|
| 220 |
+
while unseen:
|
| 221 |
+
(neg_deg, cnt, u) = heappop(seen)
|
| 222 |
+
# Check if u's unseen-degree changed while in the heap
|
| 223 |
+
if -neg_deg > unseen_degree[u]:
|
| 224 |
+
heappush(seen, (-unseen_degree[u], cnt, u))
|
| 225 |
+
continue
|
| 226 |
+
# Mark all u's unseen neighbors as seen and add them to the heap
|
| 227 |
+
for v in G_succ[u]:
|
| 228 |
+
if v in unseen:
|
| 229 |
+
unseen.remove(v)
|
| 230 |
+
for nbr in G_succ[v]:
|
| 231 |
+
unseen_degree[nbr] -= 1
|
| 232 |
+
heappush(seen, (-unseen_degree[v], next(c), v))
|
| 233 |
+
# Add u to the dominating set
|
| 234 |
+
connected_dominating_set.add(u)
|
| 235 |
+
|
| 236 |
+
return connected_dominating_set
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@nx.utils.not_implemented_for("directed")
|
| 240 |
+
@nx._dispatchable
|
| 241 |
+
def is_connected_dominating_set(G, nbunch):
|
| 242 |
+
"""Checks if `nbunch` is a connected dominating set for `G`.
|
| 243 |
+
|
| 244 |
+
A *dominating set* for a graph *G* with node set *V* is a subset *D* of
|
| 245 |
+
*V* such that every node not in *D* is adjacent to at least one
|
| 246 |
+
member of *D* [1]_. A *connected dominating set* is a dominating
|
| 247 |
+
set *C* that induces a connected subgraph of *G* [2]_.
|
| 248 |
+
|
| 249 |
+
Parameters
|
| 250 |
+
----------
|
| 251 |
+
G : NetworkX graph
|
| 252 |
+
Undirected graph.
|
| 253 |
+
|
| 254 |
+
nbunch : iterable
|
| 255 |
+
An iterable of nodes in the graph `G`.
|
| 256 |
+
|
| 257 |
+
Returns
|
| 258 |
+
-------
|
| 259 |
+
connected_dominating : bool
|
| 260 |
+
True if `nbunch` is connected dominating set of `G`, false otherwise.
|
| 261 |
+
|
| 262 |
+
References
|
| 263 |
+
----------
|
| 264 |
+
.. [1] https://en.wikipedia.org/wiki/Dominating_set
|
| 265 |
+
.. [2] https://en.wikipedia.org/wiki/Connected_dominating_set
|
| 266 |
+
|
| 267 |
+
"""
|
| 268 |
+
return nx.is_dominating_set(G, nbunch) and nx.is_connected(nx.subgraph(G, nbunch))
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/efficiency_measures.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provides functions for computing the efficiency of nodes and graphs."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.exception import NetworkXNoPath
|
| 5 |
+
|
| 6 |
+
from ..utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = ["efficiency", "local_efficiency", "global_efficiency"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@not_implemented_for("directed")
|
| 12 |
+
@nx._dispatchable
|
| 13 |
+
def efficiency(G, u, v):
|
| 14 |
+
"""Returns the efficiency of a pair of nodes in a graph.
|
| 15 |
+
|
| 16 |
+
The *efficiency* of a pair of nodes is the multiplicative inverse of the
|
| 17 |
+
shortest path distance between the nodes [1]_. Returns 0 if no path
|
| 18 |
+
between nodes.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
G : :class:`networkx.Graph`
|
| 23 |
+
An undirected graph for which to compute the average local efficiency.
|
| 24 |
+
u, v : node
|
| 25 |
+
Nodes in the graph ``G``.
|
| 26 |
+
|
| 27 |
+
Returns
|
| 28 |
+
-------
|
| 29 |
+
float
|
| 30 |
+
Multiplicative inverse of the shortest path distance between the nodes.
|
| 31 |
+
|
| 32 |
+
Examples
|
| 33 |
+
--------
|
| 34 |
+
>>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
|
| 35 |
+
>>> nx.efficiency(G, 2, 3) # this gives efficiency for node 2 and 3
|
| 36 |
+
0.5
|
| 37 |
+
|
| 38 |
+
Notes
|
| 39 |
+
-----
|
| 40 |
+
Edge weights are ignored when computing the shortest path distances.
|
| 41 |
+
|
| 42 |
+
See also
|
| 43 |
+
--------
|
| 44 |
+
local_efficiency
|
| 45 |
+
global_efficiency
|
| 46 |
+
|
| 47 |
+
References
|
| 48 |
+
----------
|
| 49 |
+
.. [1] Latora, Vito, and Massimo Marchiori.
|
| 50 |
+
"Efficient behavior of small-world networks."
|
| 51 |
+
*Physical Review Letters* 87.19 (2001): 198701.
|
| 52 |
+
<https://doi.org/10.1103/PhysRevLett.87.198701>
|
| 53 |
+
|
| 54 |
+
"""
|
| 55 |
+
try:
|
| 56 |
+
eff = 1 / nx.shortest_path_length(G, u, v)
|
| 57 |
+
except NetworkXNoPath:
|
| 58 |
+
eff = 0
|
| 59 |
+
return eff
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@not_implemented_for("directed")
|
| 63 |
+
@nx._dispatchable
|
| 64 |
+
def global_efficiency(G):
|
| 65 |
+
"""Returns the average global efficiency of the graph.
|
| 66 |
+
|
| 67 |
+
The *efficiency* of a pair of nodes in a graph is the multiplicative
|
| 68 |
+
inverse of the shortest path distance between the nodes. The *average
|
| 69 |
+
global efficiency* of a graph is the average efficiency of all pairs of
|
| 70 |
+
nodes [1]_.
|
| 71 |
+
|
| 72 |
+
Parameters
|
| 73 |
+
----------
|
| 74 |
+
G : :class:`networkx.Graph`
|
| 75 |
+
An undirected graph for which to compute the average global efficiency.
|
| 76 |
+
|
| 77 |
+
Returns
|
| 78 |
+
-------
|
| 79 |
+
float
|
| 80 |
+
The average global efficiency of the graph.
|
| 81 |
+
|
| 82 |
+
Examples
|
| 83 |
+
--------
|
| 84 |
+
>>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
|
| 85 |
+
>>> round(nx.global_efficiency(G), 12)
|
| 86 |
+
0.916666666667
|
| 87 |
+
|
| 88 |
+
Notes
|
| 89 |
+
-----
|
| 90 |
+
Edge weights are ignored when computing the shortest path distances.
|
| 91 |
+
|
| 92 |
+
See also
|
| 93 |
+
--------
|
| 94 |
+
local_efficiency
|
| 95 |
+
|
| 96 |
+
References
|
| 97 |
+
----------
|
| 98 |
+
.. [1] Latora, Vito, and Massimo Marchiori.
|
| 99 |
+
"Efficient behavior of small-world networks."
|
| 100 |
+
*Physical Review Letters* 87.19 (2001): 198701.
|
| 101 |
+
<https://doi.org/10.1103/PhysRevLett.87.198701>
|
| 102 |
+
|
| 103 |
+
"""
|
| 104 |
+
n = len(G)
|
| 105 |
+
denom = n * (n - 1)
|
| 106 |
+
if denom != 0:
|
| 107 |
+
lengths = nx.all_pairs_shortest_path_length(G)
|
| 108 |
+
g_eff = 0
|
| 109 |
+
for source, targets in lengths:
|
| 110 |
+
for target, distance in targets.items():
|
| 111 |
+
if distance > 0:
|
| 112 |
+
g_eff += 1 / distance
|
| 113 |
+
g_eff /= denom
|
| 114 |
+
# g_eff = sum(1 / d for s, tgts in lengths
|
| 115 |
+
# for t, d in tgts.items() if d > 0) / denom
|
| 116 |
+
else:
|
| 117 |
+
g_eff = 0
|
| 118 |
+
# TODO This can be made more efficient by computing all pairs shortest
|
| 119 |
+
# path lengths in parallel.
|
| 120 |
+
return g_eff
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@not_implemented_for("directed")
|
| 124 |
+
@nx._dispatchable
|
| 125 |
+
def local_efficiency(G):
|
| 126 |
+
"""Returns the average local efficiency of the graph.
|
| 127 |
+
|
| 128 |
+
The *efficiency* of a pair of nodes in a graph is the multiplicative
|
| 129 |
+
inverse of the shortest path distance between the nodes. The *local
|
| 130 |
+
efficiency* of a node in the graph is the average global efficiency of the
|
| 131 |
+
subgraph induced by the neighbors of the node. The *average local
|
| 132 |
+
efficiency* is the average of the local efficiencies of each node [1]_.
|
| 133 |
+
|
| 134 |
+
Parameters
|
| 135 |
+
----------
|
| 136 |
+
G : :class:`networkx.Graph`
|
| 137 |
+
An undirected graph for which to compute the average local efficiency.
|
| 138 |
+
|
| 139 |
+
Returns
|
| 140 |
+
-------
|
| 141 |
+
float
|
| 142 |
+
The average local efficiency of the graph.
|
| 143 |
+
|
| 144 |
+
Examples
|
| 145 |
+
--------
|
| 146 |
+
>>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
|
| 147 |
+
>>> nx.local_efficiency(G)
|
| 148 |
+
0.9166666666666667
|
| 149 |
+
|
| 150 |
+
Notes
|
| 151 |
+
-----
|
| 152 |
+
Edge weights are ignored when computing the shortest path distances.
|
| 153 |
+
|
| 154 |
+
See also
|
| 155 |
+
--------
|
| 156 |
+
global_efficiency
|
| 157 |
+
|
| 158 |
+
References
|
| 159 |
+
----------
|
| 160 |
+
.. [1] Latora, Vito, and Massimo Marchiori.
|
| 161 |
+
"Efficient behavior of small-world networks."
|
| 162 |
+
*Physical Review Letters* 87.19 (2001): 198701.
|
| 163 |
+
<https://doi.org/10.1103/PhysRevLett.87.198701>
|
| 164 |
+
|
| 165 |
+
"""
|
| 166 |
+
efficiency_list = (global_efficiency(G.subgraph(G[v])) for v in G)
|
| 167 |
+
return sum(efficiency_list) / len(G)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/euler.py
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
|
| 5 |
+
from itertools import combinations
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
|
| 9 |
+
from ..utils import arbitrary_element, not_implemented_for
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"is_eulerian",
|
| 13 |
+
"eulerian_circuit",
|
| 14 |
+
"eulerize",
|
| 15 |
+
"is_semieulerian",
|
| 16 |
+
"has_eulerian_path",
|
| 17 |
+
"eulerian_path",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@nx._dispatchable
|
| 22 |
+
def is_eulerian(G):
|
| 23 |
+
"""Returns True if and only if `G` is Eulerian.
|
| 24 |
+
|
| 25 |
+
A graph is *Eulerian* if it has an Eulerian circuit. An *Eulerian
|
| 26 |
+
circuit* is a closed walk that includes each edge of a graph exactly
|
| 27 |
+
once.
|
| 28 |
+
|
| 29 |
+
Graphs with isolated vertices (i.e. vertices with zero degree) are not
|
| 30 |
+
considered to have Eulerian circuits. Therefore, if the graph is not
|
| 31 |
+
connected (or not strongly connected, for directed graphs), this function
|
| 32 |
+
returns False.
|
| 33 |
+
|
| 34 |
+
Parameters
|
| 35 |
+
----------
|
| 36 |
+
G : NetworkX graph
|
| 37 |
+
A graph, either directed or undirected.
|
| 38 |
+
|
| 39 |
+
Examples
|
| 40 |
+
--------
|
| 41 |
+
>>> nx.is_eulerian(nx.DiGraph({0: [3], 1: [2], 2: [3], 3: [0, 1]}))
|
| 42 |
+
True
|
| 43 |
+
>>> nx.is_eulerian(nx.complete_graph(5))
|
| 44 |
+
True
|
| 45 |
+
>>> nx.is_eulerian(nx.petersen_graph())
|
| 46 |
+
False
|
| 47 |
+
|
| 48 |
+
If you prefer to allow graphs with isolated vertices to have Eulerian circuits,
|
| 49 |
+
you can first remove such vertices and then call `is_eulerian` as below example shows.
|
| 50 |
+
|
| 51 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (0, 2)])
|
| 52 |
+
>>> G.add_node(3)
|
| 53 |
+
>>> nx.is_eulerian(G)
|
| 54 |
+
False
|
| 55 |
+
|
| 56 |
+
>>> G.remove_nodes_from(list(nx.isolates(G)))
|
| 57 |
+
>>> nx.is_eulerian(G)
|
| 58 |
+
True
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
"""
|
| 62 |
+
if G.is_directed():
|
| 63 |
+
# Every node must have equal in degree and out degree and the
|
| 64 |
+
# graph must be strongly connected
|
| 65 |
+
return all(
|
| 66 |
+
G.in_degree(n) == G.out_degree(n) for n in G
|
| 67 |
+
) and nx.is_strongly_connected(G)
|
| 68 |
+
# An undirected Eulerian graph has no vertices of odd degree and
|
| 69 |
+
# must be connected.
|
| 70 |
+
return all(d % 2 == 0 for v, d in G.degree()) and nx.is_connected(G)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@nx._dispatchable
|
| 74 |
+
def is_semieulerian(G):
|
| 75 |
+
"""Return True iff `G` is semi-Eulerian.
|
| 76 |
+
|
| 77 |
+
G is semi-Eulerian if it has an Eulerian path but no Eulerian circuit.
|
| 78 |
+
|
| 79 |
+
See Also
|
| 80 |
+
--------
|
| 81 |
+
has_eulerian_path
|
| 82 |
+
is_eulerian
|
| 83 |
+
"""
|
| 84 |
+
return has_eulerian_path(G) and not is_eulerian(G)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _find_path_start(G):
|
| 88 |
+
"""Return a suitable starting vertex for an Eulerian path.
|
| 89 |
+
|
| 90 |
+
If no path exists, return None.
|
| 91 |
+
"""
|
| 92 |
+
if not has_eulerian_path(G):
|
| 93 |
+
return None
|
| 94 |
+
|
| 95 |
+
if is_eulerian(G):
|
| 96 |
+
return arbitrary_element(G)
|
| 97 |
+
|
| 98 |
+
if G.is_directed():
|
| 99 |
+
v1, v2 = (v for v in G if G.in_degree(v) != G.out_degree(v))
|
| 100 |
+
# Determines which is the 'start' node (as opposed to the 'end')
|
| 101 |
+
if G.out_degree(v1) > G.in_degree(v1):
|
| 102 |
+
return v1
|
| 103 |
+
else:
|
| 104 |
+
return v2
|
| 105 |
+
|
| 106 |
+
else:
|
| 107 |
+
# In an undirected graph randomly choose one of the possibilities
|
| 108 |
+
start = [v for v in G if G.degree(v) % 2 != 0][0]
|
| 109 |
+
return start
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _simplegraph_eulerian_circuit(G, source):
|
| 113 |
+
if G.is_directed():
|
| 114 |
+
degree = G.out_degree
|
| 115 |
+
edges = G.out_edges
|
| 116 |
+
else:
|
| 117 |
+
degree = G.degree
|
| 118 |
+
edges = G.edges
|
| 119 |
+
vertex_stack = [source]
|
| 120 |
+
last_vertex = None
|
| 121 |
+
while vertex_stack:
|
| 122 |
+
current_vertex = vertex_stack[-1]
|
| 123 |
+
if degree(current_vertex) == 0:
|
| 124 |
+
if last_vertex is not None:
|
| 125 |
+
yield (last_vertex, current_vertex)
|
| 126 |
+
last_vertex = current_vertex
|
| 127 |
+
vertex_stack.pop()
|
| 128 |
+
else:
|
| 129 |
+
_, next_vertex = arbitrary_element(edges(current_vertex))
|
| 130 |
+
vertex_stack.append(next_vertex)
|
| 131 |
+
G.remove_edge(current_vertex, next_vertex)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _multigraph_eulerian_circuit(G, source):
|
| 135 |
+
if G.is_directed():
|
| 136 |
+
degree = G.out_degree
|
| 137 |
+
edges = G.out_edges
|
| 138 |
+
else:
|
| 139 |
+
degree = G.degree
|
| 140 |
+
edges = G.edges
|
| 141 |
+
vertex_stack = [(source, None)]
|
| 142 |
+
last_vertex = None
|
| 143 |
+
last_key = None
|
| 144 |
+
while vertex_stack:
|
| 145 |
+
current_vertex, current_key = vertex_stack[-1]
|
| 146 |
+
if degree(current_vertex) == 0:
|
| 147 |
+
if last_vertex is not None:
|
| 148 |
+
yield (last_vertex, current_vertex, last_key)
|
| 149 |
+
last_vertex, last_key = current_vertex, current_key
|
| 150 |
+
vertex_stack.pop()
|
| 151 |
+
else:
|
| 152 |
+
triple = arbitrary_element(edges(current_vertex, keys=True))
|
| 153 |
+
_, next_vertex, next_key = triple
|
| 154 |
+
vertex_stack.append((next_vertex, next_key))
|
| 155 |
+
G.remove_edge(current_vertex, next_vertex, next_key)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@nx._dispatchable
|
| 159 |
+
def eulerian_circuit(G, source=None, keys=False):
|
| 160 |
+
"""Returns an iterator over the edges of an Eulerian circuit in `G`.
|
| 161 |
+
|
| 162 |
+
An *Eulerian circuit* is a closed walk that includes each edge of a
|
| 163 |
+
graph exactly once.
|
| 164 |
+
|
| 165 |
+
Parameters
|
| 166 |
+
----------
|
| 167 |
+
G : NetworkX graph
|
| 168 |
+
A graph, either directed or undirected.
|
| 169 |
+
|
| 170 |
+
source : node, optional
|
| 171 |
+
Starting node for circuit.
|
| 172 |
+
|
| 173 |
+
keys : bool
|
| 174 |
+
If False, edges generated by this function will be of the form
|
| 175 |
+
``(u, v)``. Otherwise, edges will be of the form ``(u, v, k)``.
|
| 176 |
+
This option is ignored unless `G` is a multigraph.
|
| 177 |
+
|
| 178 |
+
Returns
|
| 179 |
+
-------
|
| 180 |
+
edges : iterator
|
| 181 |
+
An iterator over edges in the Eulerian circuit.
|
| 182 |
+
|
| 183 |
+
Raises
|
| 184 |
+
------
|
| 185 |
+
NetworkXError
|
| 186 |
+
If the graph is not Eulerian.
|
| 187 |
+
|
| 188 |
+
See Also
|
| 189 |
+
--------
|
| 190 |
+
is_eulerian
|
| 191 |
+
|
| 192 |
+
Notes
|
| 193 |
+
-----
|
| 194 |
+
This is a linear time implementation of an algorithm adapted from [1]_.
|
| 195 |
+
|
| 196 |
+
For general information about Euler tours, see [2]_.
|
| 197 |
+
|
| 198 |
+
References
|
| 199 |
+
----------
|
| 200 |
+
.. [1] J. Edmonds, E. L. Johnson.
|
| 201 |
+
Matching, Euler tours and the Chinese postman.
|
| 202 |
+
Mathematical programming, Volume 5, Issue 1 (1973), 111-114.
|
| 203 |
+
.. [2] https://en.wikipedia.org/wiki/Eulerian_path
|
| 204 |
+
|
| 205 |
+
Examples
|
| 206 |
+
--------
|
| 207 |
+
To get an Eulerian circuit in an undirected graph::
|
| 208 |
+
|
| 209 |
+
>>> G = nx.complete_graph(3)
|
| 210 |
+
>>> list(nx.eulerian_circuit(G))
|
| 211 |
+
[(0, 2), (2, 1), (1, 0)]
|
| 212 |
+
>>> list(nx.eulerian_circuit(G, source=1))
|
| 213 |
+
[(1, 2), (2, 0), (0, 1)]
|
| 214 |
+
|
| 215 |
+
To get the sequence of vertices in an Eulerian circuit::
|
| 216 |
+
|
| 217 |
+
>>> [u for u, v in nx.eulerian_circuit(G)]
|
| 218 |
+
[0, 2, 1]
|
| 219 |
+
|
| 220 |
+
"""
|
| 221 |
+
if not is_eulerian(G):
|
| 222 |
+
raise nx.NetworkXError("G is not Eulerian.")
|
| 223 |
+
if G.is_directed():
|
| 224 |
+
G = G.reverse()
|
| 225 |
+
else:
|
| 226 |
+
G = G.copy()
|
| 227 |
+
if source is None:
|
| 228 |
+
source = arbitrary_element(G)
|
| 229 |
+
if G.is_multigraph():
|
| 230 |
+
for u, v, k in _multigraph_eulerian_circuit(G, source):
|
| 231 |
+
if keys:
|
| 232 |
+
yield u, v, k
|
| 233 |
+
else:
|
| 234 |
+
yield u, v
|
| 235 |
+
else:
|
| 236 |
+
yield from _simplegraph_eulerian_circuit(G, source)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@nx._dispatchable
|
| 240 |
+
def has_eulerian_path(G, source=None):
|
| 241 |
+
"""Return True iff `G` has an Eulerian path.
|
| 242 |
+
|
| 243 |
+
An Eulerian path is a path in a graph which uses each edge of a graph
|
| 244 |
+
exactly once. If `source` is specified, then this function checks
|
| 245 |
+
whether an Eulerian path that starts at node `source` exists.
|
| 246 |
+
|
| 247 |
+
A directed graph has an Eulerian path iff:
|
| 248 |
+
- at most one vertex has out_degree - in_degree = 1,
|
| 249 |
+
- at most one vertex has in_degree - out_degree = 1,
|
| 250 |
+
- every other vertex has equal in_degree and out_degree,
|
| 251 |
+
- and all of its vertices belong to a single connected
|
| 252 |
+
component of the underlying undirected graph.
|
| 253 |
+
|
| 254 |
+
If `source` is not None, an Eulerian path starting at `source` exists if no
|
| 255 |
+
other node has out_degree - in_degree = 1. This is equivalent to either
|
| 256 |
+
there exists an Eulerian circuit or `source` has out_degree - in_degree = 1
|
| 257 |
+
and the conditions above hold.
|
| 258 |
+
|
| 259 |
+
An undirected graph has an Eulerian path iff:
|
| 260 |
+
- exactly zero or two vertices have odd degree,
|
| 261 |
+
- and all of its vertices belong to a single connected component.
|
| 262 |
+
|
| 263 |
+
If `source` is not None, an Eulerian path starting at `source` exists if
|
| 264 |
+
either there exists an Eulerian circuit or `source` has an odd degree and the
|
| 265 |
+
conditions above hold.
|
| 266 |
+
|
| 267 |
+
Graphs with isolated vertices (i.e. vertices with zero degree) are not considered
|
| 268 |
+
to have an Eulerian path. Therefore, if the graph is not connected (or not strongly
|
| 269 |
+
connected, for directed graphs), this function returns False.
|
| 270 |
+
|
| 271 |
+
Parameters
|
| 272 |
+
----------
|
| 273 |
+
G : NetworkX Graph
|
| 274 |
+
The graph to find an euler path in.
|
| 275 |
+
|
| 276 |
+
source : node, optional
|
| 277 |
+
Starting node for path.
|
| 278 |
+
|
| 279 |
+
Returns
|
| 280 |
+
-------
|
| 281 |
+
Bool : True if G has an Eulerian path.
|
| 282 |
+
|
| 283 |
+
Examples
|
| 284 |
+
--------
|
| 285 |
+
If you prefer to allow graphs with isolated vertices to have Eulerian path,
|
| 286 |
+
you can first remove such vertices and then call `has_eulerian_path` as below example shows.
|
| 287 |
+
|
| 288 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (0, 2)])
|
| 289 |
+
>>> G.add_node(3)
|
| 290 |
+
>>> nx.has_eulerian_path(G)
|
| 291 |
+
False
|
| 292 |
+
|
| 293 |
+
>>> G.remove_nodes_from(list(nx.isolates(G)))
|
| 294 |
+
>>> nx.has_eulerian_path(G)
|
| 295 |
+
True
|
| 296 |
+
|
| 297 |
+
See Also
|
| 298 |
+
--------
|
| 299 |
+
is_eulerian
|
| 300 |
+
eulerian_path
|
| 301 |
+
"""
|
| 302 |
+
if nx.is_eulerian(G):
|
| 303 |
+
return True
|
| 304 |
+
|
| 305 |
+
if G.is_directed():
|
| 306 |
+
ins = G.in_degree
|
| 307 |
+
outs = G.out_degree
|
| 308 |
+
# Since we know it is not eulerian, outs - ins must be 1 for source
|
| 309 |
+
if source is not None and outs[source] - ins[source] != 1:
|
| 310 |
+
return False
|
| 311 |
+
|
| 312 |
+
unbalanced_ins = 0
|
| 313 |
+
unbalanced_outs = 0
|
| 314 |
+
for v in G:
|
| 315 |
+
if ins[v] - outs[v] == 1:
|
| 316 |
+
unbalanced_ins += 1
|
| 317 |
+
elif outs[v] - ins[v] == 1:
|
| 318 |
+
unbalanced_outs += 1
|
| 319 |
+
elif ins[v] != outs[v]:
|
| 320 |
+
return False
|
| 321 |
+
|
| 322 |
+
return (
|
| 323 |
+
unbalanced_ins <= 1 and unbalanced_outs <= 1 and nx.is_weakly_connected(G)
|
| 324 |
+
)
|
| 325 |
+
else:
|
| 326 |
+
# We know it is not eulerian, so degree of source must be odd.
|
| 327 |
+
if source is not None and G.degree[source] % 2 != 1:
|
| 328 |
+
return False
|
| 329 |
+
|
| 330 |
+
# Sum is 2 since we know it is not eulerian (which implies sum is 0)
|
| 331 |
+
return sum(d % 2 == 1 for v, d in G.degree()) == 2 and nx.is_connected(G)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
@nx._dispatchable
|
| 335 |
+
def eulerian_path(G, source=None, keys=False):
|
| 336 |
+
"""Return an iterator over the edges of an Eulerian path in `G`.
|
| 337 |
+
|
| 338 |
+
Parameters
|
| 339 |
+
----------
|
| 340 |
+
G : NetworkX Graph
|
| 341 |
+
The graph in which to look for an eulerian path.
|
| 342 |
+
source : node or None (default: None)
|
| 343 |
+
The node at which to start the search. None means search over all
|
| 344 |
+
starting nodes.
|
| 345 |
+
keys : Bool (default: False)
|
| 346 |
+
Indicates whether to yield edge 3-tuples (u, v, edge_key).
|
| 347 |
+
The default yields edge 2-tuples
|
| 348 |
+
|
| 349 |
+
Yields
|
| 350 |
+
------
|
| 351 |
+
Edge tuples along the eulerian path.
|
| 352 |
+
|
| 353 |
+
Warning: If `source` provided is not the start node of an Euler path
|
| 354 |
+
will raise error even if an Euler Path exists.
|
| 355 |
+
"""
|
| 356 |
+
if not has_eulerian_path(G, source):
|
| 357 |
+
raise nx.NetworkXError("Graph has no Eulerian paths.")
|
| 358 |
+
if G.is_directed():
|
| 359 |
+
G = G.reverse()
|
| 360 |
+
if source is None or nx.is_eulerian(G) is False:
|
| 361 |
+
source = _find_path_start(G)
|
| 362 |
+
if G.is_multigraph():
|
| 363 |
+
for u, v, k in _multigraph_eulerian_circuit(G, source):
|
| 364 |
+
if keys:
|
| 365 |
+
yield u, v, k
|
| 366 |
+
else:
|
| 367 |
+
yield u, v
|
| 368 |
+
else:
|
| 369 |
+
yield from _simplegraph_eulerian_circuit(G, source)
|
| 370 |
+
else:
|
| 371 |
+
G = G.copy()
|
| 372 |
+
if source is None:
|
| 373 |
+
source = _find_path_start(G)
|
| 374 |
+
if G.is_multigraph():
|
| 375 |
+
if keys:
|
| 376 |
+
yield from reversed(
|
| 377 |
+
[(v, u, k) for u, v, k in _multigraph_eulerian_circuit(G, source)]
|
| 378 |
+
)
|
| 379 |
+
else:
|
| 380 |
+
yield from reversed(
|
| 381 |
+
[(v, u) for u, v, k in _multigraph_eulerian_circuit(G, source)]
|
| 382 |
+
)
|
| 383 |
+
else:
|
| 384 |
+
yield from reversed(
|
| 385 |
+
[(v, u) for u, v in _simplegraph_eulerian_circuit(G, source)]
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
@not_implemented_for("directed")
|
| 390 |
+
@nx._dispatchable(returns_graph=True)
|
| 391 |
+
def eulerize(G):
|
| 392 |
+
"""Transforms a graph into an Eulerian graph.
|
| 393 |
+
|
| 394 |
+
If `G` is Eulerian the result is `G` as a MultiGraph, otherwise the result is a smallest
|
| 395 |
+
(in terms of the number of edges) multigraph whose underlying simple graph is `G`.
|
| 396 |
+
|
| 397 |
+
Parameters
|
| 398 |
+
----------
|
| 399 |
+
G : NetworkX graph
|
| 400 |
+
An undirected graph
|
| 401 |
+
|
| 402 |
+
Returns
|
| 403 |
+
-------
|
| 404 |
+
G : NetworkX multigraph
|
| 405 |
+
|
| 406 |
+
Raises
|
| 407 |
+
------
|
| 408 |
+
NetworkXError
|
| 409 |
+
If the graph is not connected.
|
| 410 |
+
|
| 411 |
+
See Also
|
| 412 |
+
--------
|
| 413 |
+
is_eulerian
|
| 414 |
+
eulerian_circuit
|
| 415 |
+
|
| 416 |
+
References
|
| 417 |
+
----------
|
| 418 |
+
.. [1] J. Edmonds, E. L. Johnson.
|
| 419 |
+
Matching, Euler tours and the Chinese postman.
|
| 420 |
+
Mathematical programming, Volume 5, Issue 1 (1973), 111-114.
|
| 421 |
+
.. [2] https://en.wikipedia.org/wiki/Eulerian_path
|
| 422 |
+
.. [3] http://web.math.princeton.edu/math_alive/5/Notes1.pdf
|
| 423 |
+
|
| 424 |
+
Examples
|
| 425 |
+
--------
|
| 426 |
+
>>> G = nx.complete_graph(10)
|
| 427 |
+
>>> H = nx.eulerize(G)
|
| 428 |
+
>>> nx.is_eulerian(H)
|
| 429 |
+
True
|
| 430 |
+
|
| 431 |
+
"""
|
| 432 |
+
if G.order() == 0:
|
| 433 |
+
raise nx.NetworkXPointlessConcept("Cannot Eulerize null graph")
|
| 434 |
+
if not nx.is_connected(G):
|
| 435 |
+
raise nx.NetworkXError("G is not connected")
|
| 436 |
+
odd_degree_nodes = [n for n, d in G.degree() if d % 2 == 1]
|
| 437 |
+
G = nx.MultiGraph(G)
|
| 438 |
+
if len(odd_degree_nodes) == 0:
|
| 439 |
+
return G
|
| 440 |
+
|
| 441 |
+
# get all shortest paths between vertices of odd degree
|
| 442 |
+
odd_deg_pairs_paths = [
|
| 443 |
+
(m, {n: nx.shortest_path(G, source=m, target=n)})
|
| 444 |
+
for m, n in combinations(odd_degree_nodes, 2)
|
| 445 |
+
]
|
| 446 |
+
|
| 447 |
+
# use the number of vertices in a graph + 1 as an upper bound on
|
| 448 |
+
# the maximum length of a path in G
|
| 449 |
+
upper_bound_on_max_path_length = len(G) + 1
|
| 450 |
+
|
| 451 |
+
# use "len(G) + 1 - len(P)",
|
| 452 |
+
# where P is a shortest path between vertices n and m,
|
| 453 |
+
# as edge-weights in a new graph
|
| 454 |
+
# store the paths in the graph for easy indexing later
|
| 455 |
+
Gp = nx.Graph()
|
| 456 |
+
for n, Ps in odd_deg_pairs_paths:
|
| 457 |
+
for m, P in Ps.items():
|
| 458 |
+
if n != m:
|
| 459 |
+
Gp.add_edge(
|
| 460 |
+
m, n, weight=upper_bound_on_max_path_length - len(P), path=P
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
# find the minimum weight matching of edges in the weighted graph
|
| 464 |
+
best_matching = nx.Graph(list(nx.max_weight_matching(Gp)))
|
| 465 |
+
|
| 466 |
+
# duplicate each edge along each path in the set of paths in Gp
|
| 467 |
+
for m, n in best_matching.edges():
|
| 468 |
+
path = Gp[m][n]["path"]
|
| 469 |
+
G.add_edges_from(nx.utils.pairwise(path))
|
| 470 |
+
return G
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/graph_hashing.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Functions for hashing graphs to strings.
|
| 3 |
+
Isomorphic graphs should be assigned identical hashes.
|
| 4 |
+
For now, only Weisfeiler-Lehman hashing is implemented.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import warnings
|
| 8 |
+
from collections import Counter, defaultdict
|
| 9 |
+
from hashlib import blake2b
|
| 10 |
+
|
| 11 |
+
import networkx as nx
|
| 12 |
+
|
| 13 |
+
__all__ = ["weisfeiler_lehman_graph_hash", "weisfeiler_lehman_subgraph_hashes"]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _hash_label(label, digest_size):
|
| 17 |
+
return blake2b(label.encode("ascii"), digest_size=digest_size).hexdigest()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _init_node_labels(G, edge_attr, node_attr):
|
| 21 |
+
if node_attr:
|
| 22 |
+
return {u: str(dd[node_attr]) for u, dd in G.nodes(data=True)}
|
| 23 |
+
elif edge_attr:
|
| 24 |
+
return {u: "" for u in G}
|
| 25 |
+
else:
|
| 26 |
+
warnings.warn(
|
| 27 |
+
"The hashes produced for graphs without node or edge attributes "
|
| 28 |
+
"changed in v3.5 due to a bugfix (see documentation).",
|
| 29 |
+
UserWarning,
|
| 30 |
+
stacklevel=2,
|
| 31 |
+
)
|
| 32 |
+
if nx.is_directed(G):
|
| 33 |
+
return {u: str(G.in_degree(u)) + "_" + str(G.out_degree(u)) for u in G}
|
| 34 |
+
else:
|
| 35 |
+
return {u: str(deg) for u, deg in G.degree()}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _neighborhood_aggregate_undirected(G, node, node_labels, edge_attr=None):
|
| 39 |
+
"""
|
| 40 |
+
Compute new labels for given node in an undirected graph by aggregating
|
| 41 |
+
the labels of each node's neighbors.
|
| 42 |
+
"""
|
| 43 |
+
label_list = []
|
| 44 |
+
for nbr in G.neighbors(node):
|
| 45 |
+
prefix = "" if edge_attr is None else str(G[node][nbr][edge_attr])
|
| 46 |
+
label_list.append(prefix + node_labels[nbr])
|
| 47 |
+
return node_labels[node] + "".join(sorted(label_list))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _neighborhood_aggregate_directed(G, node, node_labels, edge_attr=None):
|
| 51 |
+
"""
|
| 52 |
+
Compute new labels for given node in a directed graph by aggregating
|
| 53 |
+
the labels of each node's neighbors.
|
| 54 |
+
"""
|
| 55 |
+
successor_labels = []
|
| 56 |
+
for nbr in G.successors(node):
|
| 57 |
+
prefix = "s_" + "" if edge_attr is None else str(G[node][nbr][edge_attr])
|
| 58 |
+
successor_labels.append(prefix + node_labels[nbr])
|
| 59 |
+
|
| 60 |
+
predecessor_labels = []
|
| 61 |
+
for nbr in G.predecessors(node):
|
| 62 |
+
prefix = "p_" + "" if edge_attr is None else str(G[nbr][node][edge_attr])
|
| 63 |
+
predecessor_labels.append(prefix + node_labels[nbr])
|
| 64 |
+
return (
|
| 65 |
+
node_labels[node]
|
| 66 |
+
+ "".join(sorted(successor_labels))
|
| 67 |
+
+ "".join(sorted(predecessor_labels))
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 72 |
+
@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")
|
| 73 |
+
def weisfeiler_lehman_graph_hash(
|
| 74 |
+
G, edge_attr=None, node_attr=None, iterations=3, digest_size=16
|
| 75 |
+
):
|
| 76 |
+
"""Return Weisfeiler Lehman (WL) graph hash.
|
| 77 |
+
|
| 78 |
+
.. Warning:: Hash values for directed graphs and graphs without edge or
|
| 79 |
+
node attributes have changed in v3.5. In previous versions,
|
| 80 |
+
directed graphs did not distinguish in- and outgoing edges. Also,
|
| 81 |
+
graphs without attributes set initial states such that effectively
|
| 82 |
+
one extra iteration of WL occurred than indicated by `iterations`.
|
| 83 |
+
For undirected graphs without node or edge labels, the old
|
| 84 |
+
hashes can be obtained by increasing the iteration count by one.
|
| 85 |
+
For more details, see `issue #7806
|
| 86 |
+
<https://github.com/networkx/networkx/issues/7806>`_.
|
| 87 |
+
|
| 88 |
+
The function iteratively aggregates and hashes neighborhoods of each node.
|
| 89 |
+
After each node's neighbors are hashed to obtain updated node labels,
|
| 90 |
+
a hashed histogram of resulting labels is returned as the final hash.
|
| 91 |
+
|
| 92 |
+
Hashes are identical for isomorphic graphs and strong guarantees that
|
| 93 |
+
non-isomorphic graphs will get different hashes. See [1]_ for details.
|
| 94 |
+
|
| 95 |
+
If no node or edge attributes are provided, the degree of each node
|
| 96 |
+
is used as its initial label.
|
| 97 |
+
Otherwise, node and/or edge labels are used to compute the hash.
|
| 98 |
+
|
| 99 |
+
Parameters
|
| 100 |
+
----------
|
| 101 |
+
G : graph
|
| 102 |
+
The graph to be hashed.
|
| 103 |
+
Can have node and/or edge attributes. Can also have no attributes.
|
| 104 |
+
edge_attr : string, optional (default=None)
|
| 105 |
+
The key in edge attribute dictionary to be used for hashing.
|
| 106 |
+
If None, edge labels are ignored.
|
| 107 |
+
node_attr: string, optional (default=None)
|
| 108 |
+
The key in node attribute dictionary to be used for hashing.
|
| 109 |
+
If None, and no edge_attr given, use the degrees of the nodes as labels.
|
| 110 |
+
iterations: int, optional (default=3)
|
| 111 |
+
Number of neighbor aggregations to perform.
|
| 112 |
+
Should be larger for larger graphs.
|
| 113 |
+
digest_size: int, optional (default=16)
|
| 114 |
+
Size (in bytes) of blake2b hash digest to use for hashing node labels.
|
| 115 |
+
|
| 116 |
+
Returns
|
| 117 |
+
-------
|
| 118 |
+
h : string
|
| 119 |
+
Hexadecimal string corresponding to hash of `G` (length ``2 * digest_size``).
|
| 120 |
+
|
| 121 |
+
Raises
|
| 122 |
+
------
|
| 123 |
+
ValueError
|
| 124 |
+
If `iterations` is not a positve number.
|
| 125 |
+
|
| 126 |
+
Examples
|
| 127 |
+
--------
|
| 128 |
+
Two graphs with edge attributes that are isomorphic, except for
|
| 129 |
+
differences in the edge labels.
|
| 130 |
+
|
| 131 |
+
>>> G1 = nx.Graph()
|
| 132 |
+
>>> G1.add_edges_from(
|
| 133 |
+
... [
|
| 134 |
+
... (1, 2, {"label": "A"}),
|
| 135 |
+
... (2, 3, {"label": "A"}),
|
| 136 |
+
... (3, 1, {"label": "A"}),
|
| 137 |
+
... (1, 4, {"label": "B"}),
|
| 138 |
+
... ]
|
| 139 |
+
... )
|
| 140 |
+
>>> G2 = nx.Graph()
|
| 141 |
+
>>> G2.add_edges_from(
|
| 142 |
+
... [
|
| 143 |
+
... (5, 6, {"label": "B"}),
|
| 144 |
+
... (6, 7, {"label": "A"}),
|
| 145 |
+
... (7, 5, {"label": "A"}),
|
| 146 |
+
... (7, 8, {"label": "A"}),
|
| 147 |
+
... ]
|
| 148 |
+
... )
|
| 149 |
+
|
| 150 |
+
Omitting the `edge_attr` option, results in identical hashes.
|
| 151 |
+
|
| 152 |
+
>>> nx.weisfeiler_lehman_graph_hash(G1)
|
| 153 |
+
'c045439172215f49e0bef8c3d26c6b61'
|
| 154 |
+
>>> nx.weisfeiler_lehman_graph_hash(G2)
|
| 155 |
+
'c045439172215f49e0bef8c3d26c6b61'
|
| 156 |
+
|
| 157 |
+
With edge labels, the graphs are no longer assigned
|
| 158 |
+
the same hash digest.
|
| 159 |
+
|
| 160 |
+
>>> nx.weisfeiler_lehman_graph_hash(G1, edge_attr="label")
|
| 161 |
+
'c653d85538bcf041d88c011f4f905f10'
|
| 162 |
+
>>> nx.weisfeiler_lehman_graph_hash(G2, edge_attr="label")
|
| 163 |
+
'3dcd84af1ca855d0eff3c978d88e7ec7'
|
| 164 |
+
|
| 165 |
+
Notes
|
| 166 |
+
-----
|
| 167 |
+
To return the WL hashes of each subgraph of a graph, use
|
| 168 |
+
`weisfeiler_lehman_subgraph_hashes`
|
| 169 |
+
|
| 170 |
+
Similarity between hashes does not imply similarity between graphs.
|
| 171 |
+
|
| 172 |
+
References
|
| 173 |
+
----------
|
| 174 |
+
.. [1] Shervashidze, Nino, Pascal Schweitzer, Erik Jan Van Leeuwen,
|
| 175 |
+
Kurt Mehlhorn, and Karsten M. Borgwardt. Weisfeiler Lehman
|
| 176 |
+
Graph Kernels. Journal of Machine Learning Research. 2011.
|
| 177 |
+
http://www.jmlr.org/papers/volume12/shervashidze11a/shervashidze11a.pdf
|
| 178 |
+
|
| 179 |
+
See also
|
| 180 |
+
--------
|
| 181 |
+
weisfeiler_lehman_subgraph_hashes
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
if G.is_directed():
|
| 185 |
+
_neighborhood_aggregate = _neighborhood_aggregate_directed
|
| 186 |
+
warnings.warn(
|
| 187 |
+
"The hashes produced for directed graphs changed in version v3.5"
|
| 188 |
+
" due to a bugfix to track in and out edges separately (see documentation).",
|
| 189 |
+
UserWarning,
|
| 190 |
+
stacklevel=2,
|
| 191 |
+
)
|
| 192 |
+
else:
|
| 193 |
+
_neighborhood_aggregate = _neighborhood_aggregate_undirected
|
| 194 |
+
|
| 195 |
+
def weisfeiler_lehman_step(G, labels, edge_attr=None):
|
| 196 |
+
"""
|
| 197 |
+
Apply neighborhood aggregation to each node
|
| 198 |
+
in the graph.
|
| 199 |
+
Computes a dictionary with labels for each node.
|
| 200 |
+
"""
|
| 201 |
+
new_labels = {}
|
| 202 |
+
for node in G.nodes():
|
| 203 |
+
label = _neighborhood_aggregate(G, node, labels, edge_attr=edge_attr)
|
| 204 |
+
new_labels[node] = _hash_label(label, digest_size)
|
| 205 |
+
return new_labels
|
| 206 |
+
|
| 207 |
+
if iterations <= 0:
|
| 208 |
+
raise ValueError("The WL algorithm requires that `iterations` be positive")
|
| 209 |
+
|
| 210 |
+
# set initial node labels
|
| 211 |
+
node_labels = _init_node_labels(G, edge_attr, node_attr)
|
| 212 |
+
|
| 213 |
+
# If the graph has no attributes, initial labels are the nodes' degrees.
|
| 214 |
+
# This is equivalent to doing the first iterations of WL.
|
| 215 |
+
if not edge_attr and not node_attr:
|
| 216 |
+
iterations -= 1
|
| 217 |
+
|
| 218 |
+
subgraph_hash_counts = []
|
| 219 |
+
for _ in range(iterations):
|
| 220 |
+
node_labels = weisfeiler_lehman_step(G, node_labels, edge_attr=edge_attr)
|
| 221 |
+
counter = Counter(node_labels.values())
|
| 222 |
+
# sort the counter, extend total counts
|
| 223 |
+
subgraph_hash_counts.extend(sorted(counter.items(), key=lambda x: x[0]))
|
| 224 |
+
|
| 225 |
+
# hash the final counter
|
| 226 |
+
return _hash_label(str(tuple(subgraph_hash_counts)), digest_size)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@nx.utils.not_implemented_for("multigraph")
|
| 230 |
+
@nx._dispatchable(edge_attrs={"edge_attr": None}, node_attrs="node_attr")
|
| 231 |
+
def weisfeiler_lehman_subgraph_hashes(
|
| 232 |
+
G,
|
| 233 |
+
edge_attr=None,
|
| 234 |
+
node_attr=None,
|
| 235 |
+
iterations=3,
|
| 236 |
+
digest_size=16,
|
| 237 |
+
include_initial_labels=False,
|
| 238 |
+
):
|
| 239 |
+
"""
|
| 240 |
+
Return a dictionary of subgraph hashes by node.
|
| 241 |
+
|
| 242 |
+
.. Warning:: Hash values for directed graphs have changed in version
|
| 243 |
+
v3.5. In previous versions, directed graphs did not distinguish in-
|
| 244 |
+
and outgoing edges.
|
| 245 |
+
Graphs without attributes previously performed an extra iteration of
|
| 246 |
+
WL at initialisation, which was not visible in the output of this
|
| 247 |
+
function. This hash value is now included in the returned dictionary,
|
| 248 |
+
shifting the other calculated hashes one position to the right. To
|
| 249 |
+
obtain the same last subgraph hash, increase the number of iterations
|
| 250 |
+
by one.
|
| 251 |
+
For more details, see `issue #7806
|
| 252 |
+
<https://github.com/networkx/networkx/issues/7806>`_.
|
| 253 |
+
|
| 254 |
+
Dictionary keys are nodes in `G`, and values are a list of hashes.
|
| 255 |
+
Each hash corresponds to a subgraph rooted at a given node u in `G`.
|
| 256 |
+
Lists of subgraph hashes are sorted in increasing order of depth from
|
| 257 |
+
their root node, with the hash at index i corresponding to a subgraph
|
| 258 |
+
of nodes at most i-hops (i edges) distance from u. Thus, each list will contain
|
| 259 |
+
`iterations` elements - a hash for a subgraph at each depth. If
|
| 260 |
+
`include_initial_labels` is set to `True`, each list will additionally
|
| 261 |
+
have contain a hash of the initial node label (or equivalently a
|
| 262 |
+
subgraph of depth 0) prepended, totalling ``iterations + 1`` elements.
|
| 263 |
+
|
| 264 |
+
The function iteratively aggregates and hashes neighborhoods of each node.
|
| 265 |
+
This is achieved for each step by replacing for each node its label from
|
| 266 |
+
the previous iteration with its hashed 1-hop neighborhood aggregate.
|
| 267 |
+
The new node label is then appended to a list of node labels for each
|
| 268 |
+
node.
|
| 269 |
+
|
| 270 |
+
To aggregate neighborhoods for a node $u$ at each step, all labels of
|
| 271 |
+
nodes adjacent to $u$ are concatenated. If the `edge_attr` parameter is set,
|
| 272 |
+
labels for each neighboring node are prefixed with the value of this attribute
|
| 273 |
+
along the connecting edge from this neighbor to node $u$. The resulting string
|
| 274 |
+
is then hashed to compress this information into a fixed digest size.
|
| 275 |
+
|
| 276 |
+
Thus, at the i-th iteration, nodes within i hops influence any given
|
| 277 |
+
hashed node label. We can therefore say that at depth $i$ for node $u$
|
| 278 |
+
we have a hash for a subgraph induced by the i-hop neighborhood of $u$.
|
| 279 |
+
|
| 280 |
+
The output can be used to create general Weisfeiler-Lehman graph kernels,
|
| 281 |
+
or generate features for graphs or nodes - for example to generate 'words' in
|
| 282 |
+
a graph as seen in the 'graph2vec' algorithm.
|
| 283 |
+
See [1]_ & [2]_ respectively for details.
|
| 284 |
+
|
| 285 |
+
Hashes are identical for isomorphic subgraphs and there exist strong
|
| 286 |
+
guarantees that non-isomorphic graphs will get different hashes.
|
| 287 |
+
See [1]_ for details.
|
| 288 |
+
|
| 289 |
+
If no node or edge attributes are provided, the degree of each node
|
| 290 |
+
is used as its initial label.
|
| 291 |
+
Otherwise, node and/or edge labels are used to compute the hash.
|
| 292 |
+
|
| 293 |
+
Parameters
|
| 294 |
+
----------
|
| 295 |
+
G : graph
|
| 296 |
+
The graph to be hashed.
|
| 297 |
+
Can have node and/or edge attributes. Can also have no attributes.
|
| 298 |
+
edge_attr : string, optional (default=None)
|
| 299 |
+
The key in edge attribute dictionary to be used for hashing.
|
| 300 |
+
If None, edge labels are ignored.
|
| 301 |
+
node_attr : string, optional (default=None)
|
| 302 |
+
The key in node attribute dictionary to be used for hashing.
|
| 303 |
+
If None, and no edge_attr given, use the degrees of the nodes as labels.
|
| 304 |
+
If None, and edge_attr is given, each node starts with an identical label.
|
| 305 |
+
iterations : int, optional (default=3)
|
| 306 |
+
Number of neighbor aggregations to perform.
|
| 307 |
+
Should be larger for larger graphs.
|
| 308 |
+
digest_size : int, optional (default=16)
|
| 309 |
+
Size (in bytes) of blake2b hash digest to use for hashing node labels.
|
| 310 |
+
The default size is 16 bytes.
|
| 311 |
+
include_initial_labels : bool, optional (default=False)
|
| 312 |
+
If True, include the hashed initial node label as the first subgraph
|
| 313 |
+
hash for each node.
|
| 314 |
+
|
| 315 |
+
Returns
|
| 316 |
+
-------
|
| 317 |
+
node_subgraph_hashes : dict
|
| 318 |
+
A dictionary with each key given by a node in G, and each value given
|
| 319 |
+
by the subgraph hashes in order of depth from the key node.
|
| 320 |
+
Hashes are hexadecimal strings (hence ``2 * digest_size`` long).
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
Raises
|
| 324 |
+
------
|
| 325 |
+
ValueError
|
| 326 |
+
If `iterations` is not a positve number.
|
| 327 |
+
|
| 328 |
+
Examples
|
| 329 |
+
--------
|
| 330 |
+
Finding similar nodes in different graphs:
|
| 331 |
+
|
| 332 |
+
>>> G1 = nx.Graph()
|
| 333 |
+
>>> G1.add_edges_from([(1, 2), (2, 3), (2, 4), (3, 5), (4, 6), (5, 7), (6, 7)])
|
| 334 |
+
>>> G2 = nx.Graph()
|
| 335 |
+
>>> G2.add_edges_from([(1, 3), (2, 3), (1, 6), (1, 5), (4, 6)])
|
| 336 |
+
>>> g1_hashes = nx.weisfeiler_lehman_subgraph_hashes(
|
| 337 |
+
... G1, iterations=4, digest_size=8
|
| 338 |
+
... )
|
| 339 |
+
>>> g2_hashes = nx.weisfeiler_lehman_subgraph_hashes(
|
| 340 |
+
... G2, iterations=4, digest_size=8
|
| 341 |
+
... )
|
| 342 |
+
|
| 343 |
+
Even though G1 and G2 are not isomorphic (they have different numbers of edges),
|
| 344 |
+
the hash sequence of depth 3 for node 1 in G1 and node 5 in G2 are similar:
|
| 345 |
+
|
| 346 |
+
>>> g1_hashes[1]
|
| 347 |
+
['f6fc42039fba3776', 'a93b64973cfc8897', 'db1b43ae35a1878f', '57872a7d2059c1c0']
|
| 348 |
+
>>> g2_hashes[5]
|
| 349 |
+
['f6fc42039fba3776', 'a93b64973cfc8897', 'db1b43ae35a1878f', '1716d2a4012fa4bc']
|
| 350 |
+
|
| 351 |
+
The first 3 WL subgraph hashes match. From this we can conclude that it's very
|
| 352 |
+
likely the neighborhood of 3 hops around these nodes are isomorphic.
|
| 353 |
+
|
| 354 |
+
However the 4-hop neighborhoods of ``G1`` and ``G2`` are not isomorphic since the
|
| 355 |
+
4th hashes in the lists above are not equal.
|
| 356 |
+
|
| 357 |
+
These nodes may be candidates to be classified together since their local topology
|
| 358 |
+
is similar.
|
| 359 |
+
|
| 360 |
+
Notes
|
| 361 |
+
-----
|
| 362 |
+
To hash the full graph when subgraph hashes are not needed, use
|
| 363 |
+
`weisfeiler_lehman_graph_hash` for efficiency.
|
| 364 |
+
|
| 365 |
+
Similarity between hashes does not imply similarity between graphs.
|
| 366 |
+
|
| 367 |
+
References
|
| 368 |
+
----------
|
| 369 |
+
.. [1] Shervashidze, Nino, Pascal Schweitzer, Erik Jan Van Leeuwen,
|
| 370 |
+
Kurt Mehlhorn, and Karsten M. Borgwardt. Weisfeiler Lehman
|
| 371 |
+
Graph Kernels. Journal of Machine Learning Research. 2011.
|
| 372 |
+
http://www.jmlr.org/papers/volume12/shervashidze11a/shervashidze11a.pdf
|
| 373 |
+
.. [2] Annamalai Narayanan, Mahinthan Chandramohan, Rajasekar Venkatesan,
|
| 374 |
+
Lihui Chen, Yang Liu and Shantanu Jaiswa. graph2vec: Learning
|
| 375 |
+
Distributed Representations of Graphs. arXiv. 2017
|
| 376 |
+
https://arxiv.org/pdf/1707.05005.pdf
|
| 377 |
+
|
| 378 |
+
See also
|
| 379 |
+
--------
|
| 380 |
+
weisfeiler_lehman_graph_hash
|
| 381 |
+
"""
|
| 382 |
+
|
| 383 |
+
if G.is_directed():
|
| 384 |
+
_neighborhood_aggregate = _neighborhood_aggregate_directed
|
| 385 |
+
warnings.warn(
|
| 386 |
+
"The hashes produced for directed graphs changed in v3.5"
|
| 387 |
+
" due to a bugfix (see documentation).",
|
| 388 |
+
UserWarning,
|
| 389 |
+
stacklevel=2,
|
| 390 |
+
)
|
| 391 |
+
else:
|
| 392 |
+
_neighborhood_aggregate = _neighborhood_aggregate_undirected
|
| 393 |
+
|
| 394 |
+
def weisfeiler_lehman_step(G, labels, node_subgraph_hashes, edge_attr=None):
|
| 395 |
+
"""
|
| 396 |
+
Apply neighborhood aggregation to each node
|
| 397 |
+
in the graph.
|
| 398 |
+
Computes a dictionary with labels for each node.
|
| 399 |
+
Appends the new hashed label to the dictionary of subgraph hashes
|
| 400 |
+
originating from and indexed by each node in G
|
| 401 |
+
"""
|
| 402 |
+
new_labels = {}
|
| 403 |
+
for node in G.nodes():
|
| 404 |
+
label = _neighborhood_aggregate(G, node, labels, edge_attr=edge_attr)
|
| 405 |
+
hashed_label = _hash_label(label, digest_size)
|
| 406 |
+
new_labels[node] = hashed_label
|
| 407 |
+
node_subgraph_hashes[node].append(hashed_label)
|
| 408 |
+
return new_labels
|
| 409 |
+
|
| 410 |
+
if iterations <= 0:
|
| 411 |
+
raise ValueError("The WL algorithm requires that `iterations` be positive")
|
| 412 |
+
|
| 413 |
+
node_labels = _init_node_labels(G, edge_attr, node_attr)
|
| 414 |
+
|
| 415 |
+
if include_initial_labels:
|
| 416 |
+
node_subgraph_hashes = {
|
| 417 |
+
k: [_hash_label(v, digest_size)] for k, v in node_labels.items()
|
| 418 |
+
}
|
| 419 |
+
else:
|
| 420 |
+
node_subgraph_hashes = defaultdict(list)
|
| 421 |
+
|
| 422 |
+
# If the graph has no attributes, initial labels are the nodes' degrees.
|
| 423 |
+
# This is equivalent to doing the first iterations of WL.
|
| 424 |
+
if not edge_attr and not node_attr:
|
| 425 |
+
iterations -= 1
|
| 426 |
+
for node in G.nodes():
|
| 427 |
+
hashed_label = _hash_label(node_labels[node], digest_size)
|
| 428 |
+
node_subgraph_hashes[node].append(hashed_label)
|
| 429 |
+
|
| 430 |
+
for _ in range(iterations):
|
| 431 |
+
node_labels = weisfeiler_lehman_step(
|
| 432 |
+
G, node_labels, node_subgraph_hashes, edge_attr
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
return dict(node_subgraph_hashes)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/graphical.py
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test sequences for graphiness."""
|
| 2 |
+
|
| 3 |
+
import heapq
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"is_graphical",
|
| 9 |
+
"is_multigraphical",
|
| 10 |
+
"is_pseudographical",
|
| 11 |
+
"is_digraphical",
|
| 12 |
+
"is_valid_degree_sequence_erdos_gallai",
|
| 13 |
+
"is_valid_degree_sequence_havel_hakimi",
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@nx._dispatchable(graphs=None)
|
| 18 |
+
def is_graphical(sequence, method="eg"):
|
| 19 |
+
"""Returns True if sequence is a valid degree sequence.
|
| 20 |
+
|
| 21 |
+
A degree sequence is valid if some graph can realize it.
|
| 22 |
+
|
| 23 |
+
Parameters
|
| 24 |
+
----------
|
| 25 |
+
sequence : list or iterable container
|
| 26 |
+
A sequence of integer node degrees
|
| 27 |
+
|
| 28 |
+
method : "eg" | "hh" (default: 'eg')
|
| 29 |
+
The method used to validate the degree sequence.
|
| 30 |
+
"eg" corresponds to the Erdős-Gallai algorithm
|
| 31 |
+
[EG1960]_, [choudum1986]_, and
|
| 32 |
+
"hh" to the Havel-Hakimi algorithm
|
| 33 |
+
[havel1955]_, [hakimi1962]_, [CL1996]_.
|
| 34 |
+
|
| 35 |
+
Returns
|
| 36 |
+
-------
|
| 37 |
+
valid : bool
|
| 38 |
+
True if the sequence is a valid degree sequence and False if not.
|
| 39 |
+
|
| 40 |
+
Examples
|
| 41 |
+
--------
|
| 42 |
+
>>> G = nx.path_graph(4)
|
| 43 |
+
>>> sequence = (d for n, d in G.degree())
|
| 44 |
+
>>> nx.is_graphical(sequence)
|
| 45 |
+
True
|
| 46 |
+
|
| 47 |
+
To test a non-graphical sequence:
|
| 48 |
+
>>> sequence_list = [d for n, d in G.degree()]
|
| 49 |
+
>>> sequence_list[-1] += 1
|
| 50 |
+
>>> nx.is_graphical(sequence_list)
|
| 51 |
+
False
|
| 52 |
+
|
| 53 |
+
References
|
| 54 |
+
----------
|
| 55 |
+
.. [EG1960] Erdős and Gallai, Mat. Lapok 11 264, 1960.
|
| 56 |
+
.. [choudum1986] S.A. Choudum. "A simple proof of the Erdős-Gallai theorem on
|
| 57 |
+
graph sequences." Bulletin of the Australian Mathematical Society, 33,
|
| 58 |
+
pp 67-70, 1986. https://doi.org/10.1017/S0004972700002872
|
| 59 |
+
.. [havel1955] Havel, V. "A Remark on the Existence of Finite Graphs"
|
| 60 |
+
Casopis Pest. Mat. 80, 477-480, 1955.
|
| 61 |
+
.. [hakimi1962] Hakimi, S. "On the Realizability of a Set of Integers as
|
| 62 |
+
Degrees of the Vertices of a Graph." SIAM J. Appl. Math. 10, 496-506, 1962.
|
| 63 |
+
.. [CL1996] G. Chartrand and L. Lesniak, "Graphs and Digraphs",
|
| 64 |
+
Chapman and Hall/CRC, 1996.
|
| 65 |
+
"""
|
| 66 |
+
if method == "eg":
|
| 67 |
+
valid = is_valid_degree_sequence_erdos_gallai(list(sequence))
|
| 68 |
+
elif method == "hh":
|
| 69 |
+
valid = is_valid_degree_sequence_havel_hakimi(list(sequence))
|
| 70 |
+
else:
|
| 71 |
+
msg = "`method` must be 'eg' or 'hh'"
|
| 72 |
+
raise nx.NetworkXException(msg)
|
| 73 |
+
return valid
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _basic_graphical_tests(deg_sequence):
|
| 77 |
+
# Sort and perform some simple tests on the sequence
|
| 78 |
+
deg_sequence = nx.utils.make_list_of_ints(deg_sequence)
|
| 79 |
+
p = len(deg_sequence)
|
| 80 |
+
num_degs = [0] * p
|
| 81 |
+
dmax, dmin, dsum, n = 0, p, 0, 0
|
| 82 |
+
for d in deg_sequence:
|
| 83 |
+
# Reject if degree is negative or larger than the sequence length
|
| 84 |
+
if d < 0 or d >= p:
|
| 85 |
+
raise nx.NetworkXUnfeasible
|
| 86 |
+
# Process only the non-zero integers
|
| 87 |
+
elif d > 0:
|
| 88 |
+
dmax, dmin, dsum, n = max(dmax, d), min(dmin, d), dsum + d, n + 1
|
| 89 |
+
num_degs[d] += 1
|
| 90 |
+
# Reject sequence if it has odd sum or is oversaturated
|
| 91 |
+
if dsum % 2 or dsum > n * (n - 1):
|
| 92 |
+
raise nx.NetworkXUnfeasible
|
| 93 |
+
return dmax, dmin, dsum, n, num_degs
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@nx._dispatchable(graphs=None)
|
| 97 |
+
def is_valid_degree_sequence_havel_hakimi(deg_sequence):
|
| 98 |
+
r"""Returns True if deg_sequence can be realized by a simple graph.
|
| 99 |
+
|
| 100 |
+
The validation proceeds using the Havel-Hakimi theorem
|
| 101 |
+
[havel1955]_, [hakimi1962]_, [CL1996]_.
|
| 102 |
+
Worst-case run time is $O(s)$ where $s$ is the sum of the sequence.
|
| 103 |
+
|
| 104 |
+
Parameters
|
| 105 |
+
----------
|
| 106 |
+
deg_sequence : list
|
| 107 |
+
A list of integers where each element specifies the degree of a node
|
| 108 |
+
in a graph.
|
| 109 |
+
|
| 110 |
+
Returns
|
| 111 |
+
-------
|
| 112 |
+
valid : bool
|
| 113 |
+
True if deg_sequence is graphical and False if not.
|
| 114 |
+
|
| 115 |
+
Examples
|
| 116 |
+
--------
|
| 117 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 1), (5, 4)])
|
| 118 |
+
>>> sequence = (d for _, d in G.degree())
|
| 119 |
+
>>> nx.is_valid_degree_sequence_havel_hakimi(sequence)
|
| 120 |
+
True
|
| 121 |
+
|
| 122 |
+
To test a non-valid sequence:
|
| 123 |
+
>>> sequence_list = [d for _, d in G.degree()]
|
| 124 |
+
>>> sequence_list[-1] += 1
|
| 125 |
+
>>> nx.is_valid_degree_sequence_havel_hakimi(sequence_list)
|
| 126 |
+
False
|
| 127 |
+
|
| 128 |
+
Notes
|
| 129 |
+
-----
|
| 130 |
+
The ZZ condition says that for the sequence d if
|
| 131 |
+
|
| 132 |
+
.. math::
|
| 133 |
+
|d| >= \frac{(\max(d) + \min(d) + 1)^2}{4*\min(d)}
|
| 134 |
+
|
| 135 |
+
then d is graphical. This was shown in Theorem 6 in [1]_.
|
| 136 |
+
|
| 137 |
+
References
|
| 138 |
+
----------
|
| 139 |
+
.. [1] I.E. Zverovich and V.E. Zverovich. "Contributions to the theory
|
| 140 |
+
of graphic sequences", Discrete Mathematics, 105, pp. 292-303 (1992).
|
| 141 |
+
.. [havel1955] Havel, V. "A Remark on the Existence of Finite Graphs"
|
| 142 |
+
Casopis Pest. Mat. 80, 477-480, 1955.
|
| 143 |
+
.. [hakimi1962] Hakimi, S. "On the Realizability of a Set of Integers as
|
| 144 |
+
Degrees of the Vertices of a Graph." SIAM J. Appl. Math. 10, 496-506, 1962.
|
| 145 |
+
.. [CL1996] G. Chartrand and L. Lesniak, "Graphs and Digraphs",
|
| 146 |
+
Chapman and Hall/CRC, 1996.
|
| 147 |
+
"""
|
| 148 |
+
try:
|
| 149 |
+
dmax, dmin, dsum, n, num_degs = _basic_graphical_tests(deg_sequence)
|
| 150 |
+
except nx.NetworkXUnfeasible:
|
| 151 |
+
return False
|
| 152 |
+
# Accept if sequence has no non-zero degrees or passes the ZZ condition
|
| 153 |
+
if n == 0 or 4 * dmin * n >= (dmax + dmin + 1) * (dmax + dmin + 1):
|
| 154 |
+
return True
|
| 155 |
+
|
| 156 |
+
modstubs = [0] * (dmax + 1)
|
| 157 |
+
# Successively reduce degree sequence by removing the maximum degree
|
| 158 |
+
while n > 0:
|
| 159 |
+
# Retrieve the maximum degree in the sequence
|
| 160 |
+
while num_degs[dmax] == 0:
|
| 161 |
+
dmax -= 1
|
| 162 |
+
# If there are not enough stubs to connect to, then the sequence is
|
| 163 |
+
# not graphical
|
| 164 |
+
if dmax > n - 1:
|
| 165 |
+
return False
|
| 166 |
+
|
| 167 |
+
# Remove largest stub in list
|
| 168 |
+
num_degs[dmax], n = num_degs[dmax] - 1, n - 1
|
| 169 |
+
# Reduce the next dmax largest stubs
|
| 170 |
+
mslen = 0
|
| 171 |
+
k = dmax
|
| 172 |
+
for i in range(dmax):
|
| 173 |
+
while num_degs[k] == 0:
|
| 174 |
+
k -= 1
|
| 175 |
+
num_degs[k], n = num_degs[k] - 1, n - 1
|
| 176 |
+
if k > 1:
|
| 177 |
+
modstubs[mslen] = k - 1
|
| 178 |
+
mslen += 1
|
| 179 |
+
# Add back to the list any non-zero stubs that were removed
|
| 180 |
+
for i in range(mslen):
|
| 181 |
+
stub = modstubs[i]
|
| 182 |
+
num_degs[stub], n = num_degs[stub] + 1, n + 1
|
| 183 |
+
return True
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
@nx._dispatchable(graphs=None)
|
| 187 |
+
def is_valid_degree_sequence_erdos_gallai(deg_sequence):
|
| 188 |
+
r"""Returns True if deg_sequence can be realized by a simple graph.
|
| 189 |
+
|
| 190 |
+
The validation is done using the Erdős-Gallai theorem [EG1960]_.
|
| 191 |
+
|
| 192 |
+
Parameters
|
| 193 |
+
----------
|
| 194 |
+
deg_sequence : list
|
| 195 |
+
A list of integers
|
| 196 |
+
|
| 197 |
+
Returns
|
| 198 |
+
-------
|
| 199 |
+
valid : bool
|
| 200 |
+
True if deg_sequence is graphical and False if not.
|
| 201 |
+
|
| 202 |
+
Examples
|
| 203 |
+
--------
|
| 204 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 1), (5, 4)])
|
| 205 |
+
>>> sequence = (d for _, d in G.degree())
|
| 206 |
+
>>> nx.is_valid_degree_sequence_erdos_gallai(sequence)
|
| 207 |
+
True
|
| 208 |
+
|
| 209 |
+
To test a non-valid sequence:
|
| 210 |
+
>>> sequence_list = [d for _, d in G.degree()]
|
| 211 |
+
>>> sequence_list[-1] += 1
|
| 212 |
+
>>> nx.is_valid_degree_sequence_erdos_gallai(sequence_list)
|
| 213 |
+
False
|
| 214 |
+
|
| 215 |
+
Notes
|
| 216 |
+
-----
|
| 217 |
+
|
| 218 |
+
This implementation uses an equivalent form of the Erdős-Gallai criterion.
|
| 219 |
+
Worst-case run time is $O(n)$ where $n$ is the length of the sequence.
|
| 220 |
+
|
| 221 |
+
Specifically, a sequence d is graphical if and only if the
|
| 222 |
+
sum of the sequence is even and for all strong indices k in the sequence,
|
| 223 |
+
|
| 224 |
+
.. math::
|
| 225 |
+
|
| 226 |
+
\sum_{i=1}^{k} d_i \leq k(k-1) + \sum_{j=k+1}^{n} \min(d_i,k)
|
| 227 |
+
= k(n-1) - ( k \sum_{j=0}^{k-1} n_j - \sum_{j=0}^{k-1} j n_j )
|
| 228 |
+
|
| 229 |
+
A strong index k is any index where d_k >= k and the value n_j is the
|
| 230 |
+
number of occurrences of j in d. The maximal strong index is called the
|
| 231 |
+
Durfee index.
|
| 232 |
+
|
| 233 |
+
This particular rearrangement comes from the proof of Theorem 3 in [2]_.
|
| 234 |
+
|
| 235 |
+
The ZZ condition says that for the sequence d if
|
| 236 |
+
|
| 237 |
+
.. math::
|
| 238 |
+
|d| >= \frac{(\max(d) + \min(d) + 1)^2}{4*\min(d)}
|
| 239 |
+
|
| 240 |
+
then d is graphical. This was shown in Theorem 6 in [2]_.
|
| 241 |
+
|
| 242 |
+
References
|
| 243 |
+
----------
|
| 244 |
+
.. [1] A. Tripathi and S. Vijay. "A note on a theorem of Erdős & Gallai",
|
| 245 |
+
Discrete Mathematics, 265, pp. 417-420 (2003).
|
| 246 |
+
.. [2] I.E. Zverovich and V.E. Zverovich. "Contributions to the theory
|
| 247 |
+
of graphic sequences", Discrete Mathematics, 105, pp. 292-303 (1992).
|
| 248 |
+
.. [EG1960] Erdős and Gallai, Mat. Lapok 11 264, 1960.
|
| 249 |
+
"""
|
| 250 |
+
try:
|
| 251 |
+
dmax, dmin, dsum, n, num_degs = _basic_graphical_tests(deg_sequence)
|
| 252 |
+
except nx.NetworkXUnfeasible:
|
| 253 |
+
return False
|
| 254 |
+
# Accept if sequence has no non-zero degrees or passes the ZZ condition
|
| 255 |
+
if n == 0 or 4 * dmin * n >= (dmax + dmin + 1) * (dmax + dmin + 1):
|
| 256 |
+
return True
|
| 257 |
+
|
| 258 |
+
# Perform the EG checks using the reformulation of Zverovich and Zverovich
|
| 259 |
+
k, sum_deg, sum_nj, sum_jnj = 0, 0, 0, 0
|
| 260 |
+
for dk in range(dmax, dmin - 1, -1):
|
| 261 |
+
if dk < k + 1: # Check if already past Durfee index
|
| 262 |
+
return True
|
| 263 |
+
if num_degs[dk] > 0:
|
| 264 |
+
run_size = num_degs[dk] # Process a run of identical-valued degrees
|
| 265 |
+
if dk < k + run_size: # Check if end of run is past Durfee index
|
| 266 |
+
run_size = dk - k # Adjust back to Durfee index
|
| 267 |
+
sum_deg += run_size * dk
|
| 268 |
+
for v in range(run_size):
|
| 269 |
+
sum_nj += num_degs[k + v]
|
| 270 |
+
sum_jnj += (k + v) * num_degs[k + v]
|
| 271 |
+
k += run_size
|
| 272 |
+
if sum_deg > k * (n - 1) - k * sum_nj + sum_jnj:
|
| 273 |
+
return False
|
| 274 |
+
return True
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@nx._dispatchable(graphs=None)
|
| 278 |
+
def is_multigraphical(sequence):
|
| 279 |
+
"""Returns True if some multigraph can realize the sequence.
|
| 280 |
+
|
| 281 |
+
Parameters
|
| 282 |
+
----------
|
| 283 |
+
sequence : list
|
| 284 |
+
A list of integers
|
| 285 |
+
|
| 286 |
+
Returns
|
| 287 |
+
-------
|
| 288 |
+
valid : bool
|
| 289 |
+
True if deg_sequence is a multigraphic degree sequence and False if not.
|
| 290 |
+
|
| 291 |
+
Examples
|
| 292 |
+
--------
|
| 293 |
+
>>> G = nx.MultiGraph([(1, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 1), (5, 4)])
|
| 294 |
+
>>> sequence = (d for _, d in G.degree())
|
| 295 |
+
>>> nx.is_multigraphical(sequence)
|
| 296 |
+
True
|
| 297 |
+
|
| 298 |
+
To test a non-multigraphical sequence:
|
| 299 |
+
>>> sequence_list = [d for _, d in G.degree()]
|
| 300 |
+
>>> sequence_list[-1] += 1
|
| 301 |
+
>>> nx.is_multigraphical(sequence_list)
|
| 302 |
+
False
|
| 303 |
+
|
| 304 |
+
Notes
|
| 305 |
+
-----
|
| 306 |
+
The worst-case run time is $O(n)$ where $n$ is the length of the sequence.
|
| 307 |
+
|
| 308 |
+
References
|
| 309 |
+
----------
|
| 310 |
+
.. [1] S. L. Hakimi. "On the realizability of a set of integers as
|
| 311 |
+
degrees of the vertices of a linear graph", J. SIAM, 10, pp. 496-506
|
| 312 |
+
(1962).
|
| 313 |
+
"""
|
| 314 |
+
try:
|
| 315 |
+
deg_sequence = nx.utils.make_list_of_ints(sequence)
|
| 316 |
+
except nx.NetworkXError:
|
| 317 |
+
return False
|
| 318 |
+
dsum, dmax = 0, 0
|
| 319 |
+
for d in deg_sequence:
|
| 320 |
+
if d < 0:
|
| 321 |
+
return False
|
| 322 |
+
dsum, dmax = dsum + d, max(dmax, d)
|
| 323 |
+
if dsum % 2 or dsum < 2 * dmax:
|
| 324 |
+
return False
|
| 325 |
+
return True
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@nx._dispatchable(graphs=None)
|
| 329 |
+
def is_pseudographical(sequence):
|
| 330 |
+
"""Returns True if some pseudograph can realize the sequence.
|
| 331 |
+
|
| 332 |
+
Every nonnegative integer sequence with an even sum is pseudographical
|
| 333 |
+
(see [1]_).
|
| 334 |
+
|
| 335 |
+
Parameters
|
| 336 |
+
----------
|
| 337 |
+
sequence : list or iterable container
|
| 338 |
+
A sequence of integer node degrees
|
| 339 |
+
|
| 340 |
+
Returns
|
| 341 |
+
-------
|
| 342 |
+
valid : bool
|
| 343 |
+
True if the sequence is a pseudographic degree sequence and False if not.
|
| 344 |
+
|
| 345 |
+
Examples
|
| 346 |
+
--------
|
| 347 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 1), (5, 4)])
|
| 348 |
+
>>> sequence = (d for _, d in G.degree())
|
| 349 |
+
>>> nx.is_pseudographical(sequence)
|
| 350 |
+
True
|
| 351 |
+
|
| 352 |
+
To test a non-pseudographical sequence:
|
| 353 |
+
>>> sequence_list = [d for _, d in G.degree()]
|
| 354 |
+
>>> sequence_list[-1] += 1
|
| 355 |
+
>>> nx.is_pseudographical(sequence_list)
|
| 356 |
+
False
|
| 357 |
+
|
| 358 |
+
Notes
|
| 359 |
+
-----
|
| 360 |
+
The worst-case run time is $O(n)$ where n is the length of the sequence.
|
| 361 |
+
|
| 362 |
+
References
|
| 363 |
+
----------
|
| 364 |
+
.. [1] F. Boesch and F. Harary. "Line removal algorithms for graphs
|
| 365 |
+
and their degree lists", IEEE Trans. Circuits and Systems, CAS-23(12),
|
| 366 |
+
pp. 778-782 (1976).
|
| 367 |
+
"""
|
| 368 |
+
try:
|
| 369 |
+
deg_sequence = nx.utils.make_list_of_ints(sequence)
|
| 370 |
+
except nx.NetworkXError:
|
| 371 |
+
return False
|
| 372 |
+
return sum(deg_sequence) % 2 == 0 and min(deg_sequence) >= 0
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
@nx._dispatchable(graphs=None)
|
| 376 |
+
def is_digraphical(in_sequence, out_sequence):
|
| 377 |
+
r"""Returns True if some directed graph can realize the in- and out-degree
|
| 378 |
+
sequences.
|
| 379 |
+
|
| 380 |
+
Parameters
|
| 381 |
+
----------
|
| 382 |
+
in_sequence : list or iterable container
|
| 383 |
+
A sequence of integer node in-degrees
|
| 384 |
+
|
| 385 |
+
out_sequence : list or iterable container
|
| 386 |
+
A sequence of integer node out-degrees
|
| 387 |
+
|
| 388 |
+
Returns
|
| 389 |
+
-------
|
| 390 |
+
valid : bool
|
| 391 |
+
True if in and out-sequences are digraphic False if not.
|
| 392 |
+
|
| 393 |
+
Examples
|
| 394 |
+
--------
|
| 395 |
+
>>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 1), (5, 4)])
|
| 396 |
+
>>> in_seq = (d for n, d in G.in_degree())
|
| 397 |
+
>>> out_seq = (d for n, d in G.out_degree())
|
| 398 |
+
>>> nx.is_digraphical(in_seq, out_seq)
|
| 399 |
+
True
|
| 400 |
+
|
| 401 |
+
To test a non-digraphical scenario:
|
| 402 |
+
>>> in_seq_list = [d for n, d in G.in_degree()]
|
| 403 |
+
>>> in_seq_list[-1] += 1
|
| 404 |
+
>>> nx.is_digraphical(in_seq_list, out_seq)
|
| 405 |
+
False
|
| 406 |
+
|
| 407 |
+
Notes
|
| 408 |
+
-----
|
| 409 |
+
This algorithm is from Kleitman and Wang [1]_.
|
| 410 |
+
The worst case runtime is $O(s \times \log n)$ where $s$ and $n$ are the
|
| 411 |
+
sum and length of the sequences respectively.
|
| 412 |
+
|
| 413 |
+
References
|
| 414 |
+
----------
|
| 415 |
+
.. [1] D.J. Kleitman and D.L. Wang
|
| 416 |
+
Algorithms for Constructing Graphs and Digraphs with Given Valences
|
| 417 |
+
and Factors, Discrete Mathematics, 6(1), pp. 79-88 (1973)
|
| 418 |
+
"""
|
| 419 |
+
try:
|
| 420 |
+
in_deg_sequence = nx.utils.make_list_of_ints(in_sequence)
|
| 421 |
+
out_deg_sequence = nx.utils.make_list_of_ints(out_sequence)
|
| 422 |
+
except nx.NetworkXError:
|
| 423 |
+
return False
|
| 424 |
+
# Process the sequences and form two heaps to store degree pairs with
|
| 425 |
+
# either zero or non-zero out degrees
|
| 426 |
+
sumin, sumout, nin, nout = 0, 0, len(in_deg_sequence), len(out_deg_sequence)
|
| 427 |
+
maxn = max(nin, nout)
|
| 428 |
+
maxin = 0
|
| 429 |
+
if maxn == 0:
|
| 430 |
+
return True
|
| 431 |
+
stubheap, zeroheap = [], []
|
| 432 |
+
for n in range(maxn):
|
| 433 |
+
in_deg, out_deg = 0, 0
|
| 434 |
+
if n < nout:
|
| 435 |
+
out_deg = out_deg_sequence[n]
|
| 436 |
+
if n < nin:
|
| 437 |
+
in_deg = in_deg_sequence[n]
|
| 438 |
+
if in_deg < 0 or out_deg < 0:
|
| 439 |
+
return False
|
| 440 |
+
sumin, sumout, maxin = sumin + in_deg, sumout + out_deg, max(maxin, in_deg)
|
| 441 |
+
if in_deg > 0:
|
| 442 |
+
stubheap.append((-1 * out_deg, -1 * in_deg))
|
| 443 |
+
elif out_deg > 0:
|
| 444 |
+
zeroheap.append(-1 * out_deg)
|
| 445 |
+
if sumin != sumout:
|
| 446 |
+
return False
|
| 447 |
+
heapq.heapify(stubheap)
|
| 448 |
+
heapq.heapify(zeroheap)
|
| 449 |
+
|
| 450 |
+
modstubs = [(0, 0)] * (maxin + 1)
|
| 451 |
+
# Successively reduce degree sequence by removing the maximum out degree
|
| 452 |
+
while stubheap:
|
| 453 |
+
# Take the first value in the sequence with non-zero in degree
|
| 454 |
+
(freeout, freein) = heapq.heappop(stubheap)
|
| 455 |
+
freein *= -1
|
| 456 |
+
if freein > len(stubheap) + len(zeroheap):
|
| 457 |
+
return False
|
| 458 |
+
|
| 459 |
+
# Attach out stubs to the nodes with the most in stubs
|
| 460 |
+
mslen = 0
|
| 461 |
+
for i in range(freein):
|
| 462 |
+
if zeroheap and (not stubheap or stubheap[0][0] > zeroheap[0]):
|
| 463 |
+
stubout = heapq.heappop(zeroheap)
|
| 464 |
+
stubin = 0
|
| 465 |
+
else:
|
| 466 |
+
(stubout, stubin) = heapq.heappop(stubheap)
|
| 467 |
+
if stubout == 0:
|
| 468 |
+
return False
|
| 469 |
+
# Check if target is now totally connected
|
| 470 |
+
if stubout + 1 < 0 or stubin < 0:
|
| 471 |
+
modstubs[mslen] = (stubout + 1, stubin)
|
| 472 |
+
mslen += 1
|
| 473 |
+
|
| 474 |
+
# Add back the nodes to the heap that still have available stubs
|
| 475 |
+
for i in range(mslen):
|
| 476 |
+
stub = modstubs[i]
|
| 477 |
+
if stub[1] < 0:
|
| 478 |
+
heapq.heappush(stubheap, stub)
|
| 479 |
+
else:
|
| 480 |
+
heapq.heappush(zeroheap, stub[0])
|
| 481 |
+
if freeout < 0:
|
| 482 |
+
heapq.heappush(zeroheap, freeout)
|
| 483 |
+
return True
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/hierarchy.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Flow Hierarchy.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
__all__ = ["flow_hierarchy"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 11 |
+
def flow_hierarchy(G, weight=None):
|
| 12 |
+
"""Returns the flow hierarchy of a directed network.
|
| 13 |
+
|
| 14 |
+
Flow hierarchy is defined as the fraction of edges not participating
|
| 15 |
+
in cycles in a directed graph [1]_.
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
----------
|
| 19 |
+
G : DiGraph or MultiDiGraph
|
| 20 |
+
A directed graph
|
| 21 |
+
|
| 22 |
+
weight : string, optional (default=None)
|
| 23 |
+
Attribute to use for edge weights. If None the weight defaults to 1.
|
| 24 |
+
|
| 25 |
+
Returns
|
| 26 |
+
-------
|
| 27 |
+
h : float
|
| 28 |
+
Flow hierarchy value
|
| 29 |
+
|
| 30 |
+
Raises
|
| 31 |
+
------
|
| 32 |
+
NetworkXError
|
| 33 |
+
If `G` is not a directed graph or if `G` has no edges.
|
| 34 |
+
|
| 35 |
+
Notes
|
| 36 |
+
-----
|
| 37 |
+
The algorithm described in [1]_ computes the flow hierarchy through
|
| 38 |
+
exponentiation of the adjacency matrix. This function implements an
|
| 39 |
+
alternative approach that finds strongly connected components.
|
| 40 |
+
An edge is in a cycle if and only if it is in a strongly connected
|
| 41 |
+
component, which can be found in $O(m)$ time using Tarjan's algorithm.
|
| 42 |
+
|
| 43 |
+
References
|
| 44 |
+
----------
|
| 45 |
+
.. [1] Luo, J.; Magee, C.L. (2011),
|
| 46 |
+
Detecting evolving patterns of self-organizing networks by flow
|
| 47 |
+
hierarchy measurement, Complexity, Volume 16 Issue 6 53-61.
|
| 48 |
+
DOI: 10.1002/cplx.20368
|
| 49 |
+
http://web.mit.edu/~cmagee/www/documents/28-DetectingEvolvingPatterns_FlowHierarchy.pdf
|
| 50 |
+
"""
|
| 51 |
+
# corner case: G has no edges
|
| 52 |
+
if nx.is_empty(G):
|
| 53 |
+
raise nx.NetworkXError("flow_hierarchy not applicable to empty graphs")
|
| 54 |
+
if not G.is_directed():
|
| 55 |
+
raise nx.NetworkXError("G must be a digraph in flow_hierarchy")
|
| 56 |
+
scc = nx.strongly_connected_components(G)
|
| 57 |
+
return 1 - sum(G.subgraph(c).size(weight) for c in scc) / G.size(weight)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/hybrid.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Provides functions for finding and testing for locally `(k, l)`-connected
|
| 3 |
+
graphs.
|
| 4 |
+
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import copy
|
| 8 |
+
|
| 9 |
+
import networkx as nx
|
| 10 |
+
|
| 11 |
+
__all__ = ["kl_connected_subgraph", "is_kl_connected"]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@nx._dispatchable(returns_graph=True)
|
| 15 |
+
def kl_connected_subgraph(G, k, l, low_memory=False, same_as_graph=False):
|
| 16 |
+
"""Returns the maximum locally `(k, l)`-connected subgraph of `G`.
|
| 17 |
+
|
| 18 |
+
A graph is locally `(k, l)`-connected if for each edge `(u, v)` in the
|
| 19 |
+
graph there are at least `l` edge-disjoint paths of length at most `k`
|
| 20 |
+
joining `u` to `v`.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
G : NetworkX graph
|
| 25 |
+
The graph in which to find a maximum locally `(k, l)`-connected
|
| 26 |
+
subgraph.
|
| 27 |
+
|
| 28 |
+
k : integer
|
| 29 |
+
The maximum length of paths to consider. A higher number means a looser
|
| 30 |
+
connectivity requirement.
|
| 31 |
+
|
| 32 |
+
l : integer
|
| 33 |
+
The number of edge-disjoint paths. A higher number means a stricter
|
| 34 |
+
connectivity requirement.
|
| 35 |
+
|
| 36 |
+
low_memory : bool
|
| 37 |
+
If this is True, this function uses an algorithm that uses slightly
|
| 38 |
+
more time but less memory.
|
| 39 |
+
|
| 40 |
+
same_as_graph : bool
|
| 41 |
+
If True then return a tuple of the form `(H, is_same)`,
|
| 42 |
+
where `H` is the maximum locally `(k, l)`-connected subgraph and
|
| 43 |
+
`is_same` is a Boolean representing whether `G` is locally `(k,
|
| 44 |
+
l)`-connected (and hence, whether `H` is simply a copy of the input
|
| 45 |
+
graph `G`).
|
| 46 |
+
|
| 47 |
+
Returns
|
| 48 |
+
-------
|
| 49 |
+
NetworkX graph or two-tuple
|
| 50 |
+
If `same_as_graph` is True, then this function returns a
|
| 51 |
+
two-tuple as described above. Otherwise, it returns only the maximum
|
| 52 |
+
locally `(k, l)`-connected subgraph.
|
| 53 |
+
|
| 54 |
+
See also
|
| 55 |
+
--------
|
| 56 |
+
is_kl_connected
|
| 57 |
+
|
| 58 |
+
References
|
| 59 |
+
----------
|
| 60 |
+
.. [1] Chung, Fan and Linyuan Lu. "The Small World Phenomenon in Hybrid
|
| 61 |
+
Power Law Graphs." *Complex Networks*. Springer Berlin Heidelberg,
|
| 62 |
+
2004. 89--104.
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
H = copy.deepcopy(G) # subgraph we construct by removing from G
|
| 66 |
+
|
| 67 |
+
graphOK = True
|
| 68 |
+
deleted_some = True # hack to start off the while loop
|
| 69 |
+
while deleted_some:
|
| 70 |
+
deleted_some = False
|
| 71 |
+
# We use `for edge in list(H.edges()):` instead of
|
| 72 |
+
# `for edge in H.edges():` because we edit the graph `H` in
|
| 73 |
+
# the loop. Hence using an iterator will result in
|
| 74 |
+
# `RuntimeError: dictionary changed size during iteration`
|
| 75 |
+
for edge in list(H.edges()):
|
| 76 |
+
(u, v) = edge
|
| 77 |
+
# Get copy of graph needed for this search
|
| 78 |
+
if low_memory:
|
| 79 |
+
verts = {u, v}
|
| 80 |
+
for i in range(k):
|
| 81 |
+
for w in verts.copy():
|
| 82 |
+
verts.update(G[w])
|
| 83 |
+
G2 = G.subgraph(verts).copy()
|
| 84 |
+
else:
|
| 85 |
+
G2 = copy.deepcopy(G)
|
| 86 |
+
###
|
| 87 |
+
path = [u, v]
|
| 88 |
+
cnt = 0
|
| 89 |
+
accept = 0
|
| 90 |
+
while path:
|
| 91 |
+
cnt += 1 # Found a path
|
| 92 |
+
if cnt >= l:
|
| 93 |
+
accept = 1
|
| 94 |
+
break
|
| 95 |
+
# record edges along this graph
|
| 96 |
+
prev = u
|
| 97 |
+
for w in path:
|
| 98 |
+
if prev != w:
|
| 99 |
+
G2.remove_edge(prev, w)
|
| 100 |
+
prev = w
|
| 101 |
+
# path = shortest_path(G2, u, v, k) # ??? should "Cutoff" be k+1?
|
| 102 |
+
try:
|
| 103 |
+
path = nx.shortest_path(G2, u, v) # ??? should "Cutoff" be k+1?
|
| 104 |
+
except nx.NetworkXNoPath:
|
| 105 |
+
path = False
|
| 106 |
+
# No Other Paths
|
| 107 |
+
if accept == 0:
|
| 108 |
+
H.remove_edge(u, v)
|
| 109 |
+
deleted_some = True
|
| 110 |
+
if graphOK:
|
| 111 |
+
graphOK = False
|
| 112 |
+
# We looked through all edges and removed none of them.
|
| 113 |
+
# So, H is the maximal (k,l)-connected subgraph of G
|
| 114 |
+
if same_as_graph:
|
| 115 |
+
return (H, graphOK)
|
| 116 |
+
return H
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@nx._dispatchable
|
| 120 |
+
def is_kl_connected(G, k, l, low_memory=False):
|
| 121 |
+
"""Returns True if and only if `G` is locally `(k, l)`-connected.
|
| 122 |
+
|
| 123 |
+
A graph is locally `(k, l)`-connected if for each edge `(u, v)` in the
|
| 124 |
+
graph there are at least `l` edge-disjoint paths of length at most `k`
|
| 125 |
+
joining `u` to `v`.
|
| 126 |
+
|
| 127 |
+
Parameters
|
| 128 |
+
----------
|
| 129 |
+
G : NetworkX graph
|
| 130 |
+
The graph to test for local `(k, l)`-connectedness.
|
| 131 |
+
|
| 132 |
+
k : integer
|
| 133 |
+
The maximum length of paths to consider. A higher number means a looser
|
| 134 |
+
connectivity requirement.
|
| 135 |
+
|
| 136 |
+
l : integer
|
| 137 |
+
The number of edge-disjoint paths. A higher number means a stricter
|
| 138 |
+
connectivity requirement.
|
| 139 |
+
|
| 140 |
+
low_memory : bool
|
| 141 |
+
If this is True, this function uses an algorithm that uses slightly
|
| 142 |
+
more time but less memory.
|
| 143 |
+
|
| 144 |
+
Returns
|
| 145 |
+
-------
|
| 146 |
+
bool
|
| 147 |
+
Whether the graph is locally `(k, l)`-connected subgraph.
|
| 148 |
+
|
| 149 |
+
See also
|
| 150 |
+
--------
|
| 151 |
+
kl_connected_subgraph
|
| 152 |
+
|
| 153 |
+
References
|
| 154 |
+
----------
|
| 155 |
+
.. [1] Chung, Fan and Linyuan Lu. "The Small World Phenomenon in Hybrid
|
| 156 |
+
Power Law Graphs." *Complex Networks*. Springer Berlin Heidelberg,
|
| 157 |
+
2004. 89--104.
|
| 158 |
+
|
| 159 |
+
"""
|
| 160 |
+
graphOK = True
|
| 161 |
+
for edge in G.edges():
|
| 162 |
+
(u, v) = edge
|
| 163 |
+
# Get copy of graph needed for this search
|
| 164 |
+
if low_memory:
|
| 165 |
+
verts = {u, v}
|
| 166 |
+
for i in range(k):
|
| 167 |
+
[verts.update(G.neighbors(w)) for w in verts.copy()]
|
| 168 |
+
G2 = G.subgraph(verts)
|
| 169 |
+
else:
|
| 170 |
+
G2 = copy.deepcopy(G)
|
| 171 |
+
###
|
| 172 |
+
path = [u, v]
|
| 173 |
+
cnt = 0
|
| 174 |
+
accept = 0
|
| 175 |
+
while path:
|
| 176 |
+
cnt += 1 # Found a path
|
| 177 |
+
if cnt >= l:
|
| 178 |
+
accept = 1
|
| 179 |
+
break
|
| 180 |
+
# record edges along this graph
|
| 181 |
+
prev = u
|
| 182 |
+
for w in path:
|
| 183 |
+
if w != prev:
|
| 184 |
+
G2.remove_edge(prev, w)
|
| 185 |
+
prev = w
|
| 186 |
+
# path = shortest_path(G2, u, v, k) # ??? should "Cutoff" be k+1?
|
| 187 |
+
try:
|
| 188 |
+
path = nx.shortest_path(G2, u, v) # ??? should "Cutoff" be k+1?
|
| 189 |
+
except nx.NetworkXNoPath:
|
| 190 |
+
path = False
|
| 191 |
+
# No Other Paths
|
| 192 |
+
if accept == 0:
|
| 193 |
+
graphOK = False
|
| 194 |
+
break
|
| 195 |
+
# return status
|
| 196 |
+
return graphOK
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/isolate.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Functions for identifying isolate (degree zero) nodes.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
|
| 7 |
+
__all__ = ["is_isolate", "isolates", "number_of_isolates"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@nx._dispatchable
|
| 11 |
+
def is_isolate(G, n):
|
| 12 |
+
"""Determines whether a node is an isolate.
|
| 13 |
+
|
| 14 |
+
An *isolate* is a node with no neighbors (that is, with degree
|
| 15 |
+
zero). For directed graphs, this means no in-neighbors and no
|
| 16 |
+
out-neighbors.
|
| 17 |
+
|
| 18 |
+
Parameters
|
| 19 |
+
----------
|
| 20 |
+
G : NetworkX graph
|
| 21 |
+
|
| 22 |
+
n : node
|
| 23 |
+
A node in `G`.
|
| 24 |
+
|
| 25 |
+
Returns
|
| 26 |
+
-------
|
| 27 |
+
is_isolate : bool
|
| 28 |
+
True if and only if `n` has no neighbors.
|
| 29 |
+
|
| 30 |
+
Examples
|
| 31 |
+
--------
|
| 32 |
+
>>> G = nx.Graph()
|
| 33 |
+
>>> G.add_edge(1, 2)
|
| 34 |
+
>>> G.add_node(3)
|
| 35 |
+
>>> nx.is_isolate(G, 2)
|
| 36 |
+
False
|
| 37 |
+
>>> nx.is_isolate(G, 3)
|
| 38 |
+
True
|
| 39 |
+
"""
|
| 40 |
+
return G.degree(n) == 0
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@nx._dispatchable
|
| 44 |
+
def isolates(G):
|
| 45 |
+
"""Iterator over isolates in the graph.
|
| 46 |
+
|
| 47 |
+
An *isolate* is a node with no neighbors (that is, with degree
|
| 48 |
+
zero). For directed graphs, this means no in-neighbors and no
|
| 49 |
+
out-neighbors.
|
| 50 |
+
|
| 51 |
+
Parameters
|
| 52 |
+
----------
|
| 53 |
+
G : NetworkX graph
|
| 54 |
+
|
| 55 |
+
Returns
|
| 56 |
+
-------
|
| 57 |
+
iterator
|
| 58 |
+
An iterator over the isolates of `G`.
|
| 59 |
+
|
| 60 |
+
Examples
|
| 61 |
+
--------
|
| 62 |
+
To get a list of all isolates of a graph, use the :class:`list`
|
| 63 |
+
constructor:
|
| 64 |
+
|
| 65 |
+
>>> G = nx.Graph()
|
| 66 |
+
>>> G.add_edge(1, 2)
|
| 67 |
+
>>> G.add_node(3)
|
| 68 |
+
>>> list(nx.isolates(G))
|
| 69 |
+
[3]
|
| 70 |
+
|
| 71 |
+
To remove all isolates in the graph, first create a list of the
|
| 72 |
+
isolates, then use :meth:`Graph.remove_nodes_from`:
|
| 73 |
+
|
| 74 |
+
>>> G.remove_nodes_from(list(nx.isolates(G)))
|
| 75 |
+
>>> list(G)
|
| 76 |
+
[1, 2]
|
| 77 |
+
|
| 78 |
+
For digraphs, isolates have zero in-degree and zero out_degree:
|
| 79 |
+
|
| 80 |
+
>>> G = nx.DiGraph([(0, 1), (1, 2)])
|
| 81 |
+
>>> G.add_node(3)
|
| 82 |
+
>>> list(nx.isolates(G))
|
| 83 |
+
[3]
|
| 84 |
+
|
| 85 |
+
"""
|
| 86 |
+
return (n for n, d in G.degree() if d == 0)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@nx._dispatchable
|
| 90 |
+
def number_of_isolates(G):
|
| 91 |
+
"""Returns the number of isolates in the graph.
|
| 92 |
+
|
| 93 |
+
An *isolate* is a node with no neighbors (that is, with degree
|
| 94 |
+
zero). For directed graphs, this means no in-neighbors and no
|
| 95 |
+
out-neighbors.
|
| 96 |
+
|
| 97 |
+
Parameters
|
| 98 |
+
----------
|
| 99 |
+
G : NetworkX graph
|
| 100 |
+
|
| 101 |
+
Returns
|
| 102 |
+
-------
|
| 103 |
+
int
|
| 104 |
+
The number of degree zero nodes in the graph `G`.
|
| 105 |
+
|
| 106 |
+
"""
|
| 107 |
+
return sum(1 for v in isolates(G))
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/link_prediction.py
ADDED
|
@@ -0,0 +1,687 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Link prediction algorithms.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from math import log
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx.utils import not_implemented_for
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"resource_allocation_index",
|
| 12 |
+
"jaccard_coefficient",
|
| 13 |
+
"adamic_adar_index",
|
| 14 |
+
"preferential_attachment",
|
| 15 |
+
"cn_soundarajan_hopcroft",
|
| 16 |
+
"ra_index_soundarajan_hopcroft",
|
| 17 |
+
"within_inter_cluster",
|
| 18 |
+
"common_neighbor_centrality",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _apply_prediction(G, func, ebunch=None):
|
| 23 |
+
"""Applies the given function to each edge in the specified iterable
|
| 24 |
+
of edges.
|
| 25 |
+
|
| 26 |
+
`G` is an instance of :class:`networkx.Graph`.
|
| 27 |
+
|
| 28 |
+
`func` is a function on two inputs, each of which is a node in the
|
| 29 |
+
graph. The function can return anything, but it should return a
|
| 30 |
+
value representing a prediction of the likelihood of a "link"
|
| 31 |
+
joining the two nodes.
|
| 32 |
+
|
| 33 |
+
`ebunch` is an iterable of pairs of nodes. If not specified, all
|
| 34 |
+
non-edges in the graph `G` will be used.
|
| 35 |
+
|
| 36 |
+
"""
|
| 37 |
+
if ebunch is None:
|
| 38 |
+
ebunch = nx.non_edges(G)
|
| 39 |
+
else:
|
| 40 |
+
for u, v in ebunch:
|
| 41 |
+
if u not in G:
|
| 42 |
+
raise nx.NodeNotFound(f"Node {u} not in G.")
|
| 43 |
+
if v not in G:
|
| 44 |
+
raise nx.NodeNotFound(f"Node {v} not in G.")
|
| 45 |
+
return ((u, v, func(u, v)) for u, v in ebunch)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@not_implemented_for("directed")
|
| 49 |
+
@not_implemented_for("multigraph")
|
| 50 |
+
@nx._dispatchable
|
| 51 |
+
def resource_allocation_index(G, ebunch=None):
|
| 52 |
+
r"""Compute the resource allocation index of all node pairs in ebunch.
|
| 53 |
+
|
| 54 |
+
Resource allocation index of `u` and `v` is defined as
|
| 55 |
+
|
| 56 |
+
.. math::
|
| 57 |
+
|
| 58 |
+
\sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{|\Gamma(w)|}
|
| 59 |
+
|
| 60 |
+
where $\Gamma(u)$ denotes the set of neighbors of $u$.
|
| 61 |
+
|
| 62 |
+
Parameters
|
| 63 |
+
----------
|
| 64 |
+
G : graph
|
| 65 |
+
A NetworkX undirected graph.
|
| 66 |
+
|
| 67 |
+
ebunch : iterable of node pairs, optional (default = None)
|
| 68 |
+
Resource allocation index will be computed for each pair of
|
| 69 |
+
nodes given in the iterable. The pairs must be given as
|
| 70 |
+
2-tuples (u, v) where u and v are nodes in the graph. If ebunch
|
| 71 |
+
is None then all nonexistent edges in the graph will be used.
|
| 72 |
+
Default value: None.
|
| 73 |
+
|
| 74 |
+
Returns
|
| 75 |
+
-------
|
| 76 |
+
piter : iterator
|
| 77 |
+
An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
|
| 78 |
+
pair of nodes and p is their resource allocation index.
|
| 79 |
+
|
| 80 |
+
Raises
|
| 81 |
+
------
|
| 82 |
+
NetworkXNotImplemented
|
| 83 |
+
If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
|
| 84 |
+
|
| 85 |
+
NodeNotFound
|
| 86 |
+
If `ebunch` has a node that is not in `G`.
|
| 87 |
+
|
| 88 |
+
Examples
|
| 89 |
+
--------
|
| 90 |
+
>>> G = nx.complete_graph(5)
|
| 91 |
+
>>> preds = nx.resource_allocation_index(G, [(0, 1), (2, 3)])
|
| 92 |
+
>>> for u, v, p in preds:
|
| 93 |
+
... print(f"({u}, {v}) -> {p:.8f}")
|
| 94 |
+
(0, 1) -> 0.75000000
|
| 95 |
+
(2, 3) -> 0.75000000
|
| 96 |
+
|
| 97 |
+
References
|
| 98 |
+
----------
|
| 99 |
+
.. [1] T. Zhou, L. Lu, Y.-C. Zhang.
|
| 100 |
+
Predicting missing links via local information.
|
| 101 |
+
Eur. Phys. J. B 71 (2009) 623.
|
| 102 |
+
https://arxiv.org/pdf/0901.0553.pdf
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
def predict(u, v):
|
| 106 |
+
return sum(1 / G.degree(w) for w in nx.common_neighbors(G, u, v))
|
| 107 |
+
|
| 108 |
+
return _apply_prediction(G, predict, ebunch)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@not_implemented_for("directed")
|
| 112 |
+
@not_implemented_for("multigraph")
|
| 113 |
+
@nx._dispatchable
|
| 114 |
+
def jaccard_coefficient(G, ebunch=None):
|
| 115 |
+
r"""Compute the Jaccard coefficient of all node pairs in ebunch.
|
| 116 |
+
|
| 117 |
+
Jaccard coefficient of nodes `u` and `v` is defined as
|
| 118 |
+
|
| 119 |
+
.. math::
|
| 120 |
+
|
| 121 |
+
\frac{|\Gamma(u) \cap \Gamma(v)|}{|\Gamma(u) \cup \Gamma(v)|}
|
| 122 |
+
|
| 123 |
+
where $\Gamma(u)$ denotes the set of neighbors of $u$.
|
| 124 |
+
|
| 125 |
+
Parameters
|
| 126 |
+
----------
|
| 127 |
+
G : graph
|
| 128 |
+
A NetworkX undirected graph.
|
| 129 |
+
|
| 130 |
+
ebunch : iterable of node pairs, optional (default = None)
|
| 131 |
+
Jaccard coefficient will be computed for each pair of nodes
|
| 132 |
+
given in the iterable. The pairs must be given as 2-tuples
|
| 133 |
+
(u, v) where u and v are nodes in the graph. If ebunch is None
|
| 134 |
+
then all nonexistent edges in the graph will be used.
|
| 135 |
+
Default value: None.
|
| 136 |
+
|
| 137 |
+
Returns
|
| 138 |
+
-------
|
| 139 |
+
piter : iterator
|
| 140 |
+
An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
|
| 141 |
+
pair of nodes and p is their Jaccard coefficient.
|
| 142 |
+
|
| 143 |
+
Raises
|
| 144 |
+
------
|
| 145 |
+
NetworkXNotImplemented
|
| 146 |
+
If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
|
| 147 |
+
|
| 148 |
+
NodeNotFound
|
| 149 |
+
If `ebunch` has a node that is not in `G`.
|
| 150 |
+
|
| 151 |
+
Examples
|
| 152 |
+
--------
|
| 153 |
+
>>> G = nx.complete_graph(5)
|
| 154 |
+
>>> preds = nx.jaccard_coefficient(G, [(0, 1), (2, 3)])
|
| 155 |
+
>>> for u, v, p in preds:
|
| 156 |
+
... print(f"({u}, {v}) -> {p:.8f}")
|
| 157 |
+
(0, 1) -> 0.60000000
|
| 158 |
+
(2, 3) -> 0.60000000
|
| 159 |
+
|
| 160 |
+
References
|
| 161 |
+
----------
|
| 162 |
+
.. [1] D. Liben-Nowell, J. Kleinberg.
|
| 163 |
+
The Link Prediction Problem for Social Networks (2004).
|
| 164 |
+
http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def predict(u, v):
|
| 168 |
+
union_size = len(set(G[u]) | set(G[v]))
|
| 169 |
+
if union_size == 0:
|
| 170 |
+
return 0
|
| 171 |
+
return len(nx.common_neighbors(G, u, v)) / union_size
|
| 172 |
+
|
| 173 |
+
return _apply_prediction(G, predict, ebunch)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
@not_implemented_for("directed")
|
| 177 |
+
@not_implemented_for("multigraph")
|
| 178 |
+
@nx._dispatchable
|
| 179 |
+
def adamic_adar_index(G, ebunch=None):
|
| 180 |
+
r"""Compute the Adamic-Adar index of all node pairs in ebunch.
|
| 181 |
+
|
| 182 |
+
Adamic-Adar index of `u` and `v` is defined as
|
| 183 |
+
|
| 184 |
+
.. math::
|
| 185 |
+
|
| 186 |
+
\sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{\log |\Gamma(w)|}
|
| 187 |
+
|
| 188 |
+
where $\Gamma(u)$ denotes the set of neighbors of $u$.
|
| 189 |
+
This index leads to zero-division for nodes only connected via self-loops.
|
| 190 |
+
It is intended to be used when no self-loops are present.
|
| 191 |
+
|
| 192 |
+
Parameters
|
| 193 |
+
----------
|
| 194 |
+
G : graph
|
| 195 |
+
NetworkX undirected graph.
|
| 196 |
+
|
| 197 |
+
ebunch : iterable of node pairs, optional (default = None)
|
| 198 |
+
Adamic-Adar index will be computed for each pair of nodes given
|
| 199 |
+
in the iterable. The pairs must be given as 2-tuples (u, v)
|
| 200 |
+
where u and v are nodes in the graph. If ebunch is None then all
|
| 201 |
+
nonexistent edges in the graph will be used.
|
| 202 |
+
Default value: None.
|
| 203 |
+
|
| 204 |
+
Returns
|
| 205 |
+
-------
|
| 206 |
+
piter : iterator
|
| 207 |
+
An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
|
| 208 |
+
pair of nodes and p is their Adamic-Adar index.
|
| 209 |
+
|
| 210 |
+
Raises
|
| 211 |
+
------
|
| 212 |
+
NetworkXNotImplemented
|
| 213 |
+
If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
|
| 214 |
+
|
| 215 |
+
NodeNotFound
|
| 216 |
+
If `ebunch` has a node that is not in `G`.
|
| 217 |
+
|
| 218 |
+
Examples
|
| 219 |
+
--------
|
| 220 |
+
>>> G = nx.complete_graph(5)
|
| 221 |
+
>>> preds = nx.adamic_adar_index(G, [(0, 1), (2, 3)])
|
| 222 |
+
>>> for u, v, p in preds:
|
| 223 |
+
... print(f"({u}, {v}) -> {p:.8f}")
|
| 224 |
+
(0, 1) -> 2.16404256
|
| 225 |
+
(2, 3) -> 2.16404256
|
| 226 |
+
|
| 227 |
+
References
|
| 228 |
+
----------
|
| 229 |
+
.. [1] D. Liben-Nowell, J. Kleinberg.
|
| 230 |
+
The Link Prediction Problem for Social Networks (2004).
|
| 231 |
+
http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
def predict(u, v):
|
| 235 |
+
return sum(1 / log(G.degree(w)) for w in nx.common_neighbors(G, u, v))
|
| 236 |
+
|
| 237 |
+
return _apply_prediction(G, predict, ebunch)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@not_implemented_for("directed")
|
| 241 |
+
@not_implemented_for("multigraph")
|
| 242 |
+
@nx._dispatchable
|
| 243 |
+
def common_neighbor_centrality(G, ebunch=None, alpha=0.8):
|
| 244 |
+
r"""Return the CCPA score for each pair of nodes.
|
| 245 |
+
|
| 246 |
+
Compute the Common Neighbor and Centrality based Parameterized Algorithm(CCPA)
|
| 247 |
+
score of all node pairs in ebunch.
|
| 248 |
+
|
| 249 |
+
CCPA score of `u` and `v` is defined as
|
| 250 |
+
|
| 251 |
+
.. math::
|
| 252 |
+
|
| 253 |
+
\alpha \cdot (|\Gamma (u){\cap }^{}\Gamma (v)|)+(1-\alpha )\cdot \frac{N}{{d}_{uv}}
|
| 254 |
+
|
| 255 |
+
where $\Gamma(u)$ denotes the set of neighbors of $u$, $\Gamma(v)$ denotes the
|
| 256 |
+
set of neighbors of $v$, $\alpha$ is parameter varies between [0,1], $N$ denotes
|
| 257 |
+
total number of nodes in the Graph and ${d}_{uv}$ denotes shortest distance
|
| 258 |
+
between $u$ and $v$.
|
| 259 |
+
|
| 260 |
+
This algorithm is based on two vital properties of nodes, namely the number
|
| 261 |
+
of common neighbors and their centrality. Common neighbor refers to the common
|
| 262 |
+
nodes between two nodes. Centrality refers to the prestige that a node enjoys
|
| 263 |
+
in a network.
|
| 264 |
+
|
| 265 |
+
.. seealso::
|
| 266 |
+
|
| 267 |
+
:func:`common_neighbors`
|
| 268 |
+
|
| 269 |
+
Parameters
|
| 270 |
+
----------
|
| 271 |
+
G : graph
|
| 272 |
+
NetworkX undirected graph.
|
| 273 |
+
|
| 274 |
+
ebunch : iterable of node pairs, optional (default = None)
|
| 275 |
+
Preferential attachment score will be computed for each pair of
|
| 276 |
+
nodes given in the iterable. The pairs must be given as
|
| 277 |
+
2-tuples (u, v) where u and v are nodes in the graph. If ebunch
|
| 278 |
+
is None then all nonexistent edges in the graph will be used.
|
| 279 |
+
Default value: None.
|
| 280 |
+
|
| 281 |
+
alpha : Parameter defined for participation of Common Neighbor
|
| 282 |
+
and Centrality Algorithm share. Values for alpha should
|
| 283 |
+
normally be between 0 and 1. Default value set to 0.8
|
| 284 |
+
because author found better performance at 0.8 for all the
|
| 285 |
+
dataset.
|
| 286 |
+
Default value: 0.8
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
Returns
|
| 290 |
+
-------
|
| 291 |
+
piter : iterator
|
| 292 |
+
An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
|
| 293 |
+
pair of nodes and p is their Common Neighbor and Centrality based
|
| 294 |
+
Parameterized Algorithm(CCPA) score.
|
| 295 |
+
|
| 296 |
+
Raises
|
| 297 |
+
------
|
| 298 |
+
NetworkXNotImplemented
|
| 299 |
+
If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
|
| 300 |
+
|
| 301 |
+
NetworkXAlgorithmError
|
| 302 |
+
If self loops exist in `ebunch` or in `G` (if `ebunch` is `None`).
|
| 303 |
+
|
| 304 |
+
NodeNotFound
|
| 305 |
+
If `ebunch` has a node that is not in `G`.
|
| 306 |
+
|
| 307 |
+
Examples
|
| 308 |
+
--------
|
| 309 |
+
>>> G = nx.complete_graph(5)
|
| 310 |
+
>>> preds = nx.common_neighbor_centrality(G, [(0, 1), (2, 3)])
|
| 311 |
+
>>> for u, v, p in preds:
|
| 312 |
+
... print(f"({u}, {v}) -> {p}")
|
| 313 |
+
(0, 1) -> 3.4000000000000004
|
| 314 |
+
(2, 3) -> 3.4000000000000004
|
| 315 |
+
|
| 316 |
+
References
|
| 317 |
+
----------
|
| 318 |
+
.. [1] Ahmad, I., Akhtar, M.U., Noor, S. et al.
|
| 319 |
+
Missing Link Prediction using Common Neighbor and Centrality based Parameterized Algorithm.
|
| 320 |
+
Sci Rep 10, 364 (2020).
|
| 321 |
+
https://doi.org/10.1038/s41598-019-57304-y
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
# When alpha == 1, the CCPA score simplifies to the number of common neighbors.
|
| 325 |
+
if alpha == 1:
|
| 326 |
+
|
| 327 |
+
def predict(u, v):
|
| 328 |
+
if u == v:
|
| 329 |
+
raise nx.NetworkXAlgorithmError("Self loops are not supported")
|
| 330 |
+
|
| 331 |
+
return len(nx.common_neighbors(G, u, v))
|
| 332 |
+
|
| 333 |
+
else:
|
| 334 |
+
spl = dict(nx.shortest_path_length(G))
|
| 335 |
+
inf = float("inf")
|
| 336 |
+
|
| 337 |
+
def predict(u, v):
|
| 338 |
+
if u == v:
|
| 339 |
+
raise nx.NetworkXAlgorithmError("Self loops are not supported")
|
| 340 |
+
path_len = spl[u].get(v, inf)
|
| 341 |
+
|
| 342 |
+
n_nbrs = len(nx.common_neighbors(G, u, v))
|
| 343 |
+
return alpha * n_nbrs + (1 - alpha) * len(G) / path_len
|
| 344 |
+
|
| 345 |
+
return _apply_prediction(G, predict, ebunch)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
@not_implemented_for("directed")
|
| 349 |
+
@not_implemented_for("multigraph")
|
| 350 |
+
@nx._dispatchable
|
| 351 |
+
def preferential_attachment(G, ebunch=None):
|
| 352 |
+
r"""Compute the preferential attachment score of all node pairs in ebunch.
|
| 353 |
+
|
| 354 |
+
Preferential attachment score of `u` and `v` is defined as
|
| 355 |
+
|
| 356 |
+
.. math::
|
| 357 |
+
|
| 358 |
+
|\Gamma(u)| |\Gamma(v)|
|
| 359 |
+
|
| 360 |
+
where $\Gamma(u)$ denotes the set of neighbors of $u$.
|
| 361 |
+
|
| 362 |
+
Parameters
|
| 363 |
+
----------
|
| 364 |
+
G : graph
|
| 365 |
+
NetworkX undirected graph.
|
| 366 |
+
|
| 367 |
+
ebunch : iterable of node pairs, optional (default = None)
|
| 368 |
+
Preferential attachment score will be computed for each pair of
|
| 369 |
+
nodes given in the iterable. The pairs must be given as
|
| 370 |
+
2-tuples (u, v) where u and v are nodes in the graph. If ebunch
|
| 371 |
+
is None then all nonexistent edges in the graph will be used.
|
| 372 |
+
Default value: None.
|
| 373 |
+
|
| 374 |
+
Returns
|
| 375 |
+
-------
|
| 376 |
+
piter : iterator
|
| 377 |
+
An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
|
| 378 |
+
pair of nodes and p is their preferential attachment score.
|
| 379 |
+
|
| 380 |
+
Raises
|
| 381 |
+
------
|
| 382 |
+
NetworkXNotImplemented
|
| 383 |
+
If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
|
| 384 |
+
|
| 385 |
+
NodeNotFound
|
| 386 |
+
If `ebunch` has a node that is not in `G`.
|
| 387 |
+
|
| 388 |
+
Examples
|
| 389 |
+
--------
|
| 390 |
+
>>> G = nx.complete_graph(5)
|
| 391 |
+
>>> preds = nx.preferential_attachment(G, [(0, 1), (2, 3)])
|
| 392 |
+
>>> for u, v, p in preds:
|
| 393 |
+
... print(f"({u}, {v}) -> {p}")
|
| 394 |
+
(0, 1) -> 16
|
| 395 |
+
(2, 3) -> 16
|
| 396 |
+
|
| 397 |
+
References
|
| 398 |
+
----------
|
| 399 |
+
.. [1] D. Liben-Nowell, J. Kleinberg.
|
| 400 |
+
The Link Prediction Problem for Social Networks (2004).
|
| 401 |
+
http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
|
| 402 |
+
"""
|
| 403 |
+
|
| 404 |
+
def predict(u, v):
|
| 405 |
+
return G.degree(u) * G.degree(v)
|
| 406 |
+
|
| 407 |
+
return _apply_prediction(G, predict, ebunch)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
@not_implemented_for("directed")
|
| 411 |
+
@not_implemented_for("multigraph")
|
| 412 |
+
@nx._dispatchable(node_attrs="community")
|
| 413 |
+
def cn_soundarajan_hopcroft(G, ebunch=None, community="community"):
|
| 414 |
+
r"""Count the number of common neighbors of all node pairs in ebunch
|
| 415 |
+
using community information.
|
| 416 |
+
|
| 417 |
+
For two nodes $u$ and $v$, this function computes the number of
|
| 418 |
+
common neighbors and bonus one for each common neighbor belonging to
|
| 419 |
+
the same community as $u$ and $v$. Mathematically,
|
| 420 |
+
|
| 421 |
+
.. math::
|
| 422 |
+
|
| 423 |
+
|\Gamma(u) \cap \Gamma(v)| + \sum_{w \in \Gamma(u) \cap \Gamma(v)} f(w)
|
| 424 |
+
|
| 425 |
+
where $f(w)$ equals 1 if $w$ belongs to the same community as $u$
|
| 426 |
+
and $v$ or 0 otherwise and $\Gamma(u)$ denotes the set of
|
| 427 |
+
neighbors of $u$.
|
| 428 |
+
|
| 429 |
+
Parameters
|
| 430 |
+
----------
|
| 431 |
+
G : graph
|
| 432 |
+
A NetworkX undirected graph.
|
| 433 |
+
|
| 434 |
+
ebunch : iterable of node pairs, optional (default = None)
|
| 435 |
+
The score will be computed for each pair of nodes given in the
|
| 436 |
+
iterable. The pairs must be given as 2-tuples (u, v) where u
|
| 437 |
+
and v are nodes in the graph. If ebunch is None then all
|
| 438 |
+
nonexistent edges in the graph will be used.
|
| 439 |
+
Default value: None.
|
| 440 |
+
|
| 441 |
+
community : string, optional (default = 'community')
|
| 442 |
+
Nodes attribute name containing the community information.
|
| 443 |
+
G[u][community] identifies which community u belongs to. Each
|
| 444 |
+
node belongs to at most one community. Default value: 'community'.
|
| 445 |
+
|
| 446 |
+
Returns
|
| 447 |
+
-------
|
| 448 |
+
piter : iterator
|
| 449 |
+
An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
|
| 450 |
+
pair of nodes and p is their score.
|
| 451 |
+
|
| 452 |
+
Raises
|
| 453 |
+
------
|
| 454 |
+
NetworkXNotImplemented
|
| 455 |
+
If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
|
| 456 |
+
|
| 457 |
+
NetworkXAlgorithmError
|
| 458 |
+
If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).
|
| 459 |
+
|
| 460 |
+
NodeNotFound
|
| 461 |
+
If `ebunch` has a node that is not in `G`.
|
| 462 |
+
|
| 463 |
+
Examples
|
| 464 |
+
--------
|
| 465 |
+
>>> G = nx.path_graph(3)
|
| 466 |
+
>>> G.nodes[0]["community"] = 0
|
| 467 |
+
>>> G.nodes[1]["community"] = 0
|
| 468 |
+
>>> G.nodes[2]["community"] = 0
|
| 469 |
+
>>> preds = nx.cn_soundarajan_hopcroft(G, [(0, 2)])
|
| 470 |
+
>>> for u, v, p in preds:
|
| 471 |
+
... print(f"({u}, {v}) -> {p}")
|
| 472 |
+
(0, 2) -> 2
|
| 473 |
+
|
| 474 |
+
References
|
| 475 |
+
----------
|
| 476 |
+
.. [1] Sucheta Soundarajan and John Hopcroft.
|
| 477 |
+
Using community information to improve the precision of link
|
| 478 |
+
prediction methods.
|
| 479 |
+
In Proceedings of the 21st international conference companion on
|
| 480 |
+
World Wide Web (WWW '12 Companion). ACM, New York, NY, USA, 607-608.
|
| 481 |
+
http://doi.acm.org/10.1145/2187980.2188150
|
| 482 |
+
"""
|
| 483 |
+
|
| 484 |
+
def predict(u, v):
|
| 485 |
+
Cu = _community(G, u, community)
|
| 486 |
+
Cv = _community(G, v, community)
|
| 487 |
+
cnbors = nx.common_neighbors(G, u, v)
|
| 488 |
+
neighbors = (
|
| 489 |
+
sum(_community(G, w, community) == Cu for w in cnbors) if Cu == Cv else 0
|
| 490 |
+
)
|
| 491 |
+
return len(cnbors) + neighbors
|
| 492 |
+
|
| 493 |
+
return _apply_prediction(G, predict, ebunch)
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
@not_implemented_for("directed")
|
| 497 |
+
@not_implemented_for("multigraph")
|
| 498 |
+
@nx._dispatchable(node_attrs="community")
|
| 499 |
+
def ra_index_soundarajan_hopcroft(G, ebunch=None, community="community"):
|
| 500 |
+
r"""Compute the resource allocation index of all node pairs in
|
| 501 |
+
ebunch using community information.
|
| 502 |
+
|
| 503 |
+
For two nodes $u$ and $v$, this function computes the resource
|
| 504 |
+
allocation index considering only common neighbors belonging to the
|
| 505 |
+
same community as $u$ and $v$. Mathematically,
|
| 506 |
+
|
| 507 |
+
.. math::
|
| 508 |
+
|
| 509 |
+
\sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{f(w)}{|\Gamma(w)|}
|
| 510 |
+
|
| 511 |
+
where $f(w)$ equals 1 if $w$ belongs to the same community as $u$
|
| 512 |
+
and $v$ or 0 otherwise and $\Gamma(u)$ denotes the set of
|
| 513 |
+
neighbors of $u$.
|
| 514 |
+
|
| 515 |
+
Parameters
|
| 516 |
+
----------
|
| 517 |
+
G : graph
|
| 518 |
+
A NetworkX undirected graph.
|
| 519 |
+
|
| 520 |
+
ebunch : iterable of node pairs, optional (default = None)
|
| 521 |
+
The score will be computed for each pair of nodes given in the
|
| 522 |
+
iterable. The pairs must be given as 2-tuples (u, v) where u
|
| 523 |
+
and v are nodes in the graph. If ebunch is None then all
|
| 524 |
+
nonexistent edges in the graph will be used.
|
| 525 |
+
Default value: None.
|
| 526 |
+
|
| 527 |
+
community : string, optional (default = 'community')
|
| 528 |
+
Nodes attribute name containing the community information.
|
| 529 |
+
G[u][community] identifies which community u belongs to. Each
|
| 530 |
+
node belongs to at most one community. Default value: 'community'.
|
| 531 |
+
|
| 532 |
+
Returns
|
| 533 |
+
-------
|
| 534 |
+
piter : iterator
|
| 535 |
+
An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
|
| 536 |
+
pair of nodes and p is their score.
|
| 537 |
+
|
| 538 |
+
Raises
|
| 539 |
+
------
|
| 540 |
+
NetworkXNotImplemented
|
| 541 |
+
If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
|
| 542 |
+
|
| 543 |
+
NetworkXAlgorithmError
|
| 544 |
+
If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).
|
| 545 |
+
|
| 546 |
+
NodeNotFound
|
| 547 |
+
If `ebunch` has a node that is not in `G`.
|
| 548 |
+
|
| 549 |
+
Examples
|
| 550 |
+
--------
|
| 551 |
+
>>> G = nx.Graph()
|
| 552 |
+
>>> G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
|
| 553 |
+
>>> G.nodes[0]["community"] = 0
|
| 554 |
+
>>> G.nodes[1]["community"] = 0
|
| 555 |
+
>>> G.nodes[2]["community"] = 1
|
| 556 |
+
>>> G.nodes[3]["community"] = 0
|
| 557 |
+
>>> preds = nx.ra_index_soundarajan_hopcroft(G, [(0, 3)])
|
| 558 |
+
>>> for u, v, p in preds:
|
| 559 |
+
... print(f"({u}, {v}) -> {p:.8f}")
|
| 560 |
+
(0, 3) -> 0.50000000
|
| 561 |
+
|
| 562 |
+
References
|
| 563 |
+
----------
|
| 564 |
+
.. [1] Sucheta Soundarajan and John Hopcroft.
|
| 565 |
+
Using community information to improve the precision of link
|
| 566 |
+
prediction methods.
|
| 567 |
+
In Proceedings of the 21st international conference companion on
|
| 568 |
+
World Wide Web (WWW '12 Companion). ACM, New York, NY, USA, 607-608.
|
| 569 |
+
http://doi.acm.org/10.1145/2187980.2188150
|
| 570 |
+
"""
|
| 571 |
+
|
| 572 |
+
def predict(u, v):
|
| 573 |
+
Cu = _community(G, u, community)
|
| 574 |
+
Cv = _community(G, v, community)
|
| 575 |
+
if Cu != Cv:
|
| 576 |
+
return 0
|
| 577 |
+
cnbors = nx.common_neighbors(G, u, v)
|
| 578 |
+
return sum(1 / G.degree(w) for w in cnbors if _community(G, w, community) == Cu)
|
| 579 |
+
|
| 580 |
+
return _apply_prediction(G, predict, ebunch)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
@not_implemented_for("directed")
|
| 584 |
+
@not_implemented_for("multigraph")
|
| 585 |
+
@nx._dispatchable(node_attrs="community")
|
| 586 |
+
def within_inter_cluster(G, ebunch=None, delta=0.001, community="community"):
|
| 587 |
+
"""Compute the ratio of within- and inter-cluster common neighbors
|
| 588 |
+
of all node pairs in ebunch.
|
| 589 |
+
|
| 590 |
+
For two nodes `u` and `v`, if a common neighbor `w` belongs to the
|
| 591 |
+
same community as them, `w` is considered as within-cluster common
|
| 592 |
+
neighbor of `u` and `v`. Otherwise, it is considered as
|
| 593 |
+
inter-cluster common neighbor of `u` and `v`. The ratio between the
|
| 594 |
+
size of the set of within- and inter-cluster common neighbors is
|
| 595 |
+
defined as the WIC measure. [1]_
|
| 596 |
+
|
| 597 |
+
Parameters
|
| 598 |
+
----------
|
| 599 |
+
G : graph
|
| 600 |
+
A NetworkX undirected graph.
|
| 601 |
+
|
| 602 |
+
ebunch : iterable of node pairs, optional (default = None)
|
| 603 |
+
The WIC measure will be computed for each pair of nodes given in
|
| 604 |
+
the iterable. The pairs must be given as 2-tuples (u, v) where
|
| 605 |
+
u and v are nodes in the graph. If ebunch is None then all
|
| 606 |
+
nonexistent edges in the graph will be used.
|
| 607 |
+
Default value: None.
|
| 608 |
+
|
| 609 |
+
delta : float, optional (default = 0.001)
|
| 610 |
+
Value to prevent division by zero in case there is no
|
| 611 |
+
inter-cluster common neighbor between two nodes. See [1]_ for
|
| 612 |
+
details. Default value: 0.001.
|
| 613 |
+
|
| 614 |
+
community : string, optional (default = 'community')
|
| 615 |
+
Nodes attribute name containing the community information.
|
| 616 |
+
G[u][community] identifies which community u belongs to. Each
|
| 617 |
+
node belongs to at most one community. Default value: 'community'.
|
| 618 |
+
|
| 619 |
+
Returns
|
| 620 |
+
-------
|
| 621 |
+
piter : iterator
|
| 622 |
+
An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
|
| 623 |
+
pair of nodes and p is their WIC measure.
|
| 624 |
+
|
| 625 |
+
Raises
|
| 626 |
+
------
|
| 627 |
+
NetworkXNotImplemented
|
| 628 |
+
If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
|
| 629 |
+
|
| 630 |
+
NetworkXAlgorithmError
|
| 631 |
+
- If `delta` is less than or equal to zero.
|
| 632 |
+
- If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).
|
| 633 |
+
|
| 634 |
+
NodeNotFound
|
| 635 |
+
If `ebunch` has a node that is not in `G`.
|
| 636 |
+
|
| 637 |
+
Examples
|
| 638 |
+
--------
|
| 639 |
+
>>> G = nx.Graph()
|
| 640 |
+
>>> G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 4), (2, 4), (3, 4)])
|
| 641 |
+
>>> G.nodes[0]["community"] = 0
|
| 642 |
+
>>> G.nodes[1]["community"] = 1
|
| 643 |
+
>>> G.nodes[2]["community"] = 0
|
| 644 |
+
>>> G.nodes[3]["community"] = 0
|
| 645 |
+
>>> G.nodes[4]["community"] = 0
|
| 646 |
+
>>> preds = nx.within_inter_cluster(G, [(0, 4)])
|
| 647 |
+
>>> for u, v, p in preds:
|
| 648 |
+
... print(f"({u}, {v}) -> {p:.8f}")
|
| 649 |
+
(0, 4) -> 1.99800200
|
| 650 |
+
>>> preds = nx.within_inter_cluster(G, [(0, 4)], delta=0.5)
|
| 651 |
+
>>> for u, v, p in preds:
|
| 652 |
+
... print(f"({u}, {v}) -> {p:.8f}")
|
| 653 |
+
(0, 4) -> 1.33333333
|
| 654 |
+
|
| 655 |
+
References
|
| 656 |
+
----------
|
| 657 |
+
.. [1] Jorge Carlos Valverde-Rebaza and Alneu de Andrade Lopes.
|
| 658 |
+
Link prediction in complex networks based on cluster information.
|
| 659 |
+
In Proceedings of the 21st Brazilian conference on Advances in
|
| 660 |
+
Artificial Intelligence (SBIA'12)
|
| 661 |
+
https://doi.org/10.1007/978-3-642-34459-6_10
|
| 662 |
+
"""
|
| 663 |
+
if delta <= 0:
|
| 664 |
+
raise nx.NetworkXAlgorithmError("Delta must be greater than zero")
|
| 665 |
+
|
| 666 |
+
def predict(u, v):
|
| 667 |
+
Cu = _community(G, u, community)
|
| 668 |
+
Cv = _community(G, v, community)
|
| 669 |
+
if Cu != Cv:
|
| 670 |
+
return 0
|
| 671 |
+
cnbors = nx.common_neighbors(G, u, v)
|
| 672 |
+
within = {w for w in cnbors if _community(G, w, community) == Cu}
|
| 673 |
+
inter = cnbors - within
|
| 674 |
+
return len(within) / (len(inter) + delta)
|
| 675 |
+
|
| 676 |
+
return _apply_prediction(G, predict, ebunch)
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def _community(G, u, community):
|
| 680 |
+
"""Get the community of the given node."""
|
| 681 |
+
node_u = G.nodes[u]
|
| 682 |
+
try:
|
| 683 |
+
return node_u[community]
|
| 684 |
+
except KeyError as err:
|
| 685 |
+
raise nx.NetworkXAlgorithmError(
|
| 686 |
+
f"No community information available for Node {u}"
|
| 687 |
+
) from err
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/lowest_common_ancestors.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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from collections import defaultdict
|
| 4 |
+
from collections.abc import Mapping, Set
|
| 5 |
+
from itertools import combinations_with_replacement
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx.utils import UnionFind, arbitrary_element, not_implemented_for
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"all_pairs_lowest_common_ancestor",
|
| 12 |
+
"tree_all_pairs_lowest_common_ancestor",
|
| 13 |
+
"lowest_common_ancestor",
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@not_implemented_for("undirected")
|
| 18 |
+
@nx._dispatchable
|
| 19 |
+
def all_pairs_lowest_common_ancestor(G, pairs=None):
|
| 20 |
+
"""Return the lowest common ancestor of all pairs or the provided pairs
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
G : NetworkX directed graph
|
| 25 |
+
|
| 26 |
+
pairs : iterable of pairs of nodes, optional (default: all pairs)
|
| 27 |
+
The pairs of nodes of interest.
|
| 28 |
+
If None, will find the LCA of all pairs of nodes.
|
| 29 |
+
|
| 30 |
+
Yields
|
| 31 |
+
------
|
| 32 |
+
((node1, node2), lca) : 2-tuple
|
| 33 |
+
Where lca is least common ancestor of node1 and node2.
|
| 34 |
+
Note that for the default case, the order of the node pair is not considered,
|
| 35 |
+
e.g. you will not get both ``(a, b)`` and ``(b, a)``
|
| 36 |
+
|
| 37 |
+
Raises
|
| 38 |
+
------
|
| 39 |
+
NetworkXPointlessConcept
|
| 40 |
+
If `G` is null.
|
| 41 |
+
NetworkXError
|
| 42 |
+
If `G` is not a DAG.
|
| 43 |
+
|
| 44 |
+
Examples
|
| 45 |
+
--------
|
| 46 |
+
>>> from pprint import pprint
|
| 47 |
+
|
| 48 |
+
The default behavior is to yield the lowest common ancestor for all
|
| 49 |
+
possible combinations of nodes in `G`, including self-pairings:
|
| 50 |
+
|
| 51 |
+
>>> G = nx.DiGraph([(0, 1), (0, 3), (1, 2)])
|
| 52 |
+
>>> pprint(dict(nx.all_pairs_lowest_common_ancestor(G)))
|
| 53 |
+
{(0, 0): 0,
|
| 54 |
+
(0, 1): 0,
|
| 55 |
+
(0, 2): 0,
|
| 56 |
+
(0, 3): 0,
|
| 57 |
+
(1, 1): 1,
|
| 58 |
+
(1, 2): 1,
|
| 59 |
+
(1, 3): 0,
|
| 60 |
+
(2, 2): 2,
|
| 61 |
+
(3, 2): 0,
|
| 62 |
+
(3, 3): 3}
|
| 63 |
+
|
| 64 |
+
The pairs argument can be used to limit the output to only the
|
| 65 |
+
specified node pairings:
|
| 66 |
+
|
| 67 |
+
>>> dict(nx.all_pairs_lowest_common_ancestor(G, pairs=[(1, 2), (2, 3)]))
|
| 68 |
+
{(1, 2): 1, (2, 3): 0}
|
| 69 |
+
|
| 70 |
+
Notes
|
| 71 |
+
-----
|
| 72 |
+
Only defined on non-null directed acyclic graphs.
|
| 73 |
+
|
| 74 |
+
See Also
|
| 75 |
+
--------
|
| 76 |
+
lowest_common_ancestor
|
| 77 |
+
"""
|
| 78 |
+
if not nx.is_directed_acyclic_graph(G):
|
| 79 |
+
raise nx.NetworkXError("LCA only defined on directed acyclic graphs.")
|
| 80 |
+
if len(G) == 0:
|
| 81 |
+
raise nx.NetworkXPointlessConcept("LCA meaningless on null graphs.")
|
| 82 |
+
|
| 83 |
+
if pairs is None:
|
| 84 |
+
pairs = combinations_with_replacement(G, 2)
|
| 85 |
+
else:
|
| 86 |
+
# Convert iterator to iterable, if necessary. Trim duplicates.
|
| 87 |
+
pairs = dict.fromkeys(pairs)
|
| 88 |
+
# Verify that each of the nodes in the provided pairs is in G
|
| 89 |
+
nodeset = set(G)
|
| 90 |
+
for pair in pairs:
|
| 91 |
+
if set(pair) - nodeset:
|
| 92 |
+
raise nx.NodeNotFound(
|
| 93 |
+
f"Node(s) {set(pair) - nodeset} from pair {pair} not in G."
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# Once input validation is done, construct the generator
|
| 97 |
+
def generate_lca_from_pairs(G, pairs):
|
| 98 |
+
ancestor_cache = {}
|
| 99 |
+
|
| 100 |
+
for v, w in pairs:
|
| 101 |
+
if v not in ancestor_cache:
|
| 102 |
+
ancestor_cache[v] = nx.ancestors(G, v)
|
| 103 |
+
ancestor_cache[v].add(v)
|
| 104 |
+
if w not in ancestor_cache:
|
| 105 |
+
ancestor_cache[w] = nx.ancestors(G, w)
|
| 106 |
+
ancestor_cache[w].add(w)
|
| 107 |
+
|
| 108 |
+
common_ancestors = ancestor_cache[v] & ancestor_cache[w]
|
| 109 |
+
|
| 110 |
+
if common_ancestors:
|
| 111 |
+
common_ancestor = next(iter(common_ancestors))
|
| 112 |
+
while True:
|
| 113 |
+
successor = None
|
| 114 |
+
for lower_ancestor in G.successors(common_ancestor):
|
| 115 |
+
if lower_ancestor in common_ancestors:
|
| 116 |
+
successor = lower_ancestor
|
| 117 |
+
break
|
| 118 |
+
if successor is None:
|
| 119 |
+
break
|
| 120 |
+
common_ancestor = successor
|
| 121 |
+
yield ((v, w), common_ancestor)
|
| 122 |
+
|
| 123 |
+
return generate_lca_from_pairs(G, pairs)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@not_implemented_for("undirected")
|
| 127 |
+
@nx._dispatchable
|
| 128 |
+
def lowest_common_ancestor(G, node1, node2, default=None):
|
| 129 |
+
"""Compute the lowest common ancestor of the given pair of nodes.
|
| 130 |
+
|
| 131 |
+
Parameters
|
| 132 |
+
----------
|
| 133 |
+
G : NetworkX directed graph
|
| 134 |
+
|
| 135 |
+
node1, node2 : nodes in the graph.
|
| 136 |
+
|
| 137 |
+
default : object
|
| 138 |
+
Returned if no common ancestor between `node1` and `node2`
|
| 139 |
+
|
| 140 |
+
Returns
|
| 141 |
+
-------
|
| 142 |
+
The lowest common ancestor of node1 and node2,
|
| 143 |
+
or default if they have no common ancestors.
|
| 144 |
+
|
| 145 |
+
Examples
|
| 146 |
+
--------
|
| 147 |
+
>>> G = nx.DiGraph()
|
| 148 |
+
>>> nx.add_path(G, (0, 1, 2, 3))
|
| 149 |
+
>>> nx.add_path(G, (0, 4, 3))
|
| 150 |
+
>>> nx.lowest_common_ancestor(G, 2, 4)
|
| 151 |
+
0
|
| 152 |
+
|
| 153 |
+
See Also
|
| 154 |
+
--------
|
| 155 |
+
all_pairs_lowest_common_ancestor"""
|
| 156 |
+
|
| 157 |
+
ans = list(all_pairs_lowest_common_ancestor(G, pairs=[(node1, node2)]))
|
| 158 |
+
if ans:
|
| 159 |
+
assert len(ans) == 1
|
| 160 |
+
return ans[0][1]
|
| 161 |
+
return default
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@not_implemented_for("undirected")
|
| 165 |
+
@nx._dispatchable
|
| 166 |
+
def tree_all_pairs_lowest_common_ancestor(G, root=None, pairs=None):
|
| 167 |
+
r"""Yield the lowest common ancestor for sets of pairs in a tree.
|
| 168 |
+
|
| 169 |
+
Parameters
|
| 170 |
+
----------
|
| 171 |
+
G : NetworkX directed graph (must be a tree)
|
| 172 |
+
|
| 173 |
+
root : node, optional (default: None)
|
| 174 |
+
The root of the subtree to operate on.
|
| 175 |
+
If None, assume the entire graph has exactly one source and use that.
|
| 176 |
+
|
| 177 |
+
pairs : iterable or iterator of pairs of nodes, optional (default: None)
|
| 178 |
+
The pairs of interest. If None, Defaults to all pairs of nodes
|
| 179 |
+
under `root` that have a lowest common ancestor.
|
| 180 |
+
|
| 181 |
+
Returns
|
| 182 |
+
-------
|
| 183 |
+
lcas : generator of tuples `((u, v), lca)` where `u` and `v` are nodes
|
| 184 |
+
in `pairs` and `lca` is their lowest common ancestor.
|
| 185 |
+
|
| 186 |
+
Examples
|
| 187 |
+
--------
|
| 188 |
+
>>> import pprint
|
| 189 |
+
>>> G = nx.DiGraph([(1, 3), (2, 4), (1, 2)])
|
| 190 |
+
>>> pprint.pprint(dict(nx.tree_all_pairs_lowest_common_ancestor(G)))
|
| 191 |
+
{(1, 1): 1,
|
| 192 |
+
(2, 1): 1,
|
| 193 |
+
(2, 2): 2,
|
| 194 |
+
(3, 1): 1,
|
| 195 |
+
(3, 2): 1,
|
| 196 |
+
(3, 3): 3,
|
| 197 |
+
(3, 4): 1,
|
| 198 |
+
(4, 1): 1,
|
| 199 |
+
(4, 2): 2,
|
| 200 |
+
(4, 4): 4}
|
| 201 |
+
|
| 202 |
+
We can also use `pairs` argument to specify the pairs of nodes for which we
|
| 203 |
+
want to compute lowest common ancestors. Here is an example:
|
| 204 |
+
|
| 205 |
+
>>> dict(nx.tree_all_pairs_lowest_common_ancestor(G, pairs=[(1, 4), (2, 3)]))
|
| 206 |
+
{(2, 3): 1, (1, 4): 1}
|
| 207 |
+
|
| 208 |
+
Notes
|
| 209 |
+
-----
|
| 210 |
+
Only defined on non-null trees represented with directed edges from
|
| 211 |
+
parents to children. Uses Tarjan's off-line lowest-common-ancestors
|
| 212 |
+
algorithm. Runs in time $O(4 \times (V + E + P))$ time, where 4 is the largest
|
| 213 |
+
value of the inverse Ackermann function likely to ever come up in actual
|
| 214 |
+
use, and $P$ is the number of pairs requested (or $V^2$ if all are needed).
|
| 215 |
+
|
| 216 |
+
Tarjan, R. E. (1979), "Applications of path compression on balanced trees",
|
| 217 |
+
Journal of the ACM 26 (4): 690-715, doi:10.1145/322154.322161.
|
| 218 |
+
|
| 219 |
+
See Also
|
| 220 |
+
--------
|
| 221 |
+
all_pairs_lowest_common_ancestor: similar routine for general DAGs
|
| 222 |
+
lowest_common_ancestor: just a single pair for general DAGs
|
| 223 |
+
"""
|
| 224 |
+
if len(G) == 0:
|
| 225 |
+
raise nx.NetworkXPointlessConcept("LCA meaningless on null graphs.")
|
| 226 |
+
|
| 227 |
+
# Index pairs of interest for efficient lookup from either side.
|
| 228 |
+
if pairs is not None:
|
| 229 |
+
pair_dict = defaultdict(set)
|
| 230 |
+
# See note on all_pairs_lowest_common_ancestor.
|
| 231 |
+
if not isinstance(pairs, Mapping | Set):
|
| 232 |
+
pairs = set(pairs)
|
| 233 |
+
for u, v in pairs:
|
| 234 |
+
for n in (u, v):
|
| 235 |
+
if n not in G:
|
| 236 |
+
msg = f"The node {str(n)} is not in the digraph."
|
| 237 |
+
raise nx.NodeNotFound(msg)
|
| 238 |
+
pair_dict[u].add(v)
|
| 239 |
+
pair_dict[v].add(u)
|
| 240 |
+
|
| 241 |
+
# If root is not specified, find the exactly one node with in degree 0 and
|
| 242 |
+
# use it. Raise an error if none are found, or more than one is. Also check
|
| 243 |
+
# for any nodes with in degree larger than 1, which would imply G is not a
|
| 244 |
+
# tree.
|
| 245 |
+
if root is None:
|
| 246 |
+
for n, deg in G.in_degree:
|
| 247 |
+
if deg == 0:
|
| 248 |
+
if root is not None:
|
| 249 |
+
msg = "No root specified and tree has multiple sources."
|
| 250 |
+
raise nx.NetworkXError(msg)
|
| 251 |
+
root = n
|
| 252 |
+
# checking deg>1 is not sufficient for MultiDiGraphs
|
| 253 |
+
elif deg > 1 and len(G.pred[n]) > 1:
|
| 254 |
+
msg = "Tree LCA only defined on trees; use DAG routine."
|
| 255 |
+
raise nx.NetworkXError(msg)
|
| 256 |
+
if root is None:
|
| 257 |
+
raise nx.NetworkXError("Graph contains a cycle.")
|
| 258 |
+
|
| 259 |
+
# Iterative implementation of Tarjan's offline lca algorithm
|
| 260 |
+
# as described in CLRS on page 521 (2nd edition)/page 584 (3rd edition)
|
| 261 |
+
uf = UnionFind()
|
| 262 |
+
ancestors = {}
|
| 263 |
+
for node in G:
|
| 264 |
+
ancestors[node] = uf[node]
|
| 265 |
+
|
| 266 |
+
colors = defaultdict(bool)
|
| 267 |
+
for node in nx.dfs_postorder_nodes(G, root):
|
| 268 |
+
colors[node] = True
|
| 269 |
+
for v in pair_dict[node] if pairs is not None else G:
|
| 270 |
+
if colors[v]:
|
| 271 |
+
# If the user requested both directions of a pair, give it.
|
| 272 |
+
# Otherwise, just give one.
|
| 273 |
+
if pairs is not None and (node, v) in pairs:
|
| 274 |
+
yield (node, v), ancestors[uf[v]]
|
| 275 |
+
if pairs is None or (v, node) in pairs:
|
| 276 |
+
yield (v, node), ancestors[uf[v]]
|
| 277 |
+
if node != root:
|
| 278 |
+
parent = arbitrary_element(G.pred[node])
|
| 279 |
+
uf.union(parent, node)
|
| 280 |
+
ancestors[uf[parent]] = parent
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/matching.py
ADDED
|
@@ -0,0 +1,1148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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kx.utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"is_matching",
|
| 10 |
+
"is_maximal_matching",
|
| 11 |
+
"is_perfect_matching",
|
| 12 |
+
"max_weight_matching",
|
| 13 |
+
"min_weight_matching",
|
| 14 |
+
"maximal_matching",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@not_implemented_for("multigraph")
|
| 19 |
+
@not_implemented_for("directed")
|
| 20 |
+
@nx._dispatchable
|
| 21 |
+
def maximal_matching(G):
|
| 22 |
+
r"""Find a maximal matching in the graph.
|
| 23 |
+
|
| 24 |
+
A matching is a subset of edges in which no node occurs more than once.
|
| 25 |
+
A maximal matching cannot add more edges and still be a matching.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
G : NetworkX graph
|
| 30 |
+
Undirected graph
|
| 31 |
+
|
| 32 |
+
Returns
|
| 33 |
+
-------
|
| 34 |
+
matching : set
|
| 35 |
+
A maximal matching of the graph.
|
| 36 |
+
|
| 37 |
+
Examples
|
| 38 |
+
--------
|
| 39 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 5), (4, 5)])
|
| 40 |
+
>>> sorted(nx.maximal_matching(G))
|
| 41 |
+
[(1, 2), (3, 5)]
|
| 42 |
+
|
| 43 |
+
Notes
|
| 44 |
+
-----
|
| 45 |
+
The algorithm greedily selects a maximal matching M of the graph G
|
| 46 |
+
(i.e. no superset of M exists). It runs in $O(|E|)$ time.
|
| 47 |
+
"""
|
| 48 |
+
matching = set()
|
| 49 |
+
nodes = set()
|
| 50 |
+
for edge in G.edges():
|
| 51 |
+
# If the edge isn't covered, add it to the matching
|
| 52 |
+
# then remove neighborhood of u and v from consideration.
|
| 53 |
+
u, v = edge
|
| 54 |
+
if u not in nodes and v not in nodes and u != v:
|
| 55 |
+
matching.add(edge)
|
| 56 |
+
nodes.update(edge)
|
| 57 |
+
return matching
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def matching_dict_to_set(matching):
|
| 61 |
+
"""Converts matching dict format to matching set format
|
| 62 |
+
|
| 63 |
+
Converts a dictionary representing a matching (as returned by
|
| 64 |
+
:func:`max_weight_matching`) to a set representing a matching (as
|
| 65 |
+
returned by :func:`maximal_matching`).
|
| 66 |
+
|
| 67 |
+
In the definition of maximal matching adopted by NetworkX,
|
| 68 |
+
self-loops are not allowed, so the provided dictionary is expected
|
| 69 |
+
to never have any mapping from a key to itself. However, the
|
| 70 |
+
dictionary is expected to have mirrored key/value pairs, for
|
| 71 |
+
example, key ``u`` with value ``v`` and key ``v`` with value ``u``.
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
edges = set()
|
| 75 |
+
for edge in matching.items():
|
| 76 |
+
u, v = edge
|
| 77 |
+
if (v, u) in edges or edge in edges:
|
| 78 |
+
continue
|
| 79 |
+
if u == v:
|
| 80 |
+
raise nx.NetworkXError(f"Selfloops cannot appear in matchings {edge}")
|
| 81 |
+
edges.add(edge)
|
| 82 |
+
return edges
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@nx._dispatchable
|
| 86 |
+
def is_matching(G, matching):
|
| 87 |
+
"""Return True if ``matching`` is a valid matching of ``G``
|
| 88 |
+
|
| 89 |
+
A *matching* in a graph is a set of edges in which no two distinct
|
| 90 |
+
edges share a common endpoint. Each node is incident to at most one
|
| 91 |
+
edge in the matching. The edges are said to be independent.
|
| 92 |
+
|
| 93 |
+
Parameters
|
| 94 |
+
----------
|
| 95 |
+
G : NetworkX graph
|
| 96 |
+
|
| 97 |
+
matching : dict or set
|
| 98 |
+
A dictionary or set representing a matching. If a dictionary, it
|
| 99 |
+
must have ``matching[u] == v`` and ``matching[v] == u`` for each
|
| 100 |
+
edge ``(u, v)`` in the matching. If a set, it must have elements
|
| 101 |
+
of the form ``(u, v)``, where ``(u, v)`` is an edge in the
|
| 102 |
+
matching.
|
| 103 |
+
|
| 104 |
+
Returns
|
| 105 |
+
-------
|
| 106 |
+
bool
|
| 107 |
+
Whether the given set or dictionary represents a valid matching
|
| 108 |
+
in the graph.
|
| 109 |
+
|
| 110 |
+
Raises
|
| 111 |
+
------
|
| 112 |
+
NetworkXError
|
| 113 |
+
If the proposed matching has an edge to a node not in G.
|
| 114 |
+
Or if the matching is not a collection of 2-tuple edges.
|
| 115 |
+
|
| 116 |
+
Examples
|
| 117 |
+
--------
|
| 118 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 5), (4, 5)])
|
| 119 |
+
>>> nx.is_maximal_matching(G, {1: 3, 2: 4}) # using dict to represent matching
|
| 120 |
+
True
|
| 121 |
+
|
| 122 |
+
>>> nx.is_matching(G, {(1, 3), (2, 4)}) # using set to represent matching
|
| 123 |
+
True
|
| 124 |
+
|
| 125 |
+
"""
|
| 126 |
+
if isinstance(matching, dict):
|
| 127 |
+
matching = matching_dict_to_set(matching)
|
| 128 |
+
|
| 129 |
+
nodes = set()
|
| 130 |
+
for edge in matching:
|
| 131 |
+
if len(edge) != 2:
|
| 132 |
+
raise nx.NetworkXError(f"matching has non-2-tuple edge {edge}")
|
| 133 |
+
u, v = edge
|
| 134 |
+
if u not in G or v not in G:
|
| 135 |
+
raise nx.NetworkXError(f"matching contains edge {edge} with node not in G")
|
| 136 |
+
if u == v:
|
| 137 |
+
return False
|
| 138 |
+
if not G.has_edge(u, v):
|
| 139 |
+
return False
|
| 140 |
+
if u in nodes or v in nodes:
|
| 141 |
+
return False
|
| 142 |
+
nodes.update(edge)
|
| 143 |
+
return True
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@nx._dispatchable
|
| 147 |
+
def is_maximal_matching(G, matching):
|
| 148 |
+
"""Return True if ``matching`` is a maximal matching of ``G``
|
| 149 |
+
|
| 150 |
+
A *maximal matching* in a graph is a matching in which adding any
|
| 151 |
+
edge would cause the set to no longer be a valid matching.
|
| 152 |
+
|
| 153 |
+
Parameters
|
| 154 |
+
----------
|
| 155 |
+
G : NetworkX graph
|
| 156 |
+
|
| 157 |
+
matching : dict or set
|
| 158 |
+
A dictionary or set representing a matching. If a dictionary, it
|
| 159 |
+
must have ``matching[u] == v`` and ``matching[v] == u`` for each
|
| 160 |
+
edge ``(u, v)`` in the matching. If a set, it must have elements
|
| 161 |
+
of the form ``(u, v)``, where ``(u, v)`` is an edge in the
|
| 162 |
+
matching.
|
| 163 |
+
|
| 164 |
+
Returns
|
| 165 |
+
-------
|
| 166 |
+
bool
|
| 167 |
+
Whether the given set or dictionary represents a valid maximal
|
| 168 |
+
matching in the graph.
|
| 169 |
+
|
| 170 |
+
Examples
|
| 171 |
+
--------
|
| 172 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5)])
|
| 173 |
+
>>> nx.is_maximal_matching(G, {(1, 2), (3, 4)})
|
| 174 |
+
True
|
| 175 |
+
|
| 176 |
+
"""
|
| 177 |
+
if isinstance(matching, dict):
|
| 178 |
+
matching = matching_dict_to_set(matching)
|
| 179 |
+
# If the given set is not a matching, then it is not a maximal matching.
|
| 180 |
+
edges = set()
|
| 181 |
+
nodes = set()
|
| 182 |
+
for edge in matching:
|
| 183 |
+
if len(edge) != 2:
|
| 184 |
+
raise nx.NetworkXError(f"matching has non-2-tuple edge {edge}")
|
| 185 |
+
u, v = edge
|
| 186 |
+
if u not in G or v not in G:
|
| 187 |
+
raise nx.NetworkXError(f"matching contains edge {edge} with node not in G")
|
| 188 |
+
if u == v:
|
| 189 |
+
return False
|
| 190 |
+
if not G.has_edge(u, v):
|
| 191 |
+
return False
|
| 192 |
+
if u in nodes or v in nodes:
|
| 193 |
+
return False
|
| 194 |
+
nodes.update(edge)
|
| 195 |
+
edges.add(edge)
|
| 196 |
+
edges.add((v, u))
|
| 197 |
+
# A matching is maximal if adding any new edge from G to it
|
| 198 |
+
# causes the resulting set to match some node twice.
|
| 199 |
+
# Be careful to check for adding selfloops
|
| 200 |
+
for u, v in G.edges:
|
| 201 |
+
if (u, v) not in edges:
|
| 202 |
+
# could add edge (u, v) to edges and have a bigger matching
|
| 203 |
+
if u not in nodes and v not in nodes and u != v:
|
| 204 |
+
return False
|
| 205 |
+
return True
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@nx._dispatchable
|
| 209 |
+
def is_perfect_matching(G, matching):
|
| 210 |
+
"""Return True if ``matching`` is a perfect matching for ``G``
|
| 211 |
+
|
| 212 |
+
A *perfect matching* in a graph is a matching in which exactly one edge
|
| 213 |
+
is incident upon each vertex.
|
| 214 |
+
|
| 215 |
+
Parameters
|
| 216 |
+
----------
|
| 217 |
+
G : NetworkX graph
|
| 218 |
+
|
| 219 |
+
matching : dict or set
|
| 220 |
+
A dictionary or set representing a matching. If a dictionary, it
|
| 221 |
+
must have ``matching[u] == v`` and ``matching[v] == u`` for each
|
| 222 |
+
edge ``(u, v)`` in the matching. If a set, it must have elements
|
| 223 |
+
of the form ``(u, v)``, where ``(u, v)`` is an edge in the
|
| 224 |
+
matching.
|
| 225 |
+
|
| 226 |
+
Returns
|
| 227 |
+
-------
|
| 228 |
+
bool
|
| 229 |
+
Whether the given set or dictionary represents a valid perfect
|
| 230 |
+
matching in the graph.
|
| 231 |
+
|
| 232 |
+
Examples
|
| 233 |
+
--------
|
| 234 |
+
>>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 5), (4, 5), (4, 6)])
|
| 235 |
+
>>> my_match = {1: 2, 3: 5, 4: 6}
|
| 236 |
+
>>> nx.is_perfect_matching(G, my_match)
|
| 237 |
+
True
|
| 238 |
+
|
| 239 |
+
"""
|
| 240 |
+
if isinstance(matching, dict):
|
| 241 |
+
matching = matching_dict_to_set(matching)
|
| 242 |
+
|
| 243 |
+
nodes = set()
|
| 244 |
+
for edge in matching:
|
| 245 |
+
if len(edge) != 2:
|
| 246 |
+
raise nx.NetworkXError(f"matching has non-2-tuple edge {edge}")
|
| 247 |
+
u, v = edge
|
| 248 |
+
if u not in G or v not in G:
|
| 249 |
+
raise nx.NetworkXError(f"matching contains edge {edge} with node not in G")
|
| 250 |
+
if u == v:
|
| 251 |
+
return False
|
| 252 |
+
if not G.has_edge(u, v):
|
| 253 |
+
return False
|
| 254 |
+
if u in nodes or v in nodes:
|
| 255 |
+
return False
|
| 256 |
+
nodes.update(edge)
|
| 257 |
+
return len(nodes) == len(G)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
@not_implemented_for("multigraph")
|
| 261 |
+
@not_implemented_for("directed")
|
| 262 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 263 |
+
def min_weight_matching(G, weight="weight"):
|
| 264 |
+
"""Compute a minimum-weight maximum-cardinality matching of `G`.
|
| 265 |
+
|
| 266 |
+
The minimum-weight maximum-cardinality matching is the matching
|
| 267 |
+
that has the minimum weight among all maximum-cardinality matchings.
|
| 268 |
+
|
| 269 |
+
Use the maximum-weight algorithm with edge weights subtracted
|
| 270 |
+
from the maximum weight of all edges.
|
| 271 |
+
|
| 272 |
+
A matching is a subset of edges in which no node occurs more than once.
|
| 273 |
+
The weight of a matching is the sum of the weights of its edges.
|
| 274 |
+
A maximal matching cannot add more edges and still be a matching.
|
| 275 |
+
The cardinality of a matching is the number of matched edges.
|
| 276 |
+
|
| 277 |
+
This method replaces the edge weights with 1 plus the maximum edge weight
|
| 278 |
+
minus the original edge weight.
|
| 279 |
+
|
| 280 |
+
new_weight = (max_weight + 1) - edge_weight
|
| 281 |
+
|
| 282 |
+
then runs :func:`max_weight_matching` with the new weights.
|
| 283 |
+
The max weight matching with these new weights corresponds
|
| 284 |
+
to the min weight matching using the original weights.
|
| 285 |
+
Adding 1 to the max edge weight keeps all edge weights positive
|
| 286 |
+
and as integers if they started as integers.
|
| 287 |
+
|
| 288 |
+
Read the documentation of `max_weight_matching` for more information.
|
| 289 |
+
|
| 290 |
+
Parameters
|
| 291 |
+
----------
|
| 292 |
+
G : NetworkX graph
|
| 293 |
+
Undirected graph
|
| 294 |
+
|
| 295 |
+
weight: string, optional (default='weight')
|
| 296 |
+
Edge data key corresponding to the edge weight.
|
| 297 |
+
If key not found, uses 1 as weight.
|
| 298 |
+
|
| 299 |
+
Returns
|
| 300 |
+
-------
|
| 301 |
+
matching : set
|
| 302 |
+
A minimal weight matching of the graph.
|
| 303 |
+
|
| 304 |
+
See Also
|
| 305 |
+
--------
|
| 306 |
+
max_weight_matching
|
| 307 |
+
"""
|
| 308 |
+
if len(G.edges) == 0:
|
| 309 |
+
return max_weight_matching(G, maxcardinality=True, weight=weight)
|
| 310 |
+
G_edges = G.edges(data=weight, default=1)
|
| 311 |
+
max_weight = 1 + max(w for _, _, w in G_edges)
|
| 312 |
+
InvG = nx.Graph()
|
| 313 |
+
edges = ((u, v, max_weight - w) for u, v, w in G_edges)
|
| 314 |
+
InvG.add_weighted_edges_from(edges, weight=weight)
|
| 315 |
+
return max_weight_matching(InvG, maxcardinality=True, weight=weight)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@not_implemented_for("multigraph")
|
| 319 |
+
@not_implemented_for("directed")
|
| 320 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 321 |
+
def max_weight_matching(G, maxcardinality=False, weight="weight"):
|
| 322 |
+
"""Compute a maximum-weighted matching of G.
|
| 323 |
+
|
| 324 |
+
A matching is a subset of edges in which no node occurs more than once.
|
| 325 |
+
The weight of a matching is the sum of the weights of its edges.
|
| 326 |
+
A maximal matching cannot add more edges and still be a matching.
|
| 327 |
+
The cardinality of a matching is the number of matched edges.
|
| 328 |
+
|
| 329 |
+
Parameters
|
| 330 |
+
----------
|
| 331 |
+
G : NetworkX graph
|
| 332 |
+
Undirected graph
|
| 333 |
+
|
| 334 |
+
maxcardinality: bool, optional (default=False)
|
| 335 |
+
If maxcardinality is True, compute the maximum-cardinality matching
|
| 336 |
+
with maximum weight among all maximum-cardinality matchings.
|
| 337 |
+
|
| 338 |
+
weight: string, optional (default='weight')
|
| 339 |
+
Edge data key corresponding to the edge weight.
|
| 340 |
+
If key not found, uses 1 as weight.
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
Returns
|
| 344 |
+
-------
|
| 345 |
+
matching : set
|
| 346 |
+
A maximal matching of the graph.
|
| 347 |
+
|
| 348 |
+
Examples
|
| 349 |
+
--------
|
| 350 |
+
>>> G = nx.Graph()
|
| 351 |
+
>>> edges = [(1, 2, 6), (1, 3, 2), (2, 3, 1), (2, 4, 7), (3, 5, 9), (4, 5, 3)]
|
| 352 |
+
>>> G.add_weighted_edges_from(edges)
|
| 353 |
+
>>> sorted(nx.max_weight_matching(G))
|
| 354 |
+
[(2, 4), (5, 3)]
|
| 355 |
+
|
| 356 |
+
Notes
|
| 357 |
+
-----
|
| 358 |
+
If G has edges with weight attributes the edge data are used as
|
| 359 |
+
weight values else the weights are assumed to be 1.
|
| 360 |
+
|
| 361 |
+
This function takes time O(number_of_nodes ** 3).
|
| 362 |
+
|
| 363 |
+
If all edge weights are integers, the algorithm uses only integer
|
| 364 |
+
computations. If floating point weights are used, the algorithm
|
| 365 |
+
could return a slightly suboptimal matching due to numeric
|
| 366 |
+
precision errors.
|
| 367 |
+
|
| 368 |
+
This method is based on the "blossom" method for finding augmenting
|
| 369 |
+
paths and the "primal-dual" method for finding a matching of maximum
|
| 370 |
+
weight, both methods invented by Jack Edmonds [1]_.
|
| 371 |
+
|
| 372 |
+
Bipartite graphs can also be matched using the functions present in
|
| 373 |
+
:mod:`networkx.algorithms.bipartite.matching`.
|
| 374 |
+
|
| 375 |
+
References
|
| 376 |
+
----------
|
| 377 |
+
.. [1] "Efficient Algorithms for Finding Maximum Matching in Graphs",
|
| 378 |
+
Zvi Galil, ACM Computing Surveys, 1986.
|
| 379 |
+
"""
|
| 380 |
+
#
|
| 381 |
+
# The algorithm is taken from "Efficient Algorithms for Finding Maximum
|
| 382 |
+
# Matching in Graphs" by Zvi Galil, ACM Computing Surveys, 1986.
|
| 383 |
+
# It is based on the "blossom" method for finding augmenting paths and
|
| 384 |
+
# the "primal-dual" method for finding a matching of maximum weight, both
|
| 385 |
+
# methods invented by Jack Edmonds.
|
| 386 |
+
#
|
| 387 |
+
# A C program for maximum weight matching by Ed Rothberg was used
|
| 388 |
+
# extensively to validate this new code.
|
| 389 |
+
#
|
| 390 |
+
# Many terms used in the code comments are explained in the paper
|
| 391 |
+
# by Galil. You will probably need the paper to make sense of this code.
|
| 392 |
+
#
|
| 393 |
+
|
| 394 |
+
class NoNode:
|
| 395 |
+
"""Dummy value which is different from any node."""
|
| 396 |
+
|
| 397 |
+
class Blossom:
|
| 398 |
+
"""Representation of a non-trivial blossom or sub-blossom."""
|
| 399 |
+
|
| 400 |
+
__slots__ = ["childs", "edges", "mybestedges"]
|
| 401 |
+
|
| 402 |
+
# b.childs is an ordered list of b's sub-blossoms, starting with
|
| 403 |
+
# the base and going round the blossom.
|
| 404 |
+
|
| 405 |
+
# b.edges is the list of b's connecting edges, such that
|
| 406 |
+
# b.edges[i] = (v, w) where v is a vertex in b.childs[i]
|
| 407 |
+
# and w is a vertex in b.childs[wrap(i+1)].
|
| 408 |
+
|
| 409 |
+
# If b is a top-level S-blossom,
|
| 410 |
+
# b.mybestedges is a list of least-slack edges to neighboring
|
| 411 |
+
# S-blossoms, or None if no such list has been computed yet.
|
| 412 |
+
# This is used for efficient computation of delta3.
|
| 413 |
+
|
| 414 |
+
# Generate the blossom's leaf vertices.
|
| 415 |
+
def leaves(self):
|
| 416 |
+
stack = [*self.childs]
|
| 417 |
+
while stack:
|
| 418 |
+
t = stack.pop()
|
| 419 |
+
if isinstance(t, Blossom):
|
| 420 |
+
stack.extend(t.childs)
|
| 421 |
+
else:
|
| 422 |
+
yield t
|
| 423 |
+
|
| 424 |
+
# Get a list of vertices.
|
| 425 |
+
gnodes = list(G)
|
| 426 |
+
if not gnodes:
|
| 427 |
+
return set() # don't bother with empty graphs
|
| 428 |
+
|
| 429 |
+
# Find the maximum edge weight.
|
| 430 |
+
maxweight = 0
|
| 431 |
+
allinteger = True
|
| 432 |
+
for i, j, d in G.edges(data=True):
|
| 433 |
+
wt = d.get(weight, 1)
|
| 434 |
+
if i != j and wt > maxweight:
|
| 435 |
+
maxweight = wt
|
| 436 |
+
allinteger = allinteger and (str(type(wt)).split("'")[1] in ("int", "long"))
|
| 437 |
+
|
| 438 |
+
# If v is a matched vertex, mate[v] is its partner vertex.
|
| 439 |
+
# If v is a single vertex, v does not occur as a key in mate.
|
| 440 |
+
# Initially all vertices are single; updated during augmentation.
|
| 441 |
+
mate = {}
|
| 442 |
+
|
| 443 |
+
# If b is a top-level blossom,
|
| 444 |
+
# label.get(b) is None if b is unlabeled (free),
|
| 445 |
+
# 1 if b is an S-blossom,
|
| 446 |
+
# 2 if b is a T-blossom.
|
| 447 |
+
# The label of a vertex is found by looking at the label of its top-level
|
| 448 |
+
# containing blossom.
|
| 449 |
+
# If v is a vertex inside a T-blossom, label[v] is 2 iff v is reachable
|
| 450 |
+
# from an S-vertex outside the blossom.
|
| 451 |
+
# Labels are assigned during a stage and reset after each augmentation.
|
| 452 |
+
label = {}
|
| 453 |
+
|
| 454 |
+
# If b is a labeled top-level blossom,
|
| 455 |
+
# labeledge[b] = (v, w) is the edge through which b obtained its label
|
| 456 |
+
# such that w is a vertex in b, or None if b's base vertex is single.
|
| 457 |
+
# If w is a vertex inside a T-blossom and label[w] == 2,
|
| 458 |
+
# labeledge[w] = (v, w) is an edge through which w is reachable from
|
| 459 |
+
# outside the blossom.
|
| 460 |
+
labeledge = {}
|
| 461 |
+
|
| 462 |
+
# If v is a vertex, inblossom[v] is the top-level blossom to which v
|
| 463 |
+
# belongs.
|
| 464 |
+
# If v is a top-level vertex, inblossom[v] == v since v is itself
|
| 465 |
+
# a (trivial) top-level blossom.
|
| 466 |
+
# Initially all vertices are top-level trivial blossoms.
|
| 467 |
+
inblossom = dict(zip(gnodes, gnodes))
|
| 468 |
+
|
| 469 |
+
# If b is a sub-blossom,
|
| 470 |
+
# blossomparent[b] is its immediate parent (sub-)blossom.
|
| 471 |
+
# If b is a top-level blossom, blossomparent[b] is None.
|
| 472 |
+
blossomparent = dict(zip(gnodes, repeat(None)))
|
| 473 |
+
|
| 474 |
+
# If b is a (sub-)blossom,
|
| 475 |
+
# blossombase[b] is its base VERTEX (i.e. recursive sub-blossom).
|
| 476 |
+
blossombase = dict(zip(gnodes, gnodes))
|
| 477 |
+
|
| 478 |
+
# If w is a free vertex (or an unreached vertex inside a T-blossom),
|
| 479 |
+
# bestedge[w] = (v, w) is the least-slack edge from an S-vertex,
|
| 480 |
+
# or None if there is no such edge.
|
| 481 |
+
# If b is a (possibly trivial) top-level S-blossom,
|
| 482 |
+
# bestedge[b] = (v, w) is the least-slack edge to a different S-blossom
|
| 483 |
+
# (v inside b), or None if there is no such edge.
|
| 484 |
+
# This is used for efficient computation of delta2 and delta3.
|
| 485 |
+
bestedge = {}
|
| 486 |
+
|
| 487 |
+
# If v is a vertex,
|
| 488 |
+
# dualvar[v] = 2 * u(v) where u(v) is the v's variable in the dual
|
| 489 |
+
# optimization problem (if all edge weights are integers, multiplication
|
| 490 |
+
# by two ensures that all values remain integers throughout the algorithm).
|
| 491 |
+
# Initially, u(v) = maxweight / 2.
|
| 492 |
+
dualvar = dict(zip(gnodes, repeat(maxweight)))
|
| 493 |
+
|
| 494 |
+
# If b is a non-trivial blossom,
|
| 495 |
+
# blossomdual[b] = z(b) where z(b) is b's variable in the dual
|
| 496 |
+
# optimization problem.
|
| 497 |
+
blossomdual = {}
|
| 498 |
+
|
| 499 |
+
# If (v, w) in allowedge or (w, v) in allowedg, then the edge
|
| 500 |
+
# (v, w) is known to have zero slack in the optimization problem;
|
| 501 |
+
# otherwise the edge may or may not have zero slack.
|
| 502 |
+
allowedge = {}
|
| 503 |
+
|
| 504 |
+
# Queue of newly discovered S-vertices.
|
| 505 |
+
queue = []
|
| 506 |
+
|
| 507 |
+
# Return 2 * slack of edge (v, w) (does not work inside blossoms).
|
| 508 |
+
def slack(v, w):
|
| 509 |
+
return dualvar[v] + dualvar[w] - 2 * G[v][w].get(weight, 1)
|
| 510 |
+
|
| 511 |
+
# Assign label t to the top-level blossom containing vertex w,
|
| 512 |
+
# coming through an edge from vertex v.
|
| 513 |
+
def assignLabel(w, t, v):
|
| 514 |
+
b = inblossom[w]
|
| 515 |
+
assert label.get(w) is None and label.get(b) is None
|
| 516 |
+
label[w] = label[b] = t
|
| 517 |
+
if v is not None:
|
| 518 |
+
labeledge[w] = labeledge[b] = (v, w)
|
| 519 |
+
else:
|
| 520 |
+
labeledge[w] = labeledge[b] = None
|
| 521 |
+
bestedge[w] = bestedge[b] = None
|
| 522 |
+
if t == 1:
|
| 523 |
+
# b became an S-vertex/blossom; add it(s vertices) to the queue.
|
| 524 |
+
if isinstance(b, Blossom):
|
| 525 |
+
queue.extend(b.leaves())
|
| 526 |
+
else:
|
| 527 |
+
queue.append(b)
|
| 528 |
+
elif t == 2:
|
| 529 |
+
# b became a T-vertex/blossom; assign label S to its mate.
|
| 530 |
+
# (If b is a non-trivial blossom, its base is the only vertex
|
| 531 |
+
# with an external mate.)
|
| 532 |
+
base = blossombase[b]
|
| 533 |
+
assignLabel(mate[base], 1, base)
|
| 534 |
+
|
| 535 |
+
# Trace back from vertices v and w to discover either a new blossom
|
| 536 |
+
# or an augmenting path. Return the base vertex of the new blossom,
|
| 537 |
+
# or NoNode if an augmenting path was found.
|
| 538 |
+
def scanBlossom(v, w):
|
| 539 |
+
# Trace back from v and w, placing breadcrumbs as we go.
|
| 540 |
+
path = []
|
| 541 |
+
base = NoNode
|
| 542 |
+
while v is not NoNode:
|
| 543 |
+
# Look for a breadcrumb in v's blossom or put a new breadcrumb.
|
| 544 |
+
b = inblossom[v]
|
| 545 |
+
if label[b] & 4:
|
| 546 |
+
base = blossombase[b]
|
| 547 |
+
break
|
| 548 |
+
assert label[b] == 1
|
| 549 |
+
path.append(b)
|
| 550 |
+
label[b] = 5
|
| 551 |
+
# Trace one step back.
|
| 552 |
+
if labeledge[b] is None:
|
| 553 |
+
# The base of blossom b is single; stop tracing this path.
|
| 554 |
+
assert blossombase[b] not in mate
|
| 555 |
+
v = NoNode
|
| 556 |
+
else:
|
| 557 |
+
assert labeledge[b][0] == mate[blossombase[b]]
|
| 558 |
+
v = labeledge[b][0]
|
| 559 |
+
b = inblossom[v]
|
| 560 |
+
assert label[b] == 2
|
| 561 |
+
# b is a T-blossom; trace one more step back.
|
| 562 |
+
v = labeledge[b][0]
|
| 563 |
+
# Swap v and w so that we alternate between both paths.
|
| 564 |
+
if w is not NoNode:
|
| 565 |
+
v, w = w, v
|
| 566 |
+
# Remove breadcrumbs.
|
| 567 |
+
for b in path:
|
| 568 |
+
label[b] = 1
|
| 569 |
+
# Return base vertex, if we found one.
|
| 570 |
+
return base
|
| 571 |
+
|
| 572 |
+
# Construct a new blossom with given base, through S-vertices v and w.
|
| 573 |
+
# Label the new blossom as S; set its dual variable to zero;
|
| 574 |
+
# relabel its T-vertices to S and add them to the queue.
|
| 575 |
+
def addBlossom(base, v, w):
|
| 576 |
+
bb = inblossom[base]
|
| 577 |
+
bv = inblossom[v]
|
| 578 |
+
bw = inblossom[w]
|
| 579 |
+
# Create blossom.
|
| 580 |
+
b = Blossom()
|
| 581 |
+
blossombase[b] = base
|
| 582 |
+
blossomparent[b] = None
|
| 583 |
+
blossomparent[bb] = b
|
| 584 |
+
# Make list of sub-blossoms and their interconnecting edge endpoints.
|
| 585 |
+
b.childs = path = []
|
| 586 |
+
b.edges = edgs = [(v, w)]
|
| 587 |
+
# Trace back from v to base.
|
| 588 |
+
while bv != bb:
|
| 589 |
+
# Add bv to the new blossom.
|
| 590 |
+
blossomparent[bv] = b
|
| 591 |
+
path.append(bv)
|
| 592 |
+
edgs.append(labeledge[bv])
|
| 593 |
+
assert label[bv] == 2 or (
|
| 594 |
+
label[bv] == 1 and labeledge[bv][0] == mate[blossombase[bv]]
|
| 595 |
+
)
|
| 596 |
+
# Trace one step back.
|
| 597 |
+
v = labeledge[bv][0]
|
| 598 |
+
bv = inblossom[v]
|
| 599 |
+
# Add base sub-blossom; reverse lists.
|
| 600 |
+
path.append(bb)
|
| 601 |
+
path.reverse()
|
| 602 |
+
edgs.reverse()
|
| 603 |
+
# Trace back from w to base.
|
| 604 |
+
while bw != bb:
|
| 605 |
+
# Add bw to the new blossom.
|
| 606 |
+
blossomparent[bw] = b
|
| 607 |
+
path.append(bw)
|
| 608 |
+
edgs.append((labeledge[bw][1], labeledge[bw][0]))
|
| 609 |
+
assert label[bw] == 2 or (
|
| 610 |
+
label[bw] == 1 and labeledge[bw][0] == mate[blossombase[bw]]
|
| 611 |
+
)
|
| 612 |
+
# Trace one step back.
|
| 613 |
+
w = labeledge[bw][0]
|
| 614 |
+
bw = inblossom[w]
|
| 615 |
+
# Set label to S.
|
| 616 |
+
assert label[bb] == 1
|
| 617 |
+
label[b] = 1
|
| 618 |
+
labeledge[b] = labeledge[bb]
|
| 619 |
+
# Set dual variable to zero.
|
| 620 |
+
blossomdual[b] = 0
|
| 621 |
+
# Relabel vertices.
|
| 622 |
+
for v in b.leaves():
|
| 623 |
+
if label[inblossom[v]] == 2:
|
| 624 |
+
# This T-vertex now turns into an S-vertex because it becomes
|
| 625 |
+
# part of an S-blossom; add it to the queue.
|
| 626 |
+
queue.append(v)
|
| 627 |
+
inblossom[v] = b
|
| 628 |
+
# Compute b.mybestedges.
|
| 629 |
+
bestedgeto = {}
|
| 630 |
+
for bv in path:
|
| 631 |
+
if isinstance(bv, Blossom):
|
| 632 |
+
if bv.mybestedges is not None:
|
| 633 |
+
# Walk this subblossom's least-slack edges.
|
| 634 |
+
nblist = bv.mybestedges
|
| 635 |
+
# The sub-blossom won't need this data again.
|
| 636 |
+
bv.mybestedges = None
|
| 637 |
+
else:
|
| 638 |
+
# This subblossom does not have a list of least-slack
|
| 639 |
+
# edges; get the information from the vertices.
|
| 640 |
+
nblist = [
|
| 641 |
+
(v, w) for v in bv.leaves() for w in G.neighbors(v) if v != w
|
| 642 |
+
]
|
| 643 |
+
else:
|
| 644 |
+
nblist = [(bv, w) for w in G.neighbors(bv) if bv != w]
|
| 645 |
+
for k in nblist:
|
| 646 |
+
(i, j) = k
|
| 647 |
+
if inblossom[j] == b:
|
| 648 |
+
i, j = j, i
|
| 649 |
+
bj = inblossom[j]
|
| 650 |
+
if (
|
| 651 |
+
bj != b
|
| 652 |
+
and label.get(bj) == 1
|
| 653 |
+
and ((bj not in bestedgeto) or slack(i, j) < slack(*bestedgeto[bj]))
|
| 654 |
+
):
|
| 655 |
+
bestedgeto[bj] = k
|
| 656 |
+
# Forget about least-slack edge of the subblossom.
|
| 657 |
+
bestedge[bv] = None
|
| 658 |
+
b.mybestedges = list(bestedgeto.values())
|
| 659 |
+
# Select bestedge[b].
|
| 660 |
+
mybestedge = None
|
| 661 |
+
bestedge[b] = None
|
| 662 |
+
for k in b.mybestedges:
|
| 663 |
+
kslack = slack(*k)
|
| 664 |
+
if mybestedge is None or kslack < mybestslack:
|
| 665 |
+
mybestedge = k
|
| 666 |
+
mybestslack = kslack
|
| 667 |
+
bestedge[b] = mybestedge
|
| 668 |
+
|
| 669 |
+
# Expand the given top-level blossom.
|
| 670 |
+
def expandBlossom(b, endstage):
|
| 671 |
+
# This is an obnoxiously complicated recursive function for the sake of
|
| 672 |
+
# a stack-transformation. So, we hack around the complexity by using
|
| 673 |
+
# a trampoline pattern. By yielding the arguments to each recursive
|
| 674 |
+
# call, we keep the actual callstack flat.
|
| 675 |
+
|
| 676 |
+
def _recurse(b, endstage):
|
| 677 |
+
# Convert sub-blossoms into top-level blossoms.
|
| 678 |
+
for s in b.childs:
|
| 679 |
+
blossomparent[s] = None
|
| 680 |
+
if isinstance(s, Blossom):
|
| 681 |
+
if endstage and blossomdual[s] == 0:
|
| 682 |
+
# Recursively expand this sub-blossom.
|
| 683 |
+
yield s
|
| 684 |
+
else:
|
| 685 |
+
for v in s.leaves():
|
| 686 |
+
inblossom[v] = s
|
| 687 |
+
else:
|
| 688 |
+
inblossom[s] = s
|
| 689 |
+
# If we expand a T-blossom during a stage, its sub-blossoms must be
|
| 690 |
+
# relabeled.
|
| 691 |
+
if (not endstage) and label.get(b) == 2:
|
| 692 |
+
# Start at the sub-blossom through which the expanding
|
| 693 |
+
# blossom obtained its label, and relabel sub-blossoms untili
|
| 694 |
+
# we reach the base.
|
| 695 |
+
# Figure out through which sub-blossom the expanding blossom
|
| 696 |
+
# obtained its label initially.
|
| 697 |
+
entrychild = inblossom[labeledge[b][1]]
|
| 698 |
+
# Decide in which direction we will go round the blossom.
|
| 699 |
+
j = b.childs.index(entrychild)
|
| 700 |
+
if j & 1:
|
| 701 |
+
# Start index is odd; go forward and wrap.
|
| 702 |
+
j -= len(b.childs)
|
| 703 |
+
jstep = 1
|
| 704 |
+
else:
|
| 705 |
+
# Start index is even; go backward.
|
| 706 |
+
jstep = -1
|
| 707 |
+
# Move along the blossom until we get to the base.
|
| 708 |
+
v, w = labeledge[b]
|
| 709 |
+
while j != 0:
|
| 710 |
+
# Relabel the T-sub-blossom.
|
| 711 |
+
if jstep == 1:
|
| 712 |
+
p, q = b.edges[j]
|
| 713 |
+
else:
|
| 714 |
+
q, p = b.edges[j - 1]
|
| 715 |
+
label[w] = None
|
| 716 |
+
label[q] = None
|
| 717 |
+
assignLabel(w, 2, v)
|
| 718 |
+
# Step to the next S-sub-blossom and note its forward edge.
|
| 719 |
+
allowedge[(p, q)] = allowedge[(q, p)] = True
|
| 720 |
+
j += jstep
|
| 721 |
+
if jstep == 1:
|
| 722 |
+
v, w = b.edges[j]
|
| 723 |
+
else:
|
| 724 |
+
w, v = b.edges[j - 1]
|
| 725 |
+
# Step to the next T-sub-blossom.
|
| 726 |
+
allowedge[(v, w)] = allowedge[(w, v)] = True
|
| 727 |
+
j += jstep
|
| 728 |
+
# Relabel the base T-sub-blossom WITHOUT stepping through to
|
| 729 |
+
# its mate (so don't call assignLabel).
|
| 730 |
+
bw = b.childs[j]
|
| 731 |
+
label[w] = label[bw] = 2
|
| 732 |
+
labeledge[w] = labeledge[bw] = (v, w)
|
| 733 |
+
bestedge[bw] = None
|
| 734 |
+
# Continue along the blossom until we get back to entrychild.
|
| 735 |
+
j += jstep
|
| 736 |
+
while b.childs[j] != entrychild:
|
| 737 |
+
# Examine the vertices of the sub-blossom to see whether
|
| 738 |
+
# it is reachable from a neighboring S-vertex outside the
|
| 739 |
+
# expanding blossom.
|
| 740 |
+
bv = b.childs[j]
|
| 741 |
+
if label.get(bv) == 1:
|
| 742 |
+
# This sub-blossom just got label S through one of its
|
| 743 |
+
# neighbors; leave it be.
|
| 744 |
+
j += jstep
|
| 745 |
+
continue
|
| 746 |
+
if isinstance(bv, Blossom):
|
| 747 |
+
for v in bv.leaves():
|
| 748 |
+
if label.get(v):
|
| 749 |
+
break
|
| 750 |
+
else:
|
| 751 |
+
v = bv
|
| 752 |
+
# If the sub-blossom contains a reachable vertex, assign
|
| 753 |
+
# label T to the sub-blossom.
|
| 754 |
+
if label.get(v):
|
| 755 |
+
assert label[v] == 2
|
| 756 |
+
assert inblossom[v] == bv
|
| 757 |
+
label[v] = None
|
| 758 |
+
label[mate[blossombase[bv]]] = None
|
| 759 |
+
assignLabel(v, 2, labeledge[v][0])
|
| 760 |
+
j += jstep
|
| 761 |
+
# Remove the expanded blossom entirely.
|
| 762 |
+
label.pop(b, None)
|
| 763 |
+
labeledge.pop(b, None)
|
| 764 |
+
bestedge.pop(b, None)
|
| 765 |
+
del blossomparent[b]
|
| 766 |
+
del blossombase[b]
|
| 767 |
+
del blossomdual[b]
|
| 768 |
+
|
| 769 |
+
# Now, we apply the trampoline pattern. We simulate a recursive
|
| 770 |
+
# callstack by maintaining a stack of generators, each yielding a
|
| 771 |
+
# sequence of function arguments. We grow the stack by appending a call
|
| 772 |
+
# to _recurse on each argument tuple, and shrink the stack whenever a
|
| 773 |
+
# generator is exhausted.
|
| 774 |
+
stack = [_recurse(b, endstage)]
|
| 775 |
+
while stack:
|
| 776 |
+
top = stack[-1]
|
| 777 |
+
for s in top:
|
| 778 |
+
stack.append(_recurse(s, endstage))
|
| 779 |
+
break
|
| 780 |
+
else:
|
| 781 |
+
stack.pop()
|
| 782 |
+
|
| 783 |
+
# Swap matched/unmatched edges over an alternating path through blossom b
|
| 784 |
+
# between vertex v and the base vertex. Keep blossom bookkeeping
|
| 785 |
+
# consistent.
|
| 786 |
+
def augmentBlossom(b, v):
|
| 787 |
+
# This is an obnoxiously complicated recursive function for the sake of
|
| 788 |
+
# a stack-transformation. So, we hack around the complexity by using
|
| 789 |
+
# a trampoline pattern. By yielding the arguments to each recursive
|
| 790 |
+
# call, we keep the actual callstack flat.
|
| 791 |
+
|
| 792 |
+
def _recurse(b, v):
|
| 793 |
+
# Bubble up through the blossom tree from vertex v to an immediate
|
| 794 |
+
# sub-blossom of b.
|
| 795 |
+
t = v
|
| 796 |
+
while blossomparent[t] != b:
|
| 797 |
+
t = blossomparent[t]
|
| 798 |
+
# Recursively deal with the first sub-blossom.
|
| 799 |
+
if isinstance(t, Blossom):
|
| 800 |
+
yield (t, v)
|
| 801 |
+
# Decide in which direction we will go round the blossom.
|
| 802 |
+
i = j = b.childs.index(t)
|
| 803 |
+
if i & 1:
|
| 804 |
+
# Start index is odd; go forward and wrap.
|
| 805 |
+
j -= len(b.childs)
|
| 806 |
+
jstep = 1
|
| 807 |
+
else:
|
| 808 |
+
# Start index is even; go backward.
|
| 809 |
+
jstep = -1
|
| 810 |
+
# Move along the blossom until we get to the base.
|
| 811 |
+
while j != 0:
|
| 812 |
+
# Step to the next sub-blossom and augment it recursively.
|
| 813 |
+
j += jstep
|
| 814 |
+
t = b.childs[j]
|
| 815 |
+
if jstep == 1:
|
| 816 |
+
w, x = b.edges[j]
|
| 817 |
+
else:
|
| 818 |
+
x, w = b.edges[j - 1]
|
| 819 |
+
if isinstance(t, Blossom):
|
| 820 |
+
yield (t, w)
|
| 821 |
+
# Step to the next sub-blossom and augment it recursively.
|
| 822 |
+
j += jstep
|
| 823 |
+
t = b.childs[j]
|
| 824 |
+
if isinstance(t, Blossom):
|
| 825 |
+
yield (t, x)
|
| 826 |
+
# Match the edge connecting those sub-blossoms.
|
| 827 |
+
mate[w] = x
|
| 828 |
+
mate[x] = w
|
| 829 |
+
# Rotate the list of sub-blossoms to put the new base at the front.
|
| 830 |
+
b.childs = b.childs[i:] + b.childs[:i]
|
| 831 |
+
b.edges = b.edges[i:] + b.edges[:i]
|
| 832 |
+
blossombase[b] = blossombase[b.childs[0]]
|
| 833 |
+
assert blossombase[b] == v
|
| 834 |
+
|
| 835 |
+
# Now, we apply the trampoline pattern. We simulate a recursive
|
| 836 |
+
# callstack by maintaining a stack of generators, each yielding a
|
| 837 |
+
# sequence of function arguments. We grow the stack by appending a call
|
| 838 |
+
# to _recurse on each argument tuple, and shrink the stack whenever a
|
| 839 |
+
# generator is exhausted.
|
| 840 |
+
stack = [_recurse(b, v)]
|
| 841 |
+
while stack:
|
| 842 |
+
top = stack[-1]
|
| 843 |
+
for args in top:
|
| 844 |
+
stack.append(_recurse(*args))
|
| 845 |
+
break
|
| 846 |
+
else:
|
| 847 |
+
stack.pop()
|
| 848 |
+
|
| 849 |
+
# Swap matched/unmatched edges over an alternating path between two
|
| 850 |
+
# single vertices. The augmenting path runs through S-vertices v and w.
|
| 851 |
+
def augmentMatching(v, w):
|
| 852 |
+
for s, j in ((v, w), (w, v)):
|
| 853 |
+
# Match vertex s to vertex j. Then trace back from s
|
| 854 |
+
# until we find a single vertex, swapping matched and unmatched
|
| 855 |
+
# edges as we go.
|
| 856 |
+
while 1:
|
| 857 |
+
bs = inblossom[s]
|
| 858 |
+
assert label[bs] == 1
|
| 859 |
+
assert (labeledge[bs] is None and blossombase[bs] not in mate) or (
|
| 860 |
+
labeledge[bs][0] == mate[blossombase[bs]]
|
| 861 |
+
)
|
| 862 |
+
# Augment through the S-blossom from s to base.
|
| 863 |
+
if isinstance(bs, Blossom):
|
| 864 |
+
augmentBlossom(bs, s)
|
| 865 |
+
# Update mate[s]
|
| 866 |
+
mate[s] = j
|
| 867 |
+
# Trace one step back.
|
| 868 |
+
if labeledge[bs] is None:
|
| 869 |
+
# Reached single vertex; stop.
|
| 870 |
+
break
|
| 871 |
+
t = labeledge[bs][0]
|
| 872 |
+
bt = inblossom[t]
|
| 873 |
+
assert label[bt] == 2
|
| 874 |
+
# Trace one more step back.
|
| 875 |
+
s, j = labeledge[bt]
|
| 876 |
+
# Augment through the T-blossom from j to base.
|
| 877 |
+
assert blossombase[bt] == t
|
| 878 |
+
if isinstance(bt, Blossom):
|
| 879 |
+
augmentBlossom(bt, j)
|
| 880 |
+
# Update mate[j]
|
| 881 |
+
mate[j] = s
|
| 882 |
+
|
| 883 |
+
# Verify that the optimum solution has been reached.
|
| 884 |
+
def verifyOptimum():
|
| 885 |
+
if maxcardinality:
|
| 886 |
+
# Vertices may have negative dual;
|
| 887 |
+
# find a constant non-negative number to add to all vertex duals.
|
| 888 |
+
vdualoffset = max(0, -min(dualvar.values()))
|
| 889 |
+
else:
|
| 890 |
+
vdualoffset = 0
|
| 891 |
+
# 0. all dual variables are non-negative
|
| 892 |
+
assert min(dualvar.values()) + vdualoffset >= 0
|
| 893 |
+
assert len(blossomdual) == 0 or min(blossomdual.values()) >= 0
|
| 894 |
+
# 0. all edges have non-negative slack and
|
| 895 |
+
# 1. all matched edges have zero slack;
|
| 896 |
+
for i, j, d in G.edges(data=True):
|
| 897 |
+
wt = d.get(weight, 1)
|
| 898 |
+
if i == j:
|
| 899 |
+
continue # ignore self-loops
|
| 900 |
+
s = dualvar[i] + dualvar[j] - 2 * wt
|
| 901 |
+
iblossoms = [i]
|
| 902 |
+
jblossoms = [j]
|
| 903 |
+
while blossomparent[iblossoms[-1]] is not None:
|
| 904 |
+
iblossoms.append(blossomparent[iblossoms[-1]])
|
| 905 |
+
while blossomparent[jblossoms[-1]] is not None:
|
| 906 |
+
jblossoms.append(blossomparent[jblossoms[-1]])
|
| 907 |
+
iblossoms.reverse()
|
| 908 |
+
jblossoms.reverse()
|
| 909 |
+
for bi, bj in zip(iblossoms, jblossoms):
|
| 910 |
+
if bi != bj:
|
| 911 |
+
break
|
| 912 |
+
s += 2 * blossomdual[bi]
|
| 913 |
+
assert s >= 0
|
| 914 |
+
if mate.get(i) == j or mate.get(j) == i:
|
| 915 |
+
assert mate[i] == j and mate[j] == i
|
| 916 |
+
assert s == 0
|
| 917 |
+
# 2. all single vertices have zero dual value;
|
| 918 |
+
for v in gnodes:
|
| 919 |
+
assert (v in mate) or dualvar[v] + vdualoffset == 0
|
| 920 |
+
# 3. all blossoms with positive dual value are full.
|
| 921 |
+
for b in blossomdual:
|
| 922 |
+
if blossomdual[b] > 0:
|
| 923 |
+
assert len(b.edges) % 2 == 1
|
| 924 |
+
for i, j in b.edges[1::2]:
|
| 925 |
+
assert mate[i] == j and mate[j] == i
|
| 926 |
+
# Ok.
|
| 927 |
+
|
| 928 |
+
# Main loop: continue until no further improvement is possible.
|
| 929 |
+
while 1:
|
| 930 |
+
# Each iteration of this loop is a "stage".
|
| 931 |
+
# A stage finds an augmenting path and uses that to improve
|
| 932 |
+
# the matching.
|
| 933 |
+
|
| 934 |
+
# Remove labels from top-level blossoms/vertices.
|
| 935 |
+
label.clear()
|
| 936 |
+
labeledge.clear()
|
| 937 |
+
|
| 938 |
+
# Forget all about least-slack edges.
|
| 939 |
+
bestedge.clear()
|
| 940 |
+
for b in blossomdual:
|
| 941 |
+
b.mybestedges = None
|
| 942 |
+
|
| 943 |
+
# Loss of labeling means that we can not be sure that currently
|
| 944 |
+
# allowable edges remain allowable throughout this stage.
|
| 945 |
+
allowedge.clear()
|
| 946 |
+
|
| 947 |
+
# Make queue empty.
|
| 948 |
+
queue[:] = []
|
| 949 |
+
|
| 950 |
+
# Label single blossoms/vertices with S and put them in the queue.
|
| 951 |
+
for v in gnodes:
|
| 952 |
+
if (v not in mate) and label.get(inblossom[v]) is None:
|
| 953 |
+
assignLabel(v, 1, None)
|
| 954 |
+
|
| 955 |
+
# Loop until we succeed in augmenting the matching.
|
| 956 |
+
augmented = 0
|
| 957 |
+
while 1:
|
| 958 |
+
# Each iteration of this loop is a "substage".
|
| 959 |
+
# A substage tries to find an augmenting path;
|
| 960 |
+
# if found, the path is used to improve the matching and
|
| 961 |
+
# the stage ends. If there is no augmenting path, the
|
| 962 |
+
# primal-dual method is used to pump some slack out of
|
| 963 |
+
# the dual variables.
|
| 964 |
+
|
| 965 |
+
# Continue labeling until all vertices which are reachable
|
| 966 |
+
# through an alternating path have got a label.
|
| 967 |
+
while queue and not augmented:
|
| 968 |
+
# Take an S vertex from the queue.
|
| 969 |
+
v = queue.pop()
|
| 970 |
+
assert label[inblossom[v]] == 1
|
| 971 |
+
|
| 972 |
+
# Scan its neighbors:
|
| 973 |
+
for w in G.neighbors(v):
|
| 974 |
+
if w == v:
|
| 975 |
+
continue # ignore self-loops
|
| 976 |
+
# w is a neighbor to v
|
| 977 |
+
bv = inblossom[v]
|
| 978 |
+
bw = inblossom[w]
|
| 979 |
+
if bv == bw:
|
| 980 |
+
# this edge is internal to a blossom; ignore it
|
| 981 |
+
continue
|
| 982 |
+
if (v, w) not in allowedge:
|
| 983 |
+
kslack = slack(v, w)
|
| 984 |
+
if kslack <= 0:
|
| 985 |
+
# edge k has zero slack => it is allowable
|
| 986 |
+
allowedge[(v, w)] = allowedge[(w, v)] = True
|
| 987 |
+
if (v, w) in allowedge:
|
| 988 |
+
if label.get(bw) is None:
|
| 989 |
+
# (C1) w is a free vertex;
|
| 990 |
+
# label w with T and label its mate with S (R12).
|
| 991 |
+
assignLabel(w, 2, v)
|
| 992 |
+
elif label.get(bw) == 1:
|
| 993 |
+
# (C2) w is an S-vertex (not in the same blossom);
|
| 994 |
+
# follow back-links to discover either an
|
| 995 |
+
# augmenting path or a new blossom.
|
| 996 |
+
base = scanBlossom(v, w)
|
| 997 |
+
if base is not NoNode:
|
| 998 |
+
# Found a new blossom; add it to the blossom
|
| 999 |
+
# bookkeeping and turn it into an S-blossom.
|
| 1000 |
+
addBlossom(base, v, w)
|
| 1001 |
+
else:
|
| 1002 |
+
# Found an augmenting path; augment the
|
| 1003 |
+
# matching and end this stage.
|
| 1004 |
+
augmentMatching(v, w)
|
| 1005 |
+
augmented = 1
|
| 1006 |
+
break
|
| 1007 |
+
elif label.get(w) is None:
|
| 1008 |
+
# w is inside a T-blossom, but w itself has not
|
| 1009 |
+
# yet been reached from outside the blossom;
|
| 1010 |
+
# mark it as reached (we need this to relabel
|
| 1011 |
+
# during T-blossom expansion).
|
| 1012 |
+
assert label[bw] == 2
|
| 1013 |
+
label[w] = 2
|
| 1014 |
+
labeledge[w] = (v, w)
|
| 1015 |
+
elif label.get(bw) == 1:
|
| 1016 |
+
# keep track of the least-slack non-allowable edge to
|
| 1017 |
+
# a different S-blossom.
|
| 1018 |
+
if bestedge.get(bv) is None or kslack < slack(*bestedge[bv]):
|
| 1019 |
+
bestedge[bv] = (v, w)
|
| 1020 |
+
elif label.get(w) is None:
|
| 1021 |
+
# w is a free vertex (or an unreached vertex inside
|
| 1022 |
+
# a T-blossom) but we can not reach it yet;
|
| 1023 |
+
# keep track of the least-slack edge that reaches w.
|
| 1024 |
+
if bestedge.get(w) is None or kslack < slack(*bestedge[w]):
|
| 1025 |
+
bestedge[w] = (v, w)
|
| 1026 |
+
|
| 1027 |
+
if augmented:
|
| 1028 |
+
break
|
| 1029 |
+
|
| 1030 |
+
# There is no augmenting path under these constraints;
|
| 1031 |
+
# compute delta and reduce slack in the optimization problem.
|
| 1032 |
+
# (Note that our vertex dual variables, edge slacks and delta's
|
| 1033 |
+
# are pre-multiplied by two.)
|
| 1034 |
+
deltatype = -1
|
| 1035 |
+
delta = deltaedge = deltablossom = None
|
| 1036 |
+
|
| 1037 |
+
# Compute delta1: the minimum value of any vertex dual.
|
| 1038 |
+
if not maxcardinality:
|
| 1039 |
+
deltatype = 1
|
| 1040 |
+
delta = min(dualvar.values())
|
| 1041 |
+
|
| 1042 |
+
# Compute delta2: the minimum slack on any edge between
|
| 1043 |
+
# an S-vertex and a free vertex.
|
| 1044 |
+
for v in G.nodes():
|
| 1045 |
+
if label.get(inblossom[v]) is None and bestedge.get(v) is not None:
|
| 1046 |
+
d = slack(*bestedge[v])
|
| 1047 |
+
if deltatype == -1 or d < delta:
|
| 1048 |
+
delta = d
|
| 1049 |
+
deltatype = 2
|
| 1050 |
+
deltaedge = bestedge[v]
|
| 1051 |
+
|
| 1052 |
+
# Compute delta3: half the minimum slack on any edge between
|
| 1053 |
+
# a pair of S-blossoms.
|
| 1054 |
+
for b in blossomparent:
|
| 1055 |
+
if (
|
| 1056 |
+
blossomparent[b] is None
|
| 1057 |
+
and label.get(b) == 1
|
| 1058 |
+
and bestedge.get(b) is not None
|
| 1059 |
+
):
|
| 1060 |
+
kslack = slack(*bestedge[b])
|
| 1061 |
+
if allinteger:
|
| 1062 |
+
assert (kslack % 2) == 0
|
| 1063 |
+
d = kslack // 2
|
| 1064 |
+
else:
|
| 1065 |
+
d = kslack / 2.0
|
| 1066 |
+
if deltatype == -1 or d < delta:
|
| 1067 |
+
delta = d
|
| 1068 |
+
deltatype = 3
|
| 1069 |
+
deltaedge = bestedge[b]
|
| 1070 |
+
|
| 1071 |
+
# Compute delta4: minimum z variable of any T-blossom.
|
| 1072 |
+
for b in blossomdual:
|
| 1073 |
+
if (
|
| 1074 |
+
blossomparent[b] is None
|
| 1075 |
+
and label.get(b) == 2
|
| 1076 |
+
and (deltatype == -1 or blossomdual[b] < delta)
|
| 1077 |
+
):
|
| 1078 |
+
delta = blossomdual[b]
|
| 1079 |
+
deltatype = 4
|
| 1080 |
+
deltablossom = b
|
| 1081 |
+
|
| 1082 |
+
if deltatype == -1:
|
| 1083 |
+
# No further improvement possible; max-cardinality optimum
|
| 1084 |
+
# reached. Do a final delta update to make the optimum
|
| 1085 |
+
# verifiable.
|
| 1086 |
+
assert maxcardinality
|
| 1087 |
+
deltatype = 1
|
| 1088 |
+
delta = max(0, min(dualvar.values()))
|
| 1089 |
+
|
| 1090 |
+
# Update dual variables according to delta.
|
| 1091 |
+
for v in gnodes:
|
| 1092 |
+
if label.get(inblossom[v]) == 1:
|
| 1093 |
+
# S-vertex: 2*u = 2*u - 2*delta
|
| 1094 |
+
dualvar[v] -= delta
|
| 1095 |
+
elif label.get(inblossom[v]) == 2:
|
| 1096 |
+
# T-vertex: 2*u = 2*u + 2*delta
|
| 1097 |
+
dualvar[v] += delta
|
| 1098 |
+
for b in blossomdual:
|
| 1099 |
+
if blossomparent[b] is None:
|
| 1100 |
+
if label.get(b) == 1:
|
| 1101 |
+
# top-level S-blossom: z = z + 2*delta
|
| 1102 |
+
blossomdual[b] += delta
|
| 1103 |
+
elif label.get(b) == 2:
|
| 1104 |
+
# top-level T-blossom: z = z - 2*delta
|
| 1105 |
+
blossomdual[b] -= delta
|
| 1106 |
+
|
| 1107 |
+
# Take action at the point where minimum delta occurred.
|
| 1108 |
+
if deltatype == 1:
|
| 1109 |
+
# No further improvement possible; optimum reached.
|
| 1110 |
+
break
|
| 1111 |
+
elif deltatype == 2:
|
| 1112 |
+
# Use the least-slack edge to continue the search.
|
| 1113 |
+
(v, w) = deltaedge
|
| 1114 |
+
assert label[inblossom[v]] == 1
|
| 1115 |
+
allowedge[(v, w)] = allowedge[(w, v)] = True
|
| 1116 |
+
queue.append(v)
|
| 1117 |
+
elif deltatype == 3:
|
| 1118 |
+
# Use the least-slack edge to continue the search.
|
| 1119 |
+
(v, w) = deltaedge
|
| 1120 |
+
allowedge[(v, w)] = allowedge[(w, v)] = True
|
| 1121 |
+
assert label[inblossom[v]] == 1
|
| 1122 |
+
queue.append(v)
|
| 1123 |
+
elif deltatype == 4:
|
| 1124 |
+
# Expand the least-z blossom.
|
| 1125 |
+
expandBlossom(deltablossom, False)
|
| 1126 |
+
|
| 1127 |
+
# End of a this substage.
|
| 1128 |
+
|
| 1129 |
+
# Paranoia check that the matching is symmetric.
|
| 1130 |
+
for v in mate:
|
| 1131 |
+
assert mate[mate[v]] == v
|
| 1132 |
+
|
| 1133 |
+
# Stop when no more augmenting path can be found.
|
| 1134 |
+
if not augmented:
|
| 1135 |
+
break
|
| 1136 |
+
|
| 1137 |
+
# End of a stage; expand all S-blossoms which have zero dual.
|
| 1138 |
+
for b in list(blossomdual.keys()):
|
| 1139 |
+
if b not in blossomdual:
|
| 1140 |
+
continue # already expanded
|
| 1141 |
+
if blossomparent[b] is None and label.get(b) == 1 and blossomdual[b] == 0:
|
| 1142 |
+
expandBlossom(b, True)
|
| 1143 |
+
|
| 1144 |
+
# Verify that we reached the optimum solution (only for integer weights).
|
| 1145 |
+
if allinteger:
|
| 1146 |
+
verifyOptimum()
|
| 1147 |
+
|
| 1148 |
+
return matching_dict_to_set(mate)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/mis.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Algorithm to find a maximal (not maximum) independent set.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import networkx as nx
|
| 7 |
+
from networkx.utils import not_implemented_for, py_random_state
|
| 8 |
+
|
| 9 |
+
__all__ = ["maximal_independent_set"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@not_implemented_for("directed")
|
| 13 |
+
@py_random_state(2)
|
| 14 |
+
@nx._dispatchable
|
| 15 |
+
def maximal_independent_set(G, nodes=None, seed=None):
|
| 16 |
+
"""Returns a random maximal independent set guaranteed to contain
|
| 17 |
+
a given set of nodes.
|
| 18 |
+
|
| 19 |
+
An independent set is a set of nodes such that the subgraph
|
| 20 |
+
of G induced by these nodes contains no edges. A maximal
|
| 21 |
+
independent set is an independent set such that it is not possible
|
| 22 |
+
to add a new node and still get an independent set.
|
| 23 |
+
|
| 24 |
+
Parameters
|
| 25 |
+
----------
|
| 26 |
+
G : NetworkX graph
|
| 27 |
+
|
| 28 |
+
nodes : list or iterable
|
| 29 |
+
Nodes that must be part of the independent set. This set of nodes
|
| 30 |
+
must be independent.
|
| 31 |
+
|
| 32 |
+
seed : integer, random_state, or None (default)
|
| 33 |
+
Indicator of random number generation state.
|
| 34 |
+
See :ref:`Randomness<randomness>`.
|
| 35 |
+
|
| 36 |
+
Returns
|
| 37 |
+
-------
|
| 38 |
+
indep_nodes : list
|
| 39 |
+
List of nodes that are part of a maximal independent set.
|
| 40 |
+
|
| 41 |
+
Raises
|
| 42 |
+
------
|
| 43 |
+
NetworkXUnfeasible
|
| 44 |
+
If the nodes in the provided list are not part of the graph or
|
| 45 |
+
do not form an independent set, an exception is raised.
|
| 46 |
+
|
| 47 |
+
NetworkXNotImplemented
|
| 48 |
+
If `G` is directed.
|
| 49 |
+
|
| 50 |
+
Examples
|
| 51 |
+
--------
|
| 52 |
+
>>> G = nx.path_graph(5)
|
| 53 |
+
>>> nx.maximal_independent_set(G) # doctest: +SKIP
|
| 54 |
+
[4, 0, 2]
|
| 55 |
+
>>> nx.maximal_independent_set(G, [1]) # doctest: +SKIP
|
| 56 |
+
[1, 3]
|
| 57 |
+
|
| 58 |
+
Notes
|
| 59 |
+
-----
|
| 60 |
+
This algorithm does not solve the maximum independent set problem.
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
if not nodes:
|
| 64 |
+
nodes = {seed.choice(list(G))}
|
| 65 |
+
else:
|
| 66 |
+
nodes = set(nodes)
|
| 67 |
+
if not nodes.issubset(G):
|
| 68 |
+
raise nx.NetworkXUnfeasible(f"{nodes} is not a subset of the nodes of G")
|
| 69 |
+
neighbors = set.union(*[set(G.adj[v]) for v in nodes])
|
| 70 |
+
if set.intersection(neighbors, nodes):
|
| 71 |
+
raise nx.NetworkXUnfeasible(f"{nodes} is not an independent set of G")
|
| 72 |
+
indep_nodes = list(nodes)
|
| 73 |
+
available_nodes = set(G.nodes()).difference(neighbors.union(nodes))
|
| 74 |
+
while available_nodes:
|
| 75 |
+
node = seed.choice(list(available_nodes))
|
| 76 |
+
indep_nodes.append(node)
|
| 77 |
+
available_nodes.difference_update(list(G.adj[node]) + [node])
|
| 78 |
+
return indep_nodes
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/moral.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""Function for computing the moral graph of a directed graph."""
|
| 2 |
+
|
| 3 |
+
import itertools
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = ["moral_graph"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@not_implemented_for("undirected")
|
| 12 |
+
@nx._dispatchable(returns_graph=True)
|
| 13 |
+
def moral_graph(G):
|
| 14 |
+
r"""Return the Moral Graph
|
| 15 |
+
|
| 16 |
+
Returns the moralized graph of a given directed graph.
|
| 17 |
+
|
| 18 |
+
Parameters
|
| 19 |
+
----------
|
| 20 |
+
G : NetworkX graph
|
| 21 |
+
Directed graph
|
| 22 |
+
|
| 23 |
+
Returns
|
| 24 |
+
-------
|
| 25 |
+
H : NetworkX graph
|
| 26 |
+
The undirected moralized graph of G
|
| 27 |
+
|
| 28 |
+
Raises
|
| 29 |
+
------
|
| 30 |
+
NetworkXNotImplemented
|
| 31 |
+
If `G` is undirected.
|
| 32 |
+
|
| 33 |
+
Examples
|
| 34 |
+
--------
|
| 35 |
+
>>> G = nx.DiGraph([(1, 2), (2, 3), (2, 5), (3, 4), (4, 3)])
|
| 36 |
+
>>> G_moral = nx.moral_graph(G)
|
| 37 |
+
>>> G_moral.edges()
|
| 38 |
+
EdgeView([(1, 2), (2, 3), (2, 5), (2, 4), (3, 4)])
|
| 39 |
+
|
| 40 |
+
Notes
|
| 41 |
+
-----
|
| 42 |
+
A moral graph is an undirected graph H = (V, E) generated from a
|
| 43 |
+
directed Graph, where if a node has more than one parent node, edges
|
| 44 |
+
between these parent nodes are inserted and all directed edges become
|
| 45 |
+
undirected.
|
| 46 |
+
|
| 47 |
+
https://en.wikipedia.org/wiki/Moral_graph
|
| 48 |
+
|
| 49 |
+
References
|
| 50 |
+
----------
|
| 51 |
+
.. [1] Wray L. Buntine. 1995. Chain graphs for learning.
|
| 52 |
+
In Proceedings of the Eleventh conference on Uncertainty
|
| 53 |
+
in artificial intelligence (UAI'95)
|
| 54 |
+
"""
|
| 55 |
+
H = G.to_undirected()
|
| 56 |
+
for preds in G.pred.values():
|
| 57 |
+
predecessors_combinations = itertools.combinations(preds, r=2)
|
| 58 |
+
H.add_edges_from(predecessors_combinations)
|
| 59 |
+
return H
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/node_classification.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This module provides the functions for node classification problem.
|
| 2 |
+
|
| 3 |
+
The functions in this module are not imported
|
| 4 |
+
into the top level `networkx` namespace.
|
| 5 |
+
You can access these functions by importing
|
| 6 |
+
the `networkx.algorithms.node_classification` modules,
|
| 7 |
+
then accessing the functions as attributes of `node_classification`.
|
| 8 |
+
For example:
|
| 9 |
+
|
| 10 |
+
>>> from networkx.algorithms import node_classification
|
| 11 |
+
>>> G = nx.path_graph(4)
|
| 12 |
+
>>> G.edges()
|
| 13 |
+
EdgeView([(0, 1), (1, 2), (2, 3)])
|
| 14 |
+
>>> G.nodes[0]["label"] = "A"
|
| 15 |
+
>>> G.nodes[3]["label"] = "B"
|
| 16 |
+
>>> node_classification.harmonic_function(G)
|
| 17 |
+
['A', 'A', 'B', 'B']
|
| 18 |
+
|
| 19 |
+
References
|
| 20 |
+
----------
|
| 21 |
+
Zhu, X., Ghahramani, Z., & Lafferty, J. (2003, August).
|
| 22 |
+
Semi-supervised learning using gaussian fields and harmonic functions.
|
| 23 |
+
In ICML (Vol. 3, pp. 912-919).
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
import networkx as nx
|
| 27 |
+
|
| 28 |
+
__all__ = ["harmonic_function", "local_and_global_consistency"]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@nx.utils.not_implemented_for("directed")
|
| 32 |
+
@nx._dispatchable(node_attrs="label_name")
|
| 33 |
+
def harmonic_function(G, max_iter=30, label_name="label"):
|
| 34 |
+
"""Node classification by Harmonic function
|
| 35 |
+
|
| 36 |
+
Function for computing Harmonic function algorithm by Zhu et al.
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
G : NetworkX Graph
|
| 41 |
+
max_iter : int
|
| 42 |
+
maximum number of iterations allowed
|
| 43 |
+
label_name : string
|
| 44 |
+
name of target labels to predict
|
| 45 |
+
|
| 46 |
+
Returns
|
| 47 |
+
-------
|
| 48 |
+
predicted : list
|
| 49 |
+
List of length ``len(G)`` with the predicted labels for each node.
|
| 50 |
+
|
| 51 |
+
Raises
|
| 52 |
+
------
|
| 53 |
+
NetworkXError
|
| 54 |
+
If no nodes in `G` have attribute `label_name`.
|
| 55 |
+
|
| 56 |
+
Examples
|
| 57 |
+
--------
|
| 58 |
+
>>> from networkx.algorithms import node_classification
|
| 59 |
+
>>> G = nx.path_graph(4)
|
| 60 |
+
>>> G.nodes[0]["label"] = "A"
|
| 61 |
+
>>> G.nodes[3]["label"] = "B"
|
| 62 |
+
>>> G.nodes(data=True)
|
| 63 |
+
NodeDataView({0: {'label': 'A'}, 1: {}, 2: {}, 3: {'label': 'B'}})
|
| 64 |
+
>>> G.edges()
|
| 65 |
+
EdgeView([(0, 1), (1, 2), (2, 3)])
|
| 66 |
+
>>> predicted = node_classification.harmonic_function(G)
|
| 67 |
+
>>> predicted
|
| 68 |
+
['A', 'A', 'B', 'B']
|
| 69 |
+
|
| 70 |
+
References
|
| 71 |
+
----------
|
| 72 |
+
Zhu, X., Ghahramani, Z., & Lafferty, J. (2003, August).
|
| 73 |
+
Semi-supervised learning using gaussian fields and harmonic functions.
|
| 74 |
+
In ICML (Vol. 3, pp. 912-919).
|
| 75 |
+
"""
|
| 76 |
+
import numpy as np
|
| 77 |
+
import scipy as sp
|
| 78 |
+
|
| 79 |
+
X = nx.to_scipy_sparse_array(G) # adjacency matrix
|
| 80 |
+
labels, label_dict = _get_label_info(G, label_name)
|
| 81 |
+
|
| 82 |
+
if labels.shape[0] == 0:
|
| 83 |
+
raise nx.NetworkXError(
|
| 84 |
+
f"No node on the input graph is labeled by '{label_name}'."
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
n_samples = X.shape[0]
|
| 88 |
+
n_classes = label_dict.shape[0]
|
| 89 |
+
F = np.zeros((n_samples, n_classes))
|
| 90 |
+
|
| 91 |
+
# Build propagation matrix
|
| 92 |
+
degrees = X.sum(axis=0)
|
| 93 |
+
degrees[degrees == 0] = 1 # Avoid division by 0
|
| 94 |
+
D = sp.sparse.dia_array((1.0 / degrees, 0), shape=(n_samples, n_samples)).tocsr()
|
| 95 |
+
P = (D @ X).tolil()
|
| 96 |
+
P[labels[:, 0]] = 0 # labels[:, 0] indicates IDs of labeled nodes
|
| 97 |
+
# Build base matrix
|
| 98 |
+
B = np.zeros((n_samples, n_classes))
|
| 99 |
+
B[labels[:, 0], labels[:, 1]] = 1
|
| 100 |
+
|
| 101 |
+
for _ in range(max_iter):
|
| 102 |
+
F = (P @ F) + B
|
| 103 |
+
|
| 104 |
+
return label_dict[np.argmax(F, axis=1)].tolist()
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@nx.utils.not_implemented_for("directed")
|
| 108 |
+
@nx._dispatchable(node_attrs="label_name")
|
| 109 |
+
def local_and_global_consistency(G, alpha=0.99, max_iter=30, label_name="label"):
|
| 110 |
+
"""Node classification by Local and Global Consistency
|
| 111 |
+
|
| 112 |
+
Function for computing Local and global consistency algorithm by Zhou et al.
|
| 113 |
+
|
| 114 |
+
Parameters
|
| 115 |
+
----------
|
| 116 |
+
G : NetworkX Graph
|
| 117 |
+
alpha : float
|
| 118 |
+
Clamping factor
|
| 119 |
+
max_iter : int
|
| 120 |
+
Maximum number of iterations allowed
|
| 121 |
+
label_name : string
|
| 122 |
+
Name of target labels to predict
|
| 123 |
+
|
| 124 |
+
Returns
|
| 125 |
+
-------
|
| 126 |
+
predicted : list
|
| 127 |
+
List of length ``len(G)`` with the predicted labels for each node.
|
| 128 |
+
|
| 129 |
+
Raises
|
| 130 |
+
------
|
| 131 |
+
NetworkXError
|
| 132 |
+
If no nodes in `G` have attribute `label_name`.
|
| 133 |
+
|
| 134 |
+
Examples
|
| 135 |
+
--------
|
| 136 |
+
>>> from networkx.algorithms import node_classification
|
| 137 |
+
>>> G = nx.path_graph(4)
|
| 138 |
+
>>> G.nodes[0]["label"] = "A"
|
| 139 |
+
>>> G.nodes[3]["label"] = "B"
|
| 140 |
+
>>> G.nodes(data=True)
|
| 141 |
+
NodeDataView({0: {'label': 'A'}, 1: {}, 2: {}, 3: {'label': 'B'}})
|
| 142 |
+
>>> G.edges()
|
| 143 |
+
EdgeView([(0, 1), (1, 2), (2, 3)])
|
| 144 |
+
>>> predicted = node_classification.local_and_global_consistency(G)
|
| 145 |
+
>>> predicted
|
| 146 |
+
['A', 'A', 'B', 'B']
|
| 147 |
+
|
| 148 |
+
References
|
| 149 |
+
----------
|
| 150 |
+
Zhou, D., Bousquet, O., Lal, T. N., Weston, J., & Schölkopf, B. (2004).
|
| 151 |
+
Learning with local and global consistency.
|
| 152 |
+
Advances in neural information processing systems, 16(16), 321-328.
|
| 153 |
+
"""
|
| 154 |
+
import numpy as np
|
| 155 |
+
import scipy as sp
|
| 156 |
+
|
| 157 |
+
X = nx.to_scipy_sparse_array(G) # adjacency matrix
|
| 158 |
+
labels, label_dict = _get_label_info(G, label_name)
|
| 159 |
+
|
| 160 |
+
if labels.shape[0] == 0:
|
| 161 |
+
raise nx.NetworkXError(
|
| 162 |
+
f"No node on the input graph is labeled by '{label_name}'."
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
n_samples = X.shape[0]
|
| 166 |
+
n_classes = label_dict.shape[0]
|
| 167 |
+
F = np.zeros((n_samples, n_classes))
|
| 168 |
+
|
| 169 |
+
# Build propagation matrix
|
| 170 |
+
degrees = X.sum(axis=0)
|
| 171 |
+
degrees[degrees == 0] = 1 # Avoid division by 0
|
| 172 |
+
D2 = sp.sparse.dia_array(
|
| 173 |
+
(1.0 / np.sqrt(degrees), 0), shape=(n_samples, n_samples)
|
| 174 |
+
).tocsr()
|
| 175 |
+
P = alpha * ((D2 @ X) @ D2)
|
| 176 |
+
# Build base matrix
|
| 177 |
+
B = np.zeros((n_samples, n_classes))
|
| 178 |
+
B[labels[:, 0], labels[:, 1]] = 1 - alpha
|
| 179 |
+
|
| 180 |
+
for _ in range(max_iter):
|
| 181 |
+
F = (P @ F) + B
|
| 182 |
+
|
| 183 |
+
return label_dict[np.argmax(F, axis=1)].tolist()
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _get_label_info(G, label_name):
|
| 187 |
+
"""Get and return information of labels from the input graph
|
| 188 |
+
|
| 189 |
+
Parameters
|
| 190 |
+
----------
|
| 191 |
+
G : Network X graph
|
| 192 |
+
label_name : string
|
| 193 |
+
Name of the target label
|
| 194 |
+
|
| 195 |
+
Returns
|
| 196 |
+
-------
|
| 197 |
+
labels : numpy array, shape = [n_labeled_samples, 2]
|
| 198 |
+
Array of pairs of labeled node ID and label ID
|
| 199 |
+
label_dict : numpy array, shape = [n_classes]
|
| 200 |
+
Array of labels
|
| 201 |
+
i-th element contains the label corresponding label ID `i`
|
| 202 |
+
"""
|
| 203 |
+
import numpy as np
|
| 204 |
+
|
| 205 |
+
labels = []
|
| 206 |
+
label_to_id = {}
|
| 207 |
+
lid = 0
|
| 208 |
+
for i, n in enumerate(G.nodes(data=True)):
|
| 209 |
+
if label_name in n[1]:
|
| 210 |
+
label = n[1][label_name]
|
| 211 |
+
if label not in label_to_id:
|
| 212 |
+
label_to_id[label] = lid
|
| 213 |
+
lid += 1
|
| 214 |
+
labels.append([i, label_to_id[label]])
|
| 215 |
+
labels = np.array(labels)
|
| 216 |
+
label_dict = np.array(
|
| 217 |
+
[label for label, _ in sorted(label_to_id.items(), key=lambda x: x[1])]
|
| 218 |
+
)
|
| 219 |
+
return (labels, label_dict)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/non_randomness.py
ADDED
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import networkx as nx
|
| 6 |
+
from networkx.utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = ["non_randomness"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@not_implemented_for("directed")
|
| 12 |
+
@not_implemented_for("multigraph")
|
| 13 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 14 |
+
def non_randomness(G, k=None, weight="weight"):
|
| 15 |
+
"""Compute the non-randomness of a graph.
|
| 16 |
+
|
| 17 |
+
The first value $R_G$ is the sum of non-randomness values of all
|
| 18 |
+
edges within the graph (where the non-randomness of an edge tends to be
|
| 19 |
+
small when the two nodes linked by that edge are from two different
|
| 20 |
+
communities).
|
| 21 |
+
|
| 22 |
+
The second value $R_G^*$ is a relative measure that indicates
|
| 23 |
+
to what extent `G` is different from a random graph in terms
|
| 24 |
+
of probability. The closer it is to 0, the higher the likelihood
|
| 25 |
+
the graph was generated by an Erdős--Rényi model.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
G : NetworkX graph
|
| 30 |
+
Graph must be undirected, connected, and without self-loops.
|
| 31 |
+
|
| 32 |
+
k : int or None, optional (default=None)
|
| 33 |
+
The number of communities in `G`.
|
| 34 |
+
If `k` is not set, the function uses a default community detection
|
| 35 |
+
algorithm (:func:`~networkx.algorithms.community.label_propagation_communities`)
|
| 36 |
+
to set it.
|
| 37 |
+
|
| 38 |
+
weight : string or None, optional (default="weight")
|
| 39 |
+
The name of an edge attribute that holds the numerical value used
|
| 40 |
+
as a weight. If `None`, then each edge has weight 1, i.e., the graph is
|
| 41 |
+
binary.
|
| 42 |
+
|
| 43 |
+
Returns
|
| 44 |
+
-------
|
| 45 |
+
(float, float) tuple
|
| 46 |
+
The first value is $R_G$, the non-randomness of the graph,
|
| 47 |
+
the second is $R_G^*$, the relative non-randomness
|
| 48 |
+
w.r.t. the Erdős--Rényi model.
|
| 49 |
+
|
| 50 |
+
Raises
|
| 51 |
+
------
|
| 52 |
+
NetworkXNotImplemented
|
| 53 |
+
If the input graph is directed or a multigraph.
|
| 54 |
+
|
| 55 |
+
NetworkXException
|
| 56 |
+
If the input graph is not connected.
|
| 57 |
+
|
| 58 |
+
NetworkXError
|
| 59 |
+
If the input graph contains self-loops or has no edges.
|
| 60 |
+
|
| 61 |
+
ValueError
|
| 62 |
+
If `k` is not in $\\{1, \\dots, n-1\\}$, where $n$ is the number of nodes,
|
| 63 |
+
or if `k` is such that the computed edge probability
|
| 64 |
+
$p = \\frac{2km}{n(n-k)}$ does not satisfy $0 < p < 1$.
|
| 65 |
+
|
| 66 |
+
Examples
|
| 67 |
+
--------
|
| 68 |
+
>>> G = nx.karate_club_graph()
|
| 69 |
+
>>> nr, nr_rd = nx.non_randomness(G, 2)
|
| 70 |
+
>>> nr, nr_rd = nx.non_randomness(G, 2, "weight")
|
| 71 |
+
|
| 72 |
+
When the number of communities `k` is not specified,
|
| 73 |
+
:func:`~networkx.algorithms.community.label_propagation_communities`
|
| 74 |
+
is used to compute it.
|
| 75 |
+
This algorithm can give different results depending on
|
| 76 |
+
the order of nodes and edges in the graph.
|
| 77 |
+
For example, while the following graphs are identical,
|
| 78 |
+
computing the non-randomness of each of them yields different results:
|
| 79 |
+
|
| 80 |
+
>>> G1, G2 = nx.Graph(), nx.Graph()
|
| 81 |
+
>>> G1.add_edges_from([(0, 1), (1, 2), (1, 3), (3, 4)])
|
| 82 |
+
>>> G2.add_edges_from([(0, 1), (1, 3), (1, 2), (3, 4)])
|
| 83 |
+
>>> [round(r, 6) for r in nx.non_randomness(G1)]
|
| 84 |
+
[-1.847759, -5.842437]
|
| 85 |
+
>>> [round(r, 6) for r in nx.non_randomness(G2)]
|
| 86 |
+
Traceback (most recent call last):
|
| 87 |
+
...
|
| 88 |
+
ValueError: invalid number of communities for graph with 5 nodes and 4 edges: 2
|
| 89 |
+
|
| 90 |
+
This is because the community detection algorithm finds
|
| 91 |
+
1 community in `G1` and 2 communities in `G2`.
|
| 92 |
+
This can be resolved by specifying the number of communities `k`:
|
| 93 |
+
|
| 94 |
+
>>> [round(r, 6) for r in nx.non_randomness(G2, k=1)]
|
| 95 |
+
[-1.847759, -5.842437]
|
| 96 |
+
|
| 97 |
+
Notes
|
| 98 |
+
-----
|
| 99 |
+
If a `weight` argument is passed, this algorithm will use the eigenvalues
|
| 100 |
+
of the weighted adjacency matrix instead.
|
| 101 |
+
|
| 102 |
+
The output of this function corresponds to (4.4) and (4.5) in [1]_.
|
| 103 |
+
A lower value of $R^*_G$ indicates a more random graph;
|
| 104 |
+
one can think of $1 - \\Phi(R_G^*)$ as the similarity
|
| 105 |
+
between the graph and a random graph,
|
| 106 |
+
where $\\Phi(x)$ is the cumulative distribution function
|
| 107 |
+
of the standard normal distribution.
|
| 108 |
+
|
| 109 |
+
Theorem 2 in [2]_ states that for any graph $G$
|
| 110 |
+
with $n$ nodes, $m$ edges, and $k$ communities,
|
| 111 |
+
its non-randomness is bounded below by the non-randomness of an
|
| 112 |
+
$r$-regular graph (a graph where each node has degree $r$),
|
| 113 |
+
and bounded above by the non-randomness of an $l$-complete graph
|
| 114 |
+
(a graph where each community is a clique of $l$ nodes).
|
| 115 |
+
|
| 116 |
+
References
|
| 117 |
+
----------
|
| 118 |
+
.. [1] Xiaowei Ying and Xintao Wu,
|
| 119 |
+
On Randomness Measures for Social Networks,
|
| 120 |
+
SIAM International Conference on Data Mining. 2009
|
| 121 |
+
https://doi.org/10.1137/1.9781611972795.61
|
| 122 |
+
.. [2] Ying, Xiaowei & Wu, Leting & Wu, Xintao. (2012).
|
| 123 |
+
A Spectrum-Based Framework for Quantifying Randomness of Social Networks.
|
| 124 |
+
IEEE Transactions on Knowledge and Data Engineering 23(12):1842--1856.
|
| 125 |
+
https://dl.acm.org/doi/abs/10.1109/TKDE.2010.218
|
| 126 |
+
"""
|
| 127 |
+
import numpy as np
|
| 128 |
+
|
| 129 |
+
# corner case: graph has no edges
|
| 130 |
+
if nx.is_empty(G):
|
| 131 |
+
raise nx.NetworkXError("non_randomness not applicable to empty graphs")
|
| 132 |
+
if not nx.is_connected(G):
|
| 133 |
+
raise nx.NetworkXException("Non connected graph.")
|
| 134 |
+
if len(list(nx.selfloop_edges(G))) > 0:
|
| 135 |
+
raise nx.NetworkXError("Graph must not contain self-loops")
|
| 136 |
+
|
| 137 |
+
n = G.number_of_nodes()
|
| 138 |
+
m = G.number_of_edges()
|
| 139 |
+
|
| 140 |
+
if k is None:
|
| 141 |
+
k = len(tuple(nx.community.label_propagation_communities(G)))
|
| 142 |
+
if not 1 <= k < n or not 0 < (p := (2 * k * m) / (n * (n - k))) < 1:
|
| 143 |
+
err = (
|
| 144 |
+
f"invalid number of communities for graph with {n} nodes and {m} edges: {k}"
|
| 145 |
+
)
|
| 146 |
+
raise ValueError(err)
|
| 147 |
+
|
| 148 |
+
# eq. 4.4
|
| 149 |
+
eigenvalues = np.linalg.eigvals(nx.to_numpy_array(G, weight=weight))
|
| 150 |
+
nr = float(np.real(np.sum(eigenvalues[:k])))
|
| 151 |
+
|
| 152 |
+
# eq. 4.5
|
| 153 |
+
nr_rd = (nr - ((n - 2 * k) * p + k)) / math.sqrt(2 * k * p * (1 - p))
|
| 154 |
+
|
| 155 |
+
return nr, nr_rd
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/perfect_graph.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.utils.decorators import not_implemented_for
|
| 5 |
+
|
| 6 |
+
__all__ = ["is_perfect_graph"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@nx._dispatchable
|
| 10 |
+
@not_implemented_for("directed")
|
| 11 |
+
@not_implemented_for("multigraph")
|
| 12 |
+
def is_perfect_graph(G):
|
| 13 |
+
r"""Return True if G is a perfect graph, else False.
|
| 14 |
+
|
| 15 |
+
A graph G is perfect if, for every induced subgraph H of G, the chromatic
|
| 16 |
+
number of H equals the size of the largest clique in H.
|
| 17 |
+
|
| 18 |
+
According to the **Strong Perfect Graph Theorem (SPGT)**:
|
| 19 |
+
A graph is perfect if and only if neither the graph G nor its complement
|
| 20 |
+
:math:`\overline{G}` contains an **induced odd hole** — an induced cycle of
|
| 21 |
+
odd length at least five without chords.
|
| 22 |
+
|
| 23 |
+
Parameters
|
| 24 |
+
----------
|
| 25 |
+
G : NetworkX Graph
|
| 26 |
+
The graph to check. Must be a finite, simple, undirected graph.
|
| 27 |
+
|
| 28 |
+
Returns
|
| 29 |
+
-------
|
| 30 |
+
bool
|
| 31 |
+
True if G is a perfect graph, else False.
|
| 32 |
+
|
| 33 |
+
Notes
|
| 34 |
+
-----
|
| 35 |
+
This function uses a direct approach: cycle enumeration to detect
|
| 36 |
+
chordless odd cycles in G and :math:`\overline{G}`. This implementation
|
| 37 |
+
runs in exponential time in the worst case, since the number of chordless
|
| 38 |
+
cycles can grow exponentially.
|
| 39 |
+
|
| 40 |
+
The perfect-graph recognition problem is theoretically solvable in
|
| 41 |
+
polynomial time. Chudnovsky *et al.* (2006) proved it can be solved in
|
| 42 |
+
:math:`O(n^9)` time via a complex structural decomposition [1]_, [2]_.
|
| 43 |
+
This implementation opts for a direct, transparent check rather than
|
| 44 |
+
implementing that high-degree polynomial-time decomposition algorithm.
|
| 45 |
+
|
| 46 |
+
See Also
|
| 47 |
+
--------
|
| 48 |
+
is_chordal, is_bipartite :
|
| 49 |
+
Related checks for specific categories of perfect graphs, such as chordal
|
| 50 |
+
graphs, and bipartite graphs.
|
| 51 |
+
chordless_cycles :
|
| 52 |
+
Used to detect "holes" in the graph
|
| 53 |
+
|
| 54 |
+
References
|
| 55 |
+
----------
|
| 56 |
+
.. [1] M. Chudnovsky, N. Robertson, P. Seymour, and R. Thomas,
|
| 57 |
+
*The Strong Perfect Graph Theorem*,
|
| 58 |
+
Annals of Mathematics, vol. 164, no. 1, pp. 51–229, 2006.
|
| 59 |
+
https://doi.org/10.4007/annals.2006.164.51
|
| 60 |
+
.. [2] M. Chudnovsky, G. Cornuéjols, X. Liu, P. Seymour, and K. Vušković,
|
| 61 |
+
*Recognizing Berge Graphs*,
|
| 62 |
+
Combinatorica 25(2): 143–186, 2005.
|
| 63 |
+
DOI: 10.1007/s00493-005-0003-8
|
| 64 |
+
Preprint available at:
|
| 65 |
+
https://web.math.princeton.edu/~pds/papers/algexp/Bergealg.pdf
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
return not any(
|
| 69 |
+
(len(c) >= 5) and (len(c) % 2 == 1)
|
| 70 |
+
for c in itertools.chain(
|
| 71 |
+
nx.chordless_cycles(G), nx.chordless_cycles(nx.complement(G))
|
| 72 |
+
)
|
| 73 |
+
)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/planar_drawing.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
__all__ = ["combinatorial_embedding_to_pos"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def combinatorial_embedding_to_pos(embedding, fully_triangulate=False):
|
| 9 |
+
"""Assigns every node a (x, y) position based on the given embedding
|
| 10 |
+
|
| 11 |
+
The algorithm iteratively inserts nodes of the input graph in a certain
|
| 12 |
+
order and rearranges previously inserted nodes so that the planar drawing
|
| 13 |
+
stays valid. This is done efficiently by only maintaining relative
|
| 14 |
+
positions during the node placements and calculating the absolute positions
|
| 15 |
+
at the end. For more information see [1]_.
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
----------
|
| 19 |
+
embedding : nx.PlanarEmbedding
|
| 20 |
+
This defines the order of the edges
|
| 21 |
+
|
| 22 |
+
fully_triangulate : bool
|
| 23 |
+
If set to True the algorithm adds edges to a copy of the input
|
| 24 |
+
embedding and makes it chordal.
|
| 25 |
+
|
| 26 |
+
Returns
|
| 27 |
+
-------
|
| 28 |
+
pos : dict
|
| 29 |
+
Maps each node to a tuple that defines the (x, y) position
|
| 30 |
+
|
| 31 |
+
References
|
| 32 |
+
----------
|
| 33 |
+
.. [1] M. Chrobak and T.H. Payne:
|
| 34 |
+
A Linear-time Algorithm for Drawing a Planar Graph on a Grid 1989
|
| 35 |
+
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.6677
|
| 36 |
+
|
| 37 |
+
"""
|
| 38 |
+
if len(embedding.nodes()) < 4:
|
| 39 |
+
# Position the node in any triangle
|
| 40 |
+
default_positions = [(0, 0), (2, 0), (1, 1)]
|
| 41 |
+
pos = {}
|
| 42 |
+
for i, v in enumerate(embedding.nodes()):
|
| 43 |
+
pos[v] = default_positions[i]
|
| 44 |
+
return pos
|
| 45 |
+
|
| 46 |
+
embedding, outer_face = triangulate_embedding(embedding, fully_triangulate)
|
| 47 |
+
|
| 48 |
+
# The following dicts map a node to another node
|
| 49 |
+
# If a node is not in the key set it means that the node is not yet in G_k
|
| 50 |
+
# If a node maps to None then the corresponding subtree does not exist
|
| 51 |
+
left_t_child = {}
|
| 52 |
+
right_t_child = {}
|
| 53 |
+
|
| 54 |
+
# The following dicts map a node to an integer
|
| 55 |
+
delta_x = {}
|
| 56 |
+
y_coordinate = {}
|
| 57 |
+
|
| 58 |
+
node_list = get_canonical_ordering(embedding, outer_face)
|
| 59 |
+
|
| 60 |
+
# 1. Phase: Compute relative positions
|
| 61 |
+
|
| 62 |
+
# Initialization
|
| 63 |
+
v1, v2, v3 = node_list[0][0], node_list[1][0], node_list[2][0]
|
| 64 |
+
|
| 65 |
+
delta_x[v1] = 0
|
| 66 |
+
y_coordinate[v1] = 0
|
| 67 |
+
right_t_child[v1] = v3
|
| 68 |
+
left_t_child[v1] = None
|
| 69 |
+
|
| 70 |
+
delta_x[v2] = 1
|
| 71 |
+
y_coordinate[v2] = 0
|
| 72 |
+
right_t_child[v2] = None
|
| 73 |
+
left_t_child[v2] = None
|
| 74 |
+
|
| 75 |
+
delta_x[v3] = 1
|
| 76 |
+
y_coordinate[v3] = 1
|
| 77 |
+
right_t_child[v3] = v2
|
| 78 |
+
left_t_child[v3] = None
|
| 79 |
+
|
| 80 |
+
for k in range(3, len(node_list)):
|
| 81 |
+
vk, contour_nbrs = node_list[k]
|
| 82 |
+
wp = contour_nbrs[0]
|
| 83 |
+
wp1 = contour_nbrs[1]
|
| 84 |
+
wq = contour_nbrs[-1]
|
| 85 |
+
wq1 = contour_nbrs[-2]
|
| 86 |
+
adds_mult_tri = len(contour_nbrs) > 2
|
| 87 |
+
|
| 88 |
+
# Stretch gaps:
|
| 89 |
+
delta_x[wp1] += 1
|
| 90 |
+
delta_x[wq] += 1
|
| 91 |
+
|
| 92 |
+
delta_x_wp_wq = sum(delta_x[x] for x in contour_nbrs[1:])
|
| 93 |
+
|
| 94 |
+
# Adjust offsets
|
| 95 |
+
delta_x[vk] = (-y_coordinate[wp] + delta_x_wp_wq + y_coordinate[wq]) // 2
|
| 96 |
+
y_coordinate[vk] = (y_coordinate[wp] + delta_x_wp_wq + y_coordinate[wq]) // 2
|
| 97 |
+
delta_x[wq] = delta_x_wp_wq - delta_x[vk]
|
| 98 |
+
if adds_mult_tri:
|
| 99 |
+
delta_x[wp1] -= delta_x[vk]
|
| 100 |
+
|
| 101 |
+
# Install v_k:
|
| 102 |
+
right_t_child[wp] = vk
|
| 103 |
+
right_t_child[vk] = wq
|
| 104 |
+
if adds_mult_tri:
|
| 105 |
+
left_t_child[vk] = wp1
|
| 106 |
+
right_t_child[wq1] = None
|
| 107 |
+
else:
|
| 108 |
+
left_t_child[vk] = None
|
| 109 |
+
|
| 110 |
+
# 2. Phase: Set absolute positions
|
| 111 |
+
pos = {}
|
| 112 |
+
pos[v1] = (0, y_coordinate[v1])
|
| 113 |
+
remaining_nodes = [v1]
|
| 114 |
+
while remaining_nodes:
|
| 115 |
+
parent_node = remaining_nodes.pop()
|
| 116 |
+
|
| 117 |
+
# Calculate position for left child
|
| 118 |
+
set_position(
|
| 119 |
+
parent_node, left_t_child, remaining_nodes, delta_x, y_coordinate, pos
|
| 120 |
+
)
|
| 121 |
+
# Calculate position for right child
|
| 122 |
+
set_position(
|
| 123 |
+
parent_node, right_t_child, remaining_nodes, delta_x, y_coordinate, pos
|
| 124 |
+
)
|
| 125 |
+
return pos
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def set_position(parent, tree, remaining_nodes, delta_x, y_coordinate, pos):
|
| 129 |
+
"""Helper method to calculate the absolute position of nodes."""
|
| 130 |
+
child = tree[parent]
|
| 131 |
+
parent_node_x = pos[parent][0]
|
| 132 |
+
if child is not None:
|
| 133 |
+
# Calculate pos of child
|
| 134 |
+
child_x = parent_node_x + delta_x[child]
|
| 135 |
+
pos[child] = (child_x, y_coordinate[child])
|
| 136 |
+
# Remember to calculate pos of its children
|
| 137 |
+
remaining_nodes.append(child)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def get_canonical_ordering(embedding, outer_face):
|
| 141 |
+
"""Returns a canonical ordering of the nodes
|
| 142 |
+
|
| 143 |
+
The canonical ordering of nodes (v1, ..., vn) must fulfill the following
|
| 144 |
+
conditions:
|
| 145 |
+
(See Lemma 1 in [2]_)
|
| 146 |
+
|
| 147 |
+
- For the subgraph G_k of the input graph induced by v1, ..., vk it holds:
|
| 148 |
+
- 2-connected
|
| 149 |
+
- internally triangulated
|
| 150 |
+
- the edge (v1, v2) is part of the outer face
|
| 151 |
+
- For a node v(k+1) the following holds:
|
| 152 |
+
- The node v(k+1) is part of the outer face of G_k
|
| 153 |
+
- It has at least two neighbors in G_k
|
| 154 |
+
- All neighbors of v(k+1) in G_k lie consecutively on the outer face of
|
| 155 |
+
G_k (excluding the edge (v1, v2)).
|
| 156 |
+
|
| 157 |
+
The algorithm used here starts with G_n (containing all nodes). It first
|
| 158 |
+
selects the nodes v1 and v2. And then tries to find the order of the other
|
| 159 |
+
nodes by checking which node can be removed in order to fulfill the
|
| 160 |
+
conditions mentioned above. This is done by calculating the number of
|
| 161 |
+
chords of nodes on the outer face. For more information see [1]_.
|
| 162 |
+
|
| 163 |
+
Parameters
|
| 164 |
+
----------
|
| 165 |
+
embedding : nx.PlanarEmbedding
|
| 166 |
+
The embedding must be triangulated
|
| 167 |
+
outer_face : list
|
| 168 |
+
The nodes on the outer face of the graph
|
| 169 |
+
|
| 170 |
+
Returns
|
| 171 |
+
-------
|
| 172 |
+
ordering : list
|
| 173 |
+
A list of tuples `(vk, wp_wq)`. Here `vk` is the node at this position
|
| 174 |
+
in the canonical ordering. The element `wp_wq` is a list of nodes that
|
| 175 |
+
make up the outer face of G_k.
|
| 176 |
+
|
| 177 |
+
References
|
| 178 |
+
----------
|
| 179 |
+
.. [1] Steven Chaplick.
|
| 180 |
+
Canonical Orders of Planar Graphs and (some of) Their Applications 2015
|
| 181 |
+
https://wuecampus2.uni-wuerzburg.de/moodle/pluginfile.php/545727/mod_resource/content/0/vg-ss15-vl03-canonical-orders-druckversion.pdf
|
| 182 |
+
.. [2] M. Chrobak and T.H. Payne:
|
| 183 |
+
A Linear-time Algorithm for Drawing a Planar Graph on a Grid 1989
|
| 184 |
+
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.6677
|
| 185 |
+
|
| 186 |
+
"""
|
| 187 |
+
v1 = outer_face[0]
|
| 188 |
+
v2 = outer_face[1]
|
| 189 |
+
chords = defaultdict(int) # Maps nodes to the number of their chords
|
| 190 |
+
marked_nodes = set()
|
| 191 |
+
ready_to_pick = set(outer_face)
|
| 192 |
+
|
| 193 |
+
# Initialize outer_face_ccw_nbr (do not include v1 -> v2)
|
| 194 |
+
outer_face_ccw_nbr = {}
|
| 195 |
+
prev_nbr = v2
|
| 196 |
+
for idx in range(2, len(outer_face)):
|
| 197 |
+
outer_face_ccw_nbr[prev_nbr] = outer_face[idx]
|
| 198 |
+
prev_nbr = outer_face[idx]
|
| 199 |
+
outer_face_ccw_nbr[prev_nbr] = v1
|
| 200 |
+
|
| 201 |
+
# Initialize outer_face_cw_nbr (do not include v2 -> v1)
|
| 202 |
+
outer_face_cw_nbr = {}
|
| 203 |
+
prev_nbr = v1
|
| 204 |
+
for idx in range(len(outer_face) - 1, 0, -1):
|
| 205 |
+
outer_face_cw_nbr[prev_nbr] = outer_face[idx]
|
| 206 |
+
prev_nbr = outer_face[idx]
|
| 207 |
+
|
| 208 |
+
def is_outer_face_nbr(x, y):
|
| 209 |
+
if x not in outer_face_ccw_nbr:
|
| 210 |
+
return outer_face_cw_nbr[x] == y
|
| 211 |
+
if x not in outer_face_cw_nbr:
|
| 212 |
+
return outer_face_ccw_nbr[x] == y
|
| 213 |
+
return outer_face_ccw_nbr[x] == y or outer_face_cw_nbr[x] == y
|
| 214 |
+
|
| 215 |
+
def is_on_outer_face(x):
|
| 216 |
+
return x not in marked_nodes and (x in outer_face_ccw_nbr or x == v1)
|
| 217 |
+
|
| 218 |
+
# Initialize number of chords
|
| 219 |
+
for v in outer_face:
|
| 220 |
+
for nbr in embedding.neighbors_cw_order(v):
|
| 221 |
+
if is_on_outer_face(nbr) and not is_outer_face_nbr(v, nbr):
|
| 222 |
+
chords[v] += 1
|
| 223 |
+
ready_to_pick.discard(v)
|
| 224 |
+
|
| 225 |
+
# Initialize canonical_ordering
|
| 226 |
+
canonical_ordering = [None] * len(embedding.nodes())
|
| 227 |
+
canonical_ordering[0] = (v1, [])
|
| 228 |
+
canonical_ordering[1] = (v2, [])
|
| 229 |
+
ready_to_pick.discard(v1)
|
| 230 |
+
ready_to_pick.discard(v2)
|
| 231 |
+
|
| 232 |
+
for k in range(len(embedding.nodes()) - 1, 1, -1):
|
| 233 |
+
# 1. Pick v from ready_to_pick
|
| 234 |
+
v = ready_to_pick.pop()
|
| 235 |
+
marked_nodes.add(v)
|
| 236 |
+
|
| 237 |
+
# v has exactly two neighbors on the outer face (wp and wq)
|
| 238 |
+
wp = None
|
| 239 |
+
wq = None
|
| 240 |
+
# Iterate over neighbors of v to find wp and wq
|
| 241 |
+
nbr_iterator = iter(embedding.neighbors_cw_order(v))
|
| 242 |
+
while True:
|
| 243 |
+
nbr = next(nbr_iterator)
|
| 244 |
+
if nbr in marked_nodes:
|
| 245 |
+
# Only consider nodes that are not yet removed
|
| 246 |
+
continue
|
| 247 |
+
if is_on_outer_face(nbr):
|
| 248 |
+
# nbr is either wp or wq
|
| 249 |
+
if nbr == v1:
|
| 250 |
+
wp = v1
|
| 251 |
+
elif nbr == v2:
|
| 252 |
+
wq = v2
|
| 253 |
+
else:
|
| 254 |
+
if outer_face_cw_nbr[nbr] == v:
|
| 255 |
+
# nbr is wp
|
| 256 |
+
wp = nbr
|
| 257 |
+
else:
|
| 258 |
+
# nbr is wq
|
| 259 |
+
wq = nbr
|
| 260 |
+
if wp is not None and wq is not None:
|
| 261 |
+
# We don't need to iterate any further
|
| 262 |
+
break
|
| 263 |
+
|
| 264 |
+
# Obtain new nodes on outer face (neighbors of v from wp to wq)
|
| 265 |
+
wp_wq = [wp]
|
| 266 |
+
nbr = wp
|
| 267 |
+
while nbr != wq:
|
| 268 |
+
# Get next neighbor (clockwise on the outer face)
|
| 269 |
+
next_nbr = embedding[v][nbr]["ccw"]
|
| 270 |
+
wp_wq.append(next_nbr)
|
| 271 |
+
# Update outer face
|
| 272 |
+
outer_face_cw_nbr[nbr] = next_nbr
|
| 273 |
+
outer_face_ccw_nbr[next_nbr] = nbr
|
| 274 |
+
# Move to next neighbor of v
|
| 275 |
+
nbr = next_nbr
|
| 276 |
+
|
| 277 |
+
if len(wp_wq) == 2:
|
| 278 |
+
# There was a chord between wp and wq, decrease number of chords
|
| 279 |
+
chords[wp] -= 1
|
| 280 |
+
if chords[wp] == 0:
|
| 281 |
+
ready_to_pick.add(wp)
|
| 282 |
+
chords[wq] -= 1
|
| 283 |
+
if chords[wq] == 0:
|
| 284 |
+
ready_to_pick.add(wq)
|
| 285 |
+
else:
|
| 286 |
+
# Update all chords involving w_(p+1) to w_(q-1)
|
| 287 |
+
new_face_nodes = set(wp_wq[1:-1])
|
| 288 |
+
for w in new_face_nodes:
|
| 289 |
+
# If we do not find a chord for w later we can pick it next
|
| 290 |
+
ready_to_pick.add(w)
|
| 291 |
+
for nbr in embedding.neighbors_cw_order(w):
|
| 292 |
+
if is_on_outer_face(nbr) and not is_outer_face_nbr(w, nbr):
|
| 293 |
+
# There is a chord involving w
|
| 294 |
+
chords[w] += 1
|
| 295 |
+
ready_to_pick.discard(w)
|
| 296 |
+
if nbr not in new_face_nodes:
|
| 297 |
+
# Also increase chord for the neighbor
|
| 298 |
+
# We only iterator over new_face_nodes
|
| 299 |
+
chords[nbr] += 1
|
| 300 |
+
ready_to_pick.discard(nbr)
|
| 301 |
+
# Set the canonical ordering node and the list of contour neighbors
|
| 302 |
+
canonical_ordering[k] = (v, wp_wq)
|
| 303 |
+
|
| 304 |
+
return canonical_ordering
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def triangulate_face(embedding, v1, v2):
|
| 308 |
+
"""Triangulates the face given by half edge (v, w)
|
| 309 |
+
|
| 310 |
+
Parameters
|
| 311 |
+
----------
|
| 312 |
+
embedding : nx.PlanarEmbedding
|
| 313 |
+
v1 : node
|
| 314 |
+
The half-edge (v1, v2) belongs to the face that gets triangulated
|
| 315 |
+
v2 : node
|
| 316 |
+
"""
|
| 317 |
+
_, v3 = embedding.next_face_half_edge(v1, v2)
|
| 318 |
+
_, v4 = embedding.next_face_half_edge(v2, v3)
|
| 319 |
+
if v1 in (v2, v3):
|
| 320 |
+
# The component has less than 3 nodes
|
| 321 |
+
return
|
| 322 |
+
while v1 != v4:
|
| 323 |
+
# Add edge if not already present on other side
|
| 324 |
+
if embedding.has_edge(v1, v3):
|
| 325 |
+
# Cannot triangulate at this position
|
| 326 |
+
v1, v2, v3 = v2, v3, v4
|
| 327 |
+
else:
|
| 328 |
+
# Add edge for triangulation
|
| 329 |
+
embedding.add_half_edge(v1, v3, ccw=v2)
|
| 330 |
+
embedding.add_half_edge(v3, v1, cw=v2)
|
| 331 |
+
v1, v2, v3 = v1, v3, v4
|
| 332 |
+
# Get next node
|
| 333 |
+
_, v4 = embedding.next_face_half_edge(v2, v3)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def triangulate_embedding(embedding, fully_triangulate=True):
|
| 337 |
+
"""Triangulates the embedding.
|
| 338 |
+
|
| 339 |
+
Traverses faces of the embedding and adds edges to a copy of the
|
| 340 |
+
embedding to triangulate it.
|
| 341 |
+
The method also ensures that the resulting graph is 2-connected by adding
|
| 342 |
+
edges if the same vertex is contained twice on a path around a face.
|
| 343 |
+
|
| 344 |
+
Parameters
|
| 345 |
+
----------
|
| 346 |
+
embedding : nx.PlanarEmbedding
|
| 347 |
+
The input graph must contain at least 3 nodes.
|
| 348 |
+
|
| 349 |
+
fully_triangulate : bool
|
| 350 |
+
If set to False the face with the most nodes is chooses as outer face.
|
| 351 |
+
This outer face does not get triangulated.
|
| 352 |
+
|
| 353 |
+
Returns
|
| 354 |
+
-------
|
| 355 |
+
(embedding, outer_face) : (nx.PlanarEmbedding, list) tuple
|
| 356 |
+
The element `embedding` is a new embedding containing all edges from
|
| 357 |
+
the input embedding and the additional edges to triangulate the graph.
|
| 358 |
+
The element `outer_face` is a list of nodes that lie on the outer face.
|
| 359 |
+
If the graph is fully triangulated these are three arbitrary connected
|
| 360 |
+
nodes.
|
| 361 |
+
|
| 362 |
+
"""
|
| 363 |
+
if len(embedding.nodes) <= 1:
|
| 364 |
+
return embedding, list(embedding.nodes)
|
| 365 |
+
embedding = nx.PlanarEmbedding(embedding)
|
| 366 |
+
|
| 367 |
+
# Get a list with a node for each connected component
|
| 368 |
+
component_nodes = [next(iter(x)) for x in nx.connected_components(embedding)]
|
| 369 |
+
|
| 370 |
+
# 1. Make graph a single component (add edge between components)
|
| 371 |
+
for i in range(len(component_nodes) - 1):
|
| 372 |
+
v1 = component_nodes[i]
|
| 373 |
+
v2 = component_nodes[i + 1]
|
| 374 |
+
embedding.connect_components(v1, v2)
|
| 375 |
+
|
| 376 |
+
# 2. Calculate faces, ensure 2-connectedness and determine outer face
|
| 377 |
+
outer_face = [] # A face with the most number of nodes
|
| 378 |
+
face_list = []
|
| 379 |
+
edges_visited = set() # Used to keep track of already visited faces
|
| 380 |
+
for v in embedding.nodes():
|
| 381 |
+
for w in embedding.neighbors_cw_order(v):
|
| 382 |
+
new_face = make_bi_connected(embedding, v, w, edges_visited)
|
| 383 |
+
if new_face:
|
| 384 |
+
# Found a new face
|
| 385 |
+
face_list.append(new_face)
|
| 386 |
+
if len(new_face) > len(outer_face):
|
| 387 |
+
# The face is a candidate to be the outer face
|
| 388 |
+
outer_face = new_face
|
| 389 |
+
|
| 390 |
+
# 3. Triangulate (internal) faces
|
| 391 |
+
for face in face_list:
|
| 392 |
+
if face is not outer_face or fully_triangulate:
|
| 393 |
+
# Triangulate this face
|
| 394 |
+
triangulate_face(embedding, face[0], face[1])
|
| 395 |
+
|
| 396 |
+
if fully_triangulate:
|
| 397 |
+
v1 = outer_face[0]
|
| 398 |
+
v2 = outer_face[1]
|
| 399 |
+
v3 = embedding[v2][v1]["ccw"]
|
| 400 |
+
outer_face = [v1, v2, v3]
|
| 401 |
+
|
| 402 |
+
return embedding, outer_face
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def make_bi_connected(embedding, starting_node, outgoing_node, edges_counted):
|
| 406 |
+
"""Triangulate a face and make it 2-connected
|
| 407 |
+
|
| 408 |
+
This method also adds all edges on the face to `edges_counted`.
|
| 409 |
+
|
| 410 |
+
Parameters
|
| 411 |
+
----------
|
| 412 |
+
embedding: nx.PlanarEmbedding
|
| 413 |
+
The embedding that defines the faces
|
| 414 |
+
starting_node : node
|
| 415 |
+
A node on the face
|
| 416 |
+
outgoing_node : node
|
| 417 |
+
A node such that the half edge (starting_node, outgoing_node) belongs
|
| 418 |
+
to the face
|
| 419 |
+
edges_counted: set
|
| 420 |
+
Set of all half-edges that belong to a face that have been visited
|
| 421 |
+
|
| 422 |
+
Returns
|
| 423 |
+
-------
|
| 424 |
+
face_nodes: list
|
| 425 |
+
A list of all nodes at the border of this face
|
| 426 |
+
"""
|
| 427 |
+
|
| 428 |
+
# Check if the face has already been calculated
|
| 429 |
+
if (starting_node, outgoing_node) in edges_counted:
|
| 430 |
+
# This face was already counted
|
| 431 |
+
return []
|
| 432 |
+
edges_counted.add((starting_node, outgoing_node))
|
| 433 |
+
|
| 434 |
+
# Add all edges to edges_counted which have this face to their left
|
| 435 |
+
v1 = starting_node
|
| 436 |
+
v2 = outgoing_node
|
| 437 |
+
face_list = [starting_node] # List of nodes around the face
|
| 438 |
+
face_set = set(face_list) # Set for faster queries
|
| 439 |
+
_, v3 = embedding.next_face_half_edge(v1, v2)
|
| 440 |
+
|
| 441 |
+
# Move the nodes v1, v2, v3 around the face:
|
| 442 |
+
while v2 != starting_node or v3 != outgoing_node:
|
| 443 |
+
if v1 == v2:
|
| 444 |
+
raise nx.NetworkXException("Invalid half-edge")
|
| 445 |
+
# cycle is not completed yet
|
| 446 |
+
if v2 in face_set:
|
| 447 |
+
# v2 encountered twice: Add edge to ensure 2-connectedness
|
| 448 |
+
embedding.add_half_edge(v1, v3, ccw=v2)
|
| 449 |
+
embedding.add_half_edge(v3, v1, cw=v2)
|
| 450 |
+
edges_counted.add((v2, v3))
|
| 451 |
+
edges_counted.add((v3, v1))
|
| 452 |
+
v2 = v1
|
| 453 |
+
else:
|
| 454 |
+
face_set.add(v2)
|
| 455 |
+
face_list.append(v2)
|
| 456 |
+
|
| 457 |
+
# set next edge
|
| 458 |
+
v1 = v2
|
| 459 |
+
v2, v3 = embedding.next_face_half_edge(v2, v3)
|
| 460 |
+
|
| 461 |
+
# remember that this edge has been counted
|
| 462 |
+
edges_counted.add((v1, v2))
|
| 463 |
+
|
| 464 |
+
return face_list
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/planarity.py
ADDED
|
@@ -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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
from copy import deepcopy
|
| 3 |
+
|
| 4 |
+
import networkx as nx
|
| 5 |
+
|
| 6 |
+
__all__ = ["check_planarity", "is_planar", "PlanarEmbedding"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@nx._dispatchable
|
| 10 |
+
def is_planar(G):
|
| 11 |
+
"""Returns True if and only if `G` is planar.
|
| 12 |
+
|
| 13 |
+
A graph is *planar* iff it can be drawn in a plane without
|
| 14 |
+
any edge intersections.
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
----------
|
| 18 |
+
G : NetworkX graph
|
| 19 |
+
|
| 20 |
+
Returns
|
| 21 |
+
-------
|
| 22 |
+
bool
|
| 23 |
+
Whether the graph is planar.
|
| 24 |
+
|
| 25 |
+
Examples
|
| 26 |
+
--------
|
| 27 |
+
>>> G = nx.Graph([(0, 1), (0, 2)])
|
| 28 |
+
>>> nx.is_planar(G)
|
| 29 |
+
True
|
| 30 |
+
>>> nx.is_planar(nx.complete_graph(5))
|
| 31 |
+
False
|
| 32 |
+
|
| 33 |
+
See Also
|
| 34 |
+
--------
|
| 35 |
+
check_planarity :
|
| 36 |
+
Check if graph is planar *and* return a `PlanarEmbedding` instance if True.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
return check_planarity(G, counterexample=False)[0]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@nx._dispatchable(returns_graph=True)
|
| 43 |
+
def check_planarity(G, counterexample=False):
|
| 44 |
+
"""Check if a graph is planar and return a counterexample or an embedding.
|
| 45 |
+
|
| 46 |
+
A graph is planar iff it can be drawn in a plane without
|
| 47 |
+
any edge intersections.
|
| 48 |
+
|
| 49 |
+
Parameters
|
| 50 |
+
----------
|
| 51 |
+
G : NetworkX graph
|
| 52 |
+
counterexample : bool
|
| 53 |
+
A Kuratowski subgraph (to proof non planarity) is only returned if set
|
| 54 |
+
to true.
|
| 55 |
+
|
| 56 |
+
Returns
|
| 57 |
+
-------
|
| 58 |
+
(is_planar, certificate) : (bool, NetworkX graph) tuple
|
| 59 |
+
is_planar is true if the graph is planar.
|
| 60 |
+
If the graph is planar `certificate` is a PlanarEmbedding
|
| 61 |
+
otherwise it is a Kuratowski subgraph.
|
| 62 |
+
|
| 63 |
+
Examples
|
| 64 |
+
--------
|
| 65 |
+
>>> G = nx.Graph([(0, 1), (0, 2)])
|
| 66 |
+
>>> is_planar, P = nx.check_planarity(G)
|
| 67 |
+
>>> print(is_planar)
|
| 68 |
+
True
|
| 69 |
+
|
| 70 |
+
When `G` is planar, a `PlanarEmbedding` instance is returned:
|
| 71 |
+
|
| 72 |
+
>>> P.get_data()
|
| 73 |
+
{0: [1, 2], 1: [0], 2: [0]}
|
| 74 |
+
|
| 75 |
+
Notes
|
| 76 |
+
-----
|
| 77 |
+
A (combinatorial) embedding consists of cyclic orderings of the incident
|
| 78 |
+
edges at each vertex. Given such an embedding there are multiple approaches
|
| 79 |
+
discussed in literature to drawing the graph (subject to various
|
| 80 |
+
constraints, e.g. integer coordinates), see e.g. [2].
|
| 81 |
+
|
| 82 |
+
The planarity check algorithm and extraction of the combinatorial embedding
|
| 83 |
+
is based on the Left-Right Planarity Test [1].
|
| 84 |
+
|
| 85 |
+
A counterexample is only generated if the corresponding parameter is set,
|
| 86 |
+
because the complexity of the counterexample generation is higher.
|
| 87 |
+
|
| 88 |
+
See also
|
| 89 |
+
--------
|
| 90 |
+
is_planar :
|
| 91 |
+
Check for planarity without creating a `PlanarEmbedding` or counterexample.
|
| 92 |
+
|
| 93 |
+
References
|
| 94 |
+
----------
|
| 95 |
+
.. [1] Ulrik Brandes:
|
| 96 |
+
The Left-Right Planarity Test
|
| 97 |
+
2009
|
| 98 |
+
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.217.9208
|
| 99 |
+
.. [2] Takao Nishizeki, Md Saidur Rahman:
|
| 100 |
+
Planar graph drawing
|
| 101 |
+
Lecture Notes Series on Computing: Volume 12
|
| 102 |
+
2004
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
planarity_state = LRPlanarity(G)
|
| 106 |
+
embedding = planarity_state.lr_planarity()
|
| 107 |
+
if embedding is None:
|
| 108 |
+
# graph is not planar
|
| 109 |
+
if counterexample:
|
| 110 |
+
return False, get_counterexample(G)
|
| 111 |
+
else:
|
| 112 |
+
return False, None
|
| 113 |
+
else:
|
| 114 |
+
# graph is planar
|
| 115 |
+
return True, embedding
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@nx._dispatchable(returns_graph=True)
|
| 119 |
+
def check_planarity_recursive(G, counterexample=False):
|
| 120 |
+
"""Recursive version of :meth:`check_planarity`."""
|
| 121 |
+
planarity_state = LRPlanarity(G)
|
| 122 |
+
embedding = planarity_state.lr_planarity_recursive()
|
| 123 |
+
if embedding is None:
|
| 124 |
+
# graph is not planar
|
| 125 |
+
if counterexample:
|
| 126 |
+
return False, get_counterexample_recursive(G)
|
| 127 |
+
else:
|
| 128 |
+
return False, None
|
| 129 |
+
else:
|
| 130 |
+
# graph is planar
|
| 131 |
+
return True, embedding
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@nx._dispatchable(returns_graph=True)
|
| 135 |
+
def get_counterexample(G):
|
| 136 |
+
"""Obtains a Kuratowski subgraph.
|
| 137 |
+
|
| 138 |
+
Raises nx.NetworkXException if G is planar.
|
| 139 |
+
|
| 140 |
+
The function removes edges such that the graph is still not planar.
|
| 141 |
+
At some point the removal of any edge would make the graph planar.
|
| 142 |
+
This subgraph must be a Kuratowski subgraph.
|
| 143 |
+
|
| 144 |
+
Parameters
|
| 145 |
+
----------
|
| 146 |
+
G : NetworkX graph
|
| 147 |
+
|
| 148 |
+
Returns
|
| 149 |
+
-------
|
| 150 |
+
subgraph : NetworkX graph
|
| 151 |
+
A Kuratowski subgraph that proves that G is not planar.
|
| 152 |
+
|
| 153 |
+
"""
|
| 154 |
+
# copy graph
|
| 155 |
+
G = nx.Graph(G)
|
| 156 |
+
|
| 157 |
+
if check_planarity(G)[0]:
|
| 158 |
+
raise nx.NetworkXException("G is planar - no counter example.")
|
| 159 |
+
|
| 160 |
+
# find Kuratowski subgraph
|
| 161 |
+
subgraph = nx.Graph()
|
| 162 |
+
for u in G:
|
| 163 |
+
nbrs = list(G[u])
|
| 164 |
+
for v in nbrs:
|
| 165 |
+
G.remove_edge(u, v)
|
| 166 |
+
if check_planarity(G)[0]:
|
| 167 |
+
G.add_edge(u, v)
|
| 168 |
+
subgraph.add_edge(u, v)
|
| 169 |
+
|
| 170 |
+
return subgraph
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
@nx._dispatchable(returns_graph=True)
|
| 174 |
+
def get_counterexample_recursive(G):
|
| 175 |
+
"""Recursive version of :meth:`get_counterexample`."""
|
| 176 |
+
|
| 177 |
+
# copy graph
|
| 178 |
+
G = nx.Graph(G)
|
| 179 |
+
|
| 180 |
+
if check_planarity_recursive(G)[0]:
|
| 181 |
+
raise nx.NetworkXException("G is planar - no counter example.")
|
| 182 |
+
|
| 183 |
+
# find Kuratowski subgraph
|
| 184 |
+
subgraph = nx.Graph()
|
| 185 |
+
for u in G:
|
| 186 |
+
nbrs = list(G[u])
|
| 187 |
+
for v in nbrs:
|
| 188 |
+
G.remove_edge(u, v)
|
| 189 |
+
if check_planarity_recursive(G)[0]:
|
| 190 |
+
G.add_edge(u, v)
|
| 191 |
+
subgraph.add_edge(u, v)
|
| 192 |
+
|
| 193 |
+
return subgraph
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class Interval:
|
| 197 |
+
"""Represents a set of return edges.
|
| 198 |
+
|
| 199 |
+
All return edges in an interval induce a same constraint on the contained
|
| 200 |
+
edges, which means that all edges must either have a left orientation or
|
| 201 |
+
all edges must have a right orientation.
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
+
def __init__(self, low=None, high=None):
|
| 205 |
+
self.low = low
|
| 206 |
+
self.high = high
|
| 207 |
+
|
| 208 |
+
def empty(self):
|
| 209 |
+
"""Check if the interval is empty"""
|
| 210 |
+
return self.low is None and self.high is None
|
| 211 |
+
|
| 212 |
+
def copy(self):
|
| 213 |
+
"""Returns a copy of this interval"""
|
| 214 |
+
return Interval(self.low, self.high)
|
| 215 |
+
|
| 216 |
+
def conflicting(self, b, planarity_state):
|
| 217 |
+
"""Returns True if interval I conflicts with edge b"""
|
| 218 |
+
return (
|
| 219 |
+
not self.empty()
|
| 220 |
+
and planarity_state.lowpt[self.high] > planarity_state.lowpt[b]
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class ConflictPair:
|
| 225 |
+
"""Represents a different constraint between two intervals.
|
| 226 |
+
|
| 227 |
+
The edges in the left interval must have a different orientation than
|
| 228 |
+
the one in the right interval.
|
| 229 |
+
"""
|
| 230 |
+
|
| 231 |
+
def __init__(self, left=Interval(), right=Interval()):
|
| 232 |
+
self.left = left
|
| 233 |
+
self.right = right
|
| 234 |
+
|
| 235 |
+
def swap(self):
|
| 236 |
+
"""Swap left and right intervals"""
|
| 237 |
+
temp = self.left
|
| 238 |
+
self.left = self.right
|
| 239 |
+
self.right = temp
|
| 240 |
+
|
| 241 |
+
def lowest(self, planarity_state):
|
| 242 |
+
"""Returns the lowest lowpoint of a conflict pair"""
|
| 243 |
+
if self.left.empty():
|
| 244 |
+
return planarity_state.lowpt[self.right.low]
|
| 245 |
+
if self.right.empty():
|
| 246 |
+
return planarity_state.lowpt[self.left.low]
|
| 247 |
+
return min(
|
| 248 |
+
planarity_state.lowpt[self.left.low], planarity_state.lowpt[self.right.low]
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def top_of_stack(l):
|
| 253 |
+
"""Returns the element on top of the stack."""
|
| 254 |
+
if not l:
|
| 255 |
+
return None
|
| 256 |
+
return l[-1]
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class LRPlanarity:
|
| 260 |
+
"""A class to maintain the state during planarity check."""
|
| 261 |
+
|
| 262 |
+
__slots__ = [
|
| 263 |
+
"G",
|
| 264 |
+
"roots",
|
| 265 |
+
"height",
|
| 266 |
+
"lowpt",
|
| 267 |
+
"lowpt2",
|
| 268 |
+
"nesting_depth",
|
| 269 |
+
"parent_edge",
|
| 270 |
+
"DG",
|
| 271 |
+
"adjs",
|
| 272 |
+
"ordered_adjs",
|
| 273 |
+
"ref",
|
| 274 |
+
"side",
|
| 275 |
+
"S",
|
| 276 |
+
"stack_bottom",
|
| 277 |
+
"lowpt_edge",
|
| 278 |
+
"left_ref",
|
| 279 |
+
"right_ref",
|
| 280 |
+
"embedding",
|
| 281 |
+
]
|
| 282 |
+
|
| 283 |
+
def __init__(self, G):
|
| 284 |
+
# copy G without adding self-loops
|
| 285 |
+
self.G = nx.Graph()
|
| 286 |
+
self.G.add_nodes_from(G.nodes)
|
| 287 |
+
for e in G.edges:
|
| 288 |
+
if e[0] != e[1]:
|
| 289 |
+
self.G.add_edge(e[0], e[1])
|
| 290 |
+
|
| 291 |
+
self.roots = []
|
| 292 |
+
|
| 293 |
+
# distance from tree root
|
| 294 |
+
self.height = defaultdict(lambda: None)
|
| 295 |
+
|
| 296 |
+
self.lowpt = {} # height of lowest return point of an edge
|
| 297 |
+
self.lowpt2 = {} # height of second lowest return point
|
| 298 |
+
self.nesting_depth = {} # for nesting order
|
| 299 |
+
|
| 300 |
+
# None -> missing edge
|
| 301 |
+
self.parent_edge = defaultdict(lambda: None)
|
| 302 |
+
|
| 303 |
+
# oriented DFS graph
|
| 304 |
+
self.DG = nx.DiGraph()
|
| 305 |
+
self.DG.add_nodes_from(G.nodes)
|
| 306 |
+
|
| 307 |
+
self.adjs = {}
|
| 308 |
+
self.ordered_adjs = {}
|
| 309 |
+
|
| 310 |
+
self.ref = defaultdict(lambda: None)
|
| 311 |
+
self.side = defaultdict(lambda: 1)
|
| 312 |
+
|
| 313 |
+
# stack of conflict pairs
|
| 314 |
+
self.S = []
|
| 315 |
+
self.stack_bottom = {}
|
| 316 |
+
self.lowpt_edge = {}
|
| 317 |
+
|
| 318 |
+
self.left_ref = {}
|
| 319 |
+
self.right_ref = {}
|
| 320 |
+
|
| 321 |
+
self.embedding = PlanarEmbedding()
|
| 322 |
+
|
| 323 |
+
def lr_planarity(self):
|
| 324 |
+
"""Execute the LR planarity test.
|
| 325 |
+
|
| 326 |
+
Returns
|
| 327 |
+
-------
|
| 328 |
+
embedding : dict
|
| 329 |
+
If the graph is planar an embedding is returned. Otherwise None.
|
| 330 |
+
"""
|
| 331 |
+
if self.G.order() > 2 and self.G.size() > 3 * self.G.order() - 6:
|
| 332 |
+
# graph is not planar
|
| 333 |
+
return None
|
| 334 |
+
|
| 335 |
+
# make adjacency lists for dfs
|
| 336 |
+
for v in self.G:
|
| 337 |
+
self.adjs[v] = list(self.G[v])
|
| 338 |
+
|
| 339 |
+
# orientation of the graph by depth first search traversal
|
| 340 |
+
for v in self.G:
|
| 341 |
+
if self.height[v] is None:
|
| 342 |
+
self.height[v] = 0
|
| 343 |
+
self.roots.append(v)
|
| 344 |
+
self.dfs_orientation(v)
|
| 345 |
+
|
| 346 |
+
# Free no longer used variables
|
| 347 |
+
self.G = None
|
| 348 |
+
self.lowpt2 = None
|
| 349 |
+
self.adjs = None
|
| 350 |
+
|
| 351 |
+
# testing
|
| 352 |
+
for v in self.DG: # sort the adjacency lists by nesting depth
|
| 353 |
+
# note: this sorting leads to non linear time
|
| 354 |
+
self.ordered_adjs[v] = sorted(
|
| 355 |
+
self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
|
| 356 |
+
)
|
| 357 |
+
for v in self.roots:
|
| 358 |
+
if not self.dfs_testing(v):
|
| 359 |
+
return None
|
| 360 |
+
|
| 361 |
+
# Free no longer used variables
|
| 362 |
+
self.height = None
|
| 363 |
+
self.lowpt = None
|
| 364 |
+
self.S = None
|
| 365 |
+
self.stack_bottom = None
|
| 366 |
+
self.lowpt_edge = None
|
| 367 |
+
|
| 368 |
+
for e in self.DG.edges:
|
| 369 |
+
self.nesting_depth[e] = self.sign(e) * self.nesting_depth[e]
|
| 370 |
+
|
| 371 |
+
self.embedding.add_nodes_from(self.DG.nodes)
|
| 372 |
+
for v in self.DG:
|
| 373 |
+
# sort the adjacency lists again
|
| 374 |
+
self.ordered_adjs[v] = sorted(
|
| 375 |
+
self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
|
| 376 |
+
)
|
| 377 |
+
# initialize the embedding
|
| 378 |
+
previous_node = None
|
| 379 |
+
for w in self.ordered_adjs[v]:
|
| 380 |
+
self.embedding.add_half_edge(v, w, ccw=previous_node)
|
| 381 |
+
previous_node = w
|
| 382 |
+
|
| 383 |
+
# Free no longer used variables
|
| 384 |
+
self.DG = None
|
| 385 |
+
self.nesting_depth = None
|
| 386 |
+
self.ref = None
|
| 387 |
+
|
| 388 |
+
# compute the complete embedding
|
| 389 |
+
for v in self.roots:
|
| 390 |
+
self.dfs_embedding(v)
|
| 391 |
+
|
| 392 |
+
# Free no longer used variables
|
| 393 |
+
self.roots = None
|
| 394 |
+
self.parent_edge = None
|
| 395 |
+
self.ordered_adjs = None
|
| 396 |
+
self.left_ref = None
|
| 397 |
+
self.right_ref = None
|
| 398 |
+
self.side = None
|
| 399 |
+
|
| 400 |
+
return self.embedding
|
| 401 |
+
|
| 402 |
+
def lr_planarity_recursive(self):
|
| 403 |
+
"""Recursive version of :meth:`lr_planarity`."""
|
| 404 |
+
if self.G.order() > 2 and self.G.size() > 3 * self.G.order() - 6:
|
| 405 |
+
# graph is not planar
|
| 406 |
+
return None
|
| 407 |
+
|
| 408 |
+
# orientation of the graph by depth first search traversal
|
| 409 |
+
for v in self.G:
|
| 410 |
+
if self.height[v] is None:
|
| 411 |
+
self.height[v] = 0
|
| 412 |
+
self.roots.append(v)
|
| 413 |
+
self.dfs_orientation_recursive(v)
|
| 414 |
+
|
| 415 |
+
# Free no longer used variable
|
| 416 |
+
self.G = None
|
| 417 |
+
|
| 418 |
+
# testing
|
| 419 |
+
for v in self.DG: # sort the adjacency lists by nesting depth
|
| 420 |
+
# note: this sorting leads to non linear time
|
| 421 |
+
self.ordered_adjs[v] = sorted(
|
| 422 |
+
self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
|
| 423 |
+
)
|
| 424 |
+
for v in self.roots:
|
| 425 |
+
if not self.dfs_testing_recursive(v):
|
| 426 |
+
return None
|
| 427 |
+
|
| 428 |
+
for e in self.DG.edges:
|
| 429 |
+
self.nesting_depth[e] = self.sign_recursive(e) * self.nesting_depth[e]
|
| 430 |
+
|
| 431 |
+
self.embedding.add_nodes_from(self.DG.nodes)
|
| 432 |
+
for v in self.DG:
|
| 433 |
+
# sort the adjacency lists again
|
| 434 |
+
self.ordered_adjs[v] = sorted(
|
| 435 |
+
self.DG[v], key=lambda x: self.nesting_depth[(v, x)]
|
| 436 |
+
)
|
| 437 |
+
# initialize the embedding
|
| 438 |
+
previous_node = None
|
| 439 |
+
for w in self.ordered_adjs[v]:
|
| 440 |
+
self.embedding.add_half_edge(v, w, ccw=previous_node)
|
| 441 |
+
previous_node = w
|
| 442 |
+
|
| 443 |
+
# compute the complete embedding
|
| 444 |
+
for v in self.roots:
|
| 445 |
+
self.dfs_embedding_recursive(v)
|
| 446 |
+
|
| 447 |
+
return self.embedding
|
| 448 |
+
|
| 449 |
+
def dfs_orientation(self, v):
|
| 450 |
+
"""Orient the graph by DFS, compute lowpoints and nesting order."""
|
| 451 |
+
# the recursion stack
|
| 452 |
+
dfs_stack = [v]
|
| 453 |
+
# index of next edge to handle in adjacency list of each node
|
| 454 |
+
ind = defaultdict(lambda: 0)
|
| 455 |
+
# boolean to indicate whether to skip the initial work for an edge
|
| 456 |
+
skip_init = defaultdict(lambda: False)
|
| 457 |
+
|
| 458 |
+
while dfs_stack:
|
| 459 |
+
v = dfs_stack.pop()
|
| 460 |
+
e = self.parent_edge[v]
|
| 461 |
+
|
| 462 |
+
for w in self.adjs[v][ind[v] :]:
|
| 463 |
+
vw = (v, w)
|
| 464 |
+
|
| 465 |
+
if not skip_init[vw]:
|
| 466 |
+
if (v, w) in self.DG.edges or (w, v) in self.DG.edges:
|
| 467 |
+
ind[v] += 1
|
| 468 |
+
continue # the edge was already oriented
|
| 469 |
+
|
| 470 |
+
self.DG.add_edge(v, w) # orient the edge
|
| 471 |
+
|
| 472 |
+
self.lowpt[vw] = self.height[v]
|
| 473 |
+
self.lowpt2[vw] = self.height[v]
|
| 474 |
+
if self.height[w] is None: # (v, w) is a tree edge
|
| 475 |
+
self.parent_edge[w] = vw
|
| 476 |
+
self.height[w] = self.height[v] + 1
|
| 477 |
+
|
| 478 |
+
dfs_stack.append(v) # revisit v after finishing w
|
| 479 |
+
dfs_stack.append(w) # visit w next
|
| 480 |
+
skip_init[vw] = True # don't redo this block
|
| 481 |
+
break # handle next node in dfs_stack (i.e. w)
|
| 482 |
+
else: # (v, w) is a back edge
|
| 483 |
+
self.lowpt[vw] = self.height[w]
|
| 484 |
+
|
| 485 |
+
# determine nesting graph
|
| 486 |
+
self.nesting_depth[vw] = 2 * self.lowpt[vw]
|
| 487 |
+
if self.lowpt2[vw] < self.height[v]: # chordal
|
| 488 |
+
self.nesting_depth[vw] += 1
|
| 489 |
+
|
| 490 |
+
# update lowpoints of parent edge e
|
| 491 |
+
if e is not None:
|
| 492 |
+
if self.lowpt[vw] < self.lowpt[e]:
|
| 493 |
+
self.lowpt2[e] = min(self.lowpt[e], self.lowpt2[vw])
|
| 494 |
+
self.lowpt[e] = self.lowpt[vw]
|
| 495 |
+
elif self.lowpt[vw] > self.lowpt[e]:
|
| 496 |
+
self.lowpt2[e] = min(self.lowpt2[e], self.lowpt[vw])
|
| 497 |
+
else:
|
| 498 |
+
self.lowpt2[e] = min(self.lowpt2[e], self.lowpt2[vw])
|
| 499 |
+
|
| 500 |
+
ind[v] += 1
|
| 501 |
+
|
| 502 |
+
def dfs_orientation_recursive(self, v):
|
| 503 |
+
"""Recursive version of :meth:`dfs_orientation`."""
|
| 504 |
+
e = self.parent_edge[v]
|
| 505 |
+
for w in self.G[v]:
|
| 506 |
+
if (v, w) in self.DG.edges or (w, v) in self.DG.edges:
|
| 507 |
+
continue # the edge was already oriented
|
| 508 |
+
vw = (v, w)
|
| 509 |
+
self.DG.add_edge(v, w) # orient the edge
|
| 510 |
+
|
| 511 |
+
self.lowpt[vw] = self.height[v]
|
| 512 |
+
self.lowpt2[vw] = self.height[v]
|
| 513 |
+
if self.height[w] is None: # (v, w) is a tree edge
|
| 514 |
+
self.parent_edge[w] = vw
|
| 515 |
+
self.height[w] = self.height[v] + 1
|
| 516 |
+
self.dfs_orientation_recursive(w)
|
| 517 |
+
else: # (v, w) is a back edge
|
| 518 |
+
self.lowpt[vw] = self.height[w]
|
| 519 |
+
|
| 520 |
+
# determine nesting graph
|
| 521 |
+
self.nesting_depth[vw] = 2 * self.lowpt[vw]
|
| 522 |
+
if self.lowpt2[vw] < self.height[v]: # chordal
|
| 523 |
+
self.nesting_depth[vw] += 1
|
| 524 |
+
|
| 525 |
+
# update lowpoints of parent edge e
|
| 526 |
+
if e is not None:
|
| 527 |
+
if self.lowpt[vw] < self.lowpt[e]:
|
| 528 |
+
self.lowpt2[e] = min(self.lowpt[e], self.lowpt2[vw])
|
| 529 |
+
self.lowpt[e] = self.lowpt[vw]
|
| 530 |
+
elif self.lowpt[vw] > self.lowpt[e]:
|
| 531 |
+
self.lowpt2[e] = min(self.lowpt2[e], self.lowpt[vw])
|
| 532 |
+
else:
|
| 533 |
+
self.lowpt2[e] = min(self.lowpt2[e], self.lowpt2[vw])
|
| 534 |
+
|
| 535 |
+
def dfs_testing(self, v):
|
| 536 |
+
"""Test for LR partition."""
|
| 537 |
+
# the recursion stack
|
| 538 |
+
dfs_stack = [v]
|
| 539 |
+
# index of next edge to handle in adjacency list of each node
|
| 540 |
+
ind = defaultdict(lambda: 0)
|
| 541 |
+
# boolean to indicate whether to skip the initial work for an edge
|
| 542 |
+
skip_init = defaultdict(lambda: False)
|
| 543 |
+
|
| 544 |
+
while dfs_stack:
|
| 545 |
+
v = dfs_stack.pop()
|
| 546 |
+
e = self.parent_edge[v]
|
| 547 |
+
# to indicate whether to skip the final block after the for loop
|
| 548 |
+
skip_final = False
|
| 549 |
+
|
| 550 |
+
for w in self.ordered_adjs[v][ind[v] :]:
|
| 551 |
+
ei = (v, w)
|
| 552 |
+
|
| 553 |
+
if not skip_init[ei]:
|
| 554 |
+
self.stack_bottom[ei] = top_of_stack(self.S)
|
| 555 |
+
|
| 556 |
+
if ei == self.parent_edge[w]: # tree edge
|
| 557 |
+
dfs_stack.append(v) # revisit v after finishing w
|
| 558 |
+
dfs_stack.append(w) # visit w next
|
| 559 |
+
skip_init[ei] = True # don't redo this block
|
| 560 |
+
skip_final = True # skip final work after breaking
|
| 561 |
+
break # handle next node in dfs_stack (i.e. w)
|
| 562 |
+
else: # back edge
|
| 563 |
+
self.lowpt_edge[ei] = ei
|
| 564 |
+
self.S.append(ConflictPair(right=Interval(ei, ei)))
|
| 565 |
+
|
| 566 |
+
# integrate new return edges
|
| 567 |
+
if self.lowpt[ei] < self.height[v]:
|
| 568 |
+
if w == self.ordered_adjs[v][0]: # e_i has return edge
|
| 569 |
+
self.lowpt_edge[e] = self.lowpt_edge[ei]
|
| 570 |
+
else: # add constraints of e_i
|
| 571 |
+
if not self.add_constraints(ei, e):
|
| 572 |
+
# graph is not planar
|
| 573 |
+
return False
|
| 574 |
+
|
| 575 |
+
ind[v] += 1
|
| 576 |
+
|
| 577 |
+
if not skip_final:
|
| 578 |
+
# remove back edges returning to parent
|
| 579 |
+
if e is not None: # v isn't root
|
| 580 |
+
self.remove_back_edges(e)
|
| 581 |
+
|
| 582 |
+
return True
|
| 583 |
+
|
| 584 |
+
def dfs_testing_recursive(self, v):
|
| 585 |
+
"""Recursive version of :meth:`dfs_testing`."""
|
| 586 |
+
e = self.parent_edge[v]
|
| 587 |
+
for w in self.ordered_adjs[v]:
|
| 588 |
+
ei = (v, w)
|
| 589 |
+
self.stack_bottom[ei] = top_of_stack(self.S)
|
| 590 |
+
if ei == self.parent_edge[w]: # tree edge
|
| 591 |
+
if not self.dfs_testing_recursive(w):
|
| 592 |
+
return False
|
| 593 |
+
else: # back edge
|
| 594 |
+
self.lowpt_edge[ei] = ei
|
| 595 |
+
self.S.append(ConflictPair(right=Interval(ei, ei)))
|
| 596 |
+
|
| 597 |
+
# integrate new return edges
|
| 598 |
+
if self.lowpt[ei] < self.height[v]:
|
| 599 |
+
if w == self.ordered_adjs[v][0]: # e_i has return edge
|
| 600 |
+
self.lowpt_edge[e] = self.lowpt_edge[ei]
|
| 601 |
+
else: # add constraints of e_i
|
| 602 |
+
if not self.add_constraints(ei, e):
|
| 603 |
+
# graph is not planar
|
| 604 |
+
return False
|
| 605 |
+
|
| 606 |
+
# remove back edges returning to parent
|
| 607 |
+
if e is not None: # v isn't root
|
| 608 |
+
self.remove_back_edges(e)
|
| 609 |
+
return True
|
| 610 |
+
|
| 611 |
+
def add_constraints(self, ei, e):
|
| 612 |
+
P = ConflictPair()
|
| 613 |
+
# merge return edges of e_i into P.right
|
| 614 |
+
while True:
|
| 615 |
+
Q = self.S.pop()
|
| 616 |
+
if not Q.left.empty():
|
| 617 |
+
Q.swap()
|
| 618 |
+
if not Q.left.empty(): # not planar
|
| 619 |
+
return False
|
| 620 |
+
if self.lowpt[Q.right.low] > self.lowpt[e]:
|
| 621 |
+
# merge intervals
|
| 622 |
+
if P.right.empty(): # topmost interval
|
| 623 |
+
P.right = Q.right.copy()
|
| 624 |
+
else:
|
| 625 |
+
self.ref[P.right.low] = Q.right.high
|
| 626 |
+
P.right.low = Q.right.low
|
| 627 |
+
else: # align
|
| 628 |
+
self.ref[Q.right.low] = self.lowpt_edge[e]
|
| 629 |
+
if top_of_stack(self.S) == self.stack_bottom[ei]:
|
| 630 |
+
break
|
| 631 |
+
# merge conflicting return edges of e_1,...,e_i-1 into P.L
|
| 632 |
+
while top_of_stack(self.S).left.conflicting(ei, self) or top_of_stack(
|
| 633 |
+
self.S
|
| 634 |
+
).right.conflicting(ei, self):
|
| 635 |
+
Q = self.S.pop()
|
| 636 |
+
if Q.right.conflicting(ei, self):
|
| 637 |
+
Q.swap()
|
| 638 |
+
if Q.right.conflicting(ei, self): # not planar
|
| 639 |
+
return False
|
| 640 |
+
# merge interval below lowpt(e_i) into P.R
|
| 641 |
+
self.ref[P.right.low] = Q.right.high
|
| 642 |
+
if Q.right.low is not None:
|
| 643 |
+
P.right.low = Q.right.low
|
| 644 |
+
|
| 645 |
+
if P.left.empty(): # topmost interval
|
| 646 |
+
P.left = Q.left.copy()
|
| 647 |
+
else:
|
| 648 |
+
self.ref[P.left.low] = Q.left.high
|
| 649 |
+
P.left.low = Q.left.low
|
| 650 |
+
|
| 651 |
+
if not (P.left.empty() and P.right.empty()):
|
| 652 |
+
self.S.append(P)
|
| 653 |
+
return True
|
| 654 |
+
|
| 655 |
+
def remove_back_edges(self, e):
|
| 656 |
+
u = e[0]
|
| 657 |
+
# trim back edges ending at parent u
|
| 658 |
+
# drop entire conflict pairs
|
| 659 |
+
while self.S and top_of_stack(self.S).lowest(self) == self.height[u]:
|
| 660 |
+
P = self.S.pop()
|
| 661 |
+
if P.left.low is not None:
|
| 662 |
+
self.side[P.left.low] = -1
|
| 663 |
+
|
| 664 |
+
if self.S: # one more conflict pair to consider
|
| 665 |
+
P = self.S.pop()
|
| 666 |
+
# trim left interval
|
| 667 |
+
while P.left.high is not None and P.left.high[1] == u:
|
| 668 |
+
P.left.high = self.ref[P.left.high]
|
| 669 |
+
if P.left.high is None and P.left.low is not None:
|
| 670 |
+
# just emptied
|
| 671 |
+
self.ref[P.left.low] = P.right.low
|
| 672 |
+
self.side[P.left.low] = -1
|
| 673 |
+
P.left.low = None
|
| 674 |
+
# trim right interval
|
| 675 |
+
while P.right.high is not None and P.right.high[1] == u:
|
| 676 |
+
P.right.high = self.ref[P.right.high]
|
| 677 |
+
if P.right.high is None and P.right.low is not None:
|
| 678 |
+
# just emptied
|
| 679 |
+
self.ref[P.right.low] = P.left.low
|
| 680 |
+
self.side[P.right.low] = -1
|
| 681 |
+
P.right.low = None
|
| 682 |
+
self.S.append(P)
|
| 683 |
+
|
| 684 |
+
# side of e is side of a highest return edge
|
| 685 |
+
if self.lowpt[e] < self.height[u]: # e has return edge
|
| 686 |
+
hl = top_of_stack(self.S).left.high
|
| 687 |
+
hr = top_of_stack(self.S).right.high
|
| 688 |
+
|
| 689 |
+
if hl is not None and (hr is None or self.lowpt[hl] > self.lowpt[hr]):
|
| 690 |
+
self.ref[e] = hl
|
| 691 |
+
else:
|
| 692 |
+
self.ref[e] = hr
|
| 693 |
+
|
| 694 |
+
def dfs_embedding(self, v):
|
| 695 |
+
"""Completes the embedding."""
|
| 696 |
+
# the recursion stack
|
| 697 |
+
dfs_stack = [v]
|
| 698 |
+
# index of next edge to handle in adjacency list of each node
|
| 699 |
+
ind = defaultdict(lambda: 0)
|
| 700 |
+
|
| 701 |
+
while dfs_stack:
|
| 702 |
+
v = dfs_stack.pop()
|
| 703 |
+
|
| 704 |
+
for w in self.ordered_adjs[v][ind[v] :]:
|
| 705 |
+
ind[v] += 1
|
| 706 |
+
ei = (v, w)
|
| 707 |
+
|
| 708 |
+
if ei == self.parent_edge[w]: # tree edge
|
| 709 |
+
self.embedding.add_half_edge_first(w, v)
|
| 710 |
+
self.left_ref[v] = w
|
| 711 |
+
self.right_ref[v] = w
|
| 712 |
+
|
| 713 |
+
dfs_stack.append(v) # revisit v after finishing w
|
| 714 |
+
dfs_stack.append(w) # visit w next
|
| 715 |
+
break # handle next node in dfs_stack (i.e. w)
|
| 716 |
+
else: # back edge
|
| 717 |
+
if self.side[ei] == 1:
|
| 718 |
+
self.embedding.add_half_edge(w, v, ccw=self.right_ref[w])
|
| 719 |
+
else:
|
| 720 |
+
self.embedding.add_half_edge(w, v, cw=self.left_ref[w])
|
| 721 |
+
self.left_ref[w] = v
|
| 722 |
+
|
| 723 |
+
def dfs_embedding_recursive(self, v):
|
| 724 |
+
"""Recursive version of :meth:`dfs_embedding`."""
|
| 725 |
+
for w in self.ordered_adjs[v]:
|
| 726 |
+
ei = (v, w)
|
| 727 |
+
if ei == self.parent_edge[w]: # tree edge
|
| 728 |
+
self.embedding.add_half_edge_first(w, v)
|
| 729 |
+
self.left_ref[v] = w
|
| 730 |
+
self.right_ref[v] = w
|
| 731 |
+
self.dfs_embedding_recursive(w)
|
| 732 |
+
else: # back edge
|
| 733 |
+
if self.side[ei] == 1:
|
| 734 |
+
# place v directly after right_ref[w] in embed. list of w
|
| 735 |
+
self.embedding.add_half_edge(w, v, ccw=self.right_ref[w])
|
| 736 |
+
else:
|
| 737 |
+
# place v directly before left_ref[w] in embed. list of w
|
| 738 |
+
self.embedding.add_half_edge(w, v, cw=self.left_ref[w])
|
| 739 |
+
self.left_ref[w] = v
|
| 740 |
+
|
| 741 |
+
def sign(self, e):
|
| 742 |
+
"""Resolve the relative side of an edge to the absolute side."""
|
| 743 |
+
# the recursion stack
|
| 744 |
+
dfs_stack = [e]
|
| 745 |
+
# dict to remember reference edges
|
| 746 |
+
old_ref = defaultdict(lambda: None)
|
| 747 |
+
|
| 748 |
+
while dfs_stack:
|
| 749 |
+
e = dfs_stack.pop()
|
| 750 |
+
|
| 751 |
+
if self.ref[e] is not None:
|
| 752 |
+
dfs_stack.append(e) # revisit e after finishing self.ref[e]
|
| 753 |
+
dfs_stack.append(self.ref[e]) # visit self.ref[e] next
|
| 754 |
+
old_ref[e] = self.ref[e] # remember value of self.ref[e]
|
| 755 |
+
self.ref[e] = None
|
| 756 |
+
else:
|
| 757 |
+
self.side[e] *= self.side[old_ref[e]]
|
| 758 |
+
|
| 759 |
+
return self.side[e]
|
| 760 |
+
|
| 761 |
+
def sign_recursive(self, e):
|
| 762 |
+
"""Recursive version of :meth:`sign`."""
|
| 763 |
+
if self.ref[e] is not None:
|
| 764 |
+
self.side[e] = self.side[e] * self.sign_recursive(self.ref[e])
|
| 765 |
+
self.ref[e] = None
|
| 766 |
+
return self.side[e]
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
class PlanarEmbedding(nx.DiGraph):
|
| 770 |
+
"""Represents a planar graph with its planar embedding.
|
| 771 |
+
|
| 772 |
+
The planar embedding is given by a `combinatorial embedding
|
| 773 |
+
<https://en.wikipedia.org/wiki/Graph_embedding#Combinatorial_embedding>`_.
|
| 774 |
+
|
| 775 |
+
.. note:: `check_planarity` is the preferred way to check if a graph is planar.
|
| 776 |
+
|
| 777 |
+
**Neighbor ordering:**
|
| 778 |
+
|
| 779 |
+
In comparison to a usual graph structure, the embedding also stores the
|
| 780 |
+
order of all neighbors for every vertex.
|
| 781 |
+
The order of the neighbors can be given in clockwise (cw) direction or
|
| 782 |
+
counterclockwise (ccw) direction. This order is stored as edge attributes
|
| 783 |
+
in the underlying directed graph. For the edge (u, v) the edge attribute
|
| 784 |
+
'cw' is set to the neighbor of u that follows immediately after v in
|
| 785 |
+
clockwise direction.
|
| 786 |
+
|
| 787 |
+
In order for a PlanarEmbedding to be valid it must fulfill multiple
|
| 788 |
+
conditions. It is possible to check if these conditions are fulfilled with
|
| 789 |
+
the method :meth:`check_structure`.
|
| 790 |
+
The conditions are:
|
| 791 |
+
|
| 792 |
+
* Edges must go in both directions (because the edge attributes differ)
|
| 793 |
+
* Every edge must have a 'cw' and 'ccw' attribute which corresponds to a
|
| 794 |
+
correct planar embedding.
|
| 795 |
+
|
| 796 |
+
As long as a PlanarEmbedding is invalid only the following methods should
|
| 797 |
+
be called:
|
| 798 |
+
|
| 799 |
+
* :meth:`add_half_edge`
|
| 800 |
+
* :meth:`connect_components`
|
| 801 |
+
|
| 802 |
+
Even though the graph is a subclass of nx.DiGraph, it can still be used
|
| 803 |
+
for algorithms that require undirected graphs, because the method
|
| 804 |
+
:meth:`is_directed` is overridden. This is possible, because a valid
|
| 805 |
+
PlanarGraph must have edges in both directions.
|
| 806 |
+
|
| 807 |
+
**Half edges:**
|
| 808 |
+
|
| 809 |
+
In methods like `add_half_edge` the term "half-edge" is used, which is
|
| 810 |
+
a term that is used in `doubly connected edge lists
|
| 811 |
+
<https://en.wikipedia.org/wiki/Doubly_connected_edge_list>`_. It is used
|
| 812 |
+
to emphasize that the edge is only in one direction and there exists
|
| 813 |
+
another half-edge in the opposite direction.
|
| 814 |
+
While conventional edges always have two faces (including outer face) next
|
| 815 |
+
to them, it is possible to assign each half-edge *exactly one* face.
|
| 816 |
+
For a half-edge (u, v) that is oriented such that u is below v then the
|
| 817 |
+
face that belongs to (u, v) is to the right of this half-edge.
|
| 818 |
+
|
| 819 |
+
See Also
|
| 820 |
+
--------
|
| 821 |
+
is_planar :
|
| 822 |
+
Preferred way to check if an existing graph is planar.
|
| 823 |
+
|
| 824 |
+
check_planarity :
|
| 825 |
+
A convenient way to create a `PlanarEmbedding`. If not planar,
|
| 826 |
+
it returns a subgraph that shows this.
|
| 827 |
+
|
| 828 |
+
Examples
|
| 829 |
+
--------
|
| 830 |
+
|
| 831 |
+
Create an embedding of a star graph (compare `nx.star_graph(3)`):
|
| 832 |
+
|
| 833 |
+
>>> G = nx.PlanarEmbedding()
|
| 834 |
+
>>> G.add_half_edge(0, 1)
|
| 835 |
+
>>> G.add_half_edge(0, 2, ccw=1)
|
| 836 |
+
>>> G.add_half_edge(0, 3, ccw=2)
|
| 837 |
+
>>> G.add_half_edge(1, 0)
|
| 838 |
+
>>> G.add_half_edge(2, 0)
|
| 839 |
+
>>> G.add_half_edge(3, 0)
|
| 840 |
+
|
| 841 |
+
Alternatively the same embedding can also be defined in counterclockwise
|
| 842 |
+
orientation. The following results in exactly the same PlanarEmbedding:
|
| 843 |
+
|
| 844 |
+
>>> G = nx.PlanarEmbedding()
|
| 845 |
+
>>> G.add_half_edge(0, 1)
|
| 846 |
+
>>> G.add_half_edge(0, 3, cw=1)
|
| 847 |
+
>>> G.add_half_edge(0, 2, cw=3)
|
| 848 |
+
>>> G.add_half_edge(1, 0)
|
| 849 |
+
>>> G.add_half_edge(2, 0)
|
| 850 |
+
>>> G.add_half_edge(3, 0)
|
| 851 |
+
|
| 852 |
+
After creating a graph, it is possible to validate that the PlanarEmbedding
|
| 853 |
+
object is correct:
|
| 854 |
+
|
| 855 |
+
>>> G.check_structure()
|
| 856 |
+
|
| 857 |
+
"""
|
| 858 |
+
|
| 859 |
+
def __init__(self, incoming_graph_data=None, **attr):
|
| 860 |
+
super().__init__(incoming_graph_data=incoming_graph_data, **attr)
|
| 861 |
+
self.add_edge = self._forbidden
|
| 862 |
+
self.add_edges_from = self._forbidden
|
| 863 |
+
self.add_weighted_edges_from = self._forbidden
|
| 864 |
+
|
| 865 |
+
def _forbidden(self, *args, **kwargs):
|
| 866 |
+
"""Forbidden operation
|
| 867 |
+
|
| 868 |
+
Any edge additions to a PlanarEmbedding should be done using
|
| 869 |
+
method `add_half_edge`.
|
| 870 |
+
"""
|
| 871 |
+
raise NotImplementedError(
|
| 872 |
+
"Use `add_half_edge` method to add edges to a PlanarEmbedding."
|
| 873 |
+
)
|
| 874 |
+
|
| 875 |
+
def get_data(self):
|
| 876 |
+
"""Converts the adjacency structure into a better readable structure.
|
| 877 |
+
|
| 878 |
+
Returns
|
| 879 |
+
-------
|
| 880 |
+
embedding : dict
|
| 881 |
+
A dict mapping all nodes to a list of neighbors sorted in
|
| 882 |
+
clockwise order.
|
| 883 |
+
|
| 884 |
+
See Also
|
| 885 |
+
--------
|
| 886 |
+
set_data
|
| 887 |
+
|
| 888 |
+
"""
|
| 889 |
+
embedding = {}
|
| 890 |
+
for v in self:
|
| 891 |
+
embedding[v] = list(self.neighbors_cw_order(v))
|
| 892 |
+
return embedding
|
| 893 |
+
|
| 894 |
+
def set_data(self, data):
|
| 895 |
+
"""Inserts edges according to given sorted neighbor list.
|
| 896 |
+
|
| 897 |
+
The input format is the same as the output format of get_data().
|
| 898 |
+
|
| 899 |
+
Parameters
|
| 900 |
+
----------
|
| 901 |
+
data : dict
|
| 902 |
+
A dict mapping all nodes to a list of neighbors sorted in
|
| 903 |
+
clockwise order.
|
| 904 |
+
|
| 905 |
+
See Also
|
| 906 |
+
--------
|
| 907 |
+
get_data
|
| 908 |
+
|
| 909 |
+
"""
|
| 910 |
+
for v in data:
|
| 911 |
+
ref = None
|
| 912 |
+
for w in reversed(data[v]):
|
| 913 |
+
self.add_half_edge(v, w, cw=ref)
|
| 914 |
+
ref = w
|
| 915 |
+
|
| 916 |
+
def remove_node(self, n):
|
| 917 |
+
"""Remove node n.
|
| 918 |
+
|
| 919 |
+
Removes the node n and all adjacent edges, updating the
|
| 920 |
+
PlanarEmbedding to account for any resulting edge removal.
|
| 921 |
+
Attempting to remove a non-existent node will raise an exception.
|
| 922 |
+
|
| 923 |
+
Parameters
|
| 924 |
+
----------
|
| 925 |
+
n : node
|
| 926 |
+
A node in the graph
|
| 927 |
+
|
| 928 |
+
Raises
|
| 929 |
+
------
|
| 930 |
+
NetworkXError
|
| 931 |
+
If n is not in the graph.
|
| 932 |
+
|
| 933 |
+
See Also
|
| 934 |
+
--------
|
| 935 |
+
remove_nodes_from
|
| 936 |
+
|
| 937 |
+
"""
|
| 938 |
+
try:
|
| 939 |
+
for u in self._pred[n]:
|
| 940 |
+
succs_u = self._succ[u]
|
| 941 |
+
un_cw = succs_u[n]["cw"]
|
| 942 |
+
un_ccw = succs_u[n]["ccw"]
|
| 943 |
+
del succs_u[n]
|
| 944 |
+
del self._pred[u][n]
|
| 945 |
+
if n != un_cw:
|
| 946 |
+
succs_u[un_cw]["ccw"] = un_ccw
|
| 947 |
+
succs_u[un_ccw]["cw"] = un_cw
|
| 948 |
+
del self._node[n]
|
| 949 |
+
del self._succ[n]
|
| 950 |
+
del self._pred[n]
|
| 951 |
+
except KeyError as err: # NetworkXError if n not in self
|
| 952 |
+
raise nx.NetworkXError(
|
| 953 |
+
f"The node {n} is not in the planar embedding."
|
| 954 |
+
) from err
|
| 955 |
+
nx._clear_cache(self)
|
| 956 |
+
|
| 957 |
+
def remove_nodes_from(self, nodes):
|
| 958 |
+
"""Remove multiple nodes.
|
| 959 |
+
|
| 960 |
+
Parameters
|
| 961 |
+
----------
|
| 962 |
+
nodes : iterable container
|
| 963 |
+
A container of nodes (list, dict, set, etc.). If a node
|
| 964 |
+
in the container is not in the graph it is silently ignored.
|
| 965 |
+
|
| 966 |
+
See Also
|
| 967 |
+
--------
|
| 968 |
+
remove_node
|
| 969 |
+
|
| 970 |
+
Notes
|
| 971 |
+
-----
|
| 972 |
+
When removing nodes from an iterator over the graph you are changing,
|
| 973 |
+
a `RuntimeError` will be raised with message:
|
| 974 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
| 975 |
+
happens when the graph's underlying dictionary is modified during
|
| 976 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
| 977 |
+
object, e.g. by using `list(iterator_of_nodes)`, and pass this
|
| 978 |
+
object to `G.remove_nodes_from`.
|
| 979 |
+
|
| 980 |
+
"""
|
| 981 |
+
for n in nodes:
|
| 982 |
+
if n in self._node:
|
| 983 |
+
self.remove_node(n)
|
| 984 |
+
# silently skip non-existing nodes
|
| 985 |
+
|
| 986 |
+
def neighbors_cw_order(self, v):
|
| 987 |
+
"""Generator for the neighbors of v in clockwise order.
|
| 988 |
+
|
| 989 |
+
Parameters
|
| 990 |
+
----------
|
| 991 |
+
v : node
|
| 992 |
+
|
| 993 |
+
Yields
|
| 994 |
+
------
|
| 995 |
+
node
|
| 996 |
+
|
| 997 |
+
"""
|
| 998 |
+
succs = self._succ[v]
|
| 999 |
+
if not succs:
|
| 1000 |
+
# v has no neighbors
|
| 1001 |
+
return
|
| 1002 |
+
start_node = next(reversed(succs))
|
| 1003 |
+
yield start_node
|
| 1004 |
+
current_node = succs[start_node]["cw"]
|
| 1005 |
+
while start_node != current_node:
|
| 1006 |
+
yield current_node
|
| 1007 |
+
current_node = succs[current_node]["cw"]
|
| 1008 |
+
|
| 1009 |
+
def add_half_edge(self, start_node, end_node, *, cw=None, ccw=None):
|
| 1010 |
+
"""Adds a half-edge from `start_node` to `end_node`.
|
| 1011 |
+
|
| 1012 |
+
If the half-edge is not the first one out of `start_node`, a reference
|
| 1013 |
+
node must be provided either in the clockwise (parameter `cw`) or in
|
| 1014 |
+
the counterclockwise (parameter `ccw`) direction. Only one of `cw`/`ccw`
|
| 1015 |
+
can be specified (or neither in the case of the first edge).
|
| 1016 |
+
Note that specifying a reference in the clockwise (`cw`) direction means
|
| 1017 |
+
inserting the new edge in the first counterclockwise position with
|
| 1018 |
+
respect to the reference (and vice-versa).
|
| 1019 |
+
|
| 1020 |
+
Parameters
|
| 1021 |
+
----------
|
| 1022 |
+
start_node : node
|
| 1023 |
+
Start node of inserted edge.
|
| 1024 |
+
end_node : node
|
| 1025 |
+
End node of inserted edge.
|
| 1026 |
+
cw, ccw: node
|
| 1027 |
+
End node of reference edge.
|
| 1028 |
+
Omit or pass `None` if adding the first out-half-edge of `start_node`.
|
| 1029 |
+
|
| 1030 |
+
|
| 1031 |
+
Raises
|
| 1032 |
+
------
|
| 1033 |
+
NetworkXException
|
| 1034 |
+
If the `cw` or `ccw` node is not a successor of `start_node`.
|
| 1035 |
+
If `start_node` has successors, but neither `cw` or `ccw` is provided.
|
| 1036 |
+
If both `cw` and `ccw` are specified.
|
| 1037 |
+
|
| 1038 |
+
See Also
|
| 1039 |
+
--------
|
| 1040 |
+
connect_components
|
| 1041 |
+
"""
|
| 1042 |
+
|
| 1043 |
+
succs = self._succ.get(start_node)
|
| 1044 |
+
if succs:
|
| 1045 |
+
# there is already some edge out of start_node
|
| 1046 |
+
leftmost_nbr = next(reversed(self._succ[start_node]))
|
| 1047 |
+
if cw is not None:
|
| 1048 |
+
if cw not in succs:
|
| 1049 |
+
raise nx.NetworkXError("Invalid clockwise reference node.")
|
| 1050 |
+
if ccw is not None:
|
| 1051 |
+
raise nx.NetworkXError("Only one of cw/ccw can be specified.")
|
| 1052 |
+
ref_ccw = succs[cw]["ccw"]
|
| 1053 |
+
super().add_edge(start_node, end_node, cw=cw, ccw=ref_ccw)
|
| 1054 |
+
succs[ref_ccw]["cw"] = end_node
|
| 1055 |
+
succs[cw]["ccw"] = end_node
|
| 1056 |
+
# when (cw == leftmost_nbr), the newly added neighbor is
|
| 1057 |
+
# already at the end of dict self._succ[start_node] and
|
| 1058 |
+
# takes the place of the former leftmost_nbr
|
| 1059 |
+
move_leftmost_nbr_to_end = cw != leftmost_nbr
|
| 1060 |
+
elif ccw is not None:
|
| 1061 |
+
if ccw not in succs:
|
| 1062 |
+
raise nx.NetworkXError("Invalid counterclockwise reference node.")
|
| 1063 |
+
ref_cw = succs[ccw]["cw"]
|
| 1064 |
+
super().add_edge(start_node, end_node, cw=ref_cw, ccw=ccw)
|
| 1065 |
+
succs[ref_cw]["ccw"] = end_node
|
| 1066 |
+
succs[ccw]["cw"] = end_node
|
| 1067 |
+
move_leftmost_nbr_to_end = True
|
| 1068 |
+
else:
|
| 1069 |
+
raise nx.NetworkXError(
|
| 1070 |
+
"Node already has out-half-edge(s), either cw or ccw reference node required."
|
| 1071 |
+
)
|
| 1072 |
+
if move_leftmost_nbr_to_end:
|
| 1073 |
+
# LRPlanarity (via self.add_half_edge_first()) requires that
|
| 1074 |
+
# we keep track of the leftmost neighbor, which we accomplish
|
| 1075 |
+
# by keeping it as the last key in dict self._succ[start_node]
|
| 1076 |
+
succs[leftmost_nbr] = succs.pop(leftmost_nbr)
|
| 1077 |
+
|
| 1078 |
+
else:
|
| 1079 |
+
if cw is not None or ccw is not None:
|
| 1080 |
+
raise nx.NetworkXError("Invalid reference node.")
|
| 1081 |
+
# adding the first edge out of start_node
|
| 1082 |
+
super().add_edge(start_node, end_node, ccw=end_node, cw=end_node)
|
| 1083 |
+
|
| 1084 |
+
def check_structure(self):
|
| 1085 |
+
"""Runs without exceptions if this object is valid.
|
| 1086 |
+
|
| 1087 |
+
Checks that the following properties are fulfilled:
|
| 1088 |
+
|
| 1089 |
+
* Edges go in both directions (because the edge attributes differ).
|
| 1090 |
+
* Every edge has a 'cw' and 'ccw' attribute which corresponds to a
|
| 1091 |
+
correct planar embedding.
|
| 1092 |
+
|
| 1093 |
+
Running this method verifies that the underlying Graph must be planar.
|
| 1094 |
+
|
| 1095 |
+
Raises
|
| 1096 |
+
------
|
| 1097 |
+
NetworkXException
|
| 1098 |
+
This exception is raised with a short explanation if the
|
| 1099 |
+
PlanarEmbedding is invalid.
|
| 1100 |
+
"""
|
| 1101 |
+
# Check fundamental structure
|
| 1102 |
+
for v in self:
|
| 1103 |
+
try:
|
| 1104 |
+
sorted_nbrs = set(self.neighbors_cw_order(v))
|
| 1105 |
+
except KeyError as err:
|
| 1106 |
+
msg = f"Bad embedding. Missing orientation for a neighbor of {v}"
|
| 1107 |
+
raise nx.NetworkXException(msg) from err
|
| 1108 |
+
|
| 1109 |
+
unsorted_nbrs = set(self[v])
|
| 1110 |
+
if sorted_nbrs != unsorted_nbrs:
|
| 1111 |
+
msg = "Bad embedding. Edge orientations not set correctly."
|
| 1112 |
+
raise nx.NetworkXException(msg)
|
| 1113 |
+
for w in self[v]:
|
| 1114 |
+
# Check if opposite half-edge exists
|
| 1115 |
+
if not self.has_edge(w, v):
|
| 1116 |
+
msg = "Bad embedding. Opposite half-edge is missing."
|
| 1117 |
+
raise nx.NetworkXException(msg)
|
| 1118 |
+
|
| 1119 |
+
# Check planarity
|
| 1120 |
+
counted_half_edges = set()
|
| 1121 |
+
for component in nx.connected_components(self):
|
| 1122 |
+
if len(component) == 1:
|
| 1123 |
+
# Don't need to check single node component
|
| 1124 |
+
continue
|
| 1125 |
+
num_nodes = len(component)
|
| 1126 |
+
num_half_edges = 0
|
| 1127 |
+
num_faces = 0
|
| 1128 |
+
for v in component:
|
| 1129 |
+
for w in self.neighbors_cw_order(v):
|
| 1130 |
+
num_half_edges += 1
|
| 1131 |
+
if (v, w) not in counted_half_edges:
|
| 1132 |
+
# We encountered a new face
|
| 1133 |
+
num_faces += 1
|
| 1134 |
+
# Mark all half-edges belonging to this face
|
| 1135 |
+
self.traverse_face(v, w, counted_half_edges)
|
| 1136 |
+
num_edges = num_half_edges // 2 # num_half_edges is even
|
| 1137 |
+
if num_nodes - num_edges + num_faces != 2:
|
| 1138 |
+
# The result does not match Euler's formula
|
| 1139 |
+
msg = "Bad embedding. The graph does not match Euler's formula"
|
| 1140 |
+
raise nx.NetworkXException(msg)
|
| 1141 |
+
|
| 1142 |
+
def add_half_edge_ccw(self, start_node, end_node, reference_neighbor):
|
| 1143 |
+
"""Adds a half-edge from start_node to end_node.
|
| 1144 |
+
|
| 1145 |
+
The half-edge is added counter clockwise next to the existing half-edge
|
| 1146 |
+
(start_node, reference_neighbor).
|
| 1147 |
+
|
| 1148 |
+
Parameters
|
| 1149 |
+
----------
|
| 1150 |
+
start_node : node
|
| 1151 |
+
Start node of inserted edge.
|
| 1152 |
+
end_node : node
|
| 1153 |
+
End node of inserted edge.
|
| 1154 |
+
reference_neighbor: node
|
| 1155 |
+
End node of reference edge.
|
| 1156 |
+
|
| 1157 |
+
Raises
|
| 1158 |
+
------
|
| 1159 |
+
NetworkXException
|
| 1160 |
+
If the reference_neighbor does not exist.
|
| 1161 |
+
|
| 1162 |
+
See Also
|
| 1163 |
+
--------
|
| 1164 |
+
add_half_edge
|
| 1165 |
+
add_half_edge_cw
|
| 1166 |
+
connect_components
|
| 1167 |
+
|
| 1168 |
+
"""
|
| 1169 |
+
self.add_half_edge(start_node, end_node, cw=reference_neighbor)
|
| 1170 |
+
|
| 1171 |
+
def add_half_edge_cw(self, start_node, end_node, reference_neighbor):
|
| 1172 |
+
"""Adds a half-edge from start_node to end_node.
|
| 1173 |
+
|
| 1174 |
+
The half-edge is added clockwise next to the existing half-edge
|
| 1175 |
+
(start_node, reference_neighbor).
|
| 1176 |
+
|
| 1177 |
+
Parameters
|
| 1178 |
+
----------
|
| 1179 |
+
start_node : node
|
| 1180 |
+
Start node of inserted edge.
|
| 1181 |
+
end_node : node
|
| 1182 |
+
End node of inserted edge.
|
| 1183 |
+
reference_neighbor: node
|
| 1184 |
+
End node of reference edge.
|
| 1185 |
+
|
| 1186 |
+
Raises
|
| 1187 |
+
------
|
| 1188 |
+
NetworkXException
|
| 1189 |
+
If the reference_neighbor does not exist.
|
| 1190 |
+
|
| 1191 |
+
See Also
|
| 1192 |
+
--------
|
| 1193 |
+
add_half_edge
|
| 1194 |
+
add_half_edge_ccw
|
| 1195 |
+
connect_components
|
| 1196 |
+
"""
|
| 1197 |
+
self.add_half_edge(start_node, end_node, ccw=reference_neighbor)
|
| 1198 |
+
|
| 1199 |
+
def remove_edge(self, u, v):
|
| 1200 |
+
"""Remove the edge between u and v.
|
| 1201 |
+
|
| 1202 |
+
Parameters
|
| 1203 |
+
----------
|
| 1204 |
+
u, v : nodes
|
| 1205 |
+
Remove the half-edges (u, v) and (v, u) and update the
|
| 1206 |
+
edge ordering around the removed edge.
|
| 1207 |
+
|
| 1208 |
+
Raises
|
| 1209 |
+
------
|
| 1210 |
+
NetworkXError
|
| 1211 |
+
If there is not an edge between u and v.
|
| 1212 |
+
|
| 1213 |
+
See Also
|
| 1214 |
+
--------
|
| 1215 |
+
remove_edges_from : remove a collection of edges
|
| 1216 |
+
"""
|
| 1217 |
+
try:
|
| 1218 |
+
succs_u = self._succ[u]
|
| 1219 |
+
succs_v = self._succ[v]
|
| 1220 |
+
uv_cw = succs_u[v]["cw"]
|
| 1221 |
+
uv_ccw = succs_u[v]["ccw"]
|
| 1222 |
+
vu_cw = succs_v[u]["cw"]
|
| 1223 |
+
vu_ccw = succs_v[u]["ccw"]
|
| 1224 |
+
del succs_u[v]
|
| 1225 |
+
del self._pred[v][u]
|
| 1226 |
+
del succs_v[u]
|
| 1227 |
+
del self._pred[u][v]
|
| 1228 |
+
if v != uv_cw:
|
| 1229 |
+
succs_u[uv_cw]["ccw"] = uv_ccw
|
| 1230 |
+
succs_u[uv_ccw]["cw"] = uv_cw
|
| 1231 |
+
if u != vu_cw:
|
| 1232 |
+
succs_v[vu_cw]["ccw"] = vu_ccw
|
| 1233 |
+
succs_v[vu_ccw]["cw"] = vu_cw
|
| 1234 |
+
except KeyError as err:
|
| 1235 |
+
raise nx.NetworkXError(
|
| 1236 |
+
f"The edge {u}-{v} is not in the planar embedding."
|
| 1237 |
+
) from err
|
| 1238 |
+
nx._clear_cache(self)
|
| 1239 |
+
|
| 1240 |
+
def remove_edges_from(self, ebunch):
|
| 1241 |
+
"""Remove all edges specified in ebunch.
|
| 1242 |
+
|
| 1243 |
+
Parameters
|
| 1244 |
+
----------
|
| 1245 |
+
ebunch: list or container of edge tuples
|
| 1246 |
+
Each pair of half-edges between the nodes given in the tuples
|
| 1247 |
+
will be removed from the graph. The nodes can be passed as:
|
| 1248 |
+
|
| 1249 |
+
- 2-tuples (u, v) half-edges (u, v) and (v, u).
|
| 1250 |
+
- 3-tuples (u, v, k) where k is ignored.
|
| 1251 |
+
|
| 1252 |
+
See Also
|
| 1253 |
+
--------
|
| 1254 |
+
remove_edge : remove a single edge
|
| 1255 |
+
|
| 1256 |
+
Notes
|
| 1257 |
+
-----
|
| 1258 |
+
Will fail silently if an edge in ebunch is not in the graph.
|
| 1259 |
+
|
| 1260 |
+
Examples
|
| 1261 |
+
--------
|
| 1262 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
| 1263 |
+
>>> ebunch = [(1, 2), (2, 3)]
|
| 1264 |
+
>>> G.remove_edges_from(ebunch)
|
| 1265 |
+
"""
|
| 1266 |
+
for e in ebunch:
|
| 1267 |
+
u, v = e[:2] # ignore edge data
|
| 1268 |
+
# assuming that the PlanarEmbedding is valid, if the half_edge
|
| 1269 |
+
# (u, v) is in the graph, then so is half_edge (v, u)
|
| 1270 |
+
if u in self._succ and v in self._succ[u]:
|
| 1271 |
+
self.remove_edge(u, v)
|
| 1272 |
+
|
| 1273 |
+
def connect_components(self, v, w):
|
| 1274 |
+
"""Adds half-edges for (v, w) and (w, v) at some position.
|
| 1275 |
+
|
| 1276 |
+
This method should only be called if v and w are in different
|
| 1277 |
+
components, or it might break the embedding.
|
| 1278 |
+
This especially means that if `connect_components(v, w)`
|
| 1279 |
+
is called it is not allowed to call `connect_components(w, v)`
|
| 1280 |
+
afterwards. The neighbor orientations in both directions are
|
| 1281 |
+
all set correctly after the first call.
|
| 1282 |
+
|
| 1283 |
+
Parameters
|
| 1284 |
+
----------
|
| 1285 |
+
v : node
|
| 1286 |
+
w : node
|
| 1287 |
+
|
| 1288 |
+
See Also
|
| 1289 |
+
--------
|
| 1290 |
+
add_half_edge
|
| 1291 |
+
"""
|
| 1292 |
+
if v in self._succ and self._succ[v]:
|
| 1293 |
+
ref = next(reversed(self._succ[v]))
|
| 1294 |
+
else:
|
| 1295 |
+
ref = None
|
| 1296 |
+
self.add_half_edge(v, w, cw=ref)
|
| 1297 |
+
if w in self._succ and self._succ[w]:
|
| 1298 |
+
ref = next(reversed(self._succ[w]))
|
| 1299 |
+
else:
|
| 1300 |
+
ref = None
|
| 1301 |
+
self.add_half_edge(w, v, cw=ref)
|
| 1302 |
+
|
| 1303 |
+
def add_half_edge_first(self, start_node, end_node):
|
| 1304 |
+
"""Add a half-edge and set end_node as start_node's leftmost neighbor.
|
| 1305 |
+
|
| 1306 |
+
The new edge is inserted counterclockwise with respect to the current
|
| 1307 |
+
leftmost neighbor, if there is one.
|
| 1308 |
+
|
| 1309 |
+
Parameters
|
| 1310 |
+
----------
|
| 1311 |
+
start_node : node
|
| 1312 |
+
end_node : node
|
| 1313 |
+
|
| 1314 |
+
See Also
|
| 1315 |
+
--------
|
| 1316 |
+
add_half_edge
|
| 1317 |
+
connect_components
|
| 1318 |
+
"""
|
| 1319 |
+
succs = self._succ.get(start_node)
|
| 1320 |
+
# the leftmost neighbor is the last entry in the
|
| 1321 |
+
# self._succ[start_node] dict
|
| 1322 |
+
leftmost_nbr = next(reversed(succs)) if succs else None
|
| 1323 |
+
self.add_half_edge(start_node, end_node, cw=leftmost_nbr)
|
| 1324 |
+
|
| 1325 |
+
def next_face_half_edge(self, v, w):
|
| 1326 |
+
"""Returns the following half-edge left of a face.
|
| 1327 |
+
|
| 1328 |
+
Parameters
|
| 1329 |
+
----------
|
| 1330 |
+
v : node
|
| 1331 |
+
w : node
|
| 1332 |
+
|
| 1333 |
+
Returns
|
| 1334 |
+
-------
|
| 1335 |
+
half-edge : tuple
|
| 1336 |
+
"""
|
| 1337 |
+
new_node = self[w][v]["ccw"]
|
| 1338 |
+
return w, new_node
|
| 1339 |
+
|
| 1340 |
+
def traverse_face(self, v, w, mark_half_edges=None):
|
| 1341 |
+
"""Returns nodes on the face that belong to the half-edge (v, w).
|
| 1342 |
+
|
| 1343 |
+
The face that is traversed lies to the right of the half-edge (in an
|
| 1344 |
+
orientation where v is below w).
|
| 1345 |
+
|
| 1346 |
+
Optionally it is possible to pass a set to which all encountered half
|
| 1347 |
+
edges are added. Before calling this method, this set must not include
|
| 1348 |
+
any half-edges that belong to the face.
|
| 1349 |
+
|
| 1350 |
+
Parameters
|
| 1351 |
+
----------
|
| 1352 |
+
v : node
|
| 1353 |
+
Start node of half-edge.
|
| 1354 |
+
w : node
|
| 1355 |
+
End node of half-edge.
|
| 1356 |
+
mark_half_edges: set, optional
|
| 1357 |
+
Set to which all encountered half-edges are added.
|
| 1358 |
+
|
| 1359 |
+
Returns
|
| 1360 |
+
-------
|
| 1361 |
+
face : list
|
| 1362 |
+
A list of nodes that lie on this face.
|
| 1363 |
+
"""
|
| 1364 |
+
if mark_half_edges is None:
|
| 1365 |
+
mark_half_edges = set()
|
| 1366 |
+
|
| 1367 |
+
face_nodes = [v]
|
| 1368 |
+
mark_half_edges.add((v, w))
|
| 1369 |
+
prev_node = v
|
| 1370 |
+
cur_node = w
|
| 1371 |
+
# Last half-edge is (incoming_node, v)
|
| 1372 |
+
incoming_node = self[v][w]["cw"]
|
| 1373 |
+
|
| 1374 |
+
while cur_node != v or prev_node != incoming_node:
|
| 1375 |
+
face_nodes.append(cur_node)
|
| 1376 |
+
prev_node, cur_node = self.next_face_half_edge(prev_node, cur_node)
|
| 1377 |
+
if (prev_node, cur_node) in mark_half_edges:
|
| 1378 |
+
raise nx.NetworkXException("Bad planar embedding. Impossible face.")
|
| 1379 |
+
mark_half_edges.add((prev_node, cur_node))
|
| 1380 |
+
|
| 1381 |
+
return face_nodes
|
| 1382 |
+
|
| 1383 |
+
def is_directed(self):
|
| 1384 |
+
"""A valid PlanarEmbedding is undirected.
|
| 1385 |
+
|
| 1386 |
+
All reverse edges are contained, i.e. for every existing
|
| 1387 |
+
half-edge (v, w) the half-edge in the opposite direction (w, v) is also
|
| 1388 |
+
contained.
|
| 1389 |
+
"""
|
| 1390 |
+
return False
|
| 1391 |
+
|
| 1392 |
+
def copy(self, as_view=False):
|
| 1393 |
+
if as_view is True:
|
| 1394 |
+
return nx.graphviews.generic_graph_view(self)
|
| 1395 |
+
G = self.__class__()
|
| 1396 |
+
G.graph.update(self.graph)
|
| 1397 |
+
G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
|
| 1398 |
+
super(self.__class__, G).add_edges_from(
|
| 1399 |
+
(u, v, datadict.copy())
|
| 1400 |
+
for u, nbrs in self._adj.items()
|
| 1401 |
+
for v, datadict in nbrs.items()
|
| 1402 |
+
)
|
| 1403 |
+
return G
|
| 1404 |
+
|
| 1405 |
+
def to_undirected(self, reciprocal=False, as_view=False):
|
| 1406 |
+
"""
|
| 1407 |
+
Returns a non-embedding undirected representation of the graph.
|
| 1408 |
+
|
| 1409 |
+
This method strips the planar embedding information and provides
|
| 1410 |
+
a simple undirected graph representation. While creating the undirected graph,
|
| 1411 |
+
all edge attributes are retained except the ``"cw"`` and ``"ccw"`` attributes
|
| 1412 |
+
which are removed from the edge data. Those attributes are specific to
|
| 1413 |
+
the requirements of planar embeddings.
|
| 1414 |
+
|
| 1415 |
+
Parameters
|
| 1416 |
+
----------
|
| 1417 |
+
reciprocal : bool (optional)
|
| 1418 |
+
Not supported for PlanarEmbedding. This parameter raises an exception
|
| 1419 |
+
if used. All valid embeddings include reciprocal half-edges by definition,
|
| 1420 |
+
making this parameter unnecessary.
|
| 1421 |
+
as_view : bool (optional, default=False)
|
| 1422 |
+
Not supported for PlanarEmbedding. This parameter raises an exception
|
| 1423 |
+
if used.
|
| 1424 |
+
|
| 1425 |
+
Returns
|
| 1426 |
+
-------
|
| 1427 |
+
G : Graph
|
| 1428 |
+
An undirected graph with the same name and nodes as the PlanarEmbedding.
|
| 1429 |
+
Edges are included with their data, except for the ``"cw"`` and ``"ccw"``
|
| 1430 |
+
attributes, which are omitted.
|
| 1431 |
+
|
| 1432 |
+
|
| 1433 |
+
Notes
|
| 1434 |
+
-----
|
| 1435 |
+
- If edges exist in both directions ``(u, v)`` and ``(v, u)`` in the PlanarEmbedding,
|
| 1436 |
+
attributes for the resulting undirected edge will be combined, excluding ``"cw"``
|
| 1437 |
+
and ``"ccw"``.
|
| 1438 |
+
- A deep copy is made of the other edge attributes as well as the
|
| 1439 |
+
node and graph attributes, ensuring independence of the resulting graph.
|
| 1440 |
+
- Subclass-specific data structures used in the original graph may not transfer
|
| 1441 |
+
to the undirected graph. The resulting graph will be of type ``nx.Graph``.
|
| 1442 |
+
"""
|
| 1443 |
+
|
| 1444 |
+
if reciprocal:
|
| 1445 |
+
raise ValueError(
|
| 1446 |
+
"'reciprocal=True' is not supported for PlanarEmbedding.\n"
|
| 1447 |
+
"All valid embeddings include reciprocal half-edges by definition,\n"
|
| 1448 |
+
"making this parameter unnecessary."
|
| 1449 |
+
)
|
| 1450 |
+
|
| 1451 |
+
if as_view:
|
| 1452 |
+
raise ValueError("'as_view=True' is not supported for PlanarEmbedding.")
|
| 1453 |
+
|
| 1454 |
+
graph_class = self.to_undirected_class()
|
| 1455 |
+
G = graph_class()
|
| 1456 |
+
G.graph.update(deepcopy(self.graph))
|
| 1457 |
+
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
| 1458 |
+
G.add_edges_from(
|
| 1459 |
+
(u, v, {k: deepcopy(v) for k, v in d.items() if k not in {"cw", "ccw"}})
|
| 1460 |
+
for u, nbrs in self._adj.items()
|
| 1461 |
+
for v, d in nbrs.items()
|
| 1462 |
+
)
|
| 1463 |
+
return G
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/polynomials.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provides algorithms supporting the computation of graph polynomials.
|
| 2 |
+
|
| 3 |
+
Graph polynomials are polynomial-valued graph invariants that encode a wide
|
| 4 |
+
variety of structural information. Examples include the Tutte polynomial,
|
| 5 |
+
chromatic polynomial, characteristic polynomial, and matching polynomial. An
|
| 6 |
+
extensive treatment is provided in [1]_.
|
| 7 |
+
|
| 8 |
+
For a simple example, the `~sympy.matrices.matrices.MatrixDeterminant.charpoly`
|
| 9 |
+
method can be used to compute the characteristic polynomial from the adjacency
|
| 10 |
+
matrix of a graph. Consider the complete graph ``K_4``:
|
| 11 |
+
|
| 12 |
+
>>> import sympy
|
| 13 |
+
>>> x = sympy.Symbol("x")
|
| 14 |
+
>>> G = nx.complete_graph(4)
|
| 15 |
+
>>> A = nx.to_numpy_array(G, dtype=int)
|
| 16 |
+
>>> M = sympy.SparseMatrix(A)
|
| 17 |
+
>>> M.charpoly(x).as_expr()
|
| 18 |
+
x**4 - 6*x**2 - 8*x - 3
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
.. [1] Y. Shi, M. Dehmer, X. Li, I. Gutman,
|
| 22 |
+
"Graph Polynomials"
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from collections import deque
|
| 26 |
+
|
| 27 |
+
import networkx as nx
|
| 28 |
+
from networkx.utils import not_implemented_for
|
| 29 |
+
|
| 30 |
+
__all__ = ["tutte_polynomial", "chromatic_polynomial"]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@not_implemented_for("directed")
|
| 34 |
+
@nx._dispatchable
|
| 35 |
+
def tutte_polynomial(G):
|
| 36 |
+
r"""Returns the Tutte polynomial of `G`
|
| 37 |
+
|
| 38 |
+
This function computes the Tutte polynomial via an iterative version of
|
| 39 |
+
the deletion-contraction algorithm.
|
| 40 |
+
|
| 41 |
+
The Tutte polynomial `T_G(x, y)` is a fundamental graph polynomial invariant in
|
| 42 |
+
two variables. It encodes a wide array of information related to the
|
| 43 |
+
edge-connectivity of a graph; "Many problems about graphs can be reduced to
|
| 44 |
+
problems of finding and evaluating the Tutte polynomial at certain values" [1]_.
|
| 45 |
+
In fact, every deletion-contraction-expressible feature of a graph is a
|
| 46 |
+
specialization of the Tutte polynomial [2]_ (see Notes for examples).
|
| 47 |
+
|
| 48 |
+
There are several equivalent definitions; here are three:
|
| 49 |
+
|
| 50 |
+
Def 1 (rank-nullity expansion): For `G` an undirected graph, `n(G)` the
|
| 51 |
+
number of vertices of `G`, `E` the edge set of `G`, `V` the vertex set of
|
| 52 |
+
`G`, and `c(A)` the number of connected components of the graph with vertex
|
| 53 |
+
set `V` and edge set `A` [3]_:
|
| 54 |
+
|
| 55 |
+
.. math::
|
| 56 |
+
|
| 57 |
+
T_G(x, y) = \sum_{A \in E} (x-1)^{c(A) - c(E)} (y-1)^{c(A) + |A| - n(G)}
|
| 58 |
+
|
| 59 |
+
Def 2 (spanning tree expansion): Let `G` be an undirected graph, `T` a spanning
|
| 60 |
+
tree of `G`, and `E` the edge set of `G`. Let `E` have an arbitrary strict
|
| 61 |
+
linear order `L`. Let `B_e` be the unique minimal nonempty edge cut of
|
| 62 |
+
$E \setminus T \cup {e}$. An edge `e` is internally active with respect to
|
| 63 |
+
`T` and `L` if `e` is the least edge in `B_e` according to the linear order
|
| 64 |
+
`L`. The internal activity of `T` (denoted `i(T)`) is the number of edges
|
| 65 |
+
in $E \setminus T$ that are internally active with respect to `T` and `L`.
|
| 66 |
+
Let `P_e` be the unique path in $T \cup {e}$ whose source and target vertex
|
| 67 |
+
are the same. An edge `e` is externally active with respect to `T` and `L`
|
| 68 |
+
if `e` is the least edge in `P_e` according to the linear order `L`. The
|
| 69 |
+
external activity of `T` (denoted `e(T)`) is the number of edges in
|
| 70 |
+
$E \setminus T$ that are externally active with respect to `T` and `L`.
|
| 71 |
+
Then [4]_ [5]_:
|
| 72 |
+
|
| 73 |
+
.. math::
|
| 74 |
+
|
| 75 |
+
T_G(x, y) = \sum_{T \text{ a spanning tree of } G} x^{i(T)} y^{e(T)}
|
| 76 |
+
|
| 77 |
+
Def 3 (deletion-contraction recurrence): For `G` an undirected graph, `G-e`
|
| 78 |
+
the graph obtained from `G` by deleting edge `e`, `G/e` the graph obtained
|
| 79 |
+
from `G` by contracting edge `e`, `k(G)` the number of cut-edges of `G`,
|
| 80 |
+
and `l(G)` the number of self-loops of `G`:
|
| 81 |
+
|
| 82 |
+
.. math::
|
| 83 |
+
T_G(x, y) = \begin{cases}
|
| 84 |
+
x^{k(G)} y^{l(G)}, & \text{if all edges are cut-edges or self-loops} \\
|
| 85 |
+
T_{G-e}(x, y) + T_{G/e}(x, y), & \text{otherwise, for an arbitrary edge $e$ not a cut-edge or loop}
|
| 86 |
+
\end{cases}
|
| 87 |
+
|
| 88 |
+
Parameters
|
| 89 |
+
----------
|
| 90 |
+
G : NetworkX graph
|
| 91 |
+
|
| 92 |
+
Returns
|
| 93 |
+
-------
|
| 94 |
+
instance of `sympy.core.add.Add`
|
| 95 |
+
A Sympy expression representing the Tutte polynomial for `G`.
|
| 96 |
+
|
| 97 |
+
Examples
|
| 98 |
+
--------
|
| 99 |
+
>>> C = nx.cycle_graph(5)
|
| 100 |
+
>>> nx.tutte_polynomial(C)
|
| 101 |
+
x**4 + x**3 + x**2 + x + y
|
| 102 |
+
|
| 103 |
+
>>> D = nx.diamond_graph()
|
| 104 |
+
>>> nx.tutte_polynomial(D)
|
| 105 |
+
x**3 + 2*x**2 + 2*x*y + x + y**2 + y
|
| 106 |
+
|
| 107 |
+
Notes
|
| 108 |
+
-----
|
| 109 |
+
Some specializations of the Tutte polynomial:
|
| 110 |
+
|
| 111 |
+
- `T_G(1, 1)` counts the number of spanning trees of `G`
|
| 112 |
+
- `T_G(1, 2)` counts the number of connected spanning subgraphs of `G`
|
| 113 |
+
- `T_G(2, 1)` counts the number of spanning forests in `G`
|
| 114 |
+
- `T_G(0, 2)` counts the number of strong orientations of `G`
|
| 115 |
+
- `T_G(2, 0)` counts the number of acyclic orientations of `G`
|
| 116 |
+
|
| 117 |
+
Edge contraction is defined and deletion-contraction is introduced in [6]_.
|
| 118 |
+
Combinatorial meaning of the coefficients is introduced in [7]_.
|
| 119 |
+
Universality, properties, and applications are discussed in [8]_.
|
| 120 |
+
|
| 121 |
+
Practically, up-front computation of the Tutte polynomial may be useful when
|
| 122 |
+
users wish to repeatedly calculate edge-connectivity-related information
|
| 123 |
+
about one or more graphs.
|
| 124 |
+
|
| 125 |
+
References
|
| 126 |
+
----------
|
| 127 |
+
.. [1] M. Brandt,
|
| 128 |
+
"The Tutte Polynomial."
|
| 129 |
+
Talking About Combinatorial Objects Seminar, 2015
|
| 130 |
+
https://math.berkeley.edu/~brandtm/talks/tutte.pdf
|
| 131 |
+
.. [2] A. Björklund, T. Husfeldt, P. Kaski, M. Koivisto,
|
| 132 |
+
"Computing the Tutte polynomial in vertex-exponential time"
|
| 133 |
+
49th Annual IEEE Symposium on Foundations of Computer Science, 2008
|
| 134 |
+
https://ieeexplore.ieee.org/abstract/document/4691000
|
| 135 |
+
.. [3] Y. Shi, M. Dehmer, X. Li, I. Gutman,
|
| 136 |
+
"Graph Polynomials," p. 14
|
| 137 |
+
.. [4] Y. Shi, M. Dehmer, X. Li, I. Gutman,
|
| 138 |
+
"Graph Polynomials," p. 46
|
| 139 |
+
.. [5] A. Nešetril, J. Goodall,
|
| 140 |
+
"Graph invariants, homomorphisms, and the Tutte polynomial"
|
| 141 |
+
https://iuuk.mff.cuni.cz/~andrew/Tutte.pdf
|
| 142 |
+
.. [6] D. B. West,
|
| 143 |
+
"Introduction to Graph Theory," p. 84
|
| 144 |
+
.. [7] G. Coutinho,
|
| 145 |
+
"A brief introduction to the Tutte polynomial"
|
| 146 |
+
Structural Analysis of Complex Networks, 2011
|
| 147 |
+
https://homepages.dcc.ufmg.br/~gabriel/seminars/coutinho_tuttepolynomial_seminar.pdf
|
| 148 |
+
.. [8] J. A. Ellis-Monaghan, C. Merino,
|
| 149 |
+
"Graph polynomials and their applications I: The Tutte polynomial"
|
| 150 |
+
Structural Analysis of Complex Networks, 2011
|
| 151 |
+
https://arxiv.org/pdf/0803.3079.pdf
|
| 152 |
+
"""
|
| 153 |
+
import sympy
|
| 154 |
+
|
| 155 |
+
x = sympy.Symbol("x")
|
| 156 |
+
y = sympy.Symbol("y")
|
| 157 |
+
stack = deque()
|
| 158 |
+
stack.append(nx.MultiGraph(G))
|
| 159 |
+
|
| 160 |
+
polynomial = 0
|
| 161 |
+
while stack:
|
| 162 |
+
G = stack.pop()
|
| 163 |
+
bridges = set(nx.bridges(G))
|
| 164 |
+
|
| 165 |
+
e = None
|
| 166 |
+
for i in G.edges:
|
| 167 |
+
if (i[0], i[1]) not in bridges and i[0] != i[1]:
|
| 168 |
+
e = i
|
| 169 |
+
break
|
| 170 |
+
if not e:
|
| 171 |
+
loops = list(nx.selfloop_edges(G, keys=True))
|
| 172 |
+
polynomial += x ** len(bridges) * y ** len(loops)
|
| 173 |
+
else:
|
| 174 |
+
# deletion-contraction
|
| 175 |
+
C = nx.contracted_edge(G, e, self_loops=True)
|
| 176 |
+
C.remove_edge(e[0], e[0])
|
| 177 |
+
G.remove_edge(*e)
|
| 178 |
+
stack.append(G)
|
| 179 |
+
stack.append(C)
|
| 180 |
+
return sympy.simplify(polynomial)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
@not_implemented_for("directed")
|
| 184 |
+
@nx._dispatchable
|
| 185 |
+
def chromatic_polynomial(G):
|
| 186 |
+
r"""Returns the chromatic polynomial of `G`
|
| 187 |
+
|
| 188 |
+
This function computes the chromatic polynomial via an iterative version of
|
| 189 |
+
the deletion-contraction algorithm.
|
| 190 |
+
|
| 191 |
+
The chromatic polynomial `X_G(x)` is a fundamental graph polynomial
|
| 192 |
+
invariant in one variable. Evaluating `X_G(k)` for an natural number `k`
|
| 193 |
+
enumerates the proper k-colorings of `G`.
|
| 194 |
+
|
| 195 |
+
There are several equivalent definitions; here are three:
|
| 196 |
+
|
| 197 |
+
Def 1 (explicit formula):
|
| 198 |
+
For `G` an undirected graph, `c(G)` the number of connected components of
|
| 199 |
+
`G`, `E` the edge set of `G`, and `G(S)` the spanning subgraph of `G` with
|
| 200 |
+
edge set `S` [1]_:
|
| 201 |
+
|
| 202 |
+
.. math::
|
| 203 |
+
|
| 204 |
+
X_G(x) = \sum_{S \subseteq E} (-1)^{|S|} x^{c(G(S))}
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
Def 2 (interpolating polynomial):
|
| 208 |
+
For `G` an undirected graph, `n(G)` the number of vertices of `G`, `k_0 = 0`,
|
| 209 |
+
and `k_i` the number of distinct ways to color the vertices of `G` with `i`
|
| 210 |
+
unique colors (for `i` a natural number at most `n(G)`), `X_G(x)` is the
|
| 211 |
+
unique Lagrange interpolating polynomial of degree `n(G)` through the points
|
| 212 |
+
`(0, k_0), (1, k_1), \dots, (n(G), k_{n(G)})` [2]_.
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
Def 3 (chromatic recurrence):
|
| 216 |
+
For `G` an undirected graph, `G-e` the graph obtained from `G` by deleting
|
| 217 |
+
edge `e`, `G/e` the graph obtained from `G` by contracting edge `e`, `n(G)`
|
| 218 |
+
the number of vertices of `G`, and `e(G)` the number of edges of `G` [3]_:
|
| 219 |
+
|
| 220 |
+
.. math::
|
| 221 |
+
X_G(x) = \begin{cases}
|
| 222 |
+
x^{n(G)}, & \text{if $e(G)=0$} \\
|
| 223 |
+
X_{G-e}(x) - X_{G/e}(x), & \text{otherwise, for an arbitrary edge $e$}
|
| 224 |
+
\end{cases}
|
| 225 |
+
|
| 226 |
+
This formulation is also known as the Fundamental Reduction Theorem [4]_.
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
Parameters
|
| 230 |
+
----------
|
| 231 |
+
G : NetworkX graph
|
| 232 |
+
|
| 233 |
+
Returns
|
| 234 |
+
-------
|
| 235 |
+
instance of `sympy.core.add.Add`
|
| 236 |
+
A Sympy expression representing the chromatic polynomial for `G`.
|
| 237 |
+
|
| 238 |
+
Examples
|
| 239 |
+
--------
|
| 240 |
+
>>> C = nx.cycle_graph(5)
|
| 241 |
+
>>> nx.chromatic_polynomial(C)
|
| 242 |
+
x**5 - 5*x**4 + 10*x**3 - 10*x**2 + 4*x
|
| 243 |
+
|
| 244 |
+
>>> G = nx.complete_graph(4)
|
| 245 |
+
>>> nx.chromatic_polynomial(G)
|
| 246 |
+
x**4 - 6*x**3 + 11*x**2 - 6*x
|
| 247 |
+
|
| 248 |
+
Notes
|
| 249 |
+
-----
|
| 250 |
+
Interpretation of the coefficients is discussed in [5]_. Several special
|
| 251 |
+
cases are listed in [2]_.
|
| 252 |
+
|
| 253 |
+
The chromatic polynomial is a specialization of the Tutte polynomial; in
|
| 254 |
+
particular, ``X_G(x) = T_G(x, 0)`` [6]_.
|
| 255 |
+
|
| 256 |
+
The chromatic polynomial may take negative arguments, though evaluations
|
| 257 |
+
may not have chromatic interpretations. For instance, ``X_G(-1)`` enumerates
|
| 258 |
+
the acyclic orientations of `G` [7]_.
|
| 259 |
+
|
| 260 |
+
References
|
| 261 |
+
----------
|
| 262 |
+
.. [1] D. B. West,
|
| 263 |
+
"Introduction to Graph Theory," p. 222
|
| 264 |
+
.. [2] E. W. Weisstein
|
| 265 |
+
"Chromatic Polynomial"
|
| 266 |
+
MathWorld--A Wolfram Web Resource
|
| 267 |
+
https://mathworld.wolfram.com/ChromaticPolynomial.html
|
| 268 |
+
.. [3] D. B. West,
|
| 269 |
+
"Introduction to Graph Theory," p. 221
|
| 270 |
+
.. [4] J. Zhang, J. Goodall,
|
| 271 |
+
"An Introduction to Chromatic Polynomials"
|
| 272 |
+
https://math.mit.edu/~apost/courses/18.204_2018/Julie_Zhang_paper.pdf
|
| 273 |
+
.. [5] R. C. Read,
|
| 274 |
+
"An Introduction to Chromatic Polynomials"
|
| 275 |
+
Journal of Combinatorial Theory, 1968
|
| 276 |
+
https://math.berkeley.edu/~mrklug/ReadChromatic.pdf
|
| 277 |
+
.. [6] W. T. Tutte,
|
| 278 |
+
"Graph-polynomials"
|
| 279 |
+
Advances in Applied Mathematics, 2004
|
| 280 |
+
https://www.sciencedirect.com/science/article/pii/S0196885803000411
|
| 281 |
+
.. [7] R. P. Stanley,
|
| 282 |
+
"Acyclic orientations of graphs"
|
| 283 |
+
Discrete Mathematics, 2006
|
| 284 |
+
https://math.mit.edu/~rstan/pubs/pubfiles/18.pdf
|
| 285 |
+
"""
|
| 286 |
+
import sympy
|
| 287 |
+
|
| 288 |
+
x = sympy.Symbol("x")
|
| 289 |
+
stack = deque()
|
| 290 |
+
stack.append(nx.MultiGraph(G, contraction_idx=0))
|
| 291 |
+
|
| 292 |
+
polynomial = 0
|
| 293 |
+
while stack:
|
| 294 |
+
G = stack.pop()
|
| 295 |
+
edges = list(G.edges)
|
| 296 |
+
if not edges:
|
| 297 |
+
polynomial += (-1) ** G.graph["contraction_idx"] * x ** len(G)
|
| 298 |
+
else:
|
| 299 |
+
e = edges[0]
|
| 300 |
+
C = nx.contracted_edge(G, e, self_loops=True)
|
| 301 |
+
C.graph["contraction_idx"] = G.graph["contraction_idx"] + 1
|
| 302 |
+
C.remove_edge(e[0], e[0])
|
| 303 |
+
G.remove_edge(*e)
|
| 304 |
+
stack.append(G)
|
| 305 |
+
stack.append(C)
|
| 306 |
+
return polynomial
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/reciprocity.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Algorithms to calculate reciprocity in a directed graph."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx import NetworkXError
|
| 5 |
+
|
| 6 |
+
from ..utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = ["reciprocity", "overall_reciprocity"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@not_implemented_for("undirected", "multigraph")
|
| 12 |
+
@nx._dispatchable
|
| 13 |
+
def reciprocity(G, nodes=None):
|
| 14 |
+
r"""Compute the reciprocity in a directed graph.
|
| 15 |
+
|
| 16 |
+
The reciprocity of a directed graph is defined as the ratio
|
| 17 |
+
of the number of edges pointing in both directions to the total
|
| 18 |
+
number of edges in the graph.
|
| 19 |
+
Formally, $r = |{(u,v) \in G|(v,u) \in G}| / |{(u,v) \in G}|$.
|
| 20 |
+
|
| 21 |
+
The reciprocity of a single node u is defined similarly,
|
| 22 |
+
it is the ratio of the number of edges in both directions to
|
| 23 |
+
the total number of edges attached to node u.
|
| 24 |
+
|
| 25 |
+
Parameters
|
| 26 |
+
----------
|
| 27 |
+
G : graph
|
| 28 |
+
A networkx directed graph
|
| 29 |
+
nodes : container of nodes, optional (default=whole graph)
|
| 30 |
+
Compute reciprocity for nodes in this container.
|
| 31 |
+
|
| 32 |
+
Returns
|
| 33 |
+
-------
|
| 34 |
+
out : dictionary
|
| 35 |
+
Reciprocity keyed by node label.
|
| 36 |
+
|
| 37 |
+
Notes
|
| 38 |
+
-----
|
| 39 |
+
The reciprocity is not defined for isolated nodes.
|
| 40 |
+
In such cases this function will return None.
|
| 41 |
+
|
| 42 |
+
"""
|
| 43 |
+
# If `nodes` is not specified, calculate the reciprocity of the graph.
|
| 44 |
+
if nodes is None:
|
| 45 |
+
return overall_reciprocity(G)
|
| 46 |
+
|
| 47 |
+
# If `nodes` represents a single node in the graph, return only its
|
| 48 |
+
# reciprocity.
|
| 49 |
+
if nodes in G:
|
| 50 |
+
reciprocity = next(_reciprocity_iter(G, nodes))[1]
|
| 51 |
+
if reciprocity is None:
|
| 52 |
+
raise NetworkXError("Not defined for isolated nodes.")
|
| 53 |
+
else:
|
| 54 |
+
return reciprocity
|
| 55 |
+
|
| 56 |
+
# Otherwise, `nodes` represents an iterable of nodes, so return a
|
| 57 |
+
# dictionary mapping node to its reciprocity.
|
| 58 |
+
return dict(_reciprocity_iter(G, nodes))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _reciprocity_iter(G, nodes):
|
| 62 |
+
"""Return an iterator of (node, reciprocity)."""
|
| 63 |
+
n = G.nbunch_iter(nodes)
|
| 64 |
+
for node in n:
|
| 65 |
+
pred = set(G.predecessors(node))
|
| 66 |
+
succ = set(G.successors(node))
|
| 67 |
+
overlap = pred & succ
|
| 68 |
+
n_total = len(pred) + len(succ)
|
| 69 |
+
|
| 70 |
+
# Reciprocity is not defined for isolated nodes.
|
| 71 |
+
# Return None.
|
| 72 |
+
if n_total == 0:
|
| 73 |
+
yield (node, None)
|
| 74 |
+
else:
|
| 75 |
+
reciprocity = 2 * len(overlap) / n_total
|
| 76 |
+
yield (node, reciprocity)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@not_implemented_for("undirected", "multigraph")
|
| 80 |
+
@nx._dispatchable
|
| 81 |
+
def overall_reciprocity(G):
|
| 82 |
+
"""Compute the reciprocity for the whole graph.
|
| 83 |
+
|
| 84 |
+
See the doc of reciprocity for the definition.
|
| 85 |
+
|
| 86 |
+
Parameters
|
| 87 |
+
----------
|
| 88 |
+
G : graph
|
| 89 |
+
A networkx graph
|
| 90 |
+
|
| 91 |
+
"""
|
| 92 |
+
n_all_edge = G.number_of_edges()
|
| 93 |
+
n_overlap_edge = (n_all_edge - G.to_undirected().number_of_edges()) * 2
|
| 94 |
+
|
| 95 |
+
if n_all_edge == 0:
|
| 96 |
+
raise NetworkXError("Not defined for empty graphs")
|
| 97 |
+
|
| 98 |
+
return n_overlap_edge / n_all_edge
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/regular.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for computing and verifying regular graphs."""
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
from networkx.utils import not_implemented_for
|
| 5 |
+
|
| 6 |
+
__all__ = ["is_regular", "is_k_regular", "k_factor"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@nx._dispatchable
|
| 10 |
+
def is_regular(G):
|
| 11 |
+
"""Determines whether a graph is regular.
|
| 12 |
+
|
| 13 |
+
A regular graph is a graph where all nodes have the same degree. A regular
|
| 14 |
+
digraph is a graph where all nodes have the same indegree and all nodes
|
| 15 |
+
have the same outdegree.
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
----------
|
| 19 |
+
G : NetworkX graph
|
| 20 |
+
|
| 21 |
+
Returns
|
| 22 |
+
-------
|
| 23 |
+
bool
|
| 24 |
+
Whether the given graph or digraph is regular.
|
| 25 |
+
|
| 26 |
+
Examples
|
| 27 |
+
--------
|
| 28 |
+
>>> G = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 1)])
|
| 29 |
+
>>> nx.is_regular(G)
|
| 30 |
+
True
|
| 31 |
+
|
| 32 |
+
"""
|
| 33 |
+
if len(G) == 0:
|
| 34 |
+
raise nx.NetworkXPointlessConcept("Graph has no nodes.")
|
| 35 |
+
n1 = nx.utils.arbitrary_element(G)
|
| 36 |
+
if not G.is_directed():
|
| 37 |
+
d1 = G.degree(n1)
|
| 38 |
+
return all(d1 == d for _, d in G.degree)
|
| 39 |
+
else:
|
| 40 |
+
d_in = G.in_degree(n1)
|
| 41 |
+
in_regular = (d_in == d for _, d in G.in_degree)
|
| 42 |
+
d_out = G.out_degree(n1)
|
| 43 |
+
out_regular = (d_out == d for _, d in G.out_degree)
|
| 44 |
+
return all(in_regular) and all(out_regular)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@not_implemented_for("directed")
|
| 48 |
+
@nx._dispatchable
|
| 49 |
+
def is_k_regular(G, k):
|
| 50 |
+
"""Determines whether the graph ``G`` is a k-regular graph.
|
| 51 |
+
|
| 52 |
+
A k-regular graph is a graph where each vertex has degree k.
|
| 53 |
+
|
| 54 |
+
Parameters
|
| 55 |
+
----------
|
| 56 |
+
G : NetworkX graph
|
| 57 |
+
|
| 58 |
+
Returns
|
| 59 |
+
-------
|
| 60 |
+
bool
|
| 61 |
+
Whether the given graph is k-regular.
|
| 62 |
+
|
| 63 |
+
Examples
|
| 64 |
+
--------
|
| 65 |
+
>>> G = nx.Graph([(1, 2), (2, 3), (3, 4), (4, 1)])
|
| 66 |
+
>>> nx.is_k_regular(G, k=3)
|
| 67 |
+
False
|
| 68 |
+
|
| 69 |
+
"""
|
| 70 |
+
return all(d == k for n, d in G.degree)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@not_implemented_for("directed")
|
| 74 |
+
@not_implemented_for("multigraph")
|
| 75 |
+
@nx._dispatchable(preserve_edge_attrs=True, returns_graph=True)
|
| 76 |
+
def k_factor(G, k, matching_weight="weight"):
|
| 77 |
+
"""Compute a `k`-factor of a graph.
|
| 78 |
+
|
| 79 |
+
A `k`-factor of a graph is a spanning `k`-regular subgraph.
|
| 80 |
+
A spanning `k`-regular subgraph of `G` is a subgraph that contains
|
| 81 |
+
each node of `G` and a subset of the edges of `G` such that each
|
| 82 |
+
node has degree `k`.
|
| 83 |
+
|
| 84 |
+
Parameters
|
| 85 |
+
----------
|
| 86 |
+
G : NetworkX graph
|
| 87 |
+
An undirected graph.
|
| 88 |
+
|
| 89 |
+
k : int
|
| 90 |
+
The degree of the `k`-factor.
|
| 91 |
+
|
| 92 |
+
matching_weight: string, optional (default="weight")
|
| 93 |
+
Edge attribute name corresponding to the edge weight.
|
| 94 |
+
If not present, the edge is assumed to have weight 1.
|
| 95 |
+
Used for finding the max-weighted perfect matching.
|
| 96 |
+
|
| 97 |
+
Returns
|
| 98 |
+
-------
|
| 99 |
+
NetworkX graph
|
| 100 |
+
A `k`-factor of `G`.
|
| 101 |
+
|
| 102 |
+
Examples
|
| 103 |
+
--------
|
| 104 |
+
>>> G = nx.Graph([(1, 2), (2, 3), (3, 4), (4, 1)])
|
| 105 |
+
>>> KF = nx.k_factor(G, k=1)
|
| 106 |
+
>>> KF.edges()
|
| 107 |
+
EdgeView([(1, 2), (3, 4)])
|
| 108 |
+
|
| 109 |
+
References
|
| 110 |
+
----------
|
| 111 |
+
.. [1] "An algorithm for computing simple k-factors.",
|
| 112 |
+
Meijer, Henk, Yurai Núñez-Rodríguez, and David Rappaport,
|
| 113 |
+
Information processing letters, 2009.
|
| 114 |
+
"""
|
| 115 |
+
# Validate minimum degree requirement.
|
| 116 |
+
if any(d < k for _, d in G.degree):
|
| 117 |
+
raise nx.NetworkXUnfeasible("Graph contains a vertex with degree less than k")
|
| 118 |
+
|
| 119 |
+
g = G.copy()
|
| 120 |
+
gadgets = []
|
| 121 |
+
|
| 122 |
+
# Replace each node with a gadget.
|
| 123 |
+
for node, degree in G.degree:
|
| 124 |
+
is_large = k >= degree / 2.0
|
| 125 |
+
|
| 126 |
+
# Create gadget nodes.
|
| 127 |
+
outer = [(node, i) for i in range(degree)]
|
| 128 |
+
if is_large:
|
| 129 |
+
core = [(node, i) for i in range(degree, 2 * degree - k)]
|
| 130 |
+
inner = []
|
| 131 |
+
else:
|
| 132 |
+
core = [(node, i) for i in range(2 * degree, 2 * degree + k)]
|
| 133 |
+
inner = [(node, i) for i in range(degree, 2 * degree)]
|
| 134 |
+
|
| 135 |
+
# Connect gadget nodes to neighbors.
|
| 136 |
+
g.add_edges_from(zip(outer, inner))
|
| 137 |
+
for outer_n, (neighbor, attrs) in zip(outer, g[node].items()):
|
| 138 |
+
g.add_edge(outer_n, neighbor, **attrs)
|
| 139 |
+
|
| 140 |
+
# Add internal edges.
|
| 141 |
+
g.add_edges_from((u, v) for u in core for v in (outer if is_large else inner))
|
| 142 |
+
|
| 143 |
+
g.remove_node(node)
|
| 144 |
+
gadgets.append((node, outer, core, inner))
|
| 145 |
+
|
| 146 |
+
# Find perfect matching.
|
| 147 |
+
m = nx.max_weight_matching(g, maxcardinality=True, weight=matching_weight)
|
| 148 |
+
if not nx.is_perfect_matching(g, m):
|
| 149 |
+
raise nx.NetworkXUnfeasible(
|
| 150 |
+
"Cannot find k-factor because no perfect matching exists"
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Keep only edges in matching.
|
| 154 |
+
g.remove_edges_from(e for e in g.edges if e not in m and e[::-1] not in m)
|
| 155 |
+
|
| 156 |
+
# Restore original nodes and remove gadgets.
|
| 157 |
+
for node, outer, core, inner in gadgets:
|
| 158 |
+
g.add_node(node)
|
| 159 |
+
core_set = set(core)
|
| 160 |
+
for outer_n in outer:
|
| 161 |
+
for neighbor, attrs in g._adj[outer_n].items():
|
| 162 |
+
if neighbor not in core_set:
|
| 163 |
+
g.add_edge(node, neighbor, **attrs)
|
| 164 |
+
break
|
| 165 |
+
g.remove_nodes_from(outer + core + inner)
|
| 166 |
+
|
| 167 |
+
return g
|
micromamba_root/envs/pytorch_env/Lib/site-packages/networkx/algorithms/richclub.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for computing rich-club coefficients."""
|
| 2 |
+
|
| 3 |
+
from itertools import accumulate
|
| 4 |
+
|
| 5 |
+
import networkx as nx
|
| 6 |
+
from networkx.utils import not_implemented_for
|
| 7 |
+
|
| 8 |
+
__all__ = ["rich_club_coefficient"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@not_implemented_for("directed")
|
| 12 |
+
@not_implemented_for("multigraph")
|
| 13 |
+
@nx._dispatchable
|
| 14 |
+
def rich_club_coefficient(G, normalized=True, Q=100, seed=None):
|
| 15 |
+
r"""Returns the rich-club coefficient of the graph `G`.
|
| 16 |
+
|
| 17 |
+
For each degree *k*, the *rich-club coefficient* is the ratio of the
|
| 18 |
+
number of actual to the number of potential edges for nodes with
|
| 19 |
+
degree greater than *k*:
|
| 20 |
+
|
| 21 |
+
.. math::
|
| 22 |
+
|
| 23 |
+
\phi(k) = \frac{2 E_k}{N_k (N_k - 1)}
|
| 24 |
+
|
| 25 |
+
where `N_k` is the number of nodes with degree larger than *k*, and
|
| 26 |
+
`E_k` is the number of edges among those nodes.
|
| 27 |
+
|
| 28 |
+
Parameters
|
| 29 |
+
----------
|
| 30 |
+
G : NetworkX graph
|
| 31 |
+
Undirected graph with neither parallel edges nor self-loops.
|
| 32 |
+
normalized : bool (optional)
|
| 33 |
+
Normalize using randomized network as in [1]_
|
| 34 |
+
Q : float (optional, default=100)
|
| 35 |
+
If `normalized` is True, perform `Q * m` double-edge
|
| 36 |
+
swaps, where `m` is the number of edges in `G`, to use as a
|
| 37 |
+
null-model for normalization.
|
| 38 |
+
seed : integer, random_state, or None (default)
|
| 39 |
+
Indicator of random number generation state.
|
| 40 |
+
See :ref:`Randomness<randomness>`.
|
| 41 |
+
|
| 42 |
+
Returns
|
| 43 |
+
-------
|
| 44 |
+
rc : dictionary
|
| 45 |
+
A dictionary, keyed by degree, with rich-club coefficient values.
|
| 46 |
+
|
| 47 |
+
Raises
|
| 48 |
+
------
|
| 49 |
+
NetworkXError
|
| 50 |
+
If `G` has fewer than four nodes and ``normalized=True``.
|
| 51 |
+
A randomly sampled graph for normalization cannot be generated in this case.
|
| 52 |
+
|
| 53 |
+
Examples
|
| 54 |
+
--------
|
| 55 |
+
>>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
|
| 56 |
+
>>> rc = nx.rich_club_coefficient(G, normalized=False, seed=42)
|
| 57 |
+
>>> rc[0]
|
| 58 |
+
0.4
|
| 59 |
+
|
| 60 |
+
Notes
|
| 61 |
+
-----
|
| 62 |
+
The rich club definition and algorithm are found in [1]_. This
|
| 63 |
+
algorithm ignores any edge weights and is not defined for directed
|
| 64 |
+
graphs or graphs with parallel edges or self loops.
|
| 65 |
+
|
| 66 |
+
Normalization is done by computing the rich club coefficient for a randomly
|
| 67 |
+
sampled graph with the same degree distribution as `G` by
|
| 68 |
+
repeatedly swapping the endpoints of existing edges. For graphs with fewer than 4
|
| 69 |
+
nodes, it is not possible to generate a random graph with a prescribed
|
| 70 |
+
degree distribution, as the degree distribution fully determines the graph
|
| 71 |
+
(hence making the coefficients trivially normalized to 1).
|
| 72 |
+
This function raises an exception in this case.
|
| 73 |
+
|
| 74 |
+
Estimates for appropriate values of `Q` are found in [2]_.
|
| 75 |
+
|
| 76 |
+
References
|
| 77 |
+
----------
|
| 78 |
+
.. [1] Julian J. McAuley, Luciano da Fontoura Costa,
|
| 79 |
+
and Tibério S. Caetano,
|
| 80 |
+
"The rich-club phenomenon across complex network hierarchies",
|
| 81 |
+
Applied Physics Letters Vol 91 Issue 8, August 2007.
|
| 82 |
+
https://arxiv.org/abs/physics/0701290
|
| 83 |
+
.. [2] R. Milo, N. Kashtan, S. Itzkovitz, M. E. J. Newman, U. Alon,
|
| 84 |
+
"Uniform generation of random graphs with arbitrary degree
|
| 85 |
+
sequences", 2006. https://arxiv.org/abs/cond-mat/0312028
|
| 86 |
+
"""
|
| 87 |
+
if nx.number_of_selfloops(G) > 0:
|
| 88 |
+
raise Exception(
|
| 89 |
+
"rich_club_coefficient is not implemented for graphs with self loops."
|
| 90 |
+
)
|
| 91 |
+
rc = _compute_rc(G)
|
| 92 |
+
if normalized:
|
| 93 |
+
# make R a copy of G, randomize with Q*|E| double edge swaps
|
| 94 |
+
# and use rich_club coefficient of R to normalize
|
| 95 |
+
R = G.copy()
|
| 96 |
+
E = R.number_of_edges()
|
| 97 |
+
nx.double_edge_swap(R, Q * E, max_tries=Q * E * 10, seed=seed)
|
| 98 |
+
rcran = _compute_rc(R)
|
| 99 |
+
rc = {k: v / rcran[k] for k, v in rc.items()}
|
| 100 |
+
return rc
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _compute_rc(G):
|
| 104 |
+
"""Returns the rich-club coefficient for each degree in the graph
|
| 105 |
+
`G`.
|
| 106 |
+
|
| 107 |
+
`G` is an undirected graph without multiedges.
|
| 108 |
+
|
| 109 |
+
Returns a dictionary mapping degree to rich-club coefficient for
|
| 110 |
+
that degree.
|
| 111 |
+
|
| 112 |
+
"""
|
| 113 |
+
deghist = nx.degree_histogram(G)
|
| 114 |
+
total = sum(deghist)
|
| 115 |
+
# Compute the number of nodes with degree greater than `k`, for each
|
| 116 |
+
# degree `k` (omitting the last entry, which is zero).
|
| 117 |
+
nks = (total - cs for cs in accumulate(deghist) if total - cs > 1)
|
| 118 |
+
# Create a sorted list of pairs of edge endpoint degrees.
|
| 119 |
+
#
|
| 120 |
+
# The list is sorted in reverse order so that we can pop from the
|
| 121 |
+
# right side of the list later, instead of popping from the left
|
| 122 |
+
# side of the list, which would have a linear time cost.
|
| 123 |
+
edge_degrees = sorted((sorted(map(G.degree, e)) for e in G.edges()), reverse=True)
|
| 124 |
+
ek = G.number_of_edges()
|
| 125 |
+
if ek == 0:
|
| 126 |
+
return {}
|
| 127 |
+
|
| 128 |
+
k1, k2 = edge_degrees.pop()
|
| 129 |
+
rc = {}
|
| 130 |
+
for d, nk in enumerate(nks):
|
| 131 |
+
while k1 <= d:
|
| 132 |
+
if len(edge_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions measuring similarity using graph edit distance.
|
| 2 |
+
|
| 3 |
+
The graph edit distance is the number of edge/node changes needed
|
| 4 |
+
to make two graphs isomorphic.
|
| 5 |
+
|
| 6 |
+
The default algorithm/implementation is sub-optimal for some graphs.
|
| 7 |
+
The problem of finding the exact Graph Edit Distance (GED) is NP-hard
|
| 8 |
+
so it is often slow. If the simple interface `graph_edit_distance`
|
| 9 |
+
takes too long for your graph, try `optimize_graph_edit_distance`
|
| 10 |
+
and/or `optimize_edit_paths`.
|
| 11 |
+
|
| 12 |
+
At the same time, I encourage capable people to investigate
|
| 13 |
+
alternative GED algorithms, in order to improve the choices available.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
import time
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from itertools import product
|
| 20 |
+
|
| 21 |
+
import networkx as nx
|
| 22 |
+
from networkx.utils import np_random_state
|
| 23 |
+
|
| 24 |
+
__all__ = [
|
| 25 |
+
"graph_edit_distance",
|
| 26 |
+
"optimal_edit_paths",
|
| 27 |
+
"optimize_graph_edit_distance",
|
| 28 |
+
"optimize_edit_paths",
|
| 29 |
+
"simrank_similarity",
|
| 30 |
+
"panther_similarity",
|
| 31 |
+
"panther_vector_similarity",
|
| 32 |
+
"generate_random_paths",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@nx._dispatchable(
|
| 37 |
+
graphs={"G1": 0, "G2": 1}, preserve_edge_attrs=True, preserve_node_attrs=True
|
| 38 |
+
)
|
| 39 |
+
def graph_edit_distance(
|
| 40 |
+
G1,
|
| 41 |
+
G2,
|
| 42 |
+
node_match=None,
|
| 43 |
+
edge_match=None,
|
| 44 |
+
node_subst_cost=None,
|
| 45 |
+
node_del_cost=None,
|
| 46 |
+
node_ins_cost=None,
|
| 47 |
+
edge_subst_cost=None,
|
| 48 |
+
edge_del_cost=None,
|
| 49 |
+
edge_ins_cost=None,
|
| 50 |
+
roots=None,
|
| 51 |
+
upper_bound=None,
|
| 52 |
+
timeout=None,
|
| 53 |
+
):
|
| 54 |
+
"""Returns GED (graph edit distance) between graphs G1 and G2.
|
| 55 |
+
|
| 56 |
+
Graph edit distance is a graph similarity measure analogous to
|
| 57 |
+
Levenshtein distance for strings. It is defined as minimum cost
|
| 58 |
+
of edit path (sequence of node and edge edit operations)
|
| 59 |
+
transforming graph G1 to graph isomorphic to G2.
|
| 60 |
+
|
| 61 |
+
Parameters
|
| 62 |
+
----------
|
| 63 |
+
G1, G2: graphs
|
| 64 |
+
The two graphs G1 and G2 must be of the same type.
|
| 65 |
+
|
| 66 |
+
node_match : callable
|
| 67 |
+
A function that returns True if node n1 in G1 and n2 in G2
|
| 68 |
+
should be considered equal during matching.
|
| 69 |
+
|
| 70 |
+
The function will be called like
|
| 71 |
+
|
| 72 |
+
node_match(G1.nodes[n1], G2.nodes[n2]).
|
| 73 |
+
|
| 74 |
+
That is, the function will receive the node attribute
|
| 75 |
+
dictionaries for n1 and n2 as inputs.
|
| 76 |
+
|
| 77 |
+
Ignored if node_subst_cost is specified. If neither
|
| 78 |
+
node_match nor node_subst_cost are specified then node
|
| 79 |
+
attributes are not considered.
|
| 80 |
+
|
| 81 |
+
edge_match : callable
|
| 82 |
+
A function that returns True if the edge attribute dictionaries
|
| 83 |
+
for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should
|
| 84 |
+
be considered equal during matching.
|
| 85 |
+
|
| 86 |
+
The function will be called like
|
| 87 |
+
|
| 88 |
+
edge_match(G1[u1][v1], G2[u2][v2]).
|
| 89 |
+
|
| 90 |
+
That is, the function will receive the edge attribute
|
| 91 |
+
dictionaries of the edges under consideration.
|
| 92 |
+
|
| 93 |
+
Ignored if edge_subst_cost is specified. If neither
|
| 94 |
+
edge_match nor edge_subst_cost are specified then edge
|
| 95 |
+
attributes are not considered.
|
| 96 |
+
|
| 97 |
+
node_subst_cost, node_del_cost, node_ins_cost : callable
|
| 98 |
+
Functions that return the costs of node substitution, node
|
| 99 |
+
deletion, and node insertion, respectively.
|
| 100 |
+
|
| 101 |
+
The functions will be called like
|
| 102 |
+
|
| 103 |
+
node_subst_cost(G1.nodes[n1], G2.nodes[n2]),
|
| 104 |
+
node_del_cost(G1.nodes[n1]),
|
| 105 |
+
node_ins_cost(G2.nodes[n2]).
|
| 106 |
+
|
| 107 |
+
That is, the functions will receive the node attribute
|
| 108 |
+
dictionaries as inputs. The functions are expected to return
|
| 109 |
+
positive numeric values.
|
| 110 |
+
|
| 111 |
+
Function node_subst_cost overrides node_match if specified.
|
| 112 |
+
If neither node_match nor node_subst_cost are specified then
|
| 113 |
+
default node substitution cost of 0 is used (node attributes
|
| 114 |
+
are not considered during matching).
|
| 115 |
+
|
| 116 |
+
If node_del_cost is not specified then default node deletion
|
| 117 |
+
cost of 1 is used. If node_ins_cost is not specified then
|
| 118 |
+
default node insertion cost of 1 is used.
|
| 119 |
+
|
| 120 |
+
edge_subst_cost, edge_del_cost, edge_ins_cost : callable
|
| 121 |
+
Functions that return the costs of edge substitution, edge
|
| 122 |
+
deletion, and edge insertion, respectively.
|
| 123 |
+
|
| 124 |
+
The functions will be called like
|
| 125 |
+
|
| 126 |
+
edge_subst_cost(G1[u1][v1], G2[u2][v2]),
|
| 127 |
+
edge_del_cost(G1[u1][v1]),
|
| 128 |
+
edge_ins_cost(G2[u2][v2]).
|
| 129 |
+
|
| 130 |
+
That is, the functions will receive the edge attribute
|
| 131 |
+
dictionaries as inputs. The functions are expected to return
|
| 132 |
+
positive numeric values.
|
| 133 |
+
|
| 134 |
+
Function edge_subst_cost overrides edge_match if specified.
|
| 135 |
+
If neither edge_match nor edge_subst_cost are specified then
|
| 136 |
+
default edge substitution cost of 0 is used (edge attributes
|
| 137 |
+
are not considered during matching).
|
| 138 |
+
|
| 139 |
+
If edge_del_cost is not specified then default edge deletion
|
| 140 |
+
cost of 1 is used. If edge_ins_cost is not specified then
|
| 141 |
+
default edge insertion cost of 1 is used.
|
| 142 |
+
|
| 143 |
+
roots : 2-tuple
|
| 144 |
+
Tuple where first element is a node in G1 and the second
|
| 145 |
+
is a node in G2.
|
| 146 |
+
These nodes are forced to be matched in the comparison to
|
| 147 |
+
allow comparison between rooted graphs.
|
| 148 |
+
|
| 149 |
+
upper_bound : numeric
|
| 150 |
+
Maximum edit distance to consider. Return None if no edit
|
| 151 |
+
distance under or equal to upper_bound exists.
|
| 152 |
+
|
| 153 |
+
timeout : numeric
|
| 154 |
+
Maximum number of seconds to execute.
|
| 155 |
+
After timeout is met, the current best GED is returned.
|
| 156 |
+
|
| 157 |
+
Examples
|
| 158 |
+
--------
|
| 159 |
+
>>> G1 = nx.cycle_graph(6)
|
| 160 |
+
>>> G2 = nx.wheel_graph(7)
|
| 161 |
+
>>> nx.graph_edit_distance(G1, G2)
|
| 162 |
+
7.0
|
| 163 |
+
|
| 164 |
+
>>> G1 = nx.star_graph(5)
|
| 165 |
+
>>> G2 = nx.star_graph(5)
|
| 166 |
+
>>> nx.graph_edit_distance(G1, G2, roots=(0, 0))
|
| 167 |
+
0.0
|
| 168 |
+
>>> nx.graph_edit_distance(G1, G2, roots=(1, 0))
|
| 169 |
+
8.0
|
| 170 |
+
|
| 171 |
+
See Also
|
| 172 |
+
--------
|
| 173 |
+
optimal_edit_paths, optimize_graph_edit_distance,
|
| 174 |
+
|
| 175 |
+
is_isomorphic: test for graph edit distance of 0
|
| 176 |
+
|
| 177 |
+
References
|
| 178 |
+
----------
|
| 179 |
+
.. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick
|
| 180 |
+
Martineau. An Exact Graph Edit Distance Algorithm for Solving
|
| 181 |
+
Pattern Recognition Problems. 4th International Conference on
|
| 182 |
+
Pattern Recognition Applications and Methods 2015, Jan 2015,
|
| 183 |
+
Lisbon, Portugal. 2015,
|
| 184 |
+
<10.5220/0005209202710278>. <hal-01168816>
|
| 185 |
+
https://hal.archives-ouvertes.fr/hal-01168816
|
| 186 |
+
|
| 187 |
+
"""
|
| 188 |
+
bestcost = None
|
| 189 |
+
for _, _, cost in optimize_edit_paths(
|
| 190 |
+
G1,
|
| 191 |
+
G2,
|
| 192 |
+
node_match,
|
| 193 |
+
edge_match,
|
| 194 |
+
node_subst_cost,
|
| 195 |
+
node_del_cost,
|
| 196 |
+
node_ins_cost,
|
| 197 |
+
edge_subst_cost,
|
| 198 |
+
edge_del_cost,
|
| 199 |
+
edge_ins_cost,
|
| 200 |
+
upper_bound,
|
| 201 |
+
True,
|
| 202 |
+
roots,
|
| 203 |
+
timeout,
|
| 204 |
+
):
|
| 205 |
+
# assert bestcost is None or cost < bestcost
|
| 206 |
+
bestcost = cost
|
| 207 |
+
return bestcost
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
@nx._dispatchable(graphs={"G1": 0, "G2": 1})
|
| 211 |
+
def optimal_edit_paths(
|
| 212 |
+
G1,
|
| 213 |
+
G2,
|
| 214 |
+
node_match=None,
|
| 215 |
+
edge_match=None,
|
| 216 |
+
node_subst_cost=None,
|
| 217 |
+
node_del_cost=None,
|
| 218 |
+
node_ins_cost=None,
|
| 219 |
+
edge_subst_cost=None,
|
| 220 |
+
edge_del_cost=None,
|
| 221 |
+
edge_ins_cost=None,
|
| 222 |
+
upper_bound=None,
|
| 223 |
+
):
|
| 224 |
+
"""Returns all minimum-cost edit paths transforming G1 to G2.
|
| 225 |
+
|
| 226 |
+
Graph edit path is a sequence of node and edge edit operations
|
| 227 |
+
transforming graph G1 to graph isomorphic to G2. Edit operations
|
| 228 |
+
include substitutions, deletions, and insertions.
|
| 229 |
+
|
| 230 |
+
Parameters
|
| 231 |
+
----------
|
| 232 |
+
G1, G2: graphs
|
| 233 |
+
The two graphs G1 and G2 must be of the same type.
|
| 234 |
+
|
| 235 |
+
node_match : callable
|
| 236 |
+
A function that returns True if node n1 in G1 and n2 in G2
|
| 237 |
+
should be considered equal during matching.
|
| 238 |
+
|
| 239 |
+
The function will be called like
|
| 240 |
+
|
| 241 |
+
node_match(G1.nodes[n1], G2.nodes[n2]).
|
| 242 |
+
|
| 243 |
+
That is, the function will receive the node attribute
|
| 244 |
+
dictionaries for n1 and n2 as inputs.
|
| 245 |
+
|
| 246 |
+
Ignored if node_subst_cost is specified. If neither
|
| 247 |
+
node_match nor node_subst_cost are specified then node
|
| 248 |
+
attributes are not considered.
|
| 249 |
+
|
| 250 |
+
edge_match : callable
|
| 251 |
+
A function that returns True if the edge attribute dictionaries
|
| 252 |
+
for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should
|
| 253 |
+
be considered equal during matching.
|
| 254 |
+
|
| 255 |
+
The function will be called like
|
| 256 |
+
|
| 257 |
+
edge_match(G1[u1][v1], G2[u2][v2]).
|
| 258 |
+
|
| 259 |
+
That is, the function will receive the edge attribute
|
| 260 |
+
dictionaries of the edges under consideration.
|
| 261 |
+
|
| 262 |
+
Ignored if edge_subst_cost is specified. If neither
|
| 263 |
+
edge_match nor edge_subst_cost are specified then edge
|
| 264 |
+
attributes are not considered.
|
| 265 |
+
|
| 266 |
+
node_subst_cost, node_del_cost, node_ins_cost : callable
|
| 267 |
+
Functions that return the costs of node substitution, node
|
| 268 |
+
deletion, and node insertion, respectively.
|
| 269 |
+
|
| 270 |
+
The functions will be called like
|
| 271 |
+
|
| 272 |
+
node_subst_cost(G1.nodes[n1], G2.nodes[n2]),
|
| 273 |
+
node_del_cost(G1.nodes[n1]),
|
| 274 |
+
node_ins_cost(G2.nodes[n2]).
|
| 275 |
+
|
| 276 |
+
That is, the functions will receive the node attribute
|
| 277 |
+
dictionaries as inputs. The functions are expected to return
|
| 278 |
+
positive numeric values.
|
| 279 |
+
|
| 280 |
+
Function node_subst_cost overrides node_match if specified.
|
| 281 |
+
If neither node_match nor node_subst_cost are specified then
|
| 282 |
+
default node substitution cost of 0 is used (node attributes
|
| 283 |
+
are not considered during matching).
|
| 284 |
+
|
| 285 |
+
If node_del_cost is not specified then default node deletion
|
| 286 |
+
cost of 1 is used. If node_ins_cost is not specified then
|
| 287 |
+
default node insertion cost of 1 is used.
|
| 288 |
+
|
| 289 |
+
edge_subst_cost, edge_del_cost, edge_ins_cost : callable
|
| 290 |
+
Functions that return the costs of edge substitution, edge
|
| 291 |
+
deletion, and edge insertion, respectively.
|
| 292 |
+
|
| 293 |
+
The functions will be called like
|
| 294 |
+
|
| 295 |
+
edge_subst_cost(G1[u1][v1], G2[u2][v2]),
|
| 296 |
+
edge_del_cost(G1[u1][v1]),
|
| 297 |
+
edge_ins_cost(G2[u2][v2]).
|
| 298 |
+
|
| 299 |
+
That is, the functions will receive the edge attribute
|
| 300 |
+
dictionaries as inputs. The functions are expected to return
|
| 301 |
+
positive numeric values.
|
| 302 |
+
|
| 303 |
+
Function edge_subst_cost overrides edge_match if specified.
|
| 304 |
+
If neither edge_match nor edge_subst_cost are specified then
|
| 305 |
+
default edge substitution cost of 0 is used (edge attributes
|
| 306 |
+
are not considered during matching).
|
| 307 |
+
|
| 308 |
+
If edge_del_cost is not specified then default edge deletion
|
| 309 |
+
cost of 1 is used. If edge_ins_cost is not specified then
|
| 310 |
+
default edge insertion cost of 1 is used.
|
| 311 |
+
|
| 312 |
+
upper_bound : numeric
|
| 313 |
+
Maximum edit distance to consider.
|
| 314 |
+
|
| 315 |
+
Returns
|
| 316 |
+
-------
|
| 317 |
+
edit_paths : list of tuples (node_edit_path, edge_edit_path)
|
| 318 |
+
- node_edit_path : list of tuples ``(u, v)`` indicating node transformations
|
| 319 |
+
between `G1` and `G2`. ``u`` is `None` for insertion, ``v`` is `None`
|
| 320 |
+
for deletion.
|
| 321 |
+
- edge_edit_path : list of tuples ``((u1, v1), (u2, v2))`` indicating edge
|
| 322 |
+
transformations between `G1` and `G2`. ``(None, (u2,v2))`` for insertion
|
| 323 |
+
and ``((u1,v1), None)`` for deletion.
|
| 324 |
+
|
| 325 |
+
cost : numeric
|
| 326 |
+
Optimal edit path cost (graph edit distance). When the cost
|
| 327 |
+
is zero, it indicates that `G1` and `G2` are isomorphic.
|
| 328 |
+
|
| 329 |
+
Examples
|
| 330 |
+
--------
|
| 331 |
+
>>> G1 = nx.cycle_graph(4)
|
| 332 |
+
>>> G2 = nx.wheel_graph(5)
|
| 333 |
+
>>> paths, cost = nx.optimal_edit_paths(G1, G2)
|
| 334 |
+
>>> len(paths)
|
| 335 |
+
40
|
| 336 |
+
>>> cost
|
| 337 |
+
5.0
|
| 338 |
+
|
| 339 |
+
Notes
|
| 340 |
+
-----
|
| 341 |
+
To transform `G1` into a graph isomorphic to `G2`, apply the node
|
| 342 |
+
and edge edits in the returned ``edit_paths``.
|
| 343 |
+
In the case of isomorphic graphs, the cost is zero, and the paths
|
| 344 |
+
represent different isomorphic mappings (isomorphisms). That is, the
|
| 345 |
+
edits involve renaming nodes and edges to match the structure of `G2`.
|
| 346 |
+
|
| 347 |
+
See Also
|
| 348 |
+
--------
|
| 349 |
+
graph_edit_distance, optimize_edit_paths
|
| 350 |
+
|
| 351 |
+
References
|
| 352 |
+
----------
|
| 353 |
+
.. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick
|
| 354 |
+
Martineau. An Exact Graph Edit Distance Algorithm for Solving
|
| 355 |
+
Pattern Recognition Problems. 4th International Conference on
|
| 356 |
+
Pattern Recognition Applications and Methods 2015, Jan 2015,
|
| 357 |
+
Lisbon, Portugal. 2015,
|
| 358 |
+
<10.5220/0005209202710278>. <hal-01168816>
|
| 359 |
+
https://hal.archives-ouvertes.fr/hal-01168816
|
| 360 |
+
|
| 361 |
+
"""
|
| 362 |
+
paths = []
|
| 363 |
+
bestcost = None
|
| 364 |
+
for vertex_path, edge_path, cost in optimize_edit_paths(
|
| 365 |
+
G1,
|
| 366 |
+
G2,
|
| 367 |
+
node_match,
|
| 368 |
+
edge_match,
|
| 369 |
+
node_subst_cost,
|
| 370 |
+
node_del_cost,
|
| 371 |
+
node_ins_cost,
|
| 372 |
+
edge_subst_cost,
|
| 373 |
+
edge_del_cost,
|
| 374 |
+
edge_ins_cost,
|
| 375 |
+
upper_bound,
|
| 376 |
+
False,
|
| 377 |
+
):
|
| 378 |
+
# assert bestcost is None or cost <= bestcost
|
| 379 |
+
if bestcost is not None and cost < bestcost:
|
| 380 |
+
paths = []
|
| 381 |
+
paths.append((vertex_path, edge_path))
|
| 382 |
+
bestcost = cost
|
| 383 |
+
return paths, bestcost
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
@nx._dispatchable(graphs={"G1": 0, "G2": 1})
|
| 387 |
+
def optimize_graph_edit_distance(
|
| 388 |
+
G1,
|
| 389 |
+
G2,
|
| 390 |
+
node_match=None,
|
| 391 |
+
edge_match=None,
|
| 392 |
+
node_subst_cost=None,
|
| 393 |
+
node_del_cost=None,
|
| 394 |
+
node_ins_cost=None,
|
| 395 |
+
edge_subst_cost=None,
|
| 396 |
+
edge_del_cost=None,
|
| 397 |
+
edge_ins_cost=None,
|
| 398 |
+
upper_bound=None,
|
| 399 |
+
):
|
| 400 |
+
"""Returns consecutive approximations of GED (graph edit distance)
|
| 401 |
+
between graphs G1 and G2.
|
| 402 |
+
|
| 403 |
+
Graph edit distance is a graph similarity measure analogous to
|
| 404 |
+
Levenshtein distance for strings. It is defined as minimum cost
|
| 405 |
+
of edit path (sequence of node and edge edit operations)
|
| 406 |
+
transforming graph G1 to graph isomorphic to G2.
|
| 407 |
+
|
| 408 |
+
Parameters
|
| 409 |
+
----------
|
| 410 |
+
G1, G2: graphs
|
| 411 |
+
The two graphs G1 and G2 must be of the same type.
|
| 412 |
+
|
| 413 |
+
node_match : callable
|
| 414 |
+
A function that returns True if node n1 in G1 and n2 in G2
|
| 415 |
+
should be considered equal during matching.
|
| 416 |
+
|
| 417 |
+
The function will be called like
|
| 418 |
+
|
| 419 |
+
node_match(G1.nodes[n1], G2.nodes[n2]).
|
| 420 |
+
|
| 421 |
+
That is, the function will receive the node attribute
|
| 422 |
+
dictionaries for n1 and n2 as inputs.
|
| 423 |
+
|
| 424 |
+
Ignored if node_subst_cost is specified. If neither
|
| 425 |
+
node_match nor node_subst_cost are specified then node
|
| 426 |
+
attributes are not considered.
|
| 427 |
+
|
| 428 |
+
edge_match : callable
|
| 429 |
+
A function that returns True if the edge attribute dictionaries
|
| 430 |
+
for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should
|
| 431 |
+
be considered equal during matching.
|
| 432 |
+
|
| 433 |
+
The function will be called like
|
| 434 |
+
|
| 435 |
+
edge_match(G1[u1][v1], G2[u2][v2]).
|
| 436 |
+
|
| 437 |
+
That is, the function will receive the edge attribute
|
| 438 |
+
dictionaries of the edges under consideration.
|
| 439 |
+
|
| 440 |
+
Ignored if edge_subst_cost is specified. If neither
|
| 441 |
+
edge_match nor edge_subst_cost are specified then edge
|
| 442 |
+
attributes are not considered.
|
| 443 |
+
|
| 444 |
+
node_subst_cost, node_del_cost, node_ins_cost : callable
|
| 445 |
+
Functions that return the costs of node substitution, node
|
| 446 |
+
deletion, and node insertion, respectively.
|
| 447 |
+
|
| 448 |
+
The functions will be called like
|
| 449 |
+
|
| 450 |
+
node_subst_cost(G1.nodes[n1], G2.nodes[n2]),
|
| 451 |
+
node_del_cost(G1.nodes[n1]),
|
| 452 |
+
node_ins_cost(G2.nodes[n2]).
|
| 453 |
+
|
| 454 |
+
That is, the functions will receive the node attribute
|
| 455 |
+
dictionaries as inputs. The functions are expected to return
|
| 456 |
+
positive numeric values.
|
| 457 |
+
|
| 458 |
+
Function node_subst_cost overrides node_match if specified.
|
| 459 |
+
If neither node_match nor node_subst_cost are specified then
|
| 460 |
+
default node substitution cost of 0 is used (node attributes
|
| 461 |
+
are not considered during matching).
|
| 462 |
+
|
| 463 |
+
If node_del_cost is not specified then default node deletion
|
| 464 |
+
cost of 1 is used. If node_ins_cost is not specified then
|
| 465 |
+
default node insertion cost of 1 is used.
|
| 466 |
+
|
| 467 |
+
edge_subst_cost, edge_del_cost, edge_ins_cost : callable
|
| 468 |
+
Functions that return the costs of edge substitution, edge
|
| 469 |
+
deletion, and edge insertion, respectively.
|
| 470 |
+
|
| 471 |
+
The functions will be called like
|
| 472 |
+
|
| 473 |
+
edge_subst_cost(G1[u1][v1], G2[u2][v2]),
|
| 474 |
+
edge_del_cost(G1[u1][v1]),
|
| 475 |
+
edge_ins_cost(G2[u2][v2]).
|
| 476 |
+
|
| 477 |
+
That is, the functions will receive the edge attribute
|
| 478 |
+
dictionaries as inputs. The functions are expected to return
|
| 479 |
+
positive numeric values.
|
| 480 |
+
|
| 481 |
+
Function edge_subst_cost overrides edge_match if specified.
|
| 482 |
+
If neither edge_match nor edge_subst_cost are specified then
|
| 483 |
+
default edge substitution cost of 0 is used (edge attributes
|
| 484 |
+
are not considered during matching).
|
| 485 |
+
|
| 486 |
+
If edge_del_cost is not specified then default edge deletion
|
| 487 |
+
cost of 1 is used. If edge_ins_cost is not specified then
|
| 488 |
+
default edge insertion cost of 1 is used.
|
| 489 |
+
|
| 490 |
+
upper_bound : numeric
|
| 491 |
+
Maximum edit distance to consider.
|
| 492 |
+
|
| 493 |
+
Returns
|
| 494 |
+
-------
|
| 495 |
+
Generator of consecutive approximations of graph edit distance.
|
| 496 |
+
|
| 497 |
+
Examples
|
| 498 |
+
--------
|
| 499 |
+
>>> G1 = nx.cycle_graph(6)
|
| 500 |
+
>>> G2 = nx.wheel_graph(7)
|
| 501 |
+
>>> for v in nx.optimize_graph_edit_distance(G1, G2):
|
| 502 |
+
... minv = v
|
| 503 |
+
>>> minv
|
| 504 |
+
7.0
|
| 505 |
+
|
| 506 |
+
See Also
|
| 507 |
+
--------
|
| 508 |
+
graph_edit_distance, optimize_edit_paths
|
| 509 |
+
|
| 510 |
+
References
|
| 511 |
+
----------
|
| 512 |
+
.. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick
|
| 513 |
+
Martineau. An Exact Graph Edit Distance Algorithm for Solving
|
| 514 |
+
Pattern Recognition Problems. 4th International Conference on
|
| 515 |
+
Pattern Recognition Applications and Methods 2015, Jan 2015,
|
| 516 |
+
Lisbon, Portugal. 2015,
|
| 517 |
+
<10.5220/0005209202710278>. <hal-01168816>
|
| 518 |
+
https://hal.archives-ouvertes.fr/hal-01168816
|
| 519 |
+
"""
|
| 520 |
+
for _, _, cost in optimize_edit_paths(
|
| 521 |
+
G1,
|
| 522 |
+
G2,
|
| 523 |
+
node_match,
|
| 524 |
+
edge_match,
|
| 525 |
+
node_subst_cost,
|
| 526 |
+
node_del_cost,
|
| 527 |
+
node_ins_cost,
|
| 528 |
+
edge_subst_cost,
|
| 529 |
+
edge_del_cost,
|
| 530 |
+
edge_ins_cost,
|
| 531 |
+
upper_bound,
|
| 532 |
+
True,
|
| 533 |
+
):
|
| 534 |
+
yield cost
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
@nx._dispatchable(
|
| 538 |
+
graphs={"G1": 0, "G2": 1}, preserve_edge_attrs=True, preserve_node_attrs=True
|
| 539 |
+
)
|
| 540 |
+
def optimize_edit_paths(
|
| 541 |
+
G1,
|
| 542 |
+
G2,
|
| 543 |
+
node_match=None,
|
| 544 |
+
edge_match=None,
|
| 545 |
+
node_subst_cost=None,
|
| 546 |
+
node_del_cost=None,
|
| 547 |
+
node_ins_cost=None,
|
| 548 |
+
edge_subst_cost=None,
|
| 549 |
+
edge_del_cost=None,
|
| 550 |
+
edge_ins_cost=None,
|
| 551 |
+
upper_bound=None,
|
| 552 |
+
strictly_decreasing=True,
|
| 553 |
+
roots=None,
|
| 554 |
+
timeout=None,
|
| 555 |
+
):
|
| 556 |
+
"""GED (graph edit distance) calculation: advanced interface.
|
| 557 |
+
|
| 558 |
+
Graph edit path is a sequence of node and edge edit operations
|
| 559 |
+
transforming graph G1 to graph isomorphic to G2. Edit operations
|
| 560 |
+
include substitutions, deletions, and insertions.
|
| 561 |
+
|
| 562 |
+
Graph edit distance is defined as minimum cost of edit path.
|
| 563 |
+
|
| 564 |
+
Parameters
|
| 565 |
+
----------
|
| 566 |
+
G1, G2: graphs
|
| 567 |
+
The two graphs G1 and G2 must be of the same type.
|
| 568 |
+
|
| 569 |
+
node_match : callable
|
| 570 |
+
A function that returns True if node n1 in G1 and n2 in G2
|
| 571 |
+
should be considered equal during matching.
|
| 572 |
+
|
| 573 |
+
The function will be called like
|
| 574 |
+
|
| 575 |
+
node_match(G1.nodes[n1], G2.nodes[n2]).
|
| 576 |
+
|
| 577 |
+
That is, the function will receive the node attribute
|
| 578 |
+
dictionaries for n1 and n2 as inputs.
|
| 579 |
+
|
| 580 |
+
Ignored if node_subst_cost is specified. If neither
|
| 581 |
+
node_match nor node_subst_cost are specified then node
|
| 582 |
+
attributes are not considered.
|
| 583 |
+
|
| 584 |
+
edge_match : callable
|
| 585 |
+
A function that returns True if the edge attribute dictionaries
|
| 586 |
+
for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should
|
| 587 |
+
be considered equal during matching.
|
| 588 |
+
|
| 589 |
+
The function will be called like
|
| 590 |
+
|
| 591 |
+
edge_match(G1[u1][v1], G2[u2][v2]).
|
| 592 |
+
|
| 593 |
+
That is, the function will receive the edge attribute
|
| 594 |
+
dictionaries of the edges under consideration.
|
| 595 |
+
|
| 596 |
+
Ignored if edge_subst_cost is specified. If neither
|
| 597 |
+
edge_match nor edge_subst_cost are specified then edge
|
| 598 |
+
attributes are not considered.
|
| 599 |
+
|
| 600 |
+
node_subst_cost, node_del_cost, node_ins_cost : callable
|
| 601 |
+
Functions that return the costs of node substitution, node
|
| 602 |
+
deletion, and node insertion, respectively.
|
| 603 |
+
|
| 604 |
+
The functions will be called like
|
| 605 |
+
|
| 606 |
+
node_subst_cost(G1.nodes[n1], G2.nodes[n2]),
|
| 607 |
+
node_del_cost(G1.nodes[n1]),
|
| 608 |
+
node_ins_cost(G2.nodes[n2]).
|
| 609 |
+
|
| 610 |
+
That is, the functions will receive the node attribute
|
| 611 |
+
dictionaries as inputs. The functions are expected to return
|
| 612 |
+
positive numeric values.
|
| 613 |
+
|
| 614 |
+
Function node_subst_cost overrides node_match if specified.
|
| 615 |
+
If neither node_match nor node_subst_cost are specified then
|
| 616 |
+
default node substitution cost of 0 is used (node attributes
|
| 617 |
+
are not considered during matching).
|
| 618 |
+
|
| 619 |
+
If node_del_cost is not specified then default node deletion
|
| 620 |
+
cost of 1 is used. If node_ins_cost is not specified then
|
| 621 |
+
default node insertion cost of 1 is used.
|
| 622 |
+
|
| 623 |
+
edge_subst_cost, edge_del_cost, edge_ins_cost : callable
|
| 624 |
+
Functions that return the costs of edge substitution, edge
|
| 625 |
+
deletion, and edge insertion, respectively.
|
| 626 |
+
|
| 627 |
+
The functions will be called like
|
| 628 |
+
|
| 629 |
+
edge_subst_cost(G1[u1][v1], G2[u2][v2]),
|
| 630 |
+
edge_del_cost(G1[u1][v1]),
|
| 631 |
+
edge_ins_cost(G2[u2][v2]).
|
| 632 |
+
|
| 633 |
+
That is, the functions will receive the edge attribute
|
| 634 |
+
dictionaries as inputs. The functions are expected to return
|
| 635 |
+
positive numeric values.
|
| 636 |
+
|
| 637 |
+
Function edge_subst_cost overrides edge_match if specified.
|
| 638 |
+
If neither edge_match nor edge_subst_cost are specified then
|
| 639 |
+
default edge substitution cost of 0 is used (edge attributes
|
| 640 |
+
are not considered during matching).
|
| 641 |
+
|
| 642 |
+
If edge_del_cost is not specified then default edge deletion
|
| 643 |
+
cost of 1 is used. If edge_ins_cost is not specified then
|
| 644 |
+
default edge insertion cost of 1 is used.
|
| 645 |
+
|
| 646 |
+
upper_bound : numeric
|
| 647 |
+
Maximum edit distance to consider.
|
| 648 |
+
|
| 649 |
+
strictly_decreasing : bool
|
| 650 |
+
If True, return consecutive approximations of strictly
|
| 651 |
+
decreasing cost. Otherwise, return all edit paths of cost
|
| 652 |
+
less than or equal to the previous minimum cost.
|
| 653 |
+
|
| 654 |
+
roots : 2-tuple
|
| 655 |
+
Tuple where first element is a node in G1 and the second
|
| 656 |
+
is a node in G2.
|
| 657 |
+
These nodes are forced to be matched in the comparison to
|
| 658 |
+
allow comparison between rooted graphs.
|
| 659 |
+
|
| 660 |
+
timeout : numeric
|
| 661 |
+
Maximum number of seconds to execute.
|
| 662 |
+
After timeout is met, the current best GED is returned.
|
| 663 |
+
|
| 664 |
+
Returns
|
| 665 |
+
-------
|
| 666 |
+
Generator of tuples (node_edit_path, edge_edit_path, cost)
|
| 667 |
+
node_edit_path : list of tuples (u, v)
|
| 668 |
+
edge_edit_path : list of tuples ((u1, v1), (u2, v2))
|
| 669 |
+
cost : numeric
|
| 670 |
+
|
| 671 |
+
See Also
|
| 672 |
+
--------
|
| 673 |
+
graph_edit_distance, optimize_graph_edit_distance, optimal_edit_paths
|
| 674 |
+
|
| 675 |
+
References
|
| 676 |
+
----------
|
| 677 |
+
.. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick
|
| 678 |
+
Martineau. An Exact Graph Edit Distance Algorithm for Solving
|
| 679 |
+
Pattern Recognition Problems. 4th International Conference on
|
| 680 |
+
Pattern Recognition Applications and Methods 2015, Jan 2015,
|
| 681 |
+
Lisbon, Portugal. 2015,
|
| 682 |
+
<10.5220/0005209202710278>. <hal-01168816>
|
| 683 |
+
https://hal.archives-ouvertes.fr/hal-01168816
|
| 684 |
+
|
| 685 |
+
"""
|
| 686 |
+
# TODO: support DiGraph
|
| 687 |
+
|
| 688 |
+
import numpy as np
|
| 689 |
+
import scipy as sp
|
| 690 |
+
|
| 691 |
+
@dataclass
|
| 692 |
+
class CostMatrix:
|
| 693 |
+
C: ...
|
| 694 |
+
lsa_row_ind: ...
|
| 695 |
+
lsa_col_ind: ...
|
| 696 |
+
ls: ...
|
| 697 |
+
|
| 698 |
+
def make_CostMatrix(C, m, n):
|
| 699 |
+
# assert(C.shape == (m + n, m + n))
|
| 700 |
+
lsa_row_ind, lsa_col_ind = sp.optimize.linear_sum_assignment(C)
|
| 701 |
+
|
| 702 |
+
# Fixup dummy assignments:
|
| 703 |
+
# each substitution i<->j should have dummy assignment m+j<->n+i
|
| 704 |
+
# NOTE: fast reduce of Cv relies on it
|
| 705 |
+
# Create masks for substitution and dummy indices
|
| 706 |
+
is_subst = (lsa_row_ind < m) & (lsa_col_ind < n)
|
| 707 |
+
is_dummy = (lsa_row_ind >= m) & (lsa_col_ind >= n)
|
| 708 |
+
|
| 709 |
+
# Map dummy assignments to the correct indices
|
| 710 |
+
lsa_row_ind[is_dummy] = lsa_col_ind[is_subst] + m
|
| 711 |
+
lsa_col_ind[is_dummy] = lsa_row_ind[is_subst] + n
|
| 712 |
+
|
| 713 |
+
return CostMatrix(
|
| 714 |
+
C, lsa_row_ind, lsa_col_ind, C[lsa_row_ind, lsa_col_ind].sum()
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
def extract_C(C, i, j, m, n):
|
| 718 |
+
# assert(C.shape == (m + n, m + n))
|
| 719 |
+
row_ind = [k in i or k - m in j for k in range(m + n)]
|
| 720 |
+
col_ind = [k in j or k - n in i for k in range(m + n)]
|
| 721 |
+
return C[row_ind, :][:, col_ind]
|
| 722 |
+
|
| 723 |
+
def reduce_C(C, i, j, m, n):
|
| 724 |
+
# assert(C.shape == (m + n, m + n))
|
| 725 |
+
row_ind = [k not in i and k - m not in j for k in range(m + n)]
|
| 726 |
+
col_ind = [k not in j and k - n not in i for k in range(m + n)]
|
| 727 |
+
return C[row_ind, :][:, col_ind]
|
| 728 |
+
|
| 729 |
+
def reduce_ind(ind, i):
|
| 730 |
+
# assert set(ind) == set(range(len(ind)))
|
| 731 |
+
rind = ind[[k not in i for k in ind]]
|
| 732 |
+
for k in set(i):
|
| 733 |
+
rind[rind >= k] -= 1
|
| 734 |
+
return rind
|
| 735 |
+
|
| 736 |
+
def match_edges(u, v, pending_g, pending_h, Ce, matched_uv=None):
|
| 737 |
+
"""
|
| 738 |
+
Parameters:
|
| 739 |
+
u, v: matched vertices, u=None or v=None for
|
| 740 |
+
deletion/insertion
|
| 741 |
+
pending_g, pending_h: lists of edges not yet mapped
|
| 742 |
+
Ce: CostMatrix of pending edge mappings
|
| 743 |
+
matched_uv: partial vertex edit path
|
| 744 |
+
list of tuples (u, v) of previously matched vertex
|
| 745 |
+
mappings u<->v, u=None or v=None for
|
| 746 |
+
deletion/insertion
|
| 747 |
+
|
| 748 |
+
Returns:
|
| 749 |
+
list of (i, j): indices of edge mappings g<->h
|
| 750 |
+
localCe: local CostMatrix of edge mappings
|
| 751 |
+
(basically submatrix of Ce at cross of rows i, cols j)
|
| 752 |
+
"""
|
| 753 |
+
M = len(pending_g)
|
| 754 |
+
N = len(pending_h)
|
| 755 |
+
# assert Ce.C.shape == (M + N, M + N)
|
| 756 |
+
|
| 757 |
+
# only attempt to match edges after one node match has been made
|
| 758 |
+
# this will stop self-edges on the first node being automatically deleted
|
| 759 |
+
# even when a substitution is the better option
|
| 760 |
+
|
| 761 |
+
substitution_possible = M and N
|
| 762 |
+
at_least_one_node_match = matched_uv is None or len(matched_uv) == 0
|
| 763 |
+
if at_least_one_node_match and substitution_possible:
|
| 764 |
+
g_ind = []
|
| 765 |
+
h_ind = []
|
| 766 |
+
else:
|
| 767 |
+
g_ind = [
|
| 768 |
+
i
|
| 769 |
+
for i in range(M)
|
| 770 |
+
if pending_g[i][:2] == (u, u)
|
| 771 |
+
or any(
|
| 772 |
+
pending_g[i][:2] in ((p, u), (u, p), (p, p)) for p, q in matched_uv
|
| 773 |
+
)
|
| 774 |
+
]
|
| 775 |
+
h_ind = [
|
| 776 |
+
j
|
| 777 |
+
for j in range(N)
|
| 778 |
+
if pending_h[j][:2] == (v, v)
|
| 779 |
+
or any(
|
| 780 |
+
pending_h[j][:2] in ((q, v), (v, q), (q, q)) for p, q in matched_uv
|
| 781 |
+
)
|
| 782 |
+
]
|
| 783 |
+
|
| 784 |
+
m = len(g_ind)
|
| 785 |
+
n = len(h_ind)
|
| 786 |
+
|
| 787 |
+
if m or n:
|
| 788 |
+
C = extract_C(Ce.C, g_ind, h_ind, M, N)
|
| 789 |
+
# assert C.shape == (m + n, m + n)
|
| 790 |
+
|
| 791 |
+
# Forbid structurally invalid matches
|
| 792 |
+
# NOTE: inf remembered from Ce construction
|
| 793 |
+
for k, i in enumerate(g_ind):
|
| 794 |
+
g = pending_g[i][:2]
|
| 795 |
+
for l, j in enumerate(h_ind):
|
| 796 |
+
h = pending_h[j][:2]
|
| 797 |
+
if nx.is_directed(G1) or nx.is_directed(G2):
|
| 798 |
+
if any(
|
| 799 |
+
g == (p, u) and h == (q, v) or g == (u, p) and h == (v, q)
|
| 800 |
+
for p, q in matched_uv
|
| 801 |
+
):
|
| 802 |
+
continue
|
| 803 |
+
else:
|
| 804 |
+
if any(
|
| 805 |
+
g in ((p, u), (u, p)) and h in ((q, v), (v, q))
|
| 806 |
+
for p, q in matched_uv
|
| 807 |
+
):
|
| 808 |
+
continue
|
| 809 |
+
if g == (u, u) or any(g == (p, p) for p, q in matched_uv):
|
| 810 |
+
continue
|
| 811 |
+
if h == (v, v) or any(h == (q, q) for p, q in matched_uv):
|
| 812 |
+
continue
|
| 813 |
+
C[k, l] = inf
|
| 814 |
+
|
| 815 |
+
localCe = make_CostMatrix(C, m, n)
|
| 816 |
+
ij = [
|
| 817 |
+
(
|
| 818 |
+
g_ind[k] if k < m else M + h_ind[l],
|
| 819 |
+
h_ind[l] if l < n else N + g_ind[k],
|
| 820 |
+
)
|
| 821 |
+
for k, l in zip(localCe.lsa_row_ind, localCe.lsa_col_ind)
|
| 822 |
+
if k < m or l < n
|
| 823 |
+
]
|
| 824 |
+
|
| 825 |
+
else:
|
| 826 |
+
ij = []
|
| 827 |
+
localCe = CostMatrix(np.empty((0, 0)), [], [], 0)
|
| 828 |
+
|
| 829 |
+
return ij, localCe
|
| 830 |
+
|
| 831 |
+
def reduce_Ce(Ce, ij, m, n):
|
| 832 |
+
if len(ij):
|
| 833 |
+
i, j = zip(*ij)
|
| 834 |
+
m_i = m - sum(1 for t in i if t < m)
|
| 835 |
+
n_j = n - sum(1 for t in j if t < n)
|
| 836 |
+
return make_CostMatrix(reduce_C(Ce.C, i, j, m, n), m_i, n_j)
|
| 837 |
+
return Ce
|
| 838 |
+
|
| 839 |
+
def get_edit_ops(
|
| 840 |
+
matched_uv, pending_u, pending_v, Cv, pending_g, pending_h, Ce, matched_cost
|
| 841 |
+
):
|
| 842 |
+
"""
|
| 843 |
+
Parameters:
|
| 844 |
+
matched_uv: partial vertex edit path
|
| 845 |
+
list of tuples (u, v) of vertex mappings u<->v,
|
| 846 |
+
u=None or v=None for deletion/insertion
|
| 847 |
+
pending_u, pending_v: lists of vertices not yet mapped
|
| 848 |
+
Cv: CostMatrix of pending vertex mappings
|
| 849 |
+
pending_g, pending_h: lists of edges not yet mapped
|
| 850 |
+
Ce: CostMatrix of pending edge mappings
|
| 851 |
+
matched_cost: cost of partial edit path
|
| 852 |
+
|
| 853 |
+
Returns:
|
| 854 |
+
sequence of
|
| 855 |
+
(i, j): indices of vertex mapping u<->v
|
| 856 |
+
Cv_ij: reduced CostMatrix of pending vertex mappings
|
| 857 |
+
(basically Cv with row i, col j removed)
|
| 858 |
+
list of (x, y): indices of edge mappings g<->h
|
| 859 |
+
Ce_xy: reduced CostMatrix of pending edge mappings
|
| 860 |
+
(basically Ce with rows x, cols y removed)
|
| 861 |
+
cost: total cost of edit operation
|
| 862 |
+
NOTE: most promising ops first
|
| 863 |
+
"""
|
| 864 |
+
m = len(pending_u)
|
| 865 |
+
n = len(pending_v)
|
| 866 |
+
# assert Cv.C.shape == (m + n, m + n)
|
| 867 |
+
|
| 868 |
+
# 1) a vertex mapping from optimal linear sum assignment
|
| 869 |
+
i, j = min(
|
| 870 |
+
(k, l) for k, l in zip(Cv.lsa_row_ind, Cv.lsa_col_ind) if k < m or l < n
|
| 871 |
+
)
|
| 872 |
+
xy, localCe = match_edges(
|
| 873 |
+
pending_u[i] if i < m else None,
|
| 874 |
+
pending_v[j] if j < n else None,
|
| 875 |
+
pending_g,
|
| 876 |
+
pending_h,
|
| 877 |
+
Ce,
|
| 878 |
+
matched_uv,
|
| 879 |
+
)
|
| 880 |
+
Ce_xy = reduce_Ce(Ce, xy, len(pending_g), len(pending_h))
|
| 881 |
+
# assert Ce.ls <= localCe.ls + Ce_xy.ls
|
| 882 |
+
if prune(matched_cost + Cv.ls + localCe.ls + Ce_xy.ls):
|
| 883 |
+
pass
|
| 884 |
+
else:
|
| 885 |
+
# get reduced Cv efficiently
|
| 886 |
+
Cv_ij = CostMatrix(
|
| 887 |
+
reduce_C(Cv.C, (i,), (j,), m, n),
|
| 888 |
+
reduce_ind(Cv.lsa_row_ind, (i, m + j)),
|
| 889 |
+
reduce_ind(Cv.lsa_col_ind, (j, n + i)),
|
| 890 |
+
Cv.ls - Cv.C[i, j],
|
| 891 |
+
)
|
| 892 |
+
yield (i, j), Cv_ij, xy, Ce_xy, Cv.C[i, j] + localCe.ls
|
| 893 |
+
|
| 894 |
+
# 2) other candidates, sorted by lower-bound cost estimate
|
| 895 |
+
other = []
|
| 896 |
+
fixed_i, fixed_j = i, j
|
| 897 |
+
if m <= n:
|
| 898 |
+
candidates = (
|
| 899 |
+
(t, fixed_j)
|
| 900 |
+
for t in range(m + n)
|
| 901 |
+
if t != fixed_i and (t < m or t == m + fixed_j)
|
| 902 |
+
)
|
| 903 |
+
else:
|
| 904 |
+
candidates = (
|
| 905 |
+
(fixed_i, t)
|
| 906 |
+
for t in range(m + n)
|
| 907 |
+
if t != fixed_j and (t < n or t == n + fixed_i)
|
| 908 |
+
)
|
| 909 |
+
for i, j in candidates:
|
| 910 |
+
if prune(matched_cost + Cv.C[i, j] + Ce.ls):
|
| 911 |
+
continue
|
| 912 |
+
Cv_ij = make_CostMatrix(
|
| 913 |
+
reduce_C(Cv.C, (i,), (j,), m, n),
|
| 914 |
+
m - 1 if i < m else m,
|
| 915 |
+
n - 1 if j < n else n,
|
| 916 |
+
)
|
| 917 |
+
# assert Cv.ls <= Cv.C[i, j] + Cv_ij.ls
|
| 918 |
+
if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + Ce.ls):
|
| 919 |
+
continue
|
| 920 |
+
xy, localCe = match_edges(
|
| 921 |
+
pending_u[i] if i < m else None,
|
| 922 |
+
pending_v[j] if j < n else None,
|
| 923 |
+
pending_g,
|
| 924 |
+
pending_h,
|
| 925 |
+
Ce,
|
| 926 |
+
matched_uv,
|
| 927 |
+
)
|
| 928 |
+
if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + localCe.ls):
|
| 929 |
+
continue
|
| 930 |
+
Ce_xy = reduce_Ce(Ce, xy, len(pending_g), len(pending_h))
|
| 931 |
+
# assert Ce.ls <= localCe.ls + Ce_xy.ls
|
| 932 |
+
if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + localCe.ls + Ce_xy.ls):
|
| 933 |
+
continue
|
| 934 |
+
other.append(((i, j), Cv_ij, xy, Ce_xy, Cv.C[i, j] + localCe.ls))
|
| 935 |
+
|
| 936 |
+
yield from sorted(other, key=lambda t: t[4] + t[1].ls + t[3].ls)
|
| 937 |
+
|
| 938 |
+
def get_edit_paths(
|
| 939 |
+
matched_uv,
|
| 940 |
+
pending_u,
|
| 941 |
+
pending_v,
|
| 942 |
+
Cv,
|
| 943 |
+
matched_gh,
|
| 944 |
+
pending_g,
|
| 945 |
+
pending_h,
|
| 946 |
+
Ce,
|
| 947 |
+
matched_cost,
|
| 948 |
+
):
|
| 949 |
+
"""
|
| 950 |
+
Parameters:
|
| 951 |
+
matched_uv: partial vertex edit path
|
| 952 |
+
list of tuples (u, v) of vertex mappings u<->v,
|
| 953 |
+
u=None or v=None for deletion/insertion
|
| 954 |
+
pending_u, pending_v: lists of vertices not yet mapped
|
| 955 |
+
Cv: CostMatrix of pending vertex mappings
|
| 956 |
+
matched_gh: partial edge edit path
|
| 957 |
+
list of tuples (g, h) of edge mappings g<->h,
|
| 958 |
+
g=None or h=None for deletion/insertion
|
| 959 |
+
pending_g, pending_h: lists of edges not yet mapped
|
| 960 |
+
Ce: CostMatrix of pending edge mappings
|
| 961 |
+
matched_cost: cost of partial edit path
|
| 962 |
+
|
| 963 |
+
Returns:
|
| 964 |
+
sequence of (vertex_path, edge_path, cost)
|
| 965 |
+
vertex_path: complete vertex edit path
|
| 966 |
+
list of tuples (u, v) of vertex mappings u<->v,
|
| 967 |
+
u=None or v=None for deletion/insertion
|
| 968 |
+
edge_path: complete edge edit path
|
| 969 |
+
list of tuples (g, h) of edge mappings g<->h,
|
| 970 |
+
g=None or h=None for deletion/insertion
|
| 971 |
+
cost: total cost of edit path
|
| 972 |
+
NOTE: path costs are non-increasing
|
| 973 |
+
"""
|
| 974 |
+
if prune(matched_cost + Cv.ls + Ce.ls):
|
| 975 |
+
return
|
| 976 |
+
|
| 977 |
+
if not max(len(pending_u), len(pending_v)):
|
| 978 |
+
# assert not len(pending_g)
|
| 979 |
+
# assert not len(pending_h)
|
| 980 |
+
# path completed!
|
| 981 |
+
# assert matched_cost <= maxcost_value
|
| 982 |
+
nonlocal maxcost_value
|
| 983 |
+
maxcost_value = min(maxcost_value, matched_cost)
|
| 984 |
+
yield matched_uv, matched_gh, matched_cost
|
| 985 |
+
|
| 986 |
+
else:
|
| 987 |
+
edit_ops = get_edit_ops(
|
| 988 |
+
matched_uv,
|
| 989 |
+
pending_u,
|
| 990 |
+
pending_v,
|
| 991 |
+
Cv,
|
| 992 |
+
pending_g,
|
| 993 |
+
pending_h,
|
| 994 |
+
Ce,
|
| 995 |
+
matched_cost,
|
| 996 |
+
)
|
| 997 |
+
for ij, Cv_ij, xy, Ce_xy, edit_cost in edit_ops:
|
| 998 |
+
i, j = ij
|
| 999 |
+
# assert Cv.C[i, j] + sum(Ce.C[t] for t in xy) == edit_cost
|
| 1000 |
+
if prune(matched_cost + edit_cost + Cv_ij.ls + Ce_xy.ls):
|
| 1001 |
+
continue
|
| 1002 |
+
|
| 1003 |
+
# dive deeper
|
| 1004 |
+
u = pending_u.pop(i) if i < len(pending_u) else None
|
| 1005 |
+
v = pending_v.pop(j) if j < len(pending_v) else None
|
| 1006 |
+
matched_uv.append((u, v))
|
| 1007 |
+
for x, y in xy:
|
| 1008 |
+
len_g = len(pending_g)
|
| 1009 |
+
len_h = len(pending_h)
|
| 1010 |
+
matched_gh.append(
|
| 1011 |
+
(
|
| 1012 |
+
pending_g[x] if x < len_g else None,
|
| 1013 |
+
pending_h[y] if y < len_h else None,
|
| 1014 |
+
)
|
| 1015 |
+
)
|
| 1016 |
+
sortedx = sorted(x for x, y in xy)
|
| 1017 |
+
sortedy = sorted(y for x, y in xy)
|
| 1018 |
+
G = [
|
| 1019 |
+
(pending_g.pop(x) if x < len(pending_g) else None)
|
| 1020 |
+
for x in reversed(sortedx)
|
| 1021 |
+
]
|
| 1022 |
+
H = [
|
| 1023 |
+
(pending_h.pop(y) if y < len(pending_h) else None)
|
| 1024 |
+
for y in reversed(sortedy)
|
| 1025 |
+
]
|
| 1026 |
+
|
| 1027 |
+
yield from get_edit_paths(
|
| 1028 |
+
matched_uv,
|
| 1029 |
+
pending_u,
|
| 1030 |
+
pending_v,
|
| 1031 |
+
Cv_ij,
|
| 1032 |
+
matched_gh,
|
| 1033 |
+
pending_g,
|
| 1034 |
+
pending_h,
|
| 1035 |
+
Ce_xy,
|
| 1036 |
+
matched_cost + edit_cost,
|
| 1037 |
+
)
|
| 1038 |
+
|
| 1039 |
+
# backtrack
|
| 1040 |
+
if u is not None:
|
| 1041 |
+
pending_u.insert(i, u)
|
| 1042 |
+
if v is not None:
|
| 1043 |
+
pending_v.insert(j, v)
|
| 1044 |
+
matched_uv.pop()
|
| 1045 |
+
for x, g in zip(sortedx, reversed(G)):
|
| 1046 |
+
if g is not None:
|
| 1047 |
+
pending_g.insert(x, g)
|
| 1048 |
+
for y, h in zip(sortedy, reversed(H)):
|
| 1049 |
+
if h is not None:
|
| 1050 |
+
pending_h.insert(y, h)
|
| 1051 |
+
for _ in xy:
|
| 1052 |
+
matched_gh.pop()
|
| 1053 |
+
|
| 1054 |
+
# Initialization
|
| 1055 |
+
|
| 1056 |
+
pending_u = list(G1.nodes)
|
| 1057 |
+
pending_v = list(G2.nodes)
|
| 1058 |
+
|
| 1059 |
+
initial_cost = 0
|
| 1060 |
+
if roots:
|
| 1061 |
+
root_u, root_v = roots
|
| 1062 |
+
if root_u not in pending_u or root_v not in pending_v:
|
| 1063 |
+
raise nx.NodeNotFound("Root node not in graph.")
|
| 1064 |
+
|
| 1065 |
+
# remove roots from pending
|
| 1066 |
+
pending_u.remove(root_u)
|
| 1067 |
+
pending_v.remove(root_v)
|
| 1068 |
+
|
| 1069 |
+
# cost matrix of vertex mappings
|
| 1070 |
+
m = len(pending_u)
|
| 1071 |
+
n = len(pending_v)
|
| 1072 |
+
C = np.zeros((m + n, m + n))
|
| 1073 |
+
if node_subst_cost:
|
| 1074 |
+
C[0:m, 0:n] = np.array(
|
| 1075 |
+
[
|
| 1076 |
+
node_subst_cost(G1.nodes[u], G2.nodes[v])
|
| 1077 |
+
for u in pending_u
|
| 1078 |
+
for v in pending_v
|
| 1079 |
+
]
|
| 1080 |
+
).reshape(m, n)
|
| 1081 |
+
if roots:
|
| 1082 |
+
initial_cost = node_subst_cost(G1.nodes[root_u], G2.nodes[root_v])
|
| 1083 |
+
elif node_match:
|
| 1084 |
+
C[0:m, 0:n] = np.array(
|
| 1085 |
+
[
|
| 1086 |
+
1 - int(node_match(G1.nodes[u], G2.nodes[v]))
|
| 1087 |
+
for u in pending_u
|
| 1088 |
+
for v in pending_v
|
| 1089 |
+
]
|
| 1090 |
+
).reshape(m, n)
|
| 1091 |
+
if roots:
|
| 1092 |
+
initial_cost = 1 - node_match(G1.nodes[root_u], G2.nodes[root_v])
|
| 1093 |
+
else:
|
| 1094 |
+
# all zeroes
|
| 1095 |
+
pass
|
| 1096 |
+
# assert not min(m, n) or C[0:m, 0:n].min() >= 0
|
| 1097 |
+
if node_del_cost:
|
| 1098 |
+
del_costs = [node_del_cost(G1.nodes[u]) for u in pending_u]
|
| 1099 |
+
else:
|
| 1100 |
+
del_costs = [1] * len(pending_u)
|
| 1101 |
+
# assert not m or min(del_costs) >= 0
|
| 1102 |
+
if node_ins_cost:
|
| 1103 |
+
ins_costs = [node_ins_cost(G2.nodes[v]) for v in pending_v]
|
| 1104 |
+
else:
|
| 1105 |
+
ins_costs = [1] * len(pending_v)
|
| 1106 |
+
# assert not n or min(ins_costs) >= 0
|
| 1107 |
+
inf = C[0:m, 0:n].sum() + sum(del_costs) + sum(ins_costs) + 1
|
| 1108 |
+
C[0:m, n : n + m] = np.array(
|
| 1109 |
+
[del_costs[i] if i == j else inf for i in range(m) for j in range(m)]
|
| 1110 |
+
).reshape(m, m)
|
| 1111 |
+
C[m : m + n, 0:n] = np.array(
|
| 1112 |
+
[ins_costs[i] if i == j else inf for i in range(n) for j in range(n)]
|
| 1113 |
+
).reshape(n, n)
|
| 1114 |
+
Cv = make_CostMatrix(C, m, n)
|
| 1115 |
+
|
| 1116 |
+
pending_g = list(G1.edges)
|
| 1117 |
+
pending_h = list(G2.edges)
|
| 1118 |
+
|
| 1119 |
+
# cost matrix of edge mappings
|
| 1120 |
+
m = len(pending_g)
|
| 1121 |
+
n = len(pending_h)
|
| 1122 |
+
C = np.zeros((m + n, m + n))
|
| 1123 |
+
if edge_subst_cost:
|
| 1124 |
+
C[0:m, 0:n] = np.array(
|
| 1125 |
+
[
|
| 1126 |
+
edge_subst_cost(G1.edges[g], G2.edges[h])
|
| 1127 |
+
for g in pending_g
|
| 1128 |
+
for h in pending_h
|
| 1129 |
+
]
|
| 1130 |
+
).reshape(m, n)
|
| 1131 |
+
elif edge_match:
|
| 1132 |
+
C[0:m, 0:n] = np.array(
|
| 1133 |
+
[
|
| 1134 |
+
1 - int(edge_match(G1.edges[g], G2.edges[h]))
|
| 1135 |
+
for g in pending_g
|
| 1136 |
+
for h in pending_h
|
| 1137 |
+
]
|
| 1138 |
+
).reshape(m, n)
|
| 1139 |
+
else:
|
| 1140 |
+
# all zeroes
|
| 1141 |
+
pass
|
| 1142 |
+
# assert not min(m, n) or C[0:m, 0:n].min() >= 0
|
| 1143 |
+
if edge_del_cost:
|
| 1144 |
+
del_costs = [edge_del_cost(G1.edges[g]) for g in pending_g]
|
| 1145 |
+
else:
|
| 1146 |
+
del_costs = [1] * len(pending_g)
|
| 1147 |
+
# assert not m or min(del_costs) >= 0
|
| 1148 |
+
if edge_ins_cost:
|
| 1149 |
+
ins_costs = [edge_ins_cost(G2.edges[h]) for h in pending_h]
|
| 1150 |
+
else:
|
| 1151 |
+
ins_costs = [1] * len(pending_h)
|
| 1152 |
+
# assert not n or min(ins_costs) >= 0
|
| 1153 |
+
inf = C[0:m, 0:n].sum() + sum(del_costs) + sum(ins_costs) + 1
|
| 1154 |
+
C[0:m, n : n + m] = np.array(
|
| 1155 |
+
[del_costs[i] if i == j else inf for i in range(m) for j in range(m)]
|
| 1156 |
+
).reshape(m, m)
|
| 1157 |
+
C[m : m + n, 0:n] = np.array(
|
| 1158 |
+
[ins_costs[i] if i == j else inf for i in range(n) for j in range(n)]
|
| 1159 |
+
).reshape(n, n)
|
| 1160 |
+
Ce = make_CostMatrix(C, m, n)
|
| 1161 |
+
|
| 1162 |
+
maxcost_value = Cv.C.sum() + Ce.C.sum() + 1
|
| 1163 |
+
|
| 1164 |
+
if timeout is not None:
|
| 1165 |
+
if timeout <= 0:
|
| 1166 |
+
raise nx.NetworkXError("Timeout value must be greater than 0")
|
| 1167 |
+
start = time.perf_counter()
|
| 1168 |
+
|
| 1169 |
+
def prune(cost):
|
| 1170 |
+
if timeout is not None:
|
| 1171 |
+
if time.perf_counter() - start > timeout:
|
| 1172 |
+
return True
|
| 1173 |
+
if upper_bound is not None:
|
| 1174 |
+
if cost > upper_bound:
|
| 1175 |
+
return True
|
| 1176 |
+
if cost > maxcost_value:
|
| 1177 |
+
return True
|
| 1178 |
+
if strictly_decreasing and cost >= maxcost_value:
|
| 1179 |
+
return True
|
| 1180 |
+
return False
|
| 1181 |
+
|
| 1182 |
+
# Now go!
|
| 1183 |
+
|
| 1184 |
+
done_uv = [] if roots is None else [roots]
|
| 1185 |
+
|
| 1186 |
+
for vertex_path, edge_path, cost in get_edit_paths(
|
| 1187 |
+
done_uv, pending_u, pending_v, Cv, [], pending_g, pending_h, Ce, initial_cost
|
| 1188 |
+
):
|
| 1189 |
+
# assert sorted(G1.nodes) == sorted(u for u, v in vertex_path if u is not None)
|
| 1190 |
+
# assert sorted(G2.nodes) == sorted(v for u, v in vertex_path if v is not None)
|
| 1191 |
+
# assert sorted(G1.edges) == sorted(g for g, h in edge_path if g is not None)
|
| 1192 |
+
# assert sorted(G2.edges) == sorted(h for g, h in edge_path if h is not None)
|
| 1193 |
+
# print(vertex_path, edge_path, cost, file = sys.stderr)
|
| 1194 |
+
# assert cost == maxcost_value
|
| 1195 |
+
yield list(vertex_path), list(edge_path), float(cost)
|
| 1196 |
+
|
| 1197 |
+
|
| 1198 |
+
@nx._dispatchable
|
| 1199 |
+
def simrank_similarity(
|
| 1200 |
+
G,
|
| 1201 |
+
source=None,
|
| 1202 |
+
target=None,
|
| 1203 |
+
importance_factor=0.9,
|
| 1204 |
+
max_iterations=1000,
|
| 1205 |
+
tolerance=1e-4,
|
| 1206 |
+
):
|
| 1207 |
+
"""Returns the SimRank similarity of nodes in the graph ``G``.
|
| 1208 |
+
|
| 1209 |
+
SimRank is a similarity metric that says "two objects are considered
|
| 1210 |
+
to be similar if they are referenced by similar objects." [1]_.
|
| 1211 |
+
|
| 1212 |
+
The pseudo-code definition from the paper is::
|
| 1213 |
+
|
| 1214 |
+
def simrank(G, u, v):
|
| 1215 |
+
in_neighbors_u = G.predecessors(u)
|
| 1216 |
+
in_neighbors_v = G.predecessors(v)
|
| 1217 |
+
scale = C / (len(in_neighbors_u) * len(in_neighbors_v))
|
| 1218 |
+
return scale * sum(
|
| 1219 |
+
simrank(G, w, x) for w, x in product(in_neighbors_u, in_neighbors_v)
|
| 1220 |
+
)
|
| 1221 |
+
|
| 1222 |
+
where ``G`` is the graph, ``u`` is the source, ``v`` is the target,
|
| 1223 |
+
and ``C`` is a float decay or importance factor between 0 and 1.
|
| 1224 |
+
|
| 1225 |
+
The SimRank algorithm for determining node similarity is defined in
|
| 1226 |
+
[2]_.
|
| 1227 |
+
|
| 1228 |
+
Parameters
|
| 1229 |
+
----------
|
| 1230 |
+
G : NetworkX graph
|
| 1231 |
+
A NetworkX graph
|
| 1232 |
+
|
| 1233 |
+
source : node
|
| 1234 |
+
If this is specified, the returned dictionary maps each node
|
| 1235 |
+
``v`` in the graph to the similarity between ``source`` and
|
| 1236 |
+
``v``.
|
| 1237 |
+
|
| 1238 |
+
target : node
|
| 1239 |
+
If both ``source`` and ``target`` are specified, the similarity
|
| 1240 |
+
value between ``source`` and ``target`` is returned. If
|
| 1241 |
+
``target`` is specified but ``source`` is not, this argument is
|
| 1242 |
+
ignored.
|
| 1243 |
+
|
| 1244 |
+
importance_factor : float
|
| 1245 |
+
The relative importance of indirect neighbors with respect to
|
| 1246 |
+
direct neighbors.
|
| 1247 |
+
|
| 1248 |
+
max_iterations : integer
|
| 1249 |
+
Maximum number of iterations.
|
| 1250 |
+
|
| 1251 |
+
tolerance : float
|
| 1252 |
+
Error tolerance used to check convergence. When an iteration of
|
| 1253 |
+
the algorithm finds that no similarity value changes more than
|
| 1254 |
+
this amount, the algorithm halts.
|
| 1255 |
+
|
| 1256 |
+
Returns
|
| 1257 |
+
-------
|
| 1258 |
+
similarity : dictionary or float
|
| 1259 |
+
If ``source`` and ``target`` are both ``None``, this returns a
|
| 1260 |
+
dictionary of dictionaries, where keys are node pairs and value
|
| 1261 |
+
are similarity of the pair of nodes.
|
| 1262 |
+
|
| 1263 |
+
If ``source`` is not ``None`` but ``target`` is, this returns a
|
| 1264 |
+
dictionary mapping node to the similarity of ``source`` and that
|
| 1265 |
+
node.
|
| 1266 |
+
|
| 1267 |
+
If neither ``source`` nor ``target`` is ``None``, this returns
|
| 1268 |
+
the similarity value for the given pair of nodes.
|
| 1269 |
+
|
| 1270 |
+
Raises
|
| 1271 |
+
------
|
| 1272 |
+
ExceededMaxIterations
|
| 1273 |
+
If the algorithm does not converge within ``max_iterations``.
|
| 1274 |
+
|
| 1275 |
+
NodeNotFound
|
| 1276 |
+
If either ``source`` or ``target`` is not in `G`.
|
| 1277 |
+
|
| 1278 |
+
Examples
|
| 1279 |
+
--------
|
| 1280 |
+
>>> G = nx.cycle_graph(2)
|
| 1281 |
+
>>> nx.simrank_similarity(G)
|
| 1282 |
+
{0: {0: 1.0, 1: 0.0}, 1: {0: 0.0, 1: 1.0}}
|
| 1283 |
+
>>> nx.simrank_similarity(G, source=0)
|
| 1284 |
+
{0: 1.0, 1: 0.0}
|
| 1285 |
+
>>> nx.simrank_similarity(G, source=0, target=0)
|
| 1286 |
+
1.0
|
| 1287 |
+
|
| 1288 |
+
The result of this function can be converted to a numpy array
|
| 1289 |
+
representing the SimRank matrix by using the node order of the
|
| 1290 |
+
graph to determine which row and column represent each node.
|
| 1291 |
+
Other ordering of nodes is also possible.
|
| 1292 |
+
|
| 1293 |
+
>>> import numpy as np
|
| 1294 |
+
>>> sim = nx.simrank_similarity(G)
|
| 1295 |
+
>>> np.array([[sim[u][v] for v in G] for u in G])
|
| 1296 |
+
array([[1., 0.],
|
| 1297 |
+
[0., 1.]])
|
| 1298 |
+
>>> sim_1d = nx.simrank_similarity(G, source=0)
|
| 1299 |
+
>>> np.array([sim[0][v] for v in G])
|
| 1300 |
+
array([1., 0.])
|
| 1301 |
+
|
| 1302 |
+
References
|
| 1303 |
+
----------
|
| 1304 |
+
.. [1] https://en.wikipedia.org/wiki/SimRank
|
| 1305 |
+
.. [2] G. Jeh and J. Widom.
|
| 1306 |
+
"SimRank: a measure of structural-context similarity",
|
| 1307 |
+
In KDD'02: Proceedings of the Eighth ACM SIGKDD
|
| 1308 |
+
International Conference on Knowledge Discovery and Data Mining,
|
| 1309 |
+
pp. 538--543. ACM Press, 2002.
|
| 1310 |
+
"""
|
| 1311 |
+
import numpy as np
|
| 1312 |
+
|
| 1313 |
+
nodelist = list(G)
|
| 1314 |
+
if source is not None:
|
| 1315 |
+
if source not in nodelist:
|
| 1316 |
+
raise nx.NodeNotFound(f"Source node {source} not in G")
|
| 1317 |
+
else:
|
| 1318 |
+
s_indx = nodelist.index(source)
|
| 1319 |
+
else:
|
| 1320 |
+
s_indx = None
|
| 1321 |
+
|
| 1322 |
+
if target is not None:
|
| 1323 |
+
if target not in nodelist:
|
| 1324 |
+
raise nx.NodeNotFound(f"Target node {target} not in G")
|
| 1325 |
+
else:
|
| 1326 |
+
t_indx = nodelist.index(target)
|
| 1327 |
+
else:
|
| 1328 |
+
t_indx = None
|
| 1329 |
+
|
| 1330 |
+
x = _simrank_similarity_numpy(
|
| 1331 |
+
G, s_indx, t_indx, importance_factor, max_iterations, tolerance
|
| 1332 |
+
)
|
| 1333 |
+
|
| 1334 |
+
if isinstance(x, np.ndarray):
|
| 1335 |
+
if x.ndim == 1:
|
| 1336 |
+
return dict(zip(G, x.tolist()))
|
| 1337 |
+
# else x.ndim == 2
|
| 1338 |
+
return {u: dict(zip(G, row)) for u, row in zip(G, x.tolist())}
|
| 1339 |
+
return float(x)
|
| 1340 |
+
|
| 1341 |
+
|
| 1342 |
+
def _simrank_similarity_python(
|
| 1343 |
+
G,
|
| 1344 |
+
source=None,
|
| 1345 |
+
target=None,
|
| 1346 |
+
importance_factor=0.9,
|
| 1347 |
+
max_iterations=1000,
|
| 1348 |
+
tolerance=1e-4,
|
| 1349 |
+
):
|
| 1350 |
+
"""Returns the SimRank similarity of nodes in the graph ``G``.
|
| 1351 |
+
|
| 1352 |
+
This pure Python version is provided for pedagogical purposes.
|
| 1353 |
+
|
| 1354 |
+
Examples
|
| 1355 |
+
--------
|
| 1356 |
+
>>> G = nx.cycle_graph(2)
|
| 1357 |
+
>>> nx.similarity._simrank_similarity_python(G)
|
| 1358 |
+
{0: {0: 1, 1: 0.0}, 1: {0: 0.0, 1: 1}}
|
| 1359 |
+
>>> nx.similarity._simrank_similarity_python(G, source=0)
|
| 1360 |
+
{0: 1, 1: 0.0}
|
| 1361 |
+
>>> nx.similarity._simrank_similarity_python(G, source=0, target=0)
|
| 1362 |
+
1
|
| 1363 |
+
"""
|
| 1364 |
+
# build up our similarity adjacency dictionary output
|
| 1365 |
+
newsim = {u: {v: 1 if u == v else 0 for v in G} for u in G}
|
| 1366 |
+
|
| 1367 |
+
# These functions compute the update to the similarity value of the nodes
|
| 1368 |
+
# `u` and `v` with respect to the previous similarity values.
|
| 1369 |
+
def avg_sim(s):
|
| 1370 |
+
return sum(newsim[w][x] for (w, x) in s) / len(s) if s else 0.0
|
| 1371 |
+
|
| 1372 |
+
Gadj = G.pred if G.is_directed() else G.adj
|
| 1373 |
+
|
| 1374 |
+
def sim(u, v):
|
| 1375 |
+
return importance_factor * avg_sim(list(product(Gadj[u], Gadj[v])))
|
| 1376 |
+
|
| 1377 |
+
for its in range(max_iterations):
|
| 1378 |
+
oldsim = newsim
|
| 1379 |
+
newsim = {u: {v: sim(u, v) if u != v else 1 for v in G} for u in G}
|
| 1380 |
+
is_close = all(
|
| 1381 |
+
all(
|
| 1382 |
+
abs(newsim[u][v] - old) <= tolerance * (1 + abs(old))
|
| 1383 |
+
for v, old in nbrs.items()
|
| 1384 |
+
)
|
| 1385 |
+
for u, nbrs in oldsim.items()
|
| 1386 |
+
)
|
| 1387 |
+
if is_close:
|
| 1388 |
+
break
|
| 1389 |
+
|
| 1390 |
+
if its + 1 == max_iterations:
|
| 1391 |
+
raise nx.ExceededMaxIterations(
|
| 1392 |
+
f"simrank did not converge after {max_iterations} iterations."
|
| 1393 |
+
)
|
| 1394 |
+
|
| 1395 |
+
if source is not None and target is not None:
|
| 1396 |
+
return newsim[source][target]
|
| 1397 |
+
if source is not None:
|
| 1398 |
+
return newsim[source]
|
| 1399 |
+
return newsim
|
| 1400 |
+
|
| 1401 |
+
|
| 1402 |
+
def _simrank_similarity_numpy(
|
| 1403 |
+
G,
|
| 1404 |
+
source=None,
|
| 1405 |
+
target=None,
|
| 1406 |
+
importance_factor=0.9,
|
| 1407 |
+
max_iterations=1000,
|
| 1408 |
+
tolerance=1e-4,
|
| 1409 |
+
):
|
| 1410 |
+
"""Calculate SimRank of nodes in ``G`` using matrices with ``numpy``.
|
| 1411 |
+
|
| 1412 |
+
The SimRank algorithm for determining node similarity is defined in
|
| 1413 |
+
[1]_.
|
| 1414 |
+
|
| 1415 |
+
Parameters
|
| 1416 |
+
----------
|
| 1417 |
+
G : NetworkX graph
|
| 1418 |
+
A NetworkX graph
|
| 1419 |
+
|
| 1420 |
+
source : node
|
| 1421 |
+
If this is specified, the returned dictionary maps each node
|
| 1422 |
+
``v`` in the graph to the similarity between ``source`` and
|
| 1423 |
+
``v``.
|
| 1424 |
+
|
| 1425 |
+
target : node
|
| 1426 |
+
If both ``source`` and ``target`` are specified, the similarity
|
| 1427 |
+
value between ``source`` and ``target`` is returned. If
|
| 1428 |
+
``target`` is specified but ``source`` is not, this argument is
|
| 1429 |
+
ignored.
|
| 1430 |
+
|
| 1431 |
+
importance_factor : float
|
| 1432 |
+
The relative importance of indirect neighbors with respect to
|
| 1433 |
+
direct neighbors.
|
| 1434 |
+
|
| 1435 |
+
max_iterations : integer
|
| 1436 |
+
Maximum number of iterations.
|
| 1437 |
+
|
| 1438 |
+
tolerance : float
|
| 1439 |
+
Error tolerance used to check convergence. When an iteration of
|
| 1440 |
+
the algorithm finds that no similarity value changes more than
|
| 1441 |
+
this amount, the algorithm halts.
|
| 1442 |
+
|
| 1443 |
+
Returns
|
| 1444 |
+
-------
|
| 1445 |
+
similarity : numpy array or float
|
| 1446 |
+
If ``source`` and ``target`` are both ``None``, this returns a
|
| 1447 |
+
2D array containing SimRank scores of the nodes.
|
| 1448 |
+
|
| 1449 |
+
If ``source`` is not ``None`` but ``target`` is, this returns an
|
| 1450 |
+
1D array containing SimRank scores of ``source`` and that
|
| 1451 |
+
node.
|
| 1452 |
+
|
| 1453 |
+
If neither ``source`` nor ``target`` is ``None``, this returns
|
| 1454 |
+
the similarity value for the given pair of nodes.
|
| 1455 |
+
|
| 1456 |
+
Examples
|
| 1457 |
+
--------
|
| 1458 |
+
>>> G = nx.cycle_graph(2)
|
| 1459 |
+
>>> nx.similarity._simrank_similarity_numpy(G)
|
| 1460 |
+
array([[1., 0.],
|
| 1461 |
+
[0., 1.]])
|
| 1462 |
+
>>> nx.similarity._simrank_similarity_numpy(G, source=0)
|
| 1463 |
+
array([1., 0.])
|
| 1464 |
+
>>> nx.similarity._simrank_similarity_numpy(G, source=0, target=0)
|
| 1465 |
+
1.0
|
| 1466 |
+
|
| 1467 |
+
References
|
| 1468 |
+
----------
|
| 1469 |
+
.. [1] G. Jeh and J. Widom.
|
| 1470 |
+
"SimRank: a measure of structural-context similarity",
|
| 1471 |
+
In KDD'02: Proceedings of the Eighth ACM SIGKDD
|
| 1472 |
+
International Conference on Knowledge Discovery and Data Mining,
|
| 1473 |
+
pp. 538--543. ACM Press, 2002.
|
| 1474 |
+
"""
|
| 1475 |
+
# This algorithm follows roughly
|
| 1476 |
+
#
|
| 1477 |
+
# S = max{C * (A.T * S * A), I}
|
| 1478 |
+
#
|
| 1479 |
+
# where C is the importance factor, A is the column normalized
|
| 1480 |
+
# adjacency matrix, and I is the identity matrix.
|
| 1481 |
+
import numpy as np
|
| 1482 |
+
|
| 1483 |
+
adjacency_matrix = nx.to_numpy_array(G)
|
| 1484 |
+
|
| 1485 |
+
# column-normalize the ``adjacency_matrix``
|
| 1486 |
+
s = np.array(adjacency_matrix.sum(axis=0))
|
| 1487 |
+
s[s == 0] = 1
|
| 1488 |
+
adjacency_matrix /= s # adjacency_matrix.sum(axis=0)
|
| 1489 |
+
|
| 1490 |
+
newsim = np.eye(len(G), dtype=np.float64)
|
| 1491 |
+
for its in range(max_iterations):
|
| 1492 |
+
prevsim = newsim.copy()
|
| 1493 |
+
newsim = importance_factor * ((adjacency_matrix.T @ prevsim) @ adjacency_matrix)
|
| 1494 |
+
np.fill_diagonal(newsim, 1.0)
|
| 1495 |
+
|
| 1496 |
+
if np.allclose(prevsim, newsim, atol=tolerance):
|
| 1497 |
+
break
|
| 1498 |
+
|
| 1499 |
+
if its + 1 == max_iterations:
|
| 1500 |
+
raise nx.ExceededMaxIterations(
|
| 1501 |
+
f"simrank did not converge after {max_iterations} iterations."
|
| 1502 |
+
)
|
| 1503 |
+
|
| 1504 |
+
if source is not None and target is not None:
|
| 1505 |
+
return float(newsim[source, target])
|
| 1506 |
+
if source is not None:
|
| 1507 |
+
return newsim[source]
|
| 1508 |
+
return newsim
|
| 1509 |
+
|
| 1510 |
+
|
| 1511 |
+
@np_random_state("seed")
|
| 1512 |
+
def _prepare_panther_paths(
|
| 1513 |
+
G,
|
| 1514 |
+
source,
|
| 1515 |
+
path_length=5,
|
| 1516 |
+
c=0.5,
|
| 1517 |
+
delta=0.1,
|
| 1518 |
+
eps=None,
|
| 1519 |
+
weight="weight",
|
| 1520 |
+
remove_isolates=True,
|
| 1521 |
+
k=None,
|
| 1522 |
+
seed=None,
|
| 1523 |
+
):
|
| 1524 |
+
"""Common preparation code for Panther similarity algorithms.
|
| 1525 |
+
|
| 1526 |
+
Parameters
|
| 1527 |
+
----------
|
| 1528 |
+
G : NetworkX graph
|
| 1529 |
+
A NetworkX graph
|
| 1530 |
+
source : node
|
| 1531 |
+
Source node for similarity calculation
|
| 1532 |
+
path_length : int
|
| 1533 |
+
How long the randomly generated paths should be
|
| 1534 |
+
c : float
|
| 1535 |
+
A universal constant that controls the number of random paths to generate
|
| 1536 |
+
delta : float
|
| 1537 |
+
The probability parameter for similarity approximation
|
| 1538 |
+
eps : float or None
|
| 1539 |
+
The error bound for similarity approximation
|
| 1540 |
+
weight : string or None
|
| 1541 |
+
The name of an edge attribute that holds the numerical value used as a weight
|
| 1542 |
+
remove_isolates : bool
|
| 1543 |
+
Whether to remove isolated nodes from graph processing
|
| 1544 |
+
k : int or None
|
| 1545 |
+
The number of most similar nodes to return. If provided, validates that
|
| 1546 |
+
``k`` is not greater than the number of nodes in the graph.
|
| 1547 |
+
seed : integer, random_state, or None (default)
|
| 1548 |
+
Indicator of random number generation state.
|
| 1549 |
+
See :ref:`Randomness<randomness>`.
|
| 1550 |
+
|
| 1551 |
+
Returns
|
| 1552 |
+
-------
|
| 1553 |
+
PantherPaths
|
| 1554 |
+
A tuple containing the prepared data:
|
| 1555 |
+
- G: The graph (possibly with isolates removed)
|
| 1556 |
+
- inv_node_map: Dictionary mapping node names to indices
|
| 1557 |
+
- index_map: Populated index map of paths
|
| 1558 |
+
- inv_sample_size: Inverse of sample size (for fast calculation)
|
| 1559 |
+
- eps: Error bound for similarity approximation
|
| 1560 |
+
"""
|
| 1561 |
+
import numpy as np
|
| 1562 |
+
|
| 1563 |
+
if source not in G:
|
| 1564 |
+
raise nx.NodeNotFound(f"Source node {source} not in G")
|
| 1565 |
+
|
| 1566 |
+
isolates = set(nx.isolates(G))
|
| 1567 |
+
|
| 1568 |
+
if source in isolates:
|
| 1569 |
+
raise nx.NetworkXUnfeasible(
|
| 1570 |
+
f"Panther similarity is not defined for the isolated source node {source}."
|
| 1571 |
+
)
|
| 1572 |
+
|
| 1573 |
+
if remove_isolates:
|
| 1574 |
+
G = G.subgraph(node for node in G if node not in isolates).copy()
|
| 1575 |
+
|
| 1576 |
+
# According to [1], they empirically determined
|
| 1577 |
+
# a good value for ``eps`` to be sqrt( 1 / |E| )
|
| 1578 |
+
if eps is None:
|
| 1579 |
+
eps = np.sqrt(1.0 / G.number_of_edges())
|
| 1580 |
+
|
| 1581 |
+
num_nodes = G.number_of_nodes()
|
| 1582 |
+
|
| 1583 |
+
# Check if k is provided and validate it against the number of nodes
|
| 1584 |
+
if k is not None and not remove_isolates: # For panther_vector_similarity
|
| 1585 |
+
if num_nodes < k:
|
| 1586 |
+
raise nx.NetworkXUnfeasible(
|
| 1587 |
+
f"The number of requested nodes {k} is greater than the number of nodes {num_nodes}."
|
| 1588 |
+
)
|
| 1589 |
+
|
| 1590 |
+
inv_node_map = {name: index for index, name in enumerate(G)}
|
| 1591 |
+
|
| 1592 |
+
# Calculate the sample size ``R`` for how many paths
|
| 1593 |
+
# to randomly generate
|
| 1594 |
+
t_choose_2 = math.comb(path_length, 2)
|
| 1595 |
+
sample_size = int((c / eps**2) * (np.log2(t_choose_2) + 1 + np.log(1 / delta)))
|
| 1596 |
+
index_map = {}
|
| 1597 |
+
|
| 1598 |
+
# Check for isolated nodes before generating random paths
|
| 1599 |
+
# If there are still isolated nodes in the graph after filtering,
|
| 1600 |
+
# they will cause issues with path generation
|
| 1601 |
+
remaining_isolates = set(nx.isolates(G))
|
| 1602 |
+
if remaining_isolates:
|
| 1603 |
+
raise nx.NetworkXUnfeasible(
|
| 1604 |
+
f"Cannot generate random paths with isolated nodes present: {remaining_isolates}"
|
| 1605 |
+
)
|
| 1606 |
+
|
| 1607 |
+
# Generate the random paths and populate the index_map
|
| 1608 |
+
for _ in generate_random_paths(
|
| 1609 |
+
G,
|
| 1610 |
+
sample_size,
|
| 1611 |
+
path_length=path_length,
|
| 1612 |
+
index_map=index_map,
|
| 1613 |
+
weight=weight,
|
| 1614 |
+
seed=seed,
|
| 1615 |
+
):
|
| 1616 |
+
# NOTE: index_map is modified in-place by `generate_random_paths`
|
| 1617 |
+
pass
|
| 1618 |
+
|
| 1619 |
+
return (
|
| 1620 |
+
G, # The graph with isolated nodes removed
|
| 1621 |
+
inv_node_map,
|
| 1622 |
+
index_map,
|
| 1623 |
+
1 / sample_size,
|
| 1624 |
+
eps,
|
| 1625 |
+
)
|
| 1626 |
+
|
| 1627 |
+
|
| 1628 |
+
@np_random_state("seed")
|
| 1629 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 1630 |
+
def panther_similarity(
|
| 1631 |
+
G,
|
| 1632 |
+
source,
|
| 1633 |
+
k=5,
|
| 1634 |
+
path_length=5,
|
| 1635 |
+
c=0.5,
|
| 1636 |
+
delta=0.1,
|
| 1637 |
+
eps=None,
|
| 1638 |
+
weight="weight",
|
| 1639 |
+
seed=None,
|
| 1640 |
+
):
|
| 1641 |
+
r"""Returns the Panther similarity of nodes in the graph `G` to node ``v``.
|
| 1642 |
+
|
| 1643 |
+
Panther is a similarity metric that says "two objects are considered
|
| 1644 |
+
to be similar if they frequently appear on the same paths." [1]_.
|
| 1645 |
+
|
| 1646 |
+
Parameters
|
| 1647 |
+
----------
|
| 1648 |
+
G : NetworkX graph
|
| 1649 |
+
A NetworkX graph
|
| 1650 |
+
source : node
|
| 1651 |
+
Source node for which to find the top `k` similar other nodes
|
| 1652 |
+
k : int (default = 5)
|
| 1653 |
+
The number of most similar nodes to return.
|
| 1654 |
+
path_length : int (default = 5)
|
| 1655 |
+
How long the randomly generated paths should be (``T`` in [1]_)
|
| 1656 |
+
c : float (default = 0.5)
|
| 1657 |
+
A universal constant that controls the number of random paths to generate.
|
| 1658 |
+
Higher values increase the number of sample paths and potentially improve
|
| 1659 |
+
accuracy at the cost of more computation. Defaults to 0.5 as recommended
|
| 1660 |
+
in [1]_.
|
| 1661 |
+
delta : float (default = 0.1)
|
| 1662 |
+
The probability that the similarity $S$ is not an epsilon-approximation to (R, phi),
|
| 1663 |
+
where $R$ is the number of random paths and $\phi$ is the probability
|
| 1664 |
+
that an element sampled from a set $A \subseteq D$, where $D$ is the domain.
|
| 1665 |
+
eps : float or None (default = None)
|
| 1666 |
+
The error bound for similarity approximation. This controls the accuracy
|
| 1667 |
+
of the sampled paths in representing the true similarity. Smaller values
|
| 1668 |
+
yield more accurate results but require more sample paths. If `None`, a
|
| 1669 |
+
value of ``sqrt(1/|E|)`` is used, which the authors found empirically
|
| 1670 |
+
effective.
|
| 1671 |
+
weight : string or None, optional (default="weight")
|
| 1672 |
+
The name of an edge attribute that holds the numerical value
|
| 1673 |
+
used as a weight. If None then each edge has weight 1.
|
| 1674 |
+
seed : integer, random_state, or None (default)
|
| 1675 |
+
Indicator of random number generation state.
|
| 1676 |
+
See :ref:`Randomness<randomness>`.
|
| 1677 |
+
|
| 1678 |
+
Returns
|
| 1679 |
+
-------
|
| 1680 |
+
similarity : dictionary
|
| 1681 |
+
Dictionary of nodes to similarity scores (as floats). Note:
|
| 1682 |
+
the self-similarity (i.e., ``v``) will not be included in
|
| 1683 |
+
the returned dictionary. So, for ``k = 5``, a dictionary of
|
| 1684 |
+
top 4 nodes and their similarity scores will be returned.
|
| 1685 |
+
|
| 1686 |
+
Raises
|
| 1687 |
+
------
|
| 1688 |
+
NetworkXUnfeasible
|
| 1689 |
+
If `source` is an isolated node.
|
| 1690 |
+
|
| 1691 |
+
NodeNotFound
|
| 1692 |
+
If `source` is not in `G`.
|
| 1693 |
+
|
| 1694 |
+
Notes
|
| 1695 |
+
-----
|
| 1696 |
+
The isolated nodes in `G` are ignored.
|
| 1697 |
+
|
| 1698 |
+
Examples
|
| 1699 |
+
--------
|
| 1700 |
+
>>> G = nx.star_graph(10)
|
| 1701 |
+
>>> sim = nx.panther_similarity(G, 0)
|
| 1702 |
+
|
| 1703 |
+
References
|
| 1704 |
+
----------
|
| 1705 |
+
.. [1] Zhang, J., Tang, J., Ma, C., Tong, H., Jing, Y., & Li, J.
|
| 1706 |
+
Panther: Fast top-k similarity search on large networks.
|
| 1707 |
+
In Proceedings of the ACM SIGKDD International Conference
|
| 1708 |
+
on Knowledge Discovery and Data Mining (Vol. 2015-August, pp. 1445–1454).
|
| 1709 |
+
Association for Computing Machinery. https://doi.org/10.1145/2783258.2783267.
|
| 1710 |
+
"""
|
| 1711 |
+
import numpy as np
|
| 1712 |
+
|
| 1713 |
+
# Use helper method to prepare common data structures
|
| 1714 |
+
G, inv_node_map, index_map, inv_sample_size, eps = _prepare_panther_paths(
|
| 1715 |
+
G,
|
| 1716 |
+
source,
|
| 1717 |
+
path_length=path_length,
|
| 1718 |
+
c=c,
|
| 1719 |
+
delta=delta,
|
| 1720 |
+
eps=eps,
|
| 1721 |
+
weight=weight,
|
| 1722 |
+
k=k,
|
| 1723 |
+
seed=seed,
|
| 1724 |
+
)
|
| 1725 |
+
|
| 1726 |
+
num_nodes = G.number_of_nodes()
|
| 1727 |
+
node_list = list(G.nodes)
|
| 1728 |
+
|
| 1729 |
+
# Check number of nodes after any modifications by _prepare_panther_paths
|
| 1730 |
+
if num_nodes < k:
|
| 1731 |
+
raise nx.NetworkXUnfeasible(
|
| 1732 |
+
f"The number of requested nodes {k} is greater than the number of nodes {num_nodes}."
|
| 1733 |
+
)
|
| 1734 |
+
|
| 1735 |
+
S = np.zeros(num_nodes)
|
| 1736 |
+
source_paths = set(index_map[source])
|
| 1737 |
+
|
| 1738 |
+
# Calculate the path similarities
|
| 1739 |
+
# between ``source`` (v) and ``node`` (v_j)
|
| 1740 |
+
# using our inverted index mapping of
|
| 1741 |
+
# vertices to paths
|
| 1742 |
+
for node, paths in index_map.items():
|
| 1743 |
+
# Only consider paths where both
|
| 1744 |
+
# ``node`` and ``source`` are present
|
| 1745 |
+
common_paths = source_paths.intersection(paths)
|
| 1746 |
+
S[inv_node_map[node]] = len(common_paths) * inv_sample_size
|
| 1747 |
+
|
| 1748 |
+
# Retrieve top ``k+1`` similar to account for removing self-similarity
|
| 1749 |
+
# Note: the below performed anywhere from 4-10x faster
|
| 1750 |
+
# (depending on input sizes) vs the equivalent ``np.argsort(S)[::-1]``
|
| 1751 |
+
partition_k = min(k + 1, num_nodes)
|
| 1752 |
+
top_k_unsorted = np.argpartition(S, -partition_k)[-partition_k:]
|
| 1753 |
+
top_k_sorted = top_k_unsorted[np.argsort(S[top_k_unsorted])][::-1]
|
| 1754 |
+
|
| 1755 |
+
# Add back the similarity scores
|
| 1756 |
+
# Convert numpy scalars to native Python types for dispatch compatibility
|
| 1757 |
+
top_k_with_val = dict(
|
| 1758 |
+
zip((node_list[i] for i in top_k_sorted), S[top_k_sorted].tolist())
|
| 1759 |
+
)
|
| 1760 |
+
|
| 1761 |
+
# Remove the self-similarity
|
| 1762 |
+
top_k_with_val.pop(source, None)
|
| 1763 |
+
return top_k_with_val
|
| 1764 |
+
|
| 1765 |
+
|
| 1766 |
+
@np_random_state("seed")
|
| 1767 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 1768 |
+
def panther_vector_similarity(
|
| 1769 |
+
G,
|
| 1770 |
+
source,
|
| 1771 |
+
*,
|
| 1772 |
+
D=10,
|
| 1773 |
+
k=5,
|
| 1774 |
+
path_length=5,
|
| 1775 |
+
c=0.5,
|
| 1776 |
+
delta=0.1,
|
| 1777 |
+
eps=None,
|
| 1778 |
+
weight="weight",
|
| 1779 |
+
seed=None,
|
| 1780 |
+
):
|
| 1781 |
+
r"""Returns the Panther vector similarity (Panther++) of nodes in `G`.
|
| 1782 |
+
|
| 1783 |
+
Computes similarity between nodes based on the "Panther++" algorithm [1]_, which extends
|
| 1784 |
+
the basic Panther algorithm by using feature vectors to better capture structural
|
| 1785 |
+
similarity.
|
| 1786 |
+
|
| 1787 |
+
While basic Panther similarity measures how often two nodes appear on the same paths,
|
| 1788 |
+
Panther vector similarity (Panther++) creates a ``D``-dimensional feature vector for each
|
| 1789 |
+
node using its top similarity scores with other nodes, then computes similarity based
|
| 1790 |
+
on the Euclidean distance between these feature vectors. This approach better captures
|
| 1791 |
+
structural similarity and addresses the bias towards close neighbors present in
|
| 1792 |
+
the original Panther algorithm.
|
| 1793 |
+
|
| 1794 |
+
This approach is preferred when:
|
| 1795 |
+
|
| 1796 |
+
1. You need better structural similarity than basic path co-occurrence
|
| 1797 |
+
2. You want to overcome the close-neighbor bias of standard Panther
|
| 1798 |
+
3. You're working with large graphs where k-d tree indexing would be beneficial
|
| 1799 |
+
4. Graph edit distance-like similarity is more appropriate than path co-occurrence
|
| 1800 |
+
|
| 1801 |
+
Parameters
|
| 1802 |
+
----------
|
| 1803 |
+
G : NetworkX graph
|
| 1804 |
+
A NetworkX graph
|
| 1805 |
+
source : node
|
| 1806 |
+
Source node for which to find the top ``k`` similar other nodes
|
| 1807 |
+
D : int
|
| 1808 |
+
The number of similarity scores to use (in descending order)
|
| 1809 |
+
for each feature vector. Defaults to 10. Note that the original paper
|
| 1810 |
+
used D=50 [1]_, but KDTree is optimized for lower dimensions.
|
| 1811 |
+
k : int
|
| 1812 |
+
The number of most similar nodes to return
|
| 1813 |
+
path_length : int
|
| 1814 |
+
How long the randomly generated paths should be (``T`` in [1]_)
|
| 1815 |
+
c : float
|
| 1816 |
+
A universal constant that controls the number of random paths to generate.
|
| 1817 |
+
Higher values increase the number of sample paths and potentially improve
|
| 1818 |
+
accuracy at the cost of more computation. Defaults to 0.5 as recommended
|
| 1819 |
+
in [1]_.
|
| 1820 |
+
delta : float
|
| 1821 |
+
The probability that ``S`` is not an epsilon-approximation to (R, phi)
|
| 1822 |
+
eps : float
|
| 1823 |
+
The error bound for similarity approximation. This controls the accuracy
|
| 1824 |
+
of the sampled paths in representing the true similarity. Smaller values
|
| 1825 |
+
yield more accurate results but require more sample paths. If None, a
|
| 1826 |
+
value of ``sqrt(1/|E|)`` is used, which the authors found empirically
|
| 1827 |
+
effective.
|
| 1828 |
+
weight : string or None, optional (default="weight")
|
| 1829 |
+
The name of an edge attribute that holds the numerical value
|
| 1830 |
+
used as a weight. If `None` then each edge has weight 1.
|
| 1831 |
+
seed : integer, random_state, or None (default)
|
| 1832 |
+
Indicator of random number generation state.
|
| 1833 |
+
See :ref:`Randomness<randomness>`.
|
| 1834 |
+
|
| 1835 |
+
Returns
|
| 1836 |
+
-------
|
| 1837 |
+
similarity : dict
|
| 1838 |
+
Dict of nodes to similarity scores (as floats).
|
| 1839 |
+
Note: the self-similarity (i.e., `node`) is not included in the dict.
|
| 1840 |
+
|
| 1841 |
+
Examples
|
| 1842 |
+
--------
|
| 1843 |
+
>>> G = nx.star_graph(100)
|
| 1844 |
+
|
| 1845 |
+
The "hub" node is distinct from the "spoke" nodes
|
| 1846 |
+
|
| 1847 |
+
>>> from pprint import pprint
|
| 1848 |
+
>>> pprint(nx.panther_vector_similarity(G, source=0, seed=42))
|
| 1849 |
+
{35: 0.10402634656233918,
|
| 1850 |
+
61: 0.10434063328712018,
|
| 1851 |
+
65: 0.10401247833456054,
|
| 1852 |
+
85: 0.10506718868571752,
|
| 1853 |
+
88: 0.10402634656233918}
|
| 1854 |
+
|
| 1855 |
+
But "spoke" nodes are similar to one another
|
| 1856 |
+
|
| 1857 |
+
>>> result = nx.panther_vector_similarity(G, source=1, seed=42)
|
| 1858 |
+
>>> len(result)
|
| 1859 |
+
5
|
| 1860 |
+
>>> all(similarity == 1.0 for similarity in result.values())
|
| 1861 |
+
True
|
| 1862 |
+
|
| 1863 |
+
Notes
|
| 1864 |
+
-----
|
| 1865 |
+
Results may be nondeterministic when feature vectors have the same distances,
|
| 1866 |
+
as the KDTree's internal tie-breaking behavior can vary between runs.
|
| 1867 |
+
Using the same ``seed`` parameter ensures reproducible results.
|
| 1868 |
+
|
| 1869 |
+
References
|
| 1870 |
+
----------
|
| 1871 |
+
.. [1] Zhang, J., Tang, J., Ma, C., Tong, H., Jing, Y., & Li, J.
|
| 1872 |
+
Panther: Fast top-k similarity search on large networks.
|
| 1873 |
+
In Proceedings of the ACM SIGKDD International Conference
|
| 1874 |
+
on Knowledge Discovery and Data Mining (Vol. 2015-August, pp. 1445–1454).
|
| 1875 |
+
Association for Computing Machinery. https://doi.org/10.1145/2783258.2783267.
|
| 1876 |
+
"""
|
| 1877 |
+
import numpy as np
|
| 1878 |
+
import scipy as sp
|
| 1879 |
+
|
| 1880 |
+
# Use helper method to prepare common data structures but keep isolates in the graph
|
| 1881 |
+
G, inv_node_map, index_map, inv_sample_size, eps = _prepare_panther_paths(
|
| 1882 |
+
G,
|
| 1883 |
+
source,
|
| 1884 |
+
path_length=path_length,
|
| 1885 |
+
c=c,
|
| 1886 |
+
delta=delta,
|
| 1887 |
+
eps=eps,
|
| 1888 |
+
weight=weight,
|
| 1889 |
+
remove_isolates=False,
|
| 1890 |
+
k=k,
|
| 1891 |
+
seed=seed,
|
| 1892 |
+
)
|
| 1893 |
+
num_nodes = G.number_of_nodes()
|
| 1894 |
+
node_list = list(G.nodes)
|
| 1895 |
+
|
| 1896 |
+
# Ensure D doesn't exceed the number of nodes
|
| 1897 |
+
if num_nodes < D:
|
| 1898 |
+
raise nx.NetworkXUnfeasible(
|
| 1899 |
+
f"The number of requested similarity scores {D} is greater than the number of nodes {num_nodes}."
|
| 1900 |
+
)
|
| 1901 |
+
|
| 1902 |
+
similarities = np.zeros((num_nodes, num_nodes))
|
| 1903 |
+
theta = np.zeros((num_nodes, D))
|
| 1904 |
+
index_map_sets = {node: set(paths) for node, paths in index_map.items()}
|
| 1905 |
+
|
| 1906 |
+
# Calculate the path similarities for each node
|
| 1907 |
+
for vi_idx, vi in enumerate(G.nodes):
|
| 1908 |
+
vi_paths = index_map_sets[vi]
|
| 1909 |
+
|
| 1910 |
+
for node, node_paths in index_map_sets.items():
|
| 1911 |
+
# Calculate similarity score
|
| 1912 |
+
common_path_count = len(vi_paths.intersection(node_paths))
|
| 1913 |
+
similarities[vi_idx, inv_node_map[node]] = (
|
| 1914 |
+
common_path_count * inv_sample_size
|
| 1915 |
+
)
|
| 1916 |
+
|
| 1917 |
+
# Build up the feature vector using the largest D similarity scores
|
| 1918 |
+
theta[vi_idx] = np.sort(np.partition(similarities[vi_idx], -D)[-D:])[::-1]
|
| 1919 |
+
|
| 1920 |
+
# Insert the feature vectors into a k-d tree
|
| 1921 |
+
# for fast retrieval
|
| 1922 |
+
kdtree = sp.spatial.KDTree(theta)
|
| 1923 |
+
|
| 1924 |
+
# Retrieve top ``k+1`` similar vertices (i.e., vectors)
|
| 1925 |
+
# (based on their Euclidean distance)
|
| 1926 |
+
# Note that it's k+1 because the source node will be included and later removed
|
| 1927 |
+
query_k = min(k + 1, num_nodes)
|
| 1928 |
+
neighbor_distances, nearest_neighbors = kdtree.query(
|
| 1929 |
+
theta[inv_node_map[source]], k=query_k
|
| 1930 |
+
)
|
| 1931 |
+
|
| 1932 |
+
# Ensure results are always arrays (KDTree returns scalars when k=1)
|
| 1933 |
+
neighbor_distances = np.atleast_1d(neighbor_distances)
|
| 1934 |
+
nearest_neighbors = np.atleast_1d(nearest_neighbors)
|
| 1935 |
+
|
| 1936 |
+
# The paper defines the similarity S(v_i, v_j) as
|
| 1937 |
+
# 1 / || Theta(v_i) - Theta(v_j) ||
|
| 1938 |
+
# Calculate reciprocals and normalize to [0, 1] range
|
| 1939 |
+
|
| 1940 |
+
# Handle the case where distances are very small or zero (common in small graphs)
|
| 1941 |
+
# Use the passed in eps parameter instead of defining a new epsilon
|
| 1942 |
+
neighbor_distances = np.maximum(neighbor_distances, eps)
|
| 1943 |
+
similarities = 1 / neighbor_distances
|
| 1944 |
+
|
| 1945 |
+
# Always normalize to ensure values are between 0 and 1
|
| 1946 |
+
if len(similarities) > 0 and (max_sim := np.max(similarities)) > 0:
|
| 1947 |
+
similarities /= max_sim
|
| 1948 |
+
|
| 1949 |
+
# Add back the similarity scores (i.e., distances)
|
| 1950 |
+
# Convert numpy scalars to native Python types for dispatch compatibility
|
| 1951 |
+
top_k_with_val = dict(
|
| 1952 |
+
zip((node_list[n] for n in nearest_neighbors), similarities.tolist())
|
| 1953 |
+
)
|
| 1954 |
+
|
| 1955 |
+
# Remove the self-similarity
|
| 1956 |
+
top_k_with_val.pop(source, None)
|
| 1957 |
+
|
| 1958 |
+
# Ensure we return exactly k results (sorted by similarity)
|
| 1959 |
+
if len(top_k_with_val) > k:
|
| 1960 |
+
sorted_items = sorted(top_k_with_val.items(), key=lambda x: x[1], reverse=True)
|
| 1961 |
+
top_k_with_val = dict(sorted_items[:k])
|
| 1962 |
+
|
| 1963 |
+
return top_k_with_val
|
| 1964 |
+
|
| 1965 |
+
|
| 1966 |
+
@np_random_state("seed")
|
| 1967 |
+
@nx._dispatchable(edge_attrs="weight")
|
| 1968 |
+
def generate_random_paths(
|
| 1969 |
+
G,
|
| 1970 |
+
sample_size,
|
| 1971 |
+
path_length=5,
|
| 1972 |
+
index_map=None,
|
| 1973 |
+
weight="weight",
|
| 1974 |
+
seed=None,
|
| 1975 |
+
*,
|
| 1976 |
+
source=None,
|
| 1977 |
+
):
|
| 1978 |
+
"""Randomly generate `sample_size` paths of length `path_length`.
|
| 1979 |
+
|
| 1980 |
+
Parameters
|
| 1981 |
+
----------
|
| 1982 |
+
G : NetworkX graph
|
| 1983 |
+
A NetworkX graph
|
| 1984 |
+
sample_size : integer
|
| 1985 |
+
The number of paths to generate. This is ``R`` in [1]_.
|
| 1986 |
+
path_length : integer (default = 5)
|
| 1987 |
+
The maximum size of the path to randomly generate.
|
| 1988 |
+
This is ``T`` in [1]_. According to the paper, ``T >= 5`` is
|
| 1989 |
+
recommended.
|
| 1990 |
+
index_map : dictionary, optional
|
| 1991 |
+
If provided, this will be populated with the inverted
|
| 1992 |
+
index of nodes mapped to the set of generated random path
|
| 1993 |
+
indices within ``paths``.
|
| 1994 |
+
weight : string or None, optional (default="weight")
|
| 1995 |
+
The name of an edge attribute that holds the numerical value
|
| 1996 |
+
used as a weight. If None then each edge has weight 1.
|
| 1997 |
+
seed : integer, random_state, or None (default)
|
| 1998 |
+
Indicator of random number generation state.
|
| 1999 |
+
See :ref:`Randomness<randomness>`.
|
| 2000 |
+
source : node, optional
|
| 2001 |
+
Node to use as the starting point for all generated paths.
|
| 2002 |
+
If None then starting nodes are selected at random with uniform probability.
|
| 2003 |
+
|
| 2004 |
+
Returns
|
| 2005 |
+
-------
|
| 2006 |
+
paths : generator of lists
|
| 2007 |
+
Generator of `sample_size` paths each with length `path_length`.
|
| 2008 |
+
|
| 2009 |
+
Examples
|
| 2010 |
+
--------
|
| 2011 |
+
The generator yields `sample_size` number of paths of length `path_length`
|
| 2012 |
+
drawn from `G`:
|
| 2013 |
+
|
| 2014 |
+
>>> G = nx.complete_graph(5)
|
| 2015 |
+
>>> next(nx.generate_random_paths(G, sample_size=1, path_length=3, seed=42))
|
| 2016 |
+
[3, 4, 2, 3]
|
| 2017 |
+
>>> list(nx.generate_random_paths(G, sample_size=3, path_length=4, seed=42))
|
| 2018 |
+
[[3, 4, 2, 3, 0], [2, 0, 2, 1, 0], [2, 0, 4, 3, 0]]
|
| 2019 |
+
|
| 2020 |
+
By passing a dictionary into `index_map`, it will build an
|
| 2021 |
+
inverted index mapping of nodes to the paths in which that node is present:
|
| 2022 |
+
|
| 2023 |
+
>>> G = nx.wheel_graph(10)
|
| 2024 |
+
>>> index_map = {}
|
| 2025 |
+
>>> random_paths = list(
|
| 2026 |
+
... nx.generate_random_paths(G, sample_size=3, index_map=index_map, seed=2771)
|
| 2027 |
+
... )
|
| 2028 |
+
>>> random_paths
|
| 2029 |
+
[[3, 2, 1, 9, 8, 7], [4, 0, 5, 6, 7, 8], [3, 0, 5, 0, 9, 8]]
|
| 2030 |
+
>>> paths_containing_node_0 = [
|
| 2031 |
+
... random_paths[path_idx] for path_idx in index_map.get(0, [])
|
| 2032 |
+
... ]
|
| 2033 |
+
>>> paths_containing_node_0
|
| 2034 |
+
[[4, 0, 5, 6, 7, 8], [3, 0, 5, 0, 9, 8]]
|
| 2035 |
+
|
| 2036 |
+
References
|
| 2037 |
+
----------
|
| 2038 |
+
.. [1] Zhang, J., Tang, J., Ma, C., Tong, H., Jing, Y., & Li, J.
|
| 2039 |
+
Panther: Fast top-k similarity search on large networks.
|
| 2040 |
+
In Proceedings of the ACM SIGKDD International Conference
|
| 2041 |
+
on Knowledge Discovery and Data Mining (Vol. 2015-August, pp. 1445–1454).
|
| 2042 |
+
Association for Computing Machinery. https://doi.org/10.1145/2783258.2783267.
|
| 2043 |
+
"""
|
| 2044 |
+
import numpy as np
|
| 2045 |
+
|
| 2046 |
+
randint_fn = (
|
| 2047 |
+
seed.integers if isinstance(seed, np.random.Generator) else seed.randint
|
| 2048 |
+
)
|
| 2049 |
+
|
| 2050 |
+
# Calculate transition probabilities between
|
| 2051 |
+
# every pair of vertices according to Eq. (3)
|
| 2052 |
+
adj_mat = nx.to_numpy_array(G, weight=weight)
|
| 2053 |
+
|
| 2054 |
+
# Handle isolated nodes by checking for zero row sums
|
| 2055 |
+
row_sums = adj_mat.sum(axis=1).reshape(-1, 1)
|
| 2056 |
+
inv_row_sums = np.reciprocal(row_sums)
|
| 2057 |
+
transition_probabilities = adj_mat * inv_row_sums
|
| 2058 |
+
|
| 2059 |
+
node_map = list(G)
|
| 2060 |
+
num_nodes = G.number_of_nodes()
|
| 2061 |
+
|
| 2062 |
+
for path_index in range(sample_size):
|
| 2063 |
+
if source is None:
|
| 2064 |
+
# Sample current vertex v = v_i uniformly at random
|
| 2065 |
+
node_index = randint_fn(num_nodes)
|
| 2066 |
+
node = node_map[node_index]
|
| 2067 |
+
else:
|
| 2068 |
+
if source not in node_map:
|
| 2069 |
+
raise nx.NodeNotFound(f"Initial node {source} not in G")
|
| 2070 |
+
|
| 2071 |
+
node = source
|
| 2072 |
+
node_index = node_map.index(node)
|
| 2073 |
+
|
| 2074 |
+
# Add v into p_r and add p_r into the path set
|
| 2075 |
+
# of v, i.e., P_v
|
| 2076 |
+
path = [node]
|
| 2077 |
+
|
| 2078 |
+
# Build the inverted index (P_v) of vertices to paths
|
| 2079 |
+
if index_map is not None:
|
| 2080 |
+
if node in index_map:
|
| 2081 |
+
index_map[node].add(path_index)
|
| 2082 |
+
else:
|
| 2083 |
+
index_map[node] = {path_index}
|
| 2084 |
+
|
| 2085 |
+
starting_index = node_index
|
| 2086 |
+
for _ in range(path_length):
|
| 2087 |
+
# Randomly sample a neighbor (v_j) according
|
| 2088 |
+
# to transition probabilities from ``node`` (v) to its neighbors
|
| 2089 |
+
nbr_index = seed.choice(
|
| 2090 |
+
num_nodes, p=transition_probabilities[starting_index]
|
| 2091 |
+
)
|
| 2092 |
+
|
| 2093 |
+
# Set current vertex (v = v_j)
|
| 2094 |
+
starting_index = nbr_index
|
| 2095 |
+
|
| 2096 |
+
# Add v into p_r
|
| 2097 |
+
nbr_node = node_map[nbr_index]
|
| 2098 |
+
path.append(nbr_node)
|
| 2099 |
+
|
| 2100 |
+
# Add p_r into P_v
|
| 2101 |
+
if index_map is not None:
|
| 2102 |
+
if nbr_node in index_map:
|
| 2103 |
+
index_map[nbr_node].add(path_index)
|
| 2104 |
+
else:
|
| 2105 |
+
index_map[nbr_node] = {path_index}
|
| 2106 |
+
|
| 2107 |
+
yield path
|