Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

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

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

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

5 

6.. currentmodule:: scipy.sparse 

7 

8SciPy 2-D sparse matrix package for numeric data. 

9 

10Contents 

11======== 

12 

13Sparse matrix classes 

14--------------------- 

15 

16.. autosummary:: 

17 :toctree: generated/ 

18 

19 bsr_matrix - Block Sparse Row matrix 

20 coo_matrix - A sparse matrix in COOrdinate format 

21 csc_matrix - Compressed Sparse Column matrix 

22 csr_matrix - Compressed Sparse Row matrix 

23 dia_matrix - Sparse matrix with DIAgonal storage 

24 dok_matrix - Dictionary Of Keys based sparse matrix 

25 lil_matrix - Row-based list of lists sparse matrix 

26 spmatrix - Sparse matrix base class 

27 

28Functions 

29--------- 

30 

31Building sparse matrices: 

32 

33.. autosummary:: 

34 :toctree: generated/ 

35 

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

37 identity - Identity matrix in sparse format 

38 kron - kronecker product of two sparse matrices 

39 kronsum - kronecker sum of sparse matrices 

40 diags - Return a sparse matrix from diagonals 

41 spdiags - Return a sparse matrix from diagonals 

42 block_diag - Build a block diagonal sparse matrix 

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

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

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

46 hstack - Stack sparse matrices horizontally (column wise) 

47 vstack - Stack sparse matrices vertically (row wise) 

48 rand - Random values in a given shape 

49 random - Random values in a given shape 

50 

51Save and load sparse matrices: 

52 

53.. autosummary:: 

54 :toctree: generated/ 

55 

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

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

58 

59Sparse matrix tools: 

60 

61.. autosummary:: 

62 :toctree: generated/ 

63 

64 find 

65 

66Identifying sparse matrices: 

67 

68.. autosummary:: 

69 :toctree: generated/ 

70 

71 issparse 

72 isspmatrix 

73 isspmatrix_csc 

74 isspmatrix_csr 

75 isspmatrix_bsr 

76 isspmatrix_lil 

77 isspmatrix_dok 

78 isspmatrix_coo 

79 isspmatrix_dia 

80 

81Submodules 

82---------- 

83 

84.. autosummary:: 

85 

86 csgraph - Compressed sparse graph routines 

87 linalg - sparse linear algebra routines 

88 

89Exceptions 

90---------- 

91 

92.. autosummary:: 

93 :toctree: generated/ 

94 

95 SparseEfficiencyWarning 

96 SparseWarning 

97 

98 

99Usage information 

100================= 

101 

102There are seven available sparse matrix types: 

103 

104 1. csc_matrix: Compressed Sparse Column format 

105 2. csr_matrix: Compressed Sparse Row format 

106 3. bsr_matrix: Block Sparse Row format 

107 4. lil_matrix: List of Lists format 

108 5. dok_matrix: Dictionary of Keys format 

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

110 7. dia_matrix: DIAgonal format 

111 

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

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

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

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

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

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

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

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

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

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

122class) first before applying the method. 

123 

124To perform manipulations such as multiplication or inversion, first 

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

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

127is less so. 

128 

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

130linear-time operations. 

131 

132Matrix vector product 

133--------------------- 

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

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

136 

137>>> import numpy as np 

138>>> from scipy.sparse import csr_matrix 

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

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

141>>> A.dot(v) 

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

143 

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

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

146 The corresponding dense array should be obtained first instead: 

147 

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

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

150 

151 but then all the performance advantages would be lost. 

152 

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

154 

155Example 1 

156--------- 

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

158 

159>>> from scipy.sparse import lil_matrix 

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

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

162>>> from numpy.random import rand 

163 

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

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

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

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

168 

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

170 

171>>> A = A.tocsr() 

172>>> b = rand(1000) 

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

174 

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

176is the same: 

177 

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

179 

180Now we can compute norm of the error with: 

181 

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

183>>> err < 1e-10 

184True 

185 

186It should be small :) 

187 

188 

189Example 2 

190--------- 

191 

192Construct a matrix in COO format: 

193 

194>>> from scipy import sparse 

195>>> from numpy import array 

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

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

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

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

200 

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

202 

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

204 

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

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

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

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

209 

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

211 

212Further details 

213--------------- 

214 

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

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

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

218 

219""" 

220 

221# Original code by Travis Oliphant. 

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

223# Nathan Bell, and Jake Vanderplas. 

224 

225import warnings as _warnings 

226 

227from .base import * 

228from .csr import * 

229from .csc import * 

230from .lil import * 

231from .dok import * 

232from .coo import * 

233from .dia import * 

234from .bsr import * 

235from .construct import * 

236from .extract import * 

237from ._matrix_io import * 

238 

239# For backward compatibility with v0.19. 

240from . import csgraph 

241 

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

243 

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

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

246 

247from scipy._lib._testutils import PytestTester 

248test = PytestTester(__name__) 

249del PytestTester