test_matrix.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import pytest
  2. np = pytest.importorskip("numpy")
  3. sp = pytest.importorskip("scipy")
  4. sparse = pytest.importorskip("scipy.sparse")
  5. import networkx as nx
  6. from networkx.algorithms import bipartite
  7. from networkx.utils import edges_equal
  8. class TestBiadjacencyMatrix:
  9. def test_biadjacency_matrix_weight(self):
  10. G = nx.path_graph(5)
  11. G.add_edge(0, 1, weight=2, other=4)
  12. X = [1, 3]
  13. Y = [0, 2, 4]
  14. M = bipartite.biadjacency_matrix(G, X, weight="weight")
  15. assert M[0, 0] == 2
  16. M = bipartite.biadjacency_matrix(G, X, weight="other")
  17. assert M[0, 0] == 4
  18. def test_biadjacency_matrix(self):
  19. tops = [2, 5, 10]
  20. bots = [5, 10, 15]
  21. for i in range(len(tops)):
  22. G = bipartite.random_graph(tops[i], bots[i], 0.2)
  23. top = [n for n, d in G.nodes(data=True) if d["bipartite"] == 0]
  24. M = bipartite.biadjacency_matrix(G, top)
  25. assert M.shape[0] == tops[i]
  26. assert M.shape[1] == bots[i]
  27. def test_biadjacency_matrix_order(self):
  28. G = nx.path_graph(5)
  29. G.add_edge(0, 1, weight=2)
  30. X = [3, 1]
  31. Y = [4, 2, 0]
  32. M = bipartite.biadjacency_matrix(G, X, Y, weight="weight")
  33. assert M[1, 2] == 2
  34. def test_null_graph(self):
  35. with pytest.raises(nx.NetworkXError):
  36. bipartite.biadjacency_matrix(nx.Graph(), [])
  37. def test_empty_graph(self):
  38. with pytest.raises(nx.NetworkXError):
  39. bipartite.biadjacency_matrix(nx.Graph([(1, 0)]), [])
  40. def test_duplicate_row(self):
  41. with pytest.raises(nx.NetworkXError):
  42. bipartite.biadjacency_matrix(nx.Graph([(1, 0)]), [1, 1])
  43. def test_duplicate_col(self):
  44. with pytest.raises(nx.NetworkXError):
  45. bipartite.biadjacency_matrix(nx.Graph([(1, 0)]), [0], [1, 1])
  46. def test_format_keyword(self):
  47. with pytest.raises(nx.NetworkXError):
  48. bipartite.biadjacency_matrix(nx.Graph([(1, 0)]), [0], format="foo")
  49. def test_from_biadjacency_roundtrip(self):
  50. B1 = nx.path_graph(5)
  51. M = bipartite.biadjacency_matrix(B1, [0, 2, 4])
  52. B2 = bipartite.from_biadjacency_matrix(M)
  53. assert nx.is_isomorphic(B1, B2)
  54. def test_from_biadjacency_weight(self):
  55. M = sparse.csc_matrix([[1, 2], [0, 3]])
  56. B = bipartite.from_biadjacency_matrix(M)
  57. assert edges_equal(B.edges(), [(0, 2), (0, 3), (1, 3)])
  58. B = bipartite.from_biadjacency_matrix(M, edge_attribute="weight")
  59. e = [(0, 2, {"weight": 1}), (0, 3, {"weight": 2}), (1, 3, {"weight": 3})]
  60. assert edges_equal(B.edges(data=True), e)
  61. def test_from_biadjacency_multigraph(self):
  62. M = sparse.csc_matrix([[1, 2], [0, 3]])
  63. B = bipartite.from_biadjacency_matrix(M, create_using=nx.MultiGraph())
  64. assert edges_equal(B.edges(), [(0, 2), (0, 3), (0, 3), (1, 3), (1, 3), (1, 3)])