Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/scipy/sparse/_csc.py: 36%

86 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-23 06:43 +0000

1"""Compressed Sparse Column matrix format""" 

2__docformat__ = "restructuredtext en" 

3 

4__all__ = ['csc_array', 'csc_matrix', 'isspmatrix_csc'] 

5 

6 

7import numpy as np 

8 

9from ._matrix import spmatrix 

10from ._base import _spbase, sparray 

11from ._sparsetools import csc_tocsr, expandptr 

12from ._sputils import upcast 

13 

14from ._compressed import _cs_matrix 

15 

16 

17class _csc_base(_cs_matrix): 

18 _format = 'csc' 

19 

20 def transpose(self, axes=None, copy=False): 

21 if axes is not None and axes != (1, 0): 

22 raise ValueError("Sparse arrays/matrices do not support " 

23 "an 'axes' parameter because swapping " 

24 "dimensions is the only logical permutation.") 

25 

26 M, N = self.shape 

27 

28 return self._csr_container((self.data, self.indices, 

29 self.indptr), (N, M), copy=copy) 

30 

31 transpose.__doc__ = _spbase.transpose.__doc__ 

32 

33 def __iter__(self): 

34 yield from self.tocsr() 

35 

36 def tocsc(self, copy=False): 

37 if copy: 

38 return self.copy() 

39 else: 

40 return self 

41 

42 tocsc.__doc__ = _spbase.tocsc.__doc__ 

43 

44 def tocsr(self, copy=False): 

45 M,N = self.shape 

46 idx_dtype = self._get_index_dtype((self.indptr, self.indices), 

47 maxval=max(self.nnz, N)) 

48 indptr = np.empty(M + 1, dtype=idx_dtype) 

49 indices = np.empty(self.nnz, dtype=idx_dtype) 

50 data = np.empty(self.nnz, dtype=upcast(self.dtype)) 

51 

52 csc_tocsr(M, N, 

53 self.indptr.astype(idx_dtype), 

54 self.indices.astype(idx_dtype), 

55 self.data, 

56 indptr, 

57 indices, 

58 data) 

59 

60 A = self._csr_container( 

61 (data, indices, indptr), 

62 shape=self.shape, copy=False 

63 ) 

64 A.has_sorted_indices = True 

65 return A 

66 

67 tocsr.__doc__ = _spbase.tocsr.__doc__ 

68 

69 def nonzero(self): 

70 # CSC can't use _cs_matrix's .nonzero method because it 

71 # returns the indices sorted for self transposed. 

72 

73 # Get row and col indices, from _cs_matrix.tocoo 

74 major_dim, minor_dim = self._swap(self.shape) 

75 minor_indices = self.indices 

76 major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype) 

77 expandptr(major_dim, self.indptr, major_indices) 

78 row, col = self._swap((major_indices, minor_indices)) 

79 

80 # Remove explicit zeros 

81 nz_mask = self.data != 0 

82 row = row[nz_mask] 

83 col = col[nz_mask] 

84 

85 # Sort them to be in C-style order 

86 ind = np.argsort(row, kind='mergesort') 

87 row = row[ind] 

88 col = col[ind] 

89 

90 return row, col 

91 

92 nonzero.__doc__ = _cs_matrix.nonzero.__doc__ 

93 

94 def _getrow(self, i): 

95 """Returns a copy of row i of the matrix, as a (1 x n) 

96 CSR matrix (row vector). 

97 """ 

98 M, N = self.shape 

99 i = int(i) 

100 if i < 0: 

101 i += M 

102 if i < 0 or i >= M: 

103 raise IndexError('index (%d) out of range' % i) 

104 return self._get_submatrix(minor=i).tocsr() 

105 

106 def _getcol(self, i): 

107 """Returns a copy of column i of the matrix, as a (m x 1) 

108 CSC matrix (column vector). 

109 """ 

110 M, N = self.shape 

111 i = int(i) 

112 if i < 0: 

113 i += N 

114 if i < 0 or i >= N: 

115 raise IndexError('index (%d) out of range' % i) 

116 return self._get_submatrix(major=i, copy=True) 

117 

118 def _get_intXarray(self, row, col): 

119 return self._major_index_fancy(col)._get_submatrix(minor=row) 

120 

121 def _get_intXslice(self, row, col): 

122 if col.step in (1, None): 

123 return self._get_submatrix(major=col, minor=row, copy=True) 

124 return self._major_slice(col)._get_submatrix(minor=row) 

