test_modularity.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import pytest
  2. np = pytest.importorskip("numpy")
  3. pytest.importorskip("scipy")
  4. import networkx as nx
  5. from networkx.generators.degree_seq import havel_hakimi_graph
  6. class TestModularity:
  7. @classmethod
  8. def setup_class(cls):
  9. deg = [3, 2, 2, 1, 0]
  10. cls.G = havel_hakimi_graph(deg)
  11. # Graph used as an example in Sec. 4.1 of Langville and Meyer,
  12. # "Google's PageRank and Beyond". (Used for test_directed_laplacian)
  13. cls.DG = nx.DiGraph()
  14. cls.DG.add_edges_from(
  15. (
  16. (1, 2),
  17. (1, 3),
  18. (3, 1),
  19. (3, 2),
  20. (3, 5),
  21. (4, 5),
  22. (4, 6),
  23. (5, 4),
  24. (5, 6),
  25. (6, 4),
  26. )
  27. )
  28. def test_modularity(self):
  29. "Modularity matrix"
  30. # fmt: off
  31. B = np.array([[-1.125, 0.25, 0.25, 0.625, 0.],
  32. [0.25, -0.5, 0.5, -0.25, 0.],
  33. [0.25, 0.5, -0.5, -0.25, 0.],
  34. [0.625, -0.25, -0.25, -0.125, 0.],
  35. [0., 0., 0., 0., 0.]])
  36. # fmt: on
  37. permutation = [4, 0, 1, 2, 3]
  38. np.testing.assert_equal(nx.modularity_matrix(self.G), B)
  39. np.testing.assert_equal(
  40. nx.modularity_matrix(self.G, nodelist=permutation),
  41. B[np.ix_(permutation, permutation)],
  42. )
  43. def test_modularity_weight(self):
  44. "Modularity matrix with weights"
  45. # fmt: off
  46. B = np.array([[-1.125, 0.25, 0.25, 0.625, 0.],
  47. [0.25, -0.5, 0.5, -0.25, 0.],
  48. [0.25, 0.5, -0.5, -0.25, 0.],
  49. [0.625, -0.25, -0.25, -0.125, 0.],
  50. [0., 0., 0., 0., 0.]])
  51. # fmt: on
  52. G_weighted = self.G.copy()
  53. for n1, n2 in G_weighted.edges():
  54. G_weighted.edges[n1, n2]["weight"] = 0.5
  55. # The following test would fail in networkx 1.1
  56. np.testing.assert_equal(nx.modularity_matrix(G_weighted), B)
  57. # The following test that the modularity matrix get rescaled accordingly
  58. np.testing.assert_equal(
  59. nx.modularity_matrix(G_weighted, weight="weight"), 0.5 * B
  60. )
  61. def test_directed_modularity(self):
  62. "Directed Modularity matrix"
  63. # fmt: off
  64. B = np.array([[-0.2, 0.6, 0.8, -0.4, -0.4, -0.4],
  65. [0., 0., 0., 0., 0., 0.],
  66. [0.7, 0.4, -0.3, -0.6, 0.4, -0.6],
  67. [-0.2, -0.4, -0.2, -0.4, 0.6, 0.6],
  68. [-0.2, -0.4, -0.2, 0.6, -0.4, 0.6],
  69. [-0.1, -0.2, -0.1, 0.8, -0.2, -0.2]])
  70. # fmt: on
  71. node_permutation = [5, 1, 2, 3, 4, 6]
  72. idx_permutation = [4, 0, 1, 2, 3, 5]
  73. mm = nx.directed_modularity_matrix(self.DG, nodelist=sorted(self.DG))
  74. np.testing.assert_equal(mm, B)
  75. np.testing.assert_equal(
  76. nx.directed_modularity_matrix(self.DG, nodelist=node_permutation),
  77. B[np.ix_(idx_permutation, idx_permutation)],
  78. )