test_reordering.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import numpy as np
  2. from numpy.testing import assert_equal
  3. from scipy.sparse.csgraph import reverse_cuthill_mckee, structural_rank
  4. from scipy.sparse import csc_matrix, csr_matrix, coo_matrix
  5. def test_graph_reverse_cuthill_mckee():
  6. A = np.array([[1, 0, 0, 0, 1, 0, 0, 0],
  7. [0, 1, 1, 0, 0, 1, 0, 1],
  8. [0, 1, 1, 0, 1, 0, 0, 0],
  9. [0, 0, 0, 1, 0, 0, 1, 0],
  10. [1, 0, 1, 0, 1, 0, 0, 0],
  11. [0, 1, 0, 0, 0, 1, 0, 1],
  12. [0, 0, 0, 1, 0, 0, 1, 0],
  13. [0, 1, 0, 0, 0, 1, 0, 1]], dtype=int)
  14. graph = csr_matrix(A)
  15. perm = reverse_cuthill_mckee(graph)
  16. correct_perm = np.array([6, 3, 7, 5, 1, 2, 4, 0])
  17. assert_equal(perm, correct_perm)
  18. # Test int64 indices input
  19. graph.indices = graph.indices.astype('int64')
  20. graph.indptr = graph.indptr.astype('int64')
  21. perm = reverse_cuthill_mckee(graph, True)
  22. assert_equal(perm, correct_perm)
  23. def test_graph_reverse_cuthill_mckee_ordering():
  24. data = np.ones(63,dtype=int)
  25. rows = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2,
  26. 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5,
  27. 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  28. 9, 10, 10, 10, 10, 10, 11, 11, 11, 11,
  29. 12, 12, 12, 13, 13, 13, 13, 14, 14, 14,
  30. 14, 15, 15, 15, 15, 15])
  31. cols = np.array([0, 2, 5, 8, 10, 1, 3, 9, 11, 0, 2,
  32. 7, 10, 1, 3, 11, 4, 6, 12, 14, 0, 7, 13,
  33. 15, 4, 6, 14, 2, 5, 7, 15, 0, 8, 10, 13,
  34. 1, 9, 11, 0, 2, 8, 10, 15, 1, 3, 9, 11,
  35. 4, 12, 14, 5, 8, 13, 15, 4, 6, 12, 14,
  36. 5, 7, 10, 13, 15])
  37. graph = coo_matrix((data, (rows,cols))).tocsr()
  38. perm = reverse_cuthill_mckee(graph)
  39. correct_perm = np.array([12, 14, 4, 6, 10, 8, 2, 15,
  40. 0, 13, 7, 5, 9, 11, 1, 3])
  41. assert_equal(perm, correct_perm)
  42. def test_graph_structural_rank():
  43. # Test square matrix #1
  44. A = csc_matrix([[1, 1, 0],
  45. [1, 0, 1],
  46. [0, 1, 0]])
  47. assert_equal(structural_rank(A), 3)
  48. # Test square matrix #2
  49. rows = np.array([0,0,0,0,0,1,1,2,2,3,3,3,3,3,3,4,4,5,5,6,6,7,7])
  50. cols = np.array([0,1,2,3,4,2,5,2,6,0,1,3,5,6,7,4,5,5,6,2,6,2,4])
  51. data = np.ones_like(rows)
  52. B = coo_matrix((data,(rows,cols)), shape=(8,8))
  53. assert_equal(structural_rank(B), 6)
  54. #Test non-square matrix
  55. C = csc_matrix([[1, 0, 2, 0],
  56. [2, 0, 4, 0]])
  57. assert_equal(structural_rank(C), 2)
  58. #Test tall matrix
  59. assert_equal(structural_rank(C.T), 2)