test_kclique.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from itertools import combinations
  2. import pytest
  3. import networkx as nx
  4. def test_overlapping_K5():
  5. G = nx.Graph()
  6. G.add_edges_from(combinations(range(5), 2)) # Add a five clique
  7. G.add_edges_from(combinations(range(2, 7), 2)) # Add another five clique
  8. c = list(nx.community.k_clique_communities(G, 4))
  9. assert c == [frozenset(range(7))]
  10. c = set(nx.community.k_clique_communities(G, 5))
  11. assert c == {frozenset(range(5)), frozenset(range(2, 7))}
  12. def test_isolated_K5():
  13. G = nx.Graph()
  14. G.add_edges_from(combinations(range(0, 5), 2)) # Add a five clique
  15. G.add_edges_from(combinations(range(5, 10), 2)) # Add another five clique
  16. c = set(nx.community.k_clique_communities(G, 5))
  17. assert c == {frozenset(range(5)), frozenset(range(5, 10))}
  18. class TestZacharyKarateClub:
  19. def setup_method(self):
  20. self.G = nx.karate_club_graph()
  21. def _check_communities(self, k, expected):
  22. communities = set(nx.community.k_clique_communities(self.G, k))
  23. assert communities == expected
  24. def test_k2(self):
  25. # clique percolation with k=2 is just connected components
  26. expected = {frozenset(self.G)}
  27. self._check_communities(2, expected)
  28. def test_k3(self):
  29. comm1 = [
  30. 0,
  31. 1,
  32. 2,
  33. 3,
  34. 7,
  35. 8,
  36. 12,
  37. 13,
  38. 14,
  39. 15,
  40. 17,
  41. 18,
  42. 19,
  43. 20,
  44. 21,
  45. 22,
  46. 23,
  47. 26,
  48. 27,
  49. 28,
  50. 29,
  51. 30,
  52. 31,
  53. 32,
  54. 33,
  55. ]
  56. comm2 = [0, 4, 5, 6, 10, 16]
  57. comm3 = [24, 25, 31]
  58. expected = {frozenset(comm1), frozenset(comm2), frozenset(comm3)}
  59. self._check_communities(3, expected)
  60. def test_k4(self):
  61. expected = {
  62. frozenset([0, 1, 2, 3, 7, 13]),
  63. frozenset([8, 32, 30, 33]),
  64. frozenset([32, 33, 29, 23]),
  65. }
  66. self._check_communities(4, expected)
  67. def test_k5(self):
  68. expected = {frozenset([0, 1, 2, 3, 7, 13])}
  69. self._check_communities(5, expected)
  70. def test_k6(self):
  71. expected = set()
  72. self._check_communities(6, expected)
  73. def test_bad_k():
  74. with pytest.raises(nx.NetworkXError):
  75. list(nx.community.k_clique_communities(nx.Graph(), 1))