test_modularity.py 3.0 KB

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