__init__.py 6.8 KB

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