test_bethehessian.py 1.3 KB

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