test_wiener.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Unit tests for the :mod:`networkx.algorithms.wiener` module."""
  2. from networkx import DiGraph, complete_graph, empty_graph, path_graph, wiener_index
  3. class TestWienerIndex:
  4. """Unit tests for computing the Wiener index of a graph."""
  5. def test_disconnected_graph(self):
  6. """Tests that the Wiener index of a disconnected graph is
  7. positive infinity.
  8. """
  9. assert wiener_index(empty_graph(2)) == float("inf")
  10. def test_directed(self):
  11. """Tests that each pair of nodes in the directed graph is
  12. counted once when computing the Wiener index.
  13. """
  14. G = complete_graph(3)
  15. H = DiGraph(G)
  16. assert (2 * wiener_index(G)) == wiener_index(H)
  17. def test_complete_graph(self):
  18. """Tests that the Wiener index of the complete graph is simply
  19. the number of edges.
  20. """
  21. n = 10
  22. G = complete_graph(n)
  23. assert wiener_index(G) == (n * (n - 1) / 2)
  24. def test_path_graph(self):
  25. """Tests that the Wiener index of the path graph is correctly
  26. computed.
  27. """
  28. # In P_n, there are n - 1 pairs of vertices at distance one, n -
  29. # 2 pairs at distance two, n - 3 at distance three, ..., 1 at
  30. # distance n - 1, so the Wiener index should be
  31. #
  32. # 1 * (n - 1) + 2 * (n - 2) + ... + (n - 2) * 2 + (n - 1) * 1
  33. #
  34. # For example, in P_5,
  35. #
  36. # 1 * 4 + 2 * 3 + 3 * 2 + 4 * 1 = 2 (1 * 4 + 2 * 3)
  37. #
  38. # and in P_6,
  39. #
  40. # 1 * 5 + 2 * 4 + 3 * 3 + 4 * 2 + 5 * 1 = 2 (1 * 5 + 2 * 4) + 3 * 3
  41. #
  42. # assuming n is *odd*, this gives the formula
  43. #
  44. # 2 \sum_{i = 1}^{(n - 1) / 2} [i * (n - i)]
  45. #
  46. # assuming n is *even*, this gives the formula
  47. #
  48. # 2 \sum_{i = 1}^{n / 2} [i * (n - i)] - (n / 2) ** 2
  49. #
  50. n = 9
  51. G = path_graph(n)
  52. expected = 2 * sum(i * (n - i) for i in range(1, (n // 2) + 1))
  53. actual = wiener_index(G)
  54. assert expected == actual