test_conversions.py 2.0 KB

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