Upload folder using huggingface_hub (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- .venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_percolation_centrality.pyAdded+87
- .venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_reaching.pyAdded+140
- .venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_second_order_centrality.pyAdded+82
- .venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_subgraph.pyAdded+110
- .venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_trophic.pyAdded+302
- .venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_voterank.pyAdded+64
- .venv/lib/python3.12/site-packages/networkx/algorithms/centrality/trophic.pyAdded+181
- .venv/lib/python3.12/site-packages/networkx/algorithms/centrality/voterank_alg.pyAdded+95
- .venv/lib/python3.12/site-packages/networkx/algorithms/chains.pyAdded+172
- .venv/lib/python3.12/site-packages/networkx/algorithms/chordal.pyAdded+443
- .venv/lib/python3.12/site-packages/networkx/algorithms/clique.pyAdded+818
- .venv/lib/python3.12/site-packages/networkx/algorithms/cluster.pyAdded+732
- .venv/lib/python3.12/site-packages/networkx/algorithms/coloring/__init__.pyAdded+4
- .venv/lib/python3.12/site-packages/networkx/algorithms/coloring/equitable_coloring.pyAdded+505
- .venv/lib/python3.12/site-packages/networkx/algorithms/coloring/greedy_coloring.pyAdded+565
- .venv/lib/python3.12/site-packages/networkx/algorithms/coloring/tests/__init__.pyAdded
- .venv/lib/python3.12/site-packages/networkx/algorithms/coloring/tests/test_coloring.pyAdded+863
- .venv/lib/python3.12/site-packages/networkx/algorithms/communicability_alg.pyAdded+163
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/__init__.pyAdded+28
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/asyn_fluid.pyAdded+153
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/bipartitions.pyAdded+354
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/centrality.pyAdded+171
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/community_utils.pyAdded+30
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/divisive.pyAdded+216
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/kclique.pyAdded+79
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/label_propagation.pyAdded+338
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/leiden.pyAdded+162
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/local.pyAdded+220
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/louvain.pyAdded+384
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/lukes.pyAdded+227
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/modularity_max.pyAdded+452
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/quality.pyAdded+347
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/__init__.pyAdded
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_asyn_fluid.pyAdded+147
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_bipartitions.pyAdded+157
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_centrality.pyAdded+85
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_divisive.pyAdded+106
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_kclique.pyAdded+91
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_label_propagation.pyAdded+241
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_leiden.pyAdded+138
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_local.pyAdded+76
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_louvain.pyAdded+264
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_lukes.pyAdded+152
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_modularity_max.pyAdded+340
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_quality.pyAdded+139
- .venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_utils.pyAdded+26
- .venv/lib/python3.12/site-packages/networkx/algorithms/components/__init__.pyAdded+6
- .venv/lib/python3.12/site-packages/networkx/algorithms/components/attracting.pyAdded+115
- .venv/lib/python3.12/site-packages/networkx/algorithms/components/biconnected.pyAdded+394
52 unmodified lines5354555652 unmodified lines.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/hf_api.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/mpmath/__pycache__/function_docs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/multidict/_multidict.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/networkx/drawing/tests/baseline/test_display_complex.png filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687import pytest
import networkx as nx
def example1a_G(): G = nx.Graph() G.add_node(1, percolation=0.1) G.add_node(2, percolation=0.2) G.add_node(3, percolation=0.2) G.add_node(4, percolation=0.2) G.add_node(5, percolation=0.3) G.add_node(6, percolation=0.2) G.add_node(7, percolation=0.5) G.add_node(8, percolation=0.5) G.add_edges_from([(1, 4), (2, 4), (3, 4), (4, 5), (5, 6), (6, 7), (6, 8)]) return G
def example1b_G(): G = nx.Graph() G.add_node(1, percolation=0.3) G.add_node(2, percolation=0.5) G.add_node(3, percolation=0.5) G.add_node(4, percolation=0.2) G.add_node(5, percolation=0.3) G.add_node(6, percolation=0.2) G.add_node(7, percolation=0.1) G.add_node(8, percolation=0.1) G.add_edges_from([(1, 4), (2, 4), (3, 4), (4, 5), (5, 6), (6, 7), (6, 8)]) return G
def test_percolation_example1a(): """percolation centrality: example 1a""" G = example1a_G() p = nx.percolation_centrality(G) p_answer = {4: 0.625, 6: 0.667} for n, k in p_answer.items(): assert p[n] == pytest.approx(k, abs=1e-3)
def test_percolation_example1b(): """percolation centrality: example 1a""" G = example1b_G() p = nx.percolation_centrality(G) p_answer = {4: 0.825, 6: 0.4} for n, k in p_answer.items(): assert p[n] == pytest.approx(k, abs=1e-3)
def test_converge_to_betweenness(): """percolation centrality: should converge to betweenness centrality when all nodes are percolated the same""" # taken from betweenness test test_florentine_families_graph G = nx.florentine_families_graph() b_answer = { "Acciaiuoli": 0.000, "Albizzi": 0.212, "Barbadori": 0.093, "Bischeri": 0.104, "Castellani": 0.055, "Ginori": 0.000, "Guadagni": 0.255, "Lamberteschi": 0.000, "Medici": 0.522, "Pazzi": 0.000, "Peruzzi": 0.022, "Ridolfi": 0.114, "Salviati": 0.143, "Strozzi": 0.103, "Tornabuoni": 0.092, }
# If no initial state is provided, state for # every node defaults to 1 p_answer = nx.percolation_centrality(G) assert p_answer == pytest.approx(b_answer, abs=1e-3)
p_states = {k: 0.3 for k, v in b_answer.items()} p_answer = nx.percolation_centrality(G, states=p_states) assert p_answer == pytest.approx(b_answer, abs=1e-3)
def test_default_percolation(): G = nx.erdos_renyi_graph(42, 0.42, seed=42) assert nx.percolation_centrality(G) == pytest.approx(nx.betweenness_centrality(G))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Unit tests for the :mod:`networkx.algorithms.centrality.reaching` module."""
import pytest
import networkx as nx
class TestGlobalReachingCentrality: """Unit tests for the global reaching centrality function."""
def test_non_positive_weights(self): with pytest.raises(nx.NetworkXError): G = nx.DiGraph() nx.global_reaching_centrality(G, weight="weight")
def test_negatively_weighted(self): with pytest.raises(nx.NetworkXError): G = nx.Graph() G.add_weighted_edges_from([(0, 1, -2), (1, 2, +1)]) nx.global_reaching_centrality(G, weight="weight")
def test_directed_star(self): G = nx.DiGraph() G.add_weighted_edges_from([(1, 2, 0.5), (1, 3, 0.5)]) grc = nx.global_reaching_centrality assert grc(G, normalized=False, weight="weight") == 0.5 assert grc(G) == 1
def test_undirected_unweighted_star(self): G = nx.star_graph(2) grc = nx.global_reaching_centrality assert grc(G, normalized=False, weight=None) == 0.25
def test_undirected_weighted_star(self): G = nx.Graph() G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2)]) grc = nx.global_reaching_centrality assert grc(G, normalized=False, weight="weight") == 0.375
def test_cycle_directed_unweighted(self): G = nx.DiGraph() G.add_edge(1, 2) G.add_edge(2, 1) assert nx.global_reaching_centrality(G, weight=None) == 0
def test_cycle_undirected_unweighted(self): G = nx.Graph() G.add_edge(1, 2) assert nx.global_reaching_centrality(G, weight=None) == 0
def test_cycle_directed_weighted(self): G = nx.DiGraph() G.add_weighted_edges_from([(1, 2, 1), (2, 1, 1)]) assert nx.global_reaching_centrality(G) == 0
def test_cycle_undirected_weighted(self): G = nx.Graph() G.add_edge(1, 2, weight=1) grc = nx.global_reaching_centrality assert grc(G, normalized=False) == 0
def test_directed_weighted(self): G = nx.DiGraph() G.add_edge("A", "B", weight=5) G.add_edge("B", "C", weight=1) G.add_edge("B", "D", weight=0.25) G.add_edge("D", "E", weight=1)
denom = len(G) - 1 A_local = sum([5, 3, 2.625, 2.0833333333333]) / denom B_local = sum([1, 0.25, 0.625]) / denom C_local = 0 D_local = sum([1]) / denom E_local = 0
local_reach_ctrs = [A_local, C_local, B_local, D_local, E_local] max_local = max(local_reach_ctrs) expected = sum(max_local - lrc for lrc in local_reach_ctrs) / denom grc = nx.global_reaching_centrality actual = grc(G, normalized=False, weight="weight") assert expected == pytest.approx(actual, abs=1e-7)
def test_single_node_with_cycle(self): G = nx.DiGraph([(1, 1)]) with pytest.raises(nx.NetworkXError, match="local_reaching_centrality"): nx.global_reaching_centrality(G)
def test_single_node_with_weighted_cycle(self): G = nx.DiGraph() G.add_weighted_edges_from([(1, 1, 2)]) with pytest.raises(nx.NetworkXError, match="local_reaching_centrality"): nx.global_reaching_centrality(G, weight="weight")
class TestLocalReachingCentrality: """Unit tests for the local reaching centrality function."""
def test_non_positive_weights(self): with pytest.raises(nx.NetworkXError): G = nx.DiGraph() G.add_weighted_edges_from([(0, 1, 0)]) nx.local_reaching_centrality(G, 0, weight="weight")
def test_negatively_weighted(self): with pytest.raises(nx.NetworkXError): G = nx.Graph() G.add_weighted_edges_from([(0, 1, -2), (1, 2, +1)]) nx.local_reaching_centrality(G, 0, weight="weight")
def test_undirected_unweighted_star(self): G = nx.star_graph(2) grc = nx.local_reaching_centrality assert grc(G, 1, weight=None, normalized=False) == 0.75
def test_undirected_weighted_star(self): G = nx.Graph() G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2)]) centrality = nx.local_reaching_centrality( G, 1, normalized=False, weight="weight" ) assert centrality == 1.5
def test_undirected_weighted_normalized(self): G = nx.Graph() G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2)]) centrality = nx.local_reaching_centrality( G, 1, normalized=True, weight="weight" ) assert centrality == 1.0
def test_single_node_with_cycle(self): G = nx.DiGraph([(1, 1)]) with pytest.raises(nx.NetworkXError, match="local_reaching_centrality"): nx.local_reaching_centrality(G, 1)
def test_single_node_with_weighted_cycle(self): G = nx.DiGraph() G.add_weighted_edges_from([(1, 1, 2)]) with pytest.raises(nx.NetworkXError, match="local_reaching_centrality"): nx.local_reaching_centrality(G, 1, weight="weight")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""Tests for second order centrality."""
import pytest
pytest.importorskip("numpy")pytest.importorskip("scipy")
import networkx as nx
def test_empty(): with pytest.raises(nx.NetworkXException): G = nx.empty_graph() nx.second_order_centrality(G)
def test_non_connected(): with pytest.raises(nx.NetworkXException): G = nx.Graph() G.add_node(0) G.add_node(1) nx.second_order_centrality(G)
def test_non_negative_edge_weights(): with pytest.raises(nx.NetworkXException): G = nx.path_graph(2) G.add_edge(0, 1, weight=-1) nx.second_order_centrality(G)
def test_weight_attribute(): G = nx.Graph() G.add_weighted_edges_from([(0, 1, 1.0), (1, 2, 3.5)], weight="w") expected = {0: 3.431, 1: 3.082, 2: 5.612} b = nx.second_order_centrality(G, weight="w")
for n in sorted(G): assert b[n] == pytest.approx(expected[n], abs=1e-2)
def test_one_node_graph(): """Second order centrality: single node""" G = nx.Graph() G.add_node(0) G.add_edge(0, 0) assert nx.second_order_centrality(G)[0] == 0
def test_P3(): """Second order centrality: line graph, as defined in paper""" G = nx.path_graph(3) b_answer = {0: 3.741, 1: 1.414, 2: 3.741}
b = nx.second_order_centrality(G)
for n in sorted(G): assert b[n] == pytest.approx(b_answer[n], abs=1e-2)
def test_K3(): """Second order centrality: complete graph, as defined in paper""" G = nx.complete_graph(3) b_answer = {0: 1.414, 1: 1.414, 2: 1.414}
b = nx.second_order_centrality(G)
for n in sorted(G): assert b[n] == pytest.approx(b_answer[n], abs=1e-2)
def test_ring_graph(): """Second order centrality: ring graph, as defined in paper""" G = nx.cycle_graph(5) b_answer = {0: 4.472, 1: 4.472, 2: 4.472, 3: 4.472, 4: 4.472}
b = nx.second_order_centrality(G)
for n in sorted(G): assert b[n] == pytest.approx(b_answer[n], abs=1e-2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110import pytest
pytest.importorskip("numpy")pytest.importorskip("scipy")
import networkx as nxfrom networkx.algorithms.centrality.subgraph_alg import ( communicability_betweenness_centrality, estrada_index, subgraph_centrality, subgraph_centrality_exp,)
class TestSubgraph: def test_subgraph_centrality(self): answer = {0: 1.5430806348152433, 1: 1.5430806348152433} result = subgraph_centrality(nx.path_graph(2)) for k, v in result.items(): assert answer[k] == pytest.approx(v, abs=1e-7)
answer1 = { "1": 1.6445956054135658, "Albert": 2.4368257358712189, "Aric": 2.4368257358712193, "Dan": 3.1306328496328168, "Franck": 2.3876142275231915, } G1 = nx.Graph( [ ("Franck", "Aric"), ("Aric", "Dan"), ("Dan", "Albert"), ("Albert", "Franck"), ("Dan", "1"), ("Franck", "Albert"), ] ) result1 = subgraph_centrality(G1) for k, v in result1.items(): assert answer1[k] == pytest.approx(v, abs=1e-7) result1 = subgraph_centrality_exp(G1) for k, v in result1.items(): assert answer1[k] == pytest.approx(v, abs=1e-7)
def test_subgraph_centrality_big_graph(self): g199 = nx.complete_graph(199) g200 = nx.complete_graph(200)
comm199 = nx.subgraph_centrality(g199) comm199_exp = nx.subgraph_centrality_exp(g199)
comm200 = nx.subgraph_centrality(g200) comm200_exp = nx.subgraph_centrality_exp(g200)
def test_communicability_betweenness_centrality_small(self): result = communicability_betweenness_centrality(nx.path_graph(2)) assert result == {0: 0, 1: 0}
result = communicability_betweenness_centrality(nx.path_graph(1)) assert result == {0: 0}
result = communicability_betweenness_centrality(nx.path_graph(0)) assert result == {}
answer = {0: 0.1411224421177313, 1: 1.0, 2: 0.1411224421177313} result = communicability_betweenness_centrality(nx.path_graph(3)) for k, v in result.items(): assert answer[k] == pytest.approx(v, abs=1e-7)
result = communicability_betweenness_centrality(nx.complete_graph(3)) for k, v in result.items(): assert 0.49786143366223296 == pytest.approx(v, abs=1e-7)
def test_communicability_betweenness_centrality(self): answer = { 0: 0.07017447951484615, 1: 0.71565598701107991, 2: 0.71565598701107991, 3: 0.07017447951484615, } result = communicability_betweenness_centrality(nx.path_graph(4)) for k, v in result.items(): assert answer[k] == pytest.approx(v, abs=1e-7)
answer1 = { "1": 0.060039074193949521, "Albert": 0.315470761661372, "Aric": 0.31547076166137211, "Dan": 0.68297778678316201, "Franck": 0.21977926617449497, } G1 = nx.Graph( [ ("Franck", "Aric"), ("Aric", "Dan"), ("Dan", "Albert"), ("Albert", "Franck"), ("Dan", "1"), ("Franck", "Albert"), ] ) result1 = communicability_betweenness_centrality(G1) for k, v in result1.items(): assert answer1[k] == pytest.approx(v, abs=1e-7)
def test_estrada_index(self): answer = 1041.2470334195475 result = estrada_index(nx.karate_club_graph()) assert answer == pytest.approx(result, abs=1e-7)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302"""Test trophic levels, trophic differences and trophic coherence"""
import pytest
import networkx as nx
np = pytest.importorskip("numpy")pytest.importorskip("scipy")
def test_trophic_levels(): """Trivial example""" G = nx.DiGraph() G.add_edge("a", "b") G.add_edge("b", "c")
d = nx.trophic_levels(G) assert d == {"a": 1, "b": 2, "c": 3}
def test_trophic_levels_levine(): """Example from Figure 5 in Stephen Levine (1980) J. theor. Biol. 83, 195-207 """ S = nx.DiGraph() S.add_edge(1, 2, weight=1.0) S.add_edge(1, 3, weight=0.2) S.add_edge(1, 4, weight=0.8) S.add_edge(2, 3, weight=0.2) S.add_edge(2, 5, weight=0.3) S.add_edge(4, 3, weight=0.6) S.add_edge(4, 5, weight=0.7) S.add_edge(5, 4, weight=0.2)
# save copy for later, test intermediate implementation details first S2 = S.copy()
# drop nodes of in-degree zero z = [nid for nid, d in S.in_degree if d == 0] for nid in z: S.remove_node(nid)
# find adjacency matrix q = nx.linalg.graphmatrix.adjacency_matrix(S).T
# fmt: off expected_q = np.array([ [0, 0, 0., 0], [0.2, 0, 0.6, 0], [0, 0, 0, 0.2], [0.3, 0, 0.7, 0] ]) # fmt: on assert np.array_equal(q.todense(), expected_q)
# must be square, size of number of nodes assert len(q.shape) == 2 assert q.shape[0] == q.shape[1] assert q.shape[0] == len(S)
nn = q.shape[0]
i = np.eye(nn) n = np.linalg.inv(i - q) y = np.asarray(n) @ np.ones(nn)
expected_y = np.array([1, 2.07906977, 1.46511628, 2.3255814]) assert np.allclose(y, expected_y)
expected_d = {1: 1, 2: 2, 3: 3.07906977, 4: 2.46511628, 5: 3.3255814}
d = nx.trophic_levels(S2)
for nid, level in d.items(): expected_level = expected_d[nid] assert expected_level == pytest.approx(level, abs=1e-7)
def test_trophic_levels_simple(): matrix_a = np.array([[0, 0], [1, 0]]) G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph) d = nx.trophic_levels(G) assert d[0] == pytest.approx(2, abs=1e-7) assert d[1] == pytest.approx(1, abs=1e-7)
def test_trophic_levels_more_complex(): # fmt: off matrix = np.array([ [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0] ]) # fmt: on G = nx.from_numpy_array(matrix, create_using=nx.DiGraph) d = nx.trophic_levels(G) expected_result = [1, 2, 3, 4] for ind in range(4): assert d[ind] == pytest.approx(expected_result[ind], abs=1e-7)
# fmt: off matrix = np.array([ [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0] ]) # fmt: on G = nx.from_numpy_array(matrix, create_using=nx.DiGraph) d = nx.trophic_levels(G)
expected_result = [1, 2, 2.5, 3.25] for ind in range(4): assert d[ind] == pytest.approx(expected_result[ind], abs=1e-7)
def test_trophic_levels_even_more_complex(): # fmt: off # Another, bigger matrix matrix = np.array([ [0, 0, 0, 0, 0], [0, 1, 0, 1, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 1, 0] ]) # Generated this linear system using pen and paper: K = np.array([ [1, 0, -1, 0, 0], [0, 0.5, 0, -0.5, 0], [0, 0, 1, 0, 0], [0, -0.5, 0, 1, -0.5], [0, 0, 0, 0, 1], ]) # fmt: on result_1 = np.ravel(np.linalg.inv(K) @ np.ones(5)) G = nx.from_numpy_array(matrix, create_using=nx.DiGraph) result_2 = nx.trophic_levels(G)
for ind in range(5): assert result_1[ind] == pytest.approx(result_2[ind], abs=1e-7)
def test_trophic_levels_singular_matrix(): """Should raise an error with graphs with only non-basal nodes""" matrix = np.identity(4) G = nx.from_numpy_array(matrix, create_using=nx.DiGraph) with pytest.raises(nx.NetworkXError, match="no basal nodes"): nx.trophic_levels(G)
def test_trophic_levels_singular_with_basal(): """Should fail to compute if there are any parts of the graph which are not reachable from any basal node (with in-degree zero). """ G = nx.DiGraph() # a has in-degree zero G.add_edge("a", "b")
# b is one level above a, c and d G.add_edge("c", "b") G.add_edge("d", "b")
# c and d form a loop, neither are reachable from a G.add_edge("c", "d") G.add_edge("d", "c")
with pytest.raises(nx.NetworkXError) as e: nx.trophic_levels(G) msg = ( "Trophic levels are only defined for graphs where every node " + "has a path from a basal node (basal nodes are nodes with no " + "incoming edges)." ) assert msg in str(e.value)
# if self-loops are allowed, smaller example: G = nx.DiGraph() G.add_edge("a", "b") # a has in-degree zero G.add_edge("c", "b") # b is one level above a and c G.add_edge("c", "c") # c has a self-loop with pytest.raises(nx.NetworkXError) as e: nx.trophic_levels(G) msg = ( "Trophic levels are only defined for graphs where every node " + "has a path from a basal node (basal nodes are nodes with no " + "incoming edges)." ) assert msg in str(e.value)
def test_trophic_differences(): matrix_a = np.array([[0, 1], [0, 0]]) G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph) diffs = nx.trophic_differences(G) assert diffs[(0, 1)] == pytest.approx(1, abs=1e-7)
# fmt: off matrix_b = np.array([ [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0] ]) # fmt: on G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph) diffs = nx.trophic_differences(G)
assert diffs[(0, 1)] == pytest.approx(1, abs=1e-7) assert diffs[(0, 2)] == pytest.approx(1.5, abs=1e-7) assert diffs[(1, 2)] == pytest.approx(0.5, abs=1e-7) assert diffs[(1, 3)] == pytest.approx(1.25, abs=1e-7) assert diffs[(2, 3)] == pytest.approx(0.75, abs=1e-7)
def test_trophic_incoherence_parameter_no_cannibalism(): matrix_a = np.array([[0, 1], [0, 0]]) G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph) q = nx.trophic_incoherence_parameter(G, cannibalism=False) assert q == pytest.approx(0, abs=1e-7)
# fmt: off matrix_b = np.array([ [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0] ]) # fmt: on G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph) q = nx.trophic_incoherence_parameter(G, cannibalism=False) assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
# fmt: off matrix_c = np.array([ [0, 1, 1, 0], [0, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1] ]) # fmt: on G = nx.from_numpy_array(matrix_c, create_using=nx.DiGraph) q = nx.trophic_incoherence_parameter(G, cannibalism=False) # Ignore the -link assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
# no self-loops case # fmt: off matrix_d = np.array([ [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0] ]) # fmt: on G = nx.from_numpy_array(matrix_d, create_using=nx.DiGraph) q = nx.trophic_incoherence_parameter(G, cannibalism=False) # Ignore the -link assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
def test_trophic_incoherence_parameter_cannibalism(): matrix_a = np.array([[0, 1], [0, 0]]) G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph) q = nx.trophic_incoherence_parameter(G, cannibalism=True) assert q == pytest.approx(0, abs=1e-7)
# fmt: off matrix_b = np.array([ [0, 0, 0, 0, 0], [0, 1, 0, 1, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 1, 0] ]) # fmt: on G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph) q = nx.trophic_incoherence_parameter(G, cannibalism=True) assert q == pytest.approx(2, abs=1e-7)
# fmt: off matrix_c = np.array([ [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0] ]) # fmt: on G = nx.from_numpy_array(matrix_c, create_using=nx.DiGraph) q = nx.trophic_incoherence_parameter(G, cannibalism=True) # Ignore the -link assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
def test_no_basal_node(): G = nx.DiGraph([(1, 2), (2, 3), (3, 1)]) # No basal node, should raise an error with pytest.raises(nx.NetworkXError, match="no basal node"): nx.trophic_levels(G) G.add_node(4) # add basal node, but not connected with pytest.raises(nx.NetworkXError, match="every node .* path from a basal node"): nx.trophic_levels(G)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Unit tests for VoteRank."""
import networkx as nx
class TestVoteRankCentrality: # Example Graph present in reference paper def test_voterank_centrality_1(self): G = nx.Graph() G.add_edges_from( [ (7, 8), (7, 5), (7, 9), (5, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 6), (2, 6), (3, 6), (4, 6), ] ) assert [0, 7, 6] == nx.voterank(G)
def test_voterank_emptygraph(self): G = nx.Graph() assert [] == nx.voterank(G)
# Graph unit test def test_voterank_centrality_2(self): G = nx.florentine_families_graph() d = nx.voterank(G, 4) exact = ["Medici", "Strozzi", "Guadagni", "Castellani"] assert exact == d
# DiGraph unit test def test_voterank_centrality_3(self): G = nx.gnc_graph(10, seed=7) d = nx.voterank(G, 4) exact = [3, 6, 8] assert exact == d
# MultiGraph unit test def test_voterank_centrality_4(self): G = nx.MultiGraph() G.add_edges_from( [(0, 1), (0, 1), (1, 2), (2, 5), (2, 5), (5, 6), (5, 6), (2, 4), (4, 3)] ) exact = [2, 1, 5, 4] assert exact == nx.voterank(G)
# MultiDiGraph unit test def test_voterank_centrality_5(self): G = nx.MultiDiGraph() G.add_edges_from( [(0, 1), (0, 1), (1, 2), (2, 5), (2, 5), (5, 6), (5, 6), (2, 4), (4, 3)] ) exact = [2, 0, 5, 4] assert exact == nx.voterank(G)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""Trophic levels"""
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = ["trophic_levels", "trophic_differences", "trophic_incoherence_parameter"]
@not_implemented_for("undirected")@nx._dispatchable(edge_attrs="weight")def trophic_levels(G, weight="weight"): r"""Compute the trophic levels of nodes.
The trophic level of a node $i$ is
.. math::
s_i = 1 + \frac{1}{k^{in}_i} \sum_{j} a_{ij} s_j
where $k^{in}_i$ is the in-degree of i
.. math::
k^{in}_i = \sum_{j} a_{ij}
and nodes with $k^{in}_i = 0$ have $s_i = 1$ by convention.
These are calculated using the method outlined in Levine [1]_.
Parameters ---------- G : DiGraph A directed networkx graph
Returns ------- nodes : dict Dictionary of nodes with trophic level as the value.
References ---------- .. [1] Stephen Levine (1980) J. theor. Biol. 83, 195-207 """
basal_nodes = [n for n, deg in G.in_degree if deg == 0] if not basal_nodes: raise nx.NetworkXError( "This graph has no basal nodes (nodes with no incoming edges)." "Trophic levels are not defined without at least one basal node." )
reachable_nodes = { node for layer in nx.bfs_layers(G, sources=basal_nodes) for node in layer }
if len(reachable_nodes) != len(G.nodes): raise nx.NetworkXError( "Trophic levels are only defined for graphs where every node has a path " "from a basal node (basal nodes are nodes with no incoming edges)." )
import numpy as np
# find adjacency matrix a = nx.adjacency_matrix(G, weight=weight).T.toarray()
# drop rows/columns where in-degree is zero rowsum = np.sum(a, axis=1) p = a[rowsum != 0][:, rowsum != 0] # normalise so sum of in-degree weights is 1 along each row p = p / rowsum[rowsum != 0][:, np.newaxis]
# calculate trophic levels nn = p.shape[0] i = np.eye(nn) try: n = np.linalg.inv(i - p) except np.linalg.LinAlgError as err: # LinAlgError is raised when there is a non-basal node msg = ( "Trophic levels are only defined for graphs where every " + "node has a path from a basal node (basal nodes are nodes " + "with no incoming edges)." ) raise nx.NetworkXError(msg) from err y = n.sum(axis=1) + 1
levels = {}
# all nodes with in-degree zero have trophic level == 1 zero_node_ids = (node_id for node_id, degree in G.in_degree if degree == 0) for node_id in zero_node_ids: levels[node_id] = 1
# all other nodes have levels as calculated nonzero_node_ids = (node_id for node_id, degree in G.in_degree if degree != 0) for i, node_id in enumerate(nonzero_node_ids): levels[node_id] = y.item(i)
return levels
@not_implemented_for("undirected")@nx._dispatchable(edge_attrs="weight")def trophic_differences(G, weight="weight"): r"""Compute the trophic differences of the edges of a directed graph.
The trophic difference $x_ij$ for each edge is defined in Johnson et al. [1]_ as:
.. math:: x_ij = s_j - s_i
Where $s_i$ is the trophic level of node $i$.
Parameters ---------- G : DiGraph A directed networkx graph
Returns ------- diffs : dict Dictionary of edges with trophic differences as the value.
References ---------- .. [1] Samuel Johnson, Virginia Dominguez-Garcia, Luca Donetti, Miguel A. Munoz (2014) PNAS "Trophic coherence determines food-web stability" """ levels = trophic_levels(G, weight=weight) diffs = {} for u, v in G.edges: diffs[(u, v)] = levels[v] - levels[u] return diffs
@not_implemented_for("undirected")@nx._dispatchable(edge_attrs="weight")def trophic_incoherence_parameter(G, weight="weight", cannibalism=False): r"""Compute the trophic incoherence parameter of a graph.
Trophic coherence is defined as the homogeneity of the distribution of trophic distances: the more similar, the more coherent. This is measured by the standard deviation of the trophic differences and referred to as the trophic incoherence parameter $q$ by [1].
Parameters ---------- G : DiGraph A directed networkx graph
cannibalism: Boolean If set to False, self edges are not considered in the calculation
Returns ------- trophic_incoherence_parameter : float The trophic coherence of a graph
References ---------- .. [1] Samuel Johnson, Virginia Dominguez-Garcia, Luca Donetti, Miguel A. Munoz (2014) PNAS "Trophic coherence determines food-web stability" """ import numpy as np
if cannibalism: diffs = trophic_differences(G, weight=weight) else: # If no cannibalism, remove self-edges self_loops = list(nx.selfloop_edges(G)) if self_loops: # Make a copy so we do not change G's edges in memory G_2 = G.copy() G_2.remove_edges_from(self_loops) else: # Avoid copy otherwise G_2 = G diffs = trophic_differences(G_2, weight=weight) return float(np.std(list(diffs.values())))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Algorithm to select influential nodes in a graph using VoteRank."""
import networkx as nx
__all__ = ["voterank"]
@nx._dispatchabledef voterank(G, number_of_nodes=None): """Select a list of influential nodes in a graph using VoteRank algorithm
VoteRank [1]_ computes a ranking of the nodes in a graph G based on a voting scheme. With VoteRank, all nodes vote for each of its in-neighbors and the node with the highest votes is elected iteratively. The voting ability of out-neighbors of elected nodes is decreased in subsequent turns.
Parameters ---------- G : graph A NetworkX graph.
number_of_nodes : integer, optional Number of ranked nodes to extract (default all nodes).
Returns ------- voterank : list Ordered list of computed seeds. Only nodes with positive number of votes are returned.
Examples -------- >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 4)]) >>> nx.voterank(G) [0, 1]
The algorithm can be used both for undirected and directed graphs. However, the directed version is different in two ways: (i) nodes only vote for their in-neighbors and (ii) only the voting ability of elected node and its out-neighbors are updated:
>>> G = nx.DiGraph([(0, 1), (2, 1), (2, 3), (3, 4)]) >>> nx.voterank(G) [2, 3]
Notes ----- Each edge is treated independently in case of multigraphs.
References ---------- .. [1] Zhang, J.-X. et al. (2016). Identifying a set of influential spreaders in complex networks. Sci. Rep. 6, 27823; doi: 10.1038/srep27823. """ influential_nodes = [] vote_rank = {} if len(G) == 0: return influential_nodes if number_of_nodes is None or number_of_nodes > len(G): number_of_nodes = len(G) if G.is_directed(): # For directed graphs compute average out-degree avgDegree = sum(deg for _, deg in G.out_degree()) / len(G) else: # For undirected graphs compute average degree avgDegree = sum(deg for _, deg in G.degree()) / len(G) # step 1 - initiate all nodes to (0,1) (score, voting ability) for n in G.nodes(): vote_rank[n] = [0, 1] # Repeat steps 1b to 4 until num_seeds are elected. for _ in range(number_of_nodes): # step 1b - reset rank for n in G.nodes(): vote_rank[n][0] = 0 # step 2 - vote for n, nbr in G.edges(): # In directed graphs nodes only vote for their in-neighbors vote_rank[n][0] += vote_rank[nbr][1] if not G.is_directed(): vote_rank[nbr][0] += vote_rank[n][1] for n in influential_nodes: vote_rank[n][0] = 0 # step 3 - select top node n = max(G.nodes, key=lambda x: vote_rank[x][0]) if vote_rank[n][0] == 0: return influential_nodes influential_nodes.append(n) # weaken the selected node vote_rank[n] = [0, 0] # step 4 - update voterank properties for _, nbr in G.edges(n): vote_rank[nbr][1] -= 1 / avgDegree vote_rank[nbr][1] = max(vote_rank[nbr][1], 0) return influential_nodes123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""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)}1234from networkx.algorithms.coloring.greedy_coloring import *from networkx.algorithms.coloring.equitable_coloring import equitable_color
__all__ = ["greedy_color", "equitable_color"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505"""Equitable coloring of graphs with bounded degree."""
from collections import defaultdict
import networkx as nx
__all__ = ["equitable_color"]
@nx._dispatchabledef is_coloring(G, coloring): """Determine if the coloring is a valid coloring for the graph G.""" # Verify that the coloring is valid. return all(coloring[s] != coloring[d] for s, d in G.edges)
@nx._dispatchabledef is_equitable(G, coloring, num_colors=None): """Determines if the coloring is valid and equitable for the graph G."""
if not is_coloring(G, coloring): return False
# Verify whether it is equitable. color_set_size = defaultdict(int) for color in coloring.values(): color_set_size[color] += 1
if num_colors is not None: for color in range(num_colors): if color not in color_set_size: # These colors do not have any vertices attached to them. color_set_size[color] = 0
# If there are more than 2 distinct values, the coloring cannot be equitable all_set_sizes = set(color_set_size.values()) if len(all_set_sizes) == 0 and num_colors is None: # Was an empty graph return True elif len(all_set_sizes) == 1: return True elif len(all_set_sizes) == 2: a, b = list(all_set_sizes) return abs(a - b) <= 1 else: # len(all_set_sizes) > 2: return False
def make_C_from_F(F): C = defaultdict(list) for node, color in F.items(): C[color].append(node)
return C
def make_N_from_L_C(L, C): nodes = L.keys() colors = C.keys() return { (node, color): sum(1 for v in L[node] if v in C[color]) for node in nodes for color in colors }
def make_H_from_C_N(C, N): return { (c1, c2): sum(1 for node in C[c1] if N[(node, c2)] == 0) for c1 in C for c2 in C }
def change_color(u, X, Y, N, H, F, C, L): """Change the color of 'u' from X to Y and update N, H, F, C.""" assert F[u] == X and X != Y
# Change the class of 'u' from X to Y F[u] = Y
for k in C: # 'u' witnesses an edge from k -> Y instead of from k -> X now. if N[u, k] == 0: H[(X, k)] -= 1 H[(Y, k)] += 1
for v in L[u]: # 'v' has lost a neighbor in X and gained one in Y N[(v, X)] -= 1 N[(v, Y)] += 1
if N[(v, X)] == 0: # 'v' witnesses F[v] -> X H[(F[v], X)] += 1
if N[(v, Y)] == 1: # 'v' no longer witnesses F[v] -> Y H[(F[v], Y)] -= 1
C[X].remove(u) C[Y].append(u)
def move_witnesses(src_color, dst_color, N, H, F, C, T_cal, L): """Move witness along a path from src_color to dst_color.""" X = src_color while X != dst_color: Y = T_cal[X] # Move _any_ witness from X to Y = T_cal[X] w = next(x for x in C[X] if N[(x, Y)] == 0) change_color(w, X, Y, N=N, H=H, F=F, C=C, L=L) X = Y
@nx._dispatchable(mutates_input=True)def pad_graph(G, num_colors): """Add a disconnected complete clique K_p such that the number of nodes in the graph becomes a multiple of `num_colors`.
Assumes that the graph's nodes are labelled using integers.
Returns the number of nodes with each color. """
n_ = len(G) r = num_colors - 1
# Ensure that the number of nodes in G is a multiple of (r + 1) s = n_ // (r + 1) if n_ != s * (r + 1): p = (r + 1) - n_ % (r + 1) s += 1
# Complete graph K_p between (imaginary) nodes [n_, ... , n_ + p] K = nx.relabel_nodes(nx.complete_graph(p), {idx: idx + n_ for idx in range(p)}) G.add_edges_from(K.edges)
return s
def procedure_P(V_minus, V_plus, N, H, F, C, L, excluded_colors=None): """Procedure P as described in the paper."""
if excluded_colors is None: excluded_colors = set()
A_cal = set() T_cal = {} R_cal = []
# BFS to determine A_cal, i.e. colors reachable from V- reachable = [V_minus] marked = set(reachable) idx = 0
while idx < len(reachable): pop = reachable[idx] idx += 1
A_cal.add(pop) R_cal.append(pop)
# TODO: Checking whether a color has been visited can be made faster by # using a look-up table instead of testing for membership in a set by a # logarithmic factor. next_layer = [] for k in C: if ( H[(k, pop)] > 0 and k not in A_cal and k not in excluded_colors and k not in marked ): next_layer.append(k)
for dst in next_layer: # Record that `dst` can reach `pop` T_cal[dst] = pop
marked.update(next_layer) reachable.extend(next_layer)
# Variables for the algorithm b = len(C) - len(A_cal)
if V_plus in A_cal: # Easy case: V+ is in A_cal # Move one node from V+ to V- using T_cal to find the parents. move_witnesses(V_plus, V_minus, N=N, H=H, F=F, C=C, T_cal=T_cal, L=L) else: # If there is a solo edge, we can resolve the situation by # moving witnesses from B to A, making G[A] equitable and then # recursively balancing G[B - w] with a different V_minus and # but the same V_plus.
A_0 = set() A_cal_0 = set() num_terminal_sets_found = 0 made_equitable = False
for W_1 in R_cal[::-1]: for v in C[W_1]: X = None
for U in C: if N[(v, U)] == 0 and U in A_cal and U != W_1: X = U
# v does not witness an edge in H[A_cal] if X is None: continue
for U in C: # Note: Departing from the paper here. if N[(v, U)] >= 1 and U not in A_cal: X_prime = U w = v
try: # Finding the solo neighbor of w in X_prime y = next( node for node in L[w] if F[node] == X_prime and N[(node, W_1)] == 1 ) except StopIteration: pass else: W = W_1
# Move w from W to X, now X has one extra node. change_color(w, W, X, N=N, H=H, F=F, C=C, L=L)
# Move witness from X to V_minus, making the coloring # equitable. move_witnesses( src_color=X, dst_color=V_minus, N=N, H=H, F=F, C=C, T_cal=T_cal, L=L, )
# Move y from X_prime to W, making W the correct size. change_color(y, X_prime, W, N=N, H=H, F=F, C=C, L=L)
# Then call the procedure on G[B - y] procedure_P( V_minus=X_prime, V_plus=V_plus, N=N, H=H, C=C, F=F, L=L, excluded_colors=excluded_colors.union(A_cal), ) made_equitable = True break
if made_equitable: break else: # No node in W_1 was found such that # it had a solo-neighbor. A_cal_0.add(W_1) A_0.update(C[W_1]) num_terminal_sets_found += 1
if num_terminal_sets_found == b: # Otherwise, construct the maximal independent set and find # a pair of z_1, z_2 as in Case II.
# BFS to determine B_cal': the set of colors reachable from V+ B_cal_prime = set() T_cal_prime = {}
reachable = [V_plus] marked = set(reachable) idx = 0 while idx < len(reachable): pop = reachable[idx] idx += 1
B_cal_prime.add(pop)
# No need to check for excluded_colors here because # they only exclude colors from A_cal next_layer = [ k for k in C if H[(pop, k)] > 0 and k not in B_cal_prime and k not in marked ]
for dst in next_layer: T_cal_prime[pop] = dst
marked.update(next_layer) reachable.extend(next_layer)
# Construct the independent set of G[B'] I_set = set() I_covered = set() W_covering = {}
B_prime = [node for k in B_cal_prime for node in C[k]]
# Add the nodes in V_plus to I first. for z in C[V_plus] + B_prime: if z in I_covered or F[z] not in B_cal_prime: continue
I_set.add(z) I_covered.add(z) I_covered.update(list(L[z]))
for w in L[z]: if F[w] in A_cal_0 and N[(z, F[w])] == 1: if w not in W_covering: W_covering[w] = z else: # Found z1, z2 which have the same solo # neighbor in some W z_1 = W_covering[w] # z_2 = z
Z = F[z_1] W = F[w]
# shift nodes along W, V- move_witnesses( W, V_minus, N=N, H=H, F=F, C=C, T_cal=T_cal, L=L )
# shift nodes along V+ to Z move_witnesses( V_plus, Z, N=N, H=H, F=F, C=C, T_cal=T_cal_prime, L=L, )
# change color of z_1 to W change_color(z_1, Z, W, N=N, H=H, F=F, C=C, L=L)
# change color of w to some color in B_cal W_plus = next( k for k in C if N[(w, k)] == 0 and k not in A_cal ) change_color(w, W, W_plus, N=N, H=H, F=F, C=C, L=L)
# recurse with G[B \cup W*] excluded_colors.update( [k for k in C if k != W and k not in B_cal_prime] ) procedure_P( V_minus=W, V_plus=W_plus, N=N, H=H, C=C, F=F, L=L, excluded_colors=excluded_colors, )
made_equitable = True break
if made_equitable: break else: assert False, ( "Must find a w which is the solo neighbor " "of two vertices in B_cal_prime." )
if made_equitable: break
@nx._dispatchabledef equitable_color(G, num_colors): """Provides an equitable coloring for nodes of `G`.
Attempts to color a graph using `num_colors` colors, where no neighbors of a node can have same color as the node itself and the number of nodes with each color differ by at most 1. `num_colors` must be greater than the maximum degree of `G`. The algorithm is described in [1]_ and has complexity O(num_colors * n**2).
Parameters ---------- G : networkX graph The nodes of this graph will be colored.
num_colors : number of colors to use This number must be at least one more than the maximum degree of nodes in the graph.
Returns ------- A dictionary with keys representing nodes and values representing corresponding coloring.
Examples -------- >>> G = nx.cycle_graph(4) >>> nx.coloring.equitable_color(G, num_colors=3) # doctest: +SKIP {0: 2, 1: 1, 2: 2, 3: 0}
Raises ------ NetworkXAlgorithmError If `num_colors` is not at least the maximum degree of the graph `G`
References ---------- .. [1] Kierstead, H. A., Kostochka, A. V., Mydlarz, M., & Szemerédi, E. (2010). A fast algorithm for equitable coloring. Combinatorica, 30(2), 217-224. """
# Map nodes to integers for simplicity later. nodes_to_int = {} int_to_nodes = {}
for idx, node in enumerate(G.nodes): nodes_to_int[node] = idx int_to_nodes[idx] = node
G = nx.relabel_nodes(G, nodes_to_int, copy=True)
# Basic graph statistics and sanity check. if len(G.nodes) > 0: r_ = max(G.degree(node) for node in G.nodes) else: r_ = 0
if r_ >= num_colors: raise nx.NetworkXAlgorithmError( f"Graph has maximum degree {r_}, needs " f"{r_ + 1} (> {num_colors}) colors for guaranteed coloring." )
# Ensure that the number of nodes in G is a multiple of (r + 1) pad_graph(G, num_colors)
# Starting the algorithm. # L = {node: list(G.neighbors(node)) for node in G.nodes} L_ = {node: [] for node in G.nodes}
# Arbitrary equitable allocation of colors to nodes. F = {node: idx % num_colors for idx, node in enumerate(G.nodes)}
C = make_C_from_F(F)
# The neighborhood is empty initially. N = make_N_from_L_C(L_, C)
# Currently all nodes witness all edges. H = make_H_from_C_N(C, N)
# Start of algorithm. edges_seen = set()
for u in sorted(G.nodes): for v in sorted(G.neighbors(u)): # Do not double count edges if (v, u) has already been seen. if (v, u) in edges_seen: continue
edges_seen.add((u, v))
L_[u].append(v) L_[v].append(u)
N[(u, F[v])] += 1 N[(v, F[u])] += 1
if F[u] != F[v]: # Were 'u' and 'v' witnesses for F[u] -> F[v] or F[v] -> F[u]? if N[(u, F[v])] == 1: H[F[u], F[v]] -= 1 # u cannot witness an edge between F[u], F[v]
if N[(v, F[u])] == 1: H[F[v], F[u]] -= 1 # v cannot witness an edge between F[v], F[u]
if N[(u, F[u])] != 0: # Find the first color where 'u' does not have any neighbors. Y = next(k for k in C if N[(u, k)] == 0) X = F[u] change_color(u, X, Y, N=N, H=H, F=F, C=C, L=L_)
# Procedure P procedure_P(V_minus=X, V_plus=Y, N=N, H=H, F=F, C=C, L=L_)
return {int_to_nodes[x]: F[x] for x in int_to_nodes}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565"""Greedy graph coloring using various strategies."""
import itertoolsfrom collections import defaultdict, deque
import networkx as nxfrom networkx.utils import arbitrary_element, py_random_state
__all__ = [ "greedy_color", "strategy_connected_sequential", "strategy_connected_sequential_bfs", "strategy_connected_sequential_dfs", "strategy_independent_set", "strategy_largest_first", "strategy_random_sequential", "strategy_saturation_largest_first", "strategy_smallest_last",]
def strategy_largest_first(G, colors): """Returns a list of the nodes of ``G`` in decreasing order by degree.
``G`` is a NetworkX graph. ``colors`` is ignored.
""" return sorted(G, key=G.degree, reverse=True)
@py_random_state(2)def strategy_random_sequential(G, colors, seed=None): """Returns a random permutation of the nodes of ``G`` as a list.
``G`` is a NetworkX graph. ``colors`` is ignored.
seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. """ nodes = list(G) seed.shuffle(nodes) return nodes
def strategy_smallest_last(G, colors): """Returns a deque of the nodes of ``G``, "smallest" last.
Specifically, the degrees of each node are tracked in a bucket queue. From this, the node of minimum degree is repeatedly popped from the graph, updating its neighbors' degrees.
``G`` is a NetworkX graph. ``colors`` is ignored.
This implementation of the strategy runs in $O(n + m)$ time (ignoring polylogarithmic factors), where $n$ is the number of nodes and $m$ is the number of edges.
This strategy is related to :func:`strategy_independent_set`: if we interpret each node removed as an independent set of size one, then this strategy chooses an independent set of size one instead of a maximal independent set.
""" H = G.copy() result = deque()
# Build initial degree list (i.e. the bucket queue data structure) degrees = defaultdict(set) # set(), for fast random-access removals lbound = float("inf") for node, d in H.degree(): degrees[d].add(node) lbound = min(lbound, d) # Lower bound on min-degree.
def find_min_degree(): # Save time by starting the iterator at `lbound`, not 0. # The value that we find will be our new `lbound`, which we set later. return next(d for d in itertools.count(lbound) if d in degrees)
for _ in G: # Pop a min-degree node and add it to the list. min_degree = find_min_degree() u = degrees[min_degree].pop() if not degrees[min_degree]: # Clean up the degree list. del degrees[min_degree] result.appendleft(u)
# Update degrees of removed node's neighbors. for v in H[u]: degree = H.degree(v) degrees[degree].remove(v) if not degrees[degree]: # Clean up the degree list. del degrees[degree] degrees[degree - 1].add(v)
# Finally, remove the node. H.remove_node(u) lbound = min_degree - 1 # Subtract 1 in case of tied neighbors.
return result
def _maximal_independent_set(G): """Returns a maximal independent set of nodes in ``G`` by repeatedly choosing an independent node of minimum degree (with respect to the subgraph of unchosen nodes).
""" result = set() remaining = set(G) while remaining: G = G.subgraph(remaining) v = min(remaining, key=G.degree) result.add(v) remaining -= set(G[v]) | {v} return result
def strategy_independent_set(G, colors): """Uses a greedy independent set removal strategy to determine the colors.
This function updates ``colors`` **in-place** and return ``None``, unlike the other strategy functions in this module.
This algorithm repeatedly finds and removes a maximal independent set, assigning each node in the set an unused color.
``G`` is a NetworkX graph.
This strategy is related to :func:`strategy_smallest_last`: in that strategy, an independent set of size one is chosen at each step instead of a maximal independent set.
""" remaining_nodes = set(G) while len(remaining_nodes) > 0: nodes = _maximal_independent_set(G.subgraph(remaining_nodes)) remaining_nodes -= nodes yield from nodes
def strategy_connected_sequential_bfs(G, colors): """Returns an iterable over nodes in ``G`` in the order given by a breadth-first traversal.
The generated sequence has the property that for each node except the first, at least one neighbor appeared earlier in the sequence.
``G`` is a NetworkX graph. ``colors`` is ignored.
""" return strategy_connected_sequential(G, colors, "bfs")
def strategy_connected_sequential_dfs(G, colors): """Returns an iterable over nodes in ``G`` in the order given by a depth-first traversal.
The generated sequence has the property that for each node except the first, at least one neighbor appeared earlier in the sequence.
``G`` is a NetworkX graph. ``colors`` is ignored.
""" return strategy_connected_sequential(G, colors, "dfs")
def strategy_connected_sequential(G, colors, traversal="bfs"): """Returns an iterable over nodes in ``G`` in the order given by a breadth-first or depth-first traversal.
``traversal`` must be one of the strings ``'dfs'`` or ``'bfs'``, representing depth-first traversal or breadth-first traversal, respectively.
The generated sequence has the property that for each node except the first, at least one neighbor appeared earlier in the sequence.
``G`` is a NetworkX graph. ``colors`` is ignored.
""" if traversal == "bfs": traverse = nx.bfs_edges elif traversal == "dfs": traverse = nx.dfs_edges else: raise nx.NetworkXError( "Please specify one of the strings 'bfs' or" " 'dfs' for connected sequential ordering" ) for component in nx.connected_components(G): source = arbitrary_element(component) # Yield the source node, then all the nodes in the specified # traversal order. yield source for _, end in traverse(G.subgraph(component), source): yield end
def strategy_saturation_largest_first(G, colors): """Iterates over all the nodes of ``G`` in "saturation order" (also known as "DSATUR").
``G`` is a NetworkX graph. ``colors`` is a dictionary mapping nodes of ``G`` to colors, for those nodes that have already been colored.
""" distinct_colors = {v: set() for v in G}
# Add the node color assignments given in colors to the # distinct colors set for each neighbor of that node for node, color in colors.items(): for neighbor in G[node]: distinct_colors[neighbor].add(color)
# Check that the color assignments in colors are valid # i.e. no neighboring nodes have the same color if len(colors) >= 2: for node, color in colors.items(): if color in distinct_colors[node]: raise nx.NetworkXError("Neighboring nodes must have different colors")
# If 0 nodes have been colored, simply choose the node of highest degree. if not colors: node = max(G, key=G.degree) yield node # Add the color 0 to the distinct colors set for each # neighbor of that node. for v in G[node]: distinct_colors[v].add(0)
while len(G) != len(colors): # Update the distinct color sets for the neighbors. for node, color in colors.items(): for neighbor in G[node]: distinct_colors[neighbor].add(color)
# Compute the maximum saturation and the set of nodes that # achieve that saturation. saturation = {v: len(c) for v, c in distinct_colors.items() if v not in colors} # Yield the node with the highest saturation, and break ties by # degree. node = max(saturation, key=lambda v: (saturation[v], G.degree(v))) yield node
#: Dictionary mapping name of a strategy as a string to the strategy function.STRATEGIES = { "largest_first": strategy_largest_first, "random_sequential": strategy_random_sequential, "smallest_last": strategy_smallest_last, "independent_set": strategy_independent_set, "connected_sequential_bfs": strategy_connected_sequential_bfs, "connected_sequential_dfs": strategy_connected_sequential_dfs, "connected_sequential": strategy_connected_sequential, "saturation_largest_first": strategy_saturation_largest_first, "DSATUR": strategy_saturation_largest_first,}
@nx._dispatchabledef greedy_color(G, strategy="largest_first", interchange=False): """Color a graph using various strategies of greedy graph coloring.
Attempts to color a graph using as few colors as possible, where no neighbors of a node can have same color as the node itself. The given strategy determines the order in which nodes are colored.
The strategies are described in [1]_, and smallest-last is based on [2]_.
Parameters ---------- G : NetworkX graph
strategy : string or function(G, colors) A function (or a string representing a function) that provides the coloring strategy, by returning nodes in the ordering they should be colored. ``G`` is the graph, and ``colors`` is a dictionary of the currently assigned colors, keyed by nodes. The function must return an iterable over all the nodes in ``G``.
If the strategy function is an iterator generator (that is, a function with ``yield`` statements), keep in mind that the ``colors`` dictionary will be updated after each ``yield``, since this function chooses colors greedily.
If ``strategy`` is a string, it must be one of the following, each of which represents one of the built-in strategy functions.
* ``'largest_first'`` * ``'random_sequential'`` * ``'smallest_last'`` * ``'independent_set'`` * ``'connected_sequential_bfs'`` * ``'connected_sequential_dfs'`` * ``'connected_sequential'`` (alias for the previous strategy) * ``'saturation_largest_first'`` * ``'DSATUR'`` (alias for the previous strategy)
interchange: bool Will use the color interchange algorithm described by [3]_ if set to ``True``.
Note that ``saturation_largest_first`` and ``independent_set`` do not work with interchange. Furthermore, if you use interchange with your own strategy function, you cannot rely on the values in the ``colors`` argument.
Returns ------- A dictionary with keys representing nodes and values representing corresponding coloring.
Examples -------- >>> G = nx.cycle_graph(4) >>> d = nx.coloring.greedy_color(G, strategy="largest_first") >>> d in [{0: 0, 1: 1, 2: 0, 3: 1}, {0: 1, 1: 0, 2: 1, 3: 0}] True
Raises ------ NetworkXPointlessConcept If ``strategy`` is ``saturation_largest_first`` or ``independent_set`` and ``interchange`` is ``True``.
References ---------- .. [1] Adrian Kosowski, and Krzysztof Manuszewski, Classical Coloring of Graphs, Graph Colorings, 2-19, 2004. ISBN 0-8218-3458-4. .. [2] David W. Matula, and Leland L. Beck, "Smallest-last ordering and clustering and graph coloring algorithms." *J. ACM* 30, 3 (July 1983), 417–427. <https://doi.org/10.1145/2402.322385> .. [3] Maciej M. Sysło, Narsingh Deo, Janusz S. Kowalik, Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983. ISBN 0-486-45353-7.
""" if len(G) == 0: return {} # Determine the strategy provided by the caller. strategy = STRATEGIES.get(strategy, strategy) if not callable(strategy): raise nx.NetworkXError( f"strategy must be callable or a valid string. {strategy} not valid." ) # Perform some validation on the arguments before executing any # strategy functions. if interchange: if strategy is strategy_independent_set: msg = "interchange cannot be used with independent_set" raise nx.NetworkXPointlessConcept(msg) if strategy is strategy_saturation_largest_first: msg = "interchange cannot be used with saturation_largest_first" raise nx.NetworkXPointlessConcept(msg) colors = {} nodes = strategy(G, colors) if interchange: return _greedy_coloring_with_interchange(G, nodes) for u in nodes: # Set to keep track of colors of neighbors nbr_colors = {colors[v] for v in G[u] if v in colors} # Find the first unused color. for color in itertools.count(): if color not in nbr_colors: break # Assign the new color to the current node. colors[u] = color return colors
# Tools for coloring with interchangesclass _Node: __slots__ = ["node_id", "color", "adj_list", "adj_color"]
def __init__(self, node_id, n): self.node_id = node_id self.color = -1 self.adj_list = None self.adj_color = [None for _ in range(n)]
def __repr__(self): return ( f"Node_id: {self.node_id}, Color: {self.color}, " f"Adj_list: ({self.adj_list}), adj_color: ({self.adj_color})" )
def assign_color(self, adj_entry, color): adj_entry.col_prev = None adj_entry.col_next = self.adj_color[color] self.adj_color[color] = adj_entry if adj_entry.col_next is not None: adj_entry.col_next.col_prev = adj_entry
def clear_color(self, adj_entry, color): if adj_entry.col_prev is None: self.adj_color[color] = adj_entry.col_next else: adj_entry.col_prev.col_next = adj_entry.col_next if adj_entry.col_next is not None: adj_entry.col_next.col_prev = adj_entry.col_prev
def iter_neighbors(self): adj_node = self.adj_list while adj_node is not None: yield adj_node adj_node = adj_node.next
def iter_neighbors_color(self, color): adj_color_node = self.adj_color[color] while adj_color_node is not None: yield adj_color_node.node_id adj_color_node = adj_color_node.col_next
class _AdjEntry: __slots__ = ["node_id", "next", "mate", "col_next", "col_prev"]
def __init__(self, node_id): self.node_id = node_id self.next = None self.mate = None self.col_next = None self.col_prev = None
def __repr__(self): col_next = None if self.col_next is None else self.col_next.node_id col_prev = None if self.col_prev is None else self.col_prev.node_id return ( f"Node_id: {self.node_id}, Next: ({self.next}), " f"Mate: ({self.mate.node_id}), " f"col_next: ({col_next}), col_prev: ({col_prev})" )
def _greedy_coloring_with_interchange(G, nodes): """Return a coloring for `original_graph` using interchange approach
This procedure is an adaption of the algorithm described by [1]_, and is an implementation of coloring with interchange. Please be advised, that the datastructures used are rather complex because they are optimized to minimize the time spent identifying subcomponents of the graph, which are possible candidates for color interchange.
Parameters ---------- G : NetworkX graph The graph to be colored
nodes : list nodes ordered using the strategy of choice
Returns ------- dict : A dictionary keyed by node to a color value
References ---------- .. [1] Maciej M. Syslo, Narsingh Deo, Janusz S. Kowalik, Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983. ISBN 0-486-45353-7. """ n = len(G)
graph = {node: _Node(node, n) for node in G}
for node1, node2 in G.edges(): adj_entry1 = _AdjEntry(node2) adj_entry2 = _AdjEntry(node1) adj_entry1.mate = adj_entry2 adj_entry2.mate = adj_entry1 node1_head = graph[node1].adj_list adj_entry1.next = node1_head graph[node1].adj_list = adj_entry1 node2_head = graph[node2].adj_list adj_entry2.next = node2_head graph[node2].adj_list = adj_entry2
k = 0 for node in nodes: # Find the smallest possible, unused color neighbors = graph[node].iter_neighbors() col_used = {graph[adj_node.node_id].color for adj_node in neighbors} col_used.discard(-1) k1 = next(itertools.dropwhile(lambda x: x in col_used, itertools.count()))
# k1 is now the lowest available color if k1 > k: connected = True visited = set() col1 = -1 col2 = -1 while connected and col1 < k: col1 += 1 neighbor_cols = graph[node].iter_neighbors_color(col1) col1_adj = list(neighbor_cols)
col2 = col1 while connected and col2 < k: col2 += 1 visited = set(col1_adj) frontier = list(col1_adj) i = 0 while i < len(frontier): search_node = frontier[i] i += 1 col_opp = col2 if graph[search_node].color == col1 else col1 neighbor_cols = graph[search_node].iter_neighbors_color(col_opp)
for neighbor in neighbor_cols: if neighbor not in visited: visited.add(neighbor) frontier.append(neighbor)
# Search if node is not adj to any col2 vertex connected = ( len( visited.intersection(graph[node].iter_neighbors_color(col2)) ) > 0 )
# If connected is false then we can swap !!! if not connected: # Update all the nodes in the component for search_node in visited: graph[search_node].color = ( col2 if graph[search_node].color == col1 else col1 ) col2_adj = graph[search_node].adj_color[col2] graph[search_node].adj_color[col2] = graph[search_node].adj_color[ col1 ] graph[search_node].adj_color[col1] = col2_adj
# Update all the neighboring nodes for search_node in visited: col = graph[search_node].color col_opp = col1 if col == col2 else col2 for adj_node in graph[search_node].iter_neighbors(): if graph[adj_node.node_id].color != col_opp: # Direct reference to entry adj_mate = adj_node.mate graph[adj_node.node_id].clear_color(adj_mate, col_opp) graph[adj_node.node_id].assign_color(adj_mate, col) k1 = col1
# We can color this node color k1 graph[node].color = k1 k = max(k1, k)
# Update the neighbors of this node for adj_node in graph[node].iter_neighbors(): adj_mate = adj_node.mate graph[adj_node.node_id].assign_color(adj_mate, k1)
return {node.node_id: node.color for node in graph.values()}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863"""Greedy coloring test suite."""
import itertools
import pytest
import networkx as nx
is_coloring = nx.algorithms.coloring.equitable_coloring.is_coloringis_equitable = nx.algorithms.coloring.equitable_coloring.is_equitable
ALL_STRATEGIES = [ "largest_first", "random_sequential", "smallest_last", "independent_set", "connected_sequential_bfs", "connected_sequential_dfs", "connected_sequential", "saturation_largest_first", "DSATUR",]
# List of strategies where interchange=True results in an errorINTERCHANGE_INVALID = ["independent_set", "saturation_largest_first", "DSATUR"]
class TestColoring: def test_basic_cases(self): def check_basic_case(graph_func, n_nodes, strategy, interchange): graph = graph_func() coloring = nx.coloring.greedy_color( graph, strategy=strategy, interchange=interchange ) assert verify_length(coloring, n_nodes) assert verify_coloring(graph, coloring)
for graph_func, n_nodes in BASIC_TEST_CASES.items(): for interchange in [True, False]: for strategy in ALL_STRATEGIES: check_basic_case(graph_func, n_nodes, strategy, False) if strategy not in INTERCHANGE_INVALID: check_basic_case(graph_func, n_nodes, strategy, True)
def test_special_cases(self): def check_special_case(strategy, graph_func, interchange, colors): graph = graph_func() coloring = nx.coloring.greedy_color( graph, strategy=strategy, interchange=interchange ) if not hasattr(colors, "__len__"): colors = [colors] assert any(verify_length(coloring, n_colors) for n_colors in colors) assert verify_coloring(graph, coloring)
for strategy, arglist in SPECIAL_TEST_CASES.items(): for args in arglist: check_special_case(strategy, args[0], args[1], args[2])
def test_interchange_invalid(self): graph = one_node_graph() for strategy in INTERCHANGE_INVALID: pytest.raises( nx.NetworkXPointlessConcept, nx.coloring.greedy_color, graph, strategy=strategy, interchange=True, )
def test_bad_inputs(self): graph = one_node_graph() pytest.raises( nx.NetworkXError, nx.coloring.greedy_color, graph, strategy="invalid strategy", )
def test_strategy_as_function(self): graph = lf_shc() colors_1 = nx.coloring.greedy_color(graph, "largest_first") colors_2 = nx.coloring.greedy_color(graph, nx.coloring.strategy_largest_first) assert colors_1 == colors_2
def test_seed_argument(self): graph = lf_shc() rs = nx.coloring.strategy_random_sequential c1 = nx.coloring.greedy_color(graph, lambda g, c: rs(g, c, seed=1)) for u, v in graph.edges: assert c1[u] != c1[v]
def test_is_coloring(self): G = nx.Graph() G.add_edges_from([(0, 1), (1, 2)]) coloring = {0: 0, 1: 1, 2: 0} assert is_coloring(G, coloring)
coloring[0] = 1 assert not is_coloring(G, coloring) assert not is_equitable(G, coloring)
def test_is_equitable(self): G = nx.Graph() G.add_edges_from([(0, 1), (1, 2)]) coloring = {0: 0, 1: 1, 2: 0} assert is_equitable(G, coloring)
G.add_edges_from([(2, 3), (2, 4), (2, 5)]) coloring[3] = 1 coloring[4] = 1 coloring[5] = 1 assert is_coloring(G, coloring) assert not is_equitable(G, coloring)
def test_num_colors(self): G = nx.Graph() G.add_edges_from([(0, 1), (0, 2), (0, 3)]) pytest.raises(nx.NetworkXAlgorithmError, nx.coloring.equitable_color, G, 2)
def test_equitable_color(self): G = nx.fast_gnp_random_graph(n=10, p=0.2, seed=42) coloring = nx.coloring.equitable_color(G, max_degree(G) + 1) assert is_equitable(G, coloring)
def test_equitable_color_empty(self): G = nx.empty_graph() coloring = nx.coloring.equitable_color(G, max_degree(G) + 1) assert is_equitable(G, coloring)
def test_equitable_color_large(self): G = nx.fast_gnp_random_graph(100, 0.1, seed=42) coloring = nx.coloring.equitable_color(G, max_degree(G) + 1) assert is_equitable(G, coloring, num_colors=max_degree(G) + 1)
def test_case_V_plus_not_in_A_cal(self): # Hand crafted case to avoid the easy case. L = { 0: [2, 5], 1: [3, 4], 2: [0, 8], 3: [1, 7], 4: [1, 6], 5: [0, 6], 6: [4, 5], 7: [3], 8: [2], }
F = { # Color 0 0: 0, 1: 0, # Color 1 2: 1, 3: 1, 4: 1, 5: 1, # Color 2 6: 2, 7: 2, 8: 2, }
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F) N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C) H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
nx.algorithms.coloring.equitable_coloring.procedure_P( V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L ) check_state(L=L, N=N, H=H, F=F, C=C)
def test_cast_no_solo(self): L = { 0: [8, 9], 1: [10, 11], 2: [8], 3: [9], 4: [10, 11], 5: [8], 6: [9], 7: [10, 11], 8: [0, 2, 5], 9: [0, 3, 6], 10: [1, 4, 7], 11: [1, 4, 7], }
F = {0: 0, 1: 0, 2: 2, 3: 2, 4: 2, 5: 3, 6: 3, 7: 3, 8: 1, 9: 1, 10: 1, 11: 1}
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F) N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C) H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
nx.algorithms.coloring.equitable_coloring.procedure_P( V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L ) check_state(L=L, N=N, H=H, F=F, C=C)
def test_hard_prob(self): # Tests for two levels of recursion. num_colors, s = 5, 5
G = nx.Graph() G.add_edges_from( [ (0, 10), (0, 11), (0, 12), (0, 23), (10, 4), (10, 9), (10, 20), (11, 4), (11, 8), (11, 16), (12, 9), (12, 22), (12, 23), (23, 7), (1, 17), (1, 18), (1, 19), (1, 24), (17, 5), (17, 13), (17, 22), (18, 5), (19, 5), (19, 6), (19, 8), (24, 7), (24, 16), (2, 4), (2, 13), (2, 14), (2, 15), (4, 6), (13, 5), (13, 21), (14, 6), (14, 15), (15, 6), (15, 21), (3, 16), (3, 20), (3, 21), (3, 22), (16, 8), (20, 8), (21, 9), (22, 7), ] ) F = {node: node // s for node in range(num_colors * s)} F[s - 1] = num_colors - 1
params = make_params_from_graph(G=G, F=F)
nx.algorithms.coloring.equitable_coloring.procedure_P( V_minus=0, V_plus=num_colors - 1, **params ) check_state(**params)
def test_hardest_prob(self): # Tests for two levels of recursion. num_colors, s = 10, 4
G = nx.Graph() G.add_edges_from( [ (0, 19), (0, 24), (0, 29), (0, 30), (0, 35), (19, 3), (19, 7), (19, 9), (19, 15), (19, 21), (19, 24), (19, 30), (19, 38), (24, 5), (24, 11), (24, 13), (24, 20), (24, 30), (24, 37), (24, 38), (29, 6), (29, 10), (29, 13), (29, 15), (29, 16), (29, 17), (29, 20), (29, 26), (30, 6), (30, 10), (30, 15), (30, 22), (30, 23), (30, 39), (35, 6), (35, 9), (35, 14), (35, 18), (35, 22), (35, 23), (35, 25), (35, 27), (1, 20), (1, 26), (1, 31), (1, 34), (1, 38), (20, 4), (20, 8), (20, 14), (20, 18), (20, 28), (20, 33), (26, 7), (26, 10), (26, 14), (26, 18), (26, 21), (26, 32), (26, 39), (31, 5), (31, 8), (31, 13), (31, 16), (31, 17), (31, 21), (31, 25), (31, 27), (34, 7), (34, 8), (34, 13), (34, 18), (34, 22), (34, 23), (34, 25), (34, 27), (38, 4), (38, 9), (38, 12), (38, 14), (38, 21), (38, 27), (2, 3), (2, 18), (2, 21), (2, 28), (2, 32), (2, 33), (2, 36), (2, 37), (2, 39), (3, 5), (3, 9), (3, 13), (3, 22), (3, 23), (3, 25), (3, 27), (18, 6), (18, 11), (18, 15), (18, 39), (21, 4), (21, 10), (21, 14), (21, 36), (28, 6), (28, 10), (28, 14), (28, 16), (28, 17), (28, 25), (28, 27), (32, 5), (32, 10), (32, 12), (32, 16), (32, 17), (32, 22), (32, 23), (33, 7), (33, 10), (33, 12), (33, 16), (33, 17), (33, 25), (33, 27), (36, 5), (36, 8), (36, 15), (36, 16), (36, 17), (36, 25), (36, 27), (37, 5), (37, 11), (37, 15), (37, 16), (37, 17), (37, 22), (37, 23), (39, 7), (39, 8), (39, 15), (39, 22), (39, 23), ] ) F = {node: node // s for node in range(num_colors * s)} F[s - 1] = num_colors - 1 # V- = 0, V+ = num_colors - 1
params = make_params_from_graph(G=G, F=F)
nx.algorithms.coloring.equitable_coloring.procedure_P( V_minus=0, V_plus=num_colors - 1, **params ) check_state(**params)
def test_strategy_saturation_largest_first(self): def color_remaining_nodes( G, colored_nodes, full_color_assignment=None, nodes_to_add_between_calls=1, ): color_assignments = [] aux_colored_nodes = colored_nodes.copy()
node_iterator = nx.algorithms.coloring.greedy_coloring.strategy_saturation_largest_first( G, aux_colored_nodes )
for u in node_iterator: # Set to keep track of colors of neighbors nbr_colors = { aux_colored_nodes[v] for v in G[u] if v in aux_colored_nodes } # Find the first unused color. for color in itertools.count(): if color not in nbr_colors: break aux_colored_nodes[u] = color color_assignments.append((u, color))
# Color nodes between iterations for i in range(nodes_to_add_between_calls - 1): if not len(color_assignments) + len(colored_nodes) >= len( full_color_assignment ): full_color_assignment_node, color = full_color_assignment[ len(color_assignments) + len(colored_nodes) ]
# Assign the new color to the current node. aux_colored_nodes[full_color_assignment_node] = color color_assignments.append((full_color_assignment_node, color))
return color_assignments, aux_colored_nodes
for G, _, _ in SPECIAL_TEST_CASES["saturation_largest_first"]: G = G()
# Check that function still works when nodes are colored between iterations for nodes_to_add_between_calls in range(1, 5): # Get a full color assignment, (including the order in which nodes were colored) colored_nodes = {} full_color_assignment, full_colored_nodes = color_remaining_nodes( G, colored_nodes )
# For each node in the color assignment, add it to colored_nodes and re-run the function for ind, (node, color) in enumerate(full_color_assignment): colored_nodes[node] = color
( partial_color_assignment, partial_colored_nodes, ) = color_remaining_nodes( G, colored_nodes, full_color_assignment=full_color_assignment, nodes_to_add_between_calls=nodes_to_add_between_calls, )
# Check that the color assignment and order of remaining nodes are the same assert full_color_assignment[ind + 1 :] == partial_color_assignment assert full_colored_nodes == partial_colored_nodes
# ############################ Utility functions ############################def verify_coloring(graph, coloring): for node in graph.nodes(): if node not in coloring: return False
color = coloring[node] for neighbor in graph.neighbors(node): if coloring[neighbor] == color: return False
return True
def verify_length(coloring, expected): coloring = dict_to_sets(coloring) return len(coloring) == expected
def dict_to_sets(colors): if len(colors) == 0: return []
k = max(colors.values()) + 1 sets = [set() for _ in range(k)]
for node, color in colors.items(): sets[color].add(node)
return sets
# ############################ Graph Generation ############################
def empty_graph(): return nx.Graph()
def one_node_graph(): graph = nx.Graph() graph.add_nodes_from([1]) return graph
def two_node_graph(): graph = nx.Graph() graph.add_nodes_from([1, 2]) graph.add_edges_from([(1, 2)]) return graph
def three_node_clique(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3]) graph.add_edges_from([(1, 2), (1, 3), (2, 3)]) return graph
def disconnected(): graph = nx.Graph() graph.add_edges_from([(1, 2), (2, 3), (4, 5), (5, 6)]) return graph
def rs_shc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4]) graph.add_edges_from([(1, 2), (2, 3), (3, 4)]) return graph
def slf_shc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7]) graph.add_edges_from( [(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)] ) return graph
def slf_hc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8]) graph.add_edges_from( [ (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 6), (5, 7), (5, 8), (6, 7), (6, 8), (7, 8), ] ) return graph
def lf_shc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6]) graph.add_edges_from([(6, 1), (1, 4), (4, 3), (3, 2), (2, 5)]) return graph
def lf_hc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7]) graph.add_edges_from( [ (1, 7), (1, 6), (1, 3), (1, 4), (7, 2), (2, 6), (2, 3), (2, 5), (5, 3), (5, 4), (4, 3), ] ) return graph
def sl_shc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6]) graph.add_edges_from( [(1, 2), (1, 3), (2, 3), (1, 4), (2, 5), (3, 6), (4, 5), (4, 6), (5, 6)] ) return graph
def sl_hc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8]) graph.add_edges_from( [ (1, 2), (1, 3), (1, 5), (1, 7), (2, 3), (2, 4), (2, 8), (8, 4), (8, 6), (8, 7), (7, 5), (7, 6), (3, 4), (4, 6), (6, 5), (5, 3), ] ) return graph
def gis_shc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4]) graph.add_edges_from([(1, 2), (2, 3), (3, 4)]) return graph
def gis_hc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6]) graph.add_edges_from([(1, 5), (2, 5), (3, 6), (4, 6), (5, 6)]) return graph
def cs_shc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5]) graph.add_edges_from([(1, 2), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (4, 5)]) return graph
def rsi_shc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6]) graph.add_edges_from( [(1, 2), (1, 5), (1, 6), (2, 3), (3, 4), (4, 5), (4, 6), (5, 6)] ) return graph
def lfi_shc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7]) graph.add_edges_from( [(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)] ) return graph
def lfi_hc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9]) graph.add_edges_from( [ (1, 2), (1, 5), (1, 6), (1, 7), (2, 3), (2, 8), (2, 9), (3, 4), (3, 8), (3, 9), (4, 5), (4, 6), (4, 7), (5, 6), ] ) return graph
def sli_shc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7]) graph.add_edges_from( [ (1, 2), (1, 3), (1, 5), (1, 7), (2, 3), (2, 6), (3, 4), (4, 5), (4, 6), (5, 7), (6, 7), ] ) return graph
def sli_hc(): graph = nx.Graph() graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9]) graph.add_edges_from( [ (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 7), (2, 8), (2, 9), (3, 6), (3, 7), (3, 9), (4, 5), (4, 6), (4, 8), (4, 9), (5, 6), (5, 7), (5, 8), (6, 7), (6, 9), (7, 8), (8, 9), ] ) return graph
# --------------------------------------------------------------------------# Basic tests for all strategies# For each basic graph function, specify the number of expected colors.BASIC_TEST_CASES = { empty_graph: 0, one_node_graph: 1, two_node_graph: 2, disconnected: 2, three_node_clique: 3,}
# --------------------------------------------------------------------------# Special test cases. Each strategy has a list of tuples of the form# (graph function, interchange, valid # of colors)SPECIAL_TEST_CASES = { "random_sequential": [ (rs_shc, False, (2, 3)), (rs_shc, True, 2), (rsi_shc, True, (3, 4)), ], "saturation_largest_first": [(slf_shc, False, (3, 4)), (slf_hc, False, 4)], "largest_first": [ (lf_shc, False, (2, 3)), (lf_hc, False, 4), (lf_shc, True, 2), (lf_hc, True, 3), (lfi_shc, True, (3, 4)), (lfi_hc, True, 4), ], "smallest_last": [ (sl_shc, False, (3, 4)), (sl_hc, False, 5), (sl_shc, True, 3), (sl_hc, True, 4), (sli_shc, True, (3, 4)), (sli_hc, True, 5), ], "independent_set": [(gis_shc, False, (2, 3)), (gis_hc, False, 3)], "connected_sequential": [(cs_shc, False, (3, 4)), (cs_shc, True, 3)], "connected_sequential_dfs": [(cs_shc, False, (3, 4))],}
# --------------------------------------------------------------------------# Helper functions to test# (graph function, interchange, valid # of colors)
def check_state(L, N, H, F, C): s = len(C[0]) num_colors = len(C.keys())
assert all(u in L[v] for u in L for v in L[u]) assert all(F[u] != F[v] for u in L for v in L[u]) assert all(len(L[u]) < num_colors for u in L) assert all(len(C[x]) == s for x in C) assert all(H[(c1, c2)] >= 0 for c1 in C for c2 in C) assert all(N[(u, F[u])] == 0 for u in F)
def max_degree(G): """Get the maximum degree of any node in G.""" return max(G.degree(node) for node in G.nodes) if len(G.nodes) > 0 else 0
def make_params_from_graph(G, F): """Returns {N, L, H, C} from the given graph.""" num_nodes = len(G) L = {u: [] for u in range(num_nodes)} for u, v in G.edges: L[u].append(v) L[v].append(u)
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F) N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C) H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
return {"N": N, "F": F, "C": C, "H": H, "L": L}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 c12345678910111213141516171819202122232425262728"""Functions for computing and measuring community structure.
The ``community`` subpackage can be accessed by using :mod:`networkx.community`, then accessing thefunctions as attributes of ``community``. For example::
>>> import networkx as nx >>> G = nx.barbell_graph(5, 1) >>> communities_generator = nx.community.girvan_newman(G) >>> top_level_communities = next(communities_generator) >>> next_level_communities = next(communities_generator) >>> sorted(map(sorted, next_level_communities)) [[0, 1, 2, 3, 4], [5], [6, 7, 8, 9, 10]]
"""
from networkx.algorithms.community.asyn_fluid import *from networkx.algorithms.community.bipartitions import *from networkx.algorithms.community.centrality import *from networkx.algorithms.community.divisive import *from networkx.algorithms.community.kclique import *from networkx.algorithms.community.label_propagation import *from networkx.algorithms.community.lukes import *from networkx.algorithms.community.modularity_max import *from networkx.algorithms.community.quality import *from networkx.algorithms.community.community_utils import *from networkx.algorithms.community.louvain import *from networkx.algorithms.community.leiden import *from networkx.algorithms.community.local import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""Asynchronous Fluid Communities algorithm for community detection."""
from collections import Counter
import networkx as nxfrom networkx.algorithms.components import is_connectedfrom networkx.exception import NetworkXErrorfrom networkx.utils import groups, not_implemented_for, py_random_state
__all__ = ["asyn_fluidc"]
@not_implemented_for("directed")@not_implemented_for("multigraph")@py_random_state(3)@nx._dispatchabledef asyn_fluidc(G, k, max_iter=100, seed=None): """Returns communities in `G` as detected by Fluid Communities algorithm.
The asynchronous fluid communities algorithm is described in [1]_. The algorithm is based on the simple idea of fluids interacting in an environment, expanding and pushing each other. Its initialization is random, so found communities may vary on different executions.
The algorithm proceeds as follows. First each of the initial k communities is initialized in a random vertex in the graph. Then the algorithm iterates over all vertices in a random order, updating the community of each vertex based on its own community and the communities of its neighbors. This process is performed several times until convergence. At all times, each community has a total density of 1, which is equally distributed among the vertices it contains. If a vertex changes of community, vertex densities of affected communities are adjusted immediately. When a complete iteration over all vertices is done, such that no vertex changes the community it belongs to, the algorithm has converged and returns.
This is the original version of the algorithm described in [1]_. Unfortunately, it does not support weighted graphs yet.
Parameters ---------- G : NetworkX graph Graph must be simple and undirected.
k : integer The number of communities to be found.
max_iter : integer The number of maximum iterations allowed. By default 100.
seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
Returns ------- communities : iterable Iterable of communities given as sets of nodes.
Notes ----- k variable is not an optional argument.
References ---------- .. [1] Parés F., Garcia-Gasulla D. et al. "Fluid Communities: A Competitive and Highly Scalable Community Detection Algorithm". [https://arxiv.org/pdf/1703.09307.pdf]. """ # Initial checks if not isinstance(k, int): raise NetworkXError("k must be an integer.") if not k > 0: raise NetworkXError("k must be greater than 0.") if not is_connected(G): raise NetworkXError("Fluid Communities require connected Graphs.") if len(G) < k: raise NetworkXError("k cannot be bigger than the number of nodes.") if max_iter <= 0: msg = f"{max_iter=} must be greater than 0" raise ValueError(msg) # Initialization max_density = 1.0 vertices = list(G) seed.shuffle(vertices) communities = {n: i for i, n in enumerate(vertices[:k])} density = {} com_to_numvertices = {} for vertex in communities: com_to_numvertices[communities[vertex]] = 1 density[communities[vertex]] = max_density # Set up control variables and start iterating iter_count = 0 cont = True while cont and iter_count < max_iter: cont = False iter_count += 1 # Loop over all vertices in graph in a random order vertices = list(G) seed.shuffle(vertices) for vertex in vertices: # Updating rule com_counter = Counter() # Take into account self vertex community try: com_counter.update({communities[vertex]: density[communities[vertex]]}) except KeyError: pass # Gather neighbor vertex communities for v in G[vertex]: try: com_counter.update({communities[v]: density[communities[v]]}) except KeyError: continue # Check which is the community with highest density new_com = -1 if len(com_counter.keys()) > 0: max_freq = max(com_counter.values()) best_communities = [ com for com, freq in com_counter.items() if (max_freq - freq) < 0.0001 ] # If actual vertex com in best communities, it is preserved try: if communities[vertex] in best_communities: new_com = communities[vertex] except KeyError: pass
# If vertex community changes... if new_com == -1: # Set flag of non-convergence cont = True # Randomly chose a new community from candidates new_com = seed.choice(best_communities) # Update previous community status try: com_to_numvertices[communities[vertex]] -= 1 density[communities[vertex]] = ( max_density / com_to_numvertices[communities[vertex]] ) except KeyError: pass # Update new community status communities[vertex] = new_com com_to_numvertices[communities[vertex]] += 1 density[communities[vertex]] = ( max_density / com_to_numvertices[communities[vertex]] ) # If maximum iterations reached --> output actual results # Return results by grouping communities as list of vertices return iter(groups(communities).values())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354"""Functions for splitting a network into two communities (finding a bipartition)."""
import randomfrom copy import deepcopyfrom itertools import count
import networkx as nx
__all__ = [ "kernighan_lin_bisection", "spectral_modularity_bipartition", "greedy_node_swap_bipartition",]
def _kernighan_lin_sweep(edge_info, side): """ This is a modified form of Kernighan-Lin, which moves single nodes at a time, alternating between sides to keep the bisection balanced. We keep two min-heaps of swap costs to make optimal-next-move selection fast. """ heap0, heap1 = cost_heaps = nx.utils.BinaryHeap(), nx.utils.BinaryHeap() # we use heap methods insert, pop, and get for u, nbrs in edge_info.items(): cost_u = sum(wt if side[v] else -wt for v, wt in nbrs.items()) if side[u]: heap1.insert(u, cost_u) else: heap0.insert(u, -cost_u)
def _update_heap_values(node): side_node = side[node] for nbr, wt in edge_info[node].items(): side_nbr = side[nbr] if side_nbr == side_node: wt = -wt heap_nbr = cost_heaps[side_nbr] if nbr in heap_nbr: cost_nbr = heap_nbr.get(nbr) + 2 * wt # allow_increase lets us update a value already on the heap heap_nbr.insert(nbr, cost_nbr, allow_increase=True)
i = 0 totcost = 0 while heap0 and heap1: u, cost_u = heap0.pop() _update_heap_values(u) v, cost_v = heap1.pop() _update_heap_values(v) totcost += cost_u + cost_v i += 1 yield totcost, i, (u, v)
@nx.utils.not_implemented_for("directed")@nx.utils.py_random_state(4)@nx._dispatchable(edge_attrs="weight")def kernighan_lin_bisection(G, partition=None, max_iter=10, weight="weight", seed=None): """Partition a graph into two blocks using the Kernighan–Lin algorithm.
This algorithm partitions a network into two sets by iteratively swapping pairs of nodes to reduce the edge cut between the two sets. The pairs are chosen according to a modified form of Kernighan-Lin [1]_, which moves nodes individually, alternating between sides to keep the bisection balanced.
Kernighan-Lin is an approximate algorithm for maximal modularity bisection. In [2]_ they suggest that fine-tuned improvements can be made using greedy node swapping, (see `greedy_node_swap_bipartition`). The improvements are typically only a few percent of the modularity value. But they claim that can make a difference between a good and excellent method. This function does not perform any improvements. But you can do that yourself.
Parameters ---------- G : NetworkX graph Graph must be undirected.
partition : tuple Pair of iterables containing an initial partition. If not specified, a random balanced partition is used.
max_iter : int Maximum number of times to attempt swaps to find an improvement before giving up.
weight : string or function (default: "weight") If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one.
If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number or None to indicate a hidden edge.
seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Only used if partition is None
Returns ------- partition : tuple A pair of sets of nodes representing the bipartition.
Raises ------ NetworkXError If `partition` is not a valid partition of the nodes of the graph.
References ---------- .. [1] Kernighan, B. W.; Lin, Shen (1970). "An efficient heuristic procedure for partitioning graphs." *Bell Systems Technical Journal* 49: 291--307. Oxford University Press 2011. .. [2] M. E. J. Newman, "Modularity and community structure in networks", PNAS, 103 (23), p. 8577-8582, https://doi.org/10.1073/pnas.0601602103
""" nodes = list(G)
if partition is None: seed.shuffle(nodes) mid = len(nodes) // 2 A, B = nodes[:mid], nodes[mid:] else: try: A, B = partition except (TypeError, ValueError) as err: raise nx.NetworkXError("partition must be two sets") from err if not nx.community.is_partition(G, [A, B]): raise nx.NetworkXError("partition invalid")
side = {node: (node in A) for node in nodes}
# ruff: noqa: E731 skips check for no lambda functions # Using shortest_paths _weight_function with sum instead of min on multiedges if callable(weight): sum_weight = weight elif G.is_multigraph(): sum_weight = lambda u, v, d: sum(dd.get(weight, 1) for dd in d.values()) else: sum_weight = lambda u, v, d: d.get(weight, 1)
edge_info = { u: {v: wt for v, d in nbrs.items() if (wt := sum_weight(u, v, d)) is not None} for u, nbrs in G._adj.items() }
for i in range(max_iter): costs = list(_kernighan_lin_sweep(edge_info, side)) # find out how many edges to update: min_i min_cost, min_i, _ = min(costs) if min_cost >= 0: break
for _, _, (u, v) in costs[:min_i]: side[u] = 1 side[v] = 0
part1 = {u for u, s in side.items() if s == 0} part2 = {u for u, s in side.items() if s == 1} return part1, part2
@nx.utils.not_implemented_for("directed")@nx.utils.not_implemented_for("multigraph")def spectral_modularity_bipartition(G): r"""Return a bipartition of the nodes based on the spectrum of the modularity matrix of the graph.
This method calculates the eigenvector associated with the second largest eigenvalue of the modularity matrix, where the modularity matrix *B* is defined by
..math::
B_{i j} = A_{i j} - \frac{k_i k_j}{2 m},
where *A* is the adjacency matrix, `k_i` is the degree of node *i*, and *m* is the number of edges in the graph. Nodes whose corresponding values in the eigenvector are negative are placed in one block, nodes whose values are nonnegative are placed in another block.
Parameters ---------- G : NetworkX graph
Returns ------- C : tuple Pair of communities as two sets of nodes of ``G``, partitioned according to second largest eigenvalue of the modularity matrix.
Examples -------- >>> G = nx.karate_club_graph() >>> MrHi, Officer = nx.community.spectral_modularity_bipartition(G) >>> MrHi, Officer = sorted([sorted(MrHi), sorted(Officer)]) >>> MrHi [0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21] >>> Officer [8, 9, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
References ---------- .. [1] M. E. J. Newman *Networks: An Introduction*, pages 373--378 Oxford University Press 2011. .. [2] M. E. J. Newman, "Modularity and community structure in networks", PNAS, 103 (23), p. 8577-8582, https://doi.org/10.1073/pnas.0601602103
""" import numpy as np
B = nx.linalg.modularity_matrix(G) eigenvalues, eigenvectors = np.linalg.eig(B) index = np.argsort(eigenvalues)[-1] v2 = zip(np.real(eigenvectors[:, index]), G) left, right = set(), set() for u, n in v2: if u < 0: left.add(n) else: right.add(n) return left, right
@nx.utils.not_implemented_for("multigraph")def greedy_node_swap_bipartition(G, *, init_split=None, max_iter=10): """Split the nodes into two communities based on greedy modularity maximization.
The algorithm works by selecting a node to change communities which will maximize the modularity. The swap is made and the community structure with the highest modularity is kept.
Parameters ---------- G : NetworkX graph
init_split : 2-tuple of sets of nodes Pair of sets of nodes in ``G`` providing an initial bipartition for the algorithm. If not specified, a random balanced partition is used. If this pair of sets is not a partition of the nodes of `G`, :exc:`NetworkXException` is raised.
max_iter : int Maximum number of iterations of attempting swaps to find an improvement.
Returns ------- max_split : 2-tuple of sets of nodes Pair of sets of nodes of ``G``, partitioned according to a node swap greedy modularity maximization algorithm.
Raises ------ NetworkXError if init_split is not a valid partition of the graph into two communities or if G is a MultiGraph
Examples -------- >>> G = nx.barbell_graph(3, 0) >>> left, right = nx.community.greedy_node_swap_bipartition(G) >>> # Sort the communities so the nodes appear in increasing order. >>> left, right = sorted([sorted(left), sorted(right)]) >>> sorted(left) [0, 1, 2] >>> sorted(right) [3, 4, 5]
Notes ----- This function is not implemented for multigraphs.
References ---------- .. [1] M. E. J. Newman "Networks: An Introduction", pages 373--375. Oxford University Press 2011.
""" if init_split is None: m1 = len(G) // 2 m2 = len(G) - m1 some_nodes = set(random.sample(list(G), m1)) other_nodes = {n for n in G if n not in some_nodes} best_split_so_far = (some_nodes, other_nodes) else: if not nx.community.is_partition(G, init_split): raise nx.NetworkXError("init_split is not a partition of G") if not len(init_split) == 2: raise nx.NetworkXError("init_split must be a bipartition") best_split_so_far = deepcopy(init_split)
best_mod = nx.community.modularity(G, best_split_so_far)
max_split, max_mod = best_split_so_far, best_mod its = 0 m = G.number_of_edges() G_degree = dict(G.degree)
while max_mod >= best_mod and its < max_iter: best_split_so_far = max_split best_mod = max_mod next_split = deepcopy(max_split) next_mod = max_mod nodes = set(G) while nodes: max_swap = -1 max_node = None max_node_comm = None left, right = next_split leftd = sum(G_degree[n] for n in left) rightd = sum(G_degree[n] for n in right) for n in nodes: if n in left: in_comm, out_comm = left, right in_deg, out_deg = leftd, rightd else: in_comm, out_comm = right, left in_deg, out_deg = rightd, leftd
d_eii = -len(G[n].keys() & in_comm) / m d_ejj = len(G[n].keys() & out_comm) / m deg = G_degree[n] d_sum_ai = (deg / (2 * m**2)) * (in_deg - out_deg - deg) swap_change = d_eii + d_ejj + d_sum_ai
if swap_change > max_swap: max_swap = swap_change max_node = n max_node_comm = in_comm non_max_node_comm = out_comm # swap the node from one comm to the other max_node_comm.remove(max_node) non_max_node_comm.add(max_node) next_mod += max_swap # deepcopy next_split each time it reaches a high (might go lower later) if next_mod > max_mod: max_split, max_mod = deepcopy(next_split), next_mod nodes.remove(max_node) its += 1 return best_split_so_far123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""Functions for computing communities based on centrality notions."""
import networkx as nx
__all__ = ["girvan_newman"]
@nx._dispatchable(preserve_edge_attrs="most_valuable_edge")def girvan_newman(G, most_valuable_edge=None): """Finds communities in a graph using the Girvan–Newman method.
Parameters ---------- G : NetworkX graph
most_valuable_edge : function Function that takes a graph as input and outputs an edge. The edge returned by this function will be recomputed and removed at each iteration of the algorithm.
If not specified, the edge with the highest :func:`networkx.edge_betweenness_centrality` will be used.
Returns ------- iterator Iterator over tuples of sets of nodes in `G`. Each set of node is a community, each tuple is a sequence of communities at a particular level of the algorithm.
Examples -------- To get the first pair of communities::
>>> G = nx.path_graph(10) >>> comp = nx.community.girvan_newman(G) >>> tuple(sorted(c) for c in next(comp)) ([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])
To get only the first *k* tuples of communities, use :func:`itertools.islice`::
>>> import itertools >>> G = nx.path_graph(8) >>> k = 2 >>> comp = nx.community.girvan_newman(G) >>> for communities in itertools.islice(comp, k): ... print(tuple(sorted(c) for c in communities)) ... ([0, 1, 2, 3], [4, 5, 6, 7]) ([0, 1], [2, 3], [4, 5, 6, 7])
To stop getting tuples of communities once the number of communities is greater than *k*, use :func:`itertools.takewhile`::
>>> import itertools >>> G = nx.path_graph(8) >>> k = 4 >>> comp = nx.community.girvan_newman(G) >>> limited = itertools.takewhile(lambda c: len(c) <= k, comp) >>> for communities in limited: ... print(tuple(sorted(c) for c in communities)) ... ([0, 1, 2, 3], [4, 5, 6, 7]) ([0, 1], [2, 3], [4, 5, 6, 7]) ([0, 1], [2, 3], [4, 5], [6, 7])
To just choose an edge to remove based on the weight::
>>> from operator import itemgetter >>> G = nx.path_graph(10) >>> edges = G.edges() >>> nx.set_edge_attributes(G, {(u, v): v for u, v in edges}, "weight") >>> def heaviest(G): ... u, v, w = max(G.edges(data="weight"), key=itemgetter(2)) ... return (u, v) ... >>> comp = nx.community.girvan_newman(G, most_valuable_edge=heaviest) >>> tuple(sorted(c) for c in next(comp)) ([0, 1, 2, 3, 4, 5, 6, 7, 8], [9])
To utilize edge weights when choosing an edge with, for example, the highest betweenness centrality::
>>> from networkx import edge_betweenness_centrality as betweenness >>> def most_central_edge(G): ... centrality = betweenness(G, weight="weight") ... return max(centrality, key=centrality.get) ... >>> G = nx.path_graph(10) >>> comp = nx.community.girvan_newman(G, most_valuable_edge=most_central_edge) >>> tuple(sorted(c) for c in next(comp)) ([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])
To specify a different ranking algorithm for edges, use the `most_valuable_edge` keyword argument::
>>> from networkx import edge_betweenness_centrality >>> from random import random >>> def most_central_edge(G): ... centrality = edge_betweenness_centrality(G) ... max_cent = max(centrality.values()) ... # Scale the centrality values so they are between 0 and 1, ... # and add some random noise. ... centrality = {e: c / max_cent for e, c in centrality.items()} ... # Add some random noise. ... centrality = {e: c + random() for e, c in centrality.items()} ... return max(centrality, key=centrality.get) ... >>> G = nx.path_graph(10) >>> comp = nx.community.girvan_newman(G, most_valuable_edge=most_central_edge)
Notes ----- The Girvan–Newman algorithm detects communities by progressively removing edges from the original graph. The algorithm removes the "most valuable" edge, traditionally the edge with the highest betweenness centrality, at each step. As the graph breaks down into pieces, the tightly knit community structure is exposed and the result can be depicted as a dendrogram.
""" # If the graph is already empty, simply return its connected # components. if G.number_of_edges() == 0: yield tuple(nx.connected_components(G)) return # If no function is provided for computing the most valuable edge, # use the edge betweenness centrality. if most_valuable_edge is None:
def most_valuable_edge(G): """Returns the edge with the highest betweenness centrality in the graph `G`.
""" # We have guaranteed that the graph is non-empty, so this # dictionary will never be empty. betweenness = nx.edge_betweenness_centrality(G) return max(betweenness, key=betweenness.get)
# The copy of G here must include the edge weight data. g = G.copy().to_undirected() # Self-loops must be removed because their removal has no effect on # the connected components of the graph. g.remove_edges_from(nx.selfloop_edges(g)) while g.number_of_edges() > 0: yield _without_most_central_edges(g, most_valuable_edge)
def _without_most_central_edges(G, most_valuable_edge): """Returns the connected components of the graph that results from repeatedly removing the most "valuable" edge in the graph.
`G` must be a non-empty graph. This function modifies the graph `G` in-place; that is, it removes edges on the graph `G`.
`most_valuable_edge` is a function that takes the graph `G` as input (or a subgraph with one or more edges of `G` removed) and returns an edge. That edge will be removed and this process will be repeated until the number of connected components in the graph increases.
""" original_num_components = nx.number_connected_components(G) num_new_components = original_num_components while num_new_components <= original_num_components: edge = most_valuable_edge(G) G.remove_edge(*edge) new_components = tuple(nx.connected_components(G)) num_new_components = len(new_components) return new_components123456789101112131415161718192021222324252627282930"""Helper functions for community-finding algorithms."""
import networkx as nx
__all__ = ["is_partition"]
@nx._dispatchabledef is_partition(G, communities): """Returns *True* if `communities` is a partition of the nodes of `G`.
A partition of a universe set is a family of pairwise disjoint sets whose union is the entire universe set.
Parameters ---------- G : NetworkX graph.
communities : list or iterable of sets of nodes If not a list, the iterable is converted internally to a list. If it is an iterator it is exhausted.
""" # Alternate implementation: # return all(sum(1 if v in c else 0 for c in communities) == 1 for v in G) if not isinstance(communities, list): communities = list(communities) nodes = {n for c in communities for n in c if n in G}
return len(G) == len(nodes) == sum(len(c) for c in communities)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216import functools
import networkx as nx
__all__ = [ "edge_betweenness_partition", "edge_current_flow_betweenness_partition",]
@nx._dispatchable(edge_attrs="weight")def edge_betweenness_partition(G, number_of_sets, *, weight=None): """Partition created by iteratively removing the highest edge betweenness edge.
This algorithm works by calculating the edge betweenness for all edges and removing the edge with the highest value. It is then determined whether the graph has been broken into at least `number_of_sets` connected components. If not the process is repeated.
Parameters ---------- G : NetworkX Graph, DiGraph or MultiGraph Graph to be partitioned
number_of_sets : int Number of sets in the desired partition of the graph
weight : key, optional, default=None The key to use if using weights for edge betweenness calculation
Returns ------- C : list of sets Partition of the nodes of G
Raises ------ NetworkXError If number_of_sets is <= 0 or if number_of_sets > len(G)
Examples -------- >>> G = nx.karate_club_graph() >>> part = nx.community.edge_betweenness_partition(G, 2) >>> {0, 1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21} in part True >>> { ... 2, ... 8, ... 9, ... 14, ... 15, ... 18, ... 20, ... 22, ... 23, ... 24, ... 25, ... 26, ... 27, ... 28, ... 29, ... 30, ... 31, ... 32, ... 33, ... } in part True
See Also -------- edge_current_flow_betweenness_partition
Notes ----- This algorithm is fairly slow, as both the calculation of connected components and edge betweenness relies on all pairs shortest path algorithms. They could potentially be combined to cut down on overall computation time.
References ---------- .. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports Volume 486, Issue 3-5 p. 75-174 http://arxiv.org/abs/0906.0612 """ if number_of_sets <= 0: raise nx.NetworkXError("number_of_sets must be >0") if number_of_sets == 1: return [set(G)] if number_of_sets == len(G): return [{n} for n in G] if number_of_sets > len(G): raise nx.NetworkXError("number_of_sets must be <= len(G)")
H = G.copy() partition = list(nx.connected_components(H)) while len(partition) < number_of_sets: ranking = nx.edge_betweenness_centrality(H, weight=weight) edge = max(ranking, key=ranking.get) H.remove_edge(*edge) partition = list(nx.connected_components(H)) return partition
@nx._dispatchable(edge_attrs="weight")def edge_current_flow_betweenness_partition(G, number_of_sets, *, weight=None): """Partition created by removing the highest edge current flow betweenness edge.
This algorithm works by calculating the edge current flow betweenness for all edges and removing the edge with the highest value. It is then determined whether the graph has been broken into at least `number_of_sets` connected components. If not the process is repeated.
Parameters ---------- G : NetworkX Graph, DiGraph or MultiGraph Graph to be partitioned
number_of_sets : int Number of sets in the desired partition of the graph
weight : key, optional (default=None) The edge attribute key to use as weights for edge current flow betweenness calculations
Returns ------- C : list of sets Partition of G
Raises ------ NetworkXError If number_of_sets is <= 0 or number_of_sets > len(G)
Examples -------- >>> G = nx.karate_club_graph() >>> part = nx.community.edge_current_flow_betweenness_partition(G, 2) >>> {0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 16, 17, 19, 21} in part True >>> {8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33} in part True
See Also -------- edge_betweenness_partition
Notes ----- This algorithm is extremely slow, as the recalculation of the edge current flow betweenness is extremely slow.
References ---------- .. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports Volume 486, Issue 3-5 p. 75-174 http://arxiv.org/abs/0906.0612 """ if number_of_sets <= 0: raise nx.NetworkXError("number_of_sets must be >0") elif number_of_sets == 1: return [set(G)] elif number_of_sets == len(G): return [{n} for n in G] elif number_of_sets > len(G): raise nx.NetworkXError("number_of_sets must be <= len(G)")
rank = functools.partial( nx.edge_current_flow_betweenness_centrality, normalized=False, weight=weight )
# current flow requires a connected network so we track the components explicitly H = G.copy() partition = list(nx.connected_components(H)) if len(partition) > 1: Hcc_subgraphs = [H.subgraph(cc).copy() for cc in partition] else: Hcc_subgraphs = [H]
ranking = {} for Hcc in Hcc_subgraphs: ranking.update(rank(Hcc))
while len(partition) < number_of_sets: edge = max(ranking, key=ranking.get) for cc, Hcc in zip(partition, Hcc_subgraphs): if edge[0] in cc: Hcc.remove_edge(*edge) del ranking[edge] splitcc_list = list(nx.connected_components(Hcc)) if len(splitcc_list) > 1: # there are 2 connected components. split off smaller one cc_new = min(splitcc_list, key=len) Hcc_new = Hcc.subgraph(cc_new).copy() # update edge rankings for Hcc_new newranks = rank(Hcc_new) for e, r in newranks.items(): ranking[e if e in ranking else e[::-1]] = r # append new cc and Hcc to their lists. partition.append(cc_new) Hcc_subgraphs.append(Hcc_new)
# leave existing cc and Hcc in their lists, but shrink them Hcc.remove_nodes_from(cc_new) cc.difference_update(cc_new) # update edge rankings for Hcc whether it was split or not newranks = rank(Hcc) for e, r in newranks.items(): ranking[e if e in ranking else e[::-1]] = r break return partition12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879from collections import defaultdict
import networkx as nx
__all__ = ["k_clique_communities"]
@nx._dispatchabledef k_clique_communities(G, k, cliques=None): """Find k-clique communities in graph using the percolation method.
A k-clique community is the union of all cliques of size k that can be reached through adjacent (sharing k-1 nodes) k-cliques.
Parameters ---------- G : NetworkX graph
k : int Size of smallest clique
cliques: list or generator Precomputed cliques (use networkx.find_cliques(G))
Returns ------- Yields sets of nodes, one for each k-clique community.
Examples -------- >>> G = nx.complete_graph(5) >>> K5 = nx.convert_node_labels_to_integers(G, first_label=2) >>> G.add_edges_from(K5.edges()) >>> c = list(nx.community.k_clique_communities(G, 4)) >>> sorted(list(c[0])) [0, 1, 2, 3, 4, 5, 6] >>> list(nx.community.k_clique_communities(G, 6)) []
References ---------- .. [1] Gergely Palla, Imre Derényi, Illés Farkas1, and Tamás Vicsek, Uncovering the overlapping community structure of complex networks in nature and society Nature 435, 814-818, 2005, doi:10.1038/nature03607 """ if k < 2: raise nx.NetworkXError(f"k={k}, k must be greater than 1.") if cliques is None: cliques = nx.find_cliques(G) cliques = [frozenset(c) for c in cliques if len(c) >= k]
# First index which nodes are in which cliques membership_dict = defaultdict(list) for clique in cliques: for node in clique: membership_dict[node].append(clique)
# For each clique, see which adjacent cliques percolate perc_graph = nx.Graph() perc_graph.add_nodes_from(cliques) for clique in cliques: for adj_clique in _get_adjacent_cliques(clique, membership_dict): if len(clique.intersection(adj_clique)) >= (k - 1): perc_graph.add_edge(clique, adj_clique)
# Connected components of clique graph with perc edges # are the percolated cliques for component in nx.connected_components(perc_graph): yield (frozenset.union(*component))
def _get_adjacent_cliques(clique, membership_dict): adjacent_cliques = set() for n in clique: for adj_clique in membership_dict[n]: if clique != adj_clique: adjacent_cliques.add(adj_clique) return adjacent_cliques123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338"""Label propagation community detection algorithms."""
from collections import Counter, defaultdict, deque
import networkx as nxfrom networkx.utils import groups, not_implemented_for, py_random_state
__all__ = [ "label_propagation_communities", "asyn_lpa_communities", "fast_label_propagation_communities",]
@py_random_state("seed")@nx._dispatchable(edge_attrs="weight")def fast_label_propagation_communities(G, *, weight=None, seed=None): """Returns communities in `G` as detected by fast label propagation.
The fast label propagation algorithm is described in [1]_. The algorithm is probabilistic and the found communities may vary in different executions.
The algorithm operates as follows. First, the community label of each node is set to a unique label. The algorithm then repeatedly updates the labels of the nodes to the most frequent label in their neighborhood. In case of ties, a random label is chosen from the most frequent labels.
The algorithm maintains a queue of nodes that still need to be processed. Initially, all nodes are added to the queue in a random order. Then the nodes are removed from the queue one by one and processed. If a node updates its label, all its neighbors that have a different label are added to the queue (if not already in the queue). The algorithm stops when the queue is empty.
Parameters ---------- G : Graph, DiGraph, MultiGraph, or MultiDiGraph Any NetworkX graph.
weight : string, or None (default) The edge attribute representing a non-negative weight of an edge. If None, each edge is assumed to have weight one. The weight of an edge is used in determining the frequency with which a label appears among the neighbors of a node (edge with weight `w` is equivalent to `w` unweighted edges).
seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
Returns ------- communities : iterable Iterable of communities given as sets of nodes.
Notes ----- Edge directions are ignored for directed graphs. Edge weights must be non-negative numbers.
References ---------- .. [1] Vincent A. Traag & Lovro Šubelj. "Large network community detection by fast label propagation." Scientific Reports 13 (2023): 2701. https://doi.org/10.1038/s41598-023-29610-z """
# Queue of nodes to be processed. nodes_queue = deque(G) seed.shuffle(nodes_queue)
# Set of nodes in the queue. nodes_set = set(G)
# Assign unique label to each node. comms = {node: i for i, node in enumerate(G)}
while nodes_queue: # Remove next node from the queue to process. node = nodes_queue.popleft() nodes_set.remove(node)
# Isolated nodes retain their initial label. if G.degree(node) > 0: # Compute frequency of labels in node's neighborhood. label_freqs = _fast_label_count(G, comms, node, weight) max_freq = max(label_freqs.values())
# Always sample new label from most frequent labels. comm = seed.choice( [comm for comm in label_freqs if label_freqs[comm] == max_freq] )
if comms[node] != comm: comms[node] = comm
# Add neighbors that have different label to the queue. for nbr in nx.all_neighbors(G, node): if comms[nbr] != comm and nbr not in nodes_set: nodes_queue.append(nbr) nodes_set.add(nbr)
yield from groups(comms).values()
def _fast_label_count(G, comms, node, weight=None): """Computes the frequency of labels in the neighborhood of a node.
Returns a dictionary keyed by label to the frequency of that label. """
if weight is None: # Unweighted (un)directed simple graph. if not G.is_multigraph(): label_freqs = Counter(map(comms.get, nx.all_neighbors(G, node)))
# Unweighted (un)directed multigraph. else: label_freqs = defaultdict(int) for nbr in G[node]: label_freqs[comms[nbr]] += len(G[node][nbr])
if G.is_directed(): for nbr in G.pred[node]: label_freqs[comms[nbr]] += len(G.pred[node][nbr])
else: # Weighted undirected simple/multigraph. label_freqs = defaultdict(float) for _, nbr, w in G.edges(node, data=weight, default=1): label_freqs[comms[nbr]] += w
# Weighted directed simple/multigraph. if G.is_directed(): for nbr, _, w in G.in_edges(node, data=weight, default=1): label_freqs[comms[nbr]] += w
return label_freqs
@py_random_state(2)@nx._dispatchable(edge_attrs="weight")def asyn_lpa_communities(G, weight=None, seed=None): """Returns communities in `G` as detected by asynchronous label propagation.
The asynchronous label propagation algorithm is described in [1]_. The algorithm is probabilistic and the found communities may vary on different executions.
The algorithm proceeds as follows. After initializing each node with a unique label, the algorithm repeatedly sets the label of a node to be the label that appears most frequently among that nodes neighbors. The algorithm halts when each node has the label that appears most frequently among its neighbors. The algorithm is asynchronous because each node is updated without waiting for updates on the remaining nodes.
This generalized version of the algorithm in [1]_ accepts edge weights.
Parameters ---------- G : Graph
weight : string The edge attribute representing the weight of an edge. If None, each edge is assumed to have weight one. In this algorithm, the weight of an edge is used in determining the frequency with which a label appears among the neighbors of a node: a higher weight means the label appears more often.
seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
Returns ------- communities : iterable Iterable of communities given as sets of nodes.
Notes ----- Edge weight attributes must be numerical.
References ---------- .. [1] Raghavan, Usha Nandini, Réka Albert, and Soundar Kumara. "Near linear time algorithm to detect community structures in large-scale networks." Physical Review E 76.3 (2007): 036106. """
labels = {n: i for i, n in enumerate(G)} cont = True
while cont: cont = False nodes = list(G) seed.shuffle(nodes)
for node in nodes: if not G[node]: continue
# Get label frequencies among adjacent nodes. # Depending on the order they are processed in, # some nodes will be in iteration t and others in t-1, # making the algorithm asynchronous. if weight is None: # initialising a Counter from an iterator of labels is # faster for getting unweighted label frequencies label_freq = Counter(map(labels.get, G[node])) else: # updating a defaultdict is substantially faster # for getting weighted label frequencies label_freq = defaultdict(float) for _, v, wt in G.edges(node, data=weight, default=1): label_freq[labels[v]] += wt
# Get the labels that appear with maximum frequency. max_freq = max(label_freq.values()) best_labels = [ label for label, freq in label_freq.items() if freq == max_freq ]
# If the node does not have one of the maximum frequency labels, # randomly choose one of them and update the node's label. # Continue the iteration as long as at least one node # doesn't have a maximum frequency label. if labels[node] not in best_labels: labels[node] = seed.choice(best_labels) cont = True
yield from groups(labels).values()
@not_implemented_for("directed")@nx._dispatchabledef label_propagation_communities(G): """Generates community sets determined by label propagation
Finds communities in `G` using a semi-synchronous label propagation method [1]_. This method combines the advantages of both the synchronous and asynchronous models. Not implemented for directed graphs.
Parameters ---------- G : graph An undirected NetworkX graph.
Returns ------- communities : iterable A dict_values object that contains a set of nodes for each community.
Raises ------ NetworkXNotImplemented If the graph is directed
References ---------- .. [1] Cordasco, G., & Gargano, L. (2010, December). Community detection via semi-synchronous label propagation algorithms. In Business Applications of Social Network Analysis (BASNA), 2010 IEEE International Workshop on (pp. 1-8). IEEE. """ coloring = _color_network(G) # Create a unique label for each node in the graph labeling = {v: k for k, v in enumerate(G)} while not _labeling_complete(labeling, G): # Update the labels of every node with the same color. for color, nodes in coloring.items(): for n in nodes: _update_label(n, labeling, G)
clusters = defaultdict(set) for node, label in labeling.items(): clusters[label].add(node) return clusters.values()
def _color_network(G): """Colors the network so that neighboring nodes all have distinct colors.
Returns a dict keyed by color to a set of nodes with that color. """ coloring = {} # color => set(node) colors = nx.coloring.greedy_color(G) for node, color in colors.items(): if color in coloring: coloring[color].add(node) else: coloring[color] = {node} return coloring
def _labeling_complete(labeling, G): """Determines whether or not LPA is done.
Label propagation is complete when all nodes have a label that is in the set of highest frequency labels amongst its neighbors.
Nodes with no neighbors are considered complete. """ return all( labeling[v] in _most_frequent_labels(v, labeling, G) for v in G if len(G[v]) > 0 )
def _most_frequent_labels(node, labeling, G): """Returns a set of all labels with maximum frequency in `labeling`.
Input `labeling` should be a dict keyed by node to labels. """ if not G[node]: # Nodes with no neighbors are themselves a community and are labeled # accordingly, hence the immediate if statement. return {labeling[node]}
# Compute the frequencies of all neighbors of node freqs = Counter(labeling[q] for q in G[node]) max_freq = max(freqs.values()) return {label for label, freq in freqs.items() if freq == max_freq}
def _update_label(node, labeling, G): """Updates the label of a node using the Prec-Max tie breaking algorithm
The algorithm is explained in: 'Community Detection via Semi-Synchronous Label Propagation Algorithms' Cordasco and Gargano, 2011 """ high_labels = _most_frequent_labels(node, labeling, G) if len(high_labels) == 1: labeling[node] = high_labels.pop() elif len(high_labels) > 1: # Prec-Max if labeling[node] not in high_labels: labeling[node] = max(high_labels)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""Functions for detecting communities based on Leiden Community Detectionalgorithm.
These functions do not have NetworkX implementations.They may only be run with an installable :doc:`backend </backends>`that supports them."""
import itertoolsfrom collections import deque
import networkx as nxfrom networkx.utils import not_implemented_for, py_random_state
__all__ = ["leiden_communities", "leiden_partitions"]
@not_implemented_for("directed")@py_random_state("seed")@nx._dispatchable(edge_attrs="weight", implemented_by_nx=False)def leiden_communities(G, weight="weight", resolution=1, max_level=None, seed=None): r"""Find a best partition of `G` using Leiden Community Detection (backend required)
Leiden Community Detection is an algorithm to extract the community structure of a network based on modularity optimization. It is an improvement upon the Louvain Community Detection algorithm. See :any:`louvain_communities`.
Unlike the Louvain algorithm, it guarantees that communities are well connected in addition to being faster and uncovering better partitions. [1]_
The algorithm works in 3 phases. On the first phase, it adds the nodes to a queue randomly and assigns every node to be in its own community. For each node it tries to find the maximum positive modularity gain by moving each node to all of its neighbor communities. If a node is moved from its community, it adds to the rear of the queue all neighbors of the node that do not belong to the node’s new community and that are not in the queue.
The first phase continues until the queue is empty.
The second phase consists in refining the partition $P$ obtained from the first phase. It starts with a singleton partition $P_{refined}$. Then it merges nodes locally in $P_{refined}$ within each community of the partition $P$. Nodes are merged with a community in $P_{refined}$ only if both are sufficiently well connected to their community in $P$. This means that after the refinement phase is concluded, communities in $P$ sometimes will have been split into multiple communities.
The third phase consists of aggregating the network by building a new network whose nodes are now the communities found in the second phase. However, the non-refined partition is used to create an initial partition for the aggregate network.
Once this phase is complete it is possible to reapply the first and second phases creating bigger communities with increased modularity.
The above three phases are executed until no modularity gain is achieved or `max_level` number of iterations have been performed.
Parameters ---------- G : NetworkX graph weight : string or None, optional (default="weight") The name of an edge attribute that holds the numerical value used as a weight. If None then each edge has weight 1. resolution : float, optional (default=1) If resolution is less than 1, the algorithm favors larger communities. Greater than 1 favors smaller communities. max_level : int or None, optional (default=None) The maximum number of levels (steps of the algorithm) to compute. Must be a positive integer or None. If None, then there is no max level and the algorithm will run until converged. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
Returns ------- list A list of disjoint sets (partition of `G`). Each set represents one community. All communities together contain all the nodes in `G`.
Examples -------- >>> import networkx as nx >>> G = nx.petersen_graph() >>> nx.community.leiden_communities(G, backend="example_backend") # doctest: +SKIP [{2, 3, 5, 7, 8}, {0, 1, 4, 6, 9}]
Notes ----- The order in which the nodes are considered can affect the final output. In the algorithm the ordering happens using a random shuffle.
References ---------- .. [1] Traag, V.A., Waltman, L. & van Eck, N.J. From Louvain to Leiden: guaranteeing well-connected communities. Sci Rep 9, 5233 (2019). https://doi.org/10.1038/s41598-019-41695-z
See Also -------- leiden_partitions :any:`louvain_communities` """ partitions = leiden_partitions(G, weight, resolution, seed) if max_level is not None: if max_level <= 0: raise ValueError("max_level argument must be a positive integer or None") partitions = itertools.islice(partitions, max_level) final_partition = deque(partitions, maxlen=1) return final_partition.pop()
@not_implemented_for("directed")@py_random_state("seed")@nx._dispatchable(edge_attrs="weight", implemented_by_nx=False)def leiden_partitions(G, weight="weight", resolution=1, seed=None): """Yield partitions for each level of Leiden Community Detection (backend required)
Leiden Community Detection is an algorithm to extract the community structure of a network based on modularity optimization.
The partitions across levels (steps of the algorithm) form a dendrogram of communities. A dendrogram is a diagram representing a tree and each level represents a partition of the G graph. The top level contains the smallest communities and as you traverse to the bottom of the tree the communities get bigger and the overall modularity increases making the partition better.
Each level is generated by executing the three phases of the Leiden Community Detection algorithm. See :any:`leiden_communities`.
Parameters ---------- G : NetworkX graph weight : string or None, optional (default="weight") The name of an edge attribute that holds the numerical value used as a weight. If None then each edge has weight 1. resolution : float, optional (default=1) If resolution is less than 1, the algorithm favors larger communities. Greater than 1 favors smaller communities. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
Yields ------ list A list of disjoint sets (partition of `G`). Each set represents one community. All communities together contain all the nodes in `G`. The yielded partitions increase modularity with each iteration.
References ---------- .. [1] Traag, V.A., Waltman, L. & van Eck, N.J. From Louvain to Leiden: guaranteeing well-connected communities. Sci Rep 9, 5233 (2019). https://doi.org/10.1038/s41598-019-41695-z
See Also -------- leiden_communities :any:`louvain_partitions` """ raise NotImplementedError( "'leiden_partitions' is not implemented by networkx. " "Please try a different backend." )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220"""Local Community Detection Algorithms
Local Community Detection (LCD) aims to detected one or a few communitiesstarting from certain source nodes in the network. This differs from GlobalCommunity Detection (GCD), which aims to partition an entire network intocommunities.
LCD is often useful when only a portion of the graph is known or thegraph is large enough that GCD is infeasable
[1]_ Gives a good introduction and overview of LCD
References----------.. [1] Baltsou, Georgia, Konstantinos Christopoulos, and Konstantinos Tsichlas. Local community detection: A survey. IEEE Access 10 (2022): 110701-110726. https://doi.org/10.1109/ACCESS.2022.3213980
"""
__all__ = ["greedy_source_expansion"]
def _clauset_greedy_source_expansion(G, *, source, cutoff=None): if cutoff is None: cutoff = float("inf") C = {source} B = {source} U = G[source].keys() - C T = {frozenset([node, nbr]) for node in B for nbr in G.neighbors(node)} I = {edge for edge in T if all(node in C for node in edge)}
R_value = 0 while len(C) < cutoff: if not U: break
max_R = 0 best_node = None best_node_B = best_node_T = best_node_I = set()
for v in U: R_tmp, B_tmp, T_tmp, I_tmp = _calculate_local_modularity_for_candidate( G, v, C, B, T, I ) if R_tmp > max_R: max_R = R_tmp best_node = v best_node_B = B_tmp best_node_T = T_tmp best_node_I = I_tmp
C = C | {best_node} U.update(G[best_node].keys() - C) U.remove(best_node) B = best_node_B T = best_node_T I = best_node_I if max_R < R_value: break R_value = max_R
return C
def _calculate_local_modularity_for_candidate(G, v, C, B, T, I): """ Compute the local modularity R and updated variables when adding node v to the community.
Parameters ---------- G : NetworkX graph The input graph. v : node The candidate node to add to the community. C : set The current set of community nodes. B : set The current set of boundary nodes. T : set of frozenset The current set of boundary edges. I : set of frozenset The current set of internal boundary edges.
Returns ------- R_tmp : float The local modularity after adding node v. B_tmp : set The updated set of boundary nodes. T_tmp : set of frozenset The updated set of boundary edges. I_tmp : set of frozenset The updated set of internal boundary edges. """ C_tmp = C | {v} B_tmp = B.copy() T_tmp = T.copy() I_tmp = I.copy() removed_B_nodes = set()
# Update boundary nodes and edges for nbr in G[v]: if nbr not in C_tmp: # v has nbrs not in the community, so it remains a boundary node B_tmp.add(v) # Add edge between v and nbr to boundary edges T_tmp.add(frozenset([v, nbr]))
if nbr in B: # Check if nbr should be removed from boundary nodes # Go through nbrs nbrs to see if it is still a boundary node nbr_still_in_B = any(nbr_nbr not in C_tmp for nbr_nbr in G[nbr]) if not nbr_still_in_B: B_tmp.remove(nbr) removed_B_nodes.add(nbr)
if nbr in C_tmp: # Add edge between v and nbr to internal edges I_tmp.add(frozenset([v, nbr]))
# Remove edges no longer in the boundary for removed_node in removed_B_nodes: for removed_node_nbr in G[removed_node]: if removed_node_nbr not in B_tmp: T_tmp.discard(frozenset([removed_node_nbr, removed_node])) I_tmp.discard(frozenset([removed_node_nbr, removed_node]))
R_tmp = len(I_tmp) / len(T_tmp) if len(T_tmp) > 0 else 1 return R_tmp, B_tmp, T_tmp, I_tmp
ALGORITHMS = { "clauset": _clauset_greedy_source_expansion,}
def greedy_source_expansion(G, *, source, cutoff=None, method="clauset"): r"""Find the local community around a source node.
Find the local community around a source node using Greedy Source Expansion. Greedy Source Expansion generally identifies a local community starting from the source node and expands it based on the criteria of the chosen algorithm.
The algorithm is specified with the `method` keyword argument.
* `"clauset"` [1]_ uses local modularity gain to determine local communities. The algorithm adds nbring nodes that maximize local modularity to the community iteratively, stopping when no additional nodes improve the modularity or when a predefined cutoff is reached.
Local modularity measures the density of edges within a community relative to the total graph. By focusing on local modularity, the algorithm efficiently uncovers communities around a specific node without requiring global optimization over the entire graph.
The algorithm assumes that the graph $G$ consists of a known community $C$ and an unknown set of nodes $U$, which are adjacent to $C$ . The boundary of the community $B$, consists of nodes in $C$ that have at least one nbr in $U$.
Mathematically, the local modularity is expressed as:
.. math:: R = \frac{I}{T}
where $T$ is the number of edges with one or more endpoints in $B$, and $I$ is the number of those edges with neither endpoint in $U$.
Parameters ---------- G : NetworkX graph The input graph.
source : node The source node from which the community expansion begins.
cutoff : int, optional (default=None) The maximum number of nodes to include in the community. If None, the algorithm expands until no further modularity gain can be made.
method : string, optional (default='clauset') The algorithm to use to carry out greedy source expansion. Supported options: 'clauset'. Other inputs produce a ValueError
Returns ------- set A set of nodes representing the local community around the source node.
Examples -------- >>> G = nx.karate_club_graph() >>> nx.community.greedy_source_expansion(G, source=16) {16, 0, 4, 5, 6, 10}
Notes ----- This algorithm is designed for detecting local communities around a specific node, which is useful for large networks where global community detection is computationally expensive.
The result of the algorithm may vary based on the structure of the graph, the choice of the source node, and the presence of ties between nodes during the greedy expansion process.
References ---------- .. [1] Clauset, Aaron. Finding local community structure in networks. Physical Review E—Statistical, Nonlinear, and Soft Matter Physics 72, no. 2 (2005): 026132. https://arxiv.org/pdf/physics/0503036
""" try: algo = ALGORITHMS[method] except KeyError as e: raise ValueError(f"{method} is not a valid choice for an algorithm.") from e
return algo(G, source=source, cutoff=cutoff)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384"""Functions for detecting communities based on Louvain Community DetectionAlgorithm"""
import itertoolsfrom collections import defaultdict, deque
import networkx as nxfrom networkx.algorithms.community import modularityfrom networkx.utils import py_random_state
__all__ = ["louvain_communities", "louvain_partitions"]
@py_random_state("seed")@nx._dispatchable(edge_attrs="weight")def louvain_communities( G, weight="weight", resolution=1, threshold=0.0000001, max_level=None, seed=None): r"""Find the best partition of a graph using the Louvain Community Detection Algorithm.
Louvain Community Detection Algorithm is a simple method to extract the community structure of a network. This is a heuristic method based on modularity optimization. [1]_
The algorithm works in 2 steps. On the first step it assigns every node to be in its own community and then for each node it tries to find the maximum positive modularity gain by moving each node to all of its neighbor communities. If no positive gain is achieved the node remains in its original community.
The modularity gain obtained by moving an isolated node $i$ into a community $C$ can easily be calculated by the following formula (combining [1]_ [2]_ and some algebra):
.. math:: \Delta Q = \frac{k_{i,in}}{2m} - \gamma\frac{ \Sigma_{tot} \cdot k_i}{2m^2}
where $m$ is the size of the graph, $k_{i,in}$ is the sum of the weights of the links from $i$ to nodes in $C$, $k_i$ is the sum of the weights of the links incident to node $i$, $\Sigma_{tot}$ is the sum of the weights of the links incident to nodes in $C$ and $\gamma$ is the resolution parameter.
For the directed case the modularity gain can be computed using this formula according to [3]_
.. math:: \Delta Q = \frac{k_{i,in}}{m} - \gamma\frac{k_i^{out} \cdot\Sigma_{tot}^{in} + k_i^{in} \cdot \Sigma_{tot}^{out}}{m^2}
where $k_i^{out}$, $k_i^{in}$ are the outer and inner weighted degrees of node $i$ and $\Sigma_{tot}^{in}$, $\Sigma_{tot}^{out}$ are the sum of in-going and out-going links incident to nodes in $C$.
The first phase continues until no individual move can improve the modularity.
The second phase consists in building a new network whose nodes are now the communities found in the first phase. To do so, the weights of the links between the new nodes are given by the sum of the weight of the links between nodes in the corresponding two communities. Once this phase is complete it is possible to reapply the first phase creating bigger communities with increased modularity.
The above two phases are executed until no modularity gain is achieved (or is less than the `threshold`, or until `max_levels` is reached).
Be careful with self-loops in the input graph. These are treated as previously reduced communities -- as if the process had been started in the middle of the algorithm. Large self-loop edge weights thus represent strong communities and in practice may be hard to add other nodes to. If your input graph edge weights for self-loops do not represent already reduced communities you may want to remove the self-loops before inputting that graph.
Parameters ---------- G : NetworkX graph weight : string or None, optional (default="weight") The name of an edge attribute that holds the numerical value used as a weight. If None then each edge has weight 1. resolution : float, optional (default=1) If resolution is less than 1, the algorithm favors larger communities. Greater than 1 favors smaller communities threshold : float, optional (default=0.0000001) Modularity gain threshold for each level. If the gain of modularity between 2 levels of the algorithm is less than the given threshold then the algorithm stops and returns the resulting communities. max_level : int or None, optional (default=None) The maximum number of levels (steps of the algorithm) to compute. Must be a positive integer or None. If None, then there is no max level and the threshold parameter determines the stopping condition. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
Returns ------- list A list of sets (partition of `G`). Each set represents one community and contains all the nodes that constitute it.
Examples -------- >>> import networkx as nx >>> G = nx.petersen_graph() >>> nx.community.louvain_communities(G, seed=123) [{0, 4, 5, 7, 9}, {1, 2, 3, 6, 8}]
Notes ----- The order in which the nodes are considered can affect the final output. In the algorithm the ordering happens using a random shuffle.
References ---------- .. [1] Blondel, V.D. et al. Fast unfolding of communities in large networks. J. Stat. Mech 10008, 1-12(2008). https://doi.org/10.1088/1742-5468/2008/10/P10008 .. [2] Traag, V.A., Waltman, L. & van Eck, N.J. From Louvain to Leiden: guaranteeing well-connected communities. Sci Rep 9, 5233 (2019). https://doi.org/10.1038/s41598-019-41695-z .. [3] Nicolas Dugué, Anthony Perez. Directed Louvain : maximizing modularity in directed networks. [Research Report] Université d’Orléans. 2015. hal-01231784. https://hal.archives-ouvertes.fr/hal-01231784
See Also -------- louvain_partitions :any:`leiden_communities` """
partitions = louvain_partitions(G, weight, resolution, threshold, seed) if max_level is not None: if max_level <= 0: raise ValueError("max_level argument must be a positive integer or None") partitions = itertools.islice(partitions, max_level) final_partition = deque(partitions, maxlen=1) return final_partition.pop()
@py_random_state("seed")@nx._dispatchable(edge_attrs="weight")def louvain_partitions( G, weight="weight", resolution=1, threshold=0.0000001, seed=None): """Yield partitions for each level of the Louvain Community Detection Algorithm
Louvain Community Detection Algorithm is a simple method to extract the community structure of a network. This is a heuristic method based on modularity optimization. [1]_
The partitions at each level (step of the algorithm) form a dendrogram of communities. A dendrogram is a diagram representing a tree and each level represents a partition of the G graph. The top level contains the smallest communities and as you traverse to the bottom of the tree the communities get bigger and the overall modularity increases making the partition better.
Each level is generated by executing the two phases of the Louvain Community Detection Algorithm.
Be careful with self-loops in the input graph. These are treated as previously reduced communities -- as if the process had been started in the middle of the algorithm. Large self-loop edge weights thus represent strong communities and in practice may be hard to add other nodes to. If your input graph edge weights for self-loops do not represent already reduced communities you may want to remove the self-loops before inputting that graph.
Parameters ---------- G : NetworkX graph weight : string or None, optional (default="weight") The name of an edge attribute that holds the numerical value used as a weight. If None then each edge has weight 1. resolution : float, optional (default=1) If resolution is less than 1, the algorithm favors larger communities. Greater than 1 favors smaller communities threshold : float, optional (default=0.0000001) Modularity gain threshold for each level. If the gain of modularity between 2 levels of the algorithm is less than the given threshold then the algorithm stops and returns the resulting communities. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
Yields ------ list A list of sets (partition of `G`). Each set represents one community and contains all the nodes that constitute it.
References ---------- .. [1] Blondel, V.D. et al. Fast unfolding of communities in large networks. J. Stat. Mech 10008, 1-12(2008)
See Also -------- louvain_communities :any:`leiden_partitions` """
partition = [{u} for u in G.nodes()] if nx.is_empty(G): yield partition return mod = modularity(G, partition, resolution=resolution, weight=weight) is_directed = G.is_directed() if G.is_multigraph(): graph = _convert_multigraph(G, weight, is_directed) else: graph = G.__class__() graph.add_nodes_from(G) graph.add_weighted_edges_from(G.edges(data=weight, default=1))
m = graph.size(weight="weight") partition, inner_partition, improvement = _one_level( graph, m, partition, resolution, is_directed, seed ) improvement = True while improvement: # gh-5901 protect the sets in the yielded list from further manipulation here yield [s.copy() for s in partition] new_mod = modularity( graph, inner_partition, resolution=resolution, weight="weight" ) if new_mod - mod <= threshold: return mod = new_mod graph = _gen_graph(graph, inner_partition) partition, inner_partition, improvement = _one_level( graph, m, partition, resolution, is_directed, seed )
def _one_level(G, m, partition, resolution=1, is_directed=False, seed=None): """Calculate one level of the Louvain partitions tree
Parameters ---------- G : NetworkX Graph/DiGraph The graph from which to detect communities m : number The size of the graph `G`. partition : list of sets of nodes A valid partition of the graph `G` resolution : positive number The resolution parameter for computing the modularity of a partition is_directed : bool True if `G` is a directed graph. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
""" node2com = {u: i for i, u in enumerate(G.nodes())} inner_partition = [{u} for u in G.nodes()] if is_directed: in_degrees = dict(G.in_degree(weight="weight")) out_degrees = dict(G.out_degree(weight="weight")) Stot_in = list(in_degrees.values()) Stot_out = list(out_degrees.values()) # Calculate weights for both in and out neighbors without considering self-loops nbrs = {} for u in G: nbrs[u] = defaultdict(float) for _, n, wt in G.out_edges(u, data="weight"): if u != n: nbrs[u][n] += wt for n, _, wt in G.in_edges(u, data="weight"): if u != n: nbrs[u][n] += wt else: degrees = dict(G.degree(weight="weight")) Stot = list(degrees.values()) nbrs = {u: {v: data["weight"] for v, data in G[u].items() if v != u} for u in G} rand_nodes = list(G.nodes) seed.shuffle(rand_nodes) nb_moves = 1 improvement = False while nb_moves > 0: nb_moves = 0 for u in rand_nodes: best_mod = 0 best_com = node2com[u] weights2com = _neighbor_weights(nbrs[u], node2com) if is_directed: in_degree = in_degrees[u] out_degree = out_degrees[u] Stot_in[best_com] -= in_degree Stot_out[best_com] -= out_degree remove_cost = ( -weights2com[best_com] / m + resolution * (out_degree * Stot_in[best_com] + in_degree * Stot_out[best_com]) / m**2 ) else: degree = degrees[u] Stot[best_com] -= degree remove_cost = -weights2com[best_com] / m + resolution * ( Stot[best_com] * degree ) / (2 * m**2) for nbr_com, wt in weights2com.items(): if is_directed: gain = ( remove_cost + wt / m - resolution * ( out_degree * Stot_in[nbr_com] + in_degree * Stot_out[nbr_com] ) / m**2 ) else: gain = ( remove_cost + wt / m - resolution * (Stot[nbr_com] * degree) / (2 * m**2) ) if gain > best_mod: best_mod = gain best_com = nbr_com if is_directed: Stot_in[best_com] += in_degree Stot_out[best_com] += out_degree else: Stot[best_com] += degree if best_com != node2com[u]: com = G.nodes[u].get("nodes", {u}) partition[node2com[u]].difference_update(com) inner_partition[node2com[u]].remove(u) partition[best_com].update(com) inner_partition[best_com].add(u) improvement = True nb_moves += 1 node2com[u] = best_com partition = list(filter(len, partition)) inner_partition = list(filter(len, inner_partition)) return partition, inner_partition, improvement
def _neighbor_weights(nbrs, node2com): """Calculate weights between node and its neighbor communities.
Parameters ---------- nbrs : dictionary Dictionary with nodes' neighbors as keys and their edge weight as value. node2com : dictionary Dictionary with all graph's nodes as keys and their community index as value.
""" weights = defaultdict(float) for nbr, wt in nbrs.items(): weights[node2com[nbr]] += wt return weights
def _gen_graph(G, partition): """Generate a new graph based on the partitions of a given graph""" H = G.__class__() node2com = {} for i, part in enumerate(partition): nodes = set() for node in part: node2com[node] = i nodes.update(G.nodes[node].get("nodes", {node})) H.add_node(i, nodes=nodes)
for node1, node2, wt in G.edges(data=True): wt = wt["weight"] com1 = node2com[node1] com2 = node2com[node2] temp = H.get_edge_data(com1, com2, {"weight": 0})["weight"] H.add_edge(com1, com2, weight=wt + temp) return H
def _convert_multigraph(G, weight, is_directed): """Convert a Multigraph to normal Graph""" if is_directed: H = nx.DiGraph() else: H = nx.Graph() H.add_nodes_from(G) for u, v, wt in G.edges(data=weight, default=1): if H.has_edge(u, v): H[u][v]["weight"] += wt else: H.add_edge(u, v, weight=wt) return H123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227"""Lukes Algorithm for exact optimal weighted tree partitioning."""
from copy import deepcopyfrom functools import lru_cachefrom random import choice
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = ["lukes_partitioning"]
D_EDGE_W = "weight"D_EDGE_VALUE = 1.0D_NODE_W = "weight"D_NODE_VALUE = 1PKEY = "partitions"CLUSTER_EVAL_CACHE_SIZE = 2048
def _split_n_from(n, min_size_of_first_part): # splits j in two parts of which the first is at least # the second argument assert n >= min_size_of_first_part for p1 in range(min_size_of_first_part, n + 1): yield p1, n - p1
@nx._dispatchable(node_attrs="node_weight", edge_attrs="edge_weight")def lukes_partitioning(G, max_size, node_weight=None, edge_weight=None): """Optimal partitioning of a weighted tree using the Lukes algorithm.
This algorithm partitions a connected, acyclic graph featuring integer node weights and float edge weights. The resulting clusters are such that the total weight of the nodes in each cluster does not exceed max_size and that the weight of the edges that are cut by the partition is minimum. The algorithm is based on [1]_.
Parameters ---------- G : NetworkX graph
max_size : int Maximum weight a partition can have in terms of sum of node_weight for all nodes in the partition
edge_weight : key Edge data key to use as weight. If None, the weights are all set to one.
node_weight : key Node data key to use as weight. If None, the weights are all set to one. The data must be int.
Returns ------- partition : list A list of sets of nodes representing the clusters of the partition.
Raises ------ NotATree If G is not a tree. TypeError If any of the values of node_weight is not int.
References ---------- .. [1] Lukes, J. A. (1974). "Efficient Algorithm for the Partitioning of Trees." IBM Journal of Research and Development, 18(3), 217–224.
""" # First sanity check and tree preparation if not nx.is_tree(G): raise nx.NotATree("lukes_partitioning works only on trees") else: if nx.is_directed(G): root = [n for n, d in G.in_degree() if d == 0] assert len(root) == 1 root = root[0] t_G = deepcopy(G) else: root = choice(list(G.nodes)) # this has the desirable side effect of not inheriting attributes t_G = nx.dfs_tree(G, root)
# Since we do not want to screw up the original graph, # if we have a blank attribute, we make a deepcopy if edge_weight is None or node_weight is None: safe_G = deepcopy(G) if edge_weight is None: nx.set_edge_attributes(safe_G, D_EDGE_VALUE, D_EDGE_W) edge_weight = D_EDGE_W if node_weight is None: nx.set_node_attributes(safe_G, D_NODE_VALUE, D_NODE_W) node_weight = D_NODE_W else: safe_G = G
# Second sanity check # The values of node_weight MUST BE int. # I cannot see any room for duck typing without incurring serious # danger of subtle bugs. all_n_attr = nx.get_node_attributes(safe_G, node_weight).values() for x in all_n_attr: if not isinstance(x, int): raise TypeError( "lukes_partitioning needs integer " f"values for node_weight ({node_weight})" )
# SUBROUTINES ----------------------- # these functions are defined here for two reasons: # - brevity: we can leverage global "safe_G" # - caching: signatures are hashable
@not_implemented_for("undirected") # this is intended to be called only on t_G def _leaves(gr): for x in gr.nodes: if not nx.descendants(gr, x): yield x
@not_implemented_for("undirected") def _a_parent_of_leaves_only(gr): tleaves = set(_leaves(gr)) for n in set(gr.nodes) - tleaves: if all(x in tleaves for x in nx.descendants(gr, n)): return n
@lru_cache(CLUSTER_EVAL_CACHE_SIZE) def _value_of_cluster(cluster): valid_edges = [e for e in safe_G.edges if e[0] in cluster and e[1] in cluster] return sum(safe_G.edges[e][edge_weight] for e in valid_edges)
def _value_of_partition(partition): return sum(_value_of_cluster(frozenset(c)) for c in partition)
@lru_cache(CLUSTER_EVAL_CACHE_SIZE) def _weight_of_cluster(cluster): return sum(safe_G.nodes[n][node_weight] for n in cluster)
def _pivot(partition, node): ccx = [c for c in partition if node in c] assert len(ccx) == 1 return ccx[0]
def _concatenate_or_merge(partition_1, partition_2, x, i, ref_weight): ccx = _pivot(partition_1, x) cci = _pivot(partition_2, i) merged_xi = ccx.union(cci)
# We first check if we can do the merge. # If so, we do the actual calculations, otherwise we concatenate if _weight_of_cluster(frozenset(merged_xi)) <= ref_weight: cp1 = list(filter(lambda x: x != ccx, partition_1)) cp2 = list(filter(lambda x: x != cci, partition_2))
option_2 = [merged_xi] + cp1 + cp2 return option_2, _value_of_partition(option_2) else: option_1 = partition_1 + partition_2 return option_1, _value_of_partition(option_1)
# INITIALIZATION ----------------------- leaves = set(_leaves(t_G)) for lv in leaves: t_G.nodes[lv][PKEY] = {} slot = safe_G.nodes[lv][node_weight] t_G.nodes[lv][PKEY][slot] = [{lv}] t_G.nodes[lv][PKEY][0] = [{lv}]
for inner in [x for x in t_G.nodes if x not in leaves]: t_G.nodes[inner][PKEY] = {} slot = safe_G.nodes[inner][node_weight] t_G.nodes[inner][PKEY][slot] = [{inner}] nx._clear_cache(t_G)
# CORE ALGORITHM ----------------------- while True: x_node = _a_parent_of_leaves_only(t_G) weight_of_x = safe_G.nodes[x_node][node_weight] best_value = 0 best_partition = None bp_buffer = {} x_descendants = nx.descendants(t_G, x_node) for i_node in x_descendants: for j in range(weight_of_x, max_size + 1): for a, b in _split_n_from(j, weight_of_x): if ( a not in t_G.nodes[x_node][PKEY] or b not in t_G.nodes[i_node][PKEY] ): # it's not possible to form this particular weight sum continue
part1 = t_G.nodes[x_node][PKEY][a] part2 = t_G.nodes[i_node][PKEY][b] part, value = _concatenate_or_merge(part1, part2, x_node, i_node, j)
if j not in bp_buffer or bp_buffer[j][1] < value: # we annotate in the buffer the best partition for j bp_buffer[j] = part, value
# we also keep track of the overall best partition if best_value <= value: best_value = value best_partition = part
# as illustrated in Lukes, once we finished a child, we can # discharge the partitions we found into the graph # (the key phrase is make all x == x') # so that they are used by the subsequent children for w, (best_part_for_vl, vl) in bp_buffer.items(): t_G.nodes[x_node][PKEY][w] = best_part_for_vl bp_buffer.clear()
# the absolute best partition for this node # across all weights has to be stored at 0 t_G.nodes[x_node][PKEY][0] = best_partition t_G.remove_nodes_from(x_descendants)
if x_node == root: # the 0-labeled partition of root # is the optimal one for the whole tree return t_G.nodes[root][PKEY][0]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452"""Functions for detecting communities based on modularity."""
import randomfrom collections import defaultdictfrom copy import deepcopy
import networkx as nxfrom networkx.algorithms.community.quality import modularityfrom networkx.utils.mapped_queue import MappedQueue
__all__ = [ "greedy_modularity_communities", "naive_greedy_modularity_communities",]
def _greedy_modularity_communities_generator(G, weight=None, resolution=1): r"""Yield community partitions of G and the modularity change at each step.
This function performs Clauset-Newman-Moore greedy modularity maximization [2]_ At each step of the process it yields the change in modularity that will occur in the next step followed by yielding the new community partition after that step.
Greedy modularity maximization begins with each node in its own community and repeatedly joins the pair of communities that lead to the largest modularity until one community contains all nodes (the partition has one set).
This function maximizes the generalized modularity, where `resolution` is the resolution parameter, often expressed as $\gamma$. See :func:`~networkx.algorithms.community.quality.modularity`.
Parameters ---------- G : NetworkX graph
weight : string or None, optional (default=None) The name of an 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.
resolution : float (default=1) If resolution is less than 1, modularity favors larger communities. Greater than 1 favors smaller communities.
Yields ------ Alternating yield statements produce the following two objects:
communities: dict_values A dict_values of frozensets of nodes, one for each community. This represents a partition of the nodes of the graph into communities. The first yield is the partition with each node in its own community.
dq: float The change in modularity when merging the next two communities that leads to the largest modularity.
See Also -------- modularity
References ---------- .. [1] Newman, M. E. J. "Networks: An Introduction", page 224 Oxford University Press 2011. .. [2] Clauset, A., Newman, M. E., & Moore, C. "Finding community structure in very large networks." Physical Review E 70(6), 2004. .. [3] Reichardt and Bornholdt "Statistical Mechanics of Community Detection" Phys. Rev. E74, 2006. .. [4] Newman, M. E. J."Analysis of weighted networks" Physical Review E 70(5 Pt 2):056131, 2004. """ directed = G.is_directed() N = G.number_of_nodes()
# Count edges (or the sum of edge-weights for weighted graphs) m = G.size(weight) q0 = 1 / m
# Calculate degrees (notation from the papers) # a : the fraction of (weighted) out-degree for each node # b : the fraction of (weighted) in-degree for each node if directed: a = {node: deg_out * q0 for node, deg_out in G.out_degree(weight=weight)} b = {node: deg_in * q0 for node, deg_in in G.in_degree(weight=weight)} else: a = b = {node: deg * q0 * 0.5 for node, deg in G.degree(weight=weight)}
# this preliminary step collects the edge weights for each node pair # It handles multigraph and digraph and works fine for graph. dq_dict = defaultdict(lambda: defaultdict(float)) for u, v, wt in G.edges(data=weight, default=1): if u == v: continue dq_dict[u][v] += wt dq_dict[v][u] += wt
# now scale and subtract the expected edge-weights term for u, nbrdict in dq_dict.items(): for v, wt in nbrdict.items(): dq_dict[u][v] = q0 * wt - resolution * (a[u] * b[v] + b[u] * a[v])
# Use -dq to get a max_heap instead of a min_heap # dq_heap holds a heap for each node's neighbors dq_heap = {u: MappedQueue({(u, v): -dq for v, dq in dq_dict[u].items()}) for u in G} # H -> all_dq_heap holds a heap with the best items for each node H = MappedQueue([dq_heap[n].heap[0] for n in G if len(dq_heap[n]) > 0])
# Initialize single-node communities communities = {n: frozenset([n]) for n in G} yield communities.values()
# Merge the two communities that lead to the largest modularity while len(H) > 1: # Find best merge # Remove from heap of row maxes # Ties will be broken by choosing the pair with lowest min community id try: negdq, u, v = H.pop() except IndexError: break dq = -negdq yield dq # Remove best merge from row u heap dq_heap[u].pop() # Push new row max onto H if len(dq_heap[u]) > 0: H.push(dq_heap[u].heap[0]) # If this element was also at the root of row v, we need to remove the # duplicate entry from H if dq_heap[v].heap[0] == (v, u): H.remove((v, u)) # Remove best merge from row v heap dq_heap[v].remove((v, u)) # Push new row max onto H if len(dq_heap[v]) > 0: H.push(dq_heap[v].heap[0]) else: # Duplicate wasn't in H, just remove from row v heap dq_heap[v].remove((v, u))
# Perform merge communities[v] = frozenset(communities[u] | communities[v]) del communities[u]
# Get neighbor communities connected to the merged communities u_nbrs = set(dq_dict[u]) v_nbrs = set(dq_dict[v]) all_nbrs = (u_nbrs | v_nbrs) - {u, v} both_nbrs = u_nbrs & v_nbrs # Update dq for merge of u into v for w in all_nbrs: # Calculate new dq value if w in both_nbrs: dq_vw = dq_dict[v][w] + dq_dict[u][w] elif w in v_nbrs: dq_vw = dq_dict[v][w] - resolution * (a[u] * b[w] + a[w] * b[u]) else: # w in u_nbrs dq_vw = dq_dict[u][w] - resolution * (a[v] * b[w] + a[w] * b[v]) # Update rows v and w for row, col in [(v, w), (w, v)]: dq_heap_row = dq_heap[row] # Update dict for v,w only (u is removed below) dq_dict[row][col] = dq_vw # Save old max of per-row heap if len(dq_heap_row) > 0: d_oldmax = dq_heap_row.heap[0] else: d_oldmax = None # Add/update heaps d = (row, col) d_negdq = -dq_vw # Save old value for finding heap index if w in v_nbrs: # Update existing element in per-row heap dq_heap_row.update(d, d, priority=d_negdq) else: # We're creating a new nonzero element, add to heap dq_heap_row.push(d, priority=d_negdq) # Update heap of row maxes if necessary if d_oldmax is None: # No entries previously in this row, push new max H.push(d, priority=d_negdq) else: # We've updated an entry in this row, has the max changed? row_max = dq_heap_row.heap[0] if d_oldmax != row_max or d_oldmax.priority != row_max.priority: H.update(d_oldmax, row_max)
# Remove row/col u from dq_dict matrix for w in dq_dict[u]: # Remove from dict dq_old = dq_dict[w][u] del dq_dict[w][u] # Remove from heaps if we haven't already if w != v: # Remove both row and column for row, col in [(w, u), (u, w)]: dq_heap_row = dq_heap[row] # Check if replaced dq is row max d_old = (row, col) if dq_heap_row.heap[0] == d_old: # Update per-row heap and heap of row maxes dq_heap_row.remove(d_old) H.remove(d_old) # Update row max if len(dq_heap_row) > 0: H.push(dq_heap_row.heap[0]) else: # Only update per-row heap dq_heap_row.remove(d_old)
del dq_dict[u] # Mark row u as deleted, but keep placeholder dq_heap[u] = MappedQueue() # Merge u into v and update a a[v] += a[u] a[u] = 0 if directed: b[v] += b[u] b[u] = 0
yield communities.values()
@nx._dispatchable(edge_attrs="weight")def greedy_modularity_communities( G, weight=None, resolution=1, cutoff=1, best_n=None,): r"""Find communities in G using greedy modularity maximization.
This function uses Clauset-Newman-Moore greedy modularity maximization [2]_ to find the community partition with the largest modularity.
Greedy modularity maximization begins with each node in its own community and repeatedly joins the pair of communities that lead to the largest modularity until no further increase in modularity is possible (a maximum). Two keyword arguments adjust the stopping condition. `cutoff` is a lower limit on the number of communities so you can stop the process before reaching a maximum (used to save computation time). `best_n` is an upper limit on the number of communities so you can make the process continue until at most n communities remain even if the maximum modularity occurs for more. To obtain exactly n communities, set both `cutoff` and `best_n` to n.
This function maximizes the generalized modularity, where `resolution` is the resolution parameter, often expressed as $\gamma$. See :func:`~networkx.algorithms.community.quality.modularity`.
Parameters ---------- G : NetworkX graph
weight : string or None, optional (default=None) The name of an 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.
resolution : float, optional (default=1) If resolution is less than 1, modularity favors larger communities. Greater than 1 favors smaller communities.
cutoff : int, optional (default=1) A minimum number of communities below which the merging process stops. The process stops at this number of communities even if modularity is not maximized. The goal is to let the user stop the process early. The process stops before the cutoff if it finds a maximum of modularity.
best_n : int or None, optional (default=None) A maximum number of communities above which the merging process will not stop. This forces community merging to continue after modularity starts to decrease until `best_n` communities remain. If ``None``, don't force it to continue beyond a maximum.
Raises ------ ValueError : If the `cutoff` or `best_n` value is not in the range ``[1, G.number_of_nodes()]``, or if `best_n` < `cutoff`.
Returns ------- communities: list A list of frozensets of nodes, one for each community. Sorted by length with largest communities first.
Examples -------- >>> G = nx.karate_club_graph() >>> c = nx.community.greedy_modularity_communities(G) >>> sorted(c[0]) [8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
See Also -------- modularity
References ---------- .. [1] Newman, M. E. J. "Networks: An Introduction", page 224 Oxford University Press 2011. .. [2] Clauset, A., Newman, M. E., & Moore, C. "Finding community structure in very large networks." Physical Review E 70(6), 2004. .. [3] Reichardt and Bornholdt "Statistical Mechanics of Community Detection" Phys. Rev. E74, 2006. .. [4] Newman, M. E. J."Analysis of weighted networks" Physical Review E 70(5 Pt 2):056131, 2004. """ if not G.size(): return [{n} for n in G]
if (cutoff < 1) or (cutoff > G.number_of_nodes()): raise ValueError(f"cutoff must be between 1 and {len(G)}. Got {cutoff}.") if best_n is not None: if (best_n < 1) or (best_n > G.number_of_nodes()): raise ValueError(f"best_n must be between 1 and {len(G)}. Got {best_n}.") if best_n < cutoff: raise ValueError(f"Must have best_n >= cutoff. Got {best_n} < {cutoff}") if best_n == 1: return [set(G)] else: best_n = G.number_of_nodes()
# retrieve generator object to construct output community_gen = _greedy_modularity_communities_generator( G, weight=weight, resolution=resolution )
# construct the first best community communities = next(community_gen)
# continue merging communities until one of the breaking criteria is satisfied while len(communities) > cutoff: try: dq = next(community_gen) # StopIteration occurs when communities are the connected components except StopIteration: communities = sorted(communities, key=len, reverse=True) # if best_n requires more merging, merge big sets for highest modularity while len(communities) > best_n: comm1, comm2, *rest = communities communities = [comm1 ^ comm2] communities.extend(rest) return communities
# keep going unless max_mod is reached or best_n says to merge more if dq < 0 and len(communities) <= best_n: break communities = next(community_gen)
return sorted(communities, key=len, reverse=True)
@nx.utils.not_implemented_for("directed")@nx.utils.not_implemented_for("multigraph")@nx._dispatchable(edge_attrs="weight")def naive_greedy_modularity_communities(G, resolution=1, weight=None): r"""Find communities in G using greedy modularity maximization.
This implementation is O(n^4), much slower than alternatives, but it is provided as an easy-to-understand reference implementation.
Greedy modularity maximization begins with each node in its own community and joins the pair of communities that most increases modularity until no such pair exists.
This function maximizes the generalized modularity, where `resolution` is the resolution parameter, often expressed as $\gamma$. See :func:`~networkx.algorithms.community.quality.modularity`.
Parameters ---------- G : NetworkX graph Graph must be simple and undirected.
resolution : float (default=1) If resolution is less than 1, modularity favors larger communities. Greater than 1 favors smaller communities.
weight : string or None, optional (default=None) The name of an 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.
Returns ------- list A list of sets of nodes, one for each community. Sorted by length with largest communities first.
Examples -------- >>> G = nx.karate_club_graph() >>> c = nx.community.naive_greedy_modularity_communities(G) >>> sorted(c[0]) [8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
See Also -------- greedy_modularity_communities modularity """ # First create one community for each node communities = [frozenset([u]) for u in G.nodes()] # Track merges merges = [] # Greedily merge communities until no improvement is possible old_modularity = None new_modularity = modularity(G, communities, resolution=resolution, weight=weight) while old_modularity is None or new_modularity > old_modularity: # Save modularity for comparison old_modularity = new_modularity # Find best pair to merge trial_communities = list(communities) to_merge = None for i, u in enumerate(communities): for j, v in enumerate(communities): # Skip i==j and empty communities if j <= i or len(u) == 0 or len(v) == 0: continue # Merge communities u and v trial_communities[j] = u | v trial_communities[i] = frozenset([]) trial_modularity = modularity( G, trial_communities, resolution=resolution, weight=weight ) if trial_modularity >= new_modularity: # Check if strictly better or tie if trial_modularity > new_modularity: # Found new best, save modularity and group indexes new_modularity = trial_modularity to_merge = (i, j, new_modularity - old_modularity) elif to_merge and min(i, j) < min(to_merge[0], to_merge[1]): # Break ties by choosing pair with lowest min id new_modularity = trial_modularity to_merge = (i, j, new_modularity - old_modularity) # Un-merge trial_communities[i] = u trial_communities[j] = v if to_merge is not None: # If the best merge improves modularity, use it merges.append(to_merge) i, j, dq = to_merge u, v = communities[i], communities[j] communities[j] = u | v communities[i] = frozenset([]) # Remove empty communities and sort return sorted((c for c in communities if len(c) > 0), key=len, reverse=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347"""Functions for measuring the quality of a partition (intocommunities).
"""
from itertools import combinations
import networkx as nxfrom networkx import NetworkXErrorfrom networkx.algorithms.community.community_utils import is_partitionfrom networkx.utils.decorators import argmap
__all__ = ["modularity", "partition_quality"]
class NotAPartition(NetworkXError): """Raised if a given collection is not a partition."""
def __init__(self, G, collection): msg = f"{collection} is not a valid partition of the graph {G}" super().__init__(msg)
def _require_partition(G, partition): """Decorator to check that a valid partition is input to a function
Raises :exc:`networkx.NetworkXError` if the partition is not valid.
This decorator should be used on functions whose first two arguments are a graph and a partition of the nodes of that graph (in that order)::
>>> @require_partition ... def foo(G, partition): ... print("partition is valid!") ... >>> G = nx.complete_graph(5) >>> partition = [{0, 1}, {2, 3}, {4}] >>> foo(G, partition) partition is valid! >>> partition = [{0}, {2, 3}, {4}] >>> foo(G, partition) Traceback (most recent call last): ... networkx.exception.NetworkXError: `partition` is not a valid partition of the nodes of G >>> partition = [{0, 1}, {1, 2, 3}, {4}] >>> foo(G, partition) Traceback (most recent call last): ... networkx.exception.NetworkXError: `partition` is not a valid partition of the nodes of G
""" if is_partition(G, partition): return G, partition raise nx.NetworkXError("`partition` is not a valid partition of the nodes of G")
require_partition = argmap(_require_partition, (0, 1))
@nx._dispatchabledef intra_community_edges(G, partition): """Returns the number of intra-community edges for a partition of `G`.
Parameters ---------- G : NetworkX graph.
partition : iterable of sets of nodes This must be a partition of the nodes of `G`.
The "intra-community edges" are those edges joining a pair of nodes in the same block of the partition.
""" return sum(G.subgraph(block).size() for block in partition)
@nx._dispatchabledef inter_community_edges(G, partition): """Returns the number of inter-community edges for a partition of `G`. according to the given partition of the nodes of `G`.
Parameters ---------- G : NetworkX graph.
partition : iterable of sets of nodes This must be a partition of the nodes of `G`.
The *inter-community edges* are those edges joining a pair of nodes in different blocks of the partition.
Implementation note: this function creates an intermediate graph that may require the same amount of memory as that of `G`.
""" # Alternate implementation that does not require constructing a new # graph object (but does require constructing an affiliation # dictionary): # # aff = dict(chain.from_iterable(((v, block) for v in block) # for block in partition)) # return sum(1 for u, v in G.edges() if aff[u] != aff[v]) # MG = nx.MultiDiGraph if G.is_directed() else nx.MultiGraph return nx.quotient_graph(G, partition, create_using=MG).size()
@nx._dispatchabledef inter_community_non_edges(G, partition): """Returns the number of inter-community non-edges according to the given partition of the nodes of `G`.
Parameters ---------- G : NetworkX graph.
partition : iterable of sets of nodes This must be a partition of the nodes of `G`.
A *non-edge* is a pair of nodes (undirected if `G` is undirected) that are not adjacent in `G`. The *inter-community non-edges* are those non-edges on a pair of nodes in different blocks of the partition.
Implementation note: this function creates two intermediate graphs, which may require up to twice the amount of memory as required to store `G`.
""" # Alternate implementation that does not require constructing two # new graph objects (but does require constructing an affiliation # dictionary): # # aff = dict(chain.from_iterable(((v, block) for v in block) # for block in partition)) # return sum(1 for u, v in nx.non_edges(G) if aff[u] != aff[v]) # return inter_community_edges(nx.complement(G), partition)
@nx._dispatchable(edge_attrs="weight")def modularity(G, communities, weight="weight", resolution=1): r"""Returns the modularity of the given partition of the graph.
Modularity is defined in [1]_ as
.. math:: Q = \frac{1}{2m} \sum_{ij} \left( A_{ij} - \gamma\frac{k_ik_j}{2m}\right) \delta(c_i,c_j)
where $m$ is the number of edges (or sum of all edge weights as in [5]_), $A$ is the adjacency matrix of `G`, $k_i$ is the (weighted) degree of $i$, $\gamma$ is the resolution parameter, and $\delta(c_i, c_j)$ is 1 if $i$ and $j$ are in the same community else 0.
According to [2]_ (and verified by some algebra) this can be reduced to
.. math:: Q = \sum_{c=1}^{n} \left[ \frac{L_c}{m} - \gamma\left( \frac{k_c}{2m} \right) ^2 \right]
where the sum iterates over all communities $c$, $m$ is the number of edges, $L_c$ is the number of intra-community links for community $c$, $k_c$ is the sum of degrees of the nodes in community $c$, and $\gamma$ is the resolution parameter.
The resolution parameter sets an arbitrary tradeoff between intra-group edges and inter-group edges. More complex grouping patterns can be discovered by analyzing the same network with multiple values of gamma and then combining the results [3]_. That said, it is very common to simply use gamma=1. More on the choice of gamma is in [4]_.
The second formula is the one actually used in calculation of the modularity. For directed graphs the second formula replaces $k_c$ with $k^{in}_c k^{out}_c$.
Parameters ---------- G : NetworkX Graph
communities : list or iterable of set of nodes These node sets must represent a partition of G's nodes.
weight : string or None, optional (default="weight") The edge attribute that holds the numerical value used as a weight. If None or an edge does not have that attribute, then that edge has weight 1.
resolution : float (default=1) If resolution is less than 1, modularity favors larger communities. Greater than 1 favors smaller communities.
Returns ------- Q : float The modularity of the partition.
Raises ------ NotAPartition If `communities` is not a partition of the nodes of `G`.
Examples -------- >>> G = nx.barbell_graph(3, 0) >>> nx.community.modularity(G, [{0, 1, 2}, {3, 4, 5}]) 0.35714285714285715 >>> nx.community.modularity(G, nx.community.label_propagation_communities(G)) 0.35714285714285715
References ---------- .. [1] M. E. J. Newman "Networks: An Introduction", page 224. Oxford University Press, 2011. .. [2] Clauset, Aaron, Mark EJ Newman, and Cristopher Moore. "Finding community structure in very large networks." Phys. Rev. E 70.6 (2004). <https://arxiv.org/abs/cond-mat/0408187> .. [3] Reichardt and Bornholdt "Statistical Mechanics of Community Detection" Phys. Rev. E 74, 016110, 2006. https://doi.org/10.1103/PhysRevE.74.016110 .. [4] M. E. J. Newman, "Equivalence between modularity optimization and maximum likelihood methods for community detection" Phys. Rev. E 94, 052315, 2016. https://doi.org/10.1103/PhysRevE.94.052315 .. [5] Blondel, V.D. et al. "Fast unfolding of communities in large networks" J. Stat. Mech 10008, 1-12 (2008). https://doi.org/10.1088/1742-5468/2008/10/P10008 """ if not isinstance(communities, list): communities = list(communities) if not is_partition(G, communities): raise NotAPartition(G, communities)
directed = G.is_directed() if directed: out_degree = dict(G.out_degree(weight=weight)) in_degree = dict(G.in_degree(weight=weight)) m = sum(out_degree.values()) norm = 1 / m**2 else: out_degree = in_degree = dict(G.degree(weight=weight)) deg_sum = sum(out_degree.values()) m = deg_sum / 2 norm = 1 / deg_sum**2
def community_contribution(community): comm = set(community) L_c = sum(wt for u, v, wt in G.edges(comm, data=weight, default=1) if v in comm)
out_degree_sum = sum(out_degree[u] for u in comm) in_degree_sum = sum(in_degree[u] for u in comm) if directed else out_degree_sum
return L_c / m - resolution * out_degree_sum * in_degree_sum * norm
return sum(map(community_contribution, communities))
@require_partition@nx._dispatchabledef partition_quality(G, partition): """Returns the coverage and performance of a partition of G.
The *coverage* of a partition is the ratio of the number of intra-community edges to the total number of edges in the graph.
The *performance* of a partition is the number of intra-community edges plus inter-community non-edges divided by the total number of potential edges.
This algorithm has complexity $O(C^2 + L)$ where C is the number of communities and L is the number of links.
Parameters ---------- G : NetworkX graph
partition : sequence Partition of the nodes of `G`, represented as a sequence of sets of nodes (blocks). Each block of the partition represents a community.
Returns ------- (float, float) The (coverage, performance) tuple of the partition, as defined above.
Raises ------ NetworkXError If `partition` is not a valid partition of the nodes of `G`.
Notes ----- If `G` is a multigraph; - for coverage, the multiplicity of edges is counted - for performance, the result is -1 (total number of possible edges is not defined)
References ---------- .. [1] Santo Fortunato. "Community Detection in Graphs". *Physical Reports*, Volume 486, Issue 3--5 pp. 75--174 <https://arxiv.org/abs/0906.0612> """
node_community = {} for i, community in enumerate(partition): for node in community: node_community[node] = i
# `performance` is not defined for multigraphs if not G.is_multigraph(): # Iterate over the communities, quadratic, to calculate `possible_inter_community_edges` possible_inter_community_edges = sum( len(p1) * len(p2) for p1, p2 in combinations(partition, 2) )
if G.is_directed(): possible_inter_community_edges *= 2 else: possible_inter_community_edges = 0
# Compute the number of edges in the complete graph -- `n` nodes, # directed or undirected, depending on `G` n = len(G) total_pairs = n * (n - 1) if not G.is_directed(): total_pairs //= 2
intra_community_edges = 0 inter_community_non_edges = possible_inter_community_edges
# Iterate over the links to count `intra_community_edges` and `inter_community_non_edges` for e in G.edges(): if node_community[e[0]] == node_community[e[1]]: intra_community_edges += 1 else: inter_community_non_edges -= 1
coverage = intra_community_edges / len(G.edges)
if G.is_multigraph(): performance = -1.0 else: performance = (intra_community_edges + inter_community_non_edges) / total_pairs
return coverage, performance123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import pytest
import networkx as nxfrom networkx import Graph, NetworkXErrorfrom networkx.algorithms.community import asyn_fluidc
@pytest.mark.parametrize("graph_constructor", (nx.DiGraph, nx.MultiGraph))def test_raises_on_directed_and_multigraphs(graph_constructor): G = graph_constructor([(0, 1), (1, 2)]) with pytest.raises(nx.NetworkXNotImplemented): nx.community.asyn_fluidc(G, 1)
def test_exceptions(): test = Graph() test.add_node("a") pytest.raises(NetworkXError, asyn_fluidc, test, "hi") pytest.raises(NetworkXError, asyn_fluidc, test, -1) pytest.raises(NetworkXError, asyn_fluidc, test, 3) with pytest.raises(ValueError, match="must be greater than 0"): asyn_fluidc(test, 1, max_iter=0) test.add_node("b") pytest.raises(NetworkXError, asyn_fluidc, test, 1)
def test_single_node(): test = Graph()
test.add_node("a")
# ground truth ground_truth = {frozenset(["a"])}
communities = asyn_fluidc(test, 1) result = {frozenset(c) for c in communities} assert result == ground_truth
def test_two_nodes(): test = Graph()
test.add_edge("a", "b")
# ground truth ground_truth = {frozenset(["a"]), frozenset(["b"])}
communities = asyn_fluidc(test, 2) result = {frozenset(c) for c in communities} assert result == ground_truth
def test_two_clique_communities(): test = Graph()
# c1 test.add_edge("a", "b") test.add_edge("a", "c") test.add_edge("b", "c")
# connection test.add_edge("c", "d")
# c2 test.add_edge("d", "e") test.add_edge("d", "f") test.add_edge("f", "e")
# ground truth ground_truth = {frozenset(["a", "c", "b"]), frozenset(["e", "d", "f"])}
communities = asyn_fluidc(test, 2, seed=7) result = {frozenset(c) for c in communities} assert result == ground_truth
def test_five_clique_ring(): test = Graph()
# c1 test.add_edge("1a", "1b") test.add_edge("1a", "1c") test.add_edge("1a", "1d") test.add_edge("1b", "1c") test.add_edge("1b", "1d") test.add_edge("1c", "1d")
# c2 test.add_edge("2a", "2b") test.add_edge("2a", "2c") test.add_edge("2a", "2d") test.add_edge("2b", "2c") test.add_edge("2b", "2d") test.add_edge("2c", "2d")
# c3 test.add_edge("3a", "3b") test.add_edge("3a", "3c") test.add_edge("3a", "3d") test.add_edge("3b", "3c") test.add_edge("3b", "3d") test.add_edge("3c", "3d")
# c4 test.add_edge("4a", "4b") test.add_edge("4a", "4c") test.add_edge("4a", "4d") test.add_edge("4b", "4c") test.add_edge("4b", "4d") test.add_edge("4c", "4d")
# c5 test.add_edge("5a", "5b") test.add_edge("5a", "5c") test.add_edge("5a", "5d") test.add_edge("5b", "5c") test.add_edge("5b", "5d") test.add_edge("5c", "5d")
# connections test.add_edge("1a", "2c") test.add_edge("2a", "3c") test.add_edge("3a", "4c") test.add_edge("4a", "5c") test.add_edge("5a", "1c")
# ground truth ground_truth = { frozenset(["1a", "1b", "1c", "1d"]), frozenset(["2a", "2b", "2c", "2d"]), frozenset(["3a", "3b", "3c", "3d"]), frozenset(["4a", "4b", "4c", "4d"]), frozenset(["5a", "5b", "5c", "5d"]), }
communities = asyn_fluidc(test, 5, seed=9) result = {frozenset(c) for c in communities} assert result == ground_truth
def test_asyn_fluidc_max_iter(): """Check that setting `max_iter` stops the algorithm early.""" test = nx.barbell_graph(3, 2)
c1 = asyn_fluidc(test, 2, max_iter=1, seed=42) c2 = asyn_fluidc(test, 2, max_iter=100, seed=42) assert {map(frozenset, c1)} != {map(frozenset, c2)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157from itertools import permutations
import pytest
import networkx as nxfrom networkx.algorithms.community import ( greedy_node_swap_bipartition, kernighan_lin_bisection,)
def assert_partition_equal(x, y): assert set(map(frozenset, x)) == set(map(frozenset, y))
def test_partition(): G = nx.barbell_graph(3, 0) split = kernighan_lin_bisection(G) assert_partition_equal(split, [{0, 1, 2}, {3, 4, 5}])
def test_partition_argument(): G = nx.barbell_graph(3, 0) partition = [{0, 1, 2}, {3, 4, 5}] split = kernighan_lin_bisection(G, partition) assert_partition_equal(split, partition)
def test_partition_argument_non_integer_nodes(): G = nx.Graph([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")]) partition = ({"A", "B"}, {"C", "D"}) split = kernighan_lin_bisection(G, partition) assert_partition_equal(split, partition)
def test_seed_argument(): G = nx.barbell_graph(3, 0) split = kernighan_lin_bisection(G, seed=1) assert_partition_equal(split, [{0, 1, 2}, {3, 4, 5}])
def test_non_disjoint_partition(): with pytest.raises(nx.NetworkXError): G = nx.barbell_graph(3, 0) partition = ({0, 1, 2}, {2, 3, 4, 5}) kernighan_lin_bisection(G, partition)
def test_kernighan_lin_too_many_blocks(): with pytest.raises(nx.NetworkXError): G = nx.barbell_graph(3, 0) partition = ({0, 1}, {2}, {3, 4, 5}) kernighan_lin_bisection(G, partition)
def test_multigraph(): G = nx.cycle_graph(4) M = nx.MultiGraph(G.edges()) M.add_edges_from(G.edges()) M.remove_edge(1, 2) for labels in permutations(range(4)): mapping = dict(zip(M, labels)) A, B = kernighan_lin_bisection(nx.relabel_nodes(M, mapping), seed=0) assert_partition_equal( [A, B], [{mapping[0], mapping[1]}, {mapping[2], mapping[3]}] )
def test_max_iter_argument(): G = nx.Graph( [ ("A", "B", {"weight": 1}), ("A", "C", {"weight": 2}), ("A", "D", {"weight": 3}), ("A", "E", {"weight": 2}), ("A", "F", {"weight": 4}), ("B", "C", {"weight": 1}), ("B", "D", {"weight": 4}), ("B", "E", {"weight": 2}), ("B", "F", {"weight": 1}), ("C", "D", {"weight": 3}), ("C", "E", {"weight": 2}), ("C", "F", {"weight": 1}), ("D", "E", {"weight": 4}), ("D", "F", {"weight": 3}), ("E", "F", {"weight": 2}), ] ) partition = ({"A", "B", "C"}, {"D", "E", "F"}) split = kernighan_lin_bisection(G, partition, max_iter=1) assert_partition_equal(split, ({"A", "F", "C"}, {"D", "E", "B"}))
def test_weight_function(): G = nx.cycle_graph(4)
def my_weight(u, v, d): if u == 2 and v == 3: return None return u + v
split = kernighan_lin_bisection(G, weight=my_weight) assert_partition_equal(split, ({1, 2}, {0, 3}))
## Test Spectral Modularity Bipartition
def test_spectral_bipartition(): pytest.importorskip("scipy") G = nx.barbell_graph(3, 0) split = nx.community.spectral_modularity_bipartition(G) soln = ({3, 4, 5}, {0, 1, 2}) assert set(map(frozenset, split)) == set(map(frozenset, soln))
def test_karate_club(): pytest.importorskip("scipy") G = nx.karate_club_graph() MrHi = {v for v, club in G.nodes.data("club") if club == "Mr. Hi"} Officer = {v for v, club in G.nodes.data("club") if club == "Officer"} split = nx.community.spectral_modularity_bipartition(G)
# spectral method misplaces member 8 MrHi.remove(8) Officer.add(8) soln = (MrHi, Officer) assert set(map(frozenset, split)) == set(map(frozenset, soln))
## Test Node Swap Greedy Bipartition
def test_greedy_bipartition(): G = nx.barbell_graph(3, 0) split = nx.community.greedy_node_swap_bipartition(G) soln = ({0, 1, 2}, {3, 4, 5}) assert set(map(frozenset, split)) == set(map(frozenset, soln))
def test_greedy_non_disjoint_partition(): G = nx.barbell_graph(3, 0) split = ({0, 1, 2}, {2, 3, 4, 5}) with pytest.raises(nx.NetworkXError): nx.community.greedy_node_swap_bipartition(G, init_split=split)
def test_greedy_node_swap_too_many_blocks(): G = nx.barbell_graph(3, 0) split = ({0, 1}, {2}, {3, 4, 5}) with pytest.raises(nx.NetworkXError): nx.community.greedy_node_swap_bipartition(G, init_split=split)
def test_greedy_multigraph_disallowed(): with pytest.raises(nx.NetworkXNotImplemented): nx.community.greedy_node_swap_bipartition(nx.MultiGraph())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Unit tests for the :mod:`networkx.algorithms.community.centrality`module.
"""
from operator import itemgetter
import networkx as nx
def set_of_sets(iterable): return set(map(frozenset, iterable))
def validate_communities(result, expected): assert set_of_sets(result) == set_of_sets(expected)
def validate_possible_communities(result, *expected): assert any(set_of_sets(result) == set_of_sets(p) for p in expected)
class TestGirvanNewman: """Unit tests for the :func:`networkx.algorithms.community.centrality.girvan_newman` function.
"""
def test_no_edges(self): G = nx.empty_graph(3) communities = list(nx.community.girvan_newman(G)) assert len(communities) == 1 validate_communities(communities[0], [{0}, {1}, {2}])
def test_undirected(self): # Start with the graph .-.-.-. G = nx.path_graph(4) communities = list(nx.community.girvan_newman(G)) assert len(communities) == 3 # After one removal, we get the graph .-. .-. validate_communities(communities[0], [{0, 1}, {2, 3}]) # After the next, we get the graph .-. . ., but there are two # symmetric possible versions. validate_possible_communities( communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}] ) # After the last removal, we always get the empty graph. validate_communities(communities[2], [{0}, {1}, {2}, {3}])
def test_directed(self): G = nx.DiGraph(nx.path_graph(4)) communities = list(nx.community.girvan_newman(G)) assert len(communities) == 3 validate_communities(communities[0], [{0, 1}, {2, 3}]) validate_possible_communities( communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}] ) validate_communities(communities[2], [{0}, {1}, {2}, {3}])
def test_selfloops(self): G = nx.path_graph(4) G.add_edge(0, 0) G.add_edge(2, 2) communities = list(nx.community.girvan_newman(G)) assert len(communities) == 3 validate_communities(communities[0], [{0, 1}, {2, 3}]) validate_possible_communities( communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}] ) validate_communities(communities[2], [{0}, {1}, {2}, {3}])
def test_most_valuable_edge(self): G = nx.Graph() G.add_weighted_edges_from([(0, 1, 3), (1, 2, 2), (2, 3, 1)]) # Let the most valuable edge be the one with the highest weight.
def heaviest(G): return max(G.edges(data="weight"), key=itemgetter(2))[:2]
communities = list(nx.community.girvan_newman(G, heaviest)) assert len(communities) == 3 validate_communities(communities[0], [{0}, {1, 2, 3}]) validate_communities(communities[1], [{0}, {1}, {2, 3}]) validate_communities(communities[2], [{0}, {1}, {2}, {3}])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106import pytest
import networkx as nx
def test_edge_betweenness_partition(): G = nx.barbell_graph(3, 0) C = nx.community.edge_betweenness_partition(G, 2) answer = [{0, 1, 2}, {3, 4, 5}] assert len(C) == len(answer) for s in answer: assert s in C
G = nx.barbell_graph(3, 1) C = nx.community.edge_betweenness_partition(G, 3) answer = [{0, 1, 2}, {4, 5, 6}, {3}] assert len(C) == len(answer) for s in answer: assert s in C
C = nx.community.edge_betweenness_partition(G, 7) answer = [{n} for n in G] assert len(C) == len(answer) for s in answer: assert s in C
C = nx.community.edge_betweenness_partition(G, 1) assert C == [set(G)]
C = nx.community.edge_betweenness_partition(G, 1, weight="weight") assert C == [set(G)]
with pytest.raises(nx.NetworkXError): nx.community.edge_betweenness_partition(G, 0)
with pytest.raises(nx.NetworkXError): nx.community.edge_betweenness_partition(G, -1)
with pytest.raises(nx.NetworkXError): nx.community.edge_betweenness_partition(G, 10)
def test_edge_current_flow_betweenness_partition(): pytest.importorskip("scipy")
G = nx.barbell_graph(3, 0) C = nx.community.edge_current_flow_betweenness_partition(G, 2) answer = [{0, 1, 2}, {3, 4, 5}] assert len(C) == len(answer) for s in answer: assert s in C
G = nx.barbell_graph(3, 1) C = nx.community.edge_current_flow_betweenness_partition(G, 2) answers = [[{0, 1, 2, 3}, {4, 5, 6}], [{0, 1, 2}, {3, 4, 5, 6}]] assert len(C) == len(answers[0]) assert any(all(s in answer for s in C) for answer in answers)
C = nx.community.edge_current_flow_betweenness_partition(G, 3) answer = [{0, 1, 2}, {4, 5, 6}, {3}] assert len(C) == len(answer) for s in answer: assert s in C
C = nx.community.edge_current_flow_betweenness_partition(G, 4) answers = [[{1, 2}, {4, 5, 6}, {3}, {0}], [{0, 1, 2}, {5, 6}, {3}, {4}]] assert len(C) == len(answers[0]) assert any(all(s in answer for s in C) for answer in answers)
C = nx.community.edge_current_flow_betweenness_partition(G, 5) answer = [{1, 2}, {5, 6}, {3}, {0}, {4}] assert len(C) == len(answer) for s in answer: assert s in C
C = nx.community.edge_current_flow_betweenness_partition(G, 6) answers = [[{2}, {5, 6}, {3}, {0}, {4}, {1}], [{1, 2}, {6}, {3}, {0}, {4}, {5}]] assert len(C) == len(answers[0]) assert any(all(s in answer for s in C) for answer in answers)
C = nx.community.edge_current_flow_betweenness_partition(G, 7) answer = [{n} for n in G] assert len(C) == len(answer) for s in answer: assert s in C
C = nx.community.edge_current_flow_betweenness_partition(G, 1) assert C == [set(G)]
C = nx.community.edge_current_flow_betweenness_partition(G, 1, weight="weight") assert C == [set(G)]
with pytest.raises(nx.NetworkXError): nx.community.edge_current_flow_betweenness_partition(G, 0)
with pytest.raises(nx.NetworkXError): nx.community.edge_current_flow_betweenness_partition(G, -1)
with pytest.raises(nx.NetworkXError): nx.community.edge_current_flow_betweenness_partition(G, 10)
N = 10 G = nx.empty_graph(N) for i in range(2, N - 1): C = nx.community.edge_current_flow_betweenness_partition(G, i) assert C == [{n} for n in G]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091from itertools import combinations
import pytest
import networkx as nx
def test_overlapping_K5(): G = nx.Graph() G.add_edges_from(combinations(range(5), 2)) # Add a five clique G.add_edges_from(combinations(range(2, 7), 2)) # Add another five clique c = list(nx.community.k_clique_communities(G, 4)) assert c == [frozenset(range(7))] c = set(nx.community.k_clique_communities(G, 5)) assert c == {frozenset(range(5)), frozenset(range(2, 7))}
def test_isolated_K5(): G = nx.Graph() G.add_edges_from(combinations(range(5), 2)) # Add a five clique G.add_edges_from(combinations(range(5, 10), 2)) # Add another five clique c = set(nx.community.k_clique_communities(G, 5)) assert c == {frozenset(range(5)), frozenset(range(5, 10))}
class TestZacharyKarateClub: def setup_method(self): self.G = nx.karate_club_graph()
def _check_communities(self, k, expected): communities = set(nx.community.k_clique_communities(self.G, k)) assert communities == expected
def test_k2(self): # clique percolation with k=2 is just connected components expected = {frozenset(self.G)} self._check_communities(2, expected)
def test_k3(self): comm1 = [ 0, 1, 2, 3, 7, 8, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 26, 27, 28, 29, 30, 31, 32, 33, ] comm2 = [0, 4, 5, 6, 10, 16] comm3 = [24, 25, 31] expected = {frozenset(comm1), frozenset(comm2), frozenset(comm3)} self._check_communities(3, expected)
def test_k4(self): expected = { frozenset([0, 1, 2, 3, 7, 13]), frozenset([8, 32, 30, 33]), frozenset([32, 33, 29, 23]), } self._check_communities(4, expected)
def test_k5(self): expected = {frozenset([0, 1, 2, 3, 7, 13])} self._check_communities(5, expected)
def test_k6(self): expected = set() self._check_communities(6, expected)
def test_bad_k(): with pytest.raises(nx.NetworkXError): list(nx.community.k_clique_communities(nx.Graph(), 1))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241from itertools import chain, combinations
import pytest
import networkx as nx
def test_directed_not_supported(): with pytest.raises(nx.NetworkXNotImplemented): # not supported for directed graphs test = nx.DiGraph() test.add_edge("a", "b") test.add_edge("a", "c") test.add_edge("b", "d") result = nx.community.label_propagation_communities(test)
def test_iterator_vs_iterable(): G = nx.empty_graph("a") assert list(nx.community.label_propagation_communities(G)) == [{"a"}] for community in nx.community.label_propagation_communities(G): assert community == {"a"} pytest.raises(TypeError, next, nx.community.label_propagation_communities(G))
def test_one_node(): test = nx.Graph() test.add_node("a")
# The expected communities are: ground_truth = {frozenset(["a"])}
communities = nx.community.label_propagation_communities(test) result = {frozenset(c) for c in communities} assert result == ground_truth
def test_unconnected_communities(): test = nx.Graph() # community 1 test.add_edge("a", "c") test.add_edge("a", "d") test.add_edge("d", "c") # community 2 test.add_edge("b", "e") test.add_edge("e", "f") test.add_edge("f", "b")
# The expected communities are: ground_truth = {frozenset(["a", "c", "d"]), frozenset(["b", "e", "f"])}
communities = nx.community.label_propagation_communities(test) result = {frozenset(c) for c in communities} assert result == ground_truth
def test_connected_communities(): test = nx.Graph() # community 1 test.add_edge("a", "b") test.add_edge("c", "a") test.add_edge("c", "b") test.add_edge("d", "a") test.add_edge("d", "b") test.add_edge("d", "c") test.add_edge("e", "a") test.add_edge("e", "b") test.add_edge("e", "c") test.add_edge("e", "d") # community 2 test.add_edge("1", "2") test.add_edge("3", "1") test.add_edge("3", "2") test.add_edge("4", "1") test.add_edge("4", "2") test.add_edge("4", "3") test.add_edge("5", "1") test.add_edge("5", "2") test.add_edge("5", "3") test.add_edge("5", "4") # edge between community 1 and 2 test.add_edge("a", "1") # community 3 test.add_edge("x", "y") # community 4 with only a single node test.add_node("z")
# The expected communities are: ground_truth1 = { frozenset(["a", "b", "c", "d", "e"]), frozenset(["1", "2", "3", "4", "5"]), frozenset(["x", "y"]), frozenset(["z"]), } ground_truth2 = { frozenset(["a", "b", "c", "d", "e", "1", "2", "3", "4", "5"]), frozenset(["x", "y"]), frozenset(["z"]), } ground_truth = (ground_truth1, ground_truth2)
communities = nx.community.label_propagation_communities(test) result = {frozenset(c) for c in communities} assert result in ground_truth
def test_termination(): # ensure termination of asyn_lpa_communities in two cases # that led to an endless loop in a previous version test1 = nx.karate_club_graph() test2 = nx.caveman_graph(2, 10) test2.add_edges_from([(0, 20), (20, 10)]) nx.community.asyn_lpa_communities(test1) nx.community.asyn_lpa_communities(test2)
class TestAsynLpaCommunities: def _check_communities(self, G, expected): """Checks that the communities computed from the given graph ``G`` using the :func:`~networkx.asyn_lpa_communities` function match the set of nodes given in ``expected``.
``expected`` must be a :class:`set` of :class:`frozenset` instances, each element of which is a node in the graph.
""" communities = nx.community.asyn_lpa_communities(G) result = {frozenset(c) for c in communities} assert result == expected
def test_null_graph(self): G = nx.null_graph() ground_truth = set() self._check_communities(G, ground_truth)
def test_single_node(self): G = nx.empty_graph(1) ground_truth = {frozenset([0])} self._check_communities(G, ground_truth)
def test_simple_communities(self): # This graph is the disjoint union of two triangles. G = nx.Graph(["ab", "ac", "bc", "de", "df", "fe"]) ground_truth = {frozenset("abc"), frozenset("def")} self._check_communities(G, ground_truth)
def test_seed_argument(self): G = nx.Graph(["ab", "ac", "bc", "de", "df", "fe"]) ground_truth = {frozenset("abc"), frozenset("def")} communities = nx.community.asyn_lpa_communities(G, seed=1) result = {frozenset(c) for c in communities} assert result == ground_truth
def test_several_communities(self): # This graph is the disjoint union of five triangles. ground_truth = {frozenset(range(3 * i, 3 * (i + 1))) for i in range(5)} edges = chain.from_iterable(combinations(c, 2) for c in ground_truth) G = nx.Graph(edges) self._check_communities(G, ground_truth)
class TestFastLabelPropagationCommunities: N = 100 # number of nodes K = 15 # average node degree
def _check_communities(self, G, truth, weight=None, seed=42): C = nx.community.fast_label_propagation_communities(G, weight=weight, seed=seed) assert {frozenset(c) for c in C} == truth
def test_null_graph(self): G = nx.null_graph() truth = set() self._check_communities(G, truth)
def test_empty_graph(self): G = nx.empty_graph(self.N) truth = {frozenset([i]) for i in G} self._check_communities(G, truth)
def test_star_graph(self): G = nx.star_graph(self.N) truth = {frozenset(G)} self._check_communities(G, truth)
def test_complete_graph(self): G = nx.complete_graph(self.N) truth = {frozenset(G)} self._check_communities(G, truth)
def test_bipartite_graph(self): G = nx.complete_bipartite_graph(self.N // 2, self.N // 2) truth = {frozenset(G)} self._check_communities(G, truth)
def test_random_graph(self): G = nx.gnm_random_graph(self.N, self.N * self.K // 2, seed=42) truth = {frozenset(G)} self._check_communities(G, truth)
def test_disjoin_cliques(self): G = nx.Graph(["ab", "AB", "AC", "BC", "12", "13", "14", "23", "24", "34"]) truth = {frozenset("ab"), frozenset("ABC"), frozenset("1234")} self._check_communities(G, truth)
def test_ring_of_cliques(self): N, K = self.N, self.K G = nx.ring_of_cliques(N, K) truth = {frozenset([K * i + k for k in range(K)]) for i in range(N)} self._check_communities(G, truth)
def test_larger_graph(self): G = nx.gnm_random_graph(100 * self.N, 50 * self.N * self.K, seed=42) nx.community.fast_label_propagation_communities(G)
def test_graph_type(self): G1 = nx.complete_graph(self.N, nx.MultiDiGraph()) G2 = nx.MultiGraph(G1) G3 = nx.DiGraph(G1) G4 = nx.Graph(G1) truth = {frozenset(G1)} self._check_communities(G1, truth) self._check_communities(G2, truth) self._check_communities(G3, truth) self._check_communities(G4, truth)
def test_weight_argument(self): G = nx.MultiDiGraph() G.add_edge(1, 2, weight=1.41) G.add_edge(2, 1, weight=1.41) G.add_edge(2, 3) G.add_edge(3, 4, weight=3.14) truth = {frozenset({1, 2}), frozenset({3, 4})} self._check_communities(G, truth, weight="weight")
def test_seed_argument(self): G = nx.karate_club_graph() C = nx.community.fast_label_propagation_communities(G, seed=2023) truth = {frozenset(c) for c in C} self._check_communities(G, truth, seed=2023) # smoke test that seed=None works C = nx.community.fast_label_propagation_communities(G, seed=None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138import pytest
import networkx as nxfrom networkx.algorithms.community import leiden_communities, leiden_partitions
# Leiden is not yet implemented by networkx, so only run tests in this file for# backends that implement Leiden.no_backends_for_leiden_communities = ( "not set(nx.config.backend_priority.algos) & leiden_communities.backends")
no_backends_for_leiden_partitions = ( "not set(nx.config.backend_priority.algos) & leiden_partitions.backends")
def test_leiden_with_nx_backend(): G = nx.karate_club_graph() with pytest.raises(NotImplementedError): nx.community.leiden_partitions(G, backend="networkx") with pytest.raises(NotImplementedError): nx.community.leiden_communities(G, backend="networkx")
@pytest.mark.skipif(no_backends_for_leiden_communities)def test_modularity_increase(): G = nx.LFR_benchmark_graph( 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10 ) partition = [{u} for u in G.nodes()] mod = nx.community.modularity(G, partition) partition = nx.community.leiden_communities(G)
assert nx.community.modularity(G, partition) > mod
@pytest.mark.skipif(no_backends_for_leiden_communities)def test_valid_partition(): G = nx.LFR_benchmark_graph( 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10 ) partition = nx.community.leiden_communities(G)
assert nx.community.is_partition(G, partition)
@pytest.mark.skipif(no_backends_for_leiden_partitions)def test_partition_iterator(): G = nx.path_graph(15) parts_iter = nx.community.leiden_partitions(G, seed=42) first_part = next(parts_iter) first_copy = [s.copy() for s in first_part]
# check 1st part stays fixed even after 2nd iteration (like gh-5901 in louvain) assert first_copy[0] == first_part[0] second_part = next(parts_iter) assert first_copy[0] == first_part[0]
@pytest.mark.skipif(no_backends_for_leiden_communities)def test_none_weight_param(): G = nx.karate_club_graph() nx.set_edge_attributes( G, {edge: i * i for i, edge in enumerate(G.edges)}, name="foo" )
partition1 = nx.community.leiden_communities(G, weight=None, seed=2) partition2 = nx.community.leiden_communities(G, weight="foo", seed=2) partition3 = nx.community.leiden_communities(G, weight="weight", seed=2)
assert partition1 != partition2 assert partition2 != partition3
@pytest.mark.skipif(no_backends_for_leiden_communities)def test_quality(): G = nx.LFR_benchmark_graph( 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10 ) H = nx.MultiGraph(G)
partition = nx.community.leiden_communities(G) partition2 = nx.community.leiden_communities(H)
quality = nx.community.partition_quality(G, partition)[0] quality2 = nx.community.partition_quality(H, partition2)[0]
assert quality >= 0.65 assert quality2 >= 0.65
@pytest.mark.skipif(no_backends_for_leiden_communities)def test_resolution(): G = nx.LFR_benchmark_graph( 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10 )
partition1 = nx.community.leiden_communities(G, resolution=0.5, seed=12) partition2 = nx.community.leiden_communities(G, seed=12) partition3 = nx.community.leiden_communities(G, resolution=2, seed=12)
assert len(partition1) <= len(partition2) assert len(partition2) <= len(partition3)
@pytest.mark.skipif(no_backends_for_leiden_communities)def test_empty_graph(): G = nx.Graph() G.add_nodes_from(range(5)) expected = [{0}, {1}, {2}, {3}, {4}] assert nx.community.leiden_communities(G) == expected
@pytest.mark.skipif(no_backends_for_leiden_communities)def test_directed_not_implemented(): G = nx.cycle_graph(4, create_using=nx.DiGraph) with pytest.raises(nx.NetworkXNotImplemented): nx.community.leiden_communities(G)
@pytest.mark.skipif(no_backends_for_leiden_partitions)@pytest.mark.skipif(no_backends_for_leiden_communities)def test_max_level(): G = nx.LFR_benchmark_graph( 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10 ) parts_iter = nx.community.leiden_partitions(G, seed=42) for max_level, expected in enumerate(parts_iter, 1): partition = nx.community.leiden_communities(G, max_level=max_level, seed=42) assert partition == expected assert max_level > 1 # Ensure we are actually testing max_level # max_level is an upper limit; it's okay if we stop before it's hit. partition = nx.community.leiden_communities(G, max_level=max_level + 1, seed=42) assert partition == expected with pytest.raises( ValueError, match="max_level argument must be a positive integer" ): nx.community.leiden_communities(G, max_level=0)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import pytest
import networkx as nx
def test_greedy_source_expansion_karate_club(): G = nx.karate_club_graph()
community = nx.community.greedy_source_expansion(G, source=16)
expected = {0, 4, 5, 6, 10, 16}
assert community == expected
def test_greedy_source_expansion_cutoff(): G = nx.karate_club_graph()
community = nx.community.greedy_source_expansion(G, source=16, cutoff=3)
assert community == {5, 6, 16}
def test_greedy_source_expansion_invalid_method(): G = nx.karate_club_graph()
with pytest.raises(ValueError): nx.community.greedy_source_expansion(G, source=16, cutoff=3, method="invalid")
def test_greedy_source_expansion_connected_component(): G_edges = [(0, 2), (0, 1), (1, 0), (2, 1), (2, 0), (3, 4), (4, 3)] G = nx.Graph(G_edges) expected = {0, 1, 2} community = nx.community.greedy_source_expansion(G, source=0) assert community == expected
def test_greedy_source_expansion_directed_graph(): G_edges = [ (0, 2), (0, 1), (1, 0), (2, 1), (2, 0), (3, 4), (4, 3), (4, 5), (5, 3), (5, 6), (0, 6), ] G = nx.DiGraph(G_edges)
expected = {0, 1, 2, 6} community = nx.community.greedy_source_expansion(G, source=0) assert community == expected
def test_greedy_source_expansion_multigraph(): G = nx.MultiGraph(nx.karate_club_graph()) G.add_edge(0, 1) G.add_edge(0, 9)
expected = {0, 4, 5, 6, 10, 16}
community = nx.community.greedy_source_expansion(G, source=16)
assert community == expected
def test_greedy_source_expansion_empty_graph(): G = nx.Graph() G.add_nodes_from(range(5)) expected = {0} assert nx.community.greedy_source_expansion(G, source=0) == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264import pytest
import networkx as nx
def test_modularity_increase(): G = nx.LFR_benchmark_graph( 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10 ) partition = [{u} for u in G.nodes()] mod = nx.community.modularity(G, partition) partition = nx.community.louvain_communities(G)
assert nx.community.modularity(G, partition) > mod
def test_valid_partition(): G = nx.LFR_benchmark_graph( 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10 ) H = G.to_directed() partition = nx.community.louvain_communities(G) partition2 = nx.community.louvain_communities(H)
assert nx.community.is_partition(G, partition) assert nx.community.is_partition(H, partition2)
def test_karate_club_partition(): G = nx.karate_club_graph() part = [ {0, 1, 2, 3, 7, 9, 11, 12, 13, 17, 19, 21}, {16, 4, 5, 6, 10}, {23, 25, 27, 28, 24, 31}, {32, 33, 8, 14, 15, 18, 20, 22, 26, 29, 30}, ] partition = nx.community.louvain_communities(G, seed=2, weight=None)
assert part == partition
def test_partition_iterator(): G = nx.path_graph(15) parts_iter = nx.community.louvain_partitions(G, seed=42) first_part = next(parts_iter) first_copy = [s.copy() for s in first_part]
# gh-5901 reports sets changing after next partition is yielded assert first_copy[0] == first_part[0] second_part = next(parts_iter) assert first_copy[0] == first_part[0]
def test_undirected_selfloops(): G = nx.karate_club_graph() expected_partition = nx.community.louvain_communities(G, seed=2, weight=None) part = [ {0, 1, 2, 3, 7, 9, 11, 12, 13, 17, 19, 21}, {16, 4, 5, 6, 10}, {23, 25, 27, 28, 24, 31}, {32, 33, 8, 14, 15, 18, 20, 22, 26, 29, 30}, ] assert expected_partition == part
G.add_weighted_edges_from([(i, i, i * 1000) for i in range(9)]) # large self-loop weight impacts partition partition = nx.community.louvain_communities(G, seed=2, weight="weight") assert part != partition
# small self-loop weights aren't enough to impact partition in this graph partition = nx.community.louvain_communities(G, seed=2, weight=None) assert part == partition
def test_directed_selfloops(): G = nx.DiGraph() G.add_nodes_from(range(11)) G_edges = [ (0, 2), (0, 1), (1, 0), (2, 1), (2, 0), (3, 4), (4, 3), (7, 8), (8, 7), (9, 10), (10, 9), ] G.add_edges_from(G_edges) G_expected_partition = nx.community.louvain_communities(G, seed=123, weight=None)
G.add_weighted_edges_from([(i, i, i * 1000) for i in range(3)]) # large self-loop weight impacts partition G_partition = nx.community.louvain_communities(G, seed=123, weight="weight") assert G_partition != G_expected_partition
# small self-loop weights aren't enough to impact partition in this graph G_partition = nx.community.louvain_communities(G, seed=123, weight=None) assert G_partition == G_expected_partition
def test_directed_partition(): """ Test 2 cases that were looping infinitely from issues #5175 and #5704 """ G = nx.DiGraph() H = nx.DiGraph() G.add_nodes_from(range(10)) H.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) G_edges = [ (0, 2), (0, 1), (1, 0), (2, 1), (2, 0), (3, 4), (4, 3), (7, 8), (8, 7), (9, 10), (10, 9), ] H_edges = [ (1, 2), (1, 6), (1, 9), (2, 3), (2, 4), (2, 5), (3, 4), (4, 3), (4, 5), (5, 4), (6, 7), (6, 8), (9, 10), (9, 11), (10, 11), (11, 10), ] G.add_edges_from(G_edges) H.add_edges_from(H_edges)
G_expected_partition = [{0, 1, 2}, {3, 4}, {5}, {6}, {8, 7}, {9, 10}] G_partition = nx.community.louvain_communities(G, seed=123, weight=None)
H_expected_partition = [{2, 3, 4, 5}, {8, 1, 6, 7}, {9, 10, 11}] H_partition = nx.community.louvain_communities(H, seed=123, weight=None)
assert G_partition == G_expected_partition assert H_partition == H_expected_partition
def test_none_weight_param(): G = nx.karate_club_graph() nx.set_edge_attributes( G, {edge: i * i for i, edge in enumerate(G.edges)}, name="foo" )
part = [ {0, 1, 2, 3, 7, 9, 11, 12, 13, 17, 19, 21}, {16, 4, 5, 6, 10}, {23, 25, 27, 28, 24, 31}, {32, 33, 8, 14, 15, 18, 20, 22, 26, 29, 30}, ] partition1 = nx.community.louvain_communities(G, weight=None, seed=2) partition2 = nx.community.louvain_communities(G, weight="foo", seed=2) partition3 = nx.community.louvain_communities(G, weight="weight", seed=2)
assert part == partition1 assert part != partition2 assert part != partition3 assert partition2 != partition3
def test_quality(): G = nx.LFR_benchmark_graph( 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10 ) H = nx.gn_graph(200, seed=1234) I = nx.MultiGraph(G) J = nx.MultiDiGraph(H)
partition = nx.community.louvain_communities(G) partition2 = nx.community.louvain_communities(H) partition3 = nx.community.louvain_communities(I) partition4 = nx.community.louvain_communities(J)
quality = nx.community.partition_quality(G, partition)[0] quality2 = nx.community.partition_quality(H, partition2)[0] quality3 = nx.community.partition_quality(I, partition3)[0] quality4 = nx.community.partition_quality(J, partition4)[0]
assert quality >= 0.65 assert quality2 >= 0.65 assert quality3 >= 0.65 assert quality4 >= 0.65
def test_multigraph(): G = nx.karate_club_graph() H = nx.MultiGraph(G) G.add_edge(0, 1, weight=10) H.add_edge(0, 1, weight=9) G.add_edge(0, 9, foo=20) H.add_edge(0, 9, foo=20)
partition1 = nx.community.louvain_communities(G, seed=1234) partition2 = nx.community.louvain_communities(H, seed=1234) partition3 = nx.community.louvain_communities(H, weight="foo", seed=1234)
assert partition1 == partition2 != partition3
def test_resolution(): G = nx.LFR_benchmark_graph( 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10 )
partition1 = nx.community.louvain_communities(G, resolution=0.5, seed=12) partition2 = nx.community.louvain_communities(G, seed=12) partition3 = nx.community.louvain_communities(G, resolution=2, seed=12)
assert len(partition1) <= len(partition2) <= len(partition3)
def test_threshold(): G = nx.LFR_benchmark_graph( 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10 ) partition1 = nx.community.louvain_communities(G, threshold=0.3, seed=2) partition2 = nx.community.louvain_communities(G, seed=2) mod1 = nx.community.modularity(G, partition1) mod2 = nx.community.modularity(G, partition2)
assert mod1 <= mod2
def test_empty_graph(): G = nx.Graph() G.add_nodes_from(range(5)) expected = [{0}, {1}, {2}, {3}, {4}] assert nx.community.louvain_communities(G) == expected
def test_max_level(): G = nx.LFR_benchmark_graph( 250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10 ) parts_iter = nx.community.louvain_partitions(G, seed=42) for max_level, expected in enumerate(parts_iter, 1): partition = nx.community.louvain_communities(G, max_level=max_level, seed=42) assert partition == expected assert max_level > 1 # Ensure we are actually testing max_level # max_level is an upper limit; it's okay if we stop before it's hit. partition = nx.community.louvain_communities(G, max_level=max_level + 1, seed=42) assert partition == expected with pytest.raises( ValueError, match="max_level argument must be a positive integer" ): nx.community.louvain_communities(G, max_level=0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152from itertools import product
import pytest
import networkx as nx
EWL = "e_weight"NWL = "n_weight"
# first test from the Lukes original paperdef paper_1_case(float_edge_wt=False, explicit_node_wt=True, directed=False): # problem-specific constants limit = 3
# configuration if float_edge_wt: shift = 0.001 else: shift = 0
if directed: example_1 = nx.DiGraph() else: example_1 = nx.Graph()
# graph creation example_1.add_edge(1, 2, **{EWL: 3 + shift}) example_1.add_edge(1, 4, **{EWL: 2 + shift}) example_1.add_edge(2, 3, **{EWL: 4 + shift}) example_1.add_edge(2, 5, **{EWL: 6 + shift})
# node weights if explicit_node_wt: nx.set_node_attributes(example_1, 1, NWL) wtu = NWL else: wtu = None
# partitioning clusters_1 = { frozenset(x) for x in nx.community.lukes_partitioning( example_1, limit, node_weight=wtu, edge_weight=EWL ) }
return clusters_1
# second test from the Lukes original paperdef paper_2_case(explicit_edge_wt=True, directed=False): # problem specific constants byte_block_size = 32
# configuration if directed: example_2 = nx.DiGraph() else: example_2 = nx.Graph()
if explicit_edge_wt: edic = {EWL: 1} wtu = EWL else: edic = {} wtu = None
# graph creation example_2.add_edge("name", "home_address", **edic) example_2.add_edge("name", "education", **edic) example_2.add_edge("education", "bs", **edic) example_2.add_edge("education", "ms", **edic) example_2.add_edge("education", "phd", **edic) example_2.add_edge("name", "telephone", **edic) example_2.add_edge("telephone", "home", **edic) example_2.add_edge("telephone", "office", **edic) example_2.add_edge("office", "no1", **edic) example_2.add_edge("office", "no2", **edic)
example_2.nodes["name"][NWL] = 20 example_2.nodes["education"][NWL] = 10 example_2.nodes["bs"][NWL] = 1 example_2.nodes["ms"][NWL] = 1 example_2.nodes["phd"][NWL] = 1 example_2.nodes["home_address"][NWL] = 8 example_2.nodes["telephone"][NWL] = 8 example_2.nodes["home"][NWL] = 8 example_2.nodes["office"][NWL] = 4 example_2.nodes["no1"][NWL] = 1 example_2.nodes["no2"][NWL] = 1
# partitioning clusters_2 = { frozenset(x) for x in nx.community.lukes_partitioning( example_2, byte_block_size, node_weight=NWL, edge_weight=wtu ) }
return clusters_2
def test_paper_1_case(): ground_truth = {frozenset([1, 4]), frozenset([2, 3, 5])}
tf = (True, False) for flt, nwt, drc in product(tf, tf, tf): part = paper_1_case(flt, nwt, drc) assert part == ground_truth
def test_paper_2_case(): ground_truth = { frozenset(["education", "bs", "ms", "phd"]), frozenset(["name", "home_address"]), frozenset(["telephone", "home", "office", "no1", "no2"]), }
tf = (True, False) for ewt, drc in product(tf, tf): part = paper_2_case(ewt, drc) assert part == ground_truth
def test_mandatory_tree(): not_a_tree = nx.complete_graph(4)
with pytest.raises(nx.NotATree): nx.community.lukes_partitioning(not_a_tree, 5)
def test_mandatory_integrality(): byte_block_size = 32
ex_1_broken = nx.DiGraph()
ex_1_broken.add_edge(1, 2, **{EWL: 3.2}) ex_1_broken.add_edge(1, 4, **{EWL: 2.4}) ex_1_broken.add_edge(2, 3, **{EWL: 4.0}) ex_1_broken.add_edge(2, 5, **{EWL: 6.3})
ex_1_broken.nodes[1][NWL] = 1.2 # ! ex_1_broken.nodes[2][NWL] = 1 ex_1_broken.nodes[3][NWL] = 1 ex_1_broken.nodes[4][NWL] = 1 ex_1_broken.nodes[5][NWL] = 2
with pytest.raises(TypeError): nx.community.lukes_partitioning( ex_1_broken, byte_block_size, node_weight=NWL, edge_weight=EWL )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340import pytest
import networkx as nxfrom networkx.algorithms.community import ( greedy_modularity_communities, naive_greedy_modularity_communities,)
@pytest.mark.parametrize( "func", (greedy_modularity_communities, naive_greedy_modularity_communities))def test_modularity_communities(func): G = nx.karate_club_graph() john_a = frozenset( [8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33] ) mr_hi = frozenset([0, 4, 5, 6, 10, 11, 16, 19]) overlap = frozenset([1, 2, 3, 7, 9, 12, 13, 17, 21]) expected = {john_a, overlap, mr_hi} assert set(func(G, weight=None)) == expected
@pytest.mark.parametrize( "func", (greedy_modularity_communities, naive_greedy_modularity_communities))def test_modularity_communities_categorical_labels(func): # Using other than 0-starting contiguous integers as node-labels. G = nx.Graph( [ ("a", "b"), ("a", "c"), ("b", "c"), ("b", "d"), # inter-community edge ("d", "e"), ("d", "f"), ("d", "g"), ("f", "g"), ("d", "e"), ("f", "e"), ] ) expected = {frozenset({"f", "g", "e", "d"}), frozenset({"a", "b", "c"})} assert set(func(G)) == expected
def test_greedy_modularity_communities_components(): # Test for gh-5530 G = nx.Graph([(0, 1), (2, 3), (4, 5), (5, 6)]) # usual case with 3 components assert greedy_modularity_communities(G) == [{4, 5, 6}, {0, 1}, {2, 3}] # best_n can make the algorithm continue even when modularity goes down assert greedy_modularity_communities(G, best_n=3) == [{4, 5, 6}, {0, 1}, {2, 3}] assert greedy_modularity_communities(G, best_n=2) == [{0, 1, 4, 5, 6}, {2, 3}] assert greedy_modularity_communities(G, best_n=1) == [{0, 1, 2, 3, 4, 5, 6}]
def test_greedy_modularity_communities_relabeled(): # Test for gh-4966 G = nx.balanced_tree(2, 2) mapping = {0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 7: "h"} G = nx.relabel_nodes(G, mapping) expected = [frozenset({"e", "d", "a", "b"}), frozenset({"c", "f", "g"})] assert greedy_modularity_communities(G) == expected
def test_greedy_modularity_communities_directed(): G = nx.DiGraph( [ ("a", "b"), ("a", "c"), ("b", "c"), ("b", "d"), # inter-community edge ("d", "e"), ("d", "f"), ("d", "g"), ("f", "g"), ("d", "e"), ("f", "e"), ] ) expected = [frozenset({"f", "g", "e", "d"}), frozenset({"a", "b", "c"})] assert greedy_modularity_communities(G) == expected
# with loops G = nx.DiGraph() G.add_edges_from( [(1, 1), (1, 2), (1, 3), (2, 3), (1, 4), (4, 4), (5, 5), (4, 5), (4, 6), (5, 6)] ) expected = [frozenset({1, 2, 3}), frozenset({4, 5, 6})] assert greedy_modularity_communities(G) == expected
@pytest.mark.parametrize( "func", (greedy_modularity_communities, naive_greedy_modularity_communities))def test_modularity_communities_weighted(func): G = nx.balanced_tree(2, 3) for a, b in G.edges: if ((a == 1) or (a == 2)) and (b != 0): G[a][b]["weight"] = 10.0 else: G[a][b]["weight"] = 1.0
expected = [{0, 1, 3, 4, 7, 8, 9, 10}, {2, 5, 6, 11, 12, 13, 14}]
assert func(G, weight="weight") == expected assert func(G, weight="weight", resolution=0.9) == expected assert func(G, weight="weight", resolution=0.3) == expected assert func(G, weight="weight", resolution=1.1) != expected
def test_modularity_communities_floating_point(): # check for floating point error when used as key in the mapped_queue dict. # Test for gh-4992 and gh-5000 G = nx.Graph() G.add_weighted_edges_from( [(0, 1, 12), (1, 4, 71), (2, 3, 15), (2, 4, 10), (3, 6, 13)] ) expected = [{0, 1, 4}, {2, 3, 6}] assert greedy_modularity_communities(G, weight="weight") == expected assert ( greedy_modularity_communities(G, weight="weight", resolution=0.99) == expected )
def test_modularity_communities_directed_weighted(): G = nx.DiGraph() G.add_weighted_edges_from( [ (1, 2, 5), (1, 3, 3), (2, 3, 6), (2, 6, 1), (1, 4, 1), (4, 5, 3), (4, 6, 7), (5, 6, 2), (5, 7, 5), (5, 8, 4), (6, 8, 3), ] ) expected = [frozenset({4, 5, 6, 7, 8}), frozenset({1, 2, 3})] assert greedy_modularity_communities(G, weight="weight") == expected
# A large weight of the edge (2, 6) causes 6 to change group, even if it shares # only one connection with the new group and 3 with the old one. G[2][6]["weight"] = 20 expected = [frozenset({1, 2, 3, 6}), frozenset({4, 5, 7, 8})] assert greedy_modularity_communities(G, weight="weight") == expected
def test_greedy_modularity_communities_multigraph(): G = nx.MultiGraph() G.add_edges_from( [ (1, 2), (1, 2), (1, 3), (2, 3), (1, 4), (2, 4), (4, 5), (5, 6), (5, 7), (5, 7), (6, 7), (7, 8), (5, 8), ] ) expected = [frozenset({1, 2, 3, 4}), frozenset({5, 6, 7, 8})] assert greedy_modularity_communities(G) == expected
# Converting (4, 5) into a multi-edge causes node 4 to change group. G.add_edge(4, 5) expected = [frozenset({4, 5, 6, 7, 8}), frozenset({1, 2, 3})] assert greedy_modularity_communities(G) == expected
def test_greedy_modularity_communities_multigraph_weighted(): G = nx.MultiGraph() G.add_weighted_edges_from( [ (1, 2, 5), (1, 2, 3), (1, 3, 6), (1, 3, 6), (2, 3, 4), (1, 4, 1), (1, 4, 1), (2, 4, 3), (2, 4, 3), (4, 5, 1), (5, 6, 3), (5, 6, 7), (5, 6, 4), (5, 7, 9), (5, 7, 9), (6, 7, 8), (7, 8, 2), (7, 8, 2), (5, 8, 6), (5, 8, 6), ] ) expected = [frozenset({1, 2, 3, 4}), frozenset({5, 6, 7, 8})] assert greedy_modularity_communities(G, weight="weight") == expected
# Adding multi-edge (4, 5, 16) causes node 4 to change group. G.add_edge(4, 5, weight=16) expected = [frozenset({4, 5, 6, 7, 8}), frozenset({1, 2, 3})] assert greedy_modularity_communities(G, weight="weight") == expected
# Increasing the weight of edge (1, 4) causes node 4 to return to the former group. G[1][4][1]["weight"] = 3 expected = [frozenset({1, 2, 3, 4}), frozenset({5, 6, 7, 8})] assert greedy_modularity_communities(G, weight="weight") == expected
def test_greed_modularity_communities_multidigraph(): G = nx.MultiDiGraph() G.add_edges_from( [ (1, 2), (1, 2), (3, 1), (2, 3), (2, 3), (3, 2), (1, 4), (2, 4), (4, 2), (4, 5), (5, 6), (5, 6), (6, 5), (5, 7), (6, 7), (7, 8), (5, 8), (8, 4), ] ) expected = [frozenset({1, 2, 3, 4}), frozenset({5, 6, 7, 8})] assert greedy_modularity_communities(G, weight="weight") == expected
def test_greed_modularity_communities_multidigraph_weighted(): G = nx.MultiDiGraph() G.add_weighted_edges_from( [ (1, 2, 5), (1, 2, 3), (3, 1, 6), (1, 3, 6), (3, 2, 4), (1, 4, 2), (1, 4, 5), (2, 4, 3), (3, 2, 8), (4, 2, 3), (4, 3, 5), (4, 5, 2), (5, 6, 3), (5, 6, 7), (6, 5, 4), (5, 7, 9), (5, 7, 9), (7, 6, 8), (7, 8, 2), (8, 7, 2), (5, 8, 6), (5, 8, 6), ] ) expected = [frozenset({1, 2, 3, 4}), frozenset({5, 6, 7, 8})] assert greedy_modularity_communities(G, weight="weight") == expected
def test_resolution_parameter_impact(): G = nx.barbell_graph(5, 3)
gamma = 1 expected = [frozenset(range(5)), frozenset(range(8, 13)), frozenset(range(5, 8))] assert greedy_modularity_communities(G, resolution=gamma) == expected assert naive_greedy_modularity_communities(G, resolution=gamma) == expected
gamma = 2.5 expected = [{0, 1, 2, 3}, {9, 10, 11, 12}, {5, 6, 7}, {4}, {8}] assert greedy_modularity_communities(G, resolution=gamma) == expected assert naive_greedy_modularity_communities(G, resolution=gamma) == expected
gamma = 0.3 expected = [frozenset(range(8)), frozenset(range(8, 13))] assert greedy_modularity_communities(G, resolution=gamma) == expected assert naive_greedy_modularity_communities(G, resolution=gamma) == expected
def test_cutoff_parameter(): G = nx.circular_ladder_graph(4)
# No aggregation: expected = [{k} for k in range(8)] assert greedy_modularity_communities(G, cutoff=8) == expected
# Aggregation to half order (number of nodes) expected = [{k, k + 1} for k in range(0, 8, 2)] assert greedy_modularity_communities(G, cutoff=4) == expected
# Default aggregation case (here, 2 communities emerge) expected = [frozenset(range(4)), frozenset(range(4, 8))] assert greedy_modularity_communities(G, cutoff=1) == expected
def test_best_n(): G = nx.barbell_graph(5, 3)
# Same result as without enforcing cutoff: best_n = 3 expected = [frozenset(range(5)), frozenset(range(8, 13)), frozenset(range(5, 8))] assert greedy_modularity_communities(G, best_n=best_n) == expected
# One additional merging step: best_n = 2 expected = [frozenset(range(8)), frozenset(range(8, 13))] assert greedy_modularity_communities(G, best_n=best_n) == expected
# Two additional merging steps: best_n = 1 expected = [frozenset(range(13))] assert greedy_modularity_communities(G, best_n=best_n) == expected
def test_greedy_modularity_communities_corner_cases(): G = nx.empty_graph() assert nx.community.greedy_modularity_communities(G) == [] G.add_nodes_from(range(3)) assert nx.community.greedy_modularity_communities(G) == [{0}, {1}, {2}]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139"""Unit tests for the :mod:`networkx.algorithms.community.quality`module.
"""
import pytest
import networkx as nxfrom networkx import barbell_graphfrom networkx.algorithms.community import modularity, partition_qualityfrom networkx.algorithms.community.quality import inter_community_edges
class TestPerformance: """Unit tests for the :func:`performance` function."""
def test_bad_partition(self): """Tests that a poor partition has a low performance measure.""" G = barbell_graph(3, 0) partition = [{0, 1, 4}, {2, 3, 5}] assert 8 / 15 == pytest.approx(partition_quality(G, partition)[1], abs=1e-7)
def test_good_partition(self): """Tests that a good partition has a high performance measure.""" G = barbell_graph(3, 0) partition = [{0, 1, 2}, {3, 4, 5}] assert 14 / 15 == pytest.approx(partition_quality(G, partition)[1], abs=1e-7)
class TestCoverage: """Unit tests for the :func:`coverage` function."""
def test_bad_partition(self): """Tests that a poor partition has a low coverage measure.""" G = barbell_graph(3, 0) partition = [{0, 1, 4}, {2, 3, 5}] assert 3 / 7 == pytest.approx(partition_quality(G, partition)[0], abs=1e-7)
def test_good_partition(self): """Tests that a good partition has a high coverage measure.""" G = barbell_graph(3, 0) partition = [{0, 1, 2}, {3, 4, 5}] assert 6 / 7 == pytest.approx(partition_quality(G, partition)[0], abs=1e-7)
def test_modularity(): G = nx.barbell_graph(3, 0) C = [{0, 1, 4}, {2, 3, 5}] assert (-16 / (14**2)) == pytest.approx(modularity(G, C), abs=1e-7) C = [{0, 1, 2}, {3, 4, 5}] assert (35 * 2) / (14**2) == pytest.approx(modularity(G, C), abs=1e-7)
n = 1000 G = nx.erdos_renyi_graph(n, 0.09, seed=42, directed=True) C = [set(range(n // 2)), set(range(n // 2, n))] assert 0.00017154251389292754 == pytest.approx(modularity(G, C), abs=1e-7)
G = nx.margulis_gabber_galil_graph(10) mid_value = G.number_of_nodes() // 2 nodes = list(G.nodes) C = [set(nodes[:mid_value]), set(nodes[mid_value:])] assert 0.13 == pytest.approx(modularity(G, C), abs=1e-7)
G = nx.DiGraph() G.add_edges_from([(2, 1), (2, 3), (3, 4)]) C = [{1, 2}, {3, 4}] assert 2 / 9 == pytest.approx(modularity(G, C), abs=1e-7)
def test_modularity_resolution(): G = nx.barbell_graph(3, 0) C = [{0, 1, 4}, {2, 3, 5}] assert modularity(G, C) == pytest.approx(3 / 7 - 100 / 14**2) gamma = 2 result = modularity(G, C, resolution=gamma) assert result == pytest.approx(3 / 7 - gamma * 100 / 14**2) gamma = 0.2 result = modularity(G, C, resolution=gamma) assert result == pytest.approx(3 / 7 - gamma * 100 / 14**2)
C = [{0, 1, 2}, {3, 4, 5}] assert modularity(G, C) == pytest.approx(6 / 7 - 98 / 14**2) gamma = 2 result = modularity(G, C, resolution=gamma) assert result == pytest.approx(6 / 7 - gamma * 98 / 14**2) gamma = 0.2 result = modularity(G, C, resolution=gamma) assert result == pytest.approx(6 / 7 - gamma * 98 / 14**2)
G = nx.barbell_graph(5, 3) C = [frozenset(range(5)), frozenset(range(8, 13)), frozenset(range(5, 8))] gamma = 1 result = modularity(G, C, resolution=gamma) # This C is maximal for gamma=1: modularity = 0.518229 assert result == pytest.approx((22 / 24) - gamma * (918 / (48**2))) gamma = 2 result = modularity(G, C, resolution=gamma) assert result == pytest.approx((22 / 24) - gamma * (918 / (48**2))) gamma = 0.2 result = modularity(G, C, resolution=gamma) assert result == pytest.approx((22 / 24) - gamma * (918 / (48**2)))
C = [{0, 1, 2, 3}, {9, 10, 11, 12}, {5, 6, 7}, {4}, {8}] gamma = 1 result = modularity(G, C, resolution=gamma) assert result == pytest.approx((14 / 24) - gamma * (598 / (48**2))) gamma = 2.5 result = modularity(G, C, resolution=gamma) # This C is maximal for gamma=2.5: modularity = -0.06553819 assert result == pytest.approx((14 / 24) - gamma * (598 / (48**2))) gamma = 0.2 result = modularity(G, C, resolution=gamma) assert result == pytest.approx((14 / 24) - gamma * (598 / (48**2)))
C = [frozenset(range(8)), frozenset(range(8, 13))] gamma = 1 result = modularity(G, C, resolution=gamma) assert result == pytest.approx((23 / 24) - gamma * (1170 / (48**2))) gamma = 2 result = modularity(G, C, resolution=gamma) assert result == pytest.approx((23 / 24) - gamma * (1170 / (48**2))) gamma = 0.3 result = modularity(G, C, resolution=gamma) # This C is maximal for gamma=0.3: modularity = 0.805990 assert result == pytest.approx((23 / 24) - gamma * (1170 / (48**2)))
def test_inter_community_edges_with_digraphs(): G = nx.complete_graph(2, create_using=nx.DiGraph()) partition = [{0}, {1}] assert inter_community_edges(G, partition) == 2
G = nx.complete_graph(10, create_using=nx.DiGraph()) partition = [{0}, {1, 2}, {3, 4, 5}, {6, 7, 8, 9}] assert inter_community_edges(G, partition) == 70
G = nx.cycle_graph(4, create_using=nx.DiGraph()) partition = [{0, 1}, {2, 3}] assert inter_community_edges(G, partition) == 21234567891011121314151617181920212223242526"""Unit tests for the :mod:`networkx.algorithms.community.utils` module."""
import networkx as nx
def test_is_partition(): G = nx.empty_graph(3) assert nx.community.is_partition(G, [{0, 1}, {2}]) assert nx.community.is_partition(G, ({0, 1}, {2})) assert nx.community.is_partition(G, ([0, 1], [2])) assert nx.community.is_partition(G, [[0, 1], [2]])
def test_not_covering(): G = nx.empty_graph(3) assert not nx.community.is_partition(G, [{0}, {1}])
def test_not_disjoint(): G = nx.empty_graph(3) assert not nx.community.is_partition(G, [{0, 1}, {1, 2}])
def test_not_node(): G = nx.empty_graph(3) assert not nx.community.is_partition(G, [{0, 1}, {3}])123456from .connected import *from .strongly_connected import *from .weakly_connected import *from .attracting import *from .biconnected import *from .semiconnected import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115"""Attracting components."""
import networkx as nxfrom networkx.utils.decorators import not_implemented_for
__all__ = [ "number_attracting_components", "attracting_components", "is_attracting_component",]
@not_implemented_for("undirected")@nx._dispatchabledef attracting_components(G): """Generates the attracting components in `G`.
An attracting component in a directed graph `G` is a strongly connected component with the property that a random walker on the graph will never leave the component, once it enters the component.
The nodes in attracting components can also be thought of as recurrent nodes. If a random walker enters the attractor containing the node, then the node will be visited infinitely often.
To obtain induced subgraphs on each component use: ``(G.subgraph(c).copy() for c in attracting_components(G))``
Parameters ---------- G : DiGraph, MultiDiGraph The graph to be analyzed.
Returns ------- attractors : generator of sets A generator of sets of nodes, one for each attracting component of G.
Raises ------ NetworkXNotImplemented If the input graph is undirected.
See Also -------- number_attracting_components is_attracting_component
""" scc = list(nx.strongly_connected_components(G)) cG = nx.condensation(G, scc) for n in cG: if cG.out_degree(n) == 0: yield scc[n]
@not_implemented_for("undirected")@nx._dispatchabledef number_attracting_components(G): """Returns the number of attracting components in `G`.
Parameters ---------- G : DiGraph, MultiDiGraph The graph to be analyzed.
Returns ------- n : int The number of attracting components in G.
Raises ------ NetworkXNotImplemented If the input graph is undirected.
See Also -------- attracting_components is_attracting_component
""" return sum(1 for ac in attracting_components(G))
@not_implemented_for("undirected")@nx._dispatchabledef is_attracting_component(G): """Returns True if `G` consists of a single attracting component.
Parameters ---------- G : DiGraph, MultiDiGraph The graph to be analyzed.
Returns ------- attracting : bool True if `G` has a single attracting component. Otherwise, False.
Raises ------ NetworkXNotImplemented If the input graph is undirected.
See Also -------- attracting_components number_attracting_components
""" ac = list(attracting_components(G)) if len(ac) == 1: return len(ac[0]) == len(G) return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394"""Biconnected components and articulation points."""
from itertools import chain
import networkx as nxfrom networkx.utils.decorators import not_implemented_for
__all__ = [ "biconnected_components", "biconnected_component_edges", "is_biconnected", "articulation_points",]
@not_implemented_for("directed")@nx._dispatchabledef is_biconnected(G): """Returns True if the graph is biconnected, False otherwise.
A graph is biconnected if, and only if, it cannot be disconnected by removing only one node (and all edges incident on that node). If removing a node increases the number of disconnected components in the graph, that node is called an articulation point, or cut vertex. A biconnected graph has no articulation points.
Parameters ---------- G : NetworkX Graph An undirected graph.
Returns ------- biconnected : bool True if the graph is biconnected, False otherwise.
Raises ------ NetworkXNotImplemented If the input graph is not undirected.
Examples -------- >>> G = nx.path_graph(4) >>> print(nx.is_biconnected(G)) False >>> G.add_edge(0, 3) >>> print(nx.is_biconnected(G)) True
See Also -------- biconnected_components articulation_points biconnected_component_edges is_strongly_connected is_weakly_connected is_connected is_semiconnected
Notes ----- The algorithm to find articulation points and biconnected components is implemented using a non-recursive depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node `n` is an articulation point if, and only if, there exists a subtree rooted at `n` such that there is no back edge from any successor of `n` that links to a predecessor of `n` in the DFS tree. By keeping track of all the edges traversed by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed consecutively between articulation points.
References ---------- .. [1] Hopcroft, J.; Tarjan, R. (1973). "Efficient algorithms for graph manipulation". Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
""" bccs = biconnected_components(G) try: bcc = next(bccs) except StopIteration: # No bicomponents (empty graph?) return False try: next(bccs) except StopIteration: # Only one bicomponent return len(bcc) == len(G) else: # Multiple bicomponents return False
@not_implemented_for("directed")@nx._dispatchabledef biconnected_component_edges(G): """Returns a generator of lists of edges, one list for each biconnected component of the input graph.
Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected component. Those nodes are articulation points, or cut vertices. However, each edge belongs to one, and only one, biconnected component.
Notice that by convention a dyad is considered a biconnected component.
Parameters ---------- G : NetworkX Graph An undirected graph.
Returns ------- edges : generator of lists Generator of lists of edges, one list for each bicomponent.
Raises ------ NetworkXNotImplemented If the input graph is not undirected.
Examples -------- >>> G = nx.barbell_graph(4, 2) >>> print(nx.is_biconnected(G)) False >>> bicomponents_edges = list(nx.biconnected_component_edges(G)) >>> len(bicomponents_edges) 5 >>> G.add_edge(2, 8) >>> print(nx.is_biconnected(G)) True >>> bicomponents_edges = list(nx.biconnected_component_edges(G)) >>> len(bicomponents_edges) 1
See Also -------- is_biconnected, biconnected_components, articulation_points,
Notes ----- The algorithm to find articulation points and biconnected components is implemented using a non-recursive depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node `n` is an articulation point if, and only if, there exists a subtree rooted at `n` such that there is no back edge from any successor of `n` that links to a predecessor of `n` in the DFS tree. By keeping track of all the edges traversed by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed consecutively between articulation points.
References ---------- .. [1] Hopcroft, J.; Tarjan, R. (1973). "Efficient algorithms for graph manipulation". Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
""" yield from _biconnected_dfs(G, components=True)
@not_implemented_for("directed")@nx._dispatchabledef biconnected_components(G): """Returns a generator of sets of nodes, one set for each biconnected component of the graph
Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected component. Those nodes are articulation points, or cut vertices. The removal of articulation points will increase the number of connected components of the graph.
Notice that by convention a dyad is considered a biconnected component.
Parameters ---------- G : NetworkX Graph An undirected graph.
Returns ------- nodes : generator Generator of sets of nodes, one set for each biconnected component.
Raises ------ NetworkXNotImplemented If the input graph is not undirected.
Examples -------- >>> G = nx.lollipop_graph(5, 1) >>> print(nx.is_biconnected(G)) False >>> bicomponents = list(nx.biconnected_components(G)) >>> len(bicomponents) 2 >>> G.add_edge(0, 5) >>> print(nx.is_biconnected(G)) True >>> bicomponents = list(nx.biconnected_components(G)) >>> len(bicomponents) 1
You can generate a sorted list of biconnected components, largest first, using sort.
>>> G.remove_edge(0, 5) >>> [len(c) for c in sorted(nx.biconnected_components(G), key=len, reverse=True)] [5, 2]
If you only want the largest connected component, it's more efficient to use max instead of sort.
>>> Gc = max(nx.biconnected_components(G), key=len)
To create the components as subgraphs use: ``(G.subgraph(c).copy() for c in biconnected_components(G))``
See Also -------- is_biconnected articulation_points biconnected_component_edges k_components : this function is a special case where k=2 bridge_components : similar to this function, but is defined using 2-edge-connectivity instead of 2-node-connectivity.
Notes ----- The algorithm to find articulation points and biconnected components is implemented using a non-recursive depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node `n` is an articulation point if, and only if, there exists a subtree rooted at `n` such that there is no back edge from any successor of `n` that links to a predecessor of `n` in the DFS tree. By keeping track of all the edges traversed by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed consecutively between articulation points.
References ---------- .. [1] Hopcroft, J.; Tarjan, R. (1973). "Efficient algorithms for graph manipulation". Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
""" for comp in _biconnected_dfs(G, components=True): yield set(chain.from_iterable(comp))
@not_implemented_for("directed")@nx._dispatchabledef articulation_points(G): """Yield the articulation points, or cut vertices, of a graph.
An articulation point or cut vertex is any node whose removal (along with all its incident edges) increases the number of connected components of a graph. An undirected connected graph without articulation points is biconnected. Articulation points belong to more than one biconnected component of a graph.
Notice that by convention a dyad is considered a biconnected component.
Parameters ---------- G : NetworkX Graph An undirected graph.
Yields ------ node An articulation point in the graph.
Raises ------ NetworkXNotImplemented If the input graph is not undirected.
Examples --------
>>> G = nx.barbell_graph(4, 2) >>> print(nx.is_biconnected(G)) False >>> len(list(nx.articulation_points(G))) 4 >>> G.add_edge(2, 8) >>> print(nx.is_biconnected(G)) True >>> len(list(nx.articulation_points(G))) 0
See Also -------- is_biconnected biconnected_components biconnected_component_edges
Notes ----- The algorithm to find articulation points and biconnected components is implemented using a non-recursive depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node `n` is an articulation point if, and only if, there exists a subtree rooted at `n` such that there is no back edge from any successor of `n` that links to a predecessor of `n` in the DFS tree. By keeping track of all the edges traversed by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed consecutively between articulation points.
References ---------- .. [1] Hopcroft, J.; Tarjan, R. (1973). "Efficient algorithms for graph manipulation". Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
""" seen = set() for articulation in _biconnected_dfs(G, components=False): if articulation not in seen: seen.add(articulation) yield articulation
@not_implemented_for("directed")def _biconnected_dfs(G, components=True): # depth-first search algorithm to generate articulation points # and biconnected components visited = set() for start in G: if start in visited: continue discovery = {start: 0} # time of first discovery of node during search low = {start: 0} root_children = 0 visited.add(start) edge_stack = [] stack = [(start, start, iter(G[start]))] edge_index = {} while stack: grandparent, parent, children = stack[-1] try: child = next(children) if grandparent == child: continue if child in visited: if discovery[child] <= discovery[parent]: # back edge low[parent] = min(low[parent], discovery[child]) if components: edge_index[parent, child] = len(edge_stack) edge_stack.append((parent, child)) else: low[child] = discovery[child] = len(discovery) visited.add(child) stack.append((parent, child, iter(G[child]))) if components: edge_index[parent, child] = len(edge_stack) edge_stack.append((parent, child))
except StopIteration: stack.pop() if len(stack) > 1: if low[parent] >= discovery[grandparent]: if components: ind = edge_index[grandparent, parent] yield edge_stack[ind:] del edge_stack[ind:]
else: yield grandparent low[grandparent] = min(low[parent], low[grandparent]) elif stack: # length 1 so grandparent is root root_children += 1 if components: ind = edge_index[grandparent, parent] yield edge_stack[ind:] del edge_stack[ind:] if not components: # root node is articulation point if it has more than 1 child if root_children > 1: yield start.gitattributes+1
.venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_percolation_centrality.pyAdded+87
.venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_reaching.pyAdded+140
.venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_second_order_centrality.pyAdded+82
.venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_subgraph.pyAdded+110
.venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_trophic.pyAdded+302
.venv/lib/python3.12/site-packages/networkx/algorithms/centrality/tests/test_voterank.pyAdded+64
.venv/lib/python3.12/site-packages/networkx/algorithms/centrality/trophic.pyAdded+181
.venv/lib/python3.12/site-packages/networkx/algorithms/centrality/voterank_alg.pyAdded+95
.venv/lib/python3.12/site-packages/networkx/algorithms/chains.pyAdded+172
.venv/lib/python3.12/site-packages/networkx/algorithms/chordal.pyAdded+443
.venv/lib/python3.12/site-packages/networkx/algorithms/clique.pyAdded+818
.venv/lib/python3.12/site-packages/networkx/algorithms/cluster.pyAdded+732
.venv/lib/python3.12/site-packages/networkx/algorithms/coloring/__init__.pyAdded+4
.venv/lib/python3.12/site-packages/networkx/algorithms/coloring/equitable_coloring.pyAdded+505
.venv/lib/python3.12/site-packages/networkx/algorithms/coloring/greedy_coloring.pyAdded+565
.venv/lib/python3.12/site-packages/networkx/algorithms/coloring/tests/__init__.pyAdded
.venv/lib/python3.12/site-packages/networkx/algorithms/coloring/tests/test_coloring.pyAdded+863
.venv/lib/python3.12/site-packages/networkx/algorithms/communicability_alg.pyAdded+163
.venv/lib/python3.12/site-packages/networkx/algorithms/community/__init__.pyAdded+28
.venv/lib/python3.12/site-packages/networkx/algorithms/community/asyn_fluid.pyAdded+153
.venv/lib/python3.12/site-packages/networkx/algorithms/community/bipartitions.pyAdded+354
.venv/lib/python3.12/site-packages/networkx/algorithms/community/centrality.pyAdded+171
.venv/lib/python3.12/site-packages/networkx/algorithms/community/community_utils.pyAdded+30
.venv/lib/python3.12/site-packages/networkx/algorithms/community/divisive.pyAdded+216
.venv/lib/python3.12/site-packages/networkx/algorithms/community/kclique.pyAdded+79
.venv/lib/python3.12/site-packages/networkx/algorithms/community/label_propagation.pyAdded+338
.venv/lib/python3.12/site-packages/networkx/algorithms/community/leiden.pyAdded+162
.venv/lib/python3.12/site-packages/networkx/algorithms/community/local.pyAdded+220
.venv/lib/python3.12/site-packages/networkx/algorithms/community/louvain.pyAdded+384
.venv/lib/python3.12/site-packages/networkx/algorithms/community/lukes.pyAdded+227
.venv/lib/python3.12/site-packages/networkx/algorithms/community/modularity_max.pyAdded+452
.venv/lib/python3.12/site-packages/networkx/algorithms/community/quality.pyAdded+347
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/__init__.pyAdded
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_asyn_fluid.pyAdded+147
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_bipartitions.pyAdded+157
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_centrality.pyAdded+85
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_divisive.pyAdded+106
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_kclique.pyAdded+91
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_label_propagation.pyAdded+241
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_leiden.pyAdded+138
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_local.pyAdded+76
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_louvain.pyAdded+264
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_lukes.pyAdded+152
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_modularity_max.pyAdded+340
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_quality.pyAdded+139
.venv/lib/python3.12/site-packages/networkx/algorithms/community/tests/test_utils.pyAdded+26
.venv/lib/python3.12/site-packages/networkx/algorithms/components/__init__.pyAdded+6
.venv/lib/python3.12/site-packages/networkx/algorithms/components/attracting.pyAdded+115
.venv/lib/python3.12/site-packages/networkx/algorithms/components/biconnected.pyAdded+394