_csc.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. """Compressed Sparse Column matrix format"""
  2. __docformat__ = "restructuredtext en"
  3. __all__ = ['csc_matrix', 'isspmatrix_csc']
  4. import numpy as np
  5. from ._base import spmatrix
  6. from ._sparsetools import csc_tocsr, expandptr
  7. from ._sputils import upcast, get_index_dtype
  8. from ._compressed import _cs_matrix
  9. class csc_matrix(_cs_matrix):
  10. """
  11. Compressed Sparse Column matrix
  12. This can be instantiated in several ways:
  13. csc_matrix(D)
  14. with a dense matrix or rank-2 ndarray D
  15. csc_matrix(S)
  16. with another sparse matrix S (equivalent to S.tocsc())
  17. csc_matrix((M, N), [dtype])
  18. to construct an empty matrix with shape (M, N)
  19. dtype is optional, defaulting to dtype='d'.
  20. csc_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
  21. where ``data``, ``row_ind`` and ``col_ind`` satisfy the
  22. relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
  23. csc_matrix((data, indices, indptr), [shape=(M, N)])
  24. is the standard CSC representation where the row indices for
  25. column i are stored in ``indices[indptr[i]:indptr[i+1]]``
  26. and their corresponding values are stored in
  27. ``data[indptr[i]:indptr[i+1]]``. If the shape parameter is
  28. not supplied, the matrix dimensions are inferred from
  29. the index arrays.
  30. Attributes
  31. ----------
  32. dtype : dtype
  33. Data type of the matrix
  34. shape : 2-tuple
  35. Shape of the matrix
  36. ndim : int
  37. Number of dimensions (this is always 2)
  38. nnz
  39. Number of stored values, including explicit zeros
  40. data
  41. Data array of the matrix
  42. indices
  43. CSC format index array
  44. indptr
  45. CSC format index pointer array
  46. has_sorted_indices
  47. Whether indices are sorted
  48. Notes
  49. -----
  50. Sparse matrices can be used in arithmetic operations: they support
  51. addition, subtraction, multiplication, division, and matrix power.
  52. Advantages of the CSC format
  53. - efficient arithmetic operations CSC + CSC, CSC * CSC, etc.
  54. - efficient column slicing
  55. - fast matrix vector products (CSR, BSR may be faster)
  56. Disadvantages of the CSC format
  57. - slow row slicing operations (consider CSR)
  58. - changes to the sparsity structure are expensive (consider LIL or DOK)
  59. Examples
  60. --------
  61. >>> import numpy as np
  62. >>> from scipy.sparse import csc_matrix
  63. >>> csc_matrix((3, 4), dtype=np.int8).toarray()
  64. array([[0, 0, 0, 0],
  65. [0, 0, 0, 0],
  66. [0, 0, 0, 0]], dtype=int8)
  67. >>> row = np.array([0, 2, 2, 0, 1, 2])
  68. >>> col = np.array([0, 0, 1, 2, 2, 2])
  69. >>> data = np.array([1, 2, 3, 4, 5, 6])
  70. >>> csc_matrix((data, (row, col)), shape=(3, 3)).toarray()
  71. array([[1, 0, 4],
  72. [0, 0, 5],
  73. [2, 3, 6]])
  74. >>> indptr = np.array([0, 2, 3, 6])
  75. >>> indices = np.array([0, 2, 2, 0, 1, 2])
  76. >>> data = np.array([1, 2, 3, 4, 5, 6])
  77. >>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
  78. array([[1, 0, 4],
  79. [0, 0, 5],
  80. [2, 3, 6]])
  81. """
  82. format = 'csc'
  83. def transpose(self, axes=None, copy=False):
  84. if axes is not None:
  85. raise ValueError(("Sparse matrices do not support "
  86. "an 'axes' parameter because swapping "
  87. "dimensions is the only logical permutation."))
  88. M, N = self.shape
  89. return self._csr_container((self.data, self.indices,
  90. self.indptr), (N, M), copy=copy)
  91. transpose.__doc__ = spmatrix.transpose.__doc__
  92. def __iter__(self):
  93. yield from self.tocsr()
  94. def tocsc(self, copy=False):
  95. if copy:
  96. return self.copy()
  97. else:
  98. return self
  99. tocsc.__doc__ = spmatrix.tocsc.__doc__
  100. def tocsr(self, copy=False):
  101. M,N = self.shape
  102. idx_dtype = get_index_dtype((self.indptr, self.indices),
  103. maxval=max(self.nnz, N))
  104. indptr = np.empty(M + 1, dtype=idx_dtype)
  105. indices = np.empty(self.nnz, dtype=idx_dtype)
  106. data = np.empty(self.nnz, dtype=upcast(self.dtype))
  107. csc_tocsr(M, N,
  108. self.indptr.astype(idx_dtype),
  109. self.indices.astype(idx_dtype),
  110. self.data,
  111. indptr,
  112. indices,
  113. data)
  114. A = self._csr_container(
  115. (data, indices, indptr),
  116. shape=self.shape, copy=False
  117. )
  118. A.has_sorted_indices = True
  119. return A
  120. tocsr.__doc__ = spmatrix.tocsr.__doc__
  121. def nonzero(self):
  122. # CSC can't use _cs_matrix's .nonzero method because it
  123. # returns the indices sorted for self transposed.
  124. # Get row and col indices, from _cs_matrix.tocoo
  125. major_dim, minor_dim = self._swap(self.shape)
  126. minor_indices = self.indices
  127. major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype)
  128. expandptr(major_dim, self.indptr, major_indices)
  129. row, col = self._swap((major_indices, minor_indices))
  130. # Remove explicit zeros
  131. nz_mask = self.data != 0
  132. row = row[nz_mask]
  133. col = col[nz_mask]
  134. # Sort them to be in C-style order
  135. ind = np.argsort(row, kind='mergesort')
  136. row = row[ind]
  137. col = col[ind]
  138. return row, col
  139. nonzero.__doc__ = _cs_matrix.nonzero.__doc__
  140. def getrow(self, i):
  141. """Returns a copy of row i of the matrix, as a (1 x n)
  142. CSR matrix (row vector).
  143. """
  144. M, N = self.shape
  145. i = int(i)
  146. if i < 0:
  147. i += M
  148. if i < 0 or i >= M:
  149. raise IndexError('index (%d) out of range' % i)
  150. return self._get_submatrix(minor=i).tocsr()
  151. def getcol(self, i):
  152. """Returns a copy of column i of the matrix, as a (m x 1)
  153. CSC matrix (column vector).
  154. """
  155. M, N = self.shape
  156. i = int(i)
  157. if i < 0:
  158. i += N
  159. if i < 0 or i >= N:
  160. raise IndexError('index (%d) out of range' % i)
  161. return self._get_submatrix(major=i, copy=True)
  162. def _get_intXarray(self, row, col):
  163. return self._major_index_fancy(col)._get_submatrix(minor=row)
  164. def _get_intXslice(self, row, col):
  165. if col.step in (1, None):
  166. return self._get_submatrix(major=col, minor=row, copy=True)
  167. return self._major_slice(col)._get_submatrix(minor=row)
  168. def _get_sliceXint(self, row, col):
  169. if row.step in (1, None):
  170. return self._get_submatrix(major=col, minor=row, copy=True)
  171. return self._get_submatrix(major=col)._minor_slice(row)
  172. def _get_sliceXarray(self, row, col):
  173. return self._major_index_fancy(col)._minor_slice(row)
  174. def _get_arrayXint(self, row, col):
  175. return self._get_submatrix(major=col)._minor_index_fancy(row)
  176. def _get_arrayXslice(self, row, col):
  177. return self._major_slice(col)._minor_index_fancy(row)
  178. # these functions are used by the parent class (_cs_matrix)
  179. # to remove redudancy between csc_matrix and csr_matrix
  180. def _swap(self, x):
  181. """swap the members of x if this is a column-oriented matrix
  182. """
  183. return x[1], x[0]
  184. def isspmatrix_csc(x):
  185. """Is x of csc_matrix type?
  186. Parameters
  187. ----------
  188. x
  189. object to check for being a csc matrix
  190. Returns
  191. -------
  192. bool
  193. True if x is a csc matrix, False otherwise
  194. Examples
  195. --------
  196. >>> from scipy.sparse import csc_matrix, isspmatrix_csc
  197. >>> isspmatrix_csc(csc_matrix([[5]]))
  198. True
  199. >>> from scipy.sparse import csc_matrix, csr_matrix, isspmatrix_csc
  200. >>> isspmatrix_csc(csr_matrix([[5]]))
  201. False
  202. """
  203. from ._arrays import csc_array
  204. return isinstance(x, csc_matrix) or isinstance(x, csc_array)