test_construct.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. """test sparse matrix construction functions"""
  2. import numpy as np
  3. from numpy import array
  4. from numpy.testing import (assert_equal, assert_,
  5. assert_array_equal, assert_array_almost_equal_nulp)
  6. import pytest
  7. from pytest import raises as assert_raises
  8. from scipy._lib._testutils import check_free_memory
  9. from scipy._lib._util import check_random_state
  10. from scipy.sparse import (csr_matrix, coo_matrix,
  11. _construct as construct)
  12. from scipy.sparse._construct import rand as sprand
  13. from scipy.sparse._sputils import matrix
  14. sparse_formats = ['csr','csc','coo','bsr','dia','lil','dok']
  15. #TODO check whether format=XXX is respected
  16. def _sprandn(m, n, density=0.01, format="coo", dtype=None, random_state=None):
  17. # Helper function for testing.
  18. random_state = check_random_state(random_state)
  19. data_rvs = random_state.standard_normal
  20. return construct.random(m, n, density, format, dtype,
  21. random_state, data_rvs)
  22. class TestConstructUtils:
  23. def test_spdiags(self):
  24. diags1 = array([[1, 2, 3, 4, 5]])
  25. diags2 = array([[1, 2, 3, 4, 5],
  26. [6, 7, 8, 9,10]])
  27. diags3 = array([[1, 2, 3, 4, 5],
  28. [6, 7, 8, 9,10],
  29. [11,12,13,14,15]])
  30. cases = []
  31. cases.append((diags1, 0, 1, 1, [[1]]))
  32. cases.append((diags1, [0], 1, 1, [[1]]))
  33. cases.append((diags1, [0], 2, 1, [[1],[0]]))
  34. cases.append((diags1, [0], 1, 2, [[1,0]]))
  35. cases.append((diags1, [1], 1, 2, [[0,2]]))
  36. cases.append((diags1,[-1], 1, 2, [[0,0]]))
  37. cases.append((diags1, [0], 2, 2, [[1,0],[0,2]]))
  38. cases.append((diags1,[-1], 2, 2, [[0,0],[1,0]]))
  39. cases.append((diags1, [3], 2, 2, [[0,0],[0,0]]))
  40. cases.append((diags1, [0], 3, 4, [[1,0,0,0],[0,2,0,0],[0,0,3,0]]))
  41. cases.append((diags1, [1], 3, 4, [[0,2,0,0],[0,0,3,0],[0,0,0,4]]))
  42. cases.append((diags1, [2], 3, 5, [[0,0,3,0,0],[0,0,0,4,0],[0,0,0,0,5]]))
  43. cases.append((diags2, [0,2], 3, 3, [[1,0,8],[0,2,0],[0,0,3]]))
  44. cases.append((diags2, [-1,0], 3, 4, [[6,0,0,0],[1,7,0,0],[0,2,8,0]]))
  45. cases.append((diags2, [2,-3], 6, 6, [[0,0,3,0,0,0],
  46. [0,0,0,4,0,0],
  47. [0,0,0,0,5,0],
  48. [6,0,0,0,0,0],
  49. [0,7,0,0,0,0],
  50. [0,0,8,0,0,0]]))
  51. cases.append((diags3, [-1,0,1], 6, 6, [[6,12, 0, 0, 0, 0],
  52. [1, 7,13, 0, 0, 0],
  53. [0, 2, 8,14, 0, 0],
  54. [0, 0, 3, 9,15, 0],
  55. [0, 0, 0, 4,10, 0],
  56. [0, 0, 0, 0, 5, 0]]))
  57. cases.append((diags3, [-4,2,-1], 6, 5, [[0, 0, 8, 0, 0],
  58. [11, 0, 0, 9, 0],
  59. [0,12, 0, 0,10],
  60. [0, 0,13, 0, 0],
  61. [1, 0, 0,14, 0],
  62. [0, 2, 0, 0,15]]))
  63. cases.append((diags3, [-1, 1, 2], len(diags3[0]), len(diags3[0]),
  64. [[0, 7, 13, 0, 0],
  65. [1, 0, 8, 14, 0],
  66. [0, 2, 0, 9, 15],
  67. [0, 0, 3, 0, 10],
  68. [0, 0, 0, 4, 0]]))
  69. for d, o, m, n, result in cases:
  70. if len(d[0]) == m and m == n:
  71. assert_equal(construct.spdiags(d, o).toarray(), result)
  72. assert_equal(construct.spdiags(d, o, m, n).toarray(), result)
  73. assert_equal(construct.spdiags(d, o, (m, n)).toarray(), result)
  74. def test_diags(self):
  75. a = array([1, 2, 3, 4, 5])
  76. b = array([6, 7, 8, 9, 10])
  77. c = array([11, 12, 13, 14, 15])
  78. cases = []
  79. cases.append((a[:1], 0, (1, 1), [[1]]))
  80. cases.append(([a[:1]], [0], (1, 1), [[1]]))
  81. cases.append(([a[:1]], [0], (2, 1), [[1],[0]]))
  82. cases.append(([a[:1]], [0], (1, 2), [[1,0]]))
  83. cases.append(([a[:1]], [1], (1, 2), [[0,1]]))
  84. cases.append(([a[:2]], [0], (2, 2), [[1,0],[0,2]]))
  85. cases.append(([a[:1]],[-1], (2, 2), [[0,0],[1,0]]))
  86. cases.append(([a[:3]], [0], (3, 4), [[1,0,0,0],[0,2,0,0],[0,0,3,0]]))
  87. cases.append(([a[:3]], [1], (3, 4), [[0,1,0,0],[0,0,2,0],[0,0,0,3]]))
  88. cases.append(([a[:1]], [-2], (3, 5), [[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,0]]))
  89. cases.append(([a[:2]], [-1], (3, 5), [[0,0,0,0,0],[1,0,0,0,0],[0,2,0,0,0]]))
  90. cases.append(([a[:3]], [0], (3, 5), [[1,0,0,0,0],[0,2,0,0,0],[0,0,3,0,0]]))
  91. cases.append(([a[:3]], [1], (3, 5), [[0,1,0,0,0],[0,0,2,0,0],[0,0,0,3,0]]))
  92. cases.append(([a[:3]], [2], (3, 5), [[0,0,1,0,0],[0,0,0,2,0],[0,0,0,0,3]]))
  93. cases.append(([a[:2]], [3], (3, 5), [[0,0,0,1,0],[0,0,0,0,2],[0,0,0,0,0]]))
  94. cases.append(([a[:1]], [4], (3, 5), [[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0]]))
  95. cases.append(([a[:1]], [-4], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[1,0,0]]))
  96. cases.append(([a[:2]], [-3], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[1,0,0],[0,2,0]]))
  97. cases.append(([a[:3]], [-2], (5, 3), [[0,0,0],[0,0,0],[1,0,0],[0,2,0],[0,0,3]]))
  98. cases.append(([a[:3]], [-1], (5, 3), [[0,0,0],[1,0,0],[0,2,0],[0,0,3],[0,0,0]]))
  99. cases.append(([a[:3]], [0], (5, 3), [[1,0,0],[0,2,0],[0,0,3],[0,0,0],[0,0,0]]))
  100. cases.append(([a[:2]], [1], (5, 3), [[0,1,0],[0,0,2],[0,0,0],[0,0,0],[0,0,0]]))
  101. cases.append(([a[:1]], [2], (5, 3), [[0,0,1],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]))
  102. cases.append(([a[:3],b[:1]], [0,2], (3, 3), [[1,0,6],[0,2,0],[0,0,3]]))
  103. cases.append(([a[:2],b[:3]], [-1,0], (3, 4), [[6,0,0,0],[1,7,0,0],[0,2,8,0]]))
  104. cases.append(([a[:4],b[:3]], [2,-3], (6, 6), [[0,0,1,0,0,0],
  105. [0,0,0,2,0,0],
  106. [0,0,0,0,3,0],
  107. [6,0,0,0,0,4],
  108. [0,7,0,0,0,0],
  109. [0,0,8,0,0,0]]))
  110. cases.append(([a[:4],b,c[:4]], [-1,0,1], (5, 5), [[6,11, 0, 0, 0],
  111. [1, 7,12, 0, 0],
  112. [0, 2, 8,13, 0],
  113. [0, 0, 3, 9,14],
  114. [0, 0, 0, 4,10]]))
  115. cases.append(([a[:2],b[:3],c], [-4,2,-1], (6, 5), [[0, 0, 6, 0, 0],
  116. [11, 0, 0, 7, 0],
  117. [0,12, 0, 0, 8],
  118. [0, 0,13, 0, 0],
  119. [1, 0, 0,14, 0],
  120. [0, 2, 0, 0,15]]))
  121. # too long arrays are OK
  122. cases.append(([a], [0], (1, 1), [[1]]))
  123. cases.append(([a[:3],b], [0,2], (3, 3), [[1, 0, 6], [0, 2, 0], [0, 0, 3]]))
  124. cases.append((np.array([[1, 2, 3], [4, 5, 6]]), [0,-1], (3, 3), [[1, 0, 0], [4, 2, 0], [0, 5, 3]]))
  125. # scalar case: broadcasting
  126. cases.append(([1,-2,1], [1,0,-1], (3, 3), [[-2, 1, 0],
  127. [1, -2, 1],
  128. [0, 1, -2]]))
  129. for d, o, shape, result in cases:
  130. err_msg = "%r %r %r %r" % (d, o, shape, result)
  131. assert_equal(construct.diags(d, o, shape=shape).toarray(),
  132. result, err_msg=err_msg)
  133. if shape[0] == shape[1] and hasattr(d[0], '__len__') and len(d[0]) <= max(shape):
  134. # should be able to find the shape automatically
  135. assert_equal(construct.diags(d, o).toarray(), result,
  136. err_msg=err_msg)
  137. def test_diags_default(self):
  138. a = array([1, 2, 3, 4, 5])
  139. assert_equal(construct.diags(a).toarray(), np.diag(a))
  140. def test_diags_default_bad(self):
  141. a = array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])
  142. assert_raises(ValueError, construct.diags, a)
  143. def test_diags_bad(self):
  144. a = array([1, 2, 3, 4, 5])
  145. b = array([6, 7, 8, 9, 10])
  146. c = array([11, 12, 13, 14, 15])
  147. cases = []
  148. cases.append(([a[:0]], 0, (1, 1)))
  149. cases.append(([a[:4],b,c[:3]], [-1,0,1], (5, 5)))
  150. cases.append(([a[:2],c,b[:3]], [-4,2,-1], (6, 5)))
  151. cases.append(([a[:2],c,b[:3]], [-4,2,-1], None))
  152. cases.append(([], [-4,2,-1], None))
  153. cases.append(([1], [-5], (4, 4)))
  154. cases.append(([a], 0, None))
  155. for d, o, shape in cases:
  156. assert_raises(ValueError, construct.diags, d, o, shape)
  157. assert_raises(TypeError, construct.diags, [[None]], [0])
  158. def test_diags_vs_diag(self):
  159. # Check that
  160. #
  161. # diags([a, b, ...], [i, j, ...]) == diag(a, i) + diag(b, j) + ...
  162. #
  163. np.random.seed(1234)
  164. for n_diags in [1, 2, 3, 4, 5, 10]:
  165. n = 1 + n_diags//2 + np.random.randint(0, 10)
  166. offsets = np.arange(-n+1, n-1)
  167. np.random.shuffle(offsets)
  168. offsets = offsets[:n_diags]
  169. diagonals = [np.random.rand(n - abs(q)) for q in offsets]
  170. mat = construct.diags(diagonals, offsets)
  171. dense_mat = sum([np.diag(x, j) for x, j in zip(diagonals, offsets)])
  172. assert_array_almost_equal_nulp(mat.toarray(), dense_mat)
  173. if len(offsets) == 1:
  174. mat = construct.diags(diagonals[0], offsets[0])
  175. dense_mat = np.diag(diagonals[0], offsets[0])
  176. assert_array_almost_equal_nulp(mat.toarray(), dense_mat)
  177. def test_diags_dtype(self):
  178. x = construct.diags([2.2], [0], shape=(2, 2), dtype=int)
  179. assert_equal(x.dtype, int)
  180. assert_equal(x.toarray(), [[2, 0], [0, 2]])
  181. def test_diags_one_diagonal(self):
  182. d = list(range(5))
  183. for k in range(-5, 6):
  184. assert_equal(construct.diags(d, k).toarray(),
  185. construct.diags([d], [k]).toarray())
  186. def test_diags_empty(self):
  187. x = construct.diags([])
  188. assert_equal(x.shape, (0, 0))
  189. def test_identity(self):
  190. assert_equal(construct.identity(1).toarray(), [[1]])
  191. assert_equal(construct.identity(2).toarray(), [[1,0],[0,1]])
  192. I = construct.identity(3, dtype='int8', format='dia')
  193. assert_equal(I.dtype, np.dtype('int8'))
  194. assert_equal(I.format, 'dia')
  195. for fmt in sparse_formats:
  196. I = construct.identity(3, format=fmt)
  197. assert_equal(I.format, fmt)
  198. assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]])
  199. def test_eye(self):
  200. assert_equal(construct.eye(1,1).toarray(), [[1]])
  201. assert_equal(construct.eye(2,3).toarray(), [[1,0,0],[0,1,0]])
  202. assert_equal(construct.eye(3,2).toarray(), [[1,0],[0,1],[0,0]])
  203. assert_equal(construct.eye(3,3).toarray(), [[1,0,0],[0,1,0],[0,0,1]])
  204. assert_equal(construct.eye(3,3,dtype='int16').dtype, np.dtype('int16'))
  205. for m in [3, 5]:
  206. for n in [3, 5]:
  207. for k in range(-5,6):
  208. assert_equal(construct.eye(m, n, k=k).toarray(), np.eye(m, n, k=k))
  209. if m == n:
  210. assert_equal(construct.eye(m, k=k).toarray(), np.eye(m, n, k=k))
  211. def test_eye_one(self):
  212. assert_equal(construct.eye(1).toarray(), [[1]])
  213. assert_equal(construct.eye(2).toarray(), [[1,0],[0,1]])
  214. I = construct.eye(3, dtype='int8', format='dia')
  215. assert_equal(I.dtype, np.dtype('int8'))
  216. assert_equal(I.format, 'dia')
  217. for fmt in sparse_formats:
  218. I = construct.eye(3, format=fmt)
  219. assert_equal(I.format, fmt)
  220. assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]])
  221. def test_kron(self):
  222. cases = []
  223. cases.append(array([[0]]))
  224. cases.append(array([[-1]]))
  225. cases.append(array([[4]]))
  226. cases.append(array([[10]]))
  227. cases.append(array([[0],[0]]))
  228. cases.append(array([[0,0]]))
  229. cases.append(array([[1,2],[3,4]]))
  230. cases.append(array([[0,2],[5,0]]))
  231. cases.append(array([[0,2,-6],[8,0,14]]))
  232. cases.append(array([[5,4],[0,0],[6,0]]))
  233. cases.append(array([[5,4,4],[1,0,0],[6,0,8]]))
  234. cases.append(array([[0,1,0,2,0,5,8]]))
  235. cases.append(array([[0.5,0.125,0,3.25],[0,2.5,0,0]]))
  236. for a in cases:
  237. for b in cases:
  238. expected = np.kron(a, b)
  239. for fmt in sparse_formats:
  240. result = construct.kron(csr_matrix(a), csr_matrix(b), format=fmt)
  241. assert_equal(result.format, fmt)
  242. assert_array_equal(result.toarray(), expected)
  243. def test_kron_large(self):
  244. n = 2**16
  245. a = construct.eye(1, n, n-1)
  246. b = construct.eye(n, 1, 1-n)
  247. construct.kron(a, a)
  248. construct.kron(b, b)
  249. def test_kronsum(self):
  250. cases = []
  251. cases.append(array([[0]]))
  252. cases.append(array([[-1]]))
  253. cases.append(array([[4]]))
  254. cases.append(array([[10]]))
  255. cases.append(array([[1,2],[3,4]]))
  256. cases.append(array([[0,2],[5,0]]))
  257. cases.append(array([[0,2,-6],[8,0,14],[0,3,0]]))
  258. cases.append(array([[1,0,0],[0,5,-1],[4,-2,8]]))
  259. for a in cases:
  260. for b in cases:
  261. result = construct.kronsum(
  262. csr_matrix(a), csr_matrix(b)).toarray()
  263. expected = np.kron(np.eye(len(b)), a) + \
  264. np.kron(b, np.eye(len(a)))
  265. assert_array_equal(result,expected)
  266. def test_vstack(self):
  267. A = coo_matrix([[1,2],[3,4]])
  268. B = coo_matrix([[5,6]])
  269. expected = array([[1, 2],
  270. [3, 4],
  271. [5, 6]])
  272. assert_equal(construct.vstack([A, B]).toarray(), expected)
  273. assert_equal(construct.vstack([A, B], dtype=np.float32).dtype,
  274. np.float32)
  275. assert_equal(construct.vstack([A.tocsr(), B.tocsr()]).toarray(),
  276. expected)
  277. result = construct.vstack([A.tocsr(), B.tocsr()], dtype=np.float32)
  278. assert_equal(result.dtype, np.float32)
  279. assert_equal(result.indices.dtype, np.int32)
  280. assert_equal(result.indptr.dtype, np.int32)
  281. assert_equal(construct.vstack([A.tocsc(), B.tocsc()]).toarray(),
  282. expected)
  283. result = construct.vstack([A.tocsc(), B.tocsc()], dtype=np.float32)
  284. assert_equal(result.dtype, np.float32)
  285. assert_equal(result.indices.dtype, np.int32)
  286. assert_equal(result.indptr.dtype, np.int32)
  287. def test_hstack(self):
  288. A = coo_matrix([[1,2],[3,4]])
  289. B = coo_matrix([[5],[6]])
  290. expected = array([[1, 2, 5],
  291. [3, 4, 6]])
  292. assert_equal(construct.hstack([A, B]).toarray(), expected)
  293. assert_equal(construct.hstack([A, B], dtype=np.float32).dtype,
  294. np.float32)
  295. assert_equal(construct.hstack([A.tocsc(), B.tocsc()]).toarray(),
  296. expected)
  297. assert_equal(construct.hstack([A.tocsc(), B.tocsc()],
  298. dtype=np.float32).dtype,
  299. np.float32)
  300. assert_equal(construct.hstack([A.tocsr(), B.tocsr()]).toarray(),
  301. expected)
  302. assert_equal(construct.hstack([A.tocsr(), B.tocsr()],
  303. dtype=np.float32).dtype,
  304. np.float32)
  305. def test_bmat(self):
  306. A = coo_matrix([[1, 2], [3, 4]])
  307. B = coo_matrix([[5],[6]])
  308. C = coo_matrix([[7]])
  309. D = coo_matrix((0, 0))
  310. expected = array([[1, 2, 5],
  311. [3, 4, 6],
  312. [0, 0, 7]])
  313. assert_equal(construct.bmat([[A, B], [None, C]]).toarray(), expected)
  314. E = csr_matrix((1, 2), dtype=np.int32)
  315. assert_equal(construct.bmat([[A.tocsr(), B.tocsr()],
  316. [E, C.tocsr()]]).toarray(),
  317. expected)
  318. assert_equal(construct.bmat([[A.tocsc(), B.tocsc()],
  319. [E.tocsc(), C.tocsc()]]).toarray(),
  320. expected)
  321. expected = array([[1, 2, 0],
  322. [3, 4, 0],
  323. [0, 0, 7]])
  324. assert_equal(construct.bmat([[A, None], [None, C]]).toarray(),
  325. expected)
  326. assert_equal(construct.bmat([[A.tocsr(), E.T.tocsr()],
  327. [E, C.tocsr()]]).toarray(),
  328. expected)
  329. assert_equal(construct.bmat([[A.tocsc(), E.T.tocsc()],
  330. [E.tocsc(), C.tocsc()]]).toarray(),
  331. expected)
  332. Z = csr_matrix((1, 1), dtype=np.int32)
  333. expected = array([[0, 5],
  334. [0, 6],
  335. [7, 0]])
  336. assert_equal(construct.bmat([[None, B], [C, None]]).toarray(),
  337. expected)
  338. assert_equal(construct.bmat([[E.T.tocsr(), B.tocsr()],
  339. [C.tocsr(), Z]]).toarray(),
  340. expected)
  341. assert_equal(construct.bmat([[E.T.tocsc(), B.tocsc()],
  342. [C.tocsc(), Z.tocsc()]]).toarray(),
  343. expected)
  344. expected = matrix(np.empty((0, 0)))
  345. assert_equal(construct.bmat([[None, None]]).toarray(), expected)
  346. assert_equal(construct.bmat([[None, D], [D, None]]).toarray(),
  347. expected)
  348. # test bug reported in gh-5976
  349. expected = array([[7]])
  350. assert_equal(construct.bmat([[None, D], [C, None]]).toarray(),
  351. expected)
  352. # test failure cases
  353. with assert_raises(ValueError) as excinfo:
  354. construct.bmat([[A], [B]])
  355. excinfo.match(r'Got blocks\[1,0\]\.shape\[1\] == 1, expected 2')
  356. with assert_raises(ValueError) as excinfo:
  357. construct.bmat([[A.tocsr()], [B.tocsr()]])
  358. excinfo.match(r'incompatible dimensions for axis 1')
  359. with assert_raises(ValueError) as excinfo:
  360. construct.bmat([[A.tocsc()], [B.tocsc()]])
  361. excinfo.match(r'Mismatching dimensions along axis 1: ({1, 2}|{2, 1})')
  362. with assert_raises(ValueError) as excinfo:
  363. construct.bmat([[A, C]])
  364. excinfo.match(r'Got blocks\[0,1\]\.shape\[0\] == 1, expected 2')
  365. with assert_raises(ValueError) as excinfo:
  366. construct.bmat([[A.tocsr(), C.tocsr()]])
  367. excinfo.match(r'Mismatching dimensions along axis 0: ({1, 2}|{2, 1})')
  368. with assert_raises(ValueError) as excinfo:
  369. construct.bmat([[A.tocsc(), C.tocsc()]])
  370. excinfo.match(r'incompatible dimensions for axis 0')
  371. @pytest.mark.slow
  372. @pytest.mark.xfail_on_32bit("Can't create large array for test")
  373. def test_concatenate_int32_overflow(self):
  374. """ test for indptr overflow when concatenating matrices """
  375. check_free_memory(30000)
  376. n = 33000
  377. A = csr_matrix(np.ones((n, n), dtype=bool))
  378. B = A.copy()
  379. C = construct._compressed_sparse_stack((A,B), 0)
  380. assert_(np.all(np.equal(np.diff(C.indptr), n)))
  381. assert_equal(C.indices.dtype, np.int64)
  382. assert_equal(C.indptr.dtype, np.int64)
  383. def test_block_diag_basic(self):
  384. """ basic test for block_diag """
  385. A = coo_matrix([[1,2],[3,4]])
  386. B = coo_matrix([[5],[6]])
  387. C = coo_matrix([[7]])
  388. expected = array([[1, 2, 0, 0],
  389. [3, 4, 0, 0],
  390. [0, 0, 5, 0],
  391. [0, 0, 6, 0],
  392. [0, 0, 0, 7]])
  393. assert_equal(construct.block_diag((A, B, C)).toarray(), expected)
  394. def test_block_diag_scalar_1d_args(self):
  395. """ block_diag with scalar and 1d arguments """
  396. # one 1d matrix and a scalar
  397. assert_array_equal(construct.block_diag([[2,3], 4]).toarray(),
  398. [[2, 3, 0], [0, 0, 4]])
  399. def test_block_diag_1(self):
  400. """ block_diag with one matrix """
  401. assert_equal(construct.block_diag([[1, 0]]).toarray(),
  402. array([[1, 0]]))
  403. assert_equal(construct.block_diag([[[1, 0]]]).toarray(),
  404. array([[1, 0]]))
  405. assert_equal(construct.block_diag([[[1], [0]]]).toarray(),
  406. array([[1], [0]]))
  407. # just on scalar
  408. assert_equal(construct.block_diag([1]).toarray(),
  409. array([[1]]))
  410. def test_block_diag_sparse_matrices(self):
  411. """ block_diag with sparse matrices """
  412. sparse_col_matrices = [coo_matrix(([[1, 2, 3]]), shape=(1, 3)),
  413. coo_matrix(([[4, 5]]), shape=(1, 2))]
  414. block_sparse_cols_matrices = construct.block_diag(sparse_col_matrices)
  415. assert_equal(block_sparse_cols_matrices.toarray(),
  416. array([[1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]))
  417. sparse_row_matrices = [coo_matrix(([[1], [2], [3]]), shape=(3, 1)),
  418. coo_matrix(([[4], [5]]), shape=(2, 1))]
  419. block_sparse_row_matrices = construct.block_diag(sparse_row_matrices)
  420. assert_equal(block_sparse_row_matrices.toarray(),
  421. array([[1, 0], [2, 0], [3, 0], [0, 4], [0, 5]]))
  422. def test_random_sampling(self):
  423. # Simple sanity checks for sparse random sampling.
  424. for f in sprand, _sprandn:
  425. for t in [np.float32, np.float64, np.longdouble,
  426. np.int32, np.int64, np.complex64, np.complex128]:
  427. x = f(5, 10, density=0.1, dtype=t)
  428. assert_equal(x.dtype, t)
  429. assert_equal(x.shape, (5, 10))
  430. assert_equal(x.nnz, 5)
  431. x1 = f(5, 10, density=0.1, random_state=4321)
  432. assert_equal(x1.dtype, np.double)
  433. x2 = f(5, 10, density=0.1,
  434. random_state=np.random.RandomState(4321))
  435. assert_array_equal(x1.data, x2.data)
  436. assert_array_equal(x1.row, x2.row)
  437. assert_array_equal(x1.col, x2.col)
  438. for density in [0.0, 0.1, 0.5, 1.0]:
  439. x = f(5, 10, density=density)
  440. assert_equal(x.nnz, int(density * np.prod(x.shape)))
  441. for fmt in ['coo', 'csc', 'csr', 'lil']:
  442. x = f(5, 10, format=fmt)
  443. assert_equal(x.format, fmt)
  444. assert_raises(ValueError, lambda: f(5, 10, 1.1))
  445. assert_raises(ValueError, lambda: f(5, 10, -0.1))
  446. def test_rand(self):
  447. # Simple distributional checks for sparse.rand.
  448. random_states = [None, 4321, np.random.RandomState()]
  449. try:
  450. gen = np.random.default_rng()
  451. random_states.append(gen)
  452. except AttributeError:
  453. pass
  454. for random_state in random_states:
  455. x = sprand(10, 20, density=0.5, dtype=np.float64,
  456. random_state=random_state)
  457. assert_(np.all(np.less_equal(0, x.data)))
  458. assert_(np.all(np.less_equal(x.data, 1)))
  459. def test_randn(self):
  460. # Simple distributional checks for sparse.randn.
  461. # Statistically, some of these should be negative
  462. # and some should be greater than 1.
  463. random_states = [None, 4321, np.random.RandomState()]
  464. try:
  465. gen = np.random.default_rng()
  466. random_states.append(gen)
  467. except AttributeError:
  468. pass
  469. for random_state in random_states:
  470. x = _sprandn(10, 20, density=0.5, dtype=np.float64,
  471. random_state=random_state)
  472. assert_(np.any(np.less(x.data, 0)))
  473. assert_(np.any(np.less(1, x.data)))
  474. def test_random_accept_str_dtype(self):
  475. # anything that np.dtype can convert to a dtype should be accepted
  476. # for the dtype
  477. construct.random(10, 10, dtype='d')
  478. def test_random_sparse_matrix_returns_correct_number_of_non_zero_elements(self):
  479. # A 10 x 10 matrix, with density of 12.65%, should have 13 nonzero elements.
  480. # 10 x 10 x 0.1265 = 12.65, which should be rounded up to 13, not 12.
  481. sparse_matrix = construct.random(10, 10, density=0.1265)
  482. assert_equal(sparse_matrix.count_nonzero(),13)