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