test_spectrum.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import pytest
  2. import networkx as nx
  3. np = pytest.importorskip("numpy")
  4. pytest.importorskip("scipy")
  5. class TestSpectrum:
  6. @classmethod
  7. def setup_class(cls):
  8. deg = [3, 2, 2, 1, 0]
  9. cls.G = nx.havel_hakimi_graph(deg)
  10. cls.P = nx.path_graph(3)
  11. cls.WG = nx.Graph(
  12. (u, v, {"weight": 0.5, "other": 0.3}) for (u, v) in cls.G.edges()
  13. )
  14. cls.WG.add_node(4)
  15. cls.DG = nx.DiGraph()
  16. nx.add_path(cls.DG, [0, 1, 2])
  17. def test_laplacian_spectrum(self):
  18. "Laplacian eigenvalues"
  19. evals = np.array([0, 0, 1, 3, 4])
  20. e = sorted(nx.laplacian_spectrum(self.G))
  21. np.testing.assert_almost_equal(e, evals)
  22. e = sorted(nx.laplacian_spectrum(self.WG, weight=None))
  23. np.testing.assert_almost_equal(e, evals)
  24. e = sorted(nx.laplacian_spectrum(self.WG))
  25. np.testing.assert_almost_equal(e, 0.5 * evals)
  26. e = sorted(nx.laplacian_spectrum(self.WG, weight="other"))
  27. np.testing.assert_almost_equal(e, 0.3 * evals)
  28. def test_normalized_laplacian_spectrum(self):
  29. "Normalized Laplacian eigenvalues"
  30. evals = np.array([0, 0, 0.7712864461218, 1.5, 1.7287135538781])
  31. e = sorted(nx.normalized_laplacian_spectrum(self.G))
  32. np.testing.assert_almost_equal(e, evals)
  33. e = sorted(nx.normalized_laplacian_spectrum(self.WG, weight=None))
  34. np.testing.assert_almost_equal(e, evals)
  35. e = sorted(nx.normalized_laplacian_spectrum(self.WG))
  36. np.testing.assert_almost_equal(e, evals)
  37. e = sorted(nx.normalized_laplacian_spectrum(self.WG, weight="other"))
  38. np.testing.assert_almost_equal(e, evals)
  39. def test_adjacency_spectrum(self):
  40. "Adjacency eigenvalues"
  41. evals = np.array([-np.sqrt(2), 0, np.sqrt(2)])
  42. e = sorted(nx.adjacency_spectrum(self.P))
  43. np.testing.assert_almost_equal(e, evals)
  44. def test_modularity_spectrum(self):
  45. "Modularity eigenvalues"
  46. evals = np.array([-1.5, 0.0, 0.0])
  47. e = sorted(nx.modularity_spectrum(self.P))
  48. np.testing.assert_almost_equal(e, evals)
  49. # Directed modularity eigenvalues
  50. evals = np.array([-0.5, 0.0, 0.0])
  51. e = sorted(nx.modularity_spectrum(self.DG))
  52. np.testing.assert_almost_equal(e, evals)
  53. def test_bethe_hessian_spectrum(self):
  54. "Bethe Hessian eigenvalues"
  55. evals = np.array([0.5 * (9 - np.sqrt(33)), 4, 0.5 * (9 + np.sqrt(33))])
  56. e = sorted(nx.bethe_hessian_spectrum(self.P, r=2))
  57. np.testing.assert_almost_equal(e, evals)
  58. # Collapses back to Laplacian:
  59. e1 = sorted(nx.bethe_hessian_spectrum(self.P, r=1))
  60. e2 = sorted(nx.laplacian_spectrum(self.P))
  61. np.testing.assert_almost_equal(e1, e2)