Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/networkx/algorithms/__init__.pyAdded+134
- lib/python3.12/site-packages/networkx/algorithms/assortativity/__init__.pyAdded+5
- lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/connectivity.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/correlation.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/mixing.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/neighbor_degree.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/pairs.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/connectivity.pyAdded+122
- lib/python3.12/site-packages/networkx/algorithms/assortativity/correlation.pyAdded+302
- lib/python3.12/site-packages/networkx/algorithms/assortativity/mixing.pyAdded+255
- lib/python3.12/site-packages/networkx/algorithms/assortativity/neighbor_degree.pyAdded+160
- lib/python3.12/site-packages/networkx/algorithms/assortativity/pairs.pyAdded+127
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__init__.pyAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/base_test.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_connectivity.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_correlation.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_mixing.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_neighbor_degree.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_pairs.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/base_test.pyAdded+81
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/test_connectivity.pyAdded+143
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/test_correlation.pyAdded+122
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/test_mixing.pyAdded+174
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/test_neighbor_degree.pyAdded+107
- lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/test_pairs.pyAdded+87
- lib/python3.12/site-packages/networkx/algorithms/asteroidal.pyAdded+164
- lib/python3.12/site-packages/networkx/algorithms/boundary.pyAdded+168
- lib/python3.12/site-packages/networkx/algorithms/bridges.pyAdded+205
- lib/python3.12/site-packages/networkx/algorithms/broadcasting.pyAdded+164
- lib/python3.12/site-packages/networkx/algorithms/chains.pyAdded+172
- lib/python3.12/site-packages/networkx/algorithms/chordal.pyAdded+443
- lib/python3.12/site-packages/networkx/algorithms/clique.pyAdded+818
- lib/python3.12/site-packages/networkx/algorithms/cluster.pyAdded+732
- lib/python3.12/site-packages/networkx/algorithms/communicability_alg.pyAdded+163
- lib/python3.12/site-packages/networkx/algorithms/connectivity/__init__.pyAdded+11
- lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/connectivity.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/cuts.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/disjoint_paths.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/edge_augmentation.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/edge_kcomponents.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/kcomponents.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/kcutsets.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/stoerwagner.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/utils.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/connectivity/connectivity.pyAdded+811
- lib/python3.12/site-packages/networkx/algorithms/connectivity/cuts.pyAdded+616
- lib/python3.12/site-packages/networkx/algorithms/connectivity/disjoint_paths.pyAdded+408
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134from networkx.algorithms.assortativity import *from networkx.algorithms.asteroidal import *from networkx.algorithms.boundary import *from networkx.algorithms.broadcasting import *from networkx.algorithms.bridges import *from networkx.algorithms.chains import *from networkx.algorithms.centrality import *from networkx.algorithms.chordal import *from networkx.algorithms.cluster import *from networkx.algorithms.clique import *from networkx.algorithms.communicability_alg import *from networkx.algorithms.components import *from networkx.algorithms.coloring import *from networkx.algorithms.core import *from networkx.algorithms.covering import *from networkx.algorithms.cycles import *from networkx.algorithms.cuts import *from networkx.algorithms.d_separation import *from networkx.algorithms.dag import *from networkx.algorithms.distance_measures import *from networkx.algorithms.distance_regular import *from networkx.algorithms.dominance import *from networkx.algorithms.dominating import *from networkx.algorithms.efficiency_measures import *from networkx.algorithms.euler import *from networkx.algorithms.graphical import *from networkx.algorithms.hierarchy import *from networkx.algorithms.hybrid import *from networkx.algorithms.link_analysis import *from networkx.algorithms.link_prediction import *from networkx.algorithms.lowest_common_ancestors import *from networkx.algorithms.isolate import *from networkx.algorithms.matching import *from networkx.algorithms.minors import *from networkx.algorithms.mis import *from networkx.algorithms.moral import *from networkx.algorithms.non_randomness import *from networkx.algorithms.operators import *from networkx.algorithms.planarity import *from networkx.algorithms.planar_drawing import *from networkx.algorithms.polynomials import *from networkx.algorithms.perfect_graph import *from networkx.algorithms.reciprocity import *from networkx.algorithms.regular import *from networkx.algorithms.richclub import *from networkx.algorithms.shortest_paths import *from networkx.algorithms.similarity import *from networkx.algorithms.graph_hashing import *from networkx.algorithms.simple_paths import *from networkx.algorithms.smallworld import *from networkx.algorithms.smetric import *from networkx.algorithms.structuralholes import *from networkx.algorithms.sparsifiers import *from networkx.algorithms.summarization import *from networkx.algorithms.swap import *from networkx.algorithms.time_dependent import *from networkx.algorithms.traversal import *from networkx.algorithms.triads import *from networkx.algorithms.vitality import *from networkx.algorithms.voronoi import *from networkx.algorithms.walks import *from networkx.algorithms.wiener import *
# Make certain subpackages available to the user as direct imports from# the `networkx` namespace.from networkx.algorithms import approximationfrom networkx.algorithms import assortativityfrom networkx.algorithms import bipartitefrom networkx.algorithms import node_classificationfrom networkx.algorithms import centralityfrom networkx.algorithms import chordalfrom networkx.algorithms import clusterfrom networkx.algorithms import cliquefrom networkx.algorithms import componentsfrom networkx.algorithms import connectivityfrom networkx.algorithms import communityfrom networkx.algorithms import coloringfrom networkx.algorithms import flowfrom networkx.algorithms import isomorphismfrom networkx.algorithms import link_analysisfrom networkx.algorithms import lowest_common_ancestorsfrom networkx.algorithms import operatorsfrom networkx.algorithms import shortest_pathsfrom networkx.algorithms import tournamentfrom networkx.algorithms import traversalfrom networkx.algorithms import tree
# Make certain functions from some of the previous subpackages available# to the user as direct imports from the `networkx` namespace.from networkx.algorithms.bipartite import complete_bipartite_graphfrom networkx.algorithms.bipartite import is_bipartitefrom networkx.algorithms.bipartite import projected_graphfrom networkx.algorithms.connectivity import all_pairs_node_connectivityfrom networkx.algorithms.connectivity import all_node_cutsfrom networkx.algorithms.connectivity import average_node_connectivityfrom networkx.algorithms.connectivity import edge_connectivityfrom networkx.algorithms.connectivity import edge_disjoint_pathsfrom networkx.algorithms.connectivity import k_componentsfrom networkx.algorithms.connectivity import k_edge_componentsfrom networkx.algorithms.connectivity import k_edge_subgraphsfrom networkx.algorithms.connectivity import k_edge_augmentationfrom networkx.algorithms.connectivity import is_k_edge_connectedfrom networkx.algorithms.connectivity import minimum_edge_cutfrom networkx.algorithms.connectivity import minimum_node_cutfrom networkx.algorithms.connectivity import node_connectivityfrom networkx.algorithms.connectivity import node_disjoint_pathsfrom networkx.algorithms.connectivity import stoer_wagnerfrom networkx.algorithms.flow import capacity_scalingfrom networkx.algorithms.flow import cost_of_flowfrom networkx.algorithms.flow import gomory_hu_treefrom networkx.algorithms.flow import max_flow_min_costfrom networkx.algorithms.flow import maximum_flowfrom networkx.algorithms.flow import maximum_flow_valuefrom networkx.algorithms.flow import min_cost_flowfrom networkx.algorithms.flow import min_cost_flow_costfrom networkx.algorithms.flow import minimum_cutfrom networkx.algorithms.flow import minimum_cut_valuefrom networkx.algorithms.flow import network_simplexfrom networkx.algorithms.isomorphism import could_be_isomorphicfrom networkx.algorithms.isomorphism import fast_could_be_isomorphicfrom networkx.algorithms.isomorphism import faster_could_be_isomorphicfrom networkx.algorithms.isomorphism import is_isomorphicfrom networkx.algorithms.isomorphism.vf2pp import *from networkx.algorithms.tree.branchings import maximum_branchingfrom networkx.algorithms.tree.branchings import maximum_spanning_arborescencefrom networkx.algorithms.tree.branchings import minimum_branchingfrom networkx.algorithms.tree.branchings import minimum_spanning_arborescencefrom networkx.algorithms.tree.branchings import ArborescenceIteratorfrom networkx.algorithms.tree.coding import *from networkx.algorithms.tree.decomposition import *from networkx.algorithms.tree.mst import *from networkx.algorithms.tree.operations import *from networkx.algorithms.tree.recognition import *from networkx.algorithms.tournament import is_tournament12345from networkx.algorithms.assortativity.connectivity import *from networkx.algorithms.assortativity.correlation import *from networkx.algorithms.assortativity.mixing import *from networkx.algorithms.assortativity.neighbor_degree import *from networkx.algorithms.assortativity.pairs import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122from collections import defaultdict
import networkx as nx
__all__ = ["average_degree_connectivity"]
@nx._dispatchable(edge_attrs="weight")def average_degree_connectivity( G, source="in+out", target="in+out", nodes=None, weight=None): r"""Compute the average degree connectivity of graph.
The average degree connectivity is the average nearest neighbor degree of nodes with degree k. For weighted graphs, an analogous measure can be computed using the weighted average neighbors degree defined in [1]_, for a node `i`, as
.. math::
k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
where `s_i` is the weighted degree of node `i`, `w_{ij}` is the weight of the edge that links `i` and `j`, and `N(i)` are the neighbors of node `i`.
Parameters ---------- G : NetworkX graph
source : "in"|"out"|"in+out" (default:"in+out") Directed graphs only. Use "in"- or "out"-degree for source node.
target : "in"|"out"|"in+out" (default:"in+out" Directed graphs only. Use "in"- or "out"-degree for target node.
nodes : list or iterable (optional) Compute neighbor connectivity for these nodes. The default is all nodes.
weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1.
Returns ------- d : dict A dictionary keyed by degree k with the value of average connectivity.
Raises ------ NetworkXError If either `source` or `target` are not one of 'in', 'out', or 'in+out'. If either `source` or `target` is passed for an undirected graph.
Examples -------- >>> G = nx.path_graph(4) >>> G.edges[1, 2]["weight"] = 3 >>> nx.average_degree_connectivity(G) {1: 2.0, 2: 1.5} >>> nx.average_degree_connectivity(G, weight="weight") {1: 2.0, 2: 1.75}
See Also -------- average_neighbor_degree
References ---------- .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, "The architecture of complex weighted networks". PNAS 101 (11): 3747–3752 (2004). """ # First, determine the type of neighbors and the type of degree to use. if G.is_directed(): if source not in ("in", "out", "in+out"): raise nx.NetworkXError('source must be one of "in", "out", or "in+out"') if target not in ("in", "out", "in+out"): raise nx.NetworkXError('target must be one of "in", "out", or "in+out"') direction = {"out": G.out_degree, "in": G.in_degree, "in+out": G.degree} neighbor_funcs = { "out": G.successors, "in": G.predecessors, "in+out": G.neighbors, } source_degree = direction[source] target_degree = direction[target] neighbors = neighbor_funcs[source] # `reverse` indicates whether to look at the in-edge when # computing the weight of an edge. reverse = source == "in" else: if source != "in+out" or target != "in+out": raise nx.NetworkXError( f"source and target arguments are only supported for directed graphs" ) source_degree = G.degree target_degree = G.degree neighbors = G.neighbors reverse = False dsum = defaultdict(int) dnorm = defaultdict(int) # Check if `source_nodes` is actually a single node in the graph. source_nodes = source_degree(nodes) if nodes in G: source_nodes = [(nodes, source_degree(nodes))] for n, k in source_nodes: nbrdeg = target_degree(neighbors(n)) if weight is None: s = sum(d for n, d in nbrdeg) else: # weight nbr degree by weight of (n,nbr) edge if reverse: s = sum(G[nbr][n].get(weight, 1) * d for nbr, d in nbrdeg) else: s = sum(G[n][nbr].get(weight, 1) * d for nbr, d in nbrdeg) dnorm[k] += source_degree(n, weight=weight) dsum[k] += s
# normalize return {k: avg if dnorm[k] == 0 else avg / dnorm[k] for k, avg in dsum.items()}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302"""Node assortativity coefficients and correlation measures."""
import networkx as nxfrom networkx.algorithms.assortativity.mixing import ( attribute_mixing_matrix, degree_mixing_matrix,)from networkx.algorithms.assortativity.pairs import node_degree_xy
__all__ = [ "degree_pearson_correlation_coefficient", "degree_assortativity_coefficient", "attribute_assortativity_coefficient", "numeric_assortativity_coefficient",]
@nx._dispatchable(edge_attrs="weight")def degree_assortativity_coefficient(G, x="out", y="in", weight=None, nodes=None): """Compute degree assortativity of graph.
Assortativity measures the similarity of connections in the graph with respect to the node degree.
Parameters ---------- G : NetworkX graph
x: string ('in','out') The degree type for source node (directed graphs only).
y: string ('in','out') The degree type for target node (directed graphs only).
weight: string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
nodes: list or iterable (optional) Compute degree assortativity only for nodes in container. The default is all nodes.
Returns ------- r : float Assortativity of graph by degree.
Examples -------- >>> G = nx.path_graph(4) >>> r = nx.degree_assortativity_coefficient(G) >>> print(f"{r:3.1f}") -0.5
See Also -------- attribute_assortativity_coefficient numeric_assortativity_coefficient degree_mixing_dict degree_mixing_matrix
Notes ----- This computes Eq. (21) in Ref. [1]_ , where e is the joint probability distribution (mixing matrix) of the degrees. If G is directed than the matrix e is the joint probability of the user-specified degree type for the source and target.
References ---------- .. [1] M. E. J. Newman, Mixing patterns in networks, Physical Review E, 67 026126, 2003 .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M. Edge direction and the structure of networks, PNAS 107, 10815-20 (2010). """ if nodes is None: nodes = G.nodes
degrees = None
if G.is_directed(): indeg = ( {d for _, d in G.in_degree(nodes, weight=weight)} if "in" in (x, y) else set() ) outdeg = ( {d for _, d in G.out_degree(nodes, weight=weight)} if "out" in (x, y) else set() ) degrees = set.union(indeg, outdeg) else: degrees = {d for _, d in G.degree(nodes, weight=weight)}
mapping = {d: i for i, d in enumerate(degrees)} M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)
return _numeric_ac(M, mapping=mapping)
@nx._dispatchable(edge_attrs="weight")def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, nodes=None): """Compute degree assortativity of graph.
Assortativity measures the similarity of connections in the graph with respect to the node degree.
This is the same as degree_assortativity_coefficient but uses the potentially faster scipy.stats.pearsonr function.
Parameters ---------- G : NetworkX graph
x: string ('in','out') The degree type for source node (directed graphs only).
y: string ('in','out') The degree type for target node (directed graphs only).
weight: string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
nodes: list or iterable (optional) Compute pearson correlation of degrees only for specified nodes. The default is all nodes.
Returns ------- r : float Assortativity of graph by degree.
Examples -------- >>> G = nx.path_graph(4) >>> r = nx.degree_pearson_correlation_coefficient(G) >>> print(f"{r:3.1f}") -0.5
Notes ----- This calls scipy.stats.pearsonr.
References ---------- .. [1] M. E. J. Newman, Mixing patterns in networks Physical Review E, 67 026126, 2003 .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M. Edge direction and the structure of networks, PNAS 107, 10815-20 (2010). """ import scipy as sp
xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight) x, y = zip(*xy) return float(sp.stats.pearsonr(x, y)[0])
@nx._dispatchable(node_attrs="attribute")def attribute_assortativity_coefficient(G, attribute, nodes=None): """Compute assortativity for node attributes.
Assortativity measures the similarity of connections in the graph with respect to the given attribute.
Parameters ---------- G : NetworkX graph
attribute : string Node attribute key
nodes: list or iterable (optional) Compute attribute assortativity for nodes in container. The default is all nodes.
Returns ------- r: float Assortativity of graph for given attribute
Examples -------- >>> G = nx.Graph() >>> G.add_nodes_from([0, 1], color="red") >>> G.add_nodes_from([2, 3], color="blue") >>> G.add_edges_from([(0, 1), (2, 3)]) >>> print(nx.attribute_assortativity_coefficient(G, "color")) 1.0
Notes ----- This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)), where M is the joint probability distribution (mixing matrix) of the specified attribute.
References ---------- .. [1] M. E. J. Newman, Mixing patterns in networks, Physical Review E, 67 026126, 2003 """ M = attribute_mixing_matrix(G, attribute, nodes) return attribute_ac(M)
@nx._dispatchable(node_attrs="attribute")def numeric_assortativity_coefficient(G, attribute, nodes=None): """Compute assortativity for numerical node attributes.
Assortativity measures the similarity of connections in the graph with respect to the given numeric attribute.
Parameters ---------- G : NetworkX graph
attribute : string Node attribute key.
nodes: list or iterable (optional) Compute numeric assortativity only for attributes of nodes in container. The default is all nodes.
Returns ------- r: float Assortativity of graph for given attribute
Examples -------- >>> G = nx.Graph() >>> G.add_nodes_from([0, 1], size=2) >>> G.add_nodes_from([2, 3], size=3) >>> G.add_edges_from([(0, 1), (2, 3)]) >>> print(nx.numeric_assortativity_coefficient(G, "size")) 1.0
Notes ----- This computes Eq. (21) in Ref. [1]_ , which is the Pearson correlation coefficient of the specified (scalar valued) attribute across edges.
References ---------- .. [1] M. E. J. Newman, Mixing patterns in networks Physical Review E, 67 026126, 2003 """ if nodes is None: nodes = G.nodes vals = {G.nodes[n][attribute] for n in nodes} mapping = {d: i for i, d in enumerate(vals)} M = attribute_mixing_matrix(G, attribute, nodes, mapping) return _numeric_ac(M, mapping)
def attribute_ac(M): """Compute assortativity for attribute matrix M.
Parameters ---------- M : numpy.ndarray 2D ndarray representing the attribute mixing matrix.
Notes ----- This computes Eq. (2) in Ref. [1]_ , (trace(e)-sum(e^2))/(1-sum(e^2)), where e is the joint probability distribution (mixing matrix) of the specified attribute.
References ---------- .. [1] M. E. J. Newman, Mixing patterns in networks, Physical Review E, 67 026126, 2003 """ if M.sum() != 1.0: M = M / M.sum() s = (M @ M).sum() t = M.trace() r = (t - s) / (1 - s) return float(r)
def _numeric_ac(M, mapping): # M is a 2D numpy array # numeric assortativity coefficient, pearsonr import numpy as np
if M.sum() != 1.0: M = M / M.sum() x = np.array(list(mapping.keys())) y = x # x and y have the same support idx = list(mapping.values()) a = M.sum(axis=0) b = M.sum(axis=1) vara = (a[idx] * x**2).sum() - ((a[idx] * x).sum()) ** 2 varb = (b[idx] * y**2).sum() - ((b[idx] * y).sum()) ** 2 xy = np.outer(x, y) ab = np.outer(a[idx], b[idx]) return float((xy * (M - ab)).sum() / np.sqrt(vara * varb))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255"""Mixing matrices for node attributes and degree."""
import networkx as nxfrom networkx.algorithms.assortativity.pairs import node_attribute_xy, node_degree_xyfrom networkx.utils import dict_to_numpy_array
__all__ = [ "attribute_mixing_matrix", "attribute_mixing_dict", "degree_mixing_matrix", "degree_mixing_dict", "mixing_dict",]
@nx._dispatchable(node_attrs="attribute")def attribute_mixing_dict(G, attribute, nodes=None, normalized=False): """Returns dictionary representation of mixing matrix for attribute.
Parameters ---------- G : graph NetworkX graph object.
attribute : string Node attribute key.
nodes: list or iterable (optional) Unse nodes in container to build the dict. The default is all nodes.
normalized : bool (default=False) Return counts if False or probabilities if True.
Examples -------- >>> G = nx.Graph() >>> G.add_nodes_from([0, 1], color="red") >>> G.add_nodes_from([2, 3], color="blue") >>> G.add_edge(1, 3) >>> d = nx.attribute_mixing_dict(G, "color") >>> print(d["red"]["blue"]) 1 >>> print(d["blue"]["red"]) # d symmetric for undirected graphs 1
Returns ------- d : dictionary Counts or joint probability of occurrence of attribute pairs. """ xy_iter = node_attribute_xy(G, attribute, nodes) return mixing_dict(xy_iter, normalized=normalized)
@nx._dispatchable(node_attrs="attribute")def attribute_mixing_matrix(G, attribute, nodes=None, mapping=None, normalized=True): """Returns mixing matrix for attribute.
Parameters ---------- G : graph NetworkX graph object.
attribute : string Node attribute key.
nodes: list or iterable (optional) Use only nodes in container to build the matrix. The default is all nodes.
mapping : dictionary, optional Mapping from node attribute to integer index in matrix. If not specified, an arbitrary ordering will be used.
normalized : bool (default=True) Return counts if False or probabilities if True.
Returns ------- m: numpy array Counts or joint probability of occurrence of attribute pairs.
Notes ----- If each node has a unique attribute value, the unnormalized mixing matrix will be equal to the adjacency matrix. To get a denser mixing matrix, the rounding can be performed to form groups of nodes with equal values. For example, the exact height of persons in cm (180.79155222, 163.9080892, 163.30095355, 167.99016217, 168.21590163, ...) can be rounded to (180, 163, 163, 168, 168, ...).
Definitions of attribute mixing matrix vary on whether the matrix should include rows for attribute values that don't arise. Here we do not include such empty-rows. But you can force them to appear by inputting a `mapping` that includes those values.
Examples -------- >>> G = nx.path_graph(3) >>> gender = {0: "male", 1: "female", 2: "female"} >>> nx.set_node_attributes(G, gender, "gender") >>> mapping = {"male": 0, "female": 1} >>> mix_mat = nx.attribute_mixing_matrix(G, "gender", mapping=mapping) >>> mix_mat array([[0. , 0.25], [0.25, 0.5 ]]) """ d = attribute_mixing_dict(G, attribute, nodes) a = dict_to_numpy_array(d, mapping=mapping) if normalized: a = a / a.sum() return a
@nx._dispatchable(edge_attrs="weight")def degree_mixing_dict(G, x="out", y="in", weight=None, nodes=None, normalized=False): """Returns dictionary representation of mixing matrix for degree.
Parameters ---------- G : graph NetworkX graph object.
x: string ('in','out') The degree type for source node (directed graphs only).
y: string ('in','out') The degree type for target node (directed graphs only).
weight: string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
normalized : bool (default=False) Return counts if False or probabilities if True.
Returns ------- d: dictionary Counts or joint probability of occurrence of degree pairs. """ xy_iter = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight) return mixing_dict(xy_iter, normalized=normalized)
@nx._dispatchable(edge_attrs="weight")def degree_mixing_matrix( G, x="out", y="in", weight=None, nodes=None, normalized=True, mapping=None): """Returns mixing matrix for attribute.
Parameters ---------- G : graph NetworkX graph object.
x: string ('in','out') The degree type for source node (directed graphs only).
y: string ('in','out') The degree type for target node (directed graphs only).
nodes: list or iterable (optional) Build the matrix using only nodes in container. The default is all nodes.
weight: string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
normalized : bool (default=True) Return counts if False or probabilities if True.
mapping : dictionary, optional Mapping from node degree to integer index in matrix. If not specified, an arbitrary ordering will be used.
Returns ------- m: numpy array Counts, or joint probability, of occurrence of node degree.
Notes ----- Definitions of degree mixing matrix vary on whether the matrix should include rows for degree values that don't arise. Here we do not include such empty-rows. But you can force them to appear by inputting a `mapping` that includes those values. See examples.
Examples -------- >>> G = nx.star_graph(3) >>> mix_mat = nx.degree_mixing_matrix(G) >>> mix_mat array([[0. , 0.5], [0.5, 0. ]])
If you want every possible degree to appear as a row, even if no nodes have that degree, use `mapping` as follows,
>>> max_degree = max(deg for n, deg in G.degree) >>> mapping = {x: x for x in range(max_degree + 1)} # identity mapping >>> mix_mat = nx.degree_mixing_matrix(G, mapping=mapping) >>> mix_mat array([[0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0.5], [0. , 0. , 0. , 0. ], [0. , 0.5, 0. , 0. ]]) """ d = degree_mixing_dict(G, x=x, y=y, nodes=nodes, weight=weight) a = dict_to_numpy_array(d, mapping=mapping) if normalized: a = a / a.sum() return a
def mixing_dict(xy, normalized=False): """Returns a dictionary representation of mixing matrix.
Parameters ---------- xy : list or container of two-tuples Pairs of (x,y) items.
attribute : string Node attribute key
normalized : bool (default=False) Return counts if False or probabilities if True.
Returns ------- d: dictionary Counts or Joint probability of occurrence of values in xy. """ d = {} psum = 0.0 for x, y in xy: if x not in d: d[x] = {} if y not in d: d[y] = {} v = d[x].get(y, 0) d[x][y] = v + 1 psum += 1
if normalized: for _, jdict in d.items(): for j in jdict: jdict[j] /= psum return d123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160import networkx as nx
__all__ = ["average_neighbor_degree"]
@nx._dispatchable(edge_attrs="weight")def average_neighbor_degree(G, source="out", target="out", nodes=None, weight=None): r"""Returns the average degree of the neighborhood of each node.
In an undirected graph, the neighborhood `N(i)` of node `i` contains the nodes that are connected to `i` by an edge.
For directed graphs, `N(i)` is defined according to the parameter `source`:
- if source is 'in', then `N(i)` consists of predecessors of node `i`. - if source is 'out', then `N(i)` consists of successors of node `i`. - if source is 'in+out', then `N(i)` is both predecessors and successors.
The average neighborhood degree of a node `i` is
.. math::
k_{nn,i} = \frac{1}{|N(i)|} \sum_{j \in N(i)} k_j
where `N(i)` are the neighbors of node `i` and `k_j` is the degree of node `j` which belongs to `N(i)`. For weighted graphs, an analogous measure can be defined [1]_,
.. math::
k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
where `s_i` is the weighted degree of node `i`, `w_{ij}` is the weight of the edge that links `i` and `j` and `N(i)` are the neighbors of node `i`.
Parameters ---------- G : NetworkX graph
source : string ("in"|"out"|"in+out"), optional (default="out") Directed graphs only. Use "in"- or "out"-neighbors of source node.
target : string ("in"|"out"|"in+out"), optional (default="out") Directed graphs only. Use "in"- or "out"-degree for target node.
nodes : list or iterable, optional (default=G.nodes) Compute neighbor degree only for specified nodes.
weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1.
Returns ------- d: dict A dictionary keyed by node to the average degree of its neighbors.
Raises ------ NetworkXError If either `source` or `target` are not one of 'in', 'out', or 'in+out'. If either `source` or `target` is passed for an undirected graph.
Examples -------- >>> G = nx.path_graph(4) >>> G.edges[0, 1]["weight"] = 5 >>> G.edges[2, 3]["weight"] = 3
>>> nx.average_neighbor_degree(G) {0: 2.0, 1: 1.5, 2: 1.5, 3: 2.0} >>> nx.average_neighbor_degree(G, weight="weight") {0: 2.0, 1: 1.1666666666666667, 2: 1.25, 3: 2.0}
>>> G = nx.DiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> nx.average_neighbor_degree(G, source="in", target="in") {0: 0.0, 1: 0.0, 2: 1.0, 3: 1.0}
>>> nx.average_neighbor_degree(G, source="out", target="out") {0: 1.0, 1: 1.0, 2: 0.0, 3: 0.0}
See Also -------- average_degree_connectivity
References ---------- .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, "The architecture of complex weighted networks". PNAS 101 (11): 3747–3752 (2004). """ if G.is_directed(): if source == "in": source_degree = G.in_degree elif source == "out": source_degree = G.out_degree elif source == "in+out": source_degree = G.degree else: raise nx.NetworkXError( f"source argument {source} must be 'in', 'out' or 'in+out'" )
if target == "in": target_degree = G.in_degree elif target == "out": target_degree = G.out_degree elif target == "in+out": target_degree = G.degree else: raise nx.NetworkXError( f"target argument {target} must be 'in', 'out' or 'in+out'" ) else: if source != "out" or target != "out": raise nx.NetworkXError( f"source and target arguments are only supported for directed graphs" ) source_degree = target_degree = G.degree
# precompute target degrees -- should *not* be weighted degree t_deg = dict(target_degree())
# Set up both predecessor and successor neighbor dicts leaving empty if not needed G_P = G_S = {n: {} for n in G} if G.is_directed(): # "in" or "in+out" cases: G_P contains predecessors if "in" in source: G_P = G.pred # "out" or "in+out" cases: G_S contains successors if "out" in source: G_S = G.succ else: # undirected leave G_P empty but G_S is the adjacency G_S = G.adj
# Main loop: Compute average degree of neighbors avg = {} for n, deg in source_degree(nodes, weight=weight): # handle degree zero average if deg == 0: avg[n] = 0.0 continue
# we sum over both G_P and G_S, but one of the two is usually empty. if weight is None: avg[n] = ( sum(t_deg[nbr] for nbr in G_S[n]) + sum(t_deg[nbr] for nbr in G_P[n]) ) / deg else: avg[n] = ( sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_S[n].items()) + sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_P[n].items()) ) / deg return avg123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""Generators of x-y pairs of node data."""
import networkx as nx
__all__ = ["node_attribute_xy", "node_degree_xy"]
@nx._dispatchable(node_attrs="attribute")def node_attribute_xy(G, attribute, nodes=None): """Yields 2-tuples of node attribute values for all edges in `G`.
This generator yields, for each edge in `G` incident to a node in `nodes`, a 2-tuple of form ``(attribute value, attribute value)`` for the parameter specified node-attribute.
Parameters ---------- G: NetworkX graph
attribute: key The node attribute key.
nodes: list or iterable (optional) Use only edges that are incident to specified nodes. The default is all nodes.
Yields ------ (x, y): 2-tuple Generates 2-tuple of (attribute, attribute) values.
Examples -------- >>> G = nx.DiGraph() >>> G.add_node(1, color="red") >>> G.add_node(2, color="blue") >>> G.add_node(3, color="green") >>> G.add_edge(1, 2) >>> list(nx.node_attribute_xy(G, "color")) [('red', 'blue')]
Notes ----- For undirected graphs, each edge is produced twice, once for each edge representation (u, v) and (v, u), with the exception of self-loop edges which only appear once. """ if nodes is None: nodes = set(G) else: nodes = set(nodes) Gnodes = G.nodes for u, nbrsdict in G.adjacency(): if u not in nodes: continue uattr = Gnodes[u].get(attribute, None) if G.is_multigraph(): for v, keys in nbrsdict.items(): vattr = Gnodes[v].get(attribute, None) for _ in keys: yield (uattr, vattr) else: for v in nbrsdict: vattr = Gnodes[v].get(attribute, None) yield (uattr, vattr)
@nx._dispatchable(edge_attrs="weight")def node_degree_xy(G, x="out", y="in", weight=None, nodes=None): """Yields 2-tuples of ``(degree, degree)`` values for edges in `G`.
This generator yields, for each edge in `G` incident to a node in `nodes`, a 2-tuple of form ``(degree, degree)``. The node degrees are weighted when a `weight` attribute is specified.
Parameters ---------- G: NetworkX graph
x: string ('in','out') The degree type for source node (directed graphs only).
y: string ('in','out') The degree type for target node (directed graphs only).
weight: string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
nodes: list or iterable (optional) Use only edges that are adjacency to specified nodes. The default is all nodes.
Yields ------ (x, y): 2-tuple Generates 2-tuple of (degree, degree) values.
Examples -------- >>> G = nx.DiGraph() >>> G.add_edge(1, 2) >>> list(nx.node_degree_xy(G, x="out", y="in")) [(1, 1)] >>> list(nx.node_degree_xy(G, x="in", y="out")) [(0, 0)]
Notes ----- For undirected graphs, each edge is produced twice, once for each edge representation (u, v) and (v, u), with the exception of self-loop edges which only appear once. """ nodes = set(G) if nodes is None else set(nodes) if G.is_directed(): direction = {"out": G.out_degree, "in": G.in_degree} xdeg = direction[x] ydeg = direction[y] else: xdeg = ydeg = G.degree
for u, degu in xdeg(nodes, weight=weight): # use G.edges to treat multigraphs correctly neighbors = (nbr for _, nbr in G.edges(u) if nbr in nodes) for _, degv in ydeg(neighbors, weight=weight): yield degu, degv123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import networkx as nx
class BaseTestAttributeMixing: @classmethod def setup_class(cls): G = nx.Graph() G.add_nodes_from([0, 1], fish="one") G.add_nodes_from([2, 3], fish="two") G.add_nodes_from([4], fish="red") G.add_nodes_from([5], fish="blue") G.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)]) cls.G = G
D = nx.DiGraph() D.add_nodes_from([0, 1], fish="one") D.add_nodes_from([2, 3], fish="two") D.add_nodes_from([4], fish="red") D.add_nodes_from([5], fish="blue") D.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)]) cls.D = D
M = nx.MultiGraph() M.add_nodes_from([0, 1], fish="one") M.add_nodes_from([2, 3], fish="two") M.add_nodes_from([4], fish="red") M.add_nodes_from([5], fish="blue") M.add_edges_from([(0, 1), (0, 1), (2, 3)]) cls.M = M
S = nx.Graph() S.add_nodes_from([0, 1], fish="one") S.add_nodes_from([2, 3], fish="two") S.add_nodes_from([4], fish="red") S.add_nodes_from([5], fish="blue") S.add_edge(0, 0) S.add_edge(2, 2) cls.S = S
N = nx.Graph() N.add_nodes_from([0, 1], margin=-2) N.add_nodes_from([2, 3], margin=-2) N.add_nodes_from([4], margin=-3) N.add_nodes_from([5], margin=-4) N.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)]) cls.N = N
F = nx.Graph() F.add_edges_from([(0, 3), (1, 3), (2, 3)], weight=0.5) F.add_edge(0, 2, weight=1) nx.set_node_attributes(F, dict(F.degree(weight="weight")), "margin") cls.F = F
K = nx.Graph() K.add_nodes_from([1, 2], margin=-1) K.add_nodes_from([3], margin=1) K.add_nodes_from([4], margin=2) K.add_edges_from([(3, 4), (1, 2), (1, 3)]) cls.K = K
class BaseTestDegreeMixing: @classmethod def setup_class(cls): cls.P4 = nx.path_graph(4) cls.D = nx.DiGraph() cls.D.add_edges_from([(0, 2), (0, 3), (1, 3), (2, 3)]) cls.D2 = nx.DiGraph() cls.D2.add_edges_from([(0, 3), (1, 0), (1, 2), (2, 4), (4, 1), (4, 3), (4, 2)]) cls.M = nx.MultiGraph() nx.add_path(cls.M, range(4)) cls.M.add_edge(0, 1) cls.S = nx.Graph() cls.S.add_edges_from([(0, 0), (1, 1)]) cls.W = nx.Graph() cls.W.add_edges_from([(0, 3), (1, 3), (2, 3)], weight=0.5) cls.W.add_edge(0, 2, weight=1) S1 = nx.star_graph(4) S2 = nx.star_graph(4) cls.DS = nx.disjoint_union(S1, S2) cls.DS.add_edge(4, 5)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143from itertools import permutations
import pytest
import networkx as nx
class TestNeighborConnectivity: def test_degree_p4(self): G = nx.path_graph(4) answer = {1: 2.0, 2: 1.5} nd = nx.average_degree_connectivity(G) assert nd == answer
D = G.to_directed() answer = {2: 2.0, 4: 1.5} nd = nx.average_degree_connectivity(D) assert nd == answer
answer = {1: 2.0, 2: 1.5} D = G.to_directed() nd = nx.average_degree_connectivity(D, source="in", target="in") assert nd == answer
D = G.to_directed() nd = nx.average_degree_connectivity(D, source="in", target="in") assert nd == answer
def test_degree_p4_weighted(self): G = nx.path_graph(4) G[1][2]["weight"] = 4 answer = {1: 2.0, 2: 1.8} nd = nx.average_degree_connectivity(G, weight="weight") assert nd == answer answer = {1: 2.0, 2: 1.5} nd = nx.average_degree_connectivity(G) assert nd == answer
D = G.to_directed() answer = {2: 2.0, 4: 1.8} nd = nx.average_degree_connectivity(D, weight="weight") assert nd == answer
answer = {1: 2.0, 2: 1.8} D = G.to_directed() nd = nx.average_degree_connectivity( D, weight="weight", source="in", target="in" ) assert nd == answer
D = G.to_directed() nd = nx.average_degree_connectivity( D, source="in", target="out", weight="weight" ) assert nd == answer
def test_weight_keyword(self): G = nx.path_graph(4) G[1][2]["other"] = 4 answer = {1: 2.0, 2: 1.8} nd = nx.average_degree_connectivity(G, weight="other") assert nd == answer answer = {1: 2.0, 2: 1.5} nd = nx.average_degree_connectivity(G, weight=None) assert nd == answer
D = G.to_directed() answer = {2: 2.0, 4: 1.8} nd = nx.average_degree_connectivity(D, weight="other") assert nd == answer
answer = {1: 2.0, 2: 1.8} D = G.to_directed() nd = nx.average_degree_connectivity(D, weight="other", source="in", target="in") assert nd == answer
D = G.to_directed() nd = nx.average_degree_connectivity(D, weight="other", source="in", target="in") assert nd == answer
def test_degree_barrat(self): G = nx.star_graph(5) G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)]) G[0][5]["weight"] = 5 nd = nx.average_degree_connectivity(G)[5] assert nd == 1.8 nd = nx.average_degree_connectivity(G, weight="weight")[5] assert nd == pytest.approx(3.222222, abs=1e-5)
def test_zero_deg(self): G = nx.DiGraph() G.add_edge(1, 2) G.add_edge(1, 3) G.add_edge(1, 4) c = nx.average_degree_connectivity(G) assert c == {1: 0, 3: 1} c = nx.average_degree_connectivity(G, source="in", target="in") assert c == {0: 0, 1: 0} c = nx.average_degree_connectivity(G, source="in", target="out") assert c == {0: 0, 1: 3} c = nx.average_degree_connectivity(G, source="in", target="in+out") assert c == {0: 0, 1: 3} c = nx.average_degree_connectivity(G, source="out", target="out") assert c == {0: 0, 3: 0} c = nx.average_degree_connectivity(G, source="out", target="in") assert c == {0: 0, 3: 1} c = nx.average_degree_connectivity(G, source="out", target="in+out") assert c == {0: 0, 3: 1}
def test_in_out_weight(self): G = nx.DiGraph() G.add_edge(1, 2, weight=1) G.add_edge(1, 3, weight=1) G.add_edge(3, 1, weight=1) for s, t in permutations(["in", "out", "in+out"], 2): c = nx.average_degree_connectivity(G, source=s, target=t) cw = nx.average_degree_connectivity(G, source=s, target=t, weight="weight") assert c == cw
def test_invalid_source(self): with pytest.raises(nx.NetworkXError): G = nx.DiGraph() nx.average_degree_connectivity(G, source="bogus")
def test_invalid_target(self): with pytest.raises(nx.NetworkXError): G = nx.DiGraph() nx.average_degree_connectivity(G, target="bogus")
def test_invalid_undirected_graph(self): G = nx.Graph() with pytest.raises(nx.NetworkXError): nx.average_degree_connectivity(G, target="bogus") with pytest.raises(nx.NetworkXError): nx.average_degree_connectivity(G, source="bogus")
def test_single_node(self): # TODO Is this really the intended behavior for providing a # single node as the argument `nodes`? Shouldn't the function # just return the connectivity value itself? G = nx.trivial_graph() conn = nx.average_degree_connectivity(G, nodes=0) assert conn == {0: 0}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122import pytest
import networkx as nxfrom networkx.algorithms.assortativity.correlation import attribute_ac
from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
np = pytest.importorskip("numpy")pytest.importorskip("scipy")
class TestDegreeMixingCorrelation(BaseTestDegreeMixing): def test_degree_assortativity_undirected(self): r = nx.degree_assortativity_coefficient(self.P4) np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4)
def test_degree_assortativity_node_kwargs(self): G = nx.Graph() edges = [(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (5, 9), (9, 0)] G.add_edges_from(edges) r = nx.degree_assortativity_coefficient(G, nodes=[1, 2, 4]) np.testing.assert_almost_equal(r, -1.0, decimal=4)
def test_degree_assortativity_directed(self): r = nx.degree_assortativity_coefficient(self.D) np.testing.assert_almost_equal(r, -0.57735, decimal=4)
def test_degree_assortativity_directed2(self): """Test degree assortativity for a directed graph where the set of in/out degree does not equal the total degree.""" r = nx.degree_assortativity_coefficient(self.D2) np.testing.assert_almost_equal(r, 0.14852, decimal=4)
def test_degree_assortativity_multigraph(self): r = nx.degree_assortativity_coefficient(self.M) np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4)
def test_degree_pearson_assortativity_undirected(self): r = nx.degree_pearson_correlation_coefficient(self.P4) np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4)
def test_degree_pearson_assortativity_directed(self): r = nx.degree_pearson_correlation_coefficient(self.D) np.testing.assert_almost_equal(r, -0.57735, decimal=4)
def test_degree_pearson_assortativity_directed2(self): """Test degree assortativity with Pearson for a directed graph where the set of in/out degree does not equal the total degree.""" r = nx.degree_pearson_correlation_coefficient(self.D2) np.testing.assert_almost_equal(r, 0.14852, decimal=4)
def test_degree_pearson_assortativity_multigraph(self): r = nx.degree_pearson_correlation_coefficient(self.M) np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4)
def test_degree_assortativity_weighted(self): r = nx.degree_assortativity_coefficient(self.W, weight="weight") np.testing.assert_almost_equal(r, -0.1429, decimal=4)
def test_degree_assortativity_double_star(self): r = nx.degree_assortativity_coefficient(self.DS) np.testing.assert_almost_equal(r, -0.9339, decimal=4)
class TestAttributeMixingCorrelation(BaseTestAttributeMixing): def test_attribute_assortativity_undirected(self): r = nx.attribute_assortativity_coefficient(self.G, "fish") assert r == 6.0 / 22.0
def test_attribute_assortativity_directed(self): r = nx.attribute_assortativity_coefficient(self.D, "fish") assert r == 1.0 / 3.0
def test_attribute_assortativity_multigraph(self): r = nx.attribute_assortativity_coefficient(self.M, "fish") assert r == 1.0
def test_attribute_assortativity_coefficient(self): # from "Mixing patterns in networks" # fmt: off a = np.array([[0.258, 0.016, 0.035, 0.013], [0.012, 0.157, 0.058, 0.019], [0.013, 0.023, 0.306, 0.035], [0.005, 0.007, 0.024, 0.016]]) # fmt: on r = attribute_ac(a) np.testing.assert_almost_equal(r, 0.623, decimal=3)
def test_attribute_assortativity_coefficient2(self): # fmt: off a = np.array([[0.18, 0.02, 0.01, 0.03], [0.02, 0.20, 0.03, 0.02], [0.01, 0.03, 0.16, 0.01], [0.03, 0.02, 0.01, 0.22]]) # fmt: on r = attribute_ac(a) np.testing.assert_almost_equal(r, 0.68, decimal=2)
def test_attribute_assortativity(self): a = np.array([[50, 50, 0], [50, 50, 0], [0, 0, 2]]) r = attribute_ac(a) np.testing.assert_almost_equal(r, 0.029, decimal=3)
def test_attribute_assortativity_negative(self): r = nx.numeric_assortativity_coefficient(self.N, "margin") np.testing.assert_almost_equal(r, -0.2903, decimal=4)
def test_assortativity_node_kwargs(self): G = nx.Graph() G.add_nodes_from([0, 1], size=2) G.add_nodes_from([2, 3], size=3) G.add_edges_from([(0, 1), (2, 3)]) r = nx.numeric_assortativity_coefficient(G, "size", nodes=[0, 3]) np.testing.assert_almost_equal(r, 1.0, decimal=4)
def test_attribute_assortativity_float(self): r = nx.numeric_assortativity_coefficient(self.F, "margin") np.testing.assert_almost_equal(r, -0.1429, decimal=4)
def test_attribute_assortativity_mixed(self): r = nx.numeric_assortativity_coefficient(self.K, "margin") np.testing.assert_almost_equal(r, 0.4340, decimal=4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174import pytest
import networkx as nx
from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
np = pytest.importorskip("numpy")
class TestDegreeMixingDict(BaseTestDegreeMixing): def test_degree_mixing_dict_undirected(self): d = nx.degree_mixing_dict(self.P4) d_result = {1: {2: 2}, 2: {1: 2, 2: 2}} assert d == d_result
def test_degree_mixing_dict_undirected_normalized(self): d = nx.degree_mixing_dict(self.P4, normalized=True) d_result = {1: {2: 1.0 / 3}, 2: {1: 1.0 / 3, 2: 1.0 / 3}} assert d == d_result
def test_degree_mixing_dict_directed(self): d = nx.degree_mixing_dict(self.D) d_result = {1: {3: 2}, 2: {1: 1, 3: 1}, 3: {}} assert d == d_result
def test_degree_mixing_dict_multigraph(self): d = nx.degree_mixing_dict(self.M) d_result = {1: {2: 1}, 2: {1: 1, 3: 3}, 3: {2: 3}} assert d == d_result
def test_degree_mixing_dict_weighted(self): d = nx.degree_mixing_dict(self.W, weight="weight") d_result = {0.5: {1.5: 1}, 1.5: {1.5: 6, 0.5: 1}} assert d == d_result
class TestDegreeMixingMatrix(BaseTestDegreeMixing): def test_degree_mixing_matrix_undirected(self): # fmt: off a_result = np.array([[0, 2], [2, 2]] ) # fmt: on a = nx.degree_mixing_matrix(self.P4, normalized=False) np.testing.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.P4) np.testing.assert_equal(a, a_result / a_result.sum())
def test_degree_mixing_matrix_directed(self): # fmt: off a_result = np.array([[0, 0, 2], [1, 0, 1], [0, 0, 0]] ) # fmt: on a = nx.degree_mixing_matrix(self.D, normalized=False) np.testing.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.D) np.testing.assert_equal(a, a_result / a_result.sum())
def test_degree_mixing_matrix_multigraph(self): # fmt: off a_result = np.array([[0, 1, 0], [1, 0, 3], [0, 3, 0]] ) # fmt: on a = nx.degree_mixing_matrix(self.M, normalized=False) np.testing.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.M) np.testing.assert_equal(a, a_result / a_result.sum())
def test_degree_mixing_matrix_selfloop(self): # fmt: off a_result = np.array([[2]]) # fmt: on a = nx.degree_mixing_matrix(self.S, normalized=False) np.testing.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.S) np.testing.assert_equal(a, a_result / a_result.sum())
def test_degree_mixing_matrix_weighted(self): a_result = np.array([[0.0, 1.0], [1.0, 6.0]]) a = nx.degree_mixing_matrix(self.W, weight="weight", normalized=False) np.testing.assert_equal(a, a_result) a = nx.degree_mixing_matrix(self.W, weight="weight") np.testing.assert_equal(a, a_result / float(a_result.sum()))
def test_degree_mixing_matrix_mapping(self): a_result = np.array([[6.0, 1.0], [1.0, 0.0]]) mapping = {0.5: 1, 1.5: 0} a = nx.degree_mixing_matrix( self.W, weight="weight", normalized=False, mapping=mapping ) np.testing.assert_equal(a, a_result)
class TestAttributeMixingDict(BaseTestAttributeMixing): def test_attribute_mixing_dict_undirected(self): d = nx.attribute_mixing_dict(self.G, "fish") d_result = { "one": {"one": 2, "red": 1}, "two": {"two": 2, "blue": 1}, "red": {"one": 1}, "blue": {"two": 1}, } assert d == d_result
def test_attribute_mixing_dict_directed(self): d = nx.attribute_mixing_dict(self.D, "fish") d_result = { "one": {"one": 1, "red": 1}, "two": {"two": 1, "blue": 1}, "red": {}, "blue": {}, } assert d == d_result
def test_attribute_mixing_dict_multigraph(self): d = nx.attribute_mixing_dict(self.M, "fish") d_result = {"one": {"one": 4}, "two": {"two": 2}} assert d == d_result
class TestAttributeMixingMatrix(BaseTestAttributeMixing): def test_attribute_mixing_matrix_undirected(self): mapping = {"one": 0, "two": 1, "red": 2, "blue": 3} a_result = np.array([[2, 0, 1, 0], [0, 2, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]]) a = nx.attribute_mixing_matrix( self.G, "fish", mapping=mapping, normalized=False ) np.testing.assert_equal(a, a_result) a = nx.attribute_mixing_matrix(self.G, "fish", mapping=mapping) np.testing.assert_equal(a, a_result / a_result.sum())
def test_attribute_mixing_matrix_directed(self): mapping = {"one": 0, "two": 1, "red": 2, "blue": 3} a_result = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]]) a = nx.attribute_mixing_matrix( self.D, "fish", mapping=mapping, normalized=False ) np.testing.assert_equal(a, a_result) a = nx.attribute_mixing_matrix(self.D, "fish", mapping=mapping) np.testing.assert_equal(a, a_result / a_result.sum())
def test_attribute_mixing_matrix_multigraph(self): mapping = {"one": 0, "two": 1, "red": 2, "blue": 3} a_result = np.array([[4, 0, 0, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) a = nx.attribute_mixing_matrix( self.M, "fish", mapping=mapping, normalized=False ) np.testing.assert_equal(a, a_result) a = nx.attribute_mixing_matrix(self.M, "fish", mapping=mapping) np.testing.assert_equal(a, a_result / a_result.sum())
def test_attribute_mixing_matrix_negative(self): mapping = {-2: 0, -3: 1, -4: 2} a_result = np.array([[4.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) a = nx.attribute_mixing_matrix( self.N, "margin", mapping=mapping, normalized=False ) np.testing.assert_equal(a, a_result) a = nx.attribute_mixing_matrix(self.N, "margin", mapping=mapping) np.testing.assert_equal(a, a_result / float(a_result.sum()))
def test_attribute_mixing_matrix_float(self): mapping = {0.5: 1, 1.5: 0} a_result = np.array([[6.0, 1.0], [1.0, 0.0]]) a = nx.attribute_mixing_matrix( self.F, "margin", mapping=mapping, normalized=False ) np.testing.assert_equal(a, a_result) a = nx.attribute_mixing_matrix(self.F, "margin", mapping=mapping) np.testing.assert_equal(a, a_result / a_result.sum())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107import pytest
import networkx as nx
class TestAverageNeighbor: def test_degree_p4(self): G = nx.path_graph(4) answer = {0: 2, 1: 1.5, 2: 1.5, 3: 2} nd = nx.average_neighbor_degree(G) assert nd == answer
D = G.to_directed() nd = nx.average_neighbor_degree(D) assert nd == answer
D = nx.DiGraph(G.edges(data=True)) nd = nx.average_neighbor_degree(D) assert nd == {0: 1, 1: 1, 2: 0, 3: 0} nd = nx.average_neighbor_degree(D, "in", "out") assert nd == {0: 0, 1: 1, 2: 1, 3: 1} nd = nx.average_neighbor_degree(D, "out", "in") assert nd == {0: 1, 1: 1, 2: 1, 3: 0} nd = nx.average_neighbor_degree(D, "in", "in") assert nd == {0: 0, 1: 0, 2: 1, 3: 1}
def test_degree_p4_weighted(self): G = nx.path_graph(4) G[1][2]["weight"] = 4 answer = {0: 2, 1: 1.8, 2: 1.8, 3: 2} nd = nx.average_neighbor_degree(G, weight="weight") assert nd == answer
D = G.to_directed() nd = nx.average_neighbor_degree(D, weight="weight") assert nd == answer
D = nx.DiGraph(G.edges(data=True)) nd = nx.average_neighbor_degree(D, weight="weight") assert nd == {0: 1, 1: 1, 2: 0, 3: 0} nd = nx.average_neighbor_degree(D, "out", "out", weight="weight") assert nd == {0: 1, 1: 1, 2: 0, 3: 0} nd = nx.average_neighbor_degree(D, "in", "in", weight="weight") assert nd == {0: 0, 1: 0, 2: 1, 3: 1} nd = nx.average_neighbor_degree(D, "in", "out", weight="weight") assert nd == {0: 0, 1: 1, 2: 1, 3: 1} nd = nx.average_neighbor_degree(D, "out", "in", weight="weight") assert nd == {0: 1, 1: 1, 2: 1, 3: 0} nd = nx.average_neighbor_degree(D, source="in+out", weight="weight") assert nd == {0: 1.0, 1: 1.0, 2: 0.8, 3: 1.0} nd = nx.average_neighbor_degree(D, target="in+out", weight="weight") assert nd == {0: 2.0, 1: 2.0, 2: 1.0, 3: 0.0}
D = G.to_directed() nd = nx.average_neighbor_degree(D, weight="weight") assert nd == answer nd = nx.average_neighbor_degree(D, source="out", target="out", weight="weight") assert nd == answer
D = G.to_directed() nd = nx.average_neighbor_degree(D, source="in", target="in", weight="weight") assert nd == answer
def test_degree_k4(self): G = nx.complete_graph(4) answer = {0: 3, 1: 3, 2: 3, 3: 3} nd = nx.average_neighbor_degree(G) assert nd == answer
D = G.to_directed() nd = nx.average_neighbor_degree(D) assert nd == answer
D = G.to_directed() nd = nx.average_neighbor_degree(D) assert nd == answer
D = G.to_directed() nd = nx.average_neighbor_degree(D, source="in", target="in") assert nd == answer
def test_degree_k4_nodes(self): G = nx.complete_graph(4) answer = {1: 3.0, 2: 3.0} nd = nx.average_neighbor_degree(G, nodes=[1, 2]) assert nd == answer
def test_degree_barrat(self): G = nx.star_graph(5) G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)]) G[0][5]["weight"] = 5 nd = nx.average_neighbor_degree(G)[5] assert nd == 1.8 nd = nx.average_neighbor_degree(G, weight="weight")[5] assert nd == pytest.approx(3.222222, abs=1e-5)
def test_error_invalid_source_target(self): G = nx.path_graph(4) with pytest.raises(nx.NetworkXError): nx.average_neighbor_degree(G, "error") with pytest.raises(nx.NetworkXError): nx.average_neighbor_degree(G, "in", "error") G = G.to_directed() with pytest.raises(nx.NetworkXError): nx.average_neighbor_degree(G, "error") with pytest.raises(nx.NetworkXError): nx.average_neighbor_degree(G, "in", "error")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687import networkx as nx
from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
class TestAttributeMixingXY(BaseTestAttributeMixing): def test_node_attribute_xy_undirected(self): attrxy = sorted(nx.node_attribute_xy(self.G, "fish")) attrxy_result = sorted( [ ("one", "one"), ("one", "one"), ("two", "two"), ("two", "two"), ("one", "red"), ("red", "one"), ("blue", "two"), ("two", "blue"), ] ) assert attrxy == attrxy_result
def test_node_attribute_xy_undirected_nodes(self): attrxy = sorted(nx.node_attribute_xy(self.G, "fish", nodes=["one", "yellow"])) attrxy_result = sorted([]) assert attrxy == attrxy_result
def test_node_attribute_xy_directed(self): attrxy = sorted(nx.node_attribute_xy(self.D, "fish")) attrxy_result = sorted( [("one", "one"), ("two", "two"), ("one", "red"), ("two", "blue")] ) assert attrxy == attrxy_result
def test_node_attribute_xy_multigraph(self): attrxy = sorted(nx.node_attribute_xy(self.M, "fish")) attrxy_result = [ ("one", "one"), ("one", "one"), ("one", "one"), ("one", "one"), ("two", "two"), ("two", "two"), ] assert attrxy == attrxy_result
def test_node_attribute_xy_selfloop(self): attrxy = sorted(nx.node_attribute_xy(self.S, "fish")) attrxy_result = [("one", "one"), ("two", "two")] assert attrxy == attrxy_result
class TestDegreeMixingXY(BaseTestDegreeMixing): def test_node_degree_xy_undirected(self): xy = sorted(nx.node_degree_xy(self.P4)) xy_result = sorted([(1, 2), (2, 1), (2, 2), (2, 2), (1, 2), (2, 1)]) assert xy == xy_result
def test_node_degree_xy_undirected_nodes(self): xy = sorted(nx.node_degree_xy(self.P4, nodes=[0, 1, -1])) xy_result = sorted([(1, 2), (2, 1)]) assert xy == xy_result
def test_node_degree_xy_directed(self): xy = sorted(nx.node_degree_xy(self.D)) xy_result = sorted([(2, 1), (2, 3), (1, 3), (1, 3)]) assert xy == xy_result
def test_node_degree_xy_multigraph(self): xy = sorted(nx.node_degree_xy(self.M)) xy_result = sorted( [(2, 3), (2, 3), (3, 2), (3, 2), (2, 3), (3, 2), (1, 2), (2, 1)] ) assert xy == xy_result
def test_node_degree_xy_selfloop(self): xy = sorted(nx.node_degree_xy(self.S)) xy_result = sorted([(2, 2), (2, 2)]) assert xy == xy_result
def test_node_degree_xy_weighted(self): G = nx.Graph() G.add_edge(1, 2, weight=7) G.add_edge(2, 3, weight=10) xy = sorted(nx.node_degree_xy(G, weight="weight")) xy_result = sorted([(7, 17), (17, 10), (17, 7), (10, 17)]) assert xy == xy_result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164"""Algorithms for asteroidal triples and asteroidal numbers in graphs.
An asteroidal triple in a graph G is a set of three non-adjacent verticesu, v and w such that there exist a path between any two of them that avoidsclosed neighborhood of the third. More formally, v_j, v_k belongs to the sameconnected component of G - N[v_i], where N[v_i] denotes the closed neighborhoodof v_i. A graph which does not contain any asteroidal triples is calledan AT-free graph. The class of AT-free graphs is a graph class for whichmany NP-complete problems are solvable in polynomial time. Amongst them,independent set and coloring."""
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = ["is_at_free", "find_asteroidal_triple"]
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchabledef find_asteroidal_triple(G): r"""Find an asteroidal triple in the given graph.
An asteroidal triple is a triple of non-adjacent vertices such that there exists a path between any two of them which avoids the closed neighborhood of the third. It checks all independent triples of vertices and whether they are an asteroidal triple or not. This is done with the help of a data structure called a component structure. A component structure encodes information about which vertices belongs to the same connected component when the closed neighborhood of a given vertex is removed from the graph. The algorithm used to check is the trivial one, outlined in [1]_, which has a runtime of :math:`O(|V||\overline{E} + |V||E|)`, where the second term is the creation of the component structure.
Parameters ---------- G : NetworkX Graph The graph to check whether is AT-free or not
Returns ------- list or None An asteroidal triple is returned as a list of nodes. If no asteroidal triple exists, i.e. the graph is AT-free, then None is returned.
Notes ----- The component structure and the algorithm is described in [1]_. The current implementation implements the trivial algorithm for simple graphs.
References ---------- .. [1] Ekkehard Köhler, "Recognizing Graphs without asteroidal triples", Journal of Discrete Algorithms 2, pages 439-452, 2004. https://www.sciencedirect.com/science/article/pii/S157086670400019X """ V = set(G.nodes)
if len(V) < 6: # An asteroidal triple cannot exist in a graph with 5 or less vertices. return None
component_structure = create_component_structure(G)
for u, v in nx.non_edges(G): u_neighborhood = set(G[u]).union([u]) v_neighborhood = set(G[v]).union([v]) union_of_neighborhoods = u_neighborhood.union(v_neighborhood) for w in V - union_of_neighborhoods: # Check for each pair of vertices whether they belong to the # same connected component when the closed neighborhood of the # third is removed. if ( component_structure[u][v] == component_structure[u][w] and component_structure[v][u] == component_structure[v][w] and component_structure[w][u] == component_structure[w][v] ): return [u, v, w] return None
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchabledef is_at_free(G): """Check if a graph is AT-free.
The method uses the `find_asteroidal_triple` method to recognize an AT-free graph. If no asteroidal triple is found the graph is AT-free and True is returned. If at least one asteroidal triple is found the graph is not AT-free and False is returned.
Parameters ---------- G : NetworkX Graph The graph to check whether is AT-free or not.
Returns ------- bool True if G is AT-free and False otherwise.
Examples -------- >>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)]) >>> nx.is_at_free(G) True
>>> G = nx.cycle_graph(6) >>> nx.is_at_free(G) False """ return find_asteroidal_triple(G) is None
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchabledef create_component_structure(G): r"""Create component structure for G.
A *component structure* is an `nxn` array, denoted `c`, where `n` is the number of vertices, where each row and column corresponds to a vertex.
.. math:: c_{uv} = \begin{cases} 0, if v \in N[u] \\ k, if v \in component k of G \setminus N[u] \end{cases}
Where `k` is an arbitrary label for each component. The structure is used to simplify the detection of asteroidal triples.
Parameters ---------- G : NetworkX Graph Undirected, simple graph.
Returns ------- component_structure : dictionary A dictionary of dictionaries, keyed by pairs of vertices.
""" V = set(G.nodes) component_structure = {} for v in V: label = 0 closed_neighborhood = set(G[v]).union({v}) row_dict = {} for u in closed_neighborhood: row_dict[u] = 0
G_reduced = G.subgraph(set(G.nodes) - closed_neighborhood) for cc in nx.connected_components(G_reduced): label += 1 for u in cc: row_dict[u] = label
component_structure[v] = row_dict
return component_structure123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""Routines to find the boundary of a set of nodes.
An edge boundary is a set of edges, each of which has exactly oneendpoint in a given set of nodes (or, in the case of directed graphs,the set of edges whose source node is in the set).
A node boundary of a set *S* of nodes is the set of (out-)neighbors ofnodes in *S* that are outside *S*.
"""
from itertools import chain
import networkx as nx
__all__ = ["edge_boundary", "node_boundary"]
@nx._dispatchable(edge_attrs={"data": "default"}, preserve_edge_attrs="data")def edge_boundary(G, nbunch1, nbunch2=None, data=False, keys=False, default=None): """Returns the edge boundary of `nbunch1`.
The *edge boundary* of a set *S* with respect to a set *T* is the set of edges (*u*, *v*) such that *u* is in *S* and *v* is in *T*. If *T* is not specified, it is assumed to be the set of all nodes not in *S*.
Parameters ---------- G : NetworkX graph
nbunch1 : iterable Iterable of nodes in the graph representing the set of nodes whose edge boundary will be returned. (This is the set *S* from the definition above.)
nbunch2 : iterable Iterable of nodes representing the target (or "exterior") set of nodes. (This is the set *T* from the definition above.) If not specified, this is assumed to be the set of all nodes in `G` not in `nbunch1`.
keys : bool This parameter has the same meaning as in :meth:`MultiGraph.edges`.
data : bool or object This parameter has the same meaning as in :meth:`MultiGraph.edges`.
default : object This parameter has the same meaning as in :meth:`MultiGraph.edges`.
Returns ------- iterator An iterator over the edges in the boundary of `nbunch1` with respect to `nbunch2`. If `keys`, `data`, or `default` are specified and `G` is a multigraph, then edges are returned with keys and/or data, as in :meth:`MultiGraph.edges`.
Examples -------- >>> G = nx.wheel_graph(6)
When nbunch2=None:
>>> list(nx.edge_boundary(G, (1, 3))) [(1, 0), (1, 2), (1, 5), (3, 0), (3, 2), (3, 4)]
When nbunch2 is given:
>>> list(nx.edge_boundary(G, (1, 3), (2, 0))) [(1, 0), (1, 2), (3, 0), (3, 2)]
Notes ----- Any element of `nbunch` that is not in the graph `G` will be ignored.
`nbunch1` and `nbunch2` are usually meant to be disjoint, but in the interest of speed and generality, that is not required here.
""" nset1 = {n for n in nbunch1 if n in G} # Here we create an iterator over edges incident to nodes in the set # `nset1`. The `Graph.edges()` method does not provide a guarantee # on the orientation of the edges, so our algorithm below must # handle the case in which exactly one orientation, either (u, v) or # (v, u), appears in this iterable. if G.is_multigraph(): edges = G.edges(nset1, data=data, keys=keys, default=default) else: edges = G.edges(nset1, data=data, default=default) # If `nbunch2` is not provided, then it is assumed to be the set # complement of `nbunch1`. For the sake of efficiency, this is # implemented by using the `not in` operator, instead of by creating # an additional set and using the `in` operator. if nbunch2 is None: return (e for e in edges if (e[0] in nset1) ^ (e[1] in nset1)) nset2 = set(nbunch2) return ( e for e in edges if (e[0] in nset1 and e[1] in nset2) or (e[1] in nset1 and e[0] in nset2) )
@nx._dispatchabledef node_boundary(G, nbunch1, nbunch2=None): """Returns the node boundary of `nbunch1`.
The *node boundary* of a set *S* with respect to a set *T* is the set of nodes *v* in *T* such that for some *u* in *S*, there is an edge joining *u* to *v*. If *T* is not specified, it is assumed to be the set of all nodes not in *S*.
Parameters ---------- G : NetworkX graph
nbunch1 : iterable Iterable of nodes in the graph representing the set of nodes whose node boundary will be returned. (This is the set *S* from the definition above.)
nbunch2 : iterable Iterable of nodes representing the target (or "exterior") set of nodes. (This is the set *T* from the definition above.) If not specified, this is assumed to be the set of all nodes in `G` not in `nbunch1`.
Returns ------- set The node boundary of `nbunch1` with respect to `nbunch2`.
Examples -------- >>> G = nx.wheel_graph(6)
When nbunch2=None:
>>> list(nx.node_boundary(G, (3, 4))) [0, 2, 5]
When nbunch2 is given:
>>> list(nx.node_boundary(G, (3, 4), (0, 1, 5))) [0, 5]
Notes ----- Any element of `nbunch` that is not in the graph `G` will be ignored.
`nbunch1` and `nbunch2` are usually meant to be disjoint, but in the interest of speed and generality, that is not required here.
""" nset1 = {n for n in nbunch1 if n in G} bdy = set(chain.from_iterable(G[v] for v in nset1)) - nset1 # If `nbunch2` is not specified, it is assumed to be the set # complement of `nbunch1`. if nbunch2 is not None: bdy &= set(nbunch2) return bdy123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205"""Bridge-finding algorithms."""
from itertools import chain
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = ["bridges", "has_bridges", "local_bridges"]
@not_implemented_for("directed")@nx._dispatchabledef bridges(G, root=None): """Generate all bridges in a graph.
A *bridge* in a graph is an edge whose removal causes the number of connected components of the graph to increase. Equivalently, a bridge is an edge that does not belong to any cycle. Bridges are also known as cut-edges, isthmuses, or cut arcs.
Parameters ---------- G : undirected graph
root : node (optional) A node in the graph `G`. If specified, only the bridges in the connected component containing this node will be returned.
Yields ------ e : edge An edge in the graph whose removal disconnects the graph (or causes the number of connected components to increase).
Raises ------ NodeNotFound If `root` is not in the graph `G`.
NetworkXNotImplemented If `G` is a directed graph.
Examples -------- The barbell graph with parameter zero has a single bridge:
>>> G = nx.barbell_graph(10, 0) >>> list(nx.bridges(G)) [(9, 10)]
Notes ----- This is an implementation of the algorithm described in [1]_. An edge is a bridge if and only if it is not contained in any chain. Chains are found using the :func:`networkx.chain_decomposition` function.
The algorithm described in [1]_ requires a simple graph. If the provided graph is a multigraph, we convert it to a simple graph and verify that any bridges discovered by the chain decomposition algorithm are not multi-edges.
Ignoring polylogarithmic factors, the worst-case time complexity is the same as the :func:`networkx.chain_decomposition` function, $O(m + n)$, where $n$ is the number of nodes in the graph and $m$ is the number of edges.
References ---------- .. [1] https://en.wikipedia.org/wiki/Bridge_%28graph_theory%29#Bridge-Finding_with_Chain_Decompositions """ multigraph = G.is_multigraph() H = nx.Graph(G) if multigraph else G chains = nx.chain_decomposition(H, root=root) chain_edges = set(chain.from_iterable(chains)) if root is not None: H = H.subgraph(nx.node_connected_component(H, root)).copy() for u, v in H.edges(): if (u, v) not in chain_edges and (v, u) not in chain_edges: if multigraph and len(G[u][v]) > 1: continue yield u, v
@not_implemented_for("directed")@nx._dispatchabledef has_bridges(G, root=None): """Decide whether a graph has any bridges.
A *bridge* in a graph is an edge whose removal causes the number of connected components of the graph to increase.
Parameters ---------- G : undirected graph
root : node (optional) A node in the graph `G`. If specified, only the bridges in the connected component containing this node will be considered.
Returns ------- bool Whether the graph (or the connected component containing `root`) has any bridges.
Raises ------ NodeNotFound If `root` is not in the graph `G`.
NetworkXNotImplemented If `G` is a directed graph.
Examples -------- The barbell graph with parameter zero has a single bridge::
>>> G = nx.barbell_graph(10, 0) >>> nx.has_bridges(G) True
On the other hand, the cycle graph has no bridges::
>>> G = nx.cycle_graph(5) >>> nx.has_bridges(G) False
Notes ----- This implementation uses the :func:`networkx.bridges` function, so it shares its worst-case time complexity, $O(m + n)$, ignoring polylogarithmic factors, where $n$ is the number of nodes in the graph and $m$ is the number of edges.
""" try: next(bridges(G, root=root)) except StopIteration: return False else: return True
@not_implemented_for("multigraph")@not_implemented_for("directed")@nx._dispatchable(edge_attrs="weight")def local_bridges(G, with_span=True, weight=None): """Iterate over local bridges of `G` optionally computing the span
A *local bridge* is an edge whose endpoints have no common neighbors. That is, the edge is not part of a triangle in the graph.
The *span* of a *local bridge* is the shortest path length between the endpoints if the local bridge is removed.
Parameters ---------- G : undirected graph
with_span : bool If True, yield a 3-tuple `(u, v, span)`
weight : function, string or None (default: None) If function, used to compute edge weights for the span. If string, the edge data attribute used in calculating span. If None, all edges have weight 1.
Yields ------ e : edge The local bridges as an edge 2-tuple of nodes `(u, v)` or as a 3-tuple `(u, v, span)` when `with_span is True`.
Raises ------ NetworkXNotImplemented If `G` is a directed graph or multigraph.
Examples -------- A cycle graph has every edge a local bridge with span N-1.
>>> G = nx.cycle_graph(9) >>> (0, 8, 8) in set(nx.local_bridges(G)) True """ if with_span is not True: for u, v in G.edges: if not (set(G[u]) & set(G[v])): yield u, v else: wt = nx.weighted._weight_function(G, weight) for u, v in G.edges: if not (set(G[u]) & set(G[v])): enodes = {u, v}
def hide_edge(n, nbr, d): if n not in enodes or nbr not in enodes: return wt(n, nbr, d) return None
try: span = nx.shortest_path_length(G, u, v, weight=hide_edge) yield u, v, span except nx.NetworkXNoPath: yield u, v, float("inf")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164"""Routines to calculate the broadcast time of certain graphs.
Broadcasting is an information dissemination problem in which a node in a graph,called the originator, must distribute a message to all other nodes by placinga series of calls along the edges of the graph. Once informed, other nodes aidthe originator in distributing the message.
The broadcasting must be completed as quickly as possible subject to thefollowing constraints:- Each call requires one unit of time.- A node can only participate in one call per unit of time.- Each call only involves two adjacent nodes: a sender and a receiver."""
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = [ "tree_broadcast_center", "tree_broadcast_time",]
def _get_max_broadcast_value(G, U, v, values): adj = sorted(set(G.neighbors(v)) & U, key=values.get, reverse=True) return max(values[u] + i for i, u in enumerate(adj, start=1))
def _get_broadcast_centers(G, v, values, target): adj = sorted(G.neighbors(v), key=values.get, reverse=True) j = next(i for i, u in enumerate(adj, start=1) if values[u] + i == target) return set([v] + adj[:j])
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchabledef tree_broadcast_center(G): """Return the broadcast center of a tree.
The broadcast center of a graph `G` denotes the set of nodes having minimum broadcast time [1]_. This function implements a linear algorithm for determining the broadcast center of a tree with ``n`` nodes. As a by-product, it also determines the broadcast time from the broadcast center.
Parameters ---------- G : Graph The graph should be an undirected tree.
Returns ------- b_T, b_C : (int, set) tuple Minimum broadcast time of the broadcast center in `G`, set of nodes in the broadcast center.
Raises ------ NetworkXNotImplemented If `G` is directed or is a multigraph.
NotATree If `G` is not a tree.
References ---------- .. [1] Slater, P.J., Cockayne, E.J., Hedetniemi, S.T, Information dissemination in trees. SIAM J.Comput. 10(4), 692–701 (1981) """ # Assert that the graph G is a tree if not nx.is_tree(G): raise nx.NotATree("G is not a tree") # step 0 if (n := len(G)) < 3: return n - 1, set(G)
# step 1 U = {node for node, deg in G.degree if deg == 1} values = {n: 0 for n in U} T = G.copy() T.remove_nodes_from(U)
# step 2 W = {node for node, deg in T.degree if deg == 1} values.update((w, G.degree[w] - 1) for w in W)
# step 3 while len(T) >= 2: # step 4 w = min(W, key=values.get) v = next(T.neighbors(w))
# step 5 U.add(w) W.remove(w) T.remove_node(w)
# step 6 if T.degree(v) == 1: # update t(v) values.update({v: _get_max_broadcast_value(G, U, v, values)}) W.add(v)
# step 7 v = nx.utils.arbitrary_element(T) b_T = _get_max_broadcast_value(G, U, v, values) return b_T, _get_broadcast_centers(G, v, values, b_T)
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchabledef tree_broadcast_time(G, node=None): """Return the minimum broadcast time of a (node in a) tree.
The minimum broadcast time of a node is defined as the minimum amount of time required to complete broadcasting starting from that node. The broadcast time of a graph is the maximum over all nodes of the minimum broadcast time from that node [1]_. This function returns the minimum broadcast time of `node`. If `node` is `None`, the broadcast time for the graph is returned.
Parameters ---------- G : Graph The graph should be an undirected tree.
node : node, optional (default=None) Starting node for the broadcasting. If `None`, the algorithm returns the broadcast time of the graph instead.
Returns ------- int Minimum broadcast time of `node` in `G`, or broadcast time of `G` if no node is provided.
Raises ------ NetworkXNotImplemented If `G` is directed or is a multigraph.
NodeNotFound If `node` is not a node in `G`.
NotATree If `G` is not a tree.
References ---------- .. [1] Harutyunyan, H. A. and Li, Z. "A Simple Construction of Broadcast Graphs." In Computing and Combinatorics. COCOON 2019 (Ed. D. Z. Du and C. Tian.) Springer, pp. 240-253, 2019. """ if node is not None and node not in G: err = f"node {node} not in G" raise nx.NodeNotFound(err) b_T, b_C = tree_broadcast_center(G) if node is None: return b_T + sum(1 for _ in nx.bfs_layers(G, b_C)) - 1 return b_T + next( d for d, layer in enumerate(nx.bfs_layers(G, b_C)) if node in layer )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Functions for finding chains in a graph."""
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = ["chain_decomposition"]
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchabledef chain_decomposition(G, root=None): """Returns the chain decomposition of a graph.
The *chain decomposition* of a graph with respect a depth-first search tree is a set of cycles or paths derived from the set of fundamental cycles of the tree in the following manner. Consider each fundamental cycle with respect to the given tree, represented as a list of edges beginning with the nontree edge oriented away from the root of the tree. For each fundamental cycle, if it overlaps with any previous fundamental cycle, just take the initial non-overlapping segment, which is a path instead of a cycle. Each cycle or path is called a *chain*. For more information, see [1]_.
Parameters ---------- G : undirected graph
root : node (optional) A node in the graph `G`. If specified, only the chain decomposition for the connected component containing this node will be returned. This node indicates the root of the depth-first search tree.
Yields ------ chain : list A list of edges representing a chain. There is no guarantee on the orientation of the edges in each chain (for example, if a chain includes the edge joining nodes 1 and 2, the chain may include either (1, 2) or (2, 1)).
Raises ------ NodeNotFound If `root` is not in the graph `G`.
Examples -------- >>> G = nx.Graph([(0, 1), (1, 4), (3, 4), (3, 5), (4, 5)]) >>> list(nx.chain_decomposition(G)) [[(4, 5), (5, 3), (3, 4)]]
Notes ----- The worst-case running time of this implementation is linear in the number of nodes and number of edges [1]_.
References ---------- .. [1] Jens M. Schmidt (2013). "A simple test on 2-vertex- and 2-edge-connectivity." *Information Processing Letters*, 113, 241–244. Elsevier. <https://doi.org/10.1016/j.ipl.2013.01.016>
"""
def _dfs_cycle_forest(G, root=None): """Builds a directed graph composed of cycles from the given graph.
`G` is an undirected simple graph. `root` is a node in the graph from which the depth-first search is started.
This function returns both the depth-first search cycle graph (as a :class:`~networkx.DiGraph`) and the list of nodes in depth-first preorder. The depth-first search cycle graph is a directed graph whose edges are the edges of `G` oriented toward the root if the edge is a tree edge and away from the root if the edge is a non-tree edge. If `root` is not specified, this performs a depth-first search on each connected component of `G` and returns a directed forest instead.
If `root` is not in the graph, this raises :exc:`KeyError`.
""" # Create a directed graph from the depth-first search tree with # root node `root` in which tree edges are directed toward the # root and nontree edges are directed away from the root. For # each node with an incident nontree edge, this creates a # directed cycle starting with the nontree edge and returning to # that node. # # The `parent` node attribute stores the parent of each node in # the DFS tree. The `nontree` edge attribute indicates whether # the edge is a tree edge or a nontree edge. # # We also store the order of the nodes found in the depth-first # search in the `nodes` list. H = nx.DiGraph() nodes = [] for u, v, d in nx.dfs_labeled_edges(G, source=root): if d == "forward": # `dfs_labeled_edges()` yields (root, root, 'forward') # if it is beginning the search on a new connected # component. if u == v: H.add_node(v, parent=None) nodes.append(v) else: H.add_node(v, parent=u) H.add_edge(v, u, nontree=False) nodes.append(v) # `dfs_labeled_edges` considers nontree edges in both # orientations, so we need to not add the edge if it its # other orientation has been added. elif d == "nontree" and v not in H[u]: H.add_edge(v, u, nontree=True) else: # Do nothing on 'reverse' edges; we only care about # forward and nontree edges. pass return H, nodes
def _build_chain(G, u, v, visited): """Generate the chain starting from the given nontree edge.
`G` is a DFS cycle graph as constructed by :func:`_dfs_cycle_graph`. The edge (`u`, `v`) is a nontree edge that begins a chain. `visited` is a set representing the nodes in `G` that have already been visited.
This function yields the edges in an initial segment of the fundamental cycle of `G` starting with the nontree edge (`u`, `v`) that includes all the edges up until the first node that appears in `visited`. The tree edges are given by the 'parent' node attribute. The `visited` set is updated to add each node in an edge yielded by this function.
""" while v not in visited: yield u, v visited.add(v) u, v = v, G.nodes[v]["parent"] yield u, v
# Check if the root is in the graph G. If not, raise NodeNotFound if root is not None and root not in G: raise nx.NodeNotFound(f"Root node {root} is not in graph")
# Create a directed version of H that has the DFS edges directed # toward the root and the nontree edges directed away from the root # (in each connected component). H, nodes = _dfs_cycle_forest(G, root)
# Visit the nodes again in DFS order. For each node, and for each # nontree edge leaving that node, compute the fundamental cycle for # that nontree edge starting with that edge. If the fundamental # cycle overlaps with any visited nodes, just take the prefix of the # cycle up to the point of visited nodes. # # We repeat this process for each connected component (implicitly, # since `nodes` already has a list of the nodes grouped by connected # component). visited = set() for u in nodes: visited.add(u) # For each nontree edge going out of node u... edges = ((u, v) for u, v, d in H.out_edges(u, data="nontree") if d) for u, v in edges: # Create the cycle or cycle prefix starting with the # nontree edge. chain = list(_build_chain(H, u, v, visited)) yield chain123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443"""Algorithms for chordal graphs.
A graph is chordal if every cycle of length at least 4 has a chord(an edge joining two nodes not adjacent in the cycle).https://en.wikipedia.org/wiki/Chordal_graph"""
import sys
import networkx as nxfrom networkx.algorithms.components import connected_componentsfrom networkx.utils import arbitrary_element, not_implemented_for
__all__ = [ "is_chordal", "find_induced_nodes", "chordal_graph_cliques", "chordal_graph_treewidth", "NetworkXTreewidthBoundExceeded", "complete_to_chordal_graph",]
class NetworkXTreewidthBoundExceeded(nx.NetworkXException): """Exception raised when a treewidth bound has been provided and it has been exceeded"""
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchabledef is_chordal(G): """Checks whether G is a chordal graph.
A graph is chordal if every cycle of length at least 4 has a chord (an edge joining two nodes not adjacent in the cycle).
Parameters ---------- G : graph A NetworkX graph.
Returns ------- chordal : bool True if G is a chordal graph and False otherwise.
Raises ------ NetworkXNotImplemented The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
Examples -------- >>> e = [ ... (1, 2), ... (1, 3), ... (2, 3), ... (2, 4), ... (3, 4), ... (3, 5), ... (3, 6), ... (4, 5), ... (4, 6), ... (5, 6), ... ] >>> G = nx.Graph(e) >>> nx.is_chordal(G) True
Notes ----- The routine tries to go through every node following maximum cardinality search. It returns False when it finds that the separator for any node is not a clique. Based on the algorithms in [1]_.
Self loops are ignored.
References ---------- .. [1] R. E. Tarjan and M. Yannakakis, Simple linear-time algorithms to test chordality of graphs, test acyclicity of hypergraphs, and selectively reduce acyclic hypergraphs, SIAM J. Comput., 13 (1984), pp. 566–579. """ if len(G.nodes) <= 3: return True return len(_find_chordality_breaker(G)) == 0
@nx._dispatchabledef find_induced_nodes(G, s, t, treewidth_bound=sys.maxsize): """Returns the set of induced nodes in the path from s to t.
Parameters ---------- G : graph A chordal NetworkX graph s : node Source node to look for induced nodes t : node Destination node to look for induced nodes treewidth_bound: float Maximum treewidth acceptable for the graph H. The search for induced nodes will end as soon as the treewidth_bound is exceeded.
Returns ------- induced_nodes : Set of nodes The set of induced nodes in the path from s to t in G
Raises ------ NetworkXError The algorithm does not support DiGraph, MultiGraph and MultiDiGraph. If the input graph is an instance of one of these classes, a :exc:`NetworkXError` is raised. The algorithm can only be applied to chordal graphs. If the input graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
Examples -------- >>> G = nx.Graph() >>> G = nx.generators.classic.path_graph(10) >>> induced_nodes = nx.find_induced_nodes(G, 1, 9, 2) >>> sorted(induced_nodes) [1, 2, 3, 4, 5, 6, 7, 8, 9]
Notes ----- G must be a chordal graph and (s,t) an edge that is not in G.
If a treewidth_bound is provided, the search for induced nodes will end as soon as the treewidth_bound is exceeded.
The algorithm is inspired by Algorithm 4 in [1]_. A formal definition of induced node can also be found on that reference.
Self Loops are ignored
References ---------- .. [1] Learning Bounded Treewidth Bayesian Networks. Gal Elidan, Stephen Gould; JMLR, 9(Dec):2699--2731, 2008. http://jmlr.csail.mit.edu/papers/volume9/elidan08a/elidan08a.pdf """ if not is_chordal(G): raise nx.NetworkXError("Input graph is not chordal.")
H = nx.Graph(G) H.add_edge(s, t) induced_nodes = set() triplet = _find_chordality_breaker(H, s, treewidth_bound) while triplet: (u, v, w) = triplet induced_nodes.update(triplet) for n in triplet: if n != s: H.add_edge(s, n) triplet = _find_chordality_breaker(H, s, treewidth_bound) if induced_nodes: # Add t and the second node in the induced path from s to t. induced_nodes.add(t) for u in G[s]: if len(induced_nodes & set(G[u])) == 2: induced_nodes.add(u) break return induced_nodes
@nx._dispatchabledef chordal_graph_cliques(G): """Returns all maximal cliques of a chordal graph.
The algorithm breaks the graph in connected components and performs a maximum cardinality search in each component to get the cliques.
Parameters ---------- G : graph A NetworkX graph
Yields ------ frozenset of nodes Maximal cliques, each of which is a frozenset of nodes in `G`. The order of cliques is arbitrary.
Raises ------ NetworkXError The algorithm does not support DiGraph, MultiGraph and MultiDiGraph. The algorithm can only be applied to chordal graphs. If the input graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
Examples -------- >>> e = [ ... (1, 2), ... (1, 3), ... (2, 3), ... (2, 4), ... (3, 4), ... (3, 5), ... (3, 6), ... (4, 5), ... (4, 6), ... (5, 6), ... (7, 8), ... ] >>> G = nx.Graph(e) >>> G.add_node(9) >>> cliques = [c for c in chordal_graph_cliques(G)] >>> cliques[0] frozenset({1, 2, 3}) """ for C in (G.subgraph(c).copy() for c in connected_components(G)): if C.number_of_nodes() == 1: if nx.number_of_selfloops(C) > 0: raise nx.NetworkXError("Input graph is not chordal.") yield frozenset(C.nodes()) else: unnumbered = set(C.nodes()) v = arbitrary_element(C) unnumbered.remove(v) numbered = {v} clique_wanna_be = {v} while unnumbered: v = _max_cardinality_node(C, unnumbered, numbered) unnumbered.remove(v) numbered.add(v) new_clique_wanna_be = set(C.neighbors(v)) & numbered sg = C.subgraph(clique_wanna_be) if _is_complete_graph(sg): new_clique_wanna_be.add(v) if not new_clique_wanna_be >= clique_wanna_be: yield frozenset(clique_wanna_be) clique_wanna_be = new_clique_wanna_be else: raise nx.NetworkXError("Input graph is not chordal.") yield frozenset(clique_wanna_be)
@nx._dispatchabledef chordal_graph_treewidth(G): """Returns the treewidth of the chordal graph G.
Parameters ---------- G : graph A NetworkX graph
Returns ------- treewidth : int The size of the largest clique in the graph minus one.
Raises ------ NetworkXError The algorithm does not support DiGraph, MultiGraph and MultiDiGraph. The algorithm can only be applied to chordal graphs. If the input graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
Examples -------- >>> e = [ ... (1, 2), ... (1, 3), ... (2, 3), ... (2, 4), ... (3, 4), ... (3, 5), ... (3, 6), ... (4, 5), ... (4, 6), ... (5, 6), ... (7, 8), ... ] >>> G = nx.Graph(e) >>> G.add_node(9) >>> nx.chordal_graph_treewidth(G) 3
References ---------- .. [1] https://en.wikipedia.org/wiki/Tree_decomposition#Treewidth """ if not is_chordal(G): raise nx.NetworkXError("Input graph is not chordal.")
max_clique = -1 for clique in nx.chordal_graph_cliques(G): max_clique = max(max_clique, len(clique)) return max_clique - 1
def _is_complete_graph(G): """Returns True if G is a complete graph.""" if nx.number_of_selfloops(G) > 0: raise nx.NetworkXError("Self loop found in _is_complete_graph()") n = G.number_of_nodes() if n < 2: return True e = G.number_of_edges() max_edges = (n * (n - 1)) / 2 return e == max_edges
def _find_missing_edge(G): """Given a non-complete graph G, returns a missing edge.""" nodes = set(G) for u in G: missing = nodes - set(list(G[u].keys()) + [u]) if missing: return (u, missing.pop())
def _max_cardinality_node(G, choices, wanna_connect): """Returns a the node in choices that has more connections in G to nodes in wanna_connect. """ max_number = -1 for x in choices: number = len([y for y in G[x] if y in wanna_connect]) if number > max_number: max_number = number max_cardinality_node = x return max_cardinality_node
def _find_chordality_breaker(G, s=None, treewidth_bound=sys.maxsize): """Given a graph G, starts a max cardinality search (starting from s if s is given and from an arbitrary node otherwise) trying to find a non-chordal cycle.
If it does find one, it returns (u,v,w) where u,v,w are the three nodes that together with s are involved in the cycle.
It ignores any self loops. """ if len(G) == 0: raise nx.NetworkXPointlessConcept("Graph has no nodes.") unnumbered = set(G) if s is None: s = arbitrary_element(G) unnumbered.remove(s) numbered = {s} current_treewidth = -1 while unnumbered: # and current_treewidth <= treewidth_bound: v = _max_cardinality_node(G, unnumbered, numbered) unnumbered.remove(v) numbered.add(v) clique_wanna_be = set(G[v]) & numbered sg = G.subgraph(clique_wanna_be) if _is_complete_graph(sg): # The graph seems to be chordal by now. We update the treewidth current_treewidth = max(current_treewidth, len(clique_wanna_be)) if current_treewidth > treewidth_bound: raise nx.NetworkXTreewidthBoundExceeded( f"treewidth_bound exceeded: {current_treewidth}" ) else: # sg is not a clique, # look for an edge that is not included in sg (u, w) = _find_missing_edge(sg) return (u, v, w) return ()
@not_implemented_for("directed")@nx._dispatchable(returns_graph=True)def complete_to_chordal_graph(G): """Return a copy of G completed to a chordal graph
Adds edges to a copy of G to create a chordal graph. A graph G=(V,E) is called chordal if for each cycle with length bigger than 3, there exist two non-adjacent nodes connected by an edge (called a chord).
Parameters ---------- G : NetworkX graph Undirected graph
Returns ------- H : NetworkX graph The chordal enhancement of G alpha : Dictionary The elimination ordering of nodes of G
Notes ----- There are different approaches to calculate the chordal enhancement of a graph. The algorithm used here is called MCS-M and gives at least minimal (local) triangulation of graph. Note that this triangulation is not necessarily a global minimum.
https://en.wikipedia.org/wiki/Chordal_graph
References ---------- .. [1] Berry, Anne & Blair, Jean & Heggernes, Pinar & Peyton, Barry. (2004) Maximum Cardinality Search for Computing Minimal Triangulations of Graphs. Algorithmica. 39. 287-298. 10.1007/s00453-004-1084-3.
Examples -------- >>> from networkx.algorithms.chordal import complete_to_chordal_graph >>> G = nx.wheel_graph(10) >>> H, alpha = complete_to_chordal_graph(G) """ H = G.copy() alpha = {node: 0 for node in H} if nx.is_chordal(H): return H, alpha chords = set() weight = {node: 0 for node in H.nodes()} unnumbered_nodes = list(H.nodes()) for i in range(len(H.nodes()), 0, -1): # get the node in unnumbered_nodes with the maximum weight z = max(unnumbered_nodes, key=lambda node: weight[node]) unnumbered_nodes.remove(z) alpha[z] = i update_nodes = [] for y in unnumbered_nodes: if G.has_edge(y, z): update_nodes.append(y) else: # y_weight will be bigger than node weights between y and z y_weight = weight[y] lower_nodes = [ node for node in unnumbered_nodes if weight[node] < y_weight ] if nx.has_path(H.subgraph(lower_nodes + [z, y]), y, z): update_nodes.append(y) chords.add((z, y)) # during calculation of paths the weights should not be updated for node in update_nodes: weight[node] += 1 H.add_edges_from(chords) return H, alpha123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818"""Functions for finding and manipulating cliques.
Finding the largest clique in a graph is NP-complete problem, so most ofthese algorithms have an exponential running time; for more information,see the Wikipedia article on the clique problem [1]_.
.. [1] clique problem:: https://en.wikipedia.org/wiki/Clique_problem
"""
from collections import Counter, defaultdict, dequefrom itertools import chain, combinations, islice
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = [ "find_cliques", "find_cliques_recursive", "make_max_clique_graph", "make_clique_bipartite", "node_clique_number", "number_of_cliques", "enumerate_all_cliques", "max_weight_clique",]
@not_implemented_for("directed")@nx._dispatchabledef enumerate_all_cliques(G): """Returns all cliques in an undirected graph.
This function returns an iterator over cliques, each of which is a list of nodes. The iteration is ordered by cardinality of the cliques: first all cliques of size one, then all cliques of size two, etc.
Parameters ---------- G : NetworkX graph An undirected graph.
Returns ------- iterator An iterator over cliques, each of which is a list of nodes in `G`. The cliques are ordered according to size.
Notes ----- To obtain a list of all cliques, use `list(enumerate_all_cliques(G))`. However, be aware that in the worst-case, the length of this list can be exponential in the number of nodes in the graph (for example, when the graph is the complete graph). This function avoids storing all cliques in memory by only keeping current candidate node lists in memory during its search.
The implementation is adapted from the algorithm by Zhang, et al. (2005) [1]_ to output all cliques discovered.
This algorithm ignores self-loops and parallel edges, since cliques are not conventionally defined with such edges.
References ---------- .. [1] Yun Zhang, Abu-Khzam, F.N., Baldwin, N.E., Chesler, E.J., Langston, M.A., Samatova, N.F., "Genome-Scale Computational Approaches to Memory-Intensive Applications in Systems Biology". *Supercomputing*, 2005. Proceedings of the ACM/IEEE SC 2005 Conference, pp. 12, 12--18 Nov. 2005. <https://doi.org/10.1109/SC.2005.29>.
""" index = {} nbrs = {} for u in G: index[u] = len(index) # Neighbors of u that appear after u in the iteration order of G. nbrs[u] = {v for v in G[u] if v not in index}
queue = deque(([u], sorted(nbrs[u], key=index.__getitem__)) for u in G) # Loop invariants: # 1. len(base) is nondecreasing. # 2. (base + cnbrs) is sorted with respect to the iteration order of G. # 3. cnbrs is a set of common neighbors of nodes in base. while queue: base, cnbrs = map(list, queue.popleft()) yield base for i, u in enumerate(cnbrs): # Use generators to reduce memory consumption. queue.append( ( chain(base, [u]), filter(nbrs[u].__contains__, islice(cnbrs, i + 1, None)), ) )
@not_implemented_for("directed")@nx._dispatchabledef find_cliques(G, nodes=None): """Returns all maximal cliques in an undirected graph.
For each node *n*, a *maximal clique for n* is a largest complete subgraph containing *n*. The largest maximal clique is sometimes called the *maximum clique*.
This function returns an iterator over cliques, each of which is a list of nodes. It is an iterative implementation, so should not suffer from recursion depth issues.
This function accepts a list of `nodes` and only the maximal cliques containing all of these `nodes` are returned. It can considerably speed up the running time if some specific cliques are desired.
Parameters ---------- G : NetworkX graph An undirected graph.
nodes : list, optional (default=None) If provided, only yield *maximal cliques* containing all nodes in `nodes`. If `nodes` isn't a clique itself, a ValueError is raised.
Returns ------- iterator An iterator over maximal cliques, each of which is a list of nodes in `G`. If `nodes` is provided, only the maximal cliques containing all the nodes in `nodes` are returned. The order of cliques is arbitrary.
Raises ------ ValueError If `nodes` is not a clique.
Examples -------- >>> from pprint import pprint # For nice dict formatting >>> G = nx.karate_club_graph() >>> sum(1 for c in nx.find_cliques(G)) # The number of maximal cliques in G 36 >>> max(nx.find_cliques(G), key=len) # The largest maximal clique in G [0, 1, 2, 3, 13]
The size of the largest maximal clique is known as the *clique number* of the graph, which can be found directly with:
>>> max(len(c) for c in nx.find_cliques(G)) 5
One can also compute the number of maximal cliques in `G` that contain a given node. The following produces a dictionary keyed by node whose values are the number of maximal cliques in `G` that contain the node:
>>> from collections import Counter >>> from itertools import chain >>> counts = Counter(chain.from_iterable(nx.find_cliques(G))) >>> pprint(dict(counts)) {0: 13, 1: 6, 2: 7, 3: 3, 4: 2, 5: 3, 6: 3, 7: 1, 8: 3, 9: 2, 10: 2, 11: 1, 12: 1, 13: 2, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 2, 20: 1, 21: 1, 22: 1, 23: 3, 24: 2, 25: 2, 26: 1, 27: 3, 28: 2, 29: 2, 30: 2, 31: 4, 32: 9, 33: 14}
Or, similarly, the maximal cliques in `G` that contain a given node. For example, the 4 maximal cliques that contain node 31:
>>> [c for c in nx.find_cliques(G) if 31 in c] [[0, 31], [33, 32, 31], [33, 28, 31], [24, 25, 31]]
See Also -------- find_cliques_recursive A recursive version of the same algorithm.
Notes ----- To obtain a list of all maximal cliques, use `list(find_cliques(G))`. However, be aware that in the worst-case, the length of this list can be exponential in the number of nodes in the graph. This function avoids storing all cliques in memory by only keeping current candidate node lists in memory during its search.
This implementation is based on the algorithm published by Bron and Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi (2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. It essentially unrolls the recursion used in the references to avoid issues of recursion stack depth (for a recursive implementation, see :func:`find_cliques_recursive`).
This algorithm ignores self-loops and parallel edges, since cliques are not conventionally defined with such edges.
References ---------- .. [1] Bron, C. and Kerbosch, J. "Algorithm 457: finding all cliques of an undirected graph". *Communications of the ACM* 16, 9 (Sep. 1973), 575--577. <http://portal.acm.org/citation.cfm?doid=362342.362367>
.. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi, "The worst-case time complexity for generating all maximal cliques and computational experiments", *Theoretical Computer Science*, Volume 363, Issue 1, Computing and Combinatorics, 10th Annual International Conference on Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42 <https://doi.org/10.1016/j.tcs.2006.06.015>
.. [3] F. Cazals, C. Karande, "A note on the problem of reporting maximal cliques", *Theoretical Computer Science*, Volume 407, Issues 1--3, 6 November 2008, Pages 564--568, <https://doi.org/10.1016/j.tcs.2008.05.010>
""" if len(G) == 0: return
adj = {u: {v for v in G[u] if v != u} for u in G}
# Initialize Q with the given nodes and subg, cand with their nbrs Q = nodes[:] if nodes is not None else [] cand = set(G) for node in Q: if node not in cand: raise ValueError(f"The given `nodes` {nodes} do not form a clique") cand &= adj[node]
if not cand: yield Q[:] return
subg = cand.copy() stack = [] Q.append(None)
u = max(subg, key=lambda u: len(cand & adj[u])) ext_u = cand - adj[u]
try: while True: if ext_u: q = ext_u.pop() cand.remove(q) Q[-1] = q adj_q = adj[q] subg_q = subg & adj_q if not subg_q: yield Q[:] else: cand_q = cand & adj_q if cand_q: stack.append((subg, cand, ext_u)) Q.append(None) subg = subg_q cand = cand_q u = max(subg, key=lambda u: len(cand & adj[u])) ext_u = cand - adj[u] else: Q.pop() subg, cand, ext_u = stack.pop() except IndexError: pass
@not_implemented_for("directed")@nx._dispatchabledef find_cliques_recursive(G, nodes=None): """Returns all maximal cliques in a graph.
For each node *v*, a *maximal clique for v* is a largest complete subgraph containing *v*. The largest maximal clique is sometimes called the *maximum clique*.
This function returns an iterator over cliques, each of which is a list of nodes. It is a recursive implementation, so may suffer from recursion depth issues, but is included for pedagogical reasons. For a non-recursive implementation, see :func:`find_cliques`.
This function accepts a list of `nodes` and only the maximal cliques containing all of these `nodes` are returned. It can considerably speed up the running time if some specific cliques are desired.
Parameters ---------- G : NetworkX graph An undirected graph.
nodes : list, optional (default=None) If provided, only yield *maximal cliques* containing all nodes in `nodes`. If `nodes` isn't a clique itself, a ValueError is raised.
Returns ------- iterator An iterator over maximal cliques, each of which is a list of nodes in `G`. If `nodes` is provided, only the maximal cliques containing all the nodes in `nodes` are yielded. The order of cliques is arbitrary.
Raises ------ NetworkXNotImplemented If `G` is directed.
ValueError If `nodes` is not a clique.
See Also -------- find_cliques An iterative version of the same algorithm. See docstring for examples.
Notes ----- To obtain a list of all maximal cliques, use `list(find_cliques_recursive(G))`. However, be aware that in the worst-case, the length of this list can be exponential in the number of nodes in the graph. This function avoids storing all cliques in memory by only keeping current candidate node lists in memory during its search.
This implementation is based on the algorithm published by Bron and Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi (2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. For a non-recursive implementation, see :func:`find_cliques`.
This algorithm ignores self-loops and parallel edges, since cliques are not conventionally defined with such edges.
References ---------- .. [1] Bron, C. and Kerbosch, J. "Algorithm 457: finding all cliques of an undirected graph". *Communications of the ACM* 16, 9 (Sep. 1973), 575--577. <http://portal.acm.org/citation.cfm?doid=362342.362367>
.. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi, "The worst-case time complexity for generating all maximal cliques and computational experiments", *Theoretical Computer Science*, Volume 363, Issue 1, Computing and Combinatorics, 10th Annual International Conference on Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42 <https://doi.org/10.1016/j.tcs.2006.06.015>
.. [3] F. Cazals, C. Karande, "A note on the problem of reporting maximal cliques", *Theoretical Computer Science*, Volume 407, Issues 1--3, 6 November 2008, Pages 564--568, <https://doi.org/10.1016/j.tcs.2008.05.010>
""" if len(G) == 0: return iter([])
adj = {u: {v for v in G[u] if v != u} for u in G}
# Initialize Q with the given nodes and subg, cand with their nbrs Q = nodes[:] if nodes is not None else [] cand_init = set(G) for node in Q: if node not in cand_init: raise ValueError(f"The given `nodes` {nodes} do not form a clique") cand_init &= adj[node]
if not cand_init: return iter([Q])
subg_init = cand_init.copy()
def expand(subg, cand): u = max(subg, key=lambda u: len(cand & adj[u])) for q in cand - adj[u]: cand.remove(q) Q.append(q) adj_q = adj[q] subg_q = subg & adj_q if not subg_q: yield Q[:] else: cand_q = cand & adj_q if cand_q: yield from expand(subg_q, cand_q) Q.pop()
return expand(subg_init, cand_init)
@nx._dispatchable(returns_graph=True)def make_max_clique_graph(G, create_using=None): """Returns the maximal clique graph of the given graph.
The nodes of the maximal clique graph of `G` are the cliques of `G` and an edge joins two cliques if the cliques are not disjoint.
Parameters ---------- G : NetworkX graph
create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated.
Returns ------- NetworkX graph A graph whose nodes are the cliques of `G` and whose edges join two cliques if they are not disjoint.
Notes ----- This function behaves like the following code::
import networkx as nx
G = nx.make_clique_bipartite(G) cliques = [v for v in G.nodes() if G.nodes[v]["bipartite"] == 0] G = nx.bipartite.projected_graph(G, cliques) G = nx.relabel_nodes(G, {-v: v - 1 for v in G})
It should be faster, though, since it skips all the intermediate steps.
""" if create_using is None: B = G.__class__() else: B = nx.empty_graph(0, create_using) cliques = list(enumerate(set(c) for c in find_cliques(G))) # Add a numbered node for each clique. B.add_nodes_from(i for i, c in cliques) # Join cliques by an edge if they share a node. clique_pairs = combinations(cliques, 2) B.add_edges_from((i, j) for (i, c1), (j, c2) in clique_pairs if c1 & c2) return B
@nx._dispatchable(returns_graph=True)def make_clique_bipartite(G, fpos=None, create_using=None, name=None): """Returns the bipartite clique graph corresponding to `G`.
In the returned bipartite graph, the "bottom" nodes are the nodes of `G` and the "top" nodes represent the maximal cliques of `G`. There is an edge from node *v* to clique *C* in the returned graph if and only if *v* is an element of *C*.
Parameters ---------- G : NetworkX graph An undirected graph.
fpos : bool If True or not None, the returned graph will have an additional attribute, `pos`, a dictionary mapping node to position in the Euclidean plane.
create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated.
Returns ------- NetworkX graph A bipartite graph whose "bottom" set is the nodes of the graph `G`, whose "top" set is the cliques of `G`, and whose edges join nodes of `G` to the cliques that contain them.
The nodes of the graph `G` have the node attribute 'bipartite' set to 1 and the nodes representing cliques have the node attribute 'bipartite' set to 0, as is the convention for bipartite graphs in NetworkX.
""" B = nx.empty_graph(0, create_using) B.clear() # The "bottom" nodes in the bipartite graph are the nodes of the # original graph, G. B.add_nodes_from(G, bipartite=1) for i, cl in enumerate(find_cliques(G)): # The "top" nodes in the bipartite graph are the cliques. These # nodes get negative numbers as labels. name = -i - 1 B.add_node(name, bipartite=0) B.add_edges_from((v, name) for v in cl) return B
@nx._dispatchabledef node_clique_number(G, nodes=None, cliques=None, separate_nodes=False): """Returns the size of the largest maximal clique containing each given node.
Returns a single or list depending on input nodes. An optional list of cliques can be input if already computed.
Parameters ---------- G : NetworkX graph An undirected graph.
cliques : list, optional (default=None) A list of cliques, each of which is itself a list of nodes. If not specified, the list of all cliques will be computed using :func:`find_cliques`.
Returns ------- int or dict If `nodes` is a single node, returns the size of the largest maximal clique in `G` containing that node. Otherwise return a dict keyed by node to the size of the largest maximal clique containing that node.
See Also -------- find_cliques find_cliques yields the maximal cliques of G. It accepts a `nodes` argument which restricts consideration to maximal cliques containing all the given `nodes`. The search for the cliques is optimized for `nodes`. number_of_cliques """ if cliques is None: if nodes is not None: # Use ego_graph to decrease size of graph # check for single node if nodes in G: return max(len(c) for c in find_cliques(nx.ego_graph(G, nodes))) # handle multiple nodes return { n: max(len(c) for c in find_cliques(nx.ego_graph(G, n))) for n in nodes }
# nodes is None--find all cliques cliques = list(find_cliques(G))
# single node requested if nodes in G: return max(len(c) for c in cliques if nodes in c)
# multiple nodes requested # preprocess all nodes (faster than one at a time for even 2 nodes) size_for_n = defaultdict(int) for c in cliques: size_of_c = len(c) for n in c: if size_for_n[n] < size_of_c: size_for_n[n] = size_of_c if nodes is None: return size_for_n return {n: size_for_n[n] for n in nodes}
def number_of_cliques(G, nodes=None, cliques=None): """Return the number of maximal cliques each node is part of.
Output is a single value or dict depending on `nodes`. Optional list of cliques can be input if already computed.
Parameters ---------- G : NetworkX graph An undirected graph.
nodes : list or None, optional (default=None) A list of nodes to return the number of maximal cliques for. If `None`, return the number of maximal cliques for all nodes.
cliques : list or None, optional (default=None) A precomputed list of maximal cliques to use for the calculation.
Returns ------- int or dict If `nodes` is a single node, return the number of maximal cliques it is part of. If `nodes` is a list, return a dictionary keyed by node to the number of maximal cliques it is part of.
Raises ------ NetworkXNotImplemented If `G` is directed.
See Also -------- find_cliques node_clique_number
Examples -------- Compute the number of maximal cliques a node is part of:
>>> G = nx.complete_graph(3) >>> nx.add_cycle(G, [0, 3, 4]) >>> nx.number_of_cliques(G, nodes=0) 2 >>> nx.number_of_cliques(G, nodes=1) 1
Or, for a list of nodes:
>>> nx.number_of_cliques(G, nodes=[0, 1]) {0: 2, 1: 1}
If no explicit `nodes` are provided, all nodes are considered:
>>> nx.number_of_cliques(G) {0: 2, 1: 1, 2: 1, 3: 1, 4: 1}
The list of maximal cliques can also be precomputed:
>>> cl = list(nx.find_cliques(G)) >>> nx.number_of_cliques(G, cliques=cl) {0: 2, 1: 1, 2: 1, 3: 1, 4: 1} """ if cliques is None: cliques = find_cliques(G)
if nodes is None: nodes = list(G.nodes()) # none, get entire graph
if not isinstance(nodes, list): # check for a list v = nodes # assume it is a single value numcliq = sum(1 for c in cliques if v in c) else: numcliq = Counter(chain.from_iterable(cliques)) numcliq = {v: numcliq[v] for v in nodes} # return a dict return numcliq
class MaxWeightClique: """A class for the maximum weight clique algorithm.
This class is a helper for the `max_weight_clique` function. The class should not normally be used directly.
Parameters ---------- G : NetworkX graph The undirected graph for which a maximum weight clique is sought weight : string or None, optional (default='weight') The node attribute that holds the integer value used as a weight. If None, then each node has weight 1.
Attributes ---------- G : NetworkX graph The undirected graph for which a maximum weight clique is sought node_weights: dict The weight of each node incumbent_nodes : list The nodes of the incumbent clique (the best clique found so far) incumbent_weight: int The weight of the incumbent clique """
def __init__(self, G, weight): self.G = G self.incumbent_nodes = [] self.incumbent_weight = 0
if weight is None: self.node_weights = {v: 1 for v in G.nodes()} else: for v in G.nodes(): if weight not in G.nodes[v]: errmsg = f"Node {v!r} does not have the requested weight field." raise KeyError(errmsg) if not isinstance(G.nodes[v][weight], int): errmsg = f"The {weight!r} field of node {v!r} is not an integer." raise ValueError(errmsg) self.node_weights = {v: G.nodes[v][weight] for v in G.nodes()}
def update_incumbent_if_improved(self, C, C_weight): """Update the incumbent if the node set C has greater weight.
C is assumed to be a clique. """ if C_weight > self.incumbent_weight: self.incumbent_nodes = C[:] self.incumbent_weight = C_weight
def greedily_find_independent_set(self, P): """Greedily find an independent set of nodes from a set of nodes P.""" independent_set = [] P = P[:] while P: v = P[0] independent_set.append(v) P = [w for w in P if v != w and not self.G.has_edge(v, w)] return independent_set
def find_branching_nodes(self, P, target): """Find a set of nodes to branch on.""" residual_wt = {v: self.node_weights[v] for v in P} total_wt = 0 P = P[:] while P: independent_set = self.greedily_find_independent_set(P) min_wt_in_class = min(residual_wt[v] for v in independent_set) total_wt += min_wt_in_class if total_wt > target: break for v in independent_set: residual_wt[v] -= min_wt_in_class P = [v for v in P if residual_wt[v] != 0] return P
def expand(self, C, C_weight, P): """Look for the best clique that contains all the nodes in C and zero or more of the nodes in P, backtracking if it can be shown that no such clique has greater weight than the incumbent. """ self.update_incumbent_if_improved(C, C_weight) branching_nodes = self.find_branching_nodes(P, self.incumbent_weight - C_weight) while branching_nodes: v = branching_nodes.pop() P.remove(v) new_C = C + [v] new_C_weight = C_weight + self.node_weights[v] new_P = [w for w in P if self.G.has_edge(v, w)] self.expand(new_C, new_C_weight, new_P)
def find_max_weight_clique(self): """Find a maximum weight clique.""" # Sort nodes in reverse order of degree for speed nodes = sorted(self.G.nodes(), key=lambda v: self.G.degree(v), reverse=True) nodes = [v for v in nodes if self.node_weights[v] > 0] self.expand([], 0, nodes)
@not_implemented_for("directed")@nx._dispatchable(node_attrs="weight")def max_weight_clique(G, weight="weight"): """Find a maximum weight clique in G.
A *clique* in a graph is a set of nodes such that every two distinct nodes are adjacent. The *weight* of a clique is the sum of the weights of its nodes. A *maximum weight clique* of graph G is a clique C in G such that no clique in G has weight greater than the weight of C.
Parameters ---------- G : NetworkX graph Undirected graph weight : string or None, optional (default='weight') The node attribute that holds the integer value used as a weight. If None, then each node has weight 1.
Returns ------- clique : list the nodes of a maximum weight clique weight : int the weight of a maximum weight clique
Notes ----- The implementation is recursive, and therefore it may run into recursion depth issues if G contains a clique whose number of nodes is close to the recursion depth limit.
At each search node, the algorithm greedily constructs a weighted independent set cover of part of the graph in order to find a small set of nodes on which to branch. The algorithm is very similar to the algorithm of Tavares et al. [1]_, other than the fact that the NetworkX version does not use bitsets. This style of algorithm for maximum weight clique (and maximum weight independent set, which is the same problem but on the complement graph) has a decades-long history. See Algorithm B of Warren and Hicks [2]_ and the references in that paper.
References ---------- .. [1] Tavares, W.A., Neto, M.B.C., Rodrigues, C.D., Michelon, P.: Um algoritmo de branch and bound para o problema da clique máxima ponderada. Proceedings of XLVII SBPO 1 (2015).
.. [2] Warren, Jeffrey S, Hicks, Illya V.: Combinatorial Branch-and-Bound for the Maximum Weight Independent Set Problem. Technical Report, Texas A&M University (2016). """
mwc = MaxWeightClique(G, weight) mwc.find_max_weight_clique() return mwc.incumbent_nodes, mwc.incumbent_weight123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732"""Algorithms to characterize the number of triangles in a graph."""
from collections import Counterfrom itertools import chain, combinations
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = [ "triangles", "all_triangles", "average_clustering", "clustering", "transitivity", "square_clustering", "generalized_degree",]
@not_implemented_for("directed")@nx._dispatchabledef triangles(G, nodes=None): """Compute the number of triangles.
Finds the number of triangles that include a node as one vertex.
Parameters ---------- G : graph A networkx graph
nodes : node, iterable of nodes, or None (default=None) If a singleton node, return the number of triangles for that node. If an iterable, compute the number of triangles for each of those nodes. If `None` (the default) compute the number of triangles for all nodes in `G`.
Returns ------- out : dict or int If `nodes` is a container of nodes, returns number of triangles keyed by node (dict). If `nodes` is a specific node, returns number of triangles for the node (int).
Examples -------- >>> G = nx.complete_graph(5) >>> print(nx.triangles(G, 0)) 6 >>> print(nx.triangles(G)) {0: 6, 1: 6, 2: 6, 3: 6, 4: 6} >>> print(list(nx.triangles(G, [0, 1]).values())) [6, 6]
The total number of unique triangles in `G` can be determined by summing the number of triangles for each node and dividing by 3 (because a given triangle gets counted three times, once for each of its nodes).
>>> sum(nx.triangles(G).values()) // 3 10
Notes ----- Self loops are ignored.
""" if nodes is not None: # If `nodes` represents a single node, return only its number of triangles if nodes in G: return next(_triangles_and_degree_iter(G, nodes))[2] // 2
# if `nodes` is a container of nodes, then return a # dictionary mapping node to number of triangles. return {v: t // 2 for v, d, t, _ in _triangles_and_degree_iter(G, nodes)}
# if nodes is None, then compute triangles for the complete graph
# dict used to avoid visiting the same nodes twice # this allows calculating/counting each triangle only once later_nbrs = {}
# iterate over the nodes in a graph for node, neighbors in G.adjacency(): later_nbrs[node] = {n for n in neighbors if n not in later_nbrs and n != node}
# instantiate Counter for each node to include isolated nodes # add 1 to the count if a nodes neighbor's neighbor is also a neighbor triangle_counts = Counter(dict.fromkeys(G, 0)) for node1, neighbors in later_nbrs.items(): for node2 in neighbors: third_nodes = neighbors & later_nbrs[node2] m = len(third_nodes) triangle_counts[node1] += m triangle_counts[node2] += m triangle_counts.update(third_nodes)
return dict(triangle_counts)
@not_implemented_for("multigraph")def _triangles_and_degree_iter(G, nodes=None): """Return an iterator of (node, degree, triangles, generalized degree).
This double counts triangles so you may want to divide by 2. See degree(), triangles() and generalized_degree() for definitions and details.
""" if nodes is None: nodes_nbrs = G.adj.items() else: nodes_nbrs = ((n, G[n]) for n in G.nbunch_iter(nodes))
for v, v_nbrs in nodes_nbrs: vs = set(v_nbrs) - {v} gen_degree = Counter(len(vs & (set(G[w]) - {w})) for w in vs) ntriangles = sum(k * val for k, val in gen_degree.items()) yield (v, len(vs), ntriangles, gen_degree)
@not_implemented_for("multigraph")def _weighted_triangles_and_degree_iter(G, nodes=None, weight="weight"): """Return an iterator of (node, degree, weighted_triangles).
Used for weighted clustering. Note: this returns the geometric average weight of edges in the triangle. Also, each triangle is counted twice (each direction). So you may want to divide by 2.
""" import numpy as np
if weight is None or G.number_of_edges() == 0: max_weight = 1 else: max_weight = max(d.get(weight, 1) for u, v, d in G.edges(data=True)) if nodes is None: nodes_nbrs = G.adj.items() else: nodes_nbrs = ((n, G[n]) for n in G.nbunch_iter(nodes))
def wt(u, v): return G[u][v].get(weight, 1) / max_weight
for i, nbrs in nodes_nbrs: inbrs = set(nbrs) - {i} weighted_triangles = 0 seen = set() for j in inbrs: seen.add(j) # This avoids counting twice -- we double at the end. jnbrs = set(G[j]) - seen # Only compute the edge weight once, before the inner inner # loop. wij = wt(i, j) weighted_triangles += np.cbrt( [(wij * wt(j, k) * wt(k, i)) for k in inbrs & jnbrs] ).sum() yield (i, len(inbrs), 2 * float(weighted_triangles))
@not_implemented_for("multigraph")def _directed_triangles_and_degree_iter(G, nodes=None): """Return an iterator of (node, total_degree, reciprocal_degree, directed_triangles).
Used for directed clustering. Note that unlike `_triangles_and_degree_iter()`, this function counts directed triangles so does not count triangles twice.
""" nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))
for i, preds, succs in nodes_nbrs: ipreds = set(preds) - {i} isuccs = set(succs) - {i}
directed_triangles = 0 for j in chain(ipreds, isuccs): jpreds = set(G._pred[j]) - {j} jsuccs = set(G._succ[j]) - {j} directed_triangles += sum( 1 for k in chain( (ipreds & jpreds), (ipreds & jsuccs), (isuccs & jpreds), (isuccs & jsuccs), ) ) dtotal = len(ipreds) + len(isuccs) dbidirectional = len(ipreds & isuccs) yield (i, dtotal, dbidirectional, directed_triangles)
@not_implemented_for("multigraph")def _directed_weighted_triangles_and_degree_iter(G, nodes=None, weight="weight"): """Return an iterator of (node, total_degree, reciprocal_degree, directed_weighted_triangles).
Used for directed weighted clustering. Note that unlike `_weighted_triangles_and_degree_iter()`, this function counts directed triangles so does not count triangles twice.
""" import numpy as np
if weight is None or G.number_of_edges() == 0: max_weight = 1 else: max_weight = max(d.get(weight, 1) for u, v, d in G.edges(data=True))
nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))
def wt(u, v): return G[u][v].get(weight, 1) / max_weight
for i, preds, succs in nodes_nbrs: ipreds = set(preds) - {i} isuccs = set(succs) - {i}
directed_triangles = 0 for j in ipreds: jpreds = set(G._pred[j]) - {j} jsuccs = set(G._succ[j]) - {j} directed_triangles += np.cbrt( [(wt(j, i) * wt(k, i) * wt(k, j)) for k in ipreds & jpreds] ).sum() directed_triangles += np.cbrt( [(wt(j, i) * wt(k, i) * wt(j, k)) for k in ipreds & jsuccs] ).sum() directed_triangles += np.cbrt( [(wt(j, i) * wt(i, k) * wt(k, j)) for k in isuccs & jpreds] ).sum() directed_triangles += np.cbrt( [(wt(j, i) * wt(i, k) * wt(j, k)) for k in isuccs & jsuccs] ).sum()
for j in isuccs: jpreds = set(G._pred[j]) - {j} jsuccs = set(G._succ[j]) - {j} directed_triangles += np.cbrt( [(wt(i, j) * wt(k, i) * wt(k, j)) for k in ipreds & jpreds] ).sum() directed_triangles += np.cbrt( [(wt(i, j) * wt(k, i) * wt(j, k)) for k in ipreds & jsuccs] ).sum() directed_triangles += np.cbrt( [(wt(i, j) * wt(i, k) * wt(k, j)) for k in isuccs & jpreds] ).sum() directed_triangles += np.cbrt( [(wt(i, j) * wt(i, k) * wt(j, k)) for k in isuccs & jsuccs] ).sum()
dtotal = len(ipreds) + len(isuccs) dbidirectional = len(ipreds & isuccs) yield (i, dtotal, dbidirectional, float(directed_triangles))
@not_implemented_for("directed")@nx._dispatchabledef all_triangles(G, nbunch=None): """ Yields all unique triangles in an undirected graph.
A triangle is a set of three distinct nodes where each node is connected to the other two.
Parameters ---------- G : NetworkX graph An undirected graph.
nbunch : node, iterable of nodes, or None (default=None) If a node or iterable of nodes, only triangles involving at least one node in `nbunch` are yielded. If ``None``, yields all unique triangles in the graph.
Yields ------ tuple A tuple of three nodes forming a triangle ``(u, v, w)``.
Examples -------- >>> G = nx.complete_graph(4) >>> sorted([sorted(t) for t in all_triangles(G)]) [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]
Notes ----- This algorithm ensures each triangle is yielded once using an internal node ordering. In multigraphs, triangles are identified by their unique set of nodes, ignoring multiple edges between the same nodes. Self-loops are ignored. Runs in ``O(m * d)`` time in the worst case, where ``m`` the number of edges and ``d`` the maximum degree.
See Also -------- :func:`~networkx.algorithms.triads.all_triads` : related function for directed graphs """ if nbunch is None: nbunch = relevant_nodes = G else: nbunch = dict.fromkeys(G.nbunch_iter(nbunch)) relevant_nodes = chain( nbunch, (nbr for node in nbunch for nbr in G.neighbors(node) if nbr not in nbunch), )
node_to_id = {node: i for i, node in enumerate(relevant_nodes)}
for u in nbunch: u_id = node_to_id[u] u_nbrs = G._adj[u].keys() for v in u_nbrs: v_id = node_to_id.get(v, -1) if v_id <= u_id: continue v_nbrs = G._adj[v].keys() for w in v_nbrs & u_nbrs: if node_to_id.get(w, -1) > v_id: yield u, v, w
@nx._dispatchable(edge_attrs="weight")def average_clustering(G, nodes=None, weight=None, count_zeros=True): r"""Compute the average clustering coefficient for the graph G.
The clustering coefficient for the graph is the average,
.. math::
C = \frac{1}{n}\sum_{v \in G} c_v,
where :math:`n` is the number of nodes in `G`.
Parameters ---------- G : graph
nodes : container of nodes, optional (default=all nodes in G) Compute average clustering for nodes in this container.
weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1.
count_zeros : bool If False include only the nodes with nonzero clustering in the average.
Returns ------- avg : float Average clustering
Examples -------- >>> G = nx.complete_graph(5) >>> print(nx.average_clustering(G)) 1.0
Notes ----- This is a space saving routine; it might be faster to use the clustering function to get a list and then take the average.
Self loops are ignored.
References ---------- .. [1] Generalizations of the clustering coefficient to weighted complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela, K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007). http://jponnela.com/web_documents/a9.pdf .. [2] Marcus Kaiser, Mean clustering coefficients: the role of isolated nodes and leafs on clustering measures for small-world networks. https://arxiv.org/abs/0802.2512 """ c = clustering(G, nodes, weight=weight).values() if not count_zeros: c = [v for v in c if abs(v) > 0] return sum(c) / len(c)
@nx._dispatchable(edge_attrs="weight")def clustering(G, nodes=None, weight=None): r"""Compute the clustering coefficient for nodes.
For unweighted graphs, the clustering of a node :math:`u` is the fraction of possible triangles through that node that exist,
.. math::
c_u = \frac{2 T(u)}{deg(u)(deg(u)-1)},
where :math:`T(u)` is the number of triangles through node :math:`u` and :math:`deg(u)` is the degree of :math:`u`.
For weighted graphs, there are several ways to define clustering [1]_. the one used here is defined as the geometric average of the subgraph edge weights [2]_,
.. math::
c_u = \frac{1}{deg(u)(deg(u)-1))} \sum_{vw} (\hat{w}_{uv} \hat{w}_{uw} \hat{w}_{vw})^{1/3}.
The edge weights :math:`\hat{w}_{uv}` are normalized by the maximum weight in the network :math:`\hat{w}_{uv} = w_{uv}/\max(w)`.
The value of :math:`c_u` is assigned to 0 if :math:`deg(u) < 2`.
Additionally, this weighted definition has been generalized to support negative edge weights [3]_.
For directed graphs, the clustering is similarly defined as the fraction of all possible directed triangles or geometric average of the subgraph edge weights for unweighted and weighted directed graph respectively [4]_.
.. math::
c_u = \frac{T(u)}{2(deg^{tot}(u)(deg^{tot}(u)-1) - 2deg^{\leftrightarrow}(u))},
where :math:`T(u)` is the number of directed triangles through node :math:`u`, :math:`deg^{tot}(u)` is the sum of in degree and out degree of :math:`u` and :math:`deg^{\leftrightarrow}(u)` is the reciprocal degree of :math:`u`.
Parameters ---------- G : graph
nodes : node, iterable of nodes, or None (default=None) If a singleton node, return the number of triangles for that node. If an iterable, compute the number of triangles for each of those nodes. If `None` (the default) compute the number of triangles for all nodes in `G`.
weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1.
Returns ------- out : float, or dictionary Clustering coefficient at specified nodes
Examples -------- >>> G = nx.complete_graph(5) >>> print(nx.clustering(G, 0)) 1.0 >>> print(nx.clustering(G)) {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
Notes ----- Self loops are ignored.
References ---------- .. [1] Generalizations of the clustering coefficient to weighted complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela, K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007). http://jponnela.com/web_documents/a9.pdf .. [2] Intensity and coherence of motifs in weighted complex networks by J. P. Onnela, J. Saramäki, J. Kertész, and K. Kaski, Physical Review E, 71(6), 065103 (2005). .. [3] Generalization of Clustering Coefficients to Signed Correlation Networks by G. Costantini and M. Perugini, PloS one, 9(2), e88669 (2014). .. [4] Clustering in complex directed networks by G. Fagiolo, Physical Review E, 76(2), 026107 (2007). """ if G.is_directed(): if weight is not None: td_iter = _directed_weighted_triangles_and_degree_iter(G, nodes, weight) clusterc = { v: 0 if t == 0 else t / ((dt * (dt - 1) - 2 * db) * 2) for v, dt, db, t in td_iter } else: td_iter = _directed_triangles_and_degree_iter(G, nodes) clusterc = { v: 0 if t == 0 else t / ((dt * (dt - 1) - 2 * db) * 2) for v, dt, db, t in td_iter } else: # The formula 2*T/(d*(d-1)) from docs is t/(d*(d-1)) here b/c t==2*T if weight is not None: td_iter = _weighted_triangles_and_degree_iter(G, nodes, weight) clusterc = {v: 0 if t == 0 else t / (d * (d - 1)) for v, d, t in td_iter} else: td_iter = _triangles_and_degree_iter(G, nodes) clusterc = {v: 0 if t == 0 else t / (d * (d - 1)) for v, d, t, _ in td_iter} if nodes in G: # Return the value of the sole entry in the dictionary. return clusterc[nodes] return clusterc
@nx._dispatchabledef transitivity(G): r"""Compute graph transitivity, the fraction of all possible triangles present in G.
Possible triangles are identified by the number of "triads" (two edges with a shared vertex).
The transitivity is
.. math::
T = 3\frac{\#triangles}{\#triads}.
Parameters ---------- G : graph
Returns ------- out : float Transitivity
Notes ----- Self loops are ignored.
Examples -------- >>> G = nx.complete_graph(5) >>> print(nx.transitivity(G)) 1.0 """ triangles_contri = [ (t, d * (d - 1)) for v, d, t, _ in _triangles_and_degree_iter(G) ] # If the graph is empty if len(triangles_contri) == 0: return 0 triangles, contri = map(sum, zip(*triangles_contri)) return 0 if triangles == 0 else triangles / contri
@nx._dispatchabledef square_clustering(G, nodes=None): r"""Compute the squares clustering coefficient for nodes.
For each node return the fraction of possible squares that exist at the node [1]_
.. math:: C_4(v) = \frac{ \sum_{u=1}^{k_v} \sum_{w=u+1}^{k_v} q_v(u,w) }{ \sum_{u=1}^{k_v} \sum_{w=u+1}^{k_v} [a_v(u,w) + q_v(u,w)]},
where :math:`q_v(u,w)` are the number of common neighbors of :math:`u` and :math:`w` other than :math:`v` (ie squares), and :math:`a_v(u,w) = (k_u - (1+q_v(u,w)+\theta_{uv})) + (k_w - (1+q_v(u,w)+\theta_{uw}))`, where :math:`\theta_{uw} = 1` if :math:`u` and :math:`w` are connected and 0 otherwise. [2]_
Parameters ---------- G : graph
nodes : container of nodes, optional (default=all nodes in G) Compute clustering for nodes in this container.
Returns ------- c4 : dictionary A dictionary keyed by node with the square clustering coefficient value.
Examples -------- >>> G = nx.complete_graph(5) >>> print(nx.square_clustering(G, 0)) 1.0 >>> print(nx.square_clustering(G)) {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
Notes ----- Self loops are ignored.
While :math:`C_3(v)` (triangle clustering) gives the probability that two neighbors of node v are connected with each other, :math:`C_4(v)` is the probability that two neighbors of node v share a common neighbor different from v. This algorithm can be applied to both bipartite and unipartite networks.
References ---------- .. [1] Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005 Cycles and clustering in bipartite networks. Physical Review E (72) 056127. .. [2] Zhang, Peng et al. Clustering Coefficient and Community Structure of Bipartite Networks. Physica A: Statistical Mechanics and its Applications 387.27 (2008): 6869–6875. https://arxiv.org/abs/0710.0117v1 """ if nodes is None: node_iter = G else: node_iter = G.nbunch_iter(nodes) clustering = {} _G_adj = G._adj
class GAdj(dict): """Calculate (and cache) node neighbor sets excluding self-loops."""
def __missing__(self, v): v_neighbors = self[v] = set(_G_adj[v]) v_neighbors.discard(v) # Ignore self-loops return v_neighbors
G_adj = GAdj() # Values are sets of neighbors (no self-loops)
for v in node_iter: v_neighbors = G_adj[v] v_degrees_m1 = len(v_neighbors) - 1 # degrees[v] - 1 (used below) if v_degrees_m1 <= 0: # Can't form a square without at least two neighbors clustering[v] = 0 continue
# Count squares with nodes u-v-w-x from the current node v. # Terms of the denominator: potential = uw_degrees - uw_count - triangles - squares # uw_degrees: degrees[u] + degrees[w] for each u-w combo uw_degrees = 0 # uw_count: 1 for each u and 1 for each w for all combos (degrees * (degrees - 1)) uw_count = len(v_neighbors) * v_degrees_m1 # triangles: 1 for each edge where u-w or w-u are connected (i.e. triangles) triangles = 0 # squares: the number of squares (also the numerator) squares = 0
# Iterate over all neighbors for u in v_neighbors: u_neighbors = G_adj[u] uw_degrees += len(u_neighbors) * v_degrees_m1 # P2 from https://arxiv.org/abs/2007.11111 p2 = len(u_neighbors & v_neighbors) # triangles is C_3, sigma_4 from https://arxiv.org/abs/2007.11111 # This double-counts triangles compared to `triangles` function triangles += p2 # squares is C_4, sigma_12 from https://arxiv.org/abs/2007.11111 # Include this term, b/c a neighbor u can also be a neighbor of neighbor x squares += p2 * (p2 - 1) # Will divide by 2 later
# And iterate over all neighbors of neighbors. # These nodes x may be the corners opposite v in squares u-v-w-x. two_hop_neighbors = set.union(*(G_adj[u] for u in v_neighbors)) two_hop_neighbors -= v_neighbors # Neighbors already counted above two_hop_neighbors.discard(v) for x in two_hop_neighbors: p2 = len(v_neighbors & G_adj[x]) squares += p2 * (p2 - 1) # Will divide by 2 later
squares //= 2 potential = uw_degrees - uw_count - triangles - squares if potential > 0: clustering[v] = squares / potential else: clustering[v] = 0 if nodes in G: # Return the value of the sole entry in the dictionary. return clustering[nodes] return clustering
@not_implemented_for("directed")@nx._dispatchabledef generalized_degree(G, nodes=None): r"""Compute the generalized degree for nodes.
For each node, the generalized degree shows how many edges of given triangle multiplicity the node is connected to. The triangle multiplicity of an edge is the number of triangles an edge participates in. The generalized degree of node :math:`i` can be written as a vector :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc, k_i^{(N-2)})` where :math:`k_i^{(j)}` is the number of edges attached to node :math:`i` that participate in :math:`j` triangles.
Parameters ---------- G : graph
nodes : container of nodes, optional (default=all nodes in G) Compute the generalized degree for nodes in this container.
Returns ------- out : Counter, or dictionary of Counters Generalized degree of specified nodes. The Counter is keyed by edge triangle multiplicity.
Examples -------- >>> G = nx.complete_graph(5) >>> print(nx.generalized_degree(G, 0)) Counter({3: 4}) >>> print(nx.generalized_degree(G)) {0: Counter({3: 4}), 1: Counter({3: 4}), 2: Counter({3: 4}), 3: Counter({3: 4}), 4: Counter({3: 4})}
To recover the number of triangles attached to a node:
>>> k1 = nx.generalized_degree(G, 0) >>> sum([k * v for k, v in k1.items()]) / 2 == nx.triangles(G, 0) True
Notes ----- Self loops are ignored.
In a network of N nodes, the highest triangle multiplicity an edge can have is N-2.
The return value does not include a `zero` entry if no edges of a particular triangle multiplicity are present.
The number of triangles node :math:`i` is attached to can be recovered from the generalized degree :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc, k_i^{(N-2)})` by :math:`(k_i^{(1)}+2k_i^{(2)}+\dotsc +(N-2)k_i^{(N-2)})/2`.
References ---------- .. [1] Networks with arbitrary edge multiplicities by V. Zlatić, D. Garlaschelli and G. Caldarelli, EPL (Europhysics Letters), Volume 97, Number 2 (2012). https://iopscience.iop.org/article/10.1209/0295-5075/97/28005 """ if nodes in G: return next(_triangles_and_degree_iter(G, nodes))[3] return {v: gd for v, d, t, gd in _triangles_and_degree_iter(G, nodes)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163"""Communicability."""
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = ["communicability", "communicability_exp"]
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchabledef communicability(G): r"""Returns communicability between all pairs of nodes in G.
The communicability between pairs of nodes in G is the sum of walks of different lengths starting at node u and ending at node v.
Parameters ---------- G: graph
Returns ------- comm: dictionary of dictionaries Dictionary of dictionaries keyed by nodes with communicability as the value.
Raises ------ NetworkXError If the graph is not undirected and simple.
See Also -------- communicability_exp: Communicability between all pairs of nodes in G using spectral decomposition. communicability_betweenness_centrality: Communicability betweenness centrality for each node in G.
Notes ----- This algorithm uses a spectral decomposition of the adjacency matrix. Let G=(V,E) be a simple undirected graph. Using the connection between the powers of the adjacency matrix and the number of walks in the graph, the communicability between nodes `u` and `v` based on the graph spectrum is [1]_
.. math:: C(u,v)=\sum_{j=1}^{n}\phi_{j}(u)\phi_{j}(v)e^{\lambda_{j}},
where `\phi_{j}(u)` is the `u\rm{th}` element of the `j\rm{th}` orthonormal eigenvector of the adjacency matrix associated with the eigenvalue `\lambda_{j}`.
References ---------- .. [1] Ernesto Estrada, Naomichi Hatano, "Communicability in complex networks", Phys. Rev. E 77, 036111 (2008). https://arxiv.org/abs/0707.0756
Examples -------- >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)]) >>> c = nx.communicability(G) """ import numpy as np
nodelist = list(G) # ordering of nodes in matrix A = nx.to_numpy_array(G, nodelist) # convert to 0-1 matrix A[A != 0.0] = 1 w, vec = np.linalg.eigh(A) expw = np.exp(w) mapping = dict(zip(nodelist, range(len(nodelist)))) c = {} # computing communicabilities for u in G: c[u] = {} for v in G: s = 0 p = mapping[u] q = mapping[v] for j in range(len(nodelist)): s += vec[:, j][p] * vec[:, j][q] * expw[j] c[u][v] = float(s) return c
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchabledef communicability_exp(G): r"""Returns communicability between all pairs of nodes in G.
Communicability between pair of node (u,v) of node in G is the sum of walks of different lengths starting at node u and ending at node v.
Parameters ---------- G: graph
Returns ------- comm: dictionary of dictionaries Dictionary of dictionaries keyed by nodes with communicability as the value.
Raises ------ NetworkXError If the graph is not undirected and simple.
See Also -------- communicability: Communicability between pairs of nodes in G. communicability_betweenness_centrality: Communicability betweenness centrality for each node in G.
Notes ----- This algorithm uses matrix exponentiation of the adjacency matrix.
Let G=(V,E) be a simple undirected graph. Using the connection between the powers of the adjacency matrix and the number of walks in the graph, the communicability between nodes u and v is [1]_,
.. math:: C(u,v) = (e^A)_{uv},
where `A` is the adjacency matrix of G.
References ---------- .. [1] Ernesto Estrada, Naomichi Hatano, "Communicability in complex networks", Phys. Rev. E 77, 036111 (2008). https://arxiv.org/abs/0707.0756
Examples -------- >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)]) >>> c = nx.communicability_exp(G) """ import scipy as sp
nodelist = list(G) # ordering of nodes in matrix A = nx.to_numpy_array(G, nodelist) # convert to 0-1 matrix A[A != 0.0] = 1 # communicability matrix expA = sp.linalg.expm(A) mapping = dict(zip(nodelist, range(len(nodelist)))) c = {} for u in G: c[u] = {} for v in G: c[u][v] = float(expA[mapping[u], mapping[v]]) return c1234567891011"""Connectivity and cut algorithms"""
from .connectivity import *from .cuts import *from .edge_augmentation import *from .edge_kcomponents import *from .disjoint_paths import *from .kcomponents import *from .kcutsets import *from .stoerwagner import *from .utils import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811"""Flow based connectivity algorithms"""
import itertoolsfrom operator import itemgetter
import networkx as nx
# Define the default maximum flow function to use in all flow based# connectivity algorithms.from networkx.algorithms.flow import ( boykov_kolmogorov, build_residual_network, dinitz, edmonds_karp, preflow_push, shortest_augmenting_path,)
from .utils import build_auxiliary_edge_connectivity, build_auxiliary_node_connectivity
default_flow_func = edmonds_karp
__all__ = [ "average_node_connectivity", "local_node_connectivity", "node_connectivity", "local_edge_connectivity", "edge_connectivity", "all_pairs_node_connectivity",]
@nx._dispatchable(graphs={"G": 0, "auxiliary?": 4}, preserve_graph_attrs={"auxiliary"})def local_node_connectivity( G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None): r"""Computes local node connectivity for nodes s and t.
Local node connectivity for two non adjacent nodes s and t is the minimum number of nodes that must be removed (along with their incident edges) to disconnect them.
This is a flow based implementation of node connectivity. We compute the maximum flow on an auxiliary digraph build from the original input graph (see below for details).
Parameters ---------- G : NetworkX graph Undirected graph
s : node Source node
t : node Target node
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None.
auxiliary : NetworkX DiGraph Auxiliary digraph to compute flow based node connectivity. It has to have a graph attribute called mapping with a dictionary mapping node names in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default value: None.
residual : NetworkX DiGraph Residual network to compute maximum flow. If provided it will be reused instead of recreated. Default value: None.
cutoff : integer, float, or None (default: None) If specified, the maximum flow algorithm will terminate when the flow value reaches or exceeds the cutoff. This only works for flows that support the cutoff parameter (most do) and is ignored otherwise.
Returns ------- K : integer local node connectivity for nodes s and t
Examples -------- This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the connectivity package:
>>> from networkx.algorithms.connectivity import local_node_connectivity
We use in this example the platonic icosahedral graph, which has node connectivity 5.
>>> G = nx.icosahedral_graph() >>> local_node_connectivity(G, 0, 6) 5
If you need to compute local connectivity on several pairs of nodes in the same graph, it is recommended that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity, and the residual network for the underlying maximum flow computation.
Example of how to compute local node connectivity among all pairs of nodes of the platonic icosahedral graph reusing the data structures.
>>> import itertools >>> # You also have to explicitly import the function for >>> # building the auxiliary digraph from the connectivity package >>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity >>> H = build_auxiliary_node_connectivity(G) >>> # And the function for building the residual network from the >>> # flow package >>> from networkx.algorithms.flow import build_residual_network >>> # Note that the auxiliary digraph has an edge attribute named capacity >>> R = build_residual_network(H, "capacity") >>> result = dict.fromkeys(G, dict()) >>> # Reuse the auxiliary digraph and the residual network by passing them >>> # as parameters >>> for u, v in itertools.combinations(G, 2): ... k = local_node_connectivity(G, u, v, auxiliary=H, residual=R) ... result[u][v] = k >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2)) True
You can also use alternative flow algorithms for computing node connectivity. For instance, in dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp` which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path >>> local_node_connectivity(G, 0, 6, flow_func=shortest_augmenting_path) 5
Notes ----- This is a flow based implementation of node connectivity. We compute the maximum flow using, by default, the :meth:`edmonds_karp` algorithm (see: :meth:`maximum_flow`) on an auxiliary digraph build from the original input graph:
For an undirected graph G having `n` nodes and `m` edges we derive a directed graph H with `2n` nodes and `2m+n` arcs by replacing each original node `v` with two nodes `v_A`, `v_B` linked by an (internal) arc in H. Then for each edge (`u`, `v`) in G we add two arcs (`u_B`, `v_A`) and (`v_B`, `u_A`) in H. Finally we set the attribute capacity = 1 for each arc in H [1]_ .
For a directed graph G having `n` nodes and `m` arcs we derive a directed graph H with `2n` nodes and `m+n` arcs by replacing each original node `v` with two nodes `v_A`, `v_B` linked by an (internal) arc (`v_A`, `v_B`) in H. Then for each arc (`u`, `v`) in G we add one arc (`u_B`, `v_A`) in H. Finally we set the attribute capacity = 1 for each arc in H.
This is equal to the local node connectivity because the value of a maximum s-t-flow is equal to the capacity of a minimum s-t-cut.
See also -------- :meth:`local_edge_connectivity` :meth:`node_connectivity` :meth:`minimum_node_cut` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path`
References ---------- .. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and Erlebach, 'Network Analysis: Methodological Foundations', Lecture Notes in Computer Science, Volume 3418, Springer-Verlag, 2005. http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
""" if flow_func is None: flow_func = default_flow_func
if auxiliary is None: H = build_auxiliary_node_connectivity(G) else: H = auxiliary
mapping = H.graph.get("mapping", None) if mapping is None: raise nx.NetworkXError("Invalid auxiliary digraph.")
kwargs = {"flow_func": flow_func, "residual": residual}
if flow_func is not preflow_push: kwargs["cutoff"] = cutoff
if flow_func is shortest_augmenting_path: kwargs["two_phase"] = True
return nx.maximum_flow_value(H, f"{mapping[s]}B", f"{mapping[t]}A", **kwargs)
@nx._dispatchabledef node_connectivity(G, s=None, t=None, flow_func=None): r"""Returns node connectivity for a graph or digraph G.
Node connectivity is equal to the minimum number of nodes that must be removed to disconnect G or render it trivial. If source and target nodes are provided, this function returns the local node connectivity: the minimum number of nodes that must be removed to break all paths from source to target in G.
Parameters ---------- G : NetworkX graph Undirected graph
s : node Source node. Optional. Default value: None.
t : node Target node. Optional. Default value: None.
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None.
Returns ------- K : integer Node connectivity of G, or local node connectivity if source and target are provided.
Examples -------- >>> # Platonic icosahedral graph is 5-node-connected >>> G = nx.icosahedral_graph() >>> nx.node_connectivity(G) 5
You can use alternative flow algorithms for the underlying maximum flow computation. In dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp`, which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path >>> nx.node_connectivity(G, flow_func=shortest_augmenting_path) 5
If you specify a pair of nodes (source and target) as parameters, this function returns the value of local node connectivity.
>>> nx.node_connectivity(G, 3, 7) 5
If you need to perform several local computations among different pairs of nodes on the same graph, it is recommended that you reuse the data structures used in the maximum flow computations. See :meth:`local_node_connectivity` for details.
Notes ----- This is a flow based implementation of node connectivity. The algorithm works by solving $O((n-\delta-1+\delta(\delta-1)/2))$ maximum flow problems on an auxiliary digraph. Where $\delta$ is the minimum degree of G. For details about the auxiliary digraph and the computation of local node connectivity see :meth:`local_node_connectivity`. This implementation is based on algorithm 11 in [1]_.
See also -------- :meth:`local_node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path`
References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
""" if (s is not None and t is None) or (s is None and t is not None): raise nx.NetworkXError("Both source and target must be specified.")
# Local node connectivity if s is not None and t is not None: if s not in G: raise nx.NetworkXError(f"node {s} not in graph") if t not in G: raise nx.NetworkXError(f"node {t} not in graph") return local_node_connectivity(G, s, t, flow_func=flow_func)
# Global node connectivity if G.is_directed(): if not nx.is_weakly_connected(G): return 0 iter_func = itertools.permutations # It is necessary to consider both predecessors # and successors for directed graphs
def neighbors(v): return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
else: if not nx.is_connected(G): return 0 iter_func = itertools.combinations neighbors = G.neighbors
# Reuse the auxiliary digraph and the residual network H = build_auxiliary_node_connectivity(G) R = build_residual_network(H, "capacity") kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
# Pick a node with minimum degree # Node connectivity is bounded by degree. v, K = min(G.degree(), key=itemgetter(1)) # compute local node connectivity with all its non-neighbors nodes for w in set(G) - set(neighbors(v)) - {v}: kwargs["cutoff"] = K K = min(K, local_node_connectivity(G, v, w, **kwargs)) # Also for non adjacent pairs of neighbors of v for x, y in iter_func(neighbors(v), 2): if y in G[x]: continue kwargs["cutoff"] = K K = min(K, local_node_connectivity(G, x, y, **kwargs))
return K
@nx._dispatchabledef average_node_connectivity(G, flow_func=None): r"""Returns the average connectivity of a graph G.
The average connectivity `\bar{\kappa}` of a graph G is the average of local node connectivity over all pairs of nodes of G [1]_ .
.. math::
\bar{\kappa}(G) = \frac{\sum_{u,v} \kappa_{G}(u,v)}{{n \choose 2}}
Parameters ----------
G : NetworkX graph Undirected graph
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See :meth:`local_node_connectivity` for details. The choice of the default function may change from version to version and should not be relied on. Default value: None.
Returns ------- K : float Average node connectivity
See also -------- :meth:`local_node_connectivity` :meth:`node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path`
References ---------- .. [1] Beineke, L., O. Oellermann, and R. Pippert (2002). The average connectivity of a graph. Discrete mathematics 252(1-3), 31-45. http://www.sciencedirect.com/science/article/pii/S0012365X01001807
""" if G.is_directed(): iter_func = itertools.permutations else: iter_func = itertools.combinations
# Reuse the auxiliary digraph and the residual network H = build_auxiliary_node_connectivity(G) R = build_residual_network(H, "capacity") kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
num, den = 0, 0 for u, v in iter_func(G, 2): num += local_node_connectivity(G, u, v, **kwargs) den += 1
if den == 0: # Null Graph return 0 return num / den
@nx._dispatchabledef all_pairs_node_connectivity(G, nbunch=None, flow_func=None): """Compute node connectivity between all pairs of nodes of G.
Parameters ---------- G : NetworkX graph Undirected graph
nbunch: container Container of nodes. If provided node connectivity will be computed only over pairs of nodes in nbunch.
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None.
Returns ------- all_pairs : dict A dictionary with node connectivity between all pairs of nodes in G, or in nbunch if provided.
See also -------- :meth:`local_node_connectivity` :meth:`edge_connectivity` :meth:`local_edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path`
""" if nbunch is None: nbunch = G else: nbunch = set(nbunch)
directed = G.is_directed() if directed: iter_func = itertools.permutations else: iter_func = itertools.combinations
all_pairs = {n: {} for n in nbunch}
# Reuse auxiliary digraph and residual network H = build_auxiliary_node_connectivity(G) mapping = H.graph["mapping"] R = build_residual_network(H, "capacity") kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
for u, v in iter_func(nbunch, 2): K = local_node_connectivity(G, u, v, **kwargs) all_pairs[u][v] = K if not directed: all_pairs[v][u] = K
return all_pairs
@nx._dispatchable(graphs={"G": 0, "auxiliary?": 4})def local_edge_connectivity( G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None): r"""Returns local edge connectivity for nodes s and t in G.
Local edge connectivity for two nodes s and t is the minimum number of edges that must be removed to disconnect them.
This is a flow based implementation of edge connectivity. We compute the maximum flow on an auxiliary digraph build from the original network (see below for details). This is equal to the local edge connectivity because the value of a maximum s-t-flow is equal to the capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ .
Parameters ---------- G : NetworkX graph Undirected or directed graph
s : node Source node
t : node Target node
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None.
auxiliary : NetworkX DiGraph Auxiliary digraph for computing flow based edge connectivity. If provided it will be reused instead of recreated. Default value: None.
residual : NetworkX DiGraph Residual network to compute maximum flow. If provided it will be reused instead of recreated. Default value: None.
cutoff : integer, float, or None (default: None) If specified, the maximum flow algorithm will terminate when the flow value reaches or exceeds the cutoff. This only works for flows that support the cutoff parameter (most do) and is ignored otherwise.
Returns ------- K : integer local edge connectivity for nodes s and t.
Examples -------- This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the connectivity package:
>>> from networkx.algorithms.connectivity import local_edge_connectivity
We use in this example the platonic icosahedral graph, which has edge connectivity 5.
>>> G = nx.icosahedral_graph() >>> local_edge_connectivity(G, 0, 6) 5
If you need to compute local connectivity on several pairs of nodes in the same graph, it is recommended that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity, and the residual network for the underlying maximum flow computation.
Example of how to compute local edge connectivity among all pairs of nodes of the platonic icosahedral graph reusing the data structures.
>>> import itertools >>> # You also have to explicitly import the function for >>> # building the auxiliary digraph from the connectivity package >>> from networkx.algorithms.connectivity import build_auxiliary_edge_connectivity >>> H = build_auxiliary_edge_connectivity(G) >>> # And the function for building the residual network from the >>> # flow package >>> from networkx.algorithms.flow import build_residual_network >>> # Note that the auxiliary digraph has an edge attribute named capacity >>> R = build_residual_network(H, "capacity") >>> result = dict.fromkeys(G, dict()) >>> # Reuse the auxiliary digraph and the residual network by passing them >>> # as parameters >>> for u, v in itertools.combinations(G, 2): ... k = local_edge_connectivity(G, u, v, auxiliary=H, residual=R) ... result[u][v] = k >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2)) True
You can also use alternative flow algorithms for computing edge connectivity. For instance, in dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp` which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path >>> local_edge_connectivity(G, 0, 6, flow_func=shortest_augmenting_path) 5
Notes ----- This is a flow based implementation of edge connectivity. We compute the maximum flow using, by default, the :meth:`edmonds_karp` algorithm on an auxiliary digraph build from the original input graph:
If the input graph is undirected, we replace each edge (`u`,`v`) with two reciprocal arcs (`u`, `v`) and (`v`, `u`) and then we set the attribute 'capacity' for each arc to 1. If the input graph is directed we simply add the 'capacity' attribute. This is an implementation of algorithm 1 in [1]_.
The maximum flow in the auxiliary network is equal to the local edge connectivity because the value of a maximum s-t-flow is equal to the capacity of a minimum s-t-cut (Ford and Fulkerson theorem).
See also -------- :meth:`edge_connectivity` :meth:`local_node_connectivity` :meth:`node_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path`
References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
""" if flow_func is None: flow_func = default_flow_func
if auxiliary is None: H = build_auxiliary_edge_connectivity(G) else: H = auxiliary
kwargs = {"flow_func": flow_func, "residual": residual}
if flow_func is not preflow_push: kwargs["cutoff"] = cutoff
if flow_func is shortest_augmenting_path: kwargs["two_phase"] = True
return nx.maximum_flow_value(H, s, t, **kwargs)
@nx._dispatchabledef edge_connectivity(G, s=None, t=None, flow_func=None, cutoff=None): r"""Returns the edge connectivity of the graph or digraph G.
The edge connectivity is equal to the minimum number of edges that must be removed to disconnect G or render it trivial. If source and target nodes are provided, this function returns the local edge connectivity: the minimum number of edges that must be removed to break all paths from source to target in G.
Parameters ---------- G : NetworkX graph Undirected or directed graph
s : node Source node. Optional. Default value: None.
t : node Target node. Optional. Default value: None.
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None.
cutoff : integer, float, or None (default: None) If specified, the maximum flow algorithm will terminate when the flow value reaches or exceeds the cutoff. This only works for flows that support the cutoff parameter (most do) and is ignored otherwise.
Returns ------- K : integer Edge connectivity for G, or local edge connectivity if source and target were provided
Examples -------- >>> # Platonic icosahedral graph is 5-edge-connected >>> G = nx.icosahedral_graph() >>> nx.edge_connectivity(G) 5
You can use alternative flow algorithms for the underlying maximum flow computation. In dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp`, which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path >>> nx.edge_connectivity(G, flow_func=shortest_augmenting_path) 5
If you specify a pair of nodes (source and target) as parameters, this function returns the value of local edge connectivity.
>>> nx.edge_connectivity(G, 3, 7) 5
If you need to perform several local computations among different pairs of nodes on the same graph, it is recommended that you reuse the data structures used in the maximum flow computations. See :meth:`local_edge_connectivity` for details.
Notes ----- This is a flow based implementation of global edge connectivity. For undirected graphs the algorithm works by finding a 'small' dominating set of nodes of G (see algorithm 7 in [1]_ ) and computing local maximum flow (see :meth:`local_edge_connectivity`) between an arbitrary node in the dominating set and the rest of nodes in it. This is an implementation of algorithm 6 in [1]_ . For directed graphs, the algorithm does n calls to the maximum flow function. This is an implementation of algorithm 8 in [1]_ .
See also -------- :meth:`local_edge_connectivity` :meth:`local_node_connectivity` :meth:`node_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` :meth:`k_edge_components` :meth:`k_edge_subgraphs`
References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
""" if (s is not None and t is None) or (s is None and t is not None): raise nx.NetworkXError("Both source and target must be specified.")
# Local edge connectivity if s is not None and t is not None: if s not in G: raise nx.NetworkXError(f"node {s} not in graph") if t not in G: raise nx.NetworkXError(f"node {t} not in graph") return local_edge_connectivity(G, s, t, flow_func=flow_func, cutoff=cutoff)
# Global edge connectivity # reuse auxiliary digraph and residual network H = build_auxiliary_edge_connectivity(G) R = build_residual_network(H, "capacity") kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
if G.is_directed(): # Algorithm 8 in [1] if not nx.is_weakly_connected(G): return 0
# initial value for \lambda is minimum degree L = min(d for n, d in G.degree()) nodes = list(G) n = len(nodes)
if cutoff is not None: L = min(cutoff, L)
for i in range(n): kwargs["cutoff"] = L try: L = min(L, local_edge_connectivity(G, nodes[i], nodes[i + 1], **kwargs)) except IndexError: # last node! L = min(L, local_edge_connectivity(G, nodes[i], nodes[0], **kwargs)) return L else: # undirected # Algorithm 6 in [1] if not nx.is_connected(G): return 0
# initial value for \lambda is minimum degree L = min(d for n, d in G.degree())
if cutoff is not None: L = min(cutoff, L)
# A dominating set is \lambda-covering # We need a dominating set with at least two nodes for node in G: D = nx.dominating_set(G, start_with=node) v = D.pop() if D: break else: # in complete graphs the dominating sets will always be of one node # thus we return min degree return L
for w in D: kwargs["cutoff"] = L L = min(L, local_edge_connectivity(G, v, w, **kwargs))
return L123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616"""Flow based cut algorithms"""
import itertools
import networkx as nx
# Define the default maximum flow function to use in all flow based# cut algorithms.from networkx.algorithms.flow import build_residual_network, edmonds_karp
from .utils import build_auxiliary_edge_connectivity, build_auxiliary_node_connectivity
default_flow_func = edmonds_karp
__all__ = [ "minimum_st_node_cut", "minimum_node_cut", "minimum_st_edge_cut", "minimum_edge_cut",]
@nx._dispatchable( graphs={"G": 0, "auxiliary?": 4}, preserve_edge_attrs={"auxiliary": {"capacity": float("inf")}}, preserve_graph_attrs={"auxiliary"},)def minimum_st_edge_cut(G, s, t, flow_func=None, auxiliary=None, residual=None): """Returns the edges of the cut-set of a minimum (s, t)-cut.
This function returns the set of edges of minimum cardinality that, if removed, would destroy all paths among source and target in G. Edge weights are not considered. See :meth:`minimum_cut` for computing minimum cuts considering edge weights.
Parameters ---------- G : NetworkX graph
s : node Source node for the flow.
t : node Sink node for the flow.
auxiliary : NetworkX DiGraph Auxiliary digraph to compute flow based node connectivity. It has to have a graph attribute called mapping with a dictionary mapping node names in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default value: None.
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See :meth:`node_connectivity` for details. The choice of the default function may change from version to version and should not be relied on. Default value: None.
residual : NetworkX DiGraph Residual network to compute maximum flow. If provided it will be reused instead of recreated. Default value: None.
Returns ------- cutset : set Set of edges that, if removed from the graph, will disconnect it.
See also -------- :meth:`minimum_cut` :meth:`minimum_node_cut` :meth:`minimum_edge_cut` :meth:`stoer_wagner` :meth:`node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path`
Examples -------- This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the connectivity package:
>>> from networkx.algorithms.connectivity import minimum_st_edge_cut
We use in this example the platonic icosahedral graph, which has edge connectivity 5.
>>> G = nx.icosahedral_graph() >>> len(minimum_st_edge_cut(G, 0, 6)) 5
If you need to compute local edge cuts on several pairs of nodes in the same graph, it is recommended that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity, and the residual network for the underlying maximum flow computation.
Example of how to compute local edge cuts among all pairs of nodes of the platonic icosahedral graph reusing the data structures.
>>> import itertools >>> # You also have to explicitly import the function for >>> # building the auxiliary digraph from the connectivity package >>> from networkx.algorithms.connectivity import build_auxiliary_edge_connectivity >>> H = build_auxiliary_edge_connectivity(G) >>> # And the function for building the residual network from the >>> # flow package >>> from networkx.algorithms.flow import build_residual_network >>> # Note that the auxiliary digraph has an edge attribute named capacity >>> R = build_residual_network(H, "capacity") >>> result = dict.fromkeys(G, dict()) >>> # Reuse the auxiliary digraph and the residual network by passing them >>> # as parameters >>> for u, v in itertools.combinations(G, 2): ... k = len(minimum_st_edge_cut(G, u, v, auxiliary=H, residual=R)) ... result[u][v] = k >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2)) True
You can also use alternative flow algorithms for computing edge cuts. For instance, in dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp` which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path >>> len(minimum_st_edge_cut(G, 0, 6, flow_func=shortest_augmenting_path)) 5
""" if flow_func is None: flow_func = default_flow_func
if auxiliary is None: H = build_auxiliary_edge_connectivity(G) else: H = auxiliary
kwargs = {"capacity": "capacity", "flow_func": flow_func, "residual": residual}
cut_value, partition = nx.minimum_cut(H, s, t, **kwargs) reachable, non_reachable = partition # Any edge in the original graph linking the two sets in the # partition is part of the edge cutset cutset = set() for u, nbrs in ((n, G[n]) for n in reachable): cutset.update((u, v) for v in nbrs if v in non_reachable)
return cutset
@nx._dispatchable( graphs={"G": 0, "auxiliary?": 4}, preserve_node_attrs={"auxiliary": {"id": None}}, preserve_graph_attrs={"auxiliary"},)def minimum_st_node_cut(G, s, t, flow_func=None, auxiliary=None, residual=None): r"""Returns a set of nodes of minimum cardinality that disconnect source from target in G.
This function returns the set of nodes of minimum cardinality that, if removed, would destroy all paths among source and target in G.
Parameters ---------- G : NetworkX graph
s : node Source node.
t : node Target node.
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None.
auxiliary : NetworkX DiGraph Auxiliary digraph to compute flow based node connectivity. It has to have a graph attribute called mapping with a dictionary mapping node names in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default value: None.
residual : NetworkX DiGraph Residual network to compute maximum flow. If provided it will be reused instead of recreated. Default value: None.
Returns ------- cutset : set Set of nodes that, if removed, would destroy all paths between source and target in G.
Returns an empty set if source and target are either in different components or are directly connected by an edge, as no node removal can destroy the path.
Examples -------- This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the connectivity package:
>>> from networkx.algorithms.connectivity import minimum_st_node_cut
We use in this example the platonic icosahedral graph, which has node connectivity 5.
>>> G = nx.icosahedral_graph() >>> len(minimum_st_node_cut(G, 0, 6)) 5
If you need to compute local st cuts between several pairs of nodes in the same graph, it is recommended that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity and node cuts, and the residual network for the underlying maximum flow computation.
Example of how to compute local st node cuts reusing the data structures:
>>> # You also have to explicitly import the function for >>> # building the auxiliary digraph from the connectivity package >>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity >>> H = build_auxiliary_node_connectivity(G) >>> # And the function for building the residual network from the >>> # flow package >>> from networkx.algorithms.flow import build_residual_network >>> # Note that the auxiliary digraph has an edge attribute named capacity >>> R = build_residual_network(H, "capacity") >>> # Reuse the auxiliary digraph and the residual network by passing them >>> # as parameters >>> len(minimum_st_node_cut(G, 0, 6, auxiliary=H, residual=R)) 5
You can also use alternative flow algorithms for computing minimum st node cuts. For instance, in dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp` which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path >>> len(minimum_st_node_cut(G, 0, 6, flow_func=shortest_augmenting_path)) 5
Notes ----- This is a flow based implementation of minimum node cut. The algorithm is based in solving a number of maximum flow computations to determine the capacity of the minimum cut on an auxiliary directed network that corresponds to the minimum node cut of G. It handles both directed and undirected graphs. This implementation is based on algorithm 11 in [1]_.
See also -------- :meth:`minimum_node_cut` :meth:`minimum_edge_cut` :meth:`stoer_wagner` :meth:`node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path`
References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
""" if auxiliary is None: H = build_auxiliary_node_connectivity(G) else: H = auxiliary
mapping = H.graph.get("mapping", None) if mapping is None: raise nx.NetworkXError("Invalid auxiliary digraph.") if G.has_edge(s, t) or G.has_edge(t, s): return set() kwargs = {"flow_func": flow_func, "residual": residual, "auxiliary": H}
# The edge cut in the auxiliary digraph corresponds to the node cut in the # original graph. edge_cut = minimum_st_edge_cut(H, f"{mapping[s]}B", f"{mapping[t]}A", **kwargs) # Each node in the original graph maps to two nodes of the auxiliary graph node_cut = {H.nodes[node]["id"] for edge in edge_cut for node in edge} return node_cut - {s, t}
@nx._dispatchabledef minimum_node_cut(G, s=None, t=None, flow_func=None): r"""Returns a set of nodes of minimum cardinality that disconnects G.
If source and target nodes are provided, this function returns the set of nodes of minimum cardinality that, if removed, would destroy all paths among source and target in G. If not, it returns a set of nodes of minimum cardinality that disconnects G.
Parameters ---------- G : NetworkX graph
s : node Source node. Optional. Default value: None.
t : node Target node. Optional. Default value: None.
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None.
Returns ------- cutset : set Set of nodes that, if removed, would disconnect G. If source and target nodes are provided, the set contains the nodes that if removed, would destroy all paths between source and target.
Examples -------- >>> # Platonic icosahedral graph has node connectivity 5 >>> G = nx.icosahedral_graph() >>> node_cut = nx.minimum_node_cut(G) >>> len(node_cut) 5
You can use alternative flow algorithms for the underlying maximum flow computation. In dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp`, which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path >>> node_cut == nx.minimum_node_cut(G, flow_func=shortest_augmenting_path) True
If you specify a pair of nodes (source and target) as parameters, this function returns a local st node cut.
>>> len(nx.minimum_node_cut(G, 3, 7)) 5
If you need to perform several local st cuts among different pairs of nodes on the same graph, it is recommended that you reuse the data structures used in the maximum flow computations. See :meth:`minimum_st_node_cut` for details.
Notes ----- This is a flow based implementation of minimum node cut. The algorithm is based in solving a number of maximum flow computations to determine the capacity of the minimum cut on an auxiliary directed network that corresponds to the minimum node cut of G. It handles both directed and undirected graphs. This implementation is based on algorithm 11 in [1]_.
See also -------- :meth:`minimum_st_node_cut` :meth:`minimum_cut` :meth:`minimum_edge_cut` :meth:`stoer_wagner` :meth:`node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path`
References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
""" if (s is not None and t is None) or (s is None and t is not None): raise nx.NetworkXError("Both source and target must be specified.")
# Local minimum node cut. if s is not None and t is not None: if s not in G: raise nx.NetworkXError(f"node {s} not in graph") if t not in G: raise nx.NetworkXError(f"node {t} not in graph") return minimum_st_node_cut(G, s, t, flow_func=flow_func)
# Global minimum node cut. # Analog to the algorithm 11 for global node connectivity in [1]. if G.is_directed(): if not nx.is_weakly_connected(G): raise nx.NetworkXError("Input graph is not connected") iter_func = itertools.permutations
def neighbors(v): return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
else: if not nx.is_connected(G): raise nx.NetworkXError("Input graph is not connected") iter_func = itertools.combinations neighbors = G.neighbors
# Reuse the auxiliary digraph and the residual network. H = build_auxiliary_node_connectivity(G) R = build_residual_network(H, "capacity") kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
# Choose a node with minimum degree. v = min(G, key=G.degree) # Initial node cutset is all neighbors of the node with minimum degree. min_cut = set(G[v]) # Compute st node cuts between v and all its non-neighbors nodes in G. for w in set(G) - set(neighbors(v)) - {v}: this_cut = minimum_st_node_cut(G, v, w, **kwargs) if len(min_cut) >= len(this_cut): min_cut = this_cut # Also for non adjacent pairs of neighbors of v. for x, y in iter_func(neighbors(v), 2): if y in G[x]: continue this_cut = minimum_st_node_cut(G, x, y, **kwargs) if len(min_cut) >= len(this_cut): min_cut = this_cut
return min_cut
@nx._dispatchabledef minimum_edge_cut(G, s=None, t=None, flow_func=None): r"""Returns a set of edges of minimum cardinality that disconnects G.
If source and target nodes are provided, this function returns the set of edges of minimum cardinality that, if removed, would break all paths among source and target in G. If not, it returns a set of edges of minimum cardinality that disconnects G.
Parameters ---------- G : NetworkX graph
s : node Source node. Optional. Default value: None.
t : node Target node. Optional. Default value: None.
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None.
Returns ------- cutset : set Set of edges that, if removed, would disconnect G. If source and target nodes are provided, the set contains the edges that if removed, would destroy all paths between source and target.
Examples -------- >>> # Platonic icosahedral graph has edge connectivity 5 >>> G = nx.icosahedral_graph() >>> len(nx.minimum_edge_cut(G)) 5
You can use alternative flow algorithms for the underlying maximum flow computation. In dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp`, which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path >>> len(nx.minimum_edge_cut(G, flow_func=shortest_augmenting_path)) 5
If you specify a pair of nodes (source and target) as parameters, this function returns the value of local edge connectivity.
>>> nx.edge_connectivity(G, 3, 7) 5
If you need to perform several local computations among different pairs of nodes on the same graph, it is recommended that you reuse the data structures used in the maximum flow computations. See :meth:`local_edge_connectivity` for details.
Notes ----- This is a flow based implementation of minimum edge cut. For undirected graphs the algorithm works by finding a 'small' dominating set of nodes of G (see algorithm 7 in [1]_) and computing the maximum flow between an arbitrary node in the dominating set and the rest of nodes in it. This is an implementation of algorithm 6 in [1]_. For directed graphs, the algorithm does n calls to the max flow function. The function raises an error if the directed graph is not weakly connected and returns an empty set if it is weakly connected. It is an implementation of algorithm 8 in [1]_.
See also -------- :meth:`minimum_st_edge_cut` :meth:`minimum_node_cut` :meth:`stoer_wagner` :meth:`node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path`
References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
""" if (s is not None and t is None) or (s is None and t is not None): raise nx.NetworkXError("Both source and target must be specified.")
# reuse auxiliary digraph and residual network H = build_auxiliary_edge_connectivity(G) R = build_residual_network(H, "capacity") kwargs = {"flow_func": flow_func, "residual": R, "auxiliary": H}
# Local minimum edge cut if s and t are not None if s is not None and t is not None: if s not in G: raise nx.NetworkXError(f"node {s} not in graph") if t not in G: raise nx.NetworkXError(f"node {t} not in graph") return minimum_st_edge_cut(H, s, t, **kwargs)
# Global minimum edge cut # Analog to the algorithm for global edge connectivity if G.is_directed(): # Based on algorithm 8 in [1] if not nx.is_weakly_connected(G): raise nx.NetworkXError("Input graph is not connected")
# Initial cutset is all edges of a node with minimum degree node = min(G, key=G.degree) min_cut = set(G.edges(node)) nodes = list(G) n = len(nodes) for i in range(n): try: this_cut = minimum_st_edge_cut(H, nodes[i], nodes[i + 1], **kwargs) if len(this_cut) <= len(min_cut): min_cut = this_cut except IndexError: # Last node! this_cut = minimum_st_edge_cut(H, nodes[i], nodes[0], **kwargs) if len(this_cut) <= len(min_cut): min_cut = this_cut
return min_cut
else: # undirected # Based on algorithm 6 in [1] if not nx.is_connected(G): raise nx.NetworkXError("Input graph is not connected")
# Initial cutset is all edges of a node with minimum degree node = min(G, key=G.degree) min_cut = set(G.edges(node)) # A dominating set is \lambda-covering # We need a dominating set with at least two nodes for node in G: D = nx.dominating_set(G, start_with=node) v = D.pop() if D: break else: # in complete graphs the dominating set will always be of one node # thus we return min_cut, which now contains the edges of a node # with minimum degree return min_cut for w in D: this_cut = minimum_st_edge_cut(H, v, w, **kwargs) if len(this_cut) <= len(min_cut): min_cut = this_cut
return min_cut123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408"""Flow based node and edge disjoint paths."""
from itertools import filterfalse as _filterfalse
import networkx as nx
# Define the default maximum flow function to use for the underlying# maximum flow computationsfrom networkx.algorithms.flow import ( edmonds_karp, preflow_push, shortest_augmenting_path,)from networkx.exception import NetworkXNoPath
# Functions to build auxiliary data structures.from .utils import build_auxiliary_edge_connectivity, build_auxiliary_node_connectivity
__all__ = ["edge_disjoint_paths", "node_disjoint_paths"]default_flow_func = edmonds_karp
@nx._dispatchable( graphs={"G": 0, "auxiliary?": 5}, preserve_edge_attrs={"auxiliary": {"capacity": float("inf")}},)def edge_disjoint_paths( G, s, t, flow_func=None, cutoff=None, auxiliary=None, residual=None): """Returns the edges disjoint paths between source and target.
Edge disjoint paths are paths that do not share any edge. The number of edge disjoint paths between source and target is equal to their edge connectivity.
Parameters ---------- G : NetworkX graph
s : node Source node for the flow.
t : node Sink node for the flow.
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. The choice of the default function may change from version to version and should not be relied on. Default value: None.
cutoff : integer or None (default: None) Maximum number of paths to yield. If specified, the maximum flow algorithm will terminate when the flow value reaches or exceeds the cutoff. This only works for flows that support the cutoff parameter (most do) and is ignored otherwise.
auxiliary : NetworkX DiGraph Auxiliary digraph to compute flow based edge connectivity. It has to have a graph attribute called mapping with a dictionary mapping node names in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default value: None.
residual : NetworkX DiGraph Residual network to compute maximum flow. If provided it will be reused instead of recreated. Default value: None.
Returns ------- paths : generator A generator of edge independent paths.
Raises ------ NetworkXNoPath If there is no path between source and target.
NetworkXError If source or target are not in the graph G.
See also -------- :meth:`node_disjoint_paths` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path`
Examples -------- We use in this example the platonic icosahedral graph, which has node edge connectivity 5, thus there are 5 edge disjoint paths between any pair of nodes.
>>> G = nx.icosahedral_graph() >>> len(list(nx.edge_disjoint_paths(G, 0, 6))) 5
If you need to compute edge disjoint paths on several pairs of nodes in the same graph, it is recommended that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity, and the residual network for the underlying maximum flow computation.
Example of how to compute edge disjoint paths among all pairs of nodes of the platonic icosahedral graph reusing the data structures.
>>> import itertools >>> # You also have to explicitly import the function for >>> # building the auxiliary digraph from the connectivity package >>> from networkx.algorithms.connectivity import build_auxiliary_edge_connectivity >>> H = build_auxiliary_edge_connectivity(G) >>> # And the function for building the residual network from the >>> # flow package >>> from networkx.algorithms.flow import build_residual_network >>> # Note that the auxiliary digraph has an edge attribute named capacity >>> R = build_residual_network(H, "capacity") >>> result = {n: {} for n in G} >>> # Reuse the auxiliary digraph and the residual network by passing them >>> # as arguments >>> for u, v in itertools.combinations(G, 2): ... k = len(list(nx.edge_disjoint_paths(G, u, v, auxiliary=H, residual=R))) ... result[u][v] = k >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2)) True
You can also use alternative flow algorithms for computing edge disjoint paths. For instance, in dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp` which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path >>> len(list(nx.edge_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path))) 5
Notes ----- This is a flow based implementation of edge disjoint paths. We compute the maximum flow between source and target on an auxiliary directed network. The saturated edges in the residual network after running the maximum flow algorithm correspond to edge disjoint paths between source and target in the original network. This function handles both directed and undirected graphs, and can use all flow algorithms from NetworkX flow package.
""" if s not in G: raise nx.NetworkXError(f"node {s} not in graph") if t not in G: raise nx.NetworkXError(f"node {t} not in graph")
if flow_func is None: flow_func = default_flow_func
if auxiliary is None: H = build_auxiliary_edge_connectivity(G) else: H = auxiliary
# Maximum possible edge disjoint paths possible = min(H.out_degree(s), H.in_degree(t)) if not possible: raise NetworkXNoPath
if cutoff is None: cutoff = possible else: cutoff = min(cutoff, possible)
# Compute maximum flow between source and target. Flow functions in # NetworkX return a residual network. kwargs = { "capacity": "capacity", "residual": residual, "cutoff": cutoff, "value_only": True, } if flow_func is preflow_push: del kwargs["cutoff"] if flow_func is shortest_augmenting_path: kwargs["two_phase"] = True R = flow_func(H, s, t, **kwargs)
if R.graph["flow_value"] == 0: raise NetworkXNoPath
# Saturated edges in the residual network form the edge disjoint paths # between source and target cutset = [ (u, v) for u, v, d in R.edges(data=True) if d["capacity"] == d["flow"] and d["flow"] > 0 ] # This is equivalent of what flow.utils.build_flow_dict returns, but # only for the nodes with saturated edges and without reporting 0 flows. flow_dict = {n: {} for edge in cutset for n in edge} for u, v in cutset: flow_dict[u][v] = 1
# Rebuild the edge disjoint paths from the flow dictionary. paths_found = 0 for v in list(flow_dict[s]): if paths_found >= cutoff: # preflow_push does not support cutoff: we have to # keep track of the paths founds and stop at cutoff. break path = [s] if v == t: path.append(v) yield path continue u = v while u != t: path.append(u) try: u, _ = flow_dict[u].popitem() except KeyError: break else: path.append(t) yield path paths_found += 1
@nx._dispatchable( graphs={"G": 0, "auxiliary?": 5}, preserve_node_attrs={"auxiliary": {"id": None}}, preserve_graph_attrs={"auxiliary"},)def node_disjoint_paths( G, s, t, flow_func=None, cutoff=None, auxiliary=None, residual=None): r"""Computes node disjoint paths between source and target.
Node disjoint paths are paths that only share their first and last nodes. The number of node independent paths between two nodes is equal to their local node connectivity.
Parameters ---------- G : NetworkX graph
s : node Source node.
t : node Target node.
flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None.
cutoff : integer or None (default: None) Maximum number of paths to yield. If specified, the maximum flow algorithm will terminate when the flow value reaches or exceeds the cutoff. This only works for flows that support the cutoff parameter (most do) and is ignored otherwise.
auxiliary : NetworkX DiGraph Auxiliary digraph to compute flow based node connectivity. It has to have a graph attribute called mapping with a dictionary mapping node names in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default value: None.
residual : NetworkX DiGraph Residual network to compute maximum flow. If provided it will be reused instead of recreated. Default value: None.
Returns ------- paths : generator Generator of node disjoint paths.
Raises ------ NetworkXNoPath If there is no path between source and target.
NetworkXError If source or target are not in the graph G.
Examples -------- We use in this example the platonic icosahedral graph, which has node connectivity 5, thus there are 5 node disjoint paths between any pair of non neighbor nodes.
>>> G = nx.icosahedral_graph() >>> len(list(nx.node_disjoint_paths(G, 0, 6))) 5
If you need to compute node disjoint paths between several pairs of nodes in the same graph, it is recommended that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity and node cuts, and the residual network for the underlying maximum flow computation.
Example of how to compute node disjoint paths reusing the data structures:
>>> # You also have to explicitly import the function for >>> # building the auxiliary digraph from the connectivity package >>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity >>> H = build_auxiliary_node_connectivity(G) >>> # And the function for building the residual network from the >>> # flow package >>> from networkx.algorithms.flow import build_residual_network >>> # Note that the auxiliary digraph has an edge attribute named capacity >>> R = build_residual_network(H, "capacity") >>> # Reuse the auxiliary digraph and the residual network by passing them >>> # as arguments >>> len(list(nx.node_disjoint_paths(G, 0, 6, auxiliary=H, residual=R))) 5
You can also use alternative flow algorithms for computing node disjoint paths. For instance, in dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp` which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path >>> len(list(nx.node_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path))) 5
Notes ----- This is a flow based implementation of node disjoint paths. We compute the maximum flow between source and target on an auxiliary directed network. The saturated edges in the residual network after running the maximum flow algorithm correspond to node disjoint paths between source and target in the original network. This function handles both directed and undirected graphs, and can use all flow algorithms from NetworkX flow package.
See also -------- :meth:`edge_disjoint_paths` :meth:`node_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path`
""" if s not in G: raise nx.NetworkXError(f"node {s} not in graph") if t not in G: raise nx.NetworkXError(f"node {t} not in graph")
if auxiliary is None: H = build_auxiliary_node_connectivity(G) else: H = auxiliary
mapping = H.graph.get("mapping", None) if mapping is None: raise nx.NetworkXError("Invalid auxiliary digraph.")
# Maximum possible edge disjoint paths possible = min(H.out_degree(f"{mapping[s]}B"), H.in_degree(f"{mapping[t]}A")) if not possible: raise NetworkXNoPath
if cutoff is None: cutoff = possible else: cutoff = min(cutoff, possible)
kwargs = { "flow_func": flow_func, "residual": residual, "auxiliary": H, "cutoff": cutoff, }
# The edge disjoint paths in the auxiliary digraph correspond to the node # disjoint paths in the original graph. paths_edges = edge_disjoint_paths(H, f"{mapping[s]}B", f"{mapping[t]}A", **kwargs) for path in paths_edges: # Each node in the original graph maps to two nodes in auxiliary graph yield list(_unique_everseen(H.nodes[node]["id"] for node in path))
def _unique_everseen(iterable): # Adapted from https://docs.python.org/3/library/itertools.html examples "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D seen = set() seen_add = seen.add for element in _filterfalse(seen.__contains__, iterable): seen_add(element) yield elementlib/python3.12/site-packages/networkx/algorithms/__init__.pyAdded+134
lib/python3.12/site-packages/networkx/algorithms/assortativity/__init__.pyAdded+5
lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/connectivity.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/correlation.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/mixing.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/neighbor_degree.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/__pycache__/pairs.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/connectivity.pyAdded+122
lib/python3.12/site-packages/networkx/algorithms/assortativity/correlation.pyAdded+302
lib/python3.12/site-packages/networkx/algorithms/assortativity/mixing.pyAdded+255
lib/python3.12/site-packages/networkx/algorithms/assortativity/neighbor_degree.pyAdded+160
lib/python3.12/site-packages/networkx/algorithms/assortativity/pairs.pyAdded+127
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__init__.pyAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/base_test.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_connectivity.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_correlation.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_mixing.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_neighbor_degree.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_pairs.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/base_test.pyAdded+81
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/test_connectivity.pyAdded+143
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/test_correlation.pyAdded+122
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/test_mixing.pyAdded+174
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/test_neighbor_degree.pyAdded+107
lib/python3.12/site-packages/networkx/algorithms/assortativity/tests/test_pairs.pyAdded+87
lib/python3.12/site-packages/networkx/algorithms/asteroidal.pyAdded+164
lib/python3.12/site-packages/networkx/algorithms/boundary.pyAdded+168
lib/python3.12/site-packages/networkx/algorithms/bridges.pyAdded+205
lib/python3.12/site-packages/networkx/algorithms/broadcasting.pyAdded+164
lib/python3.12/site-packages/networkx/algorithms/chains.pyAdded+172
lib/python3.12/site-packages/networkx/algorithms/chordal.pyAdded+443
lib/python3.12/site-packages/networkx/algorithms/clique.pyAdded+818
lib/python3.12/site-packages/networkx/algorithms/cluster.pyAdded+732
lib/python3.12/site-packages/networkx/algorithms/communicability_alg.pyAdded+163
lib/python3.12/site-packages/networkx/algorithms/connectivity/__init__.pyAdded+11
lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/connectivity.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/cuts.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/disjoint_paths.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/edge_augmentation.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/edge_kcomponents.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/kcomponents.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/kcutsets.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/stoerwagner.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/connectivity/__pycache__/utils.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/connectivity/connectivity.pyAdded+811
lib/python3.12/site-packages/networkx/algorithms/connectivity/cuts.pyAdded+616
lib/python3.12/site-packages/networkx/algorithms/connectivity/disjoint_paths.pyAdded+408