Coverage for /usr/lib/python3/dist-packages/scipy/sparse/__init__.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2025-06-14 15:25 +0200

1""" 

2===================================== 

3Sparse matrices (:mod:`scipy.sparse`) 

4===================================== 

5 

6.. currentmodule:: scipy.sparse 

7 

8.. toctree:: 

9 :hidden: 

10 

11 sparse.csgraph 

12 sparse.linalg 

13 

14SciPy 2-D sparse array package for numeric data. 

15 

16.. note:: 

17 

18 This package is switching to an array interface, compatible with 

19 NumPy arrays, from the older matrix interface. We recommend that 

20 you use the array objects (`bsr_array`, `coo_array`, etc.) for 

21 all new work. 

22 

23 When using the array interface, please note that: 

24 

25 - ``x * y`` no longer performs matrix multiplication, but 

26 element-wise multiplication (just like with NumPy arrays). To 

27 make code work with both arrays and matrices, use ``x @ y`` for 

28 matrix multiplication. 

29 - Operations such as `sum`, that used to produce dense matrices, now 

30 produce arrays, whose multiplication behavior differs similarly. 

31 - Sparse arrays currently must be two-dimensional. This also means 

32 that all *slicing* operations on these objects must produce 

33 two-dimensional results, or they will result in an error. This 

34 will be addressed in a future version. 

35 

36 The construction utilities (`eye`, `kron`, `random`, `diags`, etc.) 

37 have not yet been ported, but their results can be wrapped into arrays:: 

38 

39 A = csr_array(eye(3)) 

40 

41Contents 

42======== 

43 

44Sparse array classes 

45-------------------- 

46 

47.. autosummary:: 

48 :toctree: generated/ 

49 

50 bsr_array - Block Sparse Row array 

51 coo_array - A sparse array in COOrdinate format 

52 csc_array - Compressed Sparse Column array 

53 csr_array - Compressed Sparse Row array 

54 dia_array - Sparse array with DIAgonal storage 

55 dok_array - Dictionary Of Keys based sparse array 

56 lil_array - Row-based list of lists sparse array 

57 sparray - Sparse array base class 

58 

59Sparse matrix classes 

60--------------------- 

61 

62.. autosummary:: 

63 :toctree: generated/ 

64 

65 bsr_matrix - Block Sparse Row matrix 

66 coo_matrix - A sparse matrix in COOrdinate format 

67 csc_matrix - Compressed Sparse Column matrix 

68 csr_matrix - Compressed Sparse Row matrix 

69 dia_matrix - Sparse matrix with DIAgonal storage 

70 dok_matrix - Dictionary Of Keys based sparse matrix 

71 lil_matrix - Row-based list of lists sparse matrix 

72 spmatrix - Sparse matrix base class 

73 

74Functions 

75--------- 

76 

77Building sparse matrices: 

78 

79.. autosummary:: 

80 :toctree: generated/ 

81 

82 eye - Sparse MxN matrix whose k-th diagonal is all ones 

83 identity - Identity matrix in sparse format 

84 kron - kronecker product of two sparse matrices 

85 kronsum - kronecker sum of sparse matrices 

86 diags - Return a sparse matrix from diagonals 

87 spdiags - Return a sparse matrix from diagonals 

88 block_diag - Build a block diagonal sparse matrix 

89 tril - Lower triangular portion of a matrix in sparse format 

90 triu - Upper triangular portion of a matrix in sparse format 

91 bmat - Build a sparse matrix from sparse sub-blocks 

92 hstack - Stack sparse matrices horizontally (column wise) 

93 vstack - Stack sparse matrices vertically (row wise) 

94 rand - Random values in a given shape 

95 random - Random values in a given shape 

96 

97Save and load sparse matrices: 

98 

99.. autosummary:: 

100 :toctree: generated/ 

101 

102 save_npz - Save a sparse matrix to a file using ``.npz`` format. 

103 load_npz - Load a sparse matrix from a file using ``.npz`` format. 

104 

105Sparse matrix tools: 

106 

107.. autosummary:: 

108 :toctree: generated/ 

109 

110 find 

111 

112Identifying sparse matrices: 

113 

114.. autosummary:: 

115 :toctree: generated/ 

116 

117 issparse 

118 isspmatrix 

119 isspmatrix_csc 

120 isspmatrix_csr 

121 isspmatrix_bsr 

122 isspmatrix_lil 

123 isspmatrix_dok 

124 isspmatrix_coo 

125 isspmatrix_dia 

126 

127Submodules 

128---------- 

129 

130.. autosummary:: 

131 

132 csgraph - Compressed sparse graph routines 

133 linalg - sparse linear algebra routines 

134 

135Exceptions 

136---------- 

137 

138.. autosummary:: 

139 :toctree: generated/ 

140 

141 SparseEfficiencyWarning 

142 SparseWarning 

143 

144 

145Usage information 

146================= 

147 

148There are seven available sparse matrix types: 

149 

150 1. csc_matrix: Compressed Sparse Column format 

151 2. csr_matrix: Compressed Sparse Row format 

152 3. bsr_matrix: Block Sparse Row format 

153 4. lil_matrix: List of Lists format 

154 5. dok_matrix: Dictionary of Keys format 

155 6. coo_matrix: COOrdinate format (aka IJV, triplet format) 

156 7. dia_matrix: DIAgonal format 

157 

158To construct a matrix efficiently, use either dok_matrix or lil_matrix. 

159The lil_matrix class supports basic slicing and fancy indexing with a 

160similar syntax to NumPy arrays. As illustrated below, the COO format 

161may also be used to efficiently construct matrices. Despite their 

162similarity to NumPy arrays, it is **strongly discouraged** to use NumPy 

163functions directly on these matrices because NumPy may not properly convert 

164them for computations, leading to unexpected (and incorrect) results. If you 

165do want to apply a NumPy function to these matrices, first check if SciPy has 

166its own implementation for the given sparse matrix class, or **convert the 

167sparse matrix to a NumPy array** (e.g., using the `toarray()` method of the 

168class) first before applying the method. 

169 

170To perform manipulations such as multiplication or inversion, first 

171convert the matrix to either CSC or CSR format. The lil_matrix format is 

172row-based, so conversion to CSR is efficient, whereas conversion to CSC 

173is less so. 

174 

175All conversions among the CSR, CSC, and COO formats are efficient, 

176linear-time operations. 

177 

178Matrix vector product 

179--------------------- 

180To do a vector product between a sparse matrix and a vector simply use 

181the matrix `dot` method, as described in its docstring: 

182 

183>>> import numpy as np 

184>>> from scipy.sparse import csr_matrix 

185>>> A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) 

186>>> v = np.array([1, 0, -1]) 

187>>> A.dot(v) 

188array([ 1, -3, -1], dtype=int64) 

189 

190.. warning:: As of NumPy 1.7, `np.dot` is not aware of sparse matrices, 

191 therefore using it will result on unexpected results or errors. 

192 The corresponding dense array should be obtained first instead: 

193 

194 >>> np.dot(A.toarray(), v) 

195 array([ 1, -3, -1], dtype=int64) 

196 

197 but then all the performance advantages would be lost. 

198 

199The CSR format is specially suitable for fast matrix vector products. 

200 

201Example 1 

202--------- 

203Construct a 1000x1000 lil_matrix and add some values to it: 

204 

205>>> from scipy.sparse import lil_matrix 

206>>> from scipy.sparse.linalg import spsolve 

207>>> from numpy.linalg import solve, norm 

208>>> from numpy.random import rand 

209 

210>>> A = lil_matrix((1000, 1000)) 

211>>> A[0, :100] = rand(100) 

212>>> A[1, 100:200] = A[0, :100] 

213>>> A.setdiag(rand(1000)) 

214 

215Now convert it to CSR format and solve A x = b for x: 

216 

217>>> A = A.tocsr() 

218>>> b = rand(1000) 

219>>> x = spsolve(A, b) 

220 

221Convert it to a dense matrix and solve, and check that the result 

222is the same: 

223 

224>>> x_ = solve(A.toarray(), b) 

225 

226Now we can compute norm of the error with: 

227 

228>>> err = norm(x-x_) 

229>>> err < 1e-10 

230True 

231 

232It should be small :) 

233 

234 

235Example 2 

236--------- 

237 

238Construct a matrix in COO format: 

239 

240>>> from scipy import sparse 

241>>> from numpy import array 

242>>> I = array([0,3,1,0]) 

243>>> J = array([0,3,1,2]) 

244>>> V = array([4,5,7,9]) 

245>>> A = sparse.coo_matrix((V,(I,J)),shape=(4,4)) 

246 

247Notice that the indices do not need to be sorted. 

248 

249Duplicate (i,j) entries are summed when converting to CSR or CSC. 

250 

251>>> I = array([0,0,1,3,1,0,0]) 

252>>> J = array([0,2,1,3,1,0,0]) 

253>>> V = array([1,1,1,1,1,1,1]) 

254>>> B = sparse.coo_matrix((V,(I,J)),shape=(4,4)).tocsr() 

255 

256This is useful for constructing finite-element stiffness and mass matrices. 

257 

258Further details 

259--------------- 

260 

261CSR column indices are not necessarily sorted. Likewise for CSC row 

262indices. Use the .sorted_indices() and .sort_indices() methods when 

263sorted indices are required (e.g., when passing data to other libraries). 

264 

265""" 

266 

267# Original code by Travis Oliphant. 

268# Modified and extended by Ed Schofield, Robert Cimrman, 

269# Nathan Bell, and Jake Vanderplas. 

270 

271import warnings as _warnings 

272 

273from ._base import * 

274from ._csr import * 

275from ._csc import * 

276from ._lil import * 

277from ._dok import * 

278from ._coo import * 

279from ._dia import * 

280from ._bsr import * 

281from ._construct import * 

282from ._extract import * 

283from ._matrix import spmatrix 

284from ._matrix_io import * 

285 

286# For backward compatibility with v0.19. 

287from . import csgraph 

288 

289# Deprecated namespaces, to be removed in v2.0.0 

290from . import ( 

291 base, bsr, compressed, construct, coo, csc, csr, data, dia, dok, extract, 

292 lil, sparsetools, sputils 

293) 

294 

295__all__ = [s for s in dir() if not s.startswith('_')] 

296 

297# Filter PendingDeprecationWarning for np.matrix introduced with numpy 1.15 

298_warnings.filterwarnings('ignore', message='the matrix subclass is not the recommended way') 

299 

300from scipy._lib._testutils import PytestTester 

301test = PytestTester(__name__) 

302del PytestTester