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
« prev ^ index » next coverage.py v7.4.4, created at 2025-06-14 15:25 +0200
1"""
2=====================================
3Sparse matrices (:mod:`scipy.sparse`)
4=====================================
6.. currentmodule:: scipy.sparse
8.. toctree::
9 :hidden:
11 sparse.csgraph
12 sparse.linalg
14SciPy 2-D sparse array package for numeric data.
16.. note::
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.
23 When using the array interface, please note that:
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.
36 The construction utilities (`eye`, `kron`, `random`, `diags`, etc.)
37 have not yet been ported, but their results can be wrapped into arrays::
39 A = csr_array(eye(3))
41Contents
42========
44Sparse array classes
45--------------------
47.. autosummary::
48 :toctree: generated/
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
59Sparse matrix classes
60---------------------
62.. autosummary::
63 :toctree: generated/
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
74Functions
75---------
77Building sparse matrices:
79.. autosummary::
80 :toctree: generated/
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
97Save and load sparse matrices:
99.. autosummary::
100 :toctree: generated/
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.
105Sparse matrix tools:
107.. autosummary::
108 :toctree: generated/
110 find
112Identifying sparse matrices:
114.. autosummary::
115 :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
127Submodules
128----------
130.. autosummary::
132 csgraph - Compressed sparse graph routines
133 linalg - sparse linear algebra routines
135Exceptions
136----------
138.. autosummary::
139 :toctree: generated/
141 SparseEfficiencyWarning
142 SparseWarning
145Usage information
146=================
148There are seven available sparse matrix types:
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
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.
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.
175All conversions among the CSR, CSC, and COO formats are efficient,
176linear-time operations.
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:
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)
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:
194 >>> np.dot(A.toarray(), v)
195 array([ 1, -3, -1], dtype=int64)
197 but then all the performance advantages would be lost.
199The CSR format is specially suitable for fast matrix vector products.
201Example 1
202---------
203Construct a 1000x1000 lil_matrix and add some values to it:
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
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))
215Now convert it to CSR format and solve A x = b for x:
217>>> A = A.tocsr()
218>>> b = rand(1000)
219>>> x = spsolve(A, b)
221Convert it to a dense matrix and solve, and check that the result
222is the same:
224>>> x_ = solve(A.toarray(), b)
226Now we can compute norm of the error with:
228>>> err = norm(x-x_)
229>>> err < 1e-10
230True
232It should be small :)
235Example 2
236---------
238Construct a matrix in COO format:
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))
247Notice that the indices do not need to be sorted.
249Duplicate (i,j) entries are summed when converting to CSR or CSC.
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()
256This is useful for constructing finite-element stiffness and mass matrices.
258Further details
259---------------
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).
265"""
267# Original code by Travis Oliphant.
268# Modified and extended by Ed Schofield, Robert Cimrman,
269# Nathan Bell, and Jake Vanderplas.
271import warnings as _warnings
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 *
286# For backward compatibility with v0.19.
287from . import csgraph
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)
295__all__ = [s for s in dir() if not s.startswith('_')]
297# Filter PendingDeprecationWarning for np.matrix introduced with numpy 1.15
298_warnings.filterwarnings('ignore', message='the matrix subclass is not the recommended way')
300from scipy._lib._testutils import PytestTester
301test = PytestTester(__name__)
302del PytestTester