__init__.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. """
  2. =====================================
  3. Sparse matrices (:mod:`scipy.sparse`)
  4. =====================================
  5. .. currentmodule:: scipy.sparse
  6. SciPy 2-D sparse array package for numeric data.
  7. .. note::
  8. This package is switching to an array interface, compatible with
  9. NumPy arrays, from the older matrix interface. We recommend that
  10. you use the array objects (`bsr_array`, `coo_array`, etc.) for
  11. all new work.
  12. When using the array interface, please note that:
  13. - ``x * y`` no longer performs matrix multiplication, but
  14. element-wise multiplication (just like with NumPy arrays). To
  15. make code work with both arrays and matrices, use ``x @ y`` for
  16. matrix multiplication.
  17. - Operations such as `sum`, that used to produce dense matrices, now
  18. produce arrays, whose multiplication behavior differs similarly.
  19. - Sparse arrays currently must be two-dimensional. This also means
  20. that all *slicing* operations on these objects must produce
  21. two-dimensional results, or they will result in an error. This
  22. will be addressed in a future version.
  23. The construction utilities (`eye`, `kron`, `random`, `diags`, etc.)
  24. have not yet been ported, but their results can be wrapped into arrays::
  25. A = csr_array(eye(3))
  26. Contents
  27. ========
  28. Sparse array classes
  29. --------------------
  30. .. autosummary::
  31. :toctree: generated/
  32. bsr_array - Block Sparse Row array
  33. coo_array - A sparse array in COOrdinate format
  34. csc_array - Compressed Sparse Column array
  35. csr_array - Compressed Sparse Row array
  36. dia_array - Sparse array with DIAgonal storage
  37. dok_array - Dictionary Of Keys based sparse array
  38. lil_array - Row-based list of lists sparse array
  39. Sparse matrix classes
  40. ---------------------
  41. .. autosummary::
  42. :toctree: generated/
  43. bsr_matrix - Block Sparse Row matrix
  44. coo_matrix - A sparse matrix in COOrdinate format
  45. csc_matrix - Compressed Sparse Column matrix
  46. csr_matrix - Compressed Sparse Row matrix
  47. dia_matrix - Sparse matrix with DIAgonal storage
  48. dok_matrix - Dictionary Of Keys based sparse matrix
  49. lil_matrix - Row-based list of lists sparse matrix
  50. spmatrix - Sparse matrix base class
  51. Functions
  52. ---------
  53. Building sparse matrices:
  54. .. autosummary::
  55. :toctree: generated/
  56. eye - Sparse MxN matrix whose k-th diagonal is all ones
  57. identity - Identity matrix in sparse format
  58. kron - kronecker product of two sparse matrices
  59. kronsum - kronecker sum of sparse matrices
  60. diags - Return a sparse matrix from diagonals
  61. spdiags - Return a sparse matrix from diagonals
  62. block_diag - Build a block diagonal sparse matrix
  63. tril - Lower triangular portion of a matrix in sparse format
  64. triu - Upper triangular portion of a matrix in sparse format
  65. bmat - Build a sparse matrix from sparse sub-blocks
  66. hstack - Stack sparse matrices horizontally (column wise)
  67. vstack - Stack sparse matrices vertically (row wise)
  68. rand - Random values in a given shape
  69. random - Random values in a given shape
  70. Save and load sparse matrices:
  71. .. autosummary::
  72. :toctree: generated/
  73. save_npz - Save a sparse matrix to a file using ``.npz`` format.
  74. load_npz - Load a sparse matrix from a file using ``.npz`` format.
  75. Sparse matrix tools:
  76. .. autosummary::
  77. :toctree: generated/
  78. find
  79. Identifying sparse matrices:
  80. .. autosummary::
  81. :toctree: generated/
  82. issparse
  83. isspmatrix
  84. isspmatrix_csc
  85. isspmatrix_csr
  86. isspmatrix_bsr
  87. isspmatrix_lil
  88. isspmatrix_dok
  89. isspmatrix_coo
  90. isspmatrix_dia
  91. Submodules
  92. ----------
  93. .. autosummary::
  94. csgraph - Compressed sparse graph routines
  95. linalg - sparse linear algebra routines
  96. Exceptions
  97. ----------
  98. .. autosummary::
  99. :toctree: generated/
  100. SparseEfficiencyWarning
  101. SparseWarning
  102. Usage information
  103. =================
  104. There are seven available sparse matrix types:
  105. 1. csc_matrix: Compressed Sparse Column format
  106. 2. csr_matrix: Compressed Sparse Row format
  107. 3. bsr_matrix: Block Sparse Row format
  108. 4. lil_matrix: List of Lists format
  109. 5. dok_matrix: Dictionary of Keys format
  110. 6. coo_matrix: COOrdinate format (aka IJV, triplet format)
  111. 7. dia_matrix: DIAgonal format
  112. To construct a matrix efficiently, use either dok_matrix or lil_matrix.
  113. The lil_matrix class supports basic slicing and fancy indexing with a
  114. similar syntax to NumPy arrays. As illustrated below, the COO format
  115. may also be used to efficiently construct matrices. Despite their
  116. similarity to NumPy arrays, it is **strongly discouraged** to use NumPy
  117. functions directly on these matrices because NumPy may not properly convert
  118. them for computations, leading to unexpected (and incorrect) results. If you
  119. do want to apply a NumPy function to these matrices, first check if SciPy has
  120. its own implementation for the given sparse matrix class, or **convert the
  121. sparse matrix to a NumPy array** (e.g., using the `toarray()` method of the
  122. class) first before applying the method.
  123. To perform manipulations such as multiplication or inversion, first
  124. convert the matrix to either CSC or CSR format. The lil_matrix format is
  125. row-based, so conversion to CSR is efficient, whereas conversion to CSC
  126. is less so.
  127. All conversions among the CSR, CSC, and COO formats are efficient,
  128. linear-time operations.
  129. Matrix vector product
  130. ---------------------
  131. To do a vector product between a sparse matrix and a vector simply use
  132. the matrix `dot` method, as described in its docstring:
  133. >>> import numpy as np
  134. >>> from scipy.sparse import csr_matrix
  135. >>> A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
  136. >>> v = np.array([1, 0, -1])
  137. >>> A.dot(v)
  138. array([ 1, -3, -1], dtype=int64)
  139. .. warning:: As of NumPy 1.7, `np.dot` is not aware of sparse matrices,
  140. therefore using it will result on unexpected results or errors.
  141. The corresponding dense array should be obtained first instead:
  142. >>> np.dot(A.toarray(), v)
  143. array([ 1, -3, -1], dtype=int64)
  144. but then all the performance advantages would be lost.
  145. The CSR format is specially suitable for fast matrix vector products.
  146. Example 1
  147. ---------
  148. Construct a 1000x1000 lil_matrix and add some values to it:
  149. >>> from scipy.sparse import lil_matrix
  150. >>> from scipy.sparse.linalg import spsolve
  151. >>> from numpy.linalg import solve, norm
  152. >>> from numpy.random import rand
  153. >>> A = lil_matrix((1000, 1000))
  154. >>> A[0, :100] = rand(100)
  155. >>> A[1, 100:200] = A[0, :100]
  156. >>> A.setdiag(rand(1000))
  157. Now convert it to CSR format and solve A x = b for x:
  158. >>> A = A.tocsr()
  159. >>> b = rand(1000)
  160. >>> x = spsolve(A, b)
  161. Convert it to a dense matrix and solve, and check that the result
  162. is the same:
  163. >>> x_ = solve(A.toarray(), b)
  164. Now we can compute norm of the error with:
  165. >>> err = norm(x-x_)
  166. >>> err < 1e-10
  167. True
  168. It should be small :)
  169. Example 2
  170. ---------
  171. Construct a matrix in COO format:
  172. >>> from scipy import sparse
  173. >>> from numpy import array
  174. >>> I = array([0,3,1,0])
  175. >>> J = array([0,3,1,2])
  176. >>> V = array([4,5,7,9])
  177. >>> A = sparse.coo_matrix((V,(I,J)),shape=(4,4))
  178. Notice that the indices do not need to be sorted.
  179. Duplicate (i,j) entries are summed when converting to CSR or CSC.
  180. >>> I = array([0,0,1,3,1,0,0])
  181. >>> J = array([0,2,1,3,1,0,0])
  182. >>> V = array([1,1,1,1,1,1,1])
  183. >>> B = sparse.coo_matrix((V,(I,J)),shape=(4,4)).tocsr()
  184. This is useful for constructing finite-element stiffness and mass matrices.
  185. Further details
  186. ---------------
  187. CSR column indices are not necessarily sorted. Likewise for CSC row
  188. indices. Use the .sorted_indices() and .sort_indices() methods when
  189. sorted indices are required (e.g., when passing data to other libraries).
  190. """
  191. # Original code by Travis Oliphant.
  192. # Modified and extended by Ed Schofield, Robert Cimrman,
  193. # Nathan Bell, and Jake Vanderplas.
  194. import warnings as _warnings
  195. from ._base import *
  196. from ._csr import *
  197. from ._csc import *
  198. from ._lil import *
  199. from ._dok import *
  200. from ._coo import *
  201. from ._dia import *
  202. from ._bsr import *
  203. from ._construct import *
  204. from ._extract import *
  205. from ._matrix_io import *
  206. from ._arrays import (
  207. csr_array, csc_array, lil_array, dok_array, coo_array, dia_array, bsr_array
  208. )
  209. # For backward compatibility with v0.19.
  210. from . import csgraph
  211. # Deprecated namespaces, to be removed in v2.0.0
  212. from . import (
  213. base, bsr, compressed, construct, coo, csc, csr, data, dia, dok, extract,
  214. lil, sparsetools, sputils
  215. )
  216. __all__ = [s for s in dir() if not s.startswith('_')]
  217. # Filter PendingDeprecationWarning for np.matrix introduced with numpy 1.15
  218. _warnings.filterwarnings('ignore', message='the matrix subclass is not the recommended way')
  219. from scipy._lib._testutils import PytestTester
  220. test = PytestTester(__name__)
  221. del PytestTester