test_efficiency.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """Unit tests for the :mod:`networkx.algorithms.efficiency` module."""
  2. import networkx as nx
  3. class TestEfficiency:
  4. def setup_method(self):
  5. # G1 is a disconnected graph
  6. self.G1 = nx.Graph()
  7. self.G1.add_nodes_from([1, 2, 3])
  8. # G2 is a cycle graph
  9. self.G2 = nx.cycle_graph(4)
  10. # G3 is the triangle graph with one additional edge
  11. self.G3 = nx.lollipop_graph(3, 1)
  12. def test_efficiency_disconnected_nodes(self):
  13. """
  14. When nodes are disconnected, efficiency is 0
  15. """
  16. assert nx.efficiency(self.G1, 1, 2) == 0
  17. def test_local_efficiency_disconnected_graph(self):
  18. """
  19. In a disconnected graph the efficiency is 0
  20. """
  21. assert nx.local_efficiency(self.G1) == 0
  22. def test_efficiency(self):
  23. assert nx.efficiency(self.G2, 0, 1) == 1
  24. assert nx.efficiency(self.G2, 0, 2) == 1 / 2
  25. def test_global_efficiency(self):
  26. assert nx.global_efficiency(self.G2) == 5 / 6
  27. def test_global_efficiency_complete_graph(self):
  28. """
  29. Tests that the average global efficiency of the complete graph is one.
  30. """
  31. for n in range(2, 10):
  32. G = nx.complete_graph(n)
  33. assert nx.global_efficiency(G) == 1
  34. def test_local_efficiency_complete_graph(self):
  35. """
  36. Test that the local efficiency for a complete graph with at least 3
  37. nodes should be one. For a graph with only 2 nodes, the induced
  38. subgraph has no edges.
  39. """
  40. for n in range(3, 10):
  41. G = nx.complete_graph(n)
  42. assert nx.local_efficiency(G) == 1
  43. def test_using_ego_graph(self):
  44. """
  45. Test that the ego graph is used when computing local efficiency.
  46. For more information, see GitHub issue #2710.
  47. """
  48. assert nx.local_efficiency(self.G3) == 7 / 12