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