test_bethehessian.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import pytest
  2. import networkx as nx
  3. np = pytest.importorskip("numpy")
  4. pytest.importorskip("scipy")
  5. class TestBetheHessian:
  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. def test_bethe_hessian(self):
  12. "Bethe Hessian matrix"
  13. # fmt: off
  14. H = np.array([[4, -2, 0],
  15. [-2, 5, -2],
  16. [0, -2, 4]])
  17. # fmt: on
  18. permutation = [2, 0, 1]
  19. # Bethe Hessian gives expected form
  20. np.testing.assert_equal(nx.bethe_hessian_matrix(self.P, r=2).todense(), H)
  21. # nodelist is correctly implemented
  22. np.testing.assert_equal(
  23. nx.bethe_hessian_matrix(self.P, r=2, nodelist=permutation).todense(),
  24. H[np.ix_(permutation, permutation)],
  25. )
  26. # Equal to Laplacian matrix when r=1
  27. np.testing.assert_equal(
  28. nx.bethe_hessian_matrix(self.G, r=1).todense(),
  29. nx.laplacian_matrix(self.G).todense(),
  30. )
  31. # Correct default for the regularizer r
  32. np.testing.assert_equal(
  33. nx.bethe_hessian_matrix(self.G).todense(),
  34. nx.bethe_hessian_matrix(self.G, r=1.25).todense(),
  35. )