__init__.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. """
  2. ===================================
  3. Sparse arrays (:mod:`scipy.sparse`)
  4. ===================================
  5. .. currentmodule:: scipy.sparse
  6. .. toctree::
  7. :hidden:
  8. sparse.csgraph
  9. sparse.linalg
  10. sparse.migration_to_sparray
  11. SciPy 2-D sparse array package for numeric data.
  12. .. note::
  13. This package is switching to an array interface, compatible with
  14. NumPy arrays, from the older matrix interface. We recommend that
  15. you use the array objects (`bsr_array`, `coo_array`, etc.) for
  16. all new work.
  17. When using the array interface, please note that:
  18. - ``x * y`` no longer performs matrix multiplication, but
  19. element-wise multiplication (just like with NumPy arrays). To
  20. make code work with both arrays and matrices, use ``x @ y`` for
  21. matrix multiplication.
  22. - Operations such as ``sum``, that used to produce dense matrices, now
  23. produce arrays, whose multiplication behavior differs similarly.
  24. - Sparse arrays use array style *slicing* operations, returning scalars,
  25. 1D, or 2D sparse arrays. If you need 2D results, use an appropriate index.
  26. E.g. ``A[:, i, None]`` or ``A[:, [i]]``.
  27. - All index arrays for a given sparse array should be of same dtype.
  28. For example, for CSR format, ``indices`` and ``indptr`` should have
  29. the same dtype. For COO, each array in `coords` should have same dtype.
  30. The construction utilities (`eye`, `kron`, `random`, `diags`, etc.)
  31. have appropriate replacements (see :ref:`sparse-construction-functions`).
  32. For more information see
  33. :ref:`Migration from spmatrix to sparray <migration_to_sparray>`.
  34. Submodules
  35. ==========
  36. .. autosummary::
  37. csgraph - Compressed sparse graph routines
  38. linalg - Sparse linear algebra routines
  39. Sparse array classes
  40. ====================
  41. .. autosummary::
  42. :toctree: generated/
  43. bsr_array - Block Sparse Row array
  44. coo_array - A sparse array in COOrdinate format
  45. csc_array - Compressed Sparse Column array
  46. csr_array - Compressed Sparse Row array
  47. dia_array - Sparse array with DIAgonal storage
  48. dok_array - Dictionary Of Keys based sparse array
  49. lil_array - Row-based list of lists sparse array
  50. sparray - Sparse array base class
  51. .. _sparse-construction-functions:
  52. Building sparse arrays
  53. ----------------------
  54. .. autosummary::
  55. :toctree: generated/
  56. diags_array - Return a sparse array from diagonals
  57. eye_array - Sparse MxN array whose k-th diagonal is all ones
  58. random_array - Random values in a given shape array
  59. block_array - Build a sparse array from sub-blocks
  60. .. _combining-arrays:
  61. Combining arrays
  62. ----------------
  63. .. autosummary::
  64. :toctree: generated/
  65. kron - Kronecker product of two sparse arrays
  66. kronsum - Kronecker sum of sparse arrays
  67. block_diag - Build a block diagonal sparse array
  68. tril - Lower triangular portion of a sparse array
  69. triu - Upper triangular portion of a sparse array
  70. hstack - Stack sparse arrays horizontally (column wise)
  71. vstack - Stack sparse arrays vertically (row wise)
  72. swapaxes - swap two axes of a sparse array
  73. expand_dims - add a new (trivial) axis to a sparse array
  74. permute_dims - reorder the axes of a sparse array
  75. Sparse tools
  76. ------------
  77. .. autosummary::
  78. :toctree: generated/
  79. save_npz - Save a sparse array to a file using ``.npz`` format.
  80. load_npz - Load a sparse array from a file using ``.npz`` format.
  81. find - Return the indices and values of the nonzero elements
  82. get_index_dtype - determine a good dtype for index arrays.
  83. safely_cast_index_arrays - cast index array dtype or raise if shape too big
  84. Identifying sparse arrays
  85. -------------------------
  86. .. autosummary::
  87. :toctree: generated/
  88. issparse - Check if the argument is a sparse object (array or matrix).
  89. Sparse matrix classes
  90. =====================
  91. .. autosummary::
  92. :toctree: generated/
  93. bsr_matrix - Block Sparse Row matrix
  94. coo_matrix - A sparse matrix in COOrdinate format
  95. csc_matrix - Compressed Sparse Column matrix
  96. csr_matrix - Compressed Sparse Row matrix
  97. dia_matrix - Sparse matrix with DIAgonal storage
  98. dok_matrix - Dictionary Of Keys based sparse matrix
  99. lil_matrix - Row-based list of lists sparse matrix
  100. spmatrix - Sparse matrix base class
  101. Building sparse matrices
  102. ------------------------
  103. .. autosummary::
  104. :toctree: generated/
  105. eye - Sparse MxN matrix whose k-th diagonal is all ones
  106. identity - Identity matrix in sparse matrix format
  107. diags - Return a sparse matrix from diagonals
  108. spdiags - Return a sparse matrix from diagonals
  109. bmat - Build a sparse matrix from sparse sub-blocks
  110. random - Random values in a given shape matrix
  111. rand - Random values in a given shape matrix (old interface)
  112. **Combining matrices use the same functions as for** :ref:`combining-arrays`.
  113. Identifying sparse matrices
  114. ---------------------------
  115. .. autosummary::
  116. :toctree: generated/
  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. Warnings
  127. ========
  128. .. autosummary::
  129. :toctree: generated/
  130. SparseEfficiencyWarning
  131. SparseWarning
  132. Usage information
  133. =================
  134. There are seven available sparse array types:
  135. 1. csc_array: Compressed Sparse Column format
  136. 2. csr_array: Compressed Sparse Row format
  137. 3. bsr_array: Block Sparse Row format
  138. 4. lil_array: List of Lists format
  139. 5. dok_array: Dictionary of Keys format
  140. 6. coo_array: COOrdinate format (aka IJV, triplet format)
  141. 7. dia_array: DIAgonal format
  142. To construct an array efficiently, use any of `coo_array`,
  143. `dok_array` or `lil_array`. `dok_array` and `lil_array`
  144. support basic slicing and fancy indexing with a similar syntax
  145. to NumPy arrays. The COO format does not support indexing (yet)
  146. but can also be used to efficiently construct arrays using coord
  147. and value info.
  148. Despite their similarity to NumPy arrays, it is **strongly discouraged**
  149. to use NumPy functions directly on these arrays because NumPy typically
  150. treats them as generic Python objects rather than arrays, leading to
  151. unexpected (and incorrect) results. If you do want to apply a NumPy
  152. function to these arrays, first check if SciPy has its own implementation
  153. for the given sparse array class, or **convert the sparse array to
  154. a NumPy array** (e.g., using the `toarray` method of the class)
  155. before applying the method.
  156. All conversions among the CSR, CSC, and COO formats are efficient,
  157. linear-time operations.
  158. To perform manipulations such as multiplication or inversion, first
  159. convert the array to either CSC or CSR format. The `lil_array`
  160. format is row-based, so conversion to CSR is efficient, whereas
  161. conversion to CSC is less so.
  162. Matrix vector product
  163. ---------------------
  164. To do a vector product between a 2D sparse array and a vector use
  165. the matmul operator (i.e., ``@``) which performs a dot product (like the
  166. ``dot`` method):
  167. >>> import numpy as np
  168. >>> from scipy.sparse import csr_array
  169. >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
  170. >>> v = np.array([1, 0, -1])
  171. >>> A @ v
  172. array([ 1, -3, -1], dtype=int64)
  173. The CSR format is especially suitable for fast matrix vector products.
  174. Example 1
  175. ---------
  176. Construct a 1000x1000 `lil_array` and add some values to it:
  177. >>> from scipy.sparse import lil_array
  178. >>> from scipy.sparse.linalg import spsolve
  179. >>> from numpy.linalg import solve, norm
  180. >>> from numpy.random import rand
  181. >>> A = lil_array((1000, 1000))
  182. >>> A[0, :100] = rand(100)
  183. >>> A.setdiag(rand(1000))
  184. Now convert it to CSR format and solve A x = b for x:
  185. >>> A = A.tocsr()
  186. >>> b = rand(1000)
  187. >>> x = spsolve(A, b)
  188. Convert it to a dense array and solve, and check that the result
  189. is the same:
  190. >>> x_ = solve(A.toarray(), b)
  191. Now we can compute norm of the error with:
  192. >>> err = norm(x-x_)
  193. >>> err < 1e-9
  194. True
  195. It should be small :)
  196. Example 2
  197. ---------
  198. Construct an array in COO format:
  199. >>> from scipy import sparse
  200. >>> from numpy import array
  201. >>> I = array([0,3,1,0])
  202. >>> J = array([0,3,1,2])
  203. >>> V = array([4,5,7,9])
  204. >>> A = sparse.coo_array((V,(I,J)),shape=(4,4))
  205. Notice that the indices do not need to be sorted.
  206. Duplicate (i,j) entries are summed when converting to CSR or CSC.
  207. >>> I = array([0,0,1,3,1,0,0])
  208. >>> J = array([0,2,1,3,1,0,0])
  209. >>> V = array([1,1,1,1,1,1,1])
  210. >>> B = sparse.coo_array((V,(I,J)),shape=(4,4)).tocsr()
  211. This is useful for constructing finite-element stiffness and mass matrices.
  212. Further details
  213. ---------------
  214. CSR column indices are not necessarily sorted. Likewise for CSC row
  215. indices. Use the ``.sorted_indices()`` and ``.sort_indices()`` methods when
  216. sorted indices are required (e.g., when passing data to other libraries).
  217. """
  218. # Original code by Travis Oliphant.
  219. # Modified and extended by Ed Schofield, Robert Cimrman,
  220. # Nathan Bell, and Jake Vanderplas.
  221. import warnings as _warnings
  222. import importlib as _importlib
  223. from ._base import *
  224. from ._csr import *
  225. from ._csc import *
  226. from ._lil import *
  227. from ._dok import *
  228. from ._coo import *
  229. from ._dia import *
  230. from ._bsr import *
  231. from ._construct import *
  232. from ._extract import *
  233. from ._matrix import spmatrix
  234. from ._matrix_io import *
  235. from ._sputils import get_index_dtype, safely_cast_index_arrays
  236. # Deprecated namespaces, to be removed in v2.0.0
  237. from . import (
  238. base, bsr, compressed, construct, coo, csc, csr, data, dia, dok, extract,
  239. lil, sparsetools, sputils
  240. )
  241. _submodules = ["csgraph", "linalg"]
  242. __all__ = [s for s in dir() if not s.startswith('_')] + _submodules
  243. # Filter PendingDeprecationWarning for np.matrix introduced with numpy 1.15
  244. msg = 'the matrix subclass is not the recommended way'
  245. _warnings.filterwarnings('ignore', message=msg)
  246. def __dir__():
  247. return __all__
  248. def __getattr__(name):
  249. if name in _submodules:
  250. return _importlib.import_module(f'scipy.sparse.{name}')
  251. else:
  252. try:
  253. return globals()[name]
  254. except KeyError:
  255. raise AttributeError(
  256. f"Module 'scipy.sparse' has no attribute '{name}'"
  257. )
  258. from scipy._lib._testutils import PytestTester
  259. test = PytestTester(__name__)
  260. del PytestTester