test_richclub.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import pytest
  2. import networkx as nx
  3. def test_richclub():
  4. G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
  5. rc = nx.richclub.rich_club_coefficient(G, normalized=False)
  6. assert rc == {0: 12.0 / 30, 1: 8.0 / 12}
  7. # test single value
  8. rc0 = nx.richclub.rich_club_coefficient(G, normalized=False)[0]
  9. assert rc0 == 12.0 / 30.0
  10. def test_richclub_seed():
  11. G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
  12. rcNorm = nx.richclub.rich_club_coefficient(G, Q=2, seed=1)
  13. assert rcNorm == {0: 1.0, 1: 1.0}
  14. def test_richclub_normalized():
  15. G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
  16. rcNorm = nx.richclub.rich_club_coefficient(G, Q=2)
  17. assert rcNorm == {0: 1.0, 1: 1.0}
  18. def test_richclub2():
  19. T = nx.balanced_tree(2, 10)
  20. rc = nx.richclub.rich_club_coefficient(T, normalized=False)
  21. assert rc == {
  22. 0: 4092 / (2047 * 2046.0),
  23. 1: (2044.0 / (1023 * 1022)),
  24. 2: (2040.0 / (1022 * 1021)),
  25. }
  26. def test_richclub3():
  27. # tests edgecase
  28. G = nx.karate_club_graph()
  29. rc = nx.rich_club_coefficient(G, normalized=False)
  30. assert rc == {
  31. 0: 156.0 / 1122,
  32. 1: 154.0 / 1056,
  33. 2: 110.0 / 462,
  34. 3: 78.0 / 240,
  35. 4: 44.0 / 90,
  36. 5: 22.0 / 42,
  37. 6: 10.0 / 20,
  38. 7: 10.0 / 20,
  39. 8: 10.0 / 20,
  40. 9: 6.0 / 12,
  41. 10: 2.0 / 6,
  42. 11: 2.0 / 6,
  43. 12: 0.0,
  44. 13: 0.0,
  45. 14: 0.0,
  46. 15: 0.0,
  47. }
  48. def test_richclub4():
  49. G = nx.Graph()
  50. G.add_edges_from(
  51. [(0, 1), (0, 2), (0, 3), (0, 4), (4, 5), (5, 9), (6, 9), (7, 9), (8, 9)]
  52. )
  53. rc = nx.rich_club_coefficient(G, normalized=False)
  54. assert rc == {0: 18 / 90.0, 1: 6 / 12.0, 2: 0.0, 3: 0.0}
  55. def test_richclub_exception():
  56. with pytest.raises(nx.NetworkXNotImplemented):
  57. G = nx.DiGraph()
  58. nx.rich_club_coefficient(G)
  59. def test_rich_club_exception2():
  60. with pytest.raises(nx.NetworkXNotImplemented):
  61. G = nx.MultiGraph()
  62. nx.rich_club_coefficient(G)
  63. def test_rich_club_selfloop():
  64. G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  65. G.add_edge(1, 1) # self loop
  66. G.add_edge(1, 2)
  67. with pytest.raises(
  68. Exception,
  69. match="rich_club_coefficient is not implemented for " "graphs with self loops.",
  70. ):
  71. nx.rich_club_coefficient(G)
  72. # def test_richclub2_normalized():
  73. # T = nx.balanced_tree(2,10)
  74. # rcNorm = nx.richclub.rich_club_coefficient(T,Q=2)
  75. # assert_true(rcNorm[0] ==1.0 and rcNorm[1] < 0.9 and rcNorm[2] < 0.9)