bsr.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. """Compressed Block Sparse Row matrix format"""
  2. from __future__ import division, print_function, absolute_import
  3. __docformat__ = "restructuredtext en"
  4. __all__ = ['bsr_matrix', 'isspmatrix_bsr']
  5. from warnings import warn
  6. import numpy as np
  7. from .data import _data_matrix, _minmax_mixin
  8. from .compressed import _cs_matrix
  9. from .base import isspmatrix, _formats, spmatrix
  10. from .sputils import (isshape, getdtype, to_native, upcast, get_index_dtype,
  11. check_shape)
  12. from . import _sparsetools
  13. from ._sparsetools import (bsr_matvec, bsr_matvecs, csr_matmat_pass1,
  14. bsr_matmat_pass2, bsr_transpose, bsr_sort_indices,
  15. bsr_tocsr)
  16. class bsr_matrix(_cs_matrix, _minmax_mixin):
  17. """Block Sparse Row matrix
  18. This can be instantiated in several ways:
  19. bsr_matrix(D, [blocksize=(R,C)])
  20. where D is a dense matrix or 2-D ndarray.
  21. bsr_matrix(S, [blocksize=(R,C)])
  22. with another sparse matrix S (equivalent to S.tobsr())
  23. bsr_matrix((M, N), [blocksize=(R,C), dtype])
  24. to construct an empty matrix with shape (M, N)
  25. dtype is optional, defaulting to dtype='d'.
  26. bsr_matrix((data, ij), [blocksize=(R,C), shape=(M, N)])
  27. where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``
  28. bsr_matrix((data, indices, indptr), [shape=(M, N)])
  29. is the standard BSR representation where the block column
  30. indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]``
  31. and their corresponding block values are stored in
  32. ``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not
  33. supplied, the matrix dimensions are inferred from the index arrays.
  34. Attributes
  35. ----------
  36. dtype : dtype
  37. Data type of the matrix
  38. shape : 2-tuple
  39. Shape of the matrix
  40. ndim : int
  41. Number of dimensions (this is always 2)
  42. nnz
  43. Number of nonzero elements
  44. data
  45. Data array of the matrix
  46. indices
  47. BSR format index array
  48. indptr
  49. BSR format index pointer array
  50. blocksize
  51. Block size of the matrix
  52. has_sorted_indices
  53. Whether indices are sorted
  54. Notes
  55. -----
  56. Sparse matrices can be used in arithmetic operations: they support
  57. addition, subtraction, multiplication, division, and matrix power.
  58. **Summary of BSR format**
  59. The Block Compressed Row (BSR) format is very similar to the Compressed
  60. Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense
  61. sub matrices like the last example below. Block matrices often arise in
  62. vector-valued finite element discretizations. In such cases, BSR is
  63. considerably more efficient than CSR and CSC for many sparse arithmetic
  64. operations.
  65. **Blocksize**
  66. The blocksize (R,C) must evenly divide the shape of the matrix (M,N).
  67. That is, R and C must satisfy the relationship ``M % R = 0`` and
  68. ``N % C = 0``.
  69. If no blocksize is specified, a simple heuristic is applied to determine
  70. an appropriate blocksize.
  71. Examples
  72. --------
  73. >>> from scipy.sparse import bsr_matrix
  74. >>> bsr_matrix((3, 4), dtype=np.int8).toarray()
  75. array([[0, 0, 0, 0],
  76. [0, 0, 0, 0],
  77. [0, 0, 0, 0]], dtype=int8)
  78. >>> row = np.array([0, 0, 1, 2, 2, 2])
  79. >>> col = np.array([0, 2, 2, 0, 1, 2])
  80. >>> data = np.array([1, 2, 3 ,4, 5, 6])
  81. >>> bsr_matrix((data, (row, col)), shape=(3, 3)).toarray()
  82. array([[1, 0, 2],
  83. [0, 0, 3],
  84. [4, 5, 6]])
  85. >>> indptr = np.array([0, 2, 3, 6])
  86. >>> indices = np.array([0, 2, 2, 0, 1, 2])
  87. >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
  88. >>> bsr_matrix((data,indices,indptr), shape=(6, 6)).toarray()
  89. array([[1, 1, 0, 0, 2, 2],
  90. [1, 1, 0, 0, 2, 2],
  91. [0, 0, 0, 0, 3, 3],
  92. [0, 0, 0, 0, 3, 3],
  93. [4, 4, 5, 5, 6, 6],
  94. [4, 4, 5, 5, 6, 6]])
  95. """
  96. format = 'bsr'
  97. def __init__(self, arg1, shape=None, dtype=None, copy=False, blocksize=None):
  98. _data_matrix.__init__(self)
  99. if isspmatrix(arg1):
  100. if isspmatrix_bsr(arg1) and copy:
  101. arg1 = arg1.copy()
  102. else:
  103. arg1 = arg1.tobsr(blocksize=blocksize)
  104. self._set_self(arg1)
  105. elif isinstance(arg1,tuple):
  106. if isshape(arg1):
  107. # it's a tuple of matrix dimensions (M,N)
  108. self._shape = check_shape(arg1)
  109. M,N = self.shape
  110. # process blocksize
  111. if blocksize is None:
  112. blocksize = (1,1)
  113. else:
  114. if not isshape(blocksize):
  115. raise ValueError('invalid blocksize=%s' % blocksize)
  116. blocksize = tuple(blocksize)
  117. self.data = np.zeros((0,) + blocksize, getdtype(dtype, default=float))
  118. R,C = blocksize
  119. if (M % R) != 0 or (N % C) != 0:
  120. raise ValueError('shape must be multiple of blocksize')
  121. # Select index dtype large enough to pass array and
  122. # scalar parameters to sparsetools
  123. idx_dtype = get_index_dtype(maxval=max(M//R, N//C, R, C))
  124. self.indices = np.zeros(0, dtype=idx_dtype)
  125. self.indptr = np.zeros(M//R + 1, dtype=idx_dtype)
  126. elif len(arg1) == 2:
  127. # (data,(row,col)) format
  128. from .coo import coo_matrix
  129. self._set_self(coo_matrix(arg1, dtype=dtype).tobsr(blocksize=blocksize))
  130. elif len(arg1) == 3:
  131. # (data,indices,indptr) format
  132. (data, indices, indptr) = arg1
  133. # Select index dtype large enough to pass array and
  134. # scalar parameters to sparsetools
  135. maxval = 1
  136. if shape is not None:
  137. maxval = max(shape)
  138. if blocksize is not None:
  139. maxval = max(maxval, max(blocksize))
  140. idx_dtype = get_index_dtype((indices, indptr), maxval=maxval, check_contents=True)
  141. self.indices = np.array(indices, copy=copy, dtype=idx_dtype)
  142. self.indptr = np.array(indptr, copy=copy, dtype=idx_dtype)
  143. self.data = np.array(data, copy=copy, dtype=getdtype(dtype, data))
  144. else:
  145. raise ValueError('unrecognized bsr_matrix constructor usage')
  146. else:
  147. # must be dense
  148. try:
  149. arg1 = np.asarray(arg1)
  150. except Exception:
  151. raise ValueError("unrecognized form for"
  152. " %s_matrix constructor" % self.format)
  153. from .coo import coo_matrix
  154. arg1 = coo_matrix(arg1, dtype=dtype).tobsr(blocksize=blocksize)
  155. self._set_self(arg1)
  156. if shape is not None:
  157. self._shape = check_shape(shape)
  158. else:
  159. if self.shape is None:
  160. # shape not already set, try to infer dimensions
  161. try:
  162. M = len(self.indptr) - 1
  163. N = self.indices.max() + 1
  164. except Exception:
  165. raise ValueError('unable to infer matrix dimensions')
  166. else:
  167. R,C = self.blocksize
  168. self._shape = check_shape((M*R,N*C))
  169. if self.shape is None:
  170. if shape is None:
  171. # TODO infer shape here
  172. raise ValueError('need to infer shape')
  173. else:
  174. self._shape = check_shape(shape)
  175. if dtype is not None:
  176. self.data = self.data.astype(dtype)
  177. self.check_format(full_check=False)
  178. def check_format(self, full_check=True):
  179. """check whether the matrix format is valid
  180. *Parameters*:
  181. full_check:
  182. True - rigorous check, O(N) operations : default
  183. False - basic check, O(1) operations
  184. """
  185. M,N = self.shape
  186. R,C = self.blocksize
  187. # index arrays should have integer data types
  188. if self.indptr.dtype.kind != 'i':
  189. warn("indptr array has non-integer dtype (%s)"
  190. % self.indptr.dtype.name)
  191. if self.indices.dtype.kind != 'i':
  192. warn("indices array has non-integer dtype (%s)"
  193. % self.indices.dtype.name)
  194. idx_dtype = get_index_dtype((self.indices, self.indptr))
  195. self.indptr = np.asarray(self.indptr, dtype=idx_dtype)
  196. self.indices = np.asarray(self.indices, dtype=idx_dtype)
  197. self.data = to_native(self.data)
  198. # check array shapes
  199. if self.indices.ndim != 1 or self.indptr.ndim != 1:
  200. raise ValueError("indices, and indptr should be 1-D")
  201. if self.data.ndim != 3:
  202. raise ValueError("data should be 3-D")
  203. # check index pointer
  204. if (len(self.indptr) != M//R + 1):
  205. raise ValueError("index pointer size (%d) should be (%d)" %
  206. (len(self.indptr), M//R + 1))
  207. if (self.indptr[0] != 0):
  208. raise ValueError("index pointer should start with 0")
  209. # check index and data arrays
  210. if (len(self.indices) != len(self.data)):
  211. raise ValueError("indices and data should have the same size")
  212. if (self.indptr[-1] > len(self.indices)):
  213. raise ValueError("Last value of index pointer should be less than "
  214. "the size of index and data arrays")
  215. self.prune()
  216. if full_check:
  217. # check format validity (more expensive)
  218. if self.nnz > 0:
  219. if self.indices.max() >= N//C:
  220. raise ValueError("column index values must be < %d (now max %d)" % (N//C, self.indices.max()))
  221. if self.indices.min() < 0:
  222. raise ValueError("column index values must be >= 0")
  223. if np.diff(self.indptr).min() < 0:
  224. raise ValueError("index pointer values must form a "
  225. "non-decreasing sequence")
  226. # if not self.has_sorted_indices():
  227. # warn('Indices were not in sorted order. Sorting indices.')
  228. # self.sort_indices(check_first=False)
  229. def _get_blocksize(self):
  230. return self.data.shape[1:]
  231. blocksize = property(fget=_get_blocksize)
  232. def getnnz(self, axis=None):
  233. if axis is not None:
  234. raise NotImplementedError("getnnz over an axis is not implemented "
  235. "for BSR format")
  236. R,C = self.blocksize
  237. return int(self.indptr[-1] * R * C)
  238. getnnz.__doc__ = spmatrix.getnnz.__doc__
  239. def __repr__(self):
  240. format = _formats[self.getformat()][1]
  241. return ("<%dx%d sparse matrix of type '%s'\n"
  242. "\twith %d stored elements (blocksize = %dx%d) in %s format>" %
  243. (self.shape + (self.dtype.type, self.nnz) + self.blocksize +
  244. (format,)))
  245. def diagonal(self, k=0):
  246. rows, cols = self.shape
  247. if k <= -rows or k >= cols:
  248. raise ValueError("k exceeds matrix dimensions")
  249. R, C = self.blocksize
  250. y = np.zeros(min(rows + min(k, 0), cols - max(k, 0)),
  251. dtype=upcast(self.dtype))
  252. _sparsetools.bsr_diagonal(k, rows // R, cols // C, R, C,
  253. self.indptr, self.indices,
  254. np.ravel(self.data), y)
  255. return y
  256. diagonal.__doc__ = spmatrix.diagonal.__doc__
  257. ##########################
  258. # NotImplemented methods #
  259. ##########################
  260. def __getitem__(self,key):
  261. raise NotImplementedError
  262. def __setitem__(self,key,val):
  263. raise NotImplementedError
  264. ######################
  265. # Arithmetic methods #
  266. ######################
  267. @np.deprecate(message="BSR matvec is deprecated in scipy 0.19.0. "
  268. "Use * operator instead.")
  269. def matvec(self, other):
  270. """Multiply matrix by vector."""
  271. return self * other
  272. @np.deprecate(message="BSR matmat is deprecated in scipy 0.19.0. "
  273. "Use * operator instead.")
  274. def matmat(self, other):
  275. """Multiply this sparse matrix by other matrix."""
  276. return self * other
  277. def _add_dense(self, other):
  278. return self.tocoo(copy=False)._add_dense(other)
  279. def _mul_vector(self, other):
  280. M,N = self.shape
  281. R,C = self.blocksize
  282. result = np.zeros(self.shape[0], dtype=upcast(self.dtype, other.dtype))
  283. bsr_matvec(M//R, N//C, R, C,
  284. self.indptr, self.indices, self.data.ravel(),
  285. other, result)
  286. return result
  287. def _mul_multivector(self,other):
  288. R,C = self.blocksize
  289. M,N = self.shape
  290. n_vecs = other.shape[1] # number of column vectors
  291. result = np.zeros((M,n_vecs), dtype=upcast(self.dtype,other.dtype))
  292. bsr_matvecs(M//R, N//C, n_vecs, R, C,
  293. self.indptr, self.indices, self.data.ravel(),
  294. other.ravel(), result.ravel())
  295. return result
  296. def _mul_sparse_matrix(self, other):
  297. M, K1 = self.shape
  298. K2, N = other.shape
  299. R,n = self.blocksize
  300. # convert to this format
  301. if isspmatrix_bsr(other):
  302. C = other.blocksize[1]
  303. else:
  304. C = 1
  305. from .csr import isspmatrix_csr
  306. if isspmatrix_csr(other) and n == 1:
  307. other = other.tobsr(blocksize=(n,C), copy=False) # lightweight conversion
  308. else:
  309. other = other.tobsr(blocksize=(n,C))
  310. idx_dtype = get_index_dtype((self.indptr, self.indices,
  311. other.indptr, other.indices),
  312. maxval=(M//R)*(N//C))
  313. indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
  314. csr_matmat_pass1(M//R, N//C,
  315. self.indptr.astype(idx_dtype),
  316. self.indices.astype(idx_dtype),
  317. other.indptr.astype(idx_dtype),
  318. other.indices.astype(idx_dtype),
  319. indptr)
  320. bnnz = indptr[-1]
  321. idx_dtype = get_index_dtype((self.indptr, self.indices,
  322. other.indptr, other.indices),
  323. maxval=bnnz)
  324. indptr = indptr.astype(idx_dtype)
  325. indices = np.empty(bnnz, dtype=idx_dtype)
  326. data = np.empty(R*C*bnnz, dtype=upcast(self.dtype,other.dtype))
  327. bsr_matmat_pass2(M//R, N//C, R, C, n,
  328. self.indptr.astype(idx_dtype),
  329. self.indices.astype(idx_dtype),
  330. np.ravel(self.data),
  331. other.indptr.astype(idx_dtype),
  332. other.indices.astype(idx_dtype),
  333. np.ravel(other.data),
  334. indptr,
  335. indices,
  336. data)
  337. data = data.reshape(-1,R,C)
  338. # TODO eliminate zeros
  339. return bsr_matrix((data,indices,indptr),shape=(M,N),blocksize=(R,C))
  340. ######################
  341. # Conversion methods #
  342. ######################
  343. def tobsr(self, blocksize=None, copy=False):
  344. """Convert this matrix into Block Sparse Row Format.
  345. With copy=False, the data/indices may be shared between this
  346. matrix and the resultant bsr_matrix.
  347. If blocksize=(R, C) is provided, it will be used for determining
  348. block size of the bsr_matrix.
  349. """
  350. if blocksize not in [None, self.blocksize]:
  351. return self.tocsr().tobsr(blocksize=blocksize)
  352. if copy:
  353. return self.copy()
  354. else:
  355. return self
  356. def tocsr(self, copy=False):
  357. M, N = self.shape
  358. R, C = self.blocksize
  359. nnz = self.nnz
  360. idx_dtype = get_index_dtype((self.indptr, self.indices),
  361. maxval=max(nnz, N))
  362. indptr = np.empty(M + 1, dtype=idx_dtype)
  363. indices = np.empty(nnz, dtype=idx_dtype)
  364. data = np.empty(nnz, dtype=upcast(self.dtype))
  365. bsr_tocsr(M // R, # n_brow
  366. N // C, # n_bcol
  367. R, C,
  368. self.indptr.astype(idx_dtype, copy=False),
  369. self.indices.astype(idx_dtype, copy=False),
  370. self.data,
  371. indptr,
  372. indices,
  373. data)
  374. from .csr import csr_matrix
  375. return csr_matrix((data, indices, indptr), shape=self.shape)
  376. tocsr.__doc__ = spmatrix.tocsr.__doc__
  377. def tocsc(self, copy=False):
  378. return self.tocsr(copy=False).tocsc(copy=copy)
  379. tocsc.__doc__ = spmatrix.tocsc.__doc__
  380. def tocoo(self, copy=True):
  381. """Convert this matrix to COOrdinate format.
  382. When copy=False the data array will be shared between
  383. this matrix and the resultant coo_matrix.
  384. """
  385. M,N = self.shape
  386. R,C = self.blocksize
  387. indptr_diff = np.diff(self.indptr)
  388. if indptr_diff.dtype.itemsize > np.dtype(np.intp).itemsize:
  389. # Check for potential overflow
  390. indptr_diff_limited = indptr_diff.astype(np.intp)
  391. if np.any(indptr_diff_limited != indptr_diff):
  392. raise ValueError("Matrix too big to convert")
  393. indptr_diff = indptr_diff_limited
  394. row = (R * np.arange(M//R)).repeat(indptr_diff)
  395. row = row.repeat(R*C).reshape(-1,R,C)
  396. row += np.tile(np.arange(R).reshape(-1,1), (1,C))
  397. row = row.reshape(-1)
  398. col = (C * self.indices).repeat(R*C).reshape(-1,R,C)
  399. col += np.tile(np.arange(C), (R,1))
  400. col = col.reshape(-1)
  401. data = self.data.reshape(-1)
  402. if copy:
  403. data = data.copy()
  404. from .coo import coo_matrix
  405. return coo_matrix((data,(row,col)), shape=self.shape)
  406. def toarray(self, order=None, out=None):
  407. return self.tocoo(copy=False).toarray(order=order, out=out)
  408. toarray.__doc__ = spmatrix.toarray.__doc__
  409. def transpose(self, axes=None, copy=False):
  410. if axes is not None:
  411. raise ValueError(("Sparse matrices do not support "
  412. "an 'axes' parameter because swapping "
  413. "dimensions is the only logical permutation."))
  414. R, C = self.blocksize
  415. M, N = self.shape
  416. NBLK = self.nnz//(R*C)
  417. if self.nnz == 0:
  418. return bsr_matrix((N, M), blocksize=(C, R),
  419. dtype=self.dtype, copy=copy)
  420. indptr = np.empty(N//C + 1, dtype=self.indptr.dtype)
  421. indices = np.empty(NBLK, dtype=self.indices.dtype)
  422. data = np.empty((NBLK, C, R), dtype=self.data.dtype)
  423. bsr_transpose(M//R, N//C, R, C,
  424. self.indptr, self.indices, self.data.ravel(),
  425. indptr, indices, data.ravel())
  426. return bsr_matrix((data, indices, indptr),
  427. shape=(N, M), copy=copy)
  428. transpose.__doc__ = spmatrix.transpose.__doc__
  429. ##############################################################
  430. # methods that examine or modify the internal data structure #
  431. ##############################################################
  432. def eliminate_zeros(self):
  433. """Remove zero elements in-place."""
  434. R,C = self.blocksize
  435. M,N = self.shape
  436. mask = (self.data != 0).reshape(-1,R*C).sum(axis=1) # nonzero blocks
  437. nonzero_blocks = mask.nonzero()[0]
  438. if len(nonzero_blocks) == 0:
  439. return # nothing to do
  440. self.data[:len(nonzero_blocks)] = self.data[nonzero_blocks]
  441. # modifies self.indptr and self.indices *in place*
  442. _sparsetools.csr_eliminate_zeros(M//R, N//C, self.indptr,
  443. self.indices, mask)
  444. self.prune()
  445. def sum_duplicates(self):
  446. """Eliminate duplicate matrix entries by adding them together
  447. The is an *in place* operation
  448. """
  449. if self.has_canonical_format:
  450. return
  451. self.sort_indices()
  452. R, C = self.blocksize
  453. M, N = self.shape
  454. # port of _sparsetools.csr_sum_duplicates
  455. n_row = M // R
  456. nnz = 0
  457. row_end = 0
  458. for i in range(n_row):
  459. jj = row_end
  460. row_end = self.indptr[i+1]
  461. while jj < row_end:
  462. j = self.indices[jj]
  463. x = self.data[jj]
  464. jj += 1
  465. while jj < row_end and self.indices[jj] == j:
  466. x += self.data[jj]
  467. jj += 1
  468. self.indices[nnz] = j
  469. self.data[nnz] = x
  470. nnz += 1
  471. self.indptr[i+1] = nnz
  472. self.prune() # nnz may have changed
  473. self.has_canonical_format = True
  474. def sort_indices(self):
  475. """Sort the indices of this matrix *in place*
  476. """
  477. if self.has_sorted_indices:
  478. return
  479. R,C = self.blocksize
  480. M,N = self.shape
  481. bsr_sort_indices(M//R, N//C, R, C, self.indptr, self.indices, self.data.ravel())
  482. self.has_sorted_indices = True
  483. def prune(self):
  484. """ Remove empty space after all non-zero elements.
  485. """
  486. R,C = self.blocksize
  487. M,N = self.shape
  488. if len(self.indptr) != M//R + 1:
  489. raise ValueError("index pointer has invalid length")
  490. bnnz = self.indptr[-1]
  491. if len(self.indices) < bnnz:
  492. raise ValueError("indices array has too few elements")
  493. if len(self.data) < bnnz:
  494. raise ValueError("data array has too few elements")
  495. self.data = self.data[:bnnz]
  496. self.indices = self.indices[:bnnz]
  497. # utility functions
  498. def _binopt(self, other, op, in_shape=None, out_shape=None):
  499. """Apply the binary operation fn to two sparse matrices."""
  500. # Ideally we'd take the GCDs of the blocksize dimensions
  501. # and explode self and other to match.
  502. other = self.__class__(other, blocksize=self.blocksize)
  503. # e.g. bsr_plus_bsr, etc.
  504. fn = getattr(_sparsetools, self.format + op + self.format)
  505. R,C = self.blocksize
  506. max_bnnz = len(self.data) + len(other.data)
  507. idx_dtype = get_index_dtype((self.indptr, self.indices,
  508. other.indptr, other.indices),
  509. maxval=max_bnnz)
  510. indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
  511. indices = np.empty(max_bnnz, dtype=idx_dtype)
  512. bool_ops = ['_ne_', '_lt_', '_gt_', '_le_', '_ge_']
  513. if op in bool_ops:
  514. data = np.empty(R*C*max_bnnz, dtype=np.bool_)
  515. else:
  516. data = np.empty(R*C*max_bnnz, dtype=upcast(self.dtype,other.dtype))
  517. fn(self.shape[0]//R, self.shape[1]//C, R, C,
  518. self.indptr.astype(idx_dtype),
  519. self.indices.astype(idx_dtype),
  520. self.data,
  521. other.indptr.astype(idx_dtype),
  522. other.indices.astype(idx_dtype),
  523. np.ravel(other.data),
  524. indptr,
  525. indices,
  526. data)
  527. actual_bnnz = indptr[-1]
  528. indices = indices[:actual_bnnz]
  529. data = data[:R*C*actual_bnnz]
  530. if actual_bnnz < max_bnnz/2:
  531. indices = indices.copy()
  532. data = data.copy()
  533. data = data.reshape(-1,R,C)
  534. return self.__class__((data, indices, indptr), shape=self.shape)
  535. # needed by _data_matrix
  536. def _with_data(self,data,copy=True):
  537. """Returns a matrix with the same sparsity structure as self,
  538. but with different data. By default the structure arrays
  539. (i.e. .indptr and .indices) are copied.
  540. """
  541. if copy:
  542. return self.__class__((data,self.indices.copy(),self.indptr.copy()),
  543. shape=self.shape,dtype=data.dtype)
  544. else:
  545. return self.__class__((data,self.indices,self.indptr),
  546. shape=self.shape,dtype=data.dtype)
  547. # # these functions are used by the parent class
  548. # # to remove redudancy between bsc_matrix and bsr_matrix
  549. # def _swap(self,x):
  550. # """swap the members of x if this is a column-oriented matrix
  551. # """
  552. # return (x[0],x[1])
  553. def isspmatrix_bsr(x):
  554. """Is x of a bsr_matrix type?
  555. Parameters
  556. ----------
  557. x
  558. object to check for being a bsr matrix
  559. Returns
  560. -------
  561. bool
  562. True if x is a bsr matrix, False otherwise
  563. Examples
  564. --------
  565. >>> from scipy.sparse import bsr_matrix, isspmatrix_bsr
  566. >>> isspmatrix_bsr(bsr_matrix([[5]]))
  567. True
  568. >>> from scipy.sparse import bsr_matrix, csr_matrix, isspmatrix_bsr
  569. >>> isspmatrix_bsr(csr_matrix([[5]]))
  570. False
  571. """
  572. return isinstance(x, bsr_matrix)