125 

126 def _get_sliceXint(self, row, col): 

127 if row.step in (1, None): 

128 return self._get_submatrix(major=col, minor=row, copy=True) 

129 return self._get_submatrix(major=col)._minor_slice(row) 

130 

131 def _get_sliceXarray(self, row, col): 

132 return self._major_index_fancy(col)._minor_slice(row) 

133 

134 def _get_arrayXint(self, row, col): 

135 return self._get_submatrix(major=col)._minor_index_fancy(row) 

136 

137 def _get_arrayXslice(self, row, col): 

138 return self._major_slice(col)._minor_index_fancy(row) 

139 

140 # these functions are used by the parent class (_cs_matrix) 

141 # to remove redudancy between csc_array and csr_matrix 

142 def _swap(self, x): 

143 """swap the members of x if this is a column-oriented matrix 

144 """ 

145 return x[1], x[0] 

146 

147 

148def isspmatrix_csc(x): 

149 """Is `x` of csc_matrix type? 

150 

151 Parameters 

152 ---------- 

153 x 

154 object to check for being a csc matrix 

155 

156 Returns 

157 ------- 

158 bool 

159 True if `x` is a csc matrix, False otherwise 

160 

161 Examples 

162 -------- 

163 >>> from scipy.sparse import csc_array, csc_matrix, coo_matrix, isspmatrix_csc 

164 >>> isspmatrix_csc(csc_matrix([[5]])) 

165 True 

166 >>> isspmatrix_csc(csc_array([[5]])) 

167 False 

168 >>> isspmatrix_csc(coo_matrix([[5]])) 

169 False 

170 """ 

171 return isinstance(x, csc_matrix) 

172 

173 

174# This namespace class separates array from matrix with isinstance 

175class csc_array(_csc_base, sparray): 

176 """ 

177 Compressed Sparse Column array. 

178 

179 This can be instantiated in several ways: 

180 csc_array(D) 

181 where D is a 2-D ndarray 

182 

183 csc_array(S) 

184 with another sparse array or matrix S (equivalent to S.tocsc()) 

185 

186 csc_array((M, N), [dtype]) 

187 to construct an empty array with shape (M, N) 

188 dtype is optional, defaulting to dtype='d'. 

189 

190 csc_array((data, (row_ind, col_ind)), [shape=(M, N)]) 

191 where ``data``, ``row_ind`` and ``col_ind`` satisfy the 

192 relationship ``a[row_ind[k], col_ind[k]] = data[k]``. 

193 

194 csc_array((data, indices, indptr), [shape=(M, N)]) 

195 is the standard CSC representation where the row indices for 

196 column i are stored in ``indices[indptr[i]:indptr[i+1]]`` 

197 and their corresponding values are stored in 

198 ``data[indptr[i]:indptr[i+1]]``. If the shape parameter is 

199 not supplied, the array dimensions are inferred from 

200 the index arrays. 

201 

202 Attributes 

203 ---------- 

204 dtype : dtype 

205 Data type of the array 

206 shape : 2-tuple 

207 Shape of the array 

208 ndim : int 

209 Number of dimensions (this is always 2) 

210 nnz 

211 size 

212 data 

213 CSC format data array of the array 

214 indices 

215 CSC format index array of the array 

216 indptr 

217 CSC format index pointer array of the array 

218 has_sorted_indices 

219 has_canonical_format 

220 T 

221 

222 Notes 

223 ----- 

224 

225 Sparse arrays can be used in arithmetic operations: they support 

226 addition, subtraction, multiplication, division, and matrix power. 

227 

228 Advantages of the CSC format 

229 - efficient arithmetic operations CSC + CSC, CSC * CSC, etc. 

230 - efficient column slicing 

231 - fast matrix vector products (CSR, BSR may be faster) 

232 

233 Disadvantages of the CSC format 

234 - slow row slicing operations (consider CSR) 

235 - changes to the sparsity structure are expensive (consider LIL or DOK) 

236 

237 Canonical format 

238 - Within each column, indices are sorted by row. 

239 - There are no duplicate entries. 

240 

241 Examples 

242 -------- 

243 

244 >>> import numpy as np 

245 >>> from scipy.sparse import csc_array 

246 >>> csc_array((3, 4), dtype=np.int8).toarray() 

247 array([[0, 0, 0, 0], 

248 [0, 0, 0, 0], 

249 [0, 0, 0, 0]], dtype=int8) 

250 

251 >>> row = np.array([0, 2, 2, 0, 1, 2]) 

252 >>> col = np.array([0, 0, 1, 2, 2, 2]) 

253 >>> data = np.array([1, 2, 3, 4, 5, 6]) 

254 >>> csc_array((data, (row, col)), shape=(3, 3)).toarray() 

255 array([[1, 0, 4], 

256 [0, 0, 5], 

257 [2, 3, 6]]) 

258 

259 >>> indptr = np.array([0, 2, 3, 6]) 

260 >>> indices = np.array([0, 2, 2, 0, 1, 2]) 

261 >>> data = np.array([1, 2, 3, 4, 5, 6]) 

262 >>> csc_array((data, indices, indptr), shape=(3, 3)).toarray() 

263 array([[1, 0, 4], 

264 [0, 0, 5], 

265 [2, 3, 6]]) 

266 

267 """ 

268 

269 

270class csc_matrix(spmatrix, _csc_base): 

271 """ 

272 Compressed Sparse Column matrix. 

273 

274 This can be instantiated in several ways: 

275 csc_matrix(D) 

276 where D is a 2-D ndarray 

277 

278 csc_matrix(S) 

279 with another sparse array or matrix S (equivalent to S.tocsc()) 

280 

281 csc_matrix((M, N), [dtype]) 

282 to construct an empty matrix with shape (M, N) 

283 dtype is optional, defaulting to dtype='d'. 

284 

285 csc_matrix((data, (row_ind, col_ind)), [shape=(M, N)]) 

286 where ``data``, ``row_ind`` and ``col_ind`` satisfy the 

287 relationship ``a[row_ind[k], col_ind[k]] = data[k]``. 

288 

289 csc_matrix((data, indices, indptr), [shape=(M, N)]) 

290 is the standard CSC representation where the row indices for 

291 column i are stored in ``indices[indptr[i]:indptr[i+1]]`` 

292 and their corresponding values are stored in 

293 ``data[indptr[i]:indptr[i+1]]``. If the shape parameter is 

294 not supplied, the matrix dimensions are inferred from 

295 the index arrays. 

296 

297 Attributes 

298 ---------- 

299 dtype : dtype 

300 Data type of the matrix 

301 shape : 2-tuple 

302 Shape of the matrix 

303 ndim : int 

304 Number of dimensions (this is always 2) 

305 nnz 

306 size 

307 data 

308 CSC format data array of the matrix 

309 indices 

310 CSC format index array of the matrix 

311 indptr 

312 CSC format index pointer array of the matrix 

313 has_sorted_indices 

314 has_canonical_format 

315 T 

316 

317 Notes 

318 ----- 

319 

320 Sparse matrices can be used in arithmetic operations: they support 

321 addition, subtraction, multiplication, division, and matrix power. 

322 

323 Advantages of the CSC format 

324 - efficient arithmetic operations CSC + CSC, CSC * CSC, etc. 

325 - efficient column slicing 

326 - fast matrix vector products (CSR, BSR may be faster) 

327 

328 Disadvantages of the CSC format 

329 - slow row slicing operations (consider CSR) 

330 - changes to the sparsity structure are expensive (consider LIL or DOK) 

331 

332 Canonical format 

333 - Within each column, indices are sorted by row. 

334 - There are no duplicate entries. 

335 

336 Examples 

337 -------- 

338 

339 >>> import numpy as np 

340 >>> from scipy.sparse import csc_matrix 

341 >>> csc_matrix((3, 4), dtype=np.int8).toarray() 

342 array([[0, 0, 0, 0], 

343 [0, 0, 0, 0], 

344 [0, 0, 0, 0]], dtype=int8) 

345 

346 >>> row = np.array([0, 2, 2, 0, 1, 2]) 

347 >>> col = np.array([0, 0, 1, 2, 2, 2]) 

348 >>> data = np.array([1, 2, 3, 4, 5, 6]) 

349 >>> csc_matrix((data, (row, col)), shape=(3, 3)).toarray() 

350 array([[1, 0, 4], 

351 [0, 0, 5], 

352 [2, 3, 6]]) 

353 

354 >>> indptr = np.array([0, 2, 3, 6]) 

355 >>> indices = np.array([0, 2, 2, 0, 1, 2]) 

356 >>> data = np.array([1, 2, 3, 4, 5, 6]) 

357 >>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray() 

358 array([[1, 0, 4], 

359 [0, 0, 5], 

360 [2, 3, 6]]) 

361 

362 """ 

363