test_conversions.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import numpy as np
  2. from numpy.testing import assert_array_almost_equal
  3. from scipy.sparse import csr_matrix
  4. from scipy.sparse.csgraph import csgraph_from_dense, csgraph_to_dense
  5. def test_csgraph_from_dense():
  6. np.random.seed(1234)
  7. G = np.random.random((10, 10))
  8. some_nulls = (G < 0.4)
  9. all_nulls = (G < 0.8)
  10. for null_value in [0, np.nan, np.inf]:
  11. G[all_nulls] = null_value
  12. with np.errstate(invalid="ignore"):
  13. G_csr = csgraph_from_dense(G, null_value=0)
  14. G[all_nulls] = 0
  15. assert_array_almost_equal(G, G_csr.toarray())
  16. for null_value in [np.nan, np.inf]:
  17. G[all_nulls] = 0
  18. G[some_nulls] = null_value
  19. with np.errstate(invalid="ignore"):
  20. G_csr = csgraph_from_dense(G, null_value=0)
  21. G[all_nulls] = 0
  22. assert_array_almost_equal(G, G_csr.toarray())
  23. def test_csgraph_to_dense():
  24. np.random.seed(1234)
  25. G = np.random.random((10, 10))
  26. nulls = (G < 0.8)
  27. G[nulls] = np.inf
  28. G_csr = csgraph_from_dense(G)
  29. for null_value in [0, 10, -np.inf, np.inf]:
  30. G[nulls] = null_value
  31. assert_array_almost_equal(G, csgraph_to_dense(G_csr, null_value))
  32. def test_multiple_edges():
  33. # create a random sqare matrix with an even number of elements
  34. np.random.seed(1234)
  35. X = np.random.random((10, 10))
  36. Xcsr = csr_matrix(X)
  37. # now double-up every other column
  38. Xcsr.indices[::2] = Xcsr.indices[1::2]
  39. # normal sparse toarray() will sum the duplicated edges
  40. Xdense = Xcsr.toarray()
  41. assert_array_almost_equal(Xdense[:, 1::2],
  42. X[:, ::2] + X[:, 1::2])
  43. # csgraph_to_dense chooses the minimum of each duplicated edge
  44. Xdense = csgraph_to_dense(Xcsr)
  45. assert_array_almost_equal(Xdense[:, 1::2],
  46. np.minimum(X[:, ::2], X[:, 1::2]))