_bsr.py 25 KB

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