Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- parrot/lib/python3.10/site-packages/scipy/sparse/__init__.py +323 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_base.py +1390 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_bsr.py +856 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_compressed.py +1463 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_coo.py +866 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_csr.py +551 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_data.py +515 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_dok.py +684 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_extract.py +178 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_index.py +392 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_lil.py +612 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_matrix.py +113 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_matrix_io.py +167 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_spfuncs.py +76 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/_sputils.py +451 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/base.py +33 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/bsr.py +36 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/compressed.py +43 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/construct.py +44 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/coo.py +37 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/csc.py +25 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/csr.py +27 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/data.py +23 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/dia.py +29 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/dok.py +32 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/lil.py +22 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/linalg/__init__.py +146 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/linalg/_expm_multiply.py +810 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/linalg/_matfuncs.py +940 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/linalg/_special_sparse_arrays.py +948 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/linalg/matfuncs.py +18 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/sparsetools.py +17 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/spfuncs.py +17 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/sputils.py +17 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/__init__.py +0 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_arithmetic1d.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_coo.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_csc.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_minmax1d.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_spfuncs.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_sputils.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_arithmetic1d.py +338 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_base.py +0 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_construct.py +836 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_coo.py +274 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_csc.py +98 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_dok.py +210 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_extract.py +51 -0
- parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_matrix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|
|
|
| 1 |
+
"""
|
| 2 |
+
=====================================
|
| 3 |
+
Sparse matrices (:mod:`scipy.sparse`)
|
| 4 |
+
=====================================
|
| 5 |
+
|
| 6 |
+
.. currentmodule:: scipy.sparse
|
| 7 |
+
|
| 8 |
+
.. toctree::
|
| 9 |
+
:hidden:
|
| 10 |
+
|
| 11 |
+
sparse.csgraph
|
| 12 |
+
sparse.linalg
|
| 13 |
+
|
| 14 |
+
SciPy 2-D sparse array package for numeric data.
|
| 15 |
+
|
| 16 |
+
.. note::
|
| 17 |
+
|
| 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.
|
| 22 |
+
|
| 23 |
+
When using the array interface, please note that:
|
| 24 |
+
|
| 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.
|
| 35 |
+
|
| 36 |
+
The construction utilities (`eye`, `kron`, `random`, `diags`, etc.)
|
| 37 |
+
have not yet been ported, but their results can be wrapped into arrays::
|
| 38 |
+
|
| 39 |
+
A = csr_array(eye(3))
|
| 40 |
+
|
| 41 |
+
Contents
|
| 42 |
+
========
|
| 43 |
+
|
| 44 |
+
Sparse array classes
|
| 45 |
+
--------------------
|
| 46 |
+
|
| 47 |
+
.. autosummary::
|
| 48 |
+
:toctree: generated/
|
| 49 |
+
|
| 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
|
| 58 |
+
|
| 59 |
+
Sparse matrix classes
|
| 60 |
+
---------------------
|
| 61 |
+
|
| 62 |
+
.. autosummary::
|
| 63 |
+
:toctree: generated/
|
| 64 |
+
|
| 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
|
| 73 |
+
|
| 74 |
+
Functions
|
| 75 |
+
---------
|
| 76 |
+
|
| 77 |
+
Building sparse arrays:
|
| 78 |
+
|
| 79 |
+
.. autosummary::
|
| 80 |
+
:toctree: generated/
|
| 81 |
+
|
| 82 |
+
diags_array - Return a sparse array from diagonals
|
| 83 |
+
eye_array - Sparse MxN array whose k-th diagonal is all ones
|
| 84 |
+
random_array - Random values in a given shape array
|
| 85 |
+
block_array - Build a sparse array from sub-blocks
|
| 86 |
+
|
| 87 |
+
Building sparse matrices:
|
| 88 |
+
|
| 89 |
+
.. autosummary::
|
| 90 |
+
:toctree: generated/
|
| 91 |
+
|
| 92 |
+
eye - Sparse MxN matrix whose k-th diagonal is all ones
|
| 93 |
+
identity - Identity matrix in sparse matrix format
|
| 94 |
+
diags - Return a sparse matrix from diagonals
|
| 95 |
+
spdiags - Return a sparse matrix from diagonals
|
| 96 |
+
bmat - Build a sparse matrix from sparse sub-blocks
|
| 97 |
+
random - Random values in a given shape matrix
|
| 98 |
+
rand - Random values in a given shape matrix (old interface)
|
| 99 |
+
|
| 100 |
+
Building larger structures from smaller (array or matrix)
|
| 101 |
+
|
| 102 |
+
.. autosummary::
|
| 103 |
+
:toctree: generated/
|
| 104 |
+
|
| 105 |
+
kron - kronecker product of two sparse matrices
|
| 106 |
+
kronsum - kronecker sum of sparse matrices
|
| 107 |
+
block_diag - Build a block diagonal sparse matrix
|
| 108 |
+
tril - Lower triangular portion of a matrix in sparse format
|
| 109 |
+
triu - Upper triangular portion of a matrix in sparse format
|
| 110 |
+
hstack - Stack sparse matrices horizontally (column wise)
|
| 111 |
+
vstack - Stack sparse matrices vertically (row wise)
|
| 112 |
+
|
| 113 |
+
Save and load sparse matrices:
|
| 114 |
+
|
| 115 |
+
.. autosummary::
|
| 116 |
+
:toctree: generated/
|
| 117 |
+
|
| 118 |
+
save_npz - Save a sparse matrix/array to a file using ``.npz`` format.
|
| 119 |
+
load_npz - Load a sparse matrix/array from a file using ``.npz`` format.
|
| 120 |
+
|
| 121 |
+
Sparse tools:
|
| 122 |
+
|
| 123 |
+
.. autosummary::
|
| 124 |
+
:toctree: generated/
|
| 125 |
+
|
| 126 |
+
find
|
| 127 |
+
|
| 128 |
+
Identifying sparse arrays:
|
| 129 |
+
|
| 130 |
+
- use `isinstance(A, sp.sparse.sparray)` to check whether an array or matrix.
|
| 131 |
+
- use `A.format == 'csr'` to check the sparse format
|
| 132 |
+
|
| 133 |
+
Identifying sparse matrices:
|
| 134 |
+
|
| 135 |
+
.. autosummary::
|
| 136 |
+
:toctree: generated/
|
| 137 |
+
|
| 138 |
+
issparse
|
| 139 |
+
isspmatrix
|
| 140 |
+
isspmatrix_csc
|
| 141 |
+
isspmatrix_csr
|
| 142 |
+
isspmatrix_bsr
|
| 143 |
+
isspmatrix_lil
|
| 144 |
+
isspmatrix_dok
|
| 145 |
+
isspmatrix_coo
|
| 146 |
+
isspmatrix_dia
|
| 147 |
+
|
| 148 |
+
Submodules
|
| 149 |
+
----------
|
| 150 |
+
|
| 151 |
+
.. autosummary::
|
| 152 |
+
|
| 153 |
+
csgraph - Compressed sparse graph routines
|
| 154 |
+
linalg - sparse linear algebra routines
|
| 155 |
+
|
| 156 |
+
Exceptions
|
| 157 |
+
----------
|
| 158 |
+
|
| 159 |
+
.. autosummary::
|
| 160 |
+
:toctree: generated/
|
| 161 |
+
|
| 162 |
+
SparseEfficiencyWarning
|
| 163 |
+
SparseWarning
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
Usage information
|
| 167 |
+
=================
|
| 168 |
+
|
| 169 |
+
There are seven available sparse array types:
|
| 170 |
+
|
| 171 |
+
1. `csc_array`: Compressed Sparse Column format
|
| 172 |
+
2. `csr_array`: Compressed Sparse Row format
|
| 173 |
+
3. `bsr_array`: Block Sparse Row format
|
| 174 |
+
4. `lil_array`: List of Lists format
|
| 175 |
+
5. `dok_array`: Dictionary of Keys format
|
| 176 |
+
6. `coo_array`: COOrdinate format (aka IJV, triplet format)
|
| 177 |
+
7. `dia_array`: DIAgonal format
|
| 178 |
+
|
| 179 |
+
To construct an array efficiently, use either `dok_array` or `lil_array`.
|
| 180 |
+
The `lil_array` class supports basic slicing and fancy indexing with a
|
| 181 |
+
similar syntax to NumPy arrays. As illustrated below, the COO format
|
| 182 |
+
may also be used to efficiently construct arrays. Despite their
|
| 183 |
+
similarity to NumPy arrays, it is **strongly discouraged** to use NumPy
|
| 184 |
+
functions directly on these arrays because NumPy may not properly convert
|
| 185 |
+
them for computations, leading to unexpected (and incorrect) results. If you
|
| 186 |
+
do want to apply a NumPy function to these arrays, first check if SciPy has
|
| 187 |
+
its own implementation for the given sparse array class, or **convert the
|
| 188 |
+
sparse array to a NumPy array** (e.g., using the ``toarray`` method of the
|
| 189 |
+
class) first before applying the method.
|
| 190 |
+
|
| 191 |
+
To perform manipulations such as multiplication or inversion, first
|
| 192 |
+
convert the array to either CSC or CSR format. The `lil_array` format is
|
| 193 |
+
row-based, so conversion to CSR is efficient, whereas conversion to CSC
|
| 194 |
+
is less so.
|
| 195 |
+
|
| 196 |
+
All conversions among the CSR, CSC, and COO formats are efficient,
|
| 197 |
+
linear-time operations.
|
| 198 |
+
|
| 199 |
+
Matrix vector product
|
| 200 |
+
---------------------
|
| 201 |
+
To do a vector product between a sparse array and a vector simply use
|
| 202 |
+
the array ``dot`` method, as described in its docstring:
|
| 203 |
+
|
| 204 |
+
>>> import numpy as np
|
| 205 |
+
>>> from scipy.sparse import csr_array
|
| 206 |
+
>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
|
| 207 |
+
>>> v = np.array([1, 0, -1])
|
| 208 |
+
>>> A.dot(v)
|
| 209 |
+
array([ 1, -3, -1], dtype=int64)
|
| 210 |
+
|
| 211 |
+
.. warning:: As of NumPy 1.7, ``np.dot`` is not aware of sparse arrays,
|
| 212 |
+
therefore using it will result on unexpected results or errors.
|
| 213 |
+
The corresponding dense array should be obtained first instead:
|
| 214 |
+
|
| 215 |
+
>>> np.dot(A.toarray(), v)
|
| 216 |
+
array([ 1, -3, -1], dtype=int64)
|
| 217 |
+
|
| 218 |
+
but then all the performance advantages would be lost.
|
| 219 |
+
|
| 220 |
+
The CSR format is especially suitable for fast matrix vector products.
|
| 221 |
+
|
| 222 |
+
Example 1
|
| 223 |
+
---------
|
| 224 |
+
Construct a 1000x1000 `lil_array` and add some values to it:
|
| 225 |
+
|
| 226 |
+
>>> from scipy.sparse import lil_array
|
| 227 |
+
>>> from scipy.sparse.linalg import spsolve
|
| 228 |
+
>>> from numpy.linalg import solve, norm
|
| 229 |
+
>>> from numpy.random import rand
|
| 230 |
+
|
| 231 |
+
>>> A = lil_array((1000, 1000))
|
| 232 |
+
>>> A[0, :100] = rand(100)
|
| 233 |
+
>>> A.setdiag(rand(1000))
|
| 234 |
+
|
| 235 |
+
Now convert it to CSR format and solve A x = b for x:
|
| 236 |
+
|
| 237 |
+
>>> A = A.tocsr()
|
| 238 |
+
>>> b = rand(1000)
|
| 239 |
+
>>> x = spsolve(A, b)
|
| 240 |
+
|
| 241 |
+
Convert it to a dense array and solve, and check that the result
|
| 242 |
+
is the same:
|
| 243 |
+
|
| 244 |
+
>>> x_ = solve(A.toarray(), b)
|
| 245 |
+
|
| 246 |
+
Now we can compute norm of the error with:
|
| 247 |
+
|
| 248 |
+
>>> err = norm(x-x_)
|
| 249 |
+
>>> err < 1e-10
|
| 250 |
+
True
|
| 251 |
+
|
| 252 |
+
It should be small :)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
Example 2
|
| 256 |
+
---------
|
| 257 |
+
|
| 258 |
+
Construct an array in COO format:
|
| 259 |
+
|
| 260 |
+
>>> from scipy import sparse
|
| 261 |
+
>>> from numpy import array
|
| 262 |
+
>>> I = array([0,3,1,0])
|
| 263 |
+
>>> J = array([0,3,1,2])
|
| 264 |
+
>>> V = array([4,5,7,9])
|
| 265 |
+
>>> A = sparse.coo_array((V,(I,J)),shape=(4,4))
|
| 266 |
+
|
| 267 |
+
Notice that the indices do not need to be sorted.
|
| 268 |
+
|
| 269 |
+
Duplicate (i,j) entries are summed when converting to CSR or CSC.
|
| 270 |
+
|
| 271 |
+
>>> I = array([0,0,1,3,1,0,0])
|
| 272 |
+
>>> J = array([0,2,1,3,1,0,0])
|
| 273 |
+
>>> V = array([1,1,1,1,1,1,1])
|
| 274 |
+
>>> B = sparse.coo_array((V,(I,J)),shape=(4,4)).tocsr()
|
| 275 |
+
|
| 276 |
+
This is useful for constructing finite-element stiffness and mass matrices.
|
| 277 |
+
|
| 278 |
+
Further details
|
| 279 |
+
---------------
|
| 280 |
+
|
| 281 |
+
CSR column indices are not necessarily sorted. Likewise for CSC row
|
| 282 |
+
indices. Use the ``.sorted_indices()`` and ``.sort_indices()`` methods when
|
| 283 |
+
sorted indices are required (e.g., when passing data to other libraries).
|
| 284 |
+
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
# Original code by Travis Oliphant.
|
| 288 |
+
# Modified and extended by Ed Schofield, Robert Cimrman,
|
| 289 |
+
# Nathan Bell, and Jake Vanderplas.
|
| 290 |
+
|
| 291 |
+
import warnings as _warnings
|
| 292 |
+
|
| 293 |
+
from ._base import *
|
| 294 |
+
from ._csr import *
|
| 295 |
+
from ._csc import *
|
| 296 |
+
from ._lil import *
|
| 297 |
+
from ._dok import *
|
| 298 |
+
from ._coo import *
|
| 299 |
+
from ._dia import *
|
| 300 |
+
from ._bsr import *
|
| 301 |
+
from ._construct import *
|
| 302 |
+
from ._extract import *
|
| 303 |
+
from ._matrix import spmatrix
|
| 304 |
+
from ._matrix_io import *
|
| 305 |
+
|
| 306 |
+
# For backward compatibility with v0.19.
|
| 307 |
+
from . import csgraph
|
| 308 |
+
|
| 309 |
+
# Deprecated namespaces, to be removed in v2.0.0
|
| 310 |
+
from . import (
|
| 311 |
+
base, bsr, compressed, construct, coo, csc, csr, data, dia, dok, extract,
|
| 312 |
+
lil, sparsetools, sputils
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
__all__ = [s for s in dir() if not s.startswith('_')]
|
| 316 |
+
|
| 317 |
+
# Filter PendingDeprecationWarning for np.matrix introduced with numpy 1.15
|
| 318 |
+
msg = 'the matrix subclass is not the recommended way'
|
| 319 |
+
_warnings.filterwarnings('ignore', message=msg)
|
| 320 |
+
|
| 321 |
+
from scipy._lib._testutils import PytestTester
|
| 322 |
+
test = PytestTester(__name__)
|
| 323 |
+
del PytestTester
|
parrot/lib/python3.10/site-packages/scipy/sparse/_base.py
ADDED
|
@@ -0,0 +1,1390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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check_reshape_kwargs, check_shape,
|
| 6 |
+
get_sum_dtype, isdense, isscalarlike,
|
| 7 |
+
matrix, validateaxis,)
|
| 8 |
+
|
| 9 |
+
from ._matrix import spmatrix
|
| 10 |
+
|
| 11 |
+
__all__ = ['isspmatrix', 'issparse', 'sparray',
|
| 12 |
+
'SparseWarning', 'SparseEfficiencyWarning']
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class SparseWarning(Warning):
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class SparseFormatWarning(SparseWarning):
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class SparseEfficiencyWarning(SparseWarning):
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# The formats that we might potentially understand.
|
| 28 |
+
_formats = {'csc': [0, "Compressed Sparse Column"],
|
| 29 |
+
'csr': [1, "Compressed Sparse Row"],
|
| 30 |
+
'dok': [2, "Dictionary Of Keys"],
|
| 31 |
+
'lil': [3, "List of Lists"],
|
| 32 |
+
'dod': [4, "Dictionary of Dictionaries"],
|
| 33 |
+
'sss': [5, "Symmetric Sparse Skyline"],
|
| 34 |
+
'coo': [6, "COOrdinate"],
|
| 35 |
+
'lba': [7, "Linpack BAnded"],
|
| 36 |
+
'egd': [8, "Ellpack-itpack Generalized Diagonal"],
|
| 37 |
+
'dia': [9, "DIAgonal"],
|
| 38 |
+
'bsr': [10, "Block Sparse Row"],
|
| 39 |
+
'msr': [11, "Modified compressed Sparse Row"],
|
| 40 |
+
'bsc': [12, "Block Sparse Column"],
|
| 41 |
+
'msc': [13, "Modified compressed Sparse Column"],
|
| 42 |
+
'ssk': [14, "Symmetric SKyline"],
|
| 43 |
+
'nsk': [15, "Nonsymmetric SKyline"],
|
| 44 |
+
'jad': [16, "JAgged Diagonal"],
|
| 45 |
+
'uss': [17, "Unsymmetric Sparse Skyline"],
|
| 46 |
+
'vbr': [18, "Variable Block Row"],
|
| 47 |
+
'und': [19, "Undefined"]
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# These univariate ufuncs preserve zeros.
|
| 52 |
+
_ufuncs_with_fixed_point_at_zero = frozenset([
|
| 53 |
+
np.sin, np.tan, np.arcsin, np.arctan, np.sinh, np.tanh, np.arcsinh,
|
| 54 |
+
np.arctanh, np.rint, np.sign, np.expm1, np.log1p, np.deg2rad,
|
| 55 |
+
np.rad2deg, np.floor, np.ceil, np.trunc, np.sqrt])
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
MAXPRINT = 50
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class _spbase:
|
| 62 |
+
""" This class provides a base class for all sparse arrays. It
|
| 63 |
+
cannot be instantiated. Most of the work is provided by subclasses.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
__array_priority__ = 10.1
|
| 67 |
+
_format = 'und' # undefined
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def ndim(self) -> int:
|
| 71 |
+
return len(self._shape)
|
| 72 |
+
|
| 73 |
+
@property
|
| 74 |
+
def _shape_as_2d(self):
|
| 75 |
+
s = self._shape
|
| 76 |
+
return (1, s[-1]) if len(s) == 1 else s
|
| 77 |
+
|
| 78 |
+
@property
|
| 79 |
+
def _bsr_container(self):
|
| 80 |
+
from ._bsr import bsr_array
|
| 81 |
+
return bsr_array
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def _coo_container(self):
|
| 85 |
+
from ._coo import coo_array
|
| 86 |
+
return coo_array
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def _csc_container(self):
|
| 90 |
+
from ._csc import csc_array
|
| 91 |
+
return csc_array
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def _csr_container(self):
|
| 95 |
+
from ._csr import csr_array
|
| 96 |
+
return csr_array
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def _dia_container(self):
|
| 100 |
+
from ._dia import dia_array
|
| 101 |
+
return dia_array
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def _dok_container(self):
|
| 105 |
+
from ._dok import dok_array
|
| 106 |
+
return dok_array
|
| 107 |
+
|
| 108 |
+
@property
|
| 109 |
+
def _lil_container(self):
|
| 110 |
+
from ._lil import lil_array
|
| 111 |
+
return lil_array
|
| 112 |
+
|
| 113 |
+
def __init__(self, arg1, maxprint=MAXPRINT):
|
| 114 |
+
self._shape = None
|
| 115 |
+
if self.__class__.__name__ == '_spbase':
|
| 116 |
+
raise ValueError("This class is not intended"
|
| 117 |
+
" to be instantiated directly.")
|
| 118 |
+
if isinstance(self, sparray) and np.isscalar(arg1):
|
| 119 |
+
raise ValueError(
|
| 120 |
+
"scipy sparse array classes do not support instantiation from a scalar"
|
| 121 |
+
)
|
| 122 |
+
self.maxprint = maxprint
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
def shape(self):
|
| 126 |
+
return self._shape
|
| 127 |
+
|
| 128 |
+
def reshape(self, *args, **kwargs):
|
| 129 |
+
"""reshape(self, shape, order='C', copy=False)
|
| 130 |
+
|
| 131 |
+
Gives a new shape to a sparse array/matrix without changing its data.
|
| 132 |
+
|
| 133 |
+
Parameters
|
| 134 |
+
----------
|
| 135 |
+
shape : length-2 tuple of ints
|
| 136 |
+
The new shape should be compatible with the original shape.
|
| 137 |
+
order : {'C', 'F'}, optional
|
| 138 |
+
Read the elements using this index order. 'C' means to read and
|
| 139 |
+
write the elements using C-like index order; e.g., read entire first
|
| 140 |
+
row, then second row, etc. 'F' means to read and write the elements
|
| 141 |
+
using Fortran-like index order; e.g., read entire first column, then
|
| 142 |
+
second column, etc.
|
| 143 |
+
copy : bool, optional
|
| 144 |
+
Indicates whether or not attributes of self should be copied
|
| 145 |
+
whenever possible. The degree to which attributes are copied varies
|
| 146 |
+
depending on the type of sparse array being used.
|
| 147 |
+
|
| 148 |
+
Returns
|
| 149 |
+
-------
|
| 150 |
+
reshaped : sparse array/matrix
|
| 151 |
+
A sparse array/matrix with the given `shape`, not necessarily of the same
|
| 152 |
+
format as the current object.
|
| 153 |
+
|
| 154 |
+
See Also
|
| 155 |
+
--------
|
| 156 |
+
numpy.reshape : NumPy's implementation of 'reshape' for ndarrays
|
| 157 |
+
"""
|
| 158 |
+
# If the shape already matches, don't bother doing an actual reshape
|
| 159 |
+
# Otherwise, the default is to convert to COO and use its reshape
|
| 160 |
+
is_array = isinstance(self, sparray)
|
| 161 |
+
shape = check_shape(args, self.shape, allow_1d=is_array)
|
| 162 |
+
order, copy = check_reshape_kwargs(kwargs)
|
| 163 |
+
if shape == self.shape:
|
| 164 |
+
if copy:
|
| 165 |
+
return self.copy()
|
| 166 |
+
else:
|
| 167 |
+
return self
|
| 168 |
+
|
| 169 |
+
return self.tocoo(copy=copy).reshape(shape, order=order, copy=False)
|
| 170 |
+
|
| 171 |
+
def resize(self, shape):
|
| 172 |
+
"""Resize the array/matrix in-place to dimensions given by ``shape``
|
| 173 |
+
|
| 174 |
+
Any elements that lie within the new shape will remain at the same
|
| 175 |
+
indices, while non-zero elements lying outside the new shape are
|
| 176 |
+
removed.
|
| 177 |
+
|
| 178 |
+
Parameters
|
| 179 |
+
----------
|
| 180 |
+
shape : (int, int)
|
| 181 |
+
number of rows and columns in the new array/matrix
|
| 182 |
+
|
| 183 |
+
Notes
|
| 184 |
+
-----
|
| 185 |
+
The semantics are not identical to `numpy.ndarray.resize` or
|
| 186 |
+
`numpy.resize`. Here, the same data will be maintained at each index
|
| 187 |
+
before and after reshape, if that index is within the new bounds. In
|
| 188 |
+
numpy, resizing maintains contiguity of the array, moving elements
|
| 189 |
+
around in the logical array but not within a flattened representation.
|
| 190 |
+
|
| 191 |
+
We give no guarantees about whether the underlying data attributes
|
| 192 |
+
(arrays, etc.) will be modified in place or replaced with new objects.
|
| 193 |
+
"""
|
| 194 |
+
# As an inplace operation, this requires implementation in each format.
|
| 195 |
+
raise NotImplementedError(
|
| 196 |
+
f'{type(self).__name__}.resize is not implemented')
|
| 197 |
+
|
| 198 |
+
def astype(self, dtype, casting='unsafe', copy=True):
|
| 199 |
+
"""Cast the array/matrix elements to a specified type.
|
| 200 |
+
|
| 201 |
+
Parameters
|
| 202 |
+
----------
|
| 203 |
+
dtype : string or numpy dtype
|
| 204 |
+
Typecode or data-type to which to cast the data.
|
| 205 |
+
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
|
| 206 |
+
Controls what kind of data casting may occur.
|
| 207 |
+
Defaults to 'unsafe' for backwards compatibility.
|
| 208 |
+
'no' means the data types should not be cast at all.
|
| 209 |
+
'equiv' means only byte-order changes are allowed.
|
| 210 |
+
'safe' means only casts which can preserve values are allowed.
|
| 211 |
+
'same_kind' means only safe casts or casts within a kind,
|
| 212 |
+
like float64 to float32, are allowed.
|
| 213 |
+
'unsafe' means any data conversions may be done.
|
| 214 |
+
copy : bool, optional
|
| 215 |
+
If `copy` is `False`, the result might share some memory with this
|
| 216 |
+
array/matrix. If `copy` is `True`, it is guaranteed that the result and
|
| 217 |
+
this array/matrix do not share any memory.
|
| 218 |
+
"""
|
| 219 |
+
|
| 220 |
+
dtype = np.dtype(dtype)
|
| 221 |
+
if self.dtype != dtype:
|
| 222 |
+
return self.tocsr().astype(
|
| 223 |
+
dtype, casting=casting, copy=copy).asformat(self.format)
|
| 224 |
+
elif copy:
|
| 225 |
+
return self.copy()
|
| 226 |
+
else:
|
| 227 |
+
return self
|
| 228 |
+
|
| 229 |
+
@classmethod
|
| 230 |
+
def _ascontainer(cls, X, **kwargs):
|
| 231 |
+
if issubclass(cls, sparray):
|
| 232 |
+
return np.asarray(X, **kwargs)
|
| 233 |
+
else:
|
| 234 |
+
return asmatrix(X, **kwargs)
|
| 235 |
+
|
| 236 |
+
@classmethod
|
| 237 |
+
def _container(cls, X, **kwargs):
|
| 238 |
+
if issubclass(cls, sparray):
|
| 239 |
+
return np.array(X, **kwargs)
|
| 240 |
+
else:
|
| 241 |
+
return matrix(X, **kwargs)
|
| 242 |
+
|
| 243 |
+
def _asfptype(self):
|
| 244 |
+
"""Upcast array to a floating point format (if necessary)"""
|
| 245 |
+
|
| 246 |
+
fp_types = ['f', 'd', 'F', 'D']
|
| 247 |
+
|
| 248 |
+
if self.dtype.char in fp_types:
|
| 249 |
+
return self
|
| 250 |
+
else:
|
| 251 |
+
for fp_type in fp_types:
|
| 252 |
+
if self.dtype <= np.dtype(fp_type):
|
| 253 |
+
return self.astype(fp_type)
|
| 254 |
+
|
| 255 |
+
raise TypeError('cannot upcast [%s] to a floating '
|
| 256 |
+
'point format' % self.dtype.name)
|
| 257 |
+
|
| 258 |
+
def __iter__(self):
|
| 259 |
+
for r in range(self.shape[0]):
|
| 260 |
+
yield self[r]
|
| 261 |
+
|
| 262 |
+
def _getmaxprint(self):
|
| 263 |
+
"""Maximum number of elements to display when printed."""
|
| 264 |
+
return self.maxprint
|
| 265 |
+
|
| 266 |
+
def count_nonzero(self):
|
| 267 |
+
"""Number of non-zero entries, equivalent to
|
| 268 |
+
|
| 269 |
+
np.count_nonzero(a.toarray())
|
| 270 |
+
|
| 271 |
+
Unlike the nnz property, which return the number of stored
|
| 272 |
+
entries (the length of the data attribute), this method counts the
|
| 273 |
+
actual number of non-zero entries in data.
|
| 274 |
+
"""
|
| 275 |
+
raise NotImplementedError("count_nonzero not implemented for %s." %
|
| 276 |
+
self.__class__.__name__)
|
| 277 |
+
|
| 278 |
+
def _getnnz(self, axis=None):
|
| 279 |
+
"""Number of stored values, including explicit zeros.
|
| 280 |
+
|
| 281 |
+
Parameters
|
| 282 |
+
----------
|
| 283 |
+
axis : None, 0, or 1
|
| 284 |
+
Select between the number of values across the whole array, in
|
| 285 |
+
each column, or in each row.
|
| 286 |
+
|
| 287 |
+
See also
|
| 288 |
+
--------
|
| 289 |
+
count_nonzero : Number of non-zero entries
|
| 290 |
+
"""
|
| 291 |
+
raise NotImplementedError("getnnz not implemented for %s." %
|
| 292 |
+
self.__class__.__name__)
|
| 293 |
+
|
| 294 |
+
@property
|
| 295 |
+
def nnz(self) -> int:
|
| 296 |
+
"""Number of stored values, including explicit zeros.
|
| 297 |
+
|
| 298 |
+
See also
|
| 299 |
+
--------
|
| 300 |
+
count_nonzero : Number of non-zero entries
|
| 301 |
+
"""
|
| 302 |
+
return self._getnnz()
|
| 303 |
+
|
| 304 |
+
@property
|
| 305 |
+
def size(self) -> int:
|
| 306 |
+
"""Number of stored values.
|
| 307 |
+
|
| 308 |
+
See also
|
| 309 |
+
--------
|
| 310 |
+
count_nonzero : Number of non-zero values.
|
| 311 |
+
"""
|
| 312 |
+
return self._getnnz()
|
| 313 |
+
|
| 314 |
+
@property
|
| 315 |
+
def format(self) -> str:
|
| 316 |
+
"""Format string for matrix."""
|
| 317 |
+
return self._format
|
| 318 |
+
|
| 319 |
+
@property
|
| 320 |
+
def T(self):
|
| 321 |
+
"""Transpose."""
|
| 322 |
+
return self.transpose()
|
| 323 |
+
|
| 324 |
+
@property
|
| 325 |
+
def real(self):
|
| 326 |
+
return self._real()
|
| 327 |
+
|
| 328 |
+
@property
|
| 329 |
+
def imag(self):
|
| 330 |
+
return self._imag()
|
| 331 |
+
|
| 332 |
+
def __repr__(self):
|
| 333 |
+
_, format_name = _formats[self.format]
|
| 334 |
+
sparse_cls = 'array' if isinstance(self, sparray) else 'matrix'
|
| 335 |
+
return (
|
| 336 |
+
f"<{format_name} sparse {sparse_cls} of dtype '{self.dtype}'\n"
|
| 337 |
+
f"\twith {self.nnz} stored elements and shape {self.shape}>"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
def __str__(self):
|
| 341 |
+
maxprint = self._getmaxprint()
|
| 342 |
+
|
| 343 |
+
A = self.tocoo()
|
| 344 |
+
|
| 345 |
+
# helper function, outputs "(i,j) v"
|
| 346 |
+
def tostr(coords, data):
|
| 347 |
+
pairs = zip(zip(*(c.tolist() for c in coords)), data)
|
| 348 |
+
return '\n'.join(f' {idx}\t{val}' for idx, val in pairs)
|
| 349 |
+
|
| 350 |
+
out = repr(self)
|
| 351 |
+
if self.nnz == 0:
|
| 352 |
+
return out
|
| 353 |
+
|
| 354 |
+
out += '\n Coords\tValues\n'
|
| 355 |
+
if self.nnz > maxprint:
|
| 356 |
+
half = maxprint // 2
|
| 357 |
+
out += tostr(tuple(c[:half] for c in A.coords), A.data[:half])
|
| 358 |
+
out += "\n :\t:\n"
|
| 359 |
+
half = maxprint - half
|
| 360 |
+
out += tostr(tuple(c[-half:] for c in A.coords), A.data[-half:])
|
| 361 |
+
else:
|
| 362 |
+
out += tostr(A.coords, A.data)
|
| 363 |
+
|
| 364 |
+
return out
|
| 365 |
+
|
| 366 |
+
def __bool__(self): # Simple -- other ideas?
|
| 367 |
+
if self.shape == (1, 1):
|
| 368 |
+
return self.nnz != 0
|
| 369 |
+
else:
|
| 370 |
+
raise ValueError("The truth value of an array with more than one "
|
| 371 |
+
"element is ambiguous. Use a.any() or a.all().")
|
| 372 |
+
__nonzero__ = __bool__
|
| 373 |
+
|
| 374 |
+
# What should len(sparse) return? For consistency with dense matrices,
|
| 375 |
+
# perhaps it should be the number of rows? But for some uses the number of
|
| 376 |
+
# non-zeros is more important. For now, raise an exception!
|
| 377 |
+
def __len__(self):
|
| 378 |
+
raise TypeError("sparse array length is ambiguous; use getnnz()"
|
| 379 |
+
" or shape[0]")
|
| 380 |
+
|
| 381 |
+
def asformat(self, format, copy=False):
|
| 382 |
+
"""Return this array/matrix in the passed format.
|
| 383 |
+
|
| 384 |
+
Parameters
|
| 385 |
+
----------
|
| 386 |
+
format : {str, None}
|
| 387 |
+
The desired sparse format ("csr", "csc", "lil", "dok", "array", ...)
|
| 388 |
+
or None for no conversion.
|
| 389 |
+
copy : bool, optional
|
| 390 |
+
If True, the result is guaranteed to not share data with self.
|
| 391 |
+
|
| 392 |
+
Returns
|
| 393 |
+
-------
|
| 394 |
+
A : This array/matrix in the passed format.
|
| 395 |
+
"""
|
| 396 |
+
if format is None or format == self.format:
|
| 397 |
+
if copy:
|
| 398 |
+
return self.copy()
|
| 399 |
+
else:
|
| 400 |
+
return self
|
| 401 |
+
else:
|
| 402 |
+
try:
|
| 403 |
+
convert_method = getattr(self, 'to' + format)
|
| 404 |
+
except AttributeError as e:
|
| 405 |
+
raise ValueError(f'Format {format} is unknown.') from e
|
| 406 |
+
|
| 407 |
+
# Forward the copy kwarg, if it's accepted.
|
| 408 |
+
try:
|
| 409 |
+
return convert_method(copy=copy)
|
| 410 |
+
except TypeError:
|
| 411 |
+
return convert_method()
|
| 412 |
+
|
| 413 |
+
###################################################################
|
| 414 |
+
# NOTE: All arithmetic operations use csr_matrix by default.
|
| 415 |
+
# Therefore a new sparse array format just needs to define a
|
| 416 |
+
# .tocsr() method to provide arithmetic support. Any of these
|
| 417 |
+
# methods can be overridden for efficiency.
|
| 418 |
+
####################################################################
|
| 419 |
+
|
| 420 |
+
def multiply(self, other):
|
| 421 |
+
"""Point-wise multiplication by another array/matrix."""
|
| 422 |
+
if isscalarlike(other):
|
| 423 |
+
return self._mul_scalar(other)
|
| 424 |
+
return self.tocsr().multiply(other)
|
| 425 |
+
|
| 426 |
+
def maximum(self, other):
|
| 427 |
+
"""Element-wise maximum between this and another array/matrix."""
|
| 428 |
+
return self.tocsr().maximum(other)
|
| 429 |
+
|
| 430 |
+
def minimum(self, other):
|
| 431 |
+
"""Element-wise minimum between this and another array/matrix."""
|
| 432 |
+
return self.tocsr().minimum(other)
|
| 433 |
+
|
| 434 |
+
def dot(self, other):
|
| 435 |
+
"""Ordinary dot product
|
| 436 |
+
|
| 437 |
+
Examples
|
| 438 |
+
--------
|
| 439 |
+
>>> import numpy as np
|
| 440 |
+
>>> from scipy.sparse import csr_array
|
| 441 |
+
>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
|
| 442 |
+
>>> v = np.array([1, 0, -1])
|
| 443 |
+
>>> A.dot(v)
|
| 444 |
+
array([ 1, -3, -1], dtype=int64)
|
| 445 |
+
|
| 446 |
+
"""
|
| 447 |
+
if np.isscalar(other):
|
| 448 |
+
return self * other
|
| 449 |
+
else:
|
| 450 |
+
return self @ other
|
| 451 |
+
|
| 452 |
+
def power(self, n, dtype=None):
|
| 453 |
+
"""Element-wise power."""
|
| 454 |
+
return self.tocsr().power(n, dtype=dtype)
|
| 455 |
+
|
| 456 |
+
def __eq__(self, other):
|
| 457 |
+
return self.tocsr().__eq__(other)
|
| 458 |
+
|
| 459 |
+
def __ne__(self, other):
|
| 460 |
+
return self.tocsr().__ne__(other)
|
| 461 |
+
|
| 462 |
+
def __lt__(self, other):
|
| 463 |
+
return self.tocsr().__lt__(other)
|
| 464 |
+
|
| 465 |
+
def __gt__(self, other):
|
| 466 |
+
return self.tocsr().__gt__(other)
|
| 467 |
+
|
| 468 |
+
def __le__(self, other):
|
| 469 |
+
return self.tocsr().__le__(other)
|
| 470 |
+
|
| 471 |
+
def __ge__(self, other):
|
| 472 |
+
return self.tocsr().__ge__(other)
|
| 473 |
+
|
| 474 |
+
def __abs__(self):
|
| 475 |
+
return abs(self.tocsr())
|
| 476 |
+
|
| 477 |
+
def __round__(self, ndigits=0):
|
| 478 |
+
return round(self.tocsr(), ndigits=ndigits)
|
| 479 |
+
|
| 480 |
+
def _add_sparse(self, other):
|
| 481 |
+
return self.tocsr()._add_sparse(other)
|
| 482 |
+
|
| 483 |
+
def _add_dense(self, other):
|
| 484 |
+
return self.tocoo()._add_dense(other)
|
| 485 |
+
|
| 486 |
+
def _sub_sparse(self, other):
|
| 487 |
+
return self.tocsr()._sub_sparse(other)
|
| 488 |
+
|
| 489 |
+
def _sub_dense(self, other):
|
| 490 |
+
return self.todense() - other
|
| 491 |
+
|
| 492 |
+
def _rsub_dense(self, other):
|
| 493 |
+
# note: this can't be replaced by other + (-self) for unsigned types
|
| 494 |
+
return other - self.todense()
|
| 495 |
+
|
| 496 |
+
def __add__(self, other): # self + other
|
| 497 |
+
if isscalarlike(other):
|
| 498 |
+
if other == 0:
|
| 499 |
+
return self.copy()
|
| 500 |
+
# Now we would add this scalar to every element.
|
| 501 |
+
raise NotImplementedError('adding a nonzero scalar to a '
|
| 502 |
+
'sparse array is not supported')
|
| 503 |
+
elif issparse(other):
|
| 504 |
+
if other.shape != self.shape:
|
| 505 |
+
raise ValueError("inconsistent shapes")
|
| 506 |
+
return self._add_sparse(other)
|
| 507 |
+
elif isdense(other):
|
| 508 |
+
other = np.broadcast_to(other, self.shape)
|
| 509 |
+
return self._add_dense(other)
|
| 510 |
+
else:
|
| 511 |
+
return NotImplemented
|
| 512 |
+
|
| 513 |
+
def __radd__(self,other): # other + self
|
| 514 |
+
return self.__add__(other)
|
| 515 |
+
|
| 516 |
+
def __sub__(self, other): # self - other
|
| 517 |
+
if isscalarlike(other):
|
| 518 |
+
if other == 0:
|
| 519 |
+
return self.copy()
|
| 520 |
+
raise NotImplementedError('subtracting a nonzero scalar from a '
|
| 521 |
+
'sparse array is not supported')
|
| 522 |
+
elif issparse(other):
|
| 523 |
+
if other.shape != self.shape:
|
| 524 |
+
raise ValueError("inconsistent shapes")
|
| 525 |
+
return self._sub_sparse(other)
|
| 526 |
+
elif isdense(other):
|
| 527 |
+
other = np.broadcast_to(other, self.shape)
|
| 528 |
+
return self._sub_dense(other)
|
| 529 |
+
else:
|
| 530 |
+
return NotImplemented
|
| 531 |
+
|
| 532 |
+
def __rsub__(self,other): # other - self
|
| 533 |
+
if isscalarlike(other):
|
| 534 |
+
if other == 0:
|
| 535 |
+
return -self.copy()
|
| 536 |
+
raise NotImplementedError('subtracting a sparse array from a '
|
| 537 |
+
'nonzero scalar is not supported')
|
| 538 |
+
elif isdense(other):
|
| 539 |
+
other = np.broadcast_to(other, self.shape)
|
| 540 |
+
return self._rsub_dense(other)
|
| 541 |
+
else:
|
| 542 |
+
return NotImplemented
|
| 543 |
+
|
| 544 |
+
def _matmul_dispatch(self, other):
|
| 545 |
+
"""np.array-like matmul & `np.matrix`-like mul, i.e. `dot` or `NotImplemented`
|
| 546 |
+
|
| 547 |
+
interpret other and call one of the following
|
| 548 |
+
self._mul_scalar()
|
| 549 |
+
self._matmul_vector()
|
| 550 |
+
self._matmul_multivector()
|
| 551 |
+
self._matmul_sparse()
|
| 552 |
+
"""
|
| 553 |
+
# This method has to be different from `__matmul__` because it is also
|
| 554 |
+
# called by sparse matrix classes.
|
| 555 |
+
|
| 556 |
+
# Currently matrix multiplication is only supported
|
| 557 |
+
# for 2D arrays. Hence we unpacked and use only the
|
| 558 |
+
# two last axes' lengths.
|
| 559 |
+
M, N = self._shape_as_2d
|
| 560 |
+
|
| 561 |
+
if other.__class__ is np.ndarray:
|
| 562 |
+
# Fast path for the most common case
|
| 563 |
+
if other.shape == (N,):
|
| 564 |
+
return self._matmul_vector(other)
|
| 565 |
+
elif other.shape == (N, 1):
|
| 566 |
+
result = self._matmul_vector(other.ravel())
|
| 567 |
+
if self.ndim == 1:
|
| 568 |
+
return result
|
| 569 |
+
return result.reshape(M, 1)
|
| 570 |
+
elif other.ndim == 2 and other.shape[0] == N:
|
| 571 |
+
return self._matmul_multivector(other)
|
| 572 |
+
|
| 573 |
+
if isscalarlike(other):
|
| 574 |
+
# scalar value
|
| 575 |
+
return self._mul_scalar(other)
|
| 576 |
+
|
| 577 |
+
if issparse(other):
|
| 578 |
+
if self.shape[-1] != other.shape[0]:
|
| 579 |
+
raise ValueError('dimension mismatch')
|
| 580 |
+
return self._matmul_sparse(other)
|
| 581 |
+
|
| 582 |
+
# If it's a list or whatever, treat it like an array
|
| 583 |
+
other_a = np.asanyarray(other)
|
| 584 |
+
|
| 585 |
+
if other_a.ndim == 0 and other_a.dtype == np.object_:
|
| 586 |
+
# Not interpretable as an array; return NotImplemented so that
|
| 587 |
+
# other's __rmatmul__ can kick in if that's implemented.
|
| 588 |
+
return NotImplemented
|
| 589 |
+
|
| 590 |
+
try:
|
| 591 |
+
other.shape
|
| 592 |
+
except AttributeError:
|
| 593 |
+
other = other_a
|
| 594 |
+
|
| 595 |
+
if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1:
|
| 596 |
+
# dense row or column vector
|
| 597 |
+
if other.shape != (N,) and other.shape != (N, 1):
|
| 598 |
+
raise ValueError('dimension mismatch')
|
| 599 |
+
|
| 600 |
+
result = self._matmul_vector(np.ravel(other))
|
| 601 |
+
|
| 602 |
+
if isinstance(other, np.matrix):
|
| 603 |
+
result = self._ascontainer(result)
|
| 604 |
+
|
| 605 |
+
if other.ndim == 2 and other.shape[1] == 1:
|
| 606 |
+
# If 'other' was an (nx1) column vector, reshape the result
|
| 607 |
+
result = result.reshape(-1, 1)
|
| 608 |
+
|
| 609 |
+
return result
|
| 610 |
+
|
| 611 |
+
elif other.ndim == 2:
|
| 612 |
+
##
|
| 613 |
+
# dense 2D array or matrix ("multivector")
|
| 614 |
+
|
| 615 |
+
if other.shape[0] != N:
|
| 616 |
+
raise ValueError('dimension mismatch')
|
| 617 |
+
|
| 618 |
+
result = self._matmul_multivector(np.asarray(other))
|
| 619 |
+
|
| 620 |
+
if isinstance(other, np.matrix):
|
| 621 |
+
result = self._ascontainer(result)
|
| 622 |
+
|
| 623 |
+
return result
|
| 624 |
+
|
| 625 |
+
else:
|
| 626 |
+
raise ValueError('could not interpret dimensions')
|
| 627 |
+
|
| 628 |
+
def __mul__(self, other):
|
| 629 |
+
return self.multiply(other)
|
| 630 |
+
|
| 631 |
+
def __rmul__(self, other): # other * self
|
| 632 |
+
return self.multiply(other)
|
| 633 |
+
|
| 634 |
+
# by default, use CSR for __mul__ handlers
|
| 635 |
+
def _mul_scalar(self, other):
|
| 636 |
+
return self.tocsr()._mul_scalar(other)
|
| 637 |
+
|
| 638 |
+
def _matmul_vector(self, other):
|
| 639 |
+
return self.tocsr()._matmul_vector(other)
|
| 640 |
+
|
| 641 |
+
def _matmul_multivector(self, other):
|
| 642 |
+
return self.tocsr()._matmul_multivector(other)
|
| 643 |
+
|
| 644 |
+
def _matmul_sparse(self, other):
|
| 645 |
+
return self.tocsr()._matmul_sparse(other)
|
| 646 |
+
|
| 647 |
+
def _rmatmul_dispatch(self, other):
|
| 648 |
+
if isscalarlike(other):
|
| 649 |
+
return self._mul_scalar(other)
|
| 650 |
+
else:
|
| 651 |
+
# Don't use asarray unless we have to
|
| 652 |
+
try:
|
| 653 |
+
tr = other.transpose()
|
| 654 |
+
except AttributeError:
|
| 655 |
+
tr = np.asarray(other).transpose()
|
| 656 |
+
ret = self.transpose()._matmul_dispatch(tr)
|
| 657 |
+
if ret is NotImplemented:
|
| 658 |
+
return NotImplemented
|
| 659 |
+
return ret.transpose()
|
| 660 |
+
|
| 661 |
+
#######################
|
| 662 |
+
# matmul (@) operator #
|
| 663 |
+
#######################
|
| 664 |
+
|
| 665 |
+
def __matmul__(self, other):
|
| 666 |
+
if isscalarlike(other):
|
| 667 |
+
raise ValueError("Scalar operands are not allowed, "
|
| 668 |
+
"use '*' instead")
|
| 669 |
+
return self._matmul_dispatch(other)
|
| 670 |
+
|
| 671 |
+
def __rmatmul__(self, other):
|
| 672 |
+
if isscalarlike(other):
|
| 673 |
+
raise ValueError("Scalar operands are not allowed, "
|
| 674 |
+
"use '*' instead")
|
| 675 |
+
return self._rmatmul_dispatch(other)
|
| 676 |
+
|
| 677 |
+
####################
|
| 678 |
+
# Other Arithmetic #
|
| 679 |
+
####################
|
| 680 |
+
|
| 681 |
+
def _divide(self, other, true_divide=False, rdivide=False):
|
| 682 |
+
if isscalarlike(other):
|
| 683 |
+
if rdivide:
|
| 684 |
+
if true_divide:
|
| 685 |
+
return np.true_divide(other, self.todense())
|
| 686 |
+
else:
|
| 687 |
+
return np.divide(other, self.todense())
|
| 688 |
+
|
| 689 |
+
if true_divide and np.can_cast(self.dtype, np.float64):
|
| 690 |
+
return self.astype(np.float64)._mul_scalar(1./other)
|
| 691 |
+
else:
|
| 692 |
+
r = self._mul_scalar(1./other)
|
| 693 |
+
|
| 694 |
+
scalar_dtype = np.asarray(other).dtype
|
| 695 |
+
if (np.issubdtype(self.dtype, np.integer) and
|
| 696 |
+
np.issubdtype(scalar_dtype, np.integer)):
|
| 697 |
+
return r.astype(self.dtype)
|
| 698 |
+
else:
|
| 699 |
+
return r
|
| 700 |
+
|
| 701 |
+
elif isdense(other):
|
| 702 |
+
if not rdivide:
|
| 703 |
+
if true_divide:
|
| 704 |
+
recip = np.true_divide(1., other)
|
| 705 |
+
else:
|
| 706 |
+
recip = np.divide(1., other)
|
| 707 |
+
return self.multiply(recip)
|
| 708 |
+
else:
|
| 709 |
+
if true_divide:
|
| 710 |
+
return np.true_divide(other, self.todense())
|
| 711 |
+
else:
|
| 712 |
+
return np.divide(other, self.todense())
|
| 713 |
+
elif issparse(other):
|
| 714 |
+
if rdivide:
|
| 715 |
+
return other._divide(self, true_divide, rdivide=False)
|
| 716 |
+
|
| 717 |
+
self_csr = self.tocsr()
|
| 718 |
+
if true_divide and np.can_cast(self.dtype, np.float64):
|
| 719 |
+
return self_csr.astype(np.float64)._divide_sparse(other)
|
| 720 |
+
else:
|
| 721 |
+
return self_csr._divide_sparse(other)
|
| 722 |
+
else:
|
| 723 |
+
return NotImplemented
|
| 724 |
+
|
| 725 |
+
def __truediv__(self, other):
|
| 726 |
+
return self._divide(other, true_divide=True)
|
| 727 |
+
|
| 728 |
+
def __div__(self, other):
|
| 729 |
+
# Always do true division
|
| 730 |
+
return self._divide(other, true_divide=True)
|
| 731 |
+
|
| 732 |
+
def __rtruediv__(self, other):
|
| 733 |
+
# Implementing this as the inverse would be too magical -- bail out
|
| 734 |
+
return NotImplemented
|
| 735 |
+
|
| 736 |
+
def __rdiv__(self, other):
|
| 737 |
+
# Implementing this as the inverse would be too magical -- bail out
|
| 738 |
+
return NotImplemented
|
| 739 |
+
|
| 740 |
+
def __neg__(self):
|
| 741 |
+
return -self.tocsr()
|
| 742 |
+
|
| 743 |
+
def __iadd__(self, other):
|
| 744 |
+
return NotImplemented
|
| 745 |
+
|
| 746 |
+
def __isub__(self, other):
|
| 747 |
+
return NotImplemented
|
| 748 |
+
|
| 749 |
+
def __imul__(self, other):
|
| 750 |
+
return NotImplemented
|
| 751 |
+
|
| 752 |
+
def __idiv__(self, other):
|
| 753 |
+
return self.__itruediv__(other)
|
| 754 |
+
|
| 755 |
+
def __itruediv__(self, other):
|
| 756 |
+
return NotImplemented
|
| 757 |
+
|
| 758 |
+
def __pow__(self, *args, **kwargs):
|
| 759 |
+
return self.power(*args, **kwargs)
|
| 760 |
+
|
| 761 |
+
def transpose(self, axes=None, copy=False):
|
| 762 |
+
"""
|
| 763 |
+
Reverses the dimensions of the sparse array/matrix.
|
| 764 |
+
|
| 765 |
+
Parameters
|
| 766 |
+
----------
|
| 767 |
+
axes : None, optional
|
| 768 |
+
This argument is in the signature *solely* for NumPy
|
| 769 |
+
compatibility reasons. Do not pass in anything except
|
| 770 |
+
for the default value.
|
| 771 |
+
copy : bool, optional
|
| 772 |
+
Indicates whether or not attributes of `self` should be
|
| 773 |
+
copied whenever possible. The degree to which attributes
|
| 774 |
+
are copied varies depending on the type of sparse array/matrix
|
| 775 |
+
being used.
|
| 776 |
+
|
| 777 |
+
Returns
|
| 778 |
+
-------
|
| 779 |
+
p : `self` with the dimensions reversed.
|
| 780 |
+
|
| 781 |
+
Notes
|
| 782 |
+
-----
|
| 783 |
+
If `self` is a `csr_array` or a `csc_array`, then this will return a
|
| 784 |
+
`csc_array` or a `csr_array`, respectively.
|
| 785 |
+
|
| 786 |
+
See Also
|
| 787 |
+
--------
|
| 788 |
+
numpy.transpose : NumPy's implementation of 'transpose' for ndarrays
|
| 789 |
+
"""
|
| 790 |
+
return self.tocsr(copy=copy).transpose(axes=axes, copy=False)
|
| 791 |
+
|
| 792 |
+
def conjugate(self, copy=True):
|
| 793 |
+
"""Element-wise complex conjugation.
|
| 794 |
+
|
| 795 |
+
If the array/matrix is of non-complex data type and `copy` is False,
|
| 796 |
+
this method does nothing and the data is not copied.
|
| 797 |
+
|
| 798 |
+
Parameters
|
| 799 |
+
----------
|
| 800 |
+
copy : bool, optional
|
| 801 |
+
If True, the result is guaranteed to not share data with self.
|
| 802 |
+
|
| 803 |
+
Returns
|
| 804 |
+
-------
|
| 805 |
+
A : The element-wise complex conjugate.
|
| 806 |
+
|
| 807 |
+
"""
|
| 808 |
+
if np.issubdtype(self.dtype, np.complexfloating):
|
| 809 |
+
return self.tocsr(copy=copy).conjugate(copy=False)
|
| 810 |
+
elif copy:
|
| 811 |
+
return self.copy()
|
| 812 |
+
else:
|
| 813 |
+
return self
|
| 814 |
+
|
| 815 |
+
def conj(self, copy=True):
|
| 816 |
+
return self.conjugate(copy=copy)
|
| 817 |
+
|
| 818 |
+
conj.__doc__ = conjugate.__doc__
|
| 819 |
+
|
| 820 |
+
def _real(self):
|
| 821 |
+
return self.tocsr()._real()
|
| 822 |
+
|
| 823 |
+
def _imag(self):
|
| 824 |
+
return self.tocsr()._imag()
|
| 825 |
+
|
| 826 |
+
def nonzero(self):
|
| 827 |
+
"""Nonzero indices of the array/matrix.
|
| 828 |
+
|
| 829 |
+
Returns a tuple of arrays (row,col) containing the indices
|
| 830 |
+
of the non-zero elements of the array.
|
| 831 |
+
|
| 832 |
+
Examples
|
| 833 |
+
--------
|
| 834 |
+
>>> from scipy.sparse import csr_array
|
| 835 |
+
>>> A = csr_array([[1,2,0],[0,0,3],[4,0,5]])
|
| 836 |
+
>>> A.nonzero()
|
| 837 |
+
(array([0, 0, 1, 2, 2]), array([0, 1, 2, 0, 2]))
|
| 838 |
+
|
| 839 |
+
"""
|
| 840 |
+
|
| 841 |
+
# convert to COOrdinate format
|
| 842 |
+
A = self.tocoo()
|
| 843 |
+
nz_mask = A.data != 0
|
| 844 |
+
return (A.row[nz_mask], A.col[nz_mask])
|
| 845 |
+
|
| 846 |
+
def _getcol(self, j):
|
| 847 |
+
"""Returns a copy of column j of the array, as an (m x 1) sparse
|
| 848 |
+
array (column vector).
|
| 849 |
+
"""
|
| 850 |
+
if self.ndim == 1:
|
| 851 |
+
raise ValueError("getcol not provided for 1d arrays. Use indexing A[j]")
|
| 852 |
+
# Subclasses should override this method for efficiency.
|
| 853 |
+
# Post-multiply by a (n x 1) column vector 'a' containing all zeros
|
| 854 |
+
# except for a_j = 1
|
| 855 |
+
N = self.shape[-1]
|
| 856 |
+
if j < 0:
|
| 857 |
+
j += N
|
| 858 |
+
if j < 0 or j >= N:
|
| 859 |
+
raise IndexError("index out of bounds")
|
| 860 |
+
col_selector = self._csc_container(([1], [[j], [0]]),
|
| 861 |
+
shape=(N, 1), dtype=self.dtype)
|
| 862 |
+
result = self @ col_selector
|
| 863 |
+
return result
|
| 864 |
+
|
| 865 |
+
def _getrow(self, i):
|
| 866 |
+
"""Returns a copy of row i of the array, as a (1 x n) sparse
|
| 867 |
+
array (row vector).
|
| 868 |
+
"""
|
| 869 |
+
if self.ndim == 1:
|
| 870 |
+
raise ValueError("getrow not meaningful for a 1d array")
|
| 871 |
+
# Subclasses should override this method for efficiency.
|
| 872 |
+
# Pre-multiply by a (1 x m) row vector 'a' containing all zeros
|
| 873 |
+
# except for a_i = 1
|
| 874 |
+
M = self.shape[0]
|
| 875 |
+
if i < 0:
|
| 876 |
+
i += M
|
| 877 |
+
if i < 0 or i >= M:
|
| 878 |
+
raise IndexError("index out of bounds")
|
| 879 |
+
row_selector = self._csr_container(([1], [[0], [i]]),
|
| 880 |
+
shape=(1, M), dtype=self.dtype)
|
| 881 |
+
return row_selector @ self
|
| 882 |
+
|
| 883 |
+
# The following dunder methods cannot be implemented.
|
| 884 |
+
#
|
| 885 |
+
# def __array__(self):
|
| 886 |
+
# # Sparse matrices rely on NumPy wrapping them in object arrays under
|
| 887 |
+
# # the hood to make unary ufuncs work on them. So we cannot raise
|
| 888 |
+
# # TypeError here - which would be handy to not give users object
|
| 889 |
+
# # arrays they probably don't want (they're looking for `.toarray()`).
|
| 890 |
+
# #
|
| 891 |
+
# # Conversion with `toarray()` would also break things because of the
|
| 892 |
+
# # behavior discussed above, plus we want to avoid densification by
|
| 893 |
+
# # accident because that can too easily blow up memory.
|
| 894 |
+
#
|
| 895 |
+
# def __array_ufunc__(self):
|
| 896 |
+
# # We cannot implement __array_ufunc__ due to mismatching semantics.
|
| 897 |
+
# # See gh-7707 and gh-7349 for details.
|
| 898 |
+
#
|
| 899 |
+
# def __array_function__(self):
|
| 900 |
+
# # We cannot implement __array_function__ due to mismatching semantics.
|
| 901 |
+
# # See gh-10362 for details.
|
| 902 |
+
|
| 903 |
+
def todense(self, order=None, out=None):
|
| 904 |
+
"""
|
| 905 |
+
Return a dense representation of this sparse array/matrix.
|
| 906 |
+
|
| 907 |
+
Parameters
|
| 908 |
+
----------
|
| 909 |
+
order : {'C', 'F'}, optional
|
| 910 |
+
Whether to store multi-dimensional data in C (row-major)
|
| 911 |
+
or Fortran (column-major) order in memory. The default
|
| 912 |
+
is 'None', which provides no ordering guarantees.
|
| 913 |
+
Cannot be specified in conjunction with the `out`
|
| 914 |
+
argument.
|
| 915 |
+
|
| 916 |
+
out : ndarray, 2-D, optional
|
| 917 |
+
If specified, uses this array (or `numpy.matrix`) as the
|
| 918 |
+
output buffer instead of allocating a new array to
|
| 919 |
+
return. The provided array must have the same shape and
|
| 920 |
+
dtype as the sparse array/matrix on which you are calling the
|
| 921 |
+
method.
|
| 922 |
+
|
| 923 |
+
Returns
|
| 924 |
+
-------
|
| 925 |
+
arr : numpy.matrix, 2-D
|
| 926 |
+
A NumPy matrix object with the same shape and containing
|
| 927 |
+
the same data represented by the sparse array/matrix, with the
|
| 928 |
+
requested memory order. If `out` was passed and was an
|
| 929 |
+
array (rather than a `numpy.matrix`), it will be filled
|
| 930 |
+
with the appropriate values and returned wrapped in a
|
| 931 |
+
`numpy.matrix` object that shares the same memory.
|
| 932 |
+
"""
|
| 933 |
+
return self._ascontainer(self.toarray(order=order, out=out))
|
| 934 |
+
|
| 935 |
+
def toarray(self, order=None, out=None):
|
| 936 |
+
"""
|
| 937 |
+
Return a dense ndarray representation of this sparse array/matrix.
|
| 938 |
+
|
| 939 |
+
Parameters
|
| 940 |
+
----------
|
| 941 |
+
order : {'C', 'F'}, optional
|
| 942 |
+
Whether to store multidimensional data in C (row-major)
|
| 943 |
+
or Fortran (column-major) order in memory. The default
|
| 944 |
+
is 'None', which provides no ordering guarantees.
|
| 945 |
+
Cannot be specified in conjunction with the `out`
|
| 946 |
+
argument.
|
| 947 |
+
|
| 948 |
+
out : ndarray, 2-D, optional
|
| 949 |
+
If specified, uses this array as the output buffer
|
| 950 |
+
instead of allocating a new array to return. The provided
|
| 951 |
+
array must have the same shape and dtype as the sparse
|
| 952 |
+
array/matrix on which you are calling the method. For most
|
| 953 |
+
sparse types, `out` is required to be memory contiguous
|
| 954 |
+
(either C or Fortran ordered).
|
| 955 |
+
|
| 956 |
+
Returns
|
| 957 |
+
-------
|
| 958 |
+
arr : ndarray, 2-D
|
| 959 |
+
An array with the same shape and containing the same
|
| 960 |
+
data represented by the sparse array/matrix, with the requested
|
| 961 |
+
memory order. If `out` was passed, the same object is
|
| 962 |
+
returned after being modified in-place to contain the
|
| 963 |
+
appropriate values.
|
| 964 |
+
"""
|
| 965 |
+
return self.tocoo(copy=False).toarray(order=order, out=out)
|
| 966 |
+
|
| 967 |
+
# Any sparse array format deriving from _spbase must define one of
|
| 968 |
+
# tocsr or tocoo. The other conversion methods may be implemented for
|
| 969 |
+
# efficiency, but are not required.
|
| 970 |
+
def tocsr(self, copy=False):
|
| 971 |
+
"""Convert this array/matrix to Compressed Sparse Row format.
|
| 972 |
+
|
| 973 |
+
With copy=False, the data/indices may be shared between this array/matrix and
|
| 974 |
+
the resultant csr_array/matrix.
|
| 975 |
+
"""
|
| 976 |
+
return self.tocoo(copy=copy).tocsr(copy=False)
|
| 977 |
+
|
| 978 |
+
def todok(self, copy=False):
|
| 979 |
+
"""Convert this array/matrix to Dictionary Of Keys format.
|
| 980 |
+
|
| 981 |
+
With copy=False, the data/indices may be shared between this array/matrix and
|
| 982 |
+
the resultant dok_array/matrix.
|
| 983 |
+
"""
|
| 984 |
+
return self.tocoo(copy=copy).todok(copy=False)
|
| 985 |
+
|
| 986 |
+
def tocoo(self, copy=False):
|
| 987 |
+
"""Convert this array/matrix to COOrdinate format.
|
| 988 |
+
|
| 989 |
+
With copy=False, the data/indices may be shared between this array/matrix and
|
| 990 |
+
the resultant coo_array/matrix.
|
| 991 |
+
"""
|
| 992 |
+
return self.tocsr(copy=False).tocoo(copy=copy)
|
| 993 |
+
|
| 994 |
+
def tolil(self, copy=False):
|
| 995 |
+
"""Convert this array/matrix to List of Lists format.
|
| 996 |
+
|
| 997 |
+
With copy=False, the data/indices may be shared between this array/matrix and
|
| 998 |
+
the resultant lil_array/matrix.
|
| 999 |
+
"""
|
| 1000 |
+
return self.tocsr(copy=False).tolil(copy=copy)
|
| 1001 |
+
|
| 1002 |
+
def todia(self, copy=False):
|
| 1003 |
+
"""Convert this array/matrix to sparse DIAgonal format.
|
| 1004 |
+
|
| 1005 |
+
With copy=False, the data/indices may be shared between this array/matrix and
|
| 1006 |
+
the resultant dia_array/matrix.
|
| 1007 |
+
"""
|
| 1008 |
+
return self.tocoo(copy=copy).todia(copy=False)
|
| 1009 |
+
|
| 1010 |
+
def tobsr(self, blocksize=None, copy=False):
|
| 1011 |
+
"""Convert this array/matrix to Block Sparse Row format.
|
| 1012 |
+
|
| 1013 |
+
With copy=False, the data/indices may be shared between this array/matrix and
|
| 1014 |
+
the resultant bsr_array/matrix.
|
| 1015 |
+
|
| 1016 |
+
When blocksize=(R, C) is provided, it will be used for construction of
|
| 1017 |
+
the bsr_array/matrix.
|
| 1018 |
+
"""
|
| 1019 |
+
return self.tocsr(copy=False).tobsr(blocksize=blocksize, copy=copy)
|
| 1020 |
+
|
| 1021 |
+
def tocsc(self, copy=False):
|
| 1022 |
+
"""Convert this array/matrix to Compressed Sparse Column format.
|
| 1023 |
+
|
| 1024 |
+
With copy=False, the data/indices may be shared between this array/matrix and
|
| 1025 |
+
the resultant csc_array/matrix.
|
| 1026 |
+
"""
|
| 1027 |
+
return self.tocsr(copy=copy).tocsc(copy=False)
|
| 1028 |
+
|
| 1029 |
+
def copy(self):
|
| 1030 |
+
"""Returns a copy of this array/matrix.
|
| 1031 |
+
|
| 1032 |
+
No data/indices will be shared between the returned value and current
|
| 1033 |
+
array/matrix.
|
| 1034 |
+
"""
|
| 1035 |
+
return self.__class__(self, copy=True)
|
| 1036 |
+
|
| 1037 |
+
def sum(self, axis=None, dtype=None, out=None):
|
| 1038 |
+
"""
|
| 1039 |
+
Sum the array/matrix elements over a given axis.
|
| 1040 |
+
|
| 1041 |
+
Parameters
|
| 1042 |
+
----------
|
| 1043 |
+
axis : {-2, -1, 0, 1, None} optional
|
| 1044 |
+
Axis along which the sum is computed. The default is to
|
| 1045 |
+
compute the sum of all the array/matrix elements, returning a scalar
|
| 1046 |
+
(i.e., `axis` = `None`).
|
| 1047 |
+
dtype : dtype, optional
|
| 1048 |
+
The type of the returned array/matrix and of the accumulator in which
|
| 1049 |
+
the elements are summed. The dtype of `a` is used by default
|
| 1050 |
+
unless `a` has an integer dtype of less precision than the default
|
| 1051 |
+
platform integer. In that case, if `a` is signed then the platform
|
| 1052 |
+
integer is used while if `a` is unsigned then an unsigned integer
|
| 1053 |
+
of the same precision as the platform integer is used.
|
| 1054 |
+
|
| 1055 |
+
.. versionadded:: 0.18.0
|
| 1056 |
+
|
| 1057 |
+
out : np.matrix, optional
|
| 1058 |
+
Alternative output matrix in which to place the result. It must
|
| 1059 |
+
have the same shape as the expected output, but the type of the
|
| 1060 |
+
output values will be cast if necessary.
|
| 1061 |
+
|
| 1062 |
+
.. versionadded:: 0.18.0
|
| 1063 |
+
|
| 1064 |
+
Returns
|
| 1065 |
+
-------
|
| 1066 |
+
sum_along_axis : np.matrix
|
| 1067 |
+
A matrix with the same shape as `self`, with the specified
|
| 1068 |
+
axis removed.
|
| 1069 |
+
|
| 1070 |
+
See Also
|
| 1071 |
+
--------
|
| 1072 |
+
numpy.matrix.sum : NumPy's implementation of 'sum' for matrices
|
| 1073 |
+
|
| 1074 |
+
"""
|
| 1075 |
+
validateaxis(axis)
|
| 1076 |
+
|
| 1077 |
+
# Mimic numpy's casting.
|
| 1078 |
+
res_dtype = get_sum_dtype(self.dtype)
|
| 1079 |
+
|
| 1080 |
+
if self.ndim == 1:
|
| 1081 |
+
if axis not in (None, -1, 0):
|
| 1082 |
+
raise ValueError("axis must be None, -1 or 0")
|
| 1083 |
+
ret = (self @ np.ones(self.shape, dtype=res_dtype)).astype(dtype)
|
| 1084 |
+
|
| 1085 |
+
if out is not None:
|
| 1086 |
+
if any(dim != 1 for dim in out.shape):
|
| 1087 |
+
raise ValueError("dimensions do not match")
|
| 1088 |
+
out[...] = ret
|
| 1089 |
+
return ret
|
| 1090 |
+
|
| 1091 |
+
# We use multiplication by a matrix of ones to achieve this.
|
| 1092 |
+
# For some sparse array formats more efficient methods are
|
| 1093 |
+
# possible -- these should override this function.
|
| 1094 |
+
M, N = self.shape
|
| 1095 |
+
|
| 1096 |
+
if axis is None:
|
| 1097 |
+
# sum over rows and columns
|
| 1098 |
+
return (
|
| 1099 |
+
self @ self._ascontainer(np.ones((N, 1), dtype=res_dtype))
|
| 1100 |
+
).sum(dtype=dtype, out=out)
|
| 1101 |
+
|
| 1102 |
+
if axis < 0:
|
| 1103 |
+
axis += 2
|
| 1104 |
+
|
| 1105 |
+
# axis = 0 or 1 now
|
| 1106 |
+
if axis == 0:
|
| 1107 |
+
# sum over columns
|
| 1108 |
+
ret = self._ascontainer(
|
| 1109 |
+
np.ones((1, M), dtype=res_dtype)
|
| 1110 |
+
) @ self
|
| 1111 |
+
else:
|
| 1112 |
+
# sum over rows
|
| 1113 |
+
ret = self @ self._ascontainer(
|
| 1114 |
+
np.ones((N, 1), dtype=res_dtype)
|
| 1115 |
+
)
|
| 1116 |
+
|
| 1117 |
+
if out is not None and out.shape != ret.shape:
|
| 1118 |
+
raise ValueError("dimensions do not match")
|
| 1119 |
+
|
| 1120 |
+
return ret.sum(axis=axis, dtype=dtype, out=out)
|
| 1121 |
+
|
| 1122 |
+
def mean(self, axis=None, dtype=None, out=None):
|
| 1123 |
+
"""
|
| 1124 |
+
Compute the arithmetic mean along the specified axis.
|
| 1125 |
+
|
| 1126 |
+
Returns the average of the array/matrix elements. The average is taken
|
| 1127 |
+
over all elements in the array/matrix by default, otherwise over the
|
| 1128 |
+
specified axis. `float64` intermediate and return values are used
|
| 1129 |
+
for integer inputs.
|
| 1130 |
+
|
| 1131 |
+
Parameters
|
| 1132 |
+
----------
|
| 1133 |
+
axis : {-2, -1, 0, 1, None} optional
|
| 1134 |
+
Axis along which the mean is computed. The default is to compute
|
| 1135 |
+
the mean of all elements in the array/matrix (i.e., `axis` = `None`).
|
| 1136 |
+
dtype : data-type, optional
|
| 1137 |
+
Type to use in computing the mean. For integer inputs, the default
|
| 1138 |
+
is `float64`; for floating point inputs, it is the same as the
|
| 1139 |
+
input dtype.
|
| 1140 |
+
|
| 1141 |
+
.. versionadded:: 0.18.0
|
| 1142 |
+
|
| 1143 |
+
out : np.matrix, optional
|
| 1144 |
+
Alternative output matrix in which to place the result. It must
|
| 1145 |
+
have the same shape as the expected output, but the type of the
|
| 1146 |
+
output values will be cast if necessary.
|
| 1147 |
+
|
| 1148 |
+
.. versionadded:: 0.18.0
|
| 1149 |
+
|
| 1150 |
+
Returns
|
| 1151 |
+
-------
|
| 1152 |
+
m : np.matrix
|
| 1153 |
+
|
| 1154 |
+
See Also
|
| 1155 |
+
--------
|
| 1156 |
+
numpy.matrix.mean : NumPy's implementation of 'mean' for matrices
|
| 1157 |
+
|
| 1158 |
+
"""
|
| 1159 |
+
validateaxis(axis)
|
| 1160 |
+
|
| 1161 |
+
res_dtype = self.dtype.type
|
| 1162 |
+
integral = (np.issubdtype(self.dtype, np.integer) or
|
| 1163 |
+
np.issubdtype(self.dtype, np.bool_))
|
| 1164 |
+
|
| 1165 |
+
# output dtype
|
| 1166 |
+
if dtype is None:
|
| 1167 |
+
if integral:
|
| 1168 |
+
res_dtype = np.float64
|
| 1169 |
+
else:
|
| 1170 |
+
res_dtype = np.dtype(dtype).type
|
| 1171 |
+
|
| 1172 |
+
# intermediate dtype for summation
|
| 1173 |
+
inter_dtype = np.float64 if integral else res_dtype
|
| 1174 |
+
inter_self = self.astype(inter_dtype)
|
| 1175 |
+
|
| 1176 |
+
if self.ndim == 1:
|
| 1177 |
+
if axis not in (None, -1, 0):
|
| 1178 |
+
raise ValueError("axis must be None, -1 or 0")
|
| 1179 |
+
res = inter_self / self.shape[-1]
|
| 1180 |
+
return res.sum(dtype=res_dtype, out=out)
|
| 1181 |
+
|
| 1182 |
+
if axis is None:
|
| 1183 |
+
return (inter_self / (self.shape[0] * self.shape[1]))\
|
| 1184 |
+
.sum(dtype=res_dtype, out=out)
|
| 1185 |
+
|
| 1186 |
+
if axis < 0:
|
| 1187 |
+
axis += 2
|
| 1188 |
+
|
| 1189 |
+
# axis = 0 or 1 now
|
| 1190 |
+
if axis == 0:
|
| 1191 |
+
return (inter_self * (1.0 / self.shape[0])).sum(
|
| 1192 |
+
axis=0, dtype=res_dtype, out=out)
|
| 1193 |
+
else:
|
| 1194 |
+
return (inter_self * (1.0 / self.shape[1])).sum(
|
| 1195 |
+
axis=1, dtype=res_dtype, out=out)
|
| 1196 |
+
|
| 1197 |
+
def diagonal(self, k=0):
|
| 1198 |
+
"""Returns the kth diagonal of the array/matrix.
|
| 1199 |
+
|
| 1200 |
+
Parameters
|
| 1201 |
+
----------
|
| 1202 |
+
k : int, optional
|
| 1203 |
+
Which diagonal to get, corresponding to elements a[i, i+k].
|
| 1204 |
+
Default: 0 (the main diagonal).
|
| 1205 |
+
|
| 1206 |
+
.. versionadded:: 1.0
|
| 1207 |
+
|
| 1208 |
+
See also
|
| 1209 |
+
--------
|
| 1210 |
+
numpy.diagonal : Equivalent numpy function.
|
| 1211 |
+
|
| 1212 |
+
Examples
|
| 1213 |
+
--------
|
| 1214 |
+
>>> from scipy.sparse import csr_array
|
| 1215 |
+
>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
|
| 1216 |
+
>>> A.diagonal()
|
| 1217 |
+
array([1, 0, 5])
|
| 1218 |
+
>>> A.diagonal(k=1)
|
| 1219 |
+
array([2, 3])
|
| 1220 |
+
"""
|
| 1221 |
+
return self.tocsr().diagonal(k=k)
|
| 1222 |
+
|
| 1223 |
+
def trace(self, offset=0):
|
| 1224 |
+
"""Returns the sum along diagonals of the sparse array/matrix.
|
| 1225 |
+
|
| 1226 |
+
Parameters
|
| 1227 |
+
----------
|
| 1228 |
+
offset : int, optional
|
| 1229 |
+
Which diagonal to get, corresponding to elements a[i, i+offset].
|
| 1230 |
+
Default: 0 (the main diagonal).
|
| 1231 |
+
|
| 1232 |
+
"""
|
| 1233 |
+
return self.diagonal(k=offset).sum()
|
| 1234 |
+
|
| 1235 |
+
def setdiag(self, values, k=0):
|
| 1236 |
+
"""
|
| 1237 |
+
Set diagonal or off-diagonal elements of the array/matrix.
|
| 1238 |
+
|
| 1239 |
+
Parameters
|
| 1240 |
+
----------
|
| 1241 |
+
values : array_like
|
| 1242 |
+
New values of the diagonal elements.
|
| 1243 |
+
|
| 1244 |
+
Values may have any length. If the diagonal is longer than values,
|
| 1245 |
+
then the remaining diagonal entries will not be set. If values are
|
| 1246 |
+
longer than the diagonal, then the remaining values are ignored.
|
| 1247 |
+
|
| 1248 |
+
If a scalar value is given, all of the diagonal is set to it.
|
| 1249 |
+
|
| 1250 |
+
k : int, optional
|
| 1251 |
+
Which off-diagonal to set, corresponding to elements a[i,i+k].
|
| 1252 |
+
Default: 0 (the main diagonal).
|
| 1253 |
+
|
| 1254 |
+
"""
|
| 1255 |
+
M, N = self.shape
|
| 1256 |
+
if (k > 0 and k >= N) or (k < 0 and -k >= M):
|
| 1257 |
+
raise ValueError("k exceeds array dimensions")
|
| 1258 |
+
self._setdiag(np.asarray(values), k)
|
| 1259 |
+
|
| 1260 |
+
def _setdiag(self, values, k):
|
| 1261 |
+
"""This part of the implementation gets overridden by the
|
| 1262 |
+
different formats.
|
| 1263 |
+
"""
|
| 1264 |
+
M, N = self.shape
|
| 1265 |
+
if k < 0:
|
| 1266 |
+
if values.ndim == 0:
|
| 1267 |
+
# broadcast
|
| 1268 |
+
max_index = min(M+k, N)
|
| 1269 |
+
for i in range(max_index):
|
| 1270 |
+
self[i - k, i] = values
|
| 1271 |
+
else:
|
| 1272 |
+
max_index = min(M+k, N, len(values))
|
| 1273 |
+
if max_index <= 0:
|
| 1274 |
+
return
|
| 1275 |
+
for i, v in enumerate(values[:max_index]):
|
| 1276 |
+
self[i - k, i] = v
|
| 1277 |
+
else:
|
| 1278 |
+
if values.ndim == 0:
|
| 1279 |
+
# broadcast
|
| 1280 |
+
max_index = min(M, N-k)
|
| 1281 |
+
for i in range(max_index):
|
| 1282 |
+
self[i, i + k] = values
|
| 1283 |
+
else:
|
| 1284 |
+
max_index = min(M, N-k, len(values))
|
| 1285 |
+
if max_index <= 0:
|
| 1286 |
+
return
|
| 1287 |
+
for i, v in enumerate(values[:max_index]):
|
| 1288 |
+
self[i, i + k] = v
|
| 1289 |
+
|
| 1290 |
+
def _process_toarray_args(self, order, out):
|
| 1291 |
+
if out is not None:
|
| 1292 |
+
if order is not None:
|
| 1293 |
+
raise ValueError('order cannot be specified if out '
|
| 1294 |
+
'is not None')
|
| 1295 |
+
if out.shape != self.shape or out.dtype != self.dtype:
|
| 1296 |
+
raise ValueError('out array must be same dtype and shape as '
|
| 1297 |
+
'sparse array')
|
| 1298 |
+
out[...] = 0.
|
| 1299 |
+
return out
|
| 1300 |
+
else:
|
| 1301 |
+
return np.zeros(self.shape, dtype=self.dtype, order=order)
|
| 1302 |
+
|
| 1303 |
+
def _get_index_dtype(self, arrays=(), maxval=None, check_contents=False):
|
| 1304 |
+
"""
|
| 1305 |
+
Determine index dtype for array.
|
| 1306 |
+
|
| 1307 |
+
This wraps _sputils.get_index_dtype, providing compatibility for both
|
| 1308 |
+
array and matrix API sparse matrices. Matrix API sparse matrices would
|
| 1309 |
+
attempt to downcast the indices - which can be computationally
|
| 1310 |
+
expensive and undesirable for users. The array API changes this
|
| 1311 |
+
behaviour.
|
| 1312 |
+
|
| 1313 |
+
See discussion: https://github.com/scipy/scipy/issues/16774
|
| 1314 |
+
|
| 1315 |
+
The get_index_dtype import is due to implementation details of the test
|
| 1316 |
+
suite. It allows the decorator ``with_64bit_maxval_limit`` to mock a
|
| 1317 |
+
lower int32 max value for checks on the matrix API's downcasting
|
| 1318 |
+
behaviour.
|
| 1319 |
+
"""
|
| 1320 |
+
from ._sputils import get_index_dtype
|
| 1321 |
+
|
| 1322 |
+
# Don't check contents for array API
|
| 1323 |
+
return get_index_dtype(arrays,
|
| 1324 |
+
maxval,
|
| 1325 |
+
(check_contents and not isinstance(self, sparray)))
|
| 1326 |
+
|
| 1327 |
+
|
| 1328 |
+
class sparray:
|
| 1329 |
+
"""A namespace class to separate sparray from spmatrix"""
|
| 1330 |
+
|
| 1331 |
+
|
| 1332 |
+
sparray.__doc__ = _spbase.__doc__
|
| 1333 |
+
|
| 1334 |
+
|
| 1335 |
+
def issparse(x):
|
| 1336 |
+
"""Is `x` of a sparse array or sparse matrix type?
|
| 1337 |
+
|
| 1338 |
+
Parameters
|
| 1339 |
+
----------
|
| 1340 |
+
x
|
| 1341 |
+
object to check for being a sparse array or sparse matrix
|
| 1342 |
+
|
| 1343 |
+
Returns
|
| 1344 |
+
-------
|
| 1345 |
+
bool
|
| 1346 |
+
True if `x` is a sparse array or a sparse matrix, False otherwise
|
| 1347 |
+
|
| 1348 |
+
Examples
|
| 1349 |
+
--------
|
| 1350 |
+
>>> import numpy as np
|
| 1351 |
+
>>> from scipy.sparse import csr_array, csr_matrix, issparse
|
| 1352 |
+
>>> issparse(csr_matrix([[5]]))
|
| 1353 |
+
True
|
| 1354 |
+
>>> issparse(csr_array([[5]]))
|
| 1355 |
+
True
|
| 1356 |
+
>>> issparse(np.array([[5]]))
|
| 1357 |
+
False
|
| 1358 |
+
>>> issparse(5)
|
| 1359 |
+
False
|
| 1360 |
+
"""
|
| 1361 |
+
return isinstance(x, _spbase)
|
| 1362 |
+
|
| 1363 |
+
|
| 1364 |
+
def isspmatrix(x):
|
| 1365 |
+
"""Is `x` of a sparse matrix type?
|
| 1366 |
+
|
| 1367 |
+
Parameters
|
| 1368 |
+
----------
|
| 1369 |
+
x
|
| 1370 |
+
object to check for being a sparse matrix
|
| 1371 |
+
|
| 1372 |
+
Returns
|
| 1373 |
+
-------
|
| 1374 |
+
bool
|
| 1375 |
+
True if `x` is a sparse matrix, False otherwise
|
| 1376 |
+
|
| 1377 |
+
Examples
|
| 1378 |
+
--------
|
| 1379 |
+
>>> import numpy as np
|
| 1380 |
+
>>> from scipy.sparse import csr_array, csr_matrix, isspmatrix
|
| 1381 |
+
>>> isspmatrix(csr_matrix([[5]]))
|
| 1382 |
+
True
|
| 1383 |
+
>>> isspmatrix(csr_array([[5]]))
|
| 1384 |
+
False
|
| 1385 |
+
>>> isspmatrix(np.array([[5]]))
|
| 1386 |
+
False
|
| 1387 |
+
>>> isspmatrix(5)
|
| 1388 |
+
False
|
| 1389 |
+
"""
|
| 1390 |
+
return isinstance(x, spmatrix)
|
parrot/lib/python3.10/site-packages/scipy/sparse/_bsr.py
ADDED
|
@@ -0,0 +1,856 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compressed Block Sparse Row format"""
|
| 2 |
+
|
| 3 |
+
__docformat__ = "restructuredtext en"
|
| 4 |
+
|
| 5 |
+
__all__ = ['bsr_array', 'bsr_matrix', 'isspmatrix_bsr']
|
| 6 |
+
|
| 7 |
+
from warnings import warn
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
from scipy._lib._util import copy_if_needed
|
| 12 |
+
from ._matrix import spmatrix
|
| 13 |
+
from ._data import _data_matrix, _minmax_mixin
|
| 14 |
+
from ._compressed import _cs_matrix
|
| 15 |
+
from ._base import issparse, _formats, _spbase, sparray
|
| 16 |
+
from ._sputils import (isshape, getdtype, getdata, to_native, upcast,
|
| 17 |
+
check_shape)
|
| 18 |
+
from . import _sparsetools
|
| 19 |
+
from ._sparsetools import (bsr_matvec, bsr_matvecs, csr_matmat_maxnnz,
|
| 20 |
+
bsr_matmat, bsr_transpose, bsr_sort_indices,
|
| 21 |
+
bsr_tocsr)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _bsr_base(_cs_matrix, _minmax_mixin):
|
| 25 |
+
_format = 'bsr'
|
| 26 |
+
|
| 27 |
+
def __init__(self, arg1, shape=None, dtype=None, copy=False, blocksize=None):
|
| 28 |
+
_data_matrix.__init__(self, arg1)
|
| 29 |
+
|
| 30 |
+
if issparse(arg1):
|
| 31 |
+
if arg1.format == self.format and copy:
|
| 32 |
+
arg1 = arg1.copy()
|
| 33 |
+
else:
|
| 34 |
+
arg1 = arg1.tobsr(blocksize=blocksize)
|
| 35 |
+
self.indptr, self.indices, self.data, self._shape = (
|
| 36 |
+
arg1.indptr, arg1.indices, arg1.data, arg1._shape
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
elif isinstance(arg1,tuple):
|
| 40 |
+
if isshape(arg1):
|
| 41 |
+
# it's a tuple of matrix dimensions (M,N)
|
| 42 |
+
self._shape = check_shape(arg1)
|
| 43 |
+
M,N = self.shape
|
| 44 |
+
# process blocksize
|
| 45 |
+
if blocksize is None:
|
| 46 |
+
blocksize = (1,1)
|
| 47 |
+
else:
|
| 48 |
+
if not isshape(blocksize):
|
| 49 |
+
raise ValueError('invalid blocksize=%s' % blocksize)
|
| 50 |
+
blocksize = tuple(blocksize)
|
| 51 |
+
self.data = np.zeros((0,) + blocksize, getdtype(dtype, default=float))
|
| 52 |
+
|
| 53 |
+
R,C = blocksize
|
| 54 |
+
if (M % R) != 0 or (N % C) != 0:
|
| 55 |
+
raise ValueError('shape must be multiple of blocksize')
|
| 56 |
+
|
| 57 |
+
# Select index dtype large enough to pass array and
|
| 58 |
+
# scalar parameters to sparsetools
|
| 59 |
+
idx_dtype = self._get_index_dtype(maxval=max(M//R, N//C, R, C))
|
| 60 |
+
self.indices = np.zeros(0, dtype=idx_dtype)
|
| 61 |
+
self.indptr = np.zeros(M//R + 1, dtype=idx_dtype)
|
| 62 |
+
|
| 63 |
+
elif len(arg1) == 2:
|
| 64 |
+
# (data,(row,col)) format
|
| 65 |
+
coo = self._coo_container(arg1, dtype=dtype, shape=shape)
|
| 66 |
+
bsr = coo.tobsr(blocksize=blocksize)
|
| 67 |
+
self.indptr, self.indices, self.data, self._shape = (
|
| 68 |
+
bsr.indptr, bsr.indices, bsr.data, bsr._shape
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
elif len(arg1) == 3:
|
| 72 |
+
# (data,indices,indptr) format
|
| 73 |
+
(data, indices, indptr) = arg1
|
| 74 |
+
|
| 75 |
+
# Select index dtype large enough to pass array and
|
| 76 |
+
# scalar parameters to sparsetools
|
| 77 |
+
maxval = 1
|
| 78 |
+
if shape is not None:
|
| 79 |
+
maxval = max(shape)
|
| 80 |
+
if blocksize is not None:
|
| 81 |
+
maxval = max(maxval, max(blocksize))
|
| 82 |
+
idx_dtype = self._get_index_dtype((indices, indptr), maxval=maxval,
|
| 83 |
+
check_contents=True)
|
| 84 |
+
if not copy:
|
| 85 |
+
copy = copy_if_needed
|
| 86 |
+
self.indices = np.array(indices, copy=copy, dtype=idx_dtype)
|
| 87 |
+
self.indptr = np.array(indptr, copy=copy, dtype=idx_dtype)
|
| 88 |
+
self.data = getdata(data, copy=copy, dtype=dtype)
|
| 89 |
+
if self.data.ndim != 3:
|
| 90 |
+
raise ValueError(
|
| 91 |
+
f'BSR data must be 3-dimensional, got shape={self.data.shape}'
|
| 92 |
+
)
|
| 93 |
+
if blocksize is not None:
|
| 94 |
+
if not isshape(blocksize):
|
| 95 |
+
raise ValueError(f'invalid blocksize={blocksize}')
|
| 96 |
+
if tuple(blocksize) != self.data.shape[1:]:
|
| 97 |
+
raise ValueError(
|
| 98 |
+
f'mismatching blocksize={blocksize}'
|
| 99 |
+
f' vs {self.data.shape[1:]}'
|
| 100 |
+
)
|
| 101 |
+
else:
|
| 102 |
+
raise ValueError('unrecognized bsr_array constructor usage')
|
| 103 |
+
else:
|
| 104 |
+
# must be dense
|
| 105 |
+
try:
|
| 106 |
+
arg1 = np.asarray(arg1)
|
| 107 |
+
except Exception as e:
|
| 108 |
+
raise ValueError("unrecognized form for"
|
| 109 |
+
" %s_matrix constructor" % self.format) from e
|
| 110 |
+
if isinstance(self, sparray) and arg1.ndim != 2:
|
| 111 |
+
raise ValueError(f"BSR arrays don't support {arg1.ndim}D input. Use 2D")
|
| 112 |
+
arg1 = self._coo_container(arg1, dtype=dtype).tobsr(blocksize=blocksize)
|
| 113 |
+
self.indptr, self.indices, self.data, self._shape = (
|
| 114 |
+
arg1.indptr, arg1.indices, arg1.data, arg1._shape
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
if shape is not None:
|
| 118 |
+
self._shape = check_shape(shape)
|
| 119 |
+
else:
|
| 120 |
+
if self.shape is None:
|
| 121 |
+
# shape not already set, try to infer dimensions
|
| 122 |
+
try:
|
| 123 |
+
M = len(self.indptr) - 1
|
| 124 |
+
N = self.indices.max() + 1
|
| 125 |
+
except Exception as e:
|
| 126 |
+
raise ValueError('unable to infer matrix dimensions') from e
|
| 127 |
+
else:
|
| 128 |
+
R,C = self.blocksize
|
| 129 |
+
self._shape = check_shape((M*R,N*C))
|
| 130 |
+
|
| 131 |
+
if self.shape is None:
|
| 132 |
+
if shape is None:
|
| 133 |
+
# TODO infer shape here
|
| 134 |
+
raise ValueError('need to infer shape')
|
| 135 |
+
else:
|
| 136 |
+
self._shape = check_shape(shape)
|
| 137 |
+
|
| 138 |
+
if dtype is not None:
|
| 139 |
+
self.data = self.data.astype(dtype, copy=False)
|
| 140 |
+
|
| 141 |
+
self.check_format(full_check=False)
|
| 142 |
+
|
| 143 |
+
def check_format(self, full_check=True):
|
| 144 |
+
"""Check whether the array/matrix respects the BSR format.
|
| 145 |
+
|
| 146 |
+
Parameters
|
| 147 |
+
----------
|
| 148 |
+
full_check : bool, optional
|
| 149 |
+
If `True`, run rigorous check, scanning arrays for valid values.
|
| 150 |
+
Note that activating those check might copy arrays for casting,
|
| 151 |
+
modifying indices and index pointers' inplace.
|
| 152 |
+
If `False`, run basic checks on attributes. O(1) operations.
|
| 153 |
+
Default is `True`.
|
| 154 |
+
"""
|
| 155 |
+
M,N = self.shape
|
| 156 |
+
R,C = self.blocksize
|
| 157 |
+
|
| 158 |
+
# index arrays should have integer data types
|
| 159 |
+
if self.indptr.dtype.kind != 'i':
|
| 160 |
+
warn(f"indptr array has non-integer dtype ({self.indptr.dtype.name})",
|
| 161 |
+
stacklevel=2)
|
| 162 |
+
if self.indices.dtype.kind != 'i':
|
| 163 |
+
warn(f"indices array has non-integer dtype ({self.indices.dtype.name})",
|
| 164 |
+
stacklevel=2)
|
| 165 |
+
|
| 166 |
+
# check array shapes
|
| 167 |
+
if self.indices.ndim != 1 or self.indptr.ndim != 1:
|
| 168 |
+
raise ValueError("indices, and indptr should be 1-D")
|
| 169 |
+
if self.data.ndim != 3:
|
| 170 |
+
raise ValueError("data should be 3-D")
|
| 171 |
+
|
| 172 |
+
# check index pointer
|
| 173 |
+
if (len(self.indptr) != M//R + 1):
|
| 174 |
+
raise ValueError("index pointer size (%d) should be (%d)" %
|
| 175 |
+
(len(self.indptr), M//R + 1))
|
| 176 |
+
if (self.indptr[0] != 0):
|
| 177 |
+
raise ValueError("index pointer should start with 0")
|
| 178 |
+
|
| 179 |
+
# check index and data arrays
|
| 180 |
+
if (len(self.indices) != len(self.data)):
|
| 181 |
+
raise ValueError("indices and data should have the same size")
|
| 182 |
+
if (self.indptr[-1] > len(self.indices)):
|
| 183 |
+
raise ValueError("Last value of index pointer should be less than "
|
| 184 |
+
"the size of index and data arrays")
|
| 185 |
+
|
| 186 |
+
self.prune()
|
| 187 |
+
|
| 188 |
+
if full_check:
|
| 189 |
+
# check format validity (more expensive)
|
| 190 |
+
if self.nnz > 0:
|
| 191 |
+
if self.indices.max() >= N//C:
|
| 192 |
+
raise ValueError("column index values must be < %d (now max %d)"
|
| 193 |
+
% (N//C, self.indices.max()))
|
| 194 |
+
if self.indices.min() < 0:
|
| 195 |
+
raise ValueError("column index values must be >= 0")
|
| 196 |
+
if np.diff(self.indptr).min() < 0:
|
| 197 |
+
raise ValueError("index pointer values must form a "
|
| 198 |
+
"non-decreasing sequence")
|
| 199 |
+
|
| 200 |
+
idx_dtype = self._get_index_dtype((self.indices, self.indptr))
|
| 201 |
+
self.indptr = np.asarray(self.indptr, dtype=idx_dtype)
|
| 202 |
+
self.indices = np.asarray(self.indices, dtype=idx_dtype)
|
| 203 |
+
self.data = to_native(self.data)
|
| 204 |
+
# if not self.has_sorted_indices():
|
| 205 |
+
# warn('Indices were not in sorted order. Sorting indices.')
|
| 206 |
+
# self.sort_indices(check_first=False)
|
| 207 |
+
|
| 208 |
+
@property
|
| 209 |
+
def blocksize(self) -> tuple:
|
| 210 |
+
"""Block size of the matrix."""
|
| 211 |
+
return self.data.shape[1:]
|
| 212 |
+
|
| 213 |
+
def _getnnz(self, axis=None):
|
| 214 |
+
if axis is not None:
|
| 215 |
+
raise NotImplementedError("_getnnz over an axis is not implemented "
|
| 216 |
+
"for BSR format")
|
| 217 |
+
R,C = self.blocksize
|
| 218 |
+
return int(self.indptr[-1] * R * C)
|
| 219 |
+
|
| 220 |
+
_getnnz.__doc__ = _spbase._getnnz.__doc__
|
| 221 |
+
|
| 222 |
+
def __repr__(self):
|
| 223 |
+
_, fmt = _formats[self.format]
|
| 224 |
+
sparse_cls = 'array' if isinstance(self, sparray) else 'matrix'
|
| 225 |
+
b = 'x'.join(str(x) for x in self.blocksize)
|
| 226 |
+
return (
|
| 227 |
+
f"<{fmt} sparse {sparse_cls} of dtype '{self.dtype}'\n"
|
| 228 |
+
f"\twith {self.nnz} stored elements (blocksize={b}) and shape {self.shape}>"
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
def diagonal(self, k=0):
|
| 232 |
+
rows, cols = self.shape
|
| 233 |
+
if k <= -rows or k >= cols:
|
| 234 |
+
return np.empty(0, dtype=self.data.dtype)
|
| 235 |
+
R, C = self.blocksize
|
| 236 |
+
y = np.zeros(min(rows + min(k, 0), cols - max(k, 0)),
|
| 237 |
+
dtype=upcast(self.dtype))
|
| 238 |
+
_sparsetools.bsr_diagonal(k, rows // R, cols // C, R, C,
|
| 239 |
+
self.indptr, self.indices,
|
| 240 |
+
np.ravel(self.data), y)
|
| 241 |
+
return y
|
| 242 |
+
|
| 243 |
+
diagonal.__doc__ = _spbase.diagonal.__doc__
|
| 244 |
+
|
| 245 |
+
##########################
|
| 246 |
+
# NotImplemented methods #
|
| 247 |
+
##########################
|
| 248 |
+
|
| 249 |
+
def __getitem__(self,key):
|
| 250 |
+
raise NotImplementedError
|
| 251 |
+
|
| 252 |
+
def __setitem__(self,key,val):
|
| 253 |
+
raise NotImplementedError
|
| 254 |
+
|
| 255 |
+
######################
|
| 256 |
+
# Arithmetic methods #
|
| 257 |
+
######################
|
| 258 |
+
|
| 259 |
+
def _add_dense(self, other):
|
| 260 |
+
return self.tocoo(copy=False)._add_dense(other)
|
| 261 |
+
|
| 262 |
+
def _matmul_vector(self, other):
|
| 263 |
+
M,N = self.shape
|
| 264 |
+
R,C = self.blocksize
|
| 265 |
+
|
| 266 |
+
result = np.zeros(self.shape[0], dtype=upcast(self.dtype, other.dtype))
|
| 267 |
+
|
| 268 |
+
bsr_matvec(M//R, N//C, R, C,
|
| 269 |
+
self.indptr, self.indices, self.data.ravel(),
|
| 270 |
+
other, result)
|
| 271 |
+
|
| 272 |
+
return result
|
| 273 |
+
|
| 274 |
+
def _matmul_multivector(self,other):
|
| 275 |
+
R,C = self.blocksize
|
| 276 |
+
M,N = self.shape
|
| 277 |
+
n_vecs = other.shape[1] # number of column vectors
|
| 278 |
+
|
| 279 |
+
result = np.zeros((M,n_vecs), dtype=upcast(self.dtype,other.dtype))
|
| 280 |
+
|
| 281 |
+
bsr_matvecs(M//R, N//C, n_vecs, R, C,
|
| 282 |
+
self.indptr, self.indices, self.data.ravel(),
|
| 283 |
+
other.ravel(), result.ravel())
|
| 284 |
+
|
| 285 |
+
return result
|
| 286 |
+
|
| 287 |
+
def _matmul_sparse(self, other):
|
| 288 |
+
M, K1 = self.shape
|
| 289 |
+
K2, N = other.shape
|
| 290 |
+
|
| 291 |
+
R,n = self.blocksize
|
| 292 |
+
|
| 293 |
+
# convert to this format
|
| 294 |
+
if other.format == "bsr":
|
| 295 |
+
C = other.blocksize[1]
|
| 296 |
+
else:
|
| 297 |
+
C = 1
|
| 298 |
+
|
| 299 |
+
if other.format == "csr" and n == 1:
|
| 300 |
+
other = other.tobsr(blocksize=(n,C), copy=False) # lightweight conversion
|
| 301 |
+
else:
|
| 302 |
+
other = other.tobsr(blocksize=(n,C))
|
| 303 |
+
|
| 304 |
+
idx_dtype = self._get_index_dtype((self.indptr, self.indices,
|
| 305 |
+
other.indptr, other.indices))
|
| 306 |
+
|
| 307 |
+
bnnz = csr_matmat_maxnnz(M//R, N//C,
|
| 308 |
+
self.indptr.astype(idx_dtype),
|
| 309 |
+
self.indices.astype(idx_dtype),
|
| 310 |
+
other.indptr.astype(idx_dtype),
|
| 311 |
+
other.indices.astype(idx_dtype))
|
| 312 |
+
|
| 313 |
+
idx_dtype = self._get_index_dtype((self.indptr, self.indices,
|
| 314 |
+
other.indptr, other.indices),
|
| 315 |
+
maxval=bnnz)
|
| 316 |
+
indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
|
| 317 |
+
indices = np.empty(bnnz, dtype=idx_dtype)
|
| 318 |
+
data = np.empty(R*C*bnnz, dtype=upcast(self.dtype,other.dtype))
|
| 319 |
+
|
| 320 |
+
bsr_matmat(bnnz, M//R, N//C, R, C, n,
|
| 321 |
+
self.indptr.astype(idx_dtype),
|
| 322 |
+
self.indices.astype(idx_dtype),
|
| 323 |
+
np.ravel(self.data),
|
| 324 |
+
other.indptr.astype(idx_dtype),
|
| 325 |
+
other.indices.astype(idx_dtype),
|
| 326 |
+
np.ravel(other.data),
|
| 327 |
+
indptr,
|
| 328 |
+
indices,
|
| 329 |
+
data)
|
| 330 |
+
|
| 331 |
+
data = data.reshape(-1,R,C)
|
| 332 |
+
|
| 333 |
+
# TODO eliminate zeros
|
| 334 |
+
|
| 335 |
+
return self._bsr_container(
|
| 336 |
+
(data, indices, indptr), shape=(M, N), blocksize=(R, C)
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
######################
|
| 340 |
+
# Conversion methods #
|
| 341 |
+
######################
|
| 342 |
+
|
| 343 |
+
def tobsr(self, blocksize=None, copy=False):
|
| 344 |
+
"""Convert this array/matrix into Block Sparse Row Format.
|
| 345 |
+
|
| 346 |
+
With copy=False, the data/indices may be shared between this
|
| 347 |
+
array/matrix and the resultant bsr_array/bsr_matrix.
|
| 348 |
+
|
| 349 |
+
If blocksize=(R, C) is provided, it will be used for determining
|
| 350 |
+
block size of the bsr_array/bsr_matrix.
|
| 351 |
+
"""
|
| 352 |
+
if blocksize not in [None, self.blocksize]:
|
| 353 |
+
return self.tocsr().tobsr(blocksize=blocksize)
|
| 354 |
+
if copy:
|
| 355 |
+
return self.copy()
|
| 356 |
+
else:
|
| 357 |
+
return self
|
| 358 |
+
|
| 359 |
+
def tocsr(self, copy=False):
|
| 360 |
+
M, N = self.shape
|
| 361 |
+
R, C = self.blocksize
|
| 362 |
+
nnz = self.nnz
|
| 363 |
+
idx_dtype = self._get_index_dtype((self.indptr, self.indices),
|
| 364 |
+
maxval=max(nnz, N))
|
| 365 |
+
indptr = np.empty(M + 1, dtype=idx_dtype)
|
| 366 |
+
indices = np.empty(nnz, dtype=idx_dtype)
|
| 367 |
+
data = np.empty(nnz, dtype=upcast(self.dtype))
|
| 368 |
+
|
| 369 |
+
bsr_tocsr(M // R, # n_brow
|
| 370 |
+
N // C, # n_bcol
|
| 371 |
+
R, C,
|
| 372 |
+
self.indptr.astype(idx_dtype, copy=False),
|
| 373 |
+
self.indices.astype(idx_dtype, copy=False),
|
| 374 |
+
self.data,
|
| 375 |
+
indptr,
|
| 376 |
+
indices,
|
| 377 |
+
data)
|
| 378 |
+
return self._csr_container((data, indices, indptr), shape=self.shape)
|
| 379 |
+
|
| 380 |
+
tocsr.__doc__ = _spbase.tocsr.__doc__
|
| 381 |
+
|
| 382 |
+
def tocsc(self, copy=False):
|
| 383 |
+
return self.tocsr(copy=False).tocsc(copy=copy)
|
| 384 |
+
|
| 385 |
+
tocsc.__doc__ = _spbase.tocsc.__doc__
|
| 386 |
+
|
| 387 |
+
def tocoo(self, copy=True):
|
| 388 |
+
"""Convert this array/matrix to COOrdinate format.
|
| 389 |
+
|
| 390 |
+
When copy=False the data array will be shared between
|
| 391 |
+
this array/matrix and the resultant coo_array/coo_matrix.
|
| 392 |
+
"""
|
| 393 |
+
|
| 394 |
+
M,N = self.shape
|
| 395 |
+
R,C = self.blocksize
|
| 396 |
+
|
| 397 |
+
indptr_diff = np.diff(self.indptr)
|
| 398 |
+
if indptr_diff.dtype.itemsize > np.dtype(np.intp).itemsize:
|
| 399 |
+
# Check for potential overflow
|
| 400 |
+
indptr_diff_limited = indptr_diff.astype(np.intp)
|
| 401 |
+
if np.any(indptr_diff_limited != indptr_diff):
|
| 402 |
+
raise ValueError("Matrix too big to convert")
|
| 403 |
+
indptr_diff = indptr_diff_limited
|
| 404 |
+
|
| 405 |
+
idx_dtype = self._get_index_dtype(maxval=max(M, N))
|
| 406 |
+
row = (R * np.arange(M//R, dtype=idx_dtype)).repeat(indptr_diff)
|
| 407 |
+
row = row.repeat(R*C).reshape(-1,R,C)
|
| 408 |
+
row += np.tile(np.arange(R, dtype=idx_dtype).reshape(-1,1), (1,C))
|
| 409 |
+
row = row.reshape(-1)
|
| 410 |
+
|
| 411 |
+
col = ((C * self.indices).astype(idx_dtype, copy=False)
|
| 412 |
+
.repeat(R*C).reshape(-1,R,C))
|
| 413 |
+
col += np.tile(np.arange(C, dtype=idx_dtype), (R,1))
|
| 414 |
+
col = col.reshape(-1)
|
| 415 |
+
|
| 416 |
+
data = self.data.reshape(-1)
|
| 417 |
+
|
| 418 |
+
if copy:
|
| 419 |
+
data = data.copy()
|
| 420 |
+
|
| 421 |
+
return self._coo_container(
|
| 422 |
+
(data, (row, col)), shape=self.shape
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
def toarray(self, order=None, out=None):
|
| 426 |
+
return self.tocoo(copy=False).toarray(order=order, out=out)
|
| 427 |
+
|
| 428 |
+
toarray.__doc__ = _spbase.toarray.__doc__
|
| 429 |
+
|
| 430 |
+
def transpose(self, axes=None, copy=False):
|
| 431 |
+
if axes is not None and axes != (1, 0):
|
| 432 |
+
raise ValueError("Sparse matrices do not support "
|
| 433 |
+
"an 'axes' parameter because swapping "
|
| 434 |
+
"dimensions is the only logical permutation.")
|
| 435 |
+
|
| 436 |
+
R, C = self.blocksize
|
| 437 |
+
M, N = self.shape
|
| 438 |
+
NBLK = self.nnz//(R*C)
|
| 439 |
+
|
| 440 |
+
if self.nnz == 0:
|
| 441 |
+
return self._bsr_container((N, M), blocksize=(C, R),
|
| 442 |
+
dtype=self.dtype, copy=copy)
|
| 443 |
+
|
| 444 |
+
indptr = np.empty(N//C + 1, dtype=self.indptr.dtype)
|
| 445 |
+
indices = np.empty(NBLK, dtype=self.indices.dtype)
|
| 446 |
+
data = np.empty((NBLK, C, R), dtype=self.data.dtype)
|
| 447 |
+
|
| 448 |
+
bsr_transpose(M//R, N//C, R, C,
|
| 449 |
+
self.indptr, self.indices, self.data.ravel(),
|
| 450 |
+
indptr, indices, data.ravel())
|
| 451 |
+
|
| 452 |
+
return self._bsr_container((data, indices, indptr),
|
| 453 |
+
shape=(N, M), copy=copy)
|
| 454 |
+
|
| 455 |
+
transpose.__doc__ = _spbase.transpose.__doc__
|
| 456 |
+
|
| 457 |
+
##############################################################
|
| 458 |
+
# methods that examine or modify the internal data structure #
|
| 459 |
+
##############################################################
|
| 460 |
+
|
| 461 |
+
def eliminate_zeros(self):
|
| 462 |
+
"""Remove zero elements in-place."""
|
| 463 |
+
|
| 464 |
+
if not self.nnz:
|
| 465 |
+
return # nothing to do
|
| 466 |
+
|
| 467 |
+
R,C = self.blocksize
|
| 468 |
+
M,N = self.shape
|
| 469 |
+
|
| 470 |
+
mask = (self.data != 0).reshape(-1,R*C).sum(axis=1) # nonzero blocks
|
| 471 |
+
|
| 472 |
+
nonzero_blocks = mask.nonzero()[0]
|
| 473 |
+
|
| 474 |
+
self.data[:len(nonzero_blocks)] = self.data[nonzero_blocks]
|
| 475 |
+
|
| 476 |
+
# modifies self.indptr and self.indices *in place*
|
| 477 |
+
_sparsetools.csr_eliminate_zeros(M//R, N//C, self.indptr,
|
| 478 |
+
self.indices, mask)
|
| 479 |
+
self.prune()
|
| 480 |
+
|
| 481 |
+
def sum_duplicates(self):
|
| 482 |
+
"""Eliminate duplicate array/matrix entries by adding them together
|
| 483 |
+
|
| 484 |
+
The is an *in place* operation
|
| 485 |
+
"""
|
| 486 |
+
if self.has_canonical_format:
|
| 487 |
+
return
|
| 488 |
+
self.sort_indices()
|
| 489 |
+
R, C = self.blocksize
|
| 490 |
+
M, N = self.shape
|
| 491 |
+
|
| 492 |
+
# port of _sparsetools.csr_sum_duplicates
|
| 493 |
+
n_row = M // R
|
| 494 |
+
nnz = 0
|
| 495 |
+
row_end = 0
|
| 496 |
+
for i in range(n_row):
|
| 497 |
+
jj = row_end
|
| 498 |
+
row_end = self.indptr[i+1]
|
| 499 |
+
while jj < row_end:
|
| 500 |
+
j = self.indices[jj]
|
| 501 |
+
x = self.data[jj]
|
| 502 |
+
jj += 1
|
| 503 |
+
while jj < row_end and self.indices[jj] == j:
|
| 504 |
+
x += self.data[jj]
|
| 505 |
+
jj += 1
|
| 506 |
+
self.indices[nnz] = j
|
| 507 |
+
self.data[nnz] = x
|
| 508 |
+
nnz += 1
|
| 509 |
+
self.indptr[i+1] = nnz
|
| 510 |
+
|
| 511 |
+
self.prune() # nnz may have changed
|
| 512 |
+
self.has_canonical_format = True
|
| 513 |
+
|
| 514 |
+
def sort_indices(self):
|
| 515 |
+
"""Sort the indices of this array/matrix *in place*
|
| 516 |
+
"""
|
| 517 |
+
if self.has_sorted_indices:
|
| 518 |
+
return
|
| 519 |
+
|
| 520 |
+
R,C = self.blocksize
|
| 521 |
+
M,N = self.shape
|
| 522 |
+
|
| 523 |
+
bsr_sort_indices(M//R, N//C, R, C, self.indptr, self.indices, self.data.ravel())
|
| 524 |
+
|
| 525 |
+
self.has_sorted_indices = True
|
| 526 |
+
|
| 527 |
+
def prune(self):
|
| 528 |
+
"""Remove empty space after all non-zero elements.
|
| 529 |
+
"""
|
| 530 |
+
|
| 531 |
+
R,C = self.blocksize
|
| 532 |
+
M,N = self.shape
|
| 533 |
+
|
| 534 |
+
if len(self.indptr) != M//R + 1:
|
| 535 |
+
raise ValueError("index pointer has invalid length")
|
| 536 |
+
|
| 537 |
+
bnnz = self.indptr[-1]
|
| 538 |
+
|
| 539 |
+
if len(self.indices) < bnnz:
|
| 540 |
+
raise ValueError("indices array has too few elements")
|
| 541 |
+
if len(self.data) < bnnz:
|
| 542 |
+
raise ValueError("data array has too few elements")
|
| 543 |
+
|
| 544 |
+
self.data = self.data[:bnnz]
|
| 545 |
+
self.indices = self.indices[:bnnz]
|
| 546 |
+
|
| 547 |
+
# utility functions
|
| 548 |
+
def _binopt(self, other, op, in_shape=None, out_shape=None):
|
| 549 |
+
"""Apply the binary operation fn to two sparse matrices."""
|
| 550 |
+
|
| 551 |
+
# Ideally we'd take the GCDs of the blocksize dimensions
|
| 552 |
+
# and explode self and other to match.
|
| 553 |
+
other = self.__class__(other, blocksize=self.blocksize)
|
| 554 |
+
|
| 555 |
+
# e.g. bsr_plus_bsr, etc.
|
| 556 |
+
fn = getattr(_sparsetools, self.format + op + self.format)
|
| 557 |
+
|
| 558 |
+
R,C = self.blocksize
|
| 559 |
+
|
| 560 |
+
max_bnnz = len(self.data) + len(other.data)
|
| 561 |
+
idx_dtype = self._get_index_dtype((self.indptr, self.indices,
|
| 562 |
+
other.indptr, other.indices),
|
| 563 |
+
maxval=max_bnnz)
|
| 564 |
+
indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
|
| 565 |
+
indices = np.empty(max_bnnz, dtype=idx_dtype)
|
| 566 |
+
|
| 567 |
+
bool_ops = ['_ne_', '_lt_', '_gt_', '_le_', '_ge_']
|
| 568 |
+
if op in bool_ops:
|
| 569 |
+
data = np.empty(R*C*max_bnnz, dtype=np.bool_)
|
| 570 |
+
else:
|
| 571 |
+
data = np.empty(R*C*max_bnnz, dtype=upcast(self.dtype,other.dtype))
|
| 572 |
+
|
| 573 |
+
fn(self.shape[0]//R, self.shape[1]//C, R, C,
|
| 574 |
+
self.indptr.astype(idx_dtype),
|
| 575 |
+
self.indices.astype(idx_dtype),
|
| 576 |
+
self.data,
|
| 577 |
+
other.indptr.astype(idx_dtype),
|
| 578 |
+
other.indices.astype(idx_dtype),
|
| 579 |
+
np.ravel(other.data),
|
| 580 |
+
indptr,
|
| 581 |
+
indices,
|
| 582 |
+
data)
|
| 583 |
+
|
| 584 |
+
actual_bnnz = indptr[-1]
|
| 585 |
+
indices = indices[:actual_bnnz]
|
| 586 |
+
data = data[:R*C*actual_bnnz]
|
| 587 |
+
|
| 588 |
+
if actual_bnnz < max_bnnz/2:
|
| 589 |
+
indices = indices.copy()
|
| 590 |
+
data = data.copy()
|
| 591 |
+
|
| 592 |
+
data = data.reshape(-1,R,C)
|
| 593 |
+
|
| 594 |
+
return self.__class__((data, indices, indptr), shape=self.shape)
|
| 595 |
+
|
| 596 |
+
# needed by _data_matrix
|
| 597 |
+
def _with_data(self,data,copy=True):
|
| 598 |
+
"""Returns a matrix with the same sparsity structure as self,
|
| 599 |
+
but with different data. By default the structure arrays
|
| 600 |
+
(i.e. .indptr and .indices) are copied.
|
| 601 |
+
"""
|
| 602 |
+
if copy:
|
| 603 |
+
return self.__class__((data,self.indices.copy(),self.indptr.copy()),
|
| 604 |
+
shape=self.shape,dtype=data.dtype)
|
| 605 |
+
else:
|
| 606 |
+
return self.__class__((data,self.indices,self.indptr),
|
| 607 |
+
shape=self.shape,dtype=data.dtype)
|
| 608 |
+
|
| 609 |
+
# # these functions are used by the parent class
|
| 610 |
+
# # to remove redundancy between bsc_matrix and bsr_matrix
|
| 611 |
+
# def _swap(self,x):
|
| 612 |
+
# """swap the members of x if this is a column-oriented matrix
|
| 613 |
+
# """
|
| 614 |
+
# return (x[0],x[1])
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
def isspmatrix_bsr(x):
|
| 618 |
+
"""Is `x` of a bsr_matrix type?
|
| 619 |
+
|
| 620 |
+
Parameters
|
| 621 |
+
----------
|
| 622 |
+
x
|
| 623 |
+
object to check for being a bsr matrix
|
| 624 |
+
|
| 625 |
+
Returns
|
| 626 |
+
-------
|
| 627 |
+
bool
|
| 628 |
+
True if `x` is a bsr matrix, False otherwise
|
| 629 |
+
|
| 630 |
+
Examples
|
| 631 |
+
--------
|
| 632 |
+
>>> from scipy.sparse import bsr_array, bsr_matrix, csr_matrix, isspmatrix_bsr
|
| 633 |
+
>>> isspmatrix_bsr(bsr_matrix([[5]]))
|
| 634 |
+
True
|
| 635 |
+
>>> isspmatrix_bsr(bsr_array([[5]]))
|
| 636 |
+
False
|
| 637 |
+
>>> isspmatrix_bsr(csr_matrix([[5]]))
|
| 638 |
+
False
|
| 639 |
+
"""
|
| 640 |
+
return isinstance(x, bsr_matrix)
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
# This namespace class separates array from matrix with isinstance
|
| 644 |
+
class bsr_array(_bsr_base, sparray):
|
| 645 |
+
"""
|
| 646 |
+
Block Sparse Row format sparse array.
|
| 647 |
+
|
| 648 |
+
This can be instantiated in several ways:
|
| 649 |
+
bsr_array(D, [blocksize=(R,C)])
|
| 650 |
+
where D is a 2-D ndarray.
|
| 651 |
+
|
| 652 |
+
bsr_array(S, [blocksize=(R,C)])
|
| 653 |
+
with another sparse array or matrix S (equivalent to S.tobsr())
|
| 654 |
+
|
| 655 |
+
bsr_array((M, N), [blocksize=(R,C), dtype])
|
| 656 |
+
to construct an empty sparse array with shape (M, N)
|
| 657 |
+
dtype is optional, defaulting to dtype='d'.
|
| 658 |
+
|
| 659 |
+
bsr_array((data, ij), [blocksize=(R,C), shape=(M, N)])
|
| 660 |
+
where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``
|
| 661 |
+
|
| 662 |
+
bsr_array((data, indices, indptr), [shape=(M, N)])
|
| 663 |
+
is the standard BSR representation where the block column
|
| 664 |
+
indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]``
|
| 665 |
+
and their corresponding block values are stored in
|
| 666 |
+
``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not
|
| 667 |
+
supplied, the array dimensions are inferred from the index arrays.
|
| 668 |
+
|
| 669 |
+
Attributes
|
| 670 |
+
----------
|
| 671 |
+
dtype : dtype
|
| 672 |
+
Data type of the array
|
| 673 |
+
shape : 2-tuple
|
| 674 |
+
Shape of the array
|
| 675 |
+
ndim : int
|
| 676 |
+
Number of dimensions (this is always 2)
|
| 677 |
+
nnz
|
| 678 |
+
size
|
| 679 |
+
data
|
| 680 |
+
BSR format data array of the array
|
| 681 |
+
indices
|
| 682 |
+
BSR format index array of the array
|
| 683 |
+
indptr
|
| 684 |
+
BSR format index pointer array of the array
|
| 685 |
+
blocksize
|
| 686 |
+
Block size
|
| 687 |
+
has_sorted_indices : bool
|
| 688 |
+
Whether indices are sorted
|
| 689 |
+
has_canonical_format : bool
|
| 690 |
+
T
|
| 691 |
+
|
| 692 |
+
Notes
|
| 693 |
+
-----
|
| 694 |
+
Sparse arrays can be used in arithmetic operations: they support
|
| 695 |
+
addition, subtraction, multiplication, division, and matrix power.
|
| 696 |
+
|
| 697 |
+
**Summary of BSR format**
|
| 698 |
+
|
| 699 |
+
The Block Sparse Row (BSR) format is very similar to the Compressed
|
| 700 |
+
Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense
|
| 701 |
+
sub matrices like the last example below. Such sparse block matrices often
|
| 702 |
+
arise in vector-valued finite element discretizations. In such cases, BSR is
|
| 703 |
+
considerably more efficient than CSR and CSC for many sparse arithmetic
|
| 704 |
+
operations.
|
| 705 |
+
|
| 706 |
+
**Blocksize**
|
| 707 |
+
|
| 708 |
+
The blocksize (R,C) must evenly divide the shape of the sparse array (M,N).
|
| 709 |
+
That is, R and C must satisfy the relationship ``M % R = 0`` and
|
| 710 |
+
``N % C = 0``.
|
| 711 |
+
|
| 712 |
+
If no blocksize is specified, a simple heuristic is applied to determine
|
| 713 |
+
an appropriate blocksize.
|
| 714 |
+
|
| 715 |
+
**Canonical Format**
|
| 716 |
+
|
| 717 |
+
In canonical format, there are no duplicate blocks and indices are sorted
|
| 718 |
+
per row.
|
| 719 |
+
|
| 720 |
+
Examples
|
| 721 |
+
--------
|
| 722 |
+
>>> import numpy as np
|
| 723 |
+
>>> from scipy.sparse import bsr_array
|
| 724 |
+
>>> bsr_array((3, 4), dtype=np.int8).toarray()
|
| 725 |
+
array([[0, 0, 0, 0],
|
| 726 |
+
[0, 0, 0, 0],
|
| 727 |
+
[0, 0, 0, 0]], dtype=int8)
|
| 728 |
+
|
| 729 |
+
>>> row = np.array([0, 0, 1, 2, 2, 2])
|
| 730 |
+
>>> col = np.array([0, 2, 2, 0, 1, 2])
|
| 731 |
+
>>> data = np.array([1, 2, 3 ,4, 5, 6])
|
| 732 |
+
>>> bsr_array((data, (row, col)), shape=(3, 3)).toarray()
|
| 733 |
+
array([[1, 0, 2],
|
| 734 |
+
[0, 0, 3],
|
| 735 |
+
[4, 5, 6]])
|
| 736 |
+
|
| 737 |
+
>>> indptr = np.array([0, 2, 3, 6])
|
| 738 |
+
>>> indices = np.array([0, 2, 2, 0, 1, 2])
|
| 739 |
+
>>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
|
| 740 |
+
>>> bsr_array((data,indices,indptr), shape=(6, 6)).toarray()
|
| 741 |
+
array([[1, 1, 0, 0, 2, 2],
|
| 742 |
+
[1, 1, 0, 0, 2, 2],
|
| 743 |
+
[0, 0, 0, 0, 3, 3],
|
| 744 |
+
[0, 0, 0, 0, 3, 3],
|
| 745 |
+
[4, 4, 5, 5, 6, 6],
|
| 746 |
+
[4, 4, 5, 5, 6, 6]])
|
| 747 |
+
|
| 748 |
+
"""
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
class bsr_matrix(spmatrix, _bsr_base):
|
| 752 |
+
"""
|
| 753 |
+
Block Sparse Row format sparse matrix.
|
| 754 |
+
|
| 755 |
+
This can be instantiated in several ways:
|
| 756 |
+
bsr_matrix(D, [blocksize=(R,C)])
|
| 757 |
+
where D is a 2-D ndarray.
|
| 758 |
+
|
| 759 |
+
bsr_matrix(S, [blocksize=(R,C)])
|
| 760 |
+
with another sparse array or matrix S (equivalent to S.tobsr())
|
| 761 |
+
|
| 762 |
+
bsr_matrix((M, N), [blocksize=(R,C), dtype])
|
| 763 |
+
to construct an empty sparse matrix with shape (M, N)
|
| 764 |
+
dtype is optional, defaulting to dtype='d'.
|
| 765 |
+
|
| 766 |
+
bsr_matrix((data, ij), [blocksize=(R,C), shape=(M, N)])
|
| 767 |
+
where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``
|
| 768 |
+
|
| 769 |
+
bsr_matrix((data, indices, indptr), [shape=(M, N)])
|
| 770 |
+
is the standard BSR representation where the block column
|
| 771 |
+
indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]``
|
| 772 |
+
and their corresponding block values are stored in
|
| 773 |
+
``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not
|
| 774 |
+
supplied, the matrix dimensions are inferred from the index arrays.
|
| 775 |
+
|
| 776 |
+
Attributes
|
| 777 |
+
----------
|
| 778 |
+
dtype : dtype
|
| 779 |
+
Data type of the matrix
|
| 780 |
+
shape : 2-tuple
|
| 781 |
+
Shape of the matrix
|
| 782 |
+
ndim : int
|
| 783 |
+
Number of dimensions (this is always 2)
|
| 784 |
+
nnz
|
| 785 |
+
size
|
| 786 |
+
data
|
| 787 |
+
BSR format data array of the matrix
|
| 788 |
+
indices
|
| 789 |
+
BSR format index array of the matrix
|
| 790 |
+
indptr
|
| 791 |
+
BSR format index pointer array of the matrix
|
| 792 |
+
blocksize
|
| 793 |
+
Block size
|
| 794 |
+
has_sorted_indices : bool
|
| 795 |
+
Whether indices are sorted
|
| 796 |
+
has_canonical_format : bool
|
| 797 |
+
T
|
| 798 |
+
|
| 799 |
+
Notes
|
| 800 |
+
-----
|
| 801 |
+
Sparse matrices can be used in arithmetic operations: they support
|
| 802 |
+
addition, subtraction, multiplication, division, and matrix power.
|
| 803 |
+
|
| 804 |
+
**Summary of BSR format**
|
| 805 |
+
|
| 806 |
+
The Block Sparse Row (BSR) format is very similar to the Compressed
|
| 807 |
+
Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense
|
| 808 |
+
sub matrices like the last example below. Such sparse block matrices often
|
| 809 |
+
arise in vector-valued finite element discretizations. In such cases, BSR is
|
| 810 |
+
considerably more efficient than CSR and CSC for many sparse arithmetic
|
| 811 |
+
operations.
|
| 812 |
+
|
| 813 |
+
**Blocksize**
|
| 814 |
+
|
| 815 |
+
The blocksize (R,C) must evenly divide the shape of the sparse matrix (M,N).
|
| 816 |
+
That is, R and C must satisfy the relationship ``M % R = 0`` and
|
| 817 |
+
``N % C = 0``.
|
| 818 |
+
|
| 819 |
+
If no blocksize is specified, a simple heuristic is applied to determine
|
| 820 |
+
an appropriate blocksize.
|
| 821 |
+
|
| 822 |
+
**Canonical Format**
|
| 823 |
+
|
| 824 |
+
In canonical format, there are no duplicate blocks and indices are sorted
|
| 825 |
+
per row.
|
| 826 |
+
|
| 827 |
+
Examples
|
| 828 |
+
--------
|
| 829 |
+
>>> import numpy as np
|
| 830 |
+
>>> from scipy.sparse import bsr_matrix
|
| 831 |
+
>>> bsr_matrix((3, 4), dtype=np.int8).toarray()
|
| 832 |
+
array([[0, 0, 0, 0],
|
| 833 |
+
[0, 0, 0, 0],
|
| 834 |
+
[0, 0, 0, 0]], dtype=int8)
|
| 835 |
+
|
| 836 |
+
>>> row = np.array([0, 0, 1, 2, 2, 2])
|
| 837 |
+
>>> col = np.array([0, 2, 2, 0, 1, 2])
|
| 838 |
+
>>> data = np.array([1, 2, 3 ,4, 5, 6])
|
| 839 |
+
>>> bsr_matrix((data, (row, col)), shape=(3, 3)).toarray()
|
| 840 |
+
array([[1, 0, 2],
|
| 841 |
+
[0, 0, 3],
|
| 842 |
+
[4, 5, 6]])
|
| 843 |
+
|
| 844 |
+
>>> indptr = np.array([0, 2, 3, 6])
|
| 845 |
+
>>> indices = np.array([0, 2, 2, 0, 1, 2])
|
| 846 |
+
>>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
|
| 847 |
+
>>> bsr_matrix((data,indices,indptr), shape=(6, 6)).toarray()
|
| 848 |
+
array([[1, 1, 0, 0, 2, 2],
|
| 849 |
+
[1, 1, 0, 0, 2, 2],
|
| 850 |
+
[0, 0, 0, 0, 3, 3],
|
| 851 |
+
[0, 0, 0, 0, 3, 3],
|
| 852 |
+
[4, 4, 5, 5, 6, 6],
|
| 853 |
+
[4, 4, 5, 5, 6, 6]])
|
| 854 |
+
|
| 855 |
+
"""
|
| 856 |
+
|
parrot/lib/python3.10/site-packages/scipy/sparse/_compressed.py
ADDED
|
@@ -0,0 +1,1463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base class for sparse matrix formats using compressed storage."""
|
| 2 |
+
__all__ = []
|
| 3 |
+
|
| 4 |
+
from warnings import warn
|
| 5 |
+
import operator
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
from scipy._lib._util import _prune_array, copy_if_needed
|
| 9 |
+
|
| 10 |
+
from ._base import _spbase, issparse, sparray, SparseEfficiencyWarning
|
| 11 |
+
from ._data import _data_matrix, _minmax_mixin
|
| 12 |
+
from . import _sparsetools
|
| 13 |
+
from ._sparsetools import (get_csr_submatrix, csr_sample_offsets, csr_todense,
|
| 14 |
+
csr_sample_values, csr_row_index, csr_row_slice,
|
| 15 |
+
csr_column_index1, csr_column_index2)
|
| 16 |
+
from ._index import IndexMixin
|
| 17 |
+
from ._sputils import (upcast, upcast_char, to_native, isdense, isshape,
|
| 18 |
+
getdtype, isscalarlike, isintlike, downcast_intp_index,
|
| 19 |
+
get_sum_dtype, check_shape, is_pydata_spmatrix)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class _cs_matrix(_data_matrix, _minmax_mixin, IndexMixin):
|
| 23 |
+
"""
|
| 24 |
+
base array/matrix class for compressed row- and column-oriented arrays/matrices
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, arg1, shape=None, dtype=None, copy=False):
|
| 28 |
+
_data_matrix.__init__(self, arg1)
|
| 29 |
+
is_array = isinstance(self, sparray)
|
| 30 |
+
|
| 31 |
+
if issparse(arg1):
|
| 32 |
+
if arg1.format == self.format and copy:
|
| 33 |
+
arg1 = arg1.copy()
|
| 34 |
+
else:
|
| 35 |
+
arg1 = arg1.asformat(self.format)
|
| 36 |
+
self.indptr, self.indices, self.data, self._shape = (
|
| 37 |
+
arg1.indptr, arg1.indices, arg1.data, arg1._shape
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
elif isinstance(arg1, tuple):
|
| 41 |
+
if isshape(arg1, allow_1d=is_array):
|
| 42 |
+
# It's a tuple of matrix dimensions (M, N)
|
| 43 |
+
# create empty matrix
|
| 44 |
+
self._shape = check_shape(arg1, allow_1d=is_array)
|
| 45 |
+
M, N = self._swap(self._shape_as_2d)
|
| 46 |
+
# Select index dtype large enough to pass array and
|
| 47 |
+
# scalar parameters to sparsetools
|
| 48 |
+
idx_dtype = self._get_index_dtype(maxval=max(self.shape))
|
| 49 |
+
self.data = np.zeros(0, getdtype(dtype, default=float))
|
| 50 |
+
self.indices = np.zeros(0, idx_dtype)
|
| 51 |
+
self.indptr = np.zeros(M + 1, dtype=idx_dtype)
|
| 52 |
+
else:
|
| 53 |
+
if len(arg1) == 2:
|
| 54 |
+
# (data, ij) format
|
| 55 |
+
coo = self._coo_container(arg1, shape=shape, dtype=dtype)
|
| 56 |
+
arrays = coo._coo_to_compressed(self._swap)
|
| 57 |
+
self.indptr, self.indices, self.data, self._shape = arrays
|
| 58 |
+
self.sum_duplicates()
|
| 59 |
+
elif len(arg1) == 3:
|
| 60 |
+
# (data, indices, indptr) format
|
| 61 |
+
(data, indices, indptr) = arg1
|
| 62 |
+
|
| 63 |
+
# Select index dtype large enough to pass array and
|
| 64 |
+
# scalar parameters to sparsetools
|
| 65 |
+
maxval = None
|
| 66 |
+
if shape is not None and 0 not in shape:
|
| 67 |
+
maxval = max(shape)
|
| 68 |
+
idx_dtype = self._get_index_dtype((indices, indptr),
|
| 69 |
+
maxval=maxval,
|
| 70 |
+
check_contents=True)
|
| 71 |
+
|
| 72 |
+
if not copy:
|
| 73 |
+
copy = copy_if_needed
|
| 74 |
+
self.indices = np.array(indices, copy=copy, dtype=idx_dtype)
|
| 75 |
+
self.indptr = np.array(indptr, copy=copy, dtype=idx_dtype)
|
| 76 |
+
self.data = np.array(data, copy=copy, dtype=dtype)
|
| 77 |
+
else:
|
| 78 |
+
raise ValueError(f"unrecognized {self.__class__.__name__} "
|
| 79 |
+
f"constructor input: {arg1}")
|
| 80 |
+
|
| 81 |
+
else:
|
| 82 |
+
# must be dense
|
| 83 |
+
try:
|
| 84 |
+
arg1 = np.asarray(arg1)
|
| 85 |
+
except Exception as e:
|
| 86 |
+
raise ValueError(f"unrecognized {self.__class__.__name__} "
|
| 87 |
+
f"constructor input: {arg1}") from e
|
| 88 |
+
if isinstance(self, sparray) and arg1.ndim < 2 and self.format == "csc":
|
| 89 |
+
raise ValueError(
|
| 90 |
+
f"CSC arrays don't support {arg1.ndim}D input. Use 2D"
|
| 91 |
+
)
|
| 92 |
+
coo = self._coo_container(arg1, dtype=dtype)
|
| 93 |
+
arrays = coo._coo_to_compressed(self._swap)
|
| 94 |
+
self.indptr, self.indices, self.data, self._shape = arrays
|
| 95 |
+
|
| 96 |
+
# Read matrix dimensions given, if any
|
| 97 |
+
if shape is not None:
|
| 98 |
+
self._shape = check_shape(shape, allow_1d=is_array)
|
| 99 |
+
elif self.shape is None:
|
| 100 |
+
# shape not already set, try to infer dimensions
|
| 101 |
+
try:
|
| 102 |
+
major_d = len(self.indptr) - 1
|
| 103 |
+
minor_d = self.indices.max() + 1
|
| 104 |
+
except Exception as e:
|
| 105 |
+
raise ValueError('unable to infer matrix dimensions') from e
|
| 106 |
+
|
| 107 |
+
self._shape = check_shape(self._swap((major_d, minor_d)), allow_1d=is_array)
|
| 108 |
+
|
| 109 |
+
if dtype is not None:
|
| 110 |
+
self.data = self.data.astype(dtype, copy=False)
|
| 111 |
+
|
| 112 |
+
self.check_format(full_check=False)
|
| 113 |
+
|
| 114 |
+
def _getnnz(self, axis=None):
|
| 115 |
+
if axis is None:
|
| 116 |
+
return int(self.indptr[-1])
|
| 117 |
+
elif self.ndim == 1:
|
| 118 |
+
if axis in (0, -1):
|
| 119 |
+
return int(self.indptr[-1])
|
| 120 |
+
raise ValueError('axis out of bounds')
|
| 121 |
+
else:
|
| 122 |
+
if axis < 0:
|
| 123 |
+
axis += 2
|
| 124 |
+
axis, _ = self._swap((axis, 1 - axis))
|
| 125 |
+
_, N = self._swap(self.shape)
|
| 126 |
+
if axis == 0:
|
| 127 |
+
return np.bincount(downcast_intp_index(self.indices),
|
| 128 |
+
minlength=N)
|
| 129 |
+
elif axis == 1:
|
| 130 |
+
return np.diff(self.indptr)
|
| 131 |
+
raise ValueError('axis out of bounds')
|
| 132 |
+
|
| 133 |
+
_getnnz.__doc__ = _spbase._getnnz.__doc__
|
| 134 |
+
|
| 135 |
+
def check_format(self, full_check=True):
|
| 136 |
+
"""Check whether the array/matrix respects the CSR or CSC format.
|
| 137 |
+
|
| 138 |
+
Parameters
|
| 139 |
+
----------
|
| 140 |
+
full_check : bool, optional
|
| 141 |
+
If `True`, run rigorous check, scanning arrays for valid values.
|
| 142 |
+
Note that activating those check might copy arrays for casting,
|
| 143 |
+
modifying indices and index pointers' inplace.
|
| 144 |
+
If `False`, run basic checks on attributes. O(1) operations.
|
| 145 |
+
Default is `True`.
|
| 146 |
+
"""
|
| 147 |
+
# index arrays should have integer data types
|
| 148 |
+
if self.indptr.dtype.kind != 'i':
|
| 149 |
+
warn(f"indptr array has non-integer dtype ({self.indptr.dtype.name})",
|
| 150 |
+
stacklevel=3)
|
| 151 |
+
if self.indices.dtype.kind != 'i':
|
| 152 |
+
warn(f"indices array has non-integer dtype ({self.indices.dtype.name})",
|
| 153 |
+
stacklevel=3)
|
| 154 |
+
|
| 155 |
+
# check array shapes
|
| 156 |
+
for x in [self.data.ndim, self.indices.ndim, self.indptr.ndim]:
|
| 157 |
+
if x != 1:
|
| 158 |
+
raise ValueError('data, indices, and indptr should be 1-D')
|
| 159 |
+
|
| 160 |
+
# check index pointer. Use _swap to determine proper bounds
|
| 161 |
+
M, N = self._swap(self._shape_as_2d)
|
| 162 |
+
|
| 163 |
+
if (len(self.indptr) != M + 1):
|
| 164 |
+
raise ValueError(f"index pointer size {len(self.indptr)} should be {M + 1}")
|
| 165 |
+
if (self.indptr[0] != 0):
|
| 166 |
+
raise ValueError("index pointer should start with 0")
|
| 167 |
+
|
| 168 |
+
# check index and data arrays
|
| 169 |
+
if (len(self.indices) != len(self.data)):
|
| 170 |
+
raise ValueError("indices and data should have the same size")
|
| 171 |
+
if (self.indptr[-1] > len(self.indices)):
|
| 172 |
+
raise ValueError("Last value of index pointer should be less than "
|
| 173 |
+
"the size of index and data arrays")
|
| 174 |
+
|
| 175 |
+
self.prune()
|
| 176 |
+
|
| 177 |
+
if full_check:
|
| 178 |
+
# check format validity (more expensive)
|
| 179 |
+
if self.nnz > 0:
|
| 180 |
+
if self.indices.max() >= N:
|
| 181 |
+
raise ValueError(f"indices must be < {N}")
|
| 182 |
+
if self.indices.min() < 0:
|
| 183 |
+
raise ValueError("indices must be >= 0")
|
| 184 |
+
if np.diff(self.indptr).min() < 0:
|
| 185 |
+
raise ValueError("indptr must be a non-decreasing sequence")
|
| 186 |
+
|
| 187 |
+
idx_dtype = self._get_index_dtype((self.indptr, self.indices))
|
| 188 |
+
self.indptr = np.asarray(self.indptr, dtype=idx_dtype)
|
| 189 |
+
self.indices = np.asarray(self.indices, dtype=idx_dtype)
|
| 190 |
+
self.data = to_native(self.data)
|
| 191 |
+
|
| 192 |
+
# if not self.has_sorted_indices():
|
| 193 |
+
# warn('Indices were not in sorted order. Sorting indices.')
|
| 194 |
+
# self.sort_indices()
|
| 195 |
+
# assert(self.has_sorted_indices())
|
| 196 |
+
# TODO check for duplicates?
|
| 197 |
+
|
| 198 |
+
#######################
|
| 199 |
+
# Boolean comparisons #
|
| 200 |
+
#######################
|
| 201 |
+
|
| 202 |
+
def _scalar_binopt(self, other, op):
|
| 203 |
+
"""Scalar version of self._binopt, for cases in which no new nonzeros
|
| 204 |
+
are added. Produces a new sparse array in canonical form.
|
| 205 |
+
"""
|
| 206 |
+
self.sum_duplicates()
|
| 207 |
+
res = self._with_data(op(self.data, other), copy=True)
|
| 208 |
+
res.eliminate_zeros()
|
| 209 |
+
return res
|
| 210 |
+
|
| 211 |
+
def __eq__(self, other):
|
| 212 |
+
# Scalar other.
|
| 213 |
+
if isscalarlike(other):
|
| 214 |
+
if np.isnan(other):
|
| 215 |
+
return self.__class__(self.shape, dtype=np.bool_)
|
| 216 |
+
|
| 217 |
+
if other == 0:
|
| 218 |
+
warn("Comparing a sparse matrix with 0 using == is inefficient"
|
| 219 |
+
", try using != instead.", SparseEfficiencyWarning,
|
| 220 |
+
stacklevel=3)
|
| 221 |
+
all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
|
| 222 |
+
inv = self._scalar_binopt(other, operator.ne)
|
| 223 |
+
return all_true - inv
|
| 224 |
+
else:
|
| 225 |
+
return self._scalar_binopt(other, operator.eq)
|
| 226 |
+
# Dense other.
|
| 227 |
+
elif isdense(other):
|
| 228 |
+
return self.todense() == other
|
| 229 |
+
# Pydata sparse other.
|
| 230 |
+
elif is_pydata_spmatrix(other):
|
| 231 |
+
return NotImplemented
|
| 232 |
+
# Sparse other.
|
| 233 |
+
elif issparse(other):
|
| 234 |
+
warn("Comparing sparse matrices using == is inefficient, try using"
|
| 235 |
+
" != instead.", SparseEfficiencyWarning, stacklevel=3)
|
| 236 |
+
# TODO sparse broadcasting
|
| 237 |
+
if self.shape != other.shape:
|
| 238 |
+
return False
|
| 239 |
+
elif self.format != other.format:
|
| 240 |
+
other = other.asformat(self.format)
|
| 241 |
+
res = self._binopt(other, '_ne_')
|
| 242 |
+
all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
|
| 243 |
+
return all_true - res
|
| 244 |
+
else:
|
| 245 |
+
return NotImplemented
|
| 246 |
+
|
| 247 |
+
def __ne__(self, other):
|
| 248 |
+
# Scalar other.
|
| 249 |
+
if isscalarlike(other):
|
| 250 |
+
if np.isnan(other):
|
| 251 |
+
warn("Comparing a sparse matrix with nan using != is"
|
| 252 |
+
" inefficient", SparseEfficiencyWarning, stacklevel=3)
|
| 253 |
+
all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
|
| 254 |
+
return all_true
|
| 255 |
+
elif other != 0:
|
| 256 |
+
warn("Comparing a sparse matrix with a nonzero scalar using !="
|
| 257 |
+
" is inefficient, try using == instead.",
|
| 258 |
+
SparseEfficiencyWarning, stacklevel=3)
|
| 259 |
+
all_true = self.__class__(np.ones(self.shape), dtype=np.bool_)
|
| 260 |
+
inv = self._scalar_binopt(other, operator.eq)
|
| 261 |
+
return all_true - inv
|
| 262 |
+
else:
|
| 263 |
+
return self._scalar_binopt(other, operator.ne)
|
| 264 |
+
# Dense other.
|
| 265 |
+
elif isdense(other):
|
| 266 |
+
return self.todense() != other
|
| 267 |
+
# Pydata sparse other.
|
| 268 |
+
elif is_pydata_spmatrix(other):
|
| 269 |
+
return NotImplemented
|
| 270 |
+
# Sparse other.
|
| 271 |
+
elif issparse(other):
|
| 272 |
+
# TODO sparse broadcasting
|
| 273 |
+
if self.shape != other.shape:
|
| 274 |
+
return True
|
| 275 |
+
elif self.format != other.format:
|
| 276 |
+
other = other.asformat(self.format)
|
| 277 |
+
return self._binopt(other, '_ne_')
|
| 278 |
+
else:
|
| 279 |
+
return NotImplemented
|
| 280 |
+
|
| 281 |
+
def _inequality(self, other, op, op_name, bad_scalar_msg):
|
| 282 |
+
# Scalar other.
|
| 283 |
+
if isscalarlike(other):
|
| 284 |
+
if 0 == other and op_name in ('_le_', '_ge_'):
|
| 285 |
+
raise NotImplementedError(" >= and <= don't work with 0.")
|
| 286 |
+
elif op(0, other):
|
| 287 |
+
warn(bad_scalar_msg, SparseEfficiencyWarning, stacklevel=3)
|
| 288 |
+
other_arr = np.empty(self.shape, dtype=np.result_type(other))
|
| 289 |
+
other_arr.fill(other)
|
| 290 |
+
other_arr = self.__class__(other_arr)
|
| 291 |
+
return self._binopt(other_arr, op_name)
|
| 292 |
+
else:
|
| 293 |
+
return self._scalar_binopt(other, op)
|
| 294 |
+
# Dense other.
|
| 295 |
+
elif isdense(other):
|
| 296 |
+
return op(self.todense(), other)
|
| 297 |
+
# Sparse other.
|
| 298 |
+
elif issparse(other):
|
| 299 |
+
# TODO sparse broadcasting
|
| 300 |
+
if self.shape != other.shape:
|
| 301 |
+
raise ValueError("inconsistent shapes")
|
| 302 |
+
elif self.format != other.format:
|
| 303 |
+
other = other.asformat(self.format)
|
| 304 |
+
if op_name not in ('_ge_', '_le_'):
|
| 305 |
+
return self._binopt(other, op_name)
|
| 306 |
+
|
| 307 |
+
warn("Comparing sparse matrices using >= and <= is inefficient, "
|
| 308 |
+
"using <, >, or !=, instead.",
|
| 309 |
+
SparseEfficiencyWarning, stacklevel=3)
|
| 310 |
+
all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
|
| 311 |
+
res = self._binopt(other, '_gt_' if op_name == '_le_' else '_lt_')
|
| 312 |
+
return all_true - res
|
| 313 |
+
else:
|
| 314 |
+
return NotImplemented
|
| 315 |
+
|
| 316 |
+
def __lt__(self, other):
|
| 317 |
+
return self._inequality(other, operator.lt, '_lt_',
|
| 318 |
+
"Comparing a sparse matrix with a scalar "
|
| 319 |
+
"greater than zero using < is inefficient, "
|
| 320 |
+
"try using >= instead.")
|
| 321 |
+
|
| 322 |
+
def __gt__(self, other):
|
| 323 |
+
return self._inequality(other, operator.gt, '_gt_',
|
| 324 |
+
"Comparing a sparse matrix with a scalar "
|
| 325 |
+
"less than zero using > is inefficient, "
|
| 326 |
+
"try using <= instead.")
|
| 327 |
+
|
| 328 |
+
def __le__(self, other):
|
| 329 |
+
return self._inequality(other, operator.le, '_le_',
|
| 330 |
+
"Comparing a sparse matrix with a scalar "
|
| 331 |
+
"greater than zero using <= is inefficient, "
|
| 332 |
+
"try using > instead.")
|
| 333 |
+
|
| 334 |
+
def __ge__(self, other):
|
| 335 |
+
return self._inequality(other, operator.ge, '_ge_',
|
| 336 |
+
"Comparing a sparse matrix with a scalar "
|
| 337 |
+
"less than zero using >= is inefficient, "
|
| 338 |
+
"try using < instead.")
|
| 339 |
+
|
| 340 |
+
#################################
|
| 341 |
+
# Arithmetic operator overrides #
|
| 342 |
+
#################################
|
| 343 |
+
|
| 344 |
+
def _add_dense(self, other):
|
| 345 |
+
if other.shape != self.shape:
|
| 346 |
+
raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})')
|
| 347 |
+
dtype = upcast_char(self.dtype.char, other.dtype.char)
|
| 348 |
+
order = self._swap('CF')[0]
|
| 349 |
+
result = np.array(other, dtype=dtype, order=order, copy=True)
|
| 350 |
+
y = result if result.flags.c_contiguous else result.T
|
| 351 |
+
M, N = self._swap(self._shape_as_2d)
|
| 352 |
+
csr_todense(M, N, self.indptr, self.indices, self.data, y)
|
| 353 |
+
return self._container(result, copy=False)
|
| 354 |
+
|
| 355 |
+
def _add_sparse(self, other):
|
| 356 |
+
return self._binopt(other, '_plus_')
|
| 357 |
+
|
| 358 |
+
def _sub_sparse(self, other):
|
| 359 |
+
return self._binopt(other, '_minus_')
|
| 360 |
+
|
| 361 |
+
def multiply(self, other):
|
| 362 |
+
"""Point-wise multiplication by array/matrix, vector, or scalar."""
|
| 363 |
+
# Scalar multiplication.
|
| 364 |
+
if isscalarlike(other):
|
| 365 |
+
return self._mul_scalar(other)
|
| 366 |
+
# Sparse matrix or vector.
|
| 367 |
+
if issparse(other):
|
| 368 |
+
if self.shape == other.shape:
|
| 369 |
+
other = self.__class__(other)
|
| 370 |
+
return self._binopt(other, '_elmul_')
|
| 371 |
+
# Single element.
|
| 372 |
+
if other.shape == (1, 1):
|
| 373 |
+
result = self._mul_scalar(other.toarray()[0, 0])
|
| 374 |
+
if self.ndim == 1:
|
| 375 |
+
return result.reshape((1, self.shape[0]))
|
| 376 |
+
return result
|
| 377 |
+
if other.shape == (1,):
|
| 378 |
+
return self._mul_scalar(other.toarray()[0])
|
| 379 |
+
if self.shape in ((1,), (1, 1)):
|
| 380 |
+
return other._mul_scalar(self.data.sum())
|
| 381 |
+
|
| 382 |
+
# broadcast. treat 1d like a row
|
| 383 |
+
sM, sN = self._shape_as_2d
|
| 384 |
+
oM, oN = other._shape_as_2d
|
| 385 |
+
# A row times a column.
|
| 386 |
+
if sM == 1 and oN == 1:
|
| 387 |
+
return other._matmul_sparse(self.reshape(sM, sN).tocsc())
|
| 388 |
+
if sN == 1 and oM == 1:
|
| 389 |
+
return self._matmul_sparse(other.reshape(oM, oN).tocsc())
|
| 390 |
+
|
| 391 |
+
is_array = isinstance(self, sparray)
|
| 392 |
+
# Other is a row.
|
| 393 |
+
if oM == 1 and sN == oN:
|
| 394 |
+
new_other = _make_diagonal_csr(other.toarray().ravel(), is_array)
|
| 395 |
+
result = self._matmul_sparse(new_other)
|
| 396 |
+
return result if self.ndim == 2 else result.reshape((1, oN))
|
| 397 |
+
# self is a row.
|
| 398 |
+
if sM == 1 and sN == oN:
|
| 399 |
+
copy = _make_diagonal_csr(self.toarray().ravel(), is_array)
|
| 400 |
+
return other._matmul_sparse(copy)
|
| 401 |
+
|
| 402 |
+
# Other is a column.
|
| 403 |
+
if oN == 1 and sM == oM:
|
| 404 |
+
new_other = _make_diagonal_csr(other.toarray().ravel(), is_array)
|
| 405 |
+
return new_other._matmul_sparse(self)
|
| 406 |
+
# self is a column.
|
| 407 |
+
if sN == 1 and sM == oM:
|
| 408 |
+
new_self = _make_diagonal_csr(self.toarray().ravel(), is_array)
|
| 409 |
+
return new_self._matmul_sparse(other)
|
| 410 |
+
raise ValueError("inconsistent shapes")
|
| 411 |
+
|
| 412 |
+
# Assume other is a dense matrix/array, which produces a single-item
|
| 413 |
+
# object array if other isn't convertible to ndarray.
|
| 414 |
+
other = np.asanyarray(other)
|
| 415 |
+
|
| 416 |
+
if other.ndim > 2:
|
| 417 |
+
return np.multiply(self.toarray(), other)
|
| 418 |
+
# Single element / wrapped object.
|
| 419 |
+
if other.size == 1:
|
| 420 |
+
if other.dtype == np.object_:
|
| 421 |
+
# 'other' not convertible to ndarray.
|
| 422 |
+
return NotImplemented
|
| 423 |
+
bshape = np.broadcast_shapes(self.shape, other.shape)
|
| 424 |
+
return self._mul_scalar(other.flat[0]).reshape(bshape)
|
| 425 |
+
# Fast case for trivial sparse matrix.
|
| 426 |
+
if self.shape in ((1,), (1, 1)):
|
| 427 |
+
bshape = np.broadcast_shapes(self.shape, other.shape)
|
| 428 |
+
return np.multiply(self.data.sum(), other).reshape(bshape)
|
| 429 |
+
|
| 430 |
+
ret = self.tocoo()
|
| 431 |
+
# Matching shapes.
|
| 432 |
+
if self.shape == other.shape:
|
| 433 |
+
data = np.multiply(ret.data, other[ret.coords])
|
| 434 |
+
ret.data = data.view(np.ndarray).ravel()
|
| 435 |
+
return ret
|
| 436 |
+
|
| 437 |
+
# convert other to 2d
|
| 438 |
+
other2d = np.atleast_2d(other)
|
| 439 |
+
# Sparse row vector times...
|
| 440 |
+
if self.shape[0] == 1 or self.ndim == 1:
|
| 441 |
+
if other2d.shape[1] == 1: # Dense column vector.
|
| 442 |
+
data = np.multiply(ret.data, other2d)
|
| 443 |
+
elif other2d.shape[1] == self.shape[-1]: # Dense 2d matrix.
|
| 444 |
+
data = np.multiply(ret.data, other2d[:, ret.col])
|
| 445 |
+
else:
|
| 446 |
+
raise ValueError("inconsistent shapes")
|
| 447 |
+
row = np.repeat(np.arange(other2d.shape[0]), ret.nnz)
|
| 448 |
+
col = np.tile(ret.col, other2d.shape[0])
|
| 449 |
+
return self._coo_container(
|
| 450 |
+
(data.view(np.ndarray).ravel(), (row, col)),
|
| 451 |
+
shape=(other2d.shape[0], self.shape[-1]),
|
| 452 |
+
copy=False
|
| 453 |
+
)
|
| 454 |
+
# Sparse column vector times...
|
| 455 |
+
if self.shape[1] == 1:
|
| 456 |
+
if other2d.shape[0] == 1: # Dense row vector.
|
| 457 |
+
data = np.multiply(ret.data[:, None], other2d)
|
| 458 |
+
elif other2d.shape[0] == self.shape[0]: # Dense 2d array.
|
| 459 |
+
data = np.multiply(ret.data[:, None], other2d[ret.row])
|
| 460 |
+
else:
|
| 461 |
+
raise ValueError("inconsistent shapes")
|
| 462 |
+
row = np.repeat(ret.row, other2d.shape[1])
|
| 463 |
+
col = np.tile(np.arange(other2d.shape[1]), len(ret.col))
|
| 464 |
+
return self._coo_container(
|
| 465 |
+
(data.view(np.ndarray).ravel(), (row, col)),
|
| 466 |
+
shape=(self.shape[0], other2d.shape[1]),
|
| 467 |
+
copy=False
|
| 468 |
+
)
|
| 469 |
+
# Sparse matrix times dense row vector.
|
| 470 |
+
if other2d.shape[0] == 1 and self.shape[1] == other2d.shape[1]:
|
| 471 |
+
data = np.multiply(ret.data, other2d[:, ret.col].ravel())
|
| 472 |
+
# Sparse matrix times dense column vector.
|
| 473 |
+
elif other2d.shape[1] == 1 and self.shape[0] == other2d.shape[0]:
|
| 474 |
+
data = np.multiply(ret.data, other2d[ret.row].ravel())
|
| 475 |
+
else:
|
| 476 |
+
raise ValueError("inconsistent shapes")
|
| 477 |
+
ret.data = data.view(np.ndarray).ravel()
|
| 478 |
+
return ret
|
| 479 |
+
|
| 480 |
+
###########################
|
| 481 |
+
# Multiplication handlers #
|
| 482 |
+
###########################
|
| 483 |
+
|
| 484 |
+
def _matmul_vector(self, other):
|
| 485 |
+
M, N = self._shape_as_2d
|
| 486 |
+
|
| 487 |
+
# output array
|
| 488 |
+
result = np.zeros(M, dtype=upcast_char(self.dtype.char, other.dtype.char))
|
| 489 |
+
|
| 490 |
+
# csr_matvec or csc_matvec
|
| 491 |
+
fn = getattr(_sparsetools, self.format + '_matvec')
|
| 492 |
+
fn(M, N, self.indptr, self.indices, self.data, other, result)
|
| 493 |
+
|
| 494 |
+
return result[0] if self.ndim == 1 else result
|
| 495 |
+
|
| 496 |
+
def _matmul_multivector(self, other):
|
| 497 |
+
M, N = self._shape_as_2d
|
| 498 |
+
n_vecs = other.shape[-1] # number of column vectors
|
| 499 |
+
|
| 500 |
+
result = np.zeros((M, n_vecs),
|
| 501 |
+
dtype=upcast_char(self.dtype.char, other.dtype.char))
|
| 502 |
+
|
| 503 |
+
# csr_matvecs or csc_matvecs
|
| 504 |
+
fn = getattr(_sparsetools, self.format + '_matvecs')
|
| 505 |
+
fn(M, N, n_vecs, self.indptr, self.indices, self.data,
|
| 506 |
+
other.ravel(), result.ravel())
|
| 507 |
+
|
| 508 |
+
if self.ndim == 1:
|
| 509 |
+
return result.reshape((n_vecs,))
|
| 510 |
+
return result
|
| 511 |
+
|
| 512 |
+
def _matmul_sparse(self, other):
|
| 513 |
+
M, K1 = self._shape_as_2d
|
| 514 |
+
# if other is 1d, treat as a **column**
|
| 515 |
+
o_ndim = other.ndim
|
| 516 |
+
if o_ndim == 1:
|
| 517 |
+
# convert 1d array to a 2d column when on the right of @
|
| 518 |
+
other = other.reshape((1, other.shape[0])).T # Note: converts to CSC
|
| 519 |
+
K2, N = other._shape
|
| 520 |
+
|
| 521 |
+
# find new_shape: (M, N), (M,), (N,) or ()
|
| 522 |
+
new_shape = ()
|
| 523 |
+
if self.ndim == 2:
|
| 524 |
+
new_shape += (M,)
|
| 525 |
+
if o_ndim == 2:
|
| 526 |
+
new_shape += (N,)
|
| 527 |
+
|
| 528 |
+
major_dim = self._swap((M, N))[0]
|
| 529 |
+
other = self.__class__(other) # convert to this format
|
| 530 |
+
|
| 531 |
+
idx_dtype = self._get_index_dtype((self.indptr, self.indices,
|
| 532 |
+
other.indptr, other.indices))
|
| 533 |
+
|
| 534 |
+
fn = getattr(_sparsetools, self.format + '_matmat_maxnnz')
|
| 535 |
+
nnz = fn(M, N,
|
| 536 |
+
np.asarray(self.indptr, dtype=idx_dtype),
|
| 537 |
+
np.asarray(self.indices, dtype=idx_dtype),
|
| 538 |
+
np.asarray(other.indptr, dtype=idx_dtype),
|
| 539 |
+
np.asarray(other.indices, dtype=idx_dtype))
|
| 540 |
+
if nnz == 0:
|
| 541 |
+
if new_shape == ():
|
| 542 |
+
return np.array(0, dtype=upcast(self.dtype, other.dtype))
|
| 543 |
+
return self.__class__(new_shape, dtype=upcast(self.dtype, other.dtype))
|
| 544 |
+
|
| 545 |
+
idx_dtype = self._get_index_dtype((self.indptr, self.indices,
|
| 546 |
+
other.indptr, other.indices),
|
| 547 |
+
maxval=nnz)
|
| 548 |
+
|
| 549 |
+
indptr = np.empty(major_dim + 1, dtype=idx_dtype)
|
| 550 |
+
indices = np.empty(nnz, dtype=idx_dtype)
|
| 551 |
+
data = np.empty(nnz, dtype=upcast(self.dtype, other.dtype))
|
| 552 |
+
|
| 553 |
+
fn = getattr(_sparsetools, self.format + '_matmat')
|
| 554 |
+
fn(M, N, np.asarray(self.indptr, dtype=idx_dtype),
|
| 555 |
+
np.asarray(self.indices, dtype=idx_dtype),
|
| 556 |
+
self.data,
|
| 557 |
+
np.asarray(other.indptr, dtype=idx_dtype),
|
| 558 |
+
np.asarray(other.indices, dtype=idx_dtype),
|
| 559 |
+
other.data,
|
| 560 |
+
indptr, indices, data)
|
| 561 |
+
|
| 562 |
+
if new_shape == ():
|
| 563 |
+
return np.array(data[0])
|
| 564 |
+
return self.__class__((data, indices, indptr), shape=new_shape)
|
| 565 |
+
|
| 566 |
+
def diagonal(self, k=0):
|
| 567 |
+
rows, cols = self.shape
|
| 568 |
+
if k <= -rows or k >= cols:
|
| 569 |
+
return np.empty(0, dtype=self.data.dtype)
|
| 570 |
+
fn = getattr(_sparsetools, self.format + "_diagonal")
|
| 571 |
+
y = np.empty(min(rows + min(k, 0), cols - max(k, 0)),
|
| 572 |
+
dtype=upcast(self.dtype))
|
| 573 |
+
fn(k, self.shape[0], self.shape[1], self.indptr, self.indices,
|
| 574 |
+
self.data, y)
|
| 575 |
+
return y
|
| 576 |
+
|
| 577 |
+
diagonal.__doc__ = _spbase.diagonal.__doc__
|
| 578 |
+
|
| 579 |
+
#####################
|
| 580 |
+
# Other binary ops #
|
| 581 |
+
#####################
|
| 582 |
+
|
| 583 |
+
def _maximum_minimum(self, other, npop, op_name, dense_check):
|
| 584 |
+
if isscalarlike(other):
|
| 585 |
+
if dense_check(other):
|
| 586 |
+
warn("Taking maximum (minimum) with > 0 (< 0) number results"
|
| 587 |
+
" to a dense matrix.", SparseEfficiencyWarning,
|
| 588 |
+
stacklevel=3)
|
| 589 |
+
other_arr = np.empty(self.shape, dtype=np.asarray(other).dtype)
|
| 590 |
+
other_arr.fill(other)
|
| 591 |
+
other_arr = self.__class__(other_arr)
|
| 592 |
+
return self._binopt(other_arr, op_name)
|
| 593 |
+
else:
|
| 594 |
+
self.sum_duplicates()
|
| 595 |
+
new_data = npop(self.data, np.asarray(other))
|
| 596 |
+
mat = self.__class__((new_data, self.indices, self.indptr),
|
| 597 |
+
dtype=new_data.dtype, shape=self.shape)
|
| 598 |
+
return mat
|
| 599 |
+
elif isdense(other):
|
| 600 |
+
return npop(self.todense(), other)
|
| 601 |
+
elif issparse(other):
|
| 602 |
+
return self._binopt(other, op_name)
|
| 603 |
+
else:
|
| 604 |
+
raise ValueError("Operands not compatible.")
|
| 605 |
+
|
| 606 |
+
def maximum(self, other):
|
| 607 |
+
return self._maximum_minimum(other, np.maximum,
|
| 608 |
+
'_maximum_', lambda x: np.asarray(x) > 0)
|
| 609 |
+
|
| 610 |
+
maximum.__doc__ = _spbase.maximum.__doc__
|
| 611 |
+
|
| 612 |
+
def minimum(self, other):
|
| 613 |
+
return self._maximum_minimum(other, np.minimum,
|
| 614 |
+
'_minimum_', lambda x: np.asarray(x) < 0)
|
| 615 |
+
|
| 616 |
+
minimum.__doc__ = _spbase.minimum.__doc__
|
| 617 |
+
|
| 618 |
+
#####################
|
| 619 |
+
# Reduce operations #
|
| 620 |
+
#####################
|
| 621 |
+
|
| 622 |
+
def sum(self, axis=None, dtype=None, out=None):
|
| 623 |
+
"""Sum the array/matrix over the given axis. If the axis is None, sum
|
| 624 |
+
over both rows and columns, returning a scalar.
|
| 625 |
+
"""
|
| 626 |
+
# The _spbase base class already does axis=0 and axis=1 efficiently
|
| 627 |
+
# so we only do the case axis=None here
|
| 628 |
+
if (self.ndim == 2 and not hasattr(self, 'blocksize') and
|
| 629 |
+
axis in self._swap(((1, -1), (0, -2)))[0]):
|
| 630 |
+
# faster than multiplication for large minor axis in CSC/CSR
|
| 631 |
+
res_dtype = get_sum_dtype(self.dtype)
|
| 632 |
+
ret = np.zeros(len(self.indptr) - 1, dtype=res_dtype)
|
| 633 |
+
|
| 634 |
+
major_index, value = self._minor_reduce(np.add)
|
| 635 |
+
ret[major_index] = value
|
| 636 |
+
ret = self._ascontainer(ret)
|
| 637 |
+
if axis % 2 == 1:
|
| 638 |
+
ret = ret.T
|
| 639 |
+
|
| 640 |
+
if out is not None and out.shape != ret.shape:
|
| 641 |
+
raise ValueError('dimensions do not match')
|
| 642 |
+
|
| 643 |
+
return ret.sum(axis=(), dtype=dtype, out=out)
|
| 644 |
+
else:
|
| 645 |
+
# _spbase handles the situations when axis is in {None, -2, -1, 0, 1}
|
| 646 |
+
return _spbase.sum(self, axis=axis, dtype=dtype, out=out)
|
| 647 |
+
|
| 648 |
+
sum.__doc__ = _spbase.sum.__doc__
|
| 649 |
+
|
| 650 |
+
def _minor_reduce(self, ufunc, data=None):
|
| 651 |
+
"""Reduce nonzeros with a ufunc over the minor axis when non-empty
|
| 652 |
+
|
| 653 |
+
Can be applied to a function of self.data by supplying data parameter.
|
| 654 |
+
|
| 655 |
+
Warning: this does not call sum_duplicates()
|
| 656 |
+
|
| 657 |
+
Returns
|
| 658 |
+
-------
|
| 659 |
+
major_index : array of ints
|
| 660 |
+
Major indices where nonzero
|
| 661 |
+
|
| 662 |
+
value : array of self.dtype
|
| 663 |
+
Reduce result for nonzeros in each major_index
|
| 664 |
+
"""
|
| 665 |
+
if data is None:
|
| 666 |
+
data = self.data
|
| 667 |
+
major_index = np.flatnonzero(np.diff(self.indptr))
|
| 668 |
+
value = ufunc.reduceat(data,
|
| 669 |
+
downcast_intp_index(self.indptr[major_index]))
|
| 670 |
+
return major_index, value
|
| 671 |
+
|
| 672 |
+
#######################
|
| 673 |
+
# Getting and Setting #
|
| 674 |
+
#######################
|
| 675 |
+
|
| 676 |
+
def _get_int(self, idx):
|
| 677 |
+
if 0 <= idx <= self.shape[0]:
|
| 678 |
+
spot = np.flatnonzero(self.indices == idx)
|
| 679 |
+
if spot.size:
|
| 680 |
+
return self.data[spot[0]]
|
| 681 |
+
return self.data.dtype.type(0)
|
| 682 |
+
raise IndexError(f'index ({idx}) out of range')
|
| 683 |
+
|
| 684 |
+
# For now, 1d only has integer indexing. Soon we will add get_slice/array
|
| 685 |
+
# def _get_slice(self, idx):
|
| 686 |
+
# if idx == slice(None):
|
| 687 |
+
# return self.copy()
|
| 688 |
+
# if idx.step in (1, None):
|
| 689 |
+
# major, minor = self._swap((0, idx))
|
| 690 |
+
# ret = self._get_submatrix(major, minor, copy=True)
|
| 691 |
+
# return ret.reshape(ret.shape[-1])
|
| 692 |
+
#
|
| 693 |
+
# _slice = self._swap((self._minor_slice, self._major_slice))[0]
|
| 694 |
+
# return _slice(idx)
|
| 695 |
+
#
|
| 696 |
+
# def _get_array(self, idx):
|
| 697 |
+
# idx = np.asarray(idx)
|
| 698 |
+
# idx_dtype = self.indices.dtype
|
| 699 |
+
# M, N = self._swap((1, self.shape[0]))
|
| 700 |
+
# row = np.zeros_like(idx, dtype=idx_dtype)
|
| 701 |
+
# major, minor = self._swap((row, idx))
|
| 702 |
+
# major = np.asarray(major, dtype=idx_dtype)
|
| 703 |
+
# minor = np.asarray(minor, dtype=idx_dtype)
|
| 704 |
+
# if minor.size == 0:
|
| 705 |
+
# return self.__class__([], dtype=self.dtype)
|
| 706 |
+
# new_shape = minor.shape if minor.shape[0] > 1 else (minor.shape[-1],)
|
| 707 |
+
#
|
| 708 |
+
# val = np.empty(major.size, dtype=self.dtype)
|
| 709 |
+
# csr_sample_values(M, N, self.indptr, self.indices, self.data,
|
| 710 |
+
# major.size, major.ravel(), minor.ravel(), val)
|
| 711 |
+
# return self.__class__(val.reshape(new_shape))
|
| 712 |
+
|
| 713 |
+
def _get_intXint(self, row, col):
|
| 714 |
+
M, N = self._swap(self.shape)
|
| 715 |
+
major, minor = self._swap((row, col))
|
| 716 |
+
indptr, indices, data = get_csr_submatrix(
|
| 717 |
+
M, N, self.indptr, self.indices, self.data,
|
| 718 |
+
major, major + 1, minor, minor + 1)
|
| 719 |
+
return data.sum(dtype=self.dtype)
|
| 720 |
+
|
| 721 |
+
def _get_sliceXslice(self, row, col):
|
| 722 |
+
major, minor = self._swap((row, col))
|
| 723 |
+
if major.step in (1, None) and minor.step in (1, None):
|
| 724 |
+
return self._get_submatrix(major, minor, copy=True)
|
| 725 |
+
return self._major_slice(major)._minor_slice(minor)
|
| 726 |
+
|
| 727 |
+
def _get_arrayXarray(self, row, col):
|
| 728 |
+
# inner indexing
|
| 729 |
+
idx_dtype = self.indices.dtype
|
| 730 |
+
M, N = self._swap(self.shape)
|
| 731 |
+
major, minor = self._swap((row, col))
|
| 732 |
+
major = np.asarray(major, dtype=idx_dtype)
|
| 733 |
+
minor = np.asarray(minor, dtype=idx_dtype)
|
| 734 |
+
|
| 735 |
+
val = np.empty(major.size, dtype=self.dtype)
|
| 736 |
+
csr_sample_values(M, N, self.indptr, self.indices, self.data,
|
| 737 |
+
major.size, major.ravel(), minor.ravel(), val)
|
| 738 |
+
if major.ndim == 1:
|
| 739 |
+
return self._ascontainer(val)
|
| 740 |
+
return self.__class__(val.reshape(major.shape))
|
| 741 |
+
|
| 742 |
+
def _get_columnXarray(self, row, col):
|
| 743 |
+
# outer indexing
|
| 744 |
+
major, minor = self._swap((row, col))
|
| 745 |
+
return self._major_index_fancy(major)._minor_index_fancy(minor)
|
| 746 |
+
|
| 747 |
+
def _major_index_fancy(self, idx):
|
| 748 |
+
"""Index along the major axis where idx is an array of ints.
|
| 749 |
+
"""
|
| 750 |
+
idx_dtype = self._get_index_dtype((self.indptr, self.indices))
|
| 751 |
+
indices = np.asarray(idx, dtype=idx_dtype).ravel()
|
| 752 |
+
|
| 753 |
+
N = self._swap(self._shape_as_2d)[1]
|
| 754 |
+
M = len(indices)
|
| 755 |
+
new_shape = self._swap((M, N)) if self.ndim == 2 else (M,)
|
| 756 |
+
if M == 0:
|
| 757 |
+
return self.__class__(new_shape, dtype=self.dtype)
|
| 758 |
+
|
| 759 |
+
row_nnz = (self.indptr[indices + 1] - self.indptr[indices]).astype(idx_dtype)
|
| 760 |
+
|
| 761 |
+
res_indptr = np.zeros(M+1, dtype=idx_dtype)
|
| 762 |
+
np.cumsum(row_nnz, out=res_indptr[1:])
|
| 763 |
+
|
| 764 |
+
nnz = res_indptr[-1]
|
| 765 |
+
res_indices = np.empty(nnz, dtype=idx_dtype)
|
| 766 |
+
res_data = np.empty(nnz, dtype=self.dtype)
|
| 767 |
+
csr_row_index(
|
| 768 |
+
M,
|
| 769 |
+
indices,
|
| 770 |
+
self.indptr.astype(idx_dtype, copy=False),
|
| 771 |
+
self.indices.astype(idx_dtype, copy=False),
|
| 772 |
+
self.data,
|
| 773 |
+
res_indices,
|
| 774 |
+
res_data
|
| 775 |
+
)
|
| 776 |
+
|
| 777 |
+
return self.__class__((res_data, res_indices, res_indptr),
|
| 778 |
+
shape=new_shape, copy=False)
|
| 779 |
+
|
| 780 |
+
def _major_slice(self, idx, copy=False):
|
| 781 |
+
"""Index along the major axis where idx is a slice object.
|
| 782 |
+
"""
|
| 783 |
+
if idx == slice(None):
|
| 784 |
+
return self.copy() if copy else self
|
| 785 |
+
|
| 786 |
+
M, N = self._swap(self._shape_as_2d)
|
| 787 |
+
start, stop, step = idx.indices(M)
|
| 788 |
+
M = len(range(start, stop, step))
|
| 789 |
+
new_shape = self._swap((M, N)) if self.ndim == 2 else (M,)
|
| 790 |
+
if M == 0:
|
| 791 |
+
return self.__class__(new_shape, dtype=self.dtype)
|
| 792 |
+
|
| 793 |
+
# Work out what slices are needed for `row_nnz`
|
| 794 |
+
# start,stop can be -1, only if step is negative
|
| 795 |
+
start0, stop0 = start, stop
|
| 796 |
+
if stop == -1 and start >= 0:
|
| 797 |
+
stop0 = None
|
| 798 |
+
start1, stop1 = start + 1, stop + 1
|
| 799 |
+
|
| 800 |
+
row_nnz = self.indptr[start1:stop1:step] - \
|
| 801 |
+
self.indptr[start0:stop0:step]
|
| 802 |
+
idx_dtype = self.indices.dtype
|
| 803 |
+
res_indptr = np.zeros(M+1, dtype=idx_dtype)
|
| 804 |
+
np.cumsum(row_nnz, out=res_indptr[1:])
|
| 805 |
+
|
| 806 |
+
if step == 1:
|
| 807 |
+
all_idx = slice(self.indptr[start], self.indptr[stop])
|
| 808 |
+
res_indices = np.array(self.indices[all_idx], copy=copy)
|
| 809 |
+
res_data = np.array(self.data[all_idx], copy=copy)
|
| 810 |
+
else:
|
| 811 |
+
nnz = res_indptr[-1]
|
| 812 |
+
res_indices = np.empty(nnz, dtype=idx_dtype)
|
| 813 |
+
res_data = np.empty(nnz, dtype=self.dtype)
|
| 814 |
+
csr_row_slice(start, stop, step, self.indptr, self.indices,
|
| 815 |
+
self.data, res_indices, res_data)
|
| 816 |
+
|
| 817 |
+
return self.__class__((res_data, res_indices, res_indptr),
|
| 818 |
+
shape=new_shape, copy=False)
|
| 819 |
+
|
| 820 |
+
def _minor_index_fancy(self, idx):
|
| 821 |
+
"""Index along the minor axis where idx is an array of ints.
|
| 822 |
+
"""
|
| 823 |
+
idx_dtype = self._get_index_dtype((self.indices, self.indptr))
|
| 824 |
+
indices = self.indices.astype(idx_dtype, copy=False)
|
| 825 |
+
indptr = self.indptr.astype(idx_dtype, copy=False)
|
| 826 |
+
|
| 827 |
+
idx = np.asarray(idx, dtype=idx_dtype).ravel()
|
| 828 |
+
|
| 829 |
+
M, N = self._swap(self._shape_as_2d)
|
| 830 |
+
k = len(idx)
|
| 831 |
+
new_shape = self._swap((M, k)) if self.ndim == 2 else (k,)
|
| 832 |
+
if k == 0:
|
| 833 |
+
return self.__class__(new_shape, dtype=self.dtype)
|
| 834 |
+
|
| 835 |
+
# pass 1: count idx entries and compute new indptr
|
| 836 |
+
col_offsets = np.zeros(N, dtype=idx_dtype)
|
| 837 |
+
res_indptr = np.empty_like(self.indptr, dtype=idx_dtype)
|
| 838 |
+
csr_column_index1(
|
| 839 |
+
k,
|
| 840 |
+
idx,
|
| 841 |
+
M,
|
| 842 |
+
N,
|
| 843 |
+
indptr,
|
| 844 |
+
indices,
|
| 845 |
+
col_offsets,
|
| 846 |
+
res_indptr,
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
# pass 2: copy indices/data for selected idxs
|
| 850 |
+
col_order = np.argsort(idx).astype(idx_dtype, copy=False)
|
| 851 |
+
nnz = res_indptr[-1]
|
| 852 |
+
res_indices = np.empty(nnz, dtype=idx_dtype)
|
| 853 |
+
res_data = np.empty(nnz, dtype=self.dtype)
|
| 854 |
+
csr_column_index2(col_order, col_offsets, len(self.indices),
|
| 855 |
+
indices, self.data, res_indices, res_data)
|
| 856 |
+
return self.__class__((res_data, res_indices, res_indptr),
|
| 857 |
+
shape=new_shape, copy=False)
|
| 858 |
+
|
| 859 |
+
def _minor_slice(self, idx, copy=False):
|
| 860 |
+
"""Index along the minor axis where idx is a slice object.
|
| 861 |
+
"""
|
| 862 |
+
if idx == slice(None):
|
| 863 |
+
return self.copy() if copy else self
|
| 864 |
+
|
| 865 |
+
M, N = self._swap(self._shape_as_2d)
|
| 866 |
+
start, stop, step = idx.indices(N)
|
| 867 |
+
N = len(range(start, stop, step))
|
| 868 |
+
if N == 0:
|
| 869 |
+
return self.__class__(self._swap((M, N)), dtype=self.dtype)
|
| 870 |
+
if step == 1:
|
| 871 |
+
return self._get_submatrix(minor=idx, copy=copy)
|
| 872 |
+
# TODO: don't fall back to fancy indexing here
|
| 873 |
+
return self._minor_index_fancy(np.arange(start, stop, step))
|
| 874 |
+
|
| 875 |
+
def _get_submatrix(self, major=None, minor=None, copy=False):
|
| 876 |
+
"""Return a submatrix of this matrix.
|
| 877 |
+
|
| 878 |
+
major, minor: None, int, or slice with step 1
|
| 879 |
+
"""
|
| 880 |
+
M, N = self._swap(self._shape_as_2d)
|
| 881 |
+
i0, i1 = _process_slice(major, M)
|
| 882 |
+
j0, j1 = _process_slice(minor, N)
|
| 883 |
+
|
| 884 |
+
if i0 == 0 and j0 == 0 and i1 == M and j1 == N:
|
| 885 |
+
return self.copy() if copy else self
|
| 886 |
+
|
| 887 |
+
indptr, indices, data = get_csr_submatrix(
|
| 888 |
+
M, N, self.indptr, self.indices, self.data, i0, i1, j0, j1)
|
| 889 |
+
|
| 890 |
+
shape = self._swap((i1 - i0, j1 - j0))
|
| 891 |
+
if self.ndim == 1:
|
| 892 |
+
shape = (shape[1],)
|
| 893 |
+
return self.__class__((data, indices, indptr), shape=shape,
|
| 894 |
+
dtype=self.dtype, copy=False)
|
| 895 |
+
|
| 896 |
+
def _set_int(self, idx, x):
|
| 897 |
+
major, minor = self._swap((0, idx))
|
| 898 |
+
self._set_many(major, minor, x)
|
| 899 |
+
|
| 900 |
+
def _set_array(self, idx, x):
|
| 901 |
+
major, minor = self._swap((np.zeros_like(idx), idx))
|
| 902 |
+
broadcast = x.shape[-1] == 1 and minor.shape[-1] != 1
|
| 903 |
+
if broadcast:
|
| 904 |
+
x = np.repeat(x.data, idx.shape[-1])
|
| 905 |
+
self._set_many(major, minor, x)
|
| 906 |
+
|
| 907 |
+
def _set_intXint(self, row, col, x):
|
| 908 |
+
i, j = self._swap((row, col))
|
| 909 |
+
self._set_many(i, j, x)
|
| 910 |
+
|
| 911 |
+
def _set_arrayXarray(self, row, col, x):
|
| 912 |
+
i, j = self._swap((row, col))
|
| 913 |
+
self._set_many(i, j, x)
|
| 914 |
+
|
| 915 |
+
def _set_arrayXarray_sparse(self, row, col, x):
|
| 916 |
+
# clear entries that will be overwritten
|
| 917 |
+
self._zero_many(*self._swap((row, col)))
|
| 918 |
+
|
| 919 |
+
M, N = row.shape # matches col.shape
|
| 920 |
+
broadcast_row = M != 1 and x.shape[0] == 1
|
| 921 |
+
broadcast_col = N != 1 and x.shape[1] == 1
|
| 922 |
+
r, c = x.row, x.col
|
| 923 |
+
|
| 924 |
+
x = np.asarray(x.data, dtype=self.dtype)
|
| 925 |
+
if x.size == 0:
|
| 926 |
+
return
|
| 927 |
+
|
| 928 |
+
if broadcast_row:
|
| 929 |
+
r = np.repeat(np.arange(M), len(r))
|
| 930 |
+
c = np.tile(c, M)
|
| 931 |
+
x = np.tile(x, M)
|
| 932 |
+
if broadcast_col:
|
| 933 |
+
r = np.repeat(r, N)
|
| 934 |
+
c = np.tile(np.arange(N), len(c))
|
| 935 |
+
x = np.repeat(x, N)
|
| 936 |
+
# only assign entries in the new sparsity structure
|
| 937 |
+
i, j = self._swap((row[r, c], col[r, c]))
|
| 938 |
+
self._set_many(i, j, x)
|
| 939 |
+
|
| 940 |
+
def _setdiag(self, values, k):
|
| 941 |
+
if 0 in self.shape:
|
| 942 |
+
return
|
| 943 |
+
if self.ndim == 1:
|
| 944 |
+
raise NotImplementedError('diagonals cant be set in 1d arrays')
|
| 945 |
+
|
| 946 |
+
M, N = self.shape
|
| 947 |
+
broadcast = (values.ndim == 0)
|
| 948 |
+
|
| 949 |
+
if k < 0:
|
| 950 |
+
if broadcast:
|
| 951 |
+
max_index = min(M + k, N)
|
| 952 |
+
else:
|
| 953 |
+
max_index = min(M + k, N, len(values))
|
| 954 |
+
i = np.arange(-k, max_index - k, dtype=self.indices.dtype)
|
| 955 |
+
j = np.arange(max_index, dtype=self.indices.dtype)
|
| 956 |
+
|
| 957 |
+
else:
|
| 958 |
+
if broadcast:
|
| 959 |
+
max_index = min(M, N - k)
|
| 960 |
+
else:
|
| 961 |
+
max_index = min(M, N - k, len(values))
|
| 962 |
+
i = np.arange(max_index, dtype=self.indices.dtype)
|
| 963 |
+
j = np.arange(k, k + max_index, dtype=self.indices.dtype)
|
| 964 |
+
|
| 965 |
+
if not broadcast:
|
| 966 |
+
values = values[:len(i)]
|
| 967 |
+
|
| 968 |
+
x = np.atleast_1d(np.asarray(values, dtype=self.dtype)).ravel()
|
| 969 |
+
if x.squeeze().shape != i.squeeze().shape:
|
| 970 |
+
x = np.broadcast_to(x, i.shape)
|
| 971 |
+
if x.size == 0:
|
| 972 |
+
return
|
| 973 |
+
|
| 974 |
+
M, N = self._swap((M, N))
|
| 975 |
+
i, j = self._swap((i, j))
|
| 976 |
+
n_samples = x.size
|
| 977 |
+
offsets = np.empty(n_samples, dtype=self.indices.dtype)
|
| 978 |
+
ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
|
| 979 |
+
i, j, offsets)
|
| 980 |
+
if ret == 1:
|
| 981 |
+
# rinse and repeat
|
| 982 |
+
self.sum_duplicates()
|
| 983 |
+
csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
|
| 984 |
+
i, j, offsets)
|
| 985 |
+
if -1 not in offsets:
|
| 986 |
+
# only affects existing non-zero cells
|
| 987 |
+
self.data[offsets] = x
|
| 988 |
+
return
|
| 989 |
+
|
| 990 |
+
mask = (offsets <= -1)
|
| 991 |
+
# Boundary between csc and convert to coo
|
| 992 |
+
# The value 0.001 is justified in gh-19962#issuecomment-1920499678
|
| 993 |
+
if mask.sum() < self.nnz * 0.001:
|
| 994 |
+
# create new entries
|
| 995 |
+
i = i[mask]
|
| 996 |
+
j = j[mask]
|
| 997 |
+
self._insert_many(i, j, x[mask])
|
| 998 |
+
# replace existing entries
|
| 999 |
+
mask = ~mask
|
| 1000 |
+
self.data[offsets[mask]] = x[mask]
|
| 1001 |
+
else:
|
| 1002 |
+
# convert to coo for _set_diag
|
| 1003 |
+
coo = self.tocoo()
|
| 1004 |
+
coo._setdiag(values, k)
|
| 1005 |
+
arrays = coo._coo_to_compressed(self._swap)
|
| 1006 |
+
self.indptr, self.indices, self.data, _ = arrays
|
| 1007 |
+
|
| 1008 |
+
def _prepare_indices(self, i, j):
|
| 1009 |
+
M, N = self._swap(self._shape_as_2d)
|
| 1010 |
+
|
| 1011 |
+
def check_bounds(indices, bound):
|
| 1012 |
+
idx = indices.max()
|
| 1013 |
+
if idx >= bound:
|
| 1014 |
+
raise IndexError('index (%d) out of range (>= %d)' %
|
| 1015 |
+
(idx, bound))
|
| 1016 |
+
idx = indices.min()
|
| 1017 |
+
if idx < -bound:
|
| 1018 |
+
raise IndexError('index (%d) out of range (< -%d)' %
|
| 1019 |
+
(idx, bound))
|
| 1020 |
+
|
| 1021 |
+
i = np.atleast_1d(np.asarray(i, dtype=self.indices.dtype)).ravel()
|
| 1022 |
+
j = np.atleast_1d(np.asarray(j, dtype=self.indices.dtype)).ravel()
|
| 1023 |
+
check_bounds(i, M)
|
| 1024 |
+
check_bounds(j, N)
|
| 1025 |
+
return i, j, M, N
|
| 1026 |
+
|
| 1027 |
+
def _set_many(self, i, j, x):
|
| 1028 |
+
"""Sets value at each (i, j) to x
|
| 1029 |
+
|
| 1030 |
+
Here (i,j) index major and minor respectively, and must not contain
|
| 1031 |
+
duplicate entries.
|
| 1032 |
+
"""
|
| 1033 |
+
i, j, M, N = self._prepare_indices(i, j)
|
| 1034 |
+
x = np.atleast_1d(np.asarray(x, dtype=self.dtype)).ravel()
|
| 1035 |
+
|
| 1036 |
+
n_samples = x.size
|
| 1037 |
+
offsets = np.empty(n_samples, dtype=self.indices.dtype)
|
| 1038 |
+
ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
|
| 1039 |
+
i, j, offsets)
|
| 1040 |
+
if ret == 1:
|
| 1041 |
+
# rinse and repeat
|
| 1042 |
+
self.sum_duplicates()
|
| 1043 |
+
csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
|
| 1044 |
+
i, j, offsets)
|
| 1045 |
+
|
| 1046 |
+
if -1 not in offsets:
|
| 1047 |
+
# only affects existing non-zero cells
|
| 1048 |
+
self.data[offsets] = x
|
| 1049 |
+
return
|
| 1050 |
+
|
| 1051 |
+
else:
|
| 1052 |
+
warn(f"Changing the sparsity structure of a {self.__class__.__name__} is"
|
| 1053 |
+
" expensive. lil and dok are more efficient.",
|
| 1054 |
+
SparseEfficiencyWarning, stacklevel=3)
|
| 1055 |
+
# replace where possible
|
| 1056 |
+
mask = offsets > -1
|
| 1057 |
+
self.data[offsets[mask]] = x[mask]
|
| 1058 |
+
# only insertions remain
|
| 1059 |
+
mask = ~mask
|
| 1060 |
+
i = i[mask]
|
| 1061 |
+
i[i < 0] += M
|
| 1062 |
+
j = j[mask]
|
| 1063 |
+
j[j < 0] += N
|
| 1064 |
+
self._insert_many(i, j, x[mask])
|
| 1065 |
+
|
| 1066 |
+
def _zero_many(self, i, j):
|
| 1067 |
+
"""Sets value at each (i, j) to zero, preserving sparsity structure.
|
| 1068 |
+
|
| 1069 |
+
Here (i,j) index major and minor respectively.
|
| 1070 |
+
"""
|
| 1071 |
+
i, j, M, N = self._prepare_indices(i, j)
|
| 1072 |
+
|
| 1073 |
+
n_samples = len(i)
|
| 1074 |
+
offsets = np.empty(n_samples, dtype=self.indices.dtype)
|
| 1075 |
+
ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
|
| 1076 |
+
i, j, offsets)
|
| 1077 |
+
if ret == 1:
|
| 1078 |
+
# rinse and repeat
|
| 1079 |
+
self.sum_duplicates()
|
| 1080 |
+
csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
|
| 1081 |
+
i, j, offsets)
|
| 1082 |
+
|
| 1083 |
+
# only assign zeros to the existing sparsity structure
|
| 1084 |
+
self.data[offsets[offsets > -1]] = 0
|
| 1085 |
+
|
| 1086 |
+
def _insert_many(self, i, j, x):
|
| 1087 |
+
"""Inserts new nonzero at each (i, j) with value x
|
| 1088 |
+
|
| 1089 |
+
Here (i,j) index major and minor respectively.
|
| 1090 |
+
i, j and x must be non-empty, 1d arrays.
|
| 1091 |
+
Inserts each major group (e.g. all entries per row) at a time.
|
| 1092 |
+
Maintains has_sorted_indices property.
|
| 1093 |
+
Modifies i, j, x in place.
|
| 1094 |
+
"""
|
| 1095 |
+
order = np.argsort(i, kind='mergesort') # stable for duplicates
|
| 1096 |
+
i = i.take(order, mode='clip')
|
| 1097 |
+
j = j.take(order, mode='clip')
|
| 1098 |
+
x = x.take(order, mode='clip')
|
| 1099 |
+
|
| 1100 |
+
do_sort = self.has_sorted_indices
|
| 1101 |
+
|
| 1102 |
+
# Update index data type
|
| 1103 |
+
idx_dtype = self._get_index_dtype((self.indices, self.indptr),
|
| 1104 |
+
maxval=(self.indptr[-1] + x.size))
|
| 1105 |
+
self.indptr = np.asarray(self.indptr, dtype=idx_dtype)
|
| 1106 |
+
self.indices = np.asarray(self.indices, dtype=idx_dtype)
|
| 1107 |
+
i = np.asarray(i, dtype=idx_dtype)
|
| 1108 |
+
j = np.asarray(j, dtype=idx_dtype)
|
| 1109 |
+
|
| 1110 |
+
# Collate old and new in chunks by major index
|
| 1111 |
+
indices_parts = []
|
| 1112 |
+
data_parts = []
|
| 1113 |
+
ui, ui_indptr = np.unique(i, return_index=True)
|
| 1114 |
+
ui_indptr = np.append(ui_indptr, len(j))
|
| 1115 |
+
new_nnzs = np.diff(ui_indptr)
|
| 1116 |
+
prev = 0
|
| 1117 |
+
for c, (ii, js, je) in enumerate(zip(ui, ui_indptr, ui_indptr[1:])):
|
| 1118 |
+
# old entries
|
| 1119 |
+
start = self.indptr[prev]
|
| 1120 |
+
stop = self.indptr[ii]
|
| 1121 |
+
indices_parts.append(self.indices[start:stop])
|
| 1122 |
+
data_parts.append(self.data[start:stop])
|
| 1123 |
+
|
| 1124 |
+
# handle duplicate j: keep last setting
|
| 1125 |
+
uj, uj_indptr = np.unique(j[js:je][::-1], return_index=True)
|
| 1126 |
+
if len(uj) == je - js:
|
| 1127 |
+
indices_parts.append(j[js:je])
|
| 1128 |
+
data_parts.append(x[js:je])
|
| 1129 |
+
else:
|
| 1130 |
+
indices_parts.append(j[js:je][::-1][uj_indptr])
|
| 1131 |
+
data_parts.append(x[js:je][::-1][uj_indptr])
|
| 1132 |
+
new_nnzs[c] = len(uj)
|
| 1133 |
+
|
| 1134 |
+
prev = ii
|
| 1135 |
+
|
| 1136 |
+
# remaining old entries
|
| 1137 |
+
start = self.indptr[ii]
|
| 1138 |
+
indices_parts.append(self.indices[start:])
|
| 1139 |
+
data_parts.append(self.data[start:])
|
| 1140 |
+
|
| 1141 |
+
# update attributes
|
| 1142 |
+
self.indices = np.concatenate(indices_parts)
|
| 1143 |
+
self.data = np.concatenate(data_parts)
|
| 1144 |
+
nnzs = np.empty(self.indptr.shape, dtype=idx_dtype)
|
| 1145 |
+
nnzs[0] = idx_dtype(0)
|
| 1146 |
+
indptr_diff = np.diff(self.indptr)
|
| 1147 |
+
indptr_diff[ui] += new_nnzs
|
| 1148 |
+
nnzs[1:] = indptr_diff
|
| 1149 |
+
self.indptr = np.cumsum(nnzs, out=nnzs)
|
| 1150 |
+
|
| 1151 |
+
if do_sort:
|
| 1152 |
+
# TODO: only sort where necessary
|
| 1153 |
+
self.has_sorted_indices = False
|
| 1154 |
+
self.sort_indices()
|
| 1155 |
+
|
| 1156 |
+
self.check_format(full_check=False)
|
| 1157 |
+
|
| 1158 |
+
######################
|
| 1159 |
+
# Conversion methods #
|
| 1160 |
+
######################
|
| 1161 |
+
|
| 1162 |
+
def tocoo(self, copy=True):
|
| 1163 |
+
if self.ndim == 1:
|
| 1164 |
+
csr = self.tocsr()
|
| 1165 |
+
return self._coo_container((csr.data, (csr.indices,)), csr.shape, copy=copy)
|
| 1166 |
+
major_dim, minor_dim = self._swap(self.shape)
|
| 1167 |
+
minor_indices = self.indices
|
| 1168 |
+
major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype)
|
| 1169 |
+
_sparsetools.expandptr(major_dim, self.indptr, major_indices)
|
| 1170 |
+
coords = self._swap((major_indices, minor_indices))
|
| 1171 |
+
|
| 1172 |
+
return self._coo_container(
|
| 1173 |
+
(self.data, coords), self.shape, copy=copy, dtype=self.dtype
|
| 1174 |
+
)
|
| 1175 |
+
|
| 1176 |
+
tocoo.__doc__ = _spbase.tocoo.__doc__
|
| 1177 |
+
|
| 1178 |
+
def toarray(self, order=None, out=None):
|
| 1179 |
+
if out is None and order is None:
|
| 1180 |
+
order = self._swap('cf')[0]
|
| 1181 |
+
out = self._process_toarray_args(order, out)
|
| 1182 |
+
if not (out.flags.c_contiguous or out.flags.f_contiguous):
|
| 1183 |
+
raise ValueError('Output array must be C or F contiguous')
|
| 1184 |
+
# align ideal order with output array order
|
| 1185 |
+
if out.flags.c_contiguous:
|
| 1186 |
+
x = self.tocsr()
|
| 1187 |
+
y = out
|
| 1188 |
+
else:
|
| 1189 |
+
x = self.tocsc()
|
| 1190 |
+
y = out.T
|
| 1191 |
+
M, N = x._swap(x._shape_as_2d)
|
| 1192 |
+
csr_todense(M, N, x.indptr, x.indices, x.data, y)
|
| 1193 |
+
return out
|
| 1194 |
+
|
| 1195 |
+
toarray.__doc__ = _spbase.toarray.__doc__
|
| 1196 |
+
|
| 1197 |
+
##############################################################
|
| 1198 |
+
# methods that examine or modify the internal data structure #
|
| 1199 |
+
##############################################################
|
| 1200 |
+
|
| 1201 |
+
def eliminate_zeros(self):
|
| 1202 |
+
"""Remove zero entries from the array/matrix
|
| 1203 |
+
|
| 1204 |
+
This is an *in place* operation.
|
| 1205 |
+
"""
|
| 1206 |
+
M, N = self._swap(self._shape_as_2d)
|
| 1207 |
+
_sparsetools.csr_eliminate_zeros(M, N, self.indptr, self.indices, self.data)
|
| 1208 |
+
self.prune() # nnz may have changed
|
| 1209 |
+
|
| 1210 |
+
@property
|
| 1211 |
+
def has_canonical_format(self) -> bool:
|
| 1212 |
+
"""Whether the array/matrix has sorted indices and no duplicates
|
| 1213 |
+
|
| 1214 |
+
Returns
|
| 1215 |
+
- True: if the above applies
|
| 1216 |
+
- False: otherwise
|
| 1217 |
+
|
| 1218 |
+
has_canonical_format implies has_sorted_indices, so if the latter flag
|
| 1219 |
+
is False, so will the former be; if the former is found True, the
|
| 1220 |
+
latter flag is also set.
|
| 1221 |
+
"""
|
| 1222 |
+
# first check to see if result was cached
|
| 1223 |
+
if not getattr(self, '_has_sorted_indices', True):
|
| 1224 |
+
# not sorted => not canonical
|
| 1225 |
+
self._has_canonical_format = False
|
| 1226 |
+
elif not hasattr(self, '_has_canonical_format'):
|
| 1227 |
+
self.has_canonical_format = bool(
|
| 1228 |
+
_sparsetools.csr_has_canonical_format(
|
| 1229 |
+
len(self.indptr) - 1, self.indptr, self.indices)
|
| 1230 |
+
)
|
| 1231 |
+
return self._has_canonical_format
|
| 1232 |
+
|
| 1233 |
+
@has_canonical_format.setter
|
| 1234 |
+
def has_canonical_format(self, val: bool):
|
| 1235 |
+
self._has_canonical_format = bool(val)
|
| 1236 |
+
if val:
|
| 1237 |
+
self.has_sorted_indices = True
|
| 1238 |
+
|
| 1239 |
+
def sum_duplicates(self):
|
| 1240 |
+
"""Eliminate duplicate entries by adding them together
|
| 1241 |
+
|
| 1242 |
+
This is an *in place* operation.
|
| 1243 |
+
"""
|
| 1244 |
+
if self.has_canonical_format:
|
| 1245 |
+
return
|
| 1246 |
+
self.sort_indices()
|
| 1247 |
+
|
| 1248 |
+
M, N = self._swap(self._shape_as_2d)
|
| 1249 |
+
_sparsetools.csr_sum_duplicates(M, N, self.indptr, self.indices, self.data)
|
| 1250 |
+
|
| 1251 |
+
self.prune() # nnz may have changed
|
| 1252 |
+
self.has_canonical_format = True
|
| 1253 |
+
|
| 1254 |
+
@property
|
| 1255 |
+
def has_sorted_indices(self) -> bool:
|
| 1256 |
+
"""Whether the indices are sorted
|
| 1257 |
+
|
| 1258 |
+
Returns
|
| 1259 |
+
- True: if the indices of the array/matrix are in sorted order
|
| 1260 |
+
- False: otherwise
|
| 1261 |
+
"""
|
| 1262 |
+
# first check to see if result was cached
|
| 1263 |
+
if not hasattr(self, '_has_sorted_indices'):
|
| 1264 |
+
self._has_sorted_indices = bool(
|
| 1265 |
+
_sparsetools.csr_has_sorted_indices(
|
| 1266 |
+
len(self.indptr) - 1, self.indptr, self.indices)
|
| 1267 |
+
)
|
| 1268 |
+
return self._has_sorted_indices
|
| 1269 |
+
|
| 1270 |
+
@has_sorted_indices.setter
|
| 1271 |
+
def has_sorted_indices(self, val: bool):
|
| 1272 |
+
self._has_sorted_indices = bool(val)
|
| 1273 |
+
|
| 1274 |
+
|
| 1275 |
+
def sorted_indices(self):
|
| 1276 |
+
"""Return a copy of this array/matrix with sorted indices
|
| 1277 |
+
"""
|
| 1278 |
+
A = self.copy()
|
| 1279 |
+
A.sort_indices()
|
| 1280 |
+
return A
|
| 1281 |
+
|
| 1282 |
+
# an alternative that has linear complexity is the following
|
| 1283 |
+
# although the previous option is typically faster
|
| 1284 |
+
# return self.toother().toother()
|
| 1285 |
+
|
| 1286 |
+
def sort_indices(self):
|
| 1287 |
+
"""Sort the indices of this array/matrix *in place*
|
| 1288 |
+
"""
|
| 1289 |
+
|
| 1290 |
+
if not self.has_sorted_indices:
|
| 1291 |
+
_sparsetools.csr_sort_indices(len(self.indptr) - 1, self.indptr,
|
| 1292 |
+
self.indices, self.data)
|
| 1293 |
+
self.has_sorted_indices = True
|
| 1294 |
+
|
| 1295 |
+
def prune(self):
|
| 1296 |
+
"""Remove empty space after all non-zero elements.
|
| 1297 |
+
"""
|
| 1298 |
+
major_dim = self._swap(self._shape_as_2d)[0]
|
| 1299 |
+
|
| 1300 |
+
if len(self.indptr) != major_dim + 1:
|
| 1301 |
+
raise ValueError('index pointer has invalid length')
|
| 1302 |
+
if len(self.indices) < self.nnz:
|
| 1303 |
+
raise ValueError('indices array has fewer than nnz elements')
|
| 1304 |
+
if len(self.data) < self.nnz:
|
| 1305 |
+
raise ValueError('data array has fewer than nnz elements')
|
| 1306 |
+
|
| 1307 |
+
self.indices = _prune_array(self.indices[:self.nnz])
|
| 1308 |
+
self.data = _prune_array(self.data[:self.nnz])
|
| 1309 |
+
|
| 1310 |
+
def resize(self, *shape):
|
| 1311 |
+
shape = check_shape(shape, allow_1d=isinstance(self, sparray))
|
| 1312 |
+
|
| 1313 |
+
if hasattr(self, 'blocksize'):
|
| 1314 |
+
bm, bn = self.blocksize
|
| 1315 |
+
new_M, rm = divmod(shape[0], bm)
|
| 1316 |
+
new_N, rn = divmod(shape[1], bn)
|
| 1317 |
+
if rm or rn:
|
| 1318 |
+
raise ValueError(f"shape must be divisible into {self.blocksize}"
|
| 1319 |
+
f" blocks. Got {shape}")
|
| 1320 |
+
M, N = self.shape[0] // bm, self.shape[1] // bn
|
| 1321 |
+
else:
|
| 1322 |
+
new_M, new_N = self._swap(shape if len(shape)>1 else (1, shape[0]))
|
| 1323 |
+
M, N = self._swap(self._shape_as_2d)
|
| 1324 |
+
|
| 1325 |
+
if new_M < M:
|
| 1326 |
+
self.indices = self.indices[:self.indptr[new_M]]
|
| 1327 |
+
self.data = self.data[:self.indptr[new_M]]
|
| 1328 |
+
self.indptr = self.indptr[:new_M + 1]
|
| 1329 |
+
elif new_M > M:
|
| 1330 |
+
self.indptr = np.resize(self.indptr, new_M + 1)
|
| 1331 |
+
self.indptr[M + 1:].fill(self.indptr[M])
|
| 1332 |
+
|
| 1333 |
+
if new_N < N:
|
| 1334 |
+
mask = self.indices < new_N
|
| 1335 |
+
if not np.all(mask):
|
| 1336 |
+
self.indices = self.indices[mask]
|
| 1337 |
+
self.data = self.data[mask]
|
| 1338 |
+
major_index, val = self._minor_reduce(np.add, mask)
|
| 1339 |
+
self.indptr.fill(0)
|
| 1340 |
+
self.indptr[1:][major_index] = val
|
| 1341 |
+
np.cumsum(self.indptr, out=self.indptr)
|
| 1342 |
+
|
| 1343 |
+
self._shape = shape
|
| 1344 |
+
|
| 1345 |
+
resize.__doc__ = _spbase.resize.__doc__
|
| 1346 |
+
|
| 1347 |
+
###################
|
| 1348 |
+
# utility methods #
|
| 1349 |
+
###################
|
| 1350 |
+
|
| 1351 |
+
# needed by _data_matrix
|
| 1352 |
+
def _with_data(self, data, copy=True):
|
| 1353 |
+
"""Returns a matrix with the same sparsity structure as self,
|
| 1354 |
+
but with different data. By default the structure arrays
|
| 1355 |
+
(i.e. .indptr and .indices) are copied.
|
| 1356 |
+
"""
|
| 1357 |
+
if copy:
|
| 1358 |
+
return self.__class__((data, self.indices.copy(),
|
| 1359 |
+
self.indptr.copy()),
|
| 1360 |
+
shape=self.shape,
|
| 1361 |
+
dtype=data.dtype)
|
| 1362 |
+
else:
|
| 1363 |
+
return self.__class__((data, self.indices, self.indptr),
|
| 1364 |
+
shape=self.shape, dtype=data.dtype)
|
| 1365 |
+
|
| 1366 |
+
def _binopt(self, other, op):
|
| 1367 |
+
"""apply the binary operation fn to two sparse matrices."""
|
| 1368 |
+
other = self.__class__(other)
|
| 1369 |
+
|
| 1370 |
+
# e.g. csr_plus_csr, csr_minus_csr, etc.
|
| 1371 |
+
fn = getattr(_sparsetools, self.format + op + self.format)
|
| 1372 |
+
|
| 1373 |
+
maxnnz = self.nnz + other.nnz
|
| 1374 |
+
idx_dtype = self._get_index_dtype((self.indptr, self.indices,
|
| 1375 |
+
other.indptr, other.indices),
|
| 1376 |
+
maxval=maxnnz)
|
| 1377 |
+
indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
|
| 1378 |
+
indices = np.empty(maxnnz, dtype=idx_dtype)
|
| 1379 |
+
|
| 1380 |
+
bool_ops = ['_ne_', '_lt_', '_gt_', '_le_', '_ge_']
|
| 1381 |
+
if op in bool_ops:
|
| 1382 |
+
data = np.empty(maxnnz, dtype=np.bool_)
|
| 1383 |
+
else:
|
| 1384 |
+
data = np.empty(maxnnz, dtype=upcast(self.dtype, other.dtype))
|
| 1385 |
+
|
| 1386 |
+
M, N = self._shape_as_2d
|
| 1387 |
+
fn(M, N,
|
| 1388 |
+
np.asarray(self.indptr, dtype=idx_dtype),
|
| 1389 |
+
np.asarray(self.indices, dtype=idx_dtype),
|
| 1390 |
+
self.data,
|
| 1391 |
+
np.asarray(other.indptr, dtype=idx_dtype),
|
| 1392 |
+
np.asarray(other.indices, dtype=idx_dtype),
|
| 1393 |
+
other.data,
|
| 1394 |
+
indptr, indices, data)
|
| 1395 |
+
|
| 1396 |
+
A = self.__class__((data, indices, indptr), shape=self.shape)
|
| 1397 |
+
A.prune()
|
| 1398 |
+
|
| 1399 |
+
return A
|
| 1400 |
+
|
| 1401 |
+
def _divide_sparse(self, other):
|
| 1402 |
+
"""
|
| 1403 |
+
Divide this matrix by a second sparse matrix.
|
| 1404 |
+
"""
|
| 1405 |
+
if other.shape != self.shape:
|
| 1406 |
+
raise ValueError('inconsistent shapes')
|
| 1407 |
+
|
| 1408 |
+
r = self._binopt(other, '_eldiv_')
|
| 1409 |
+
|
| 1410 |
+
if np.issubdtype(r.dtype, np.inexact):
|
| 1411 |
+
# Eldiv leaves entries outside the combined sparsity
|
| 1412 |
+
# pattern empty, so they must be filled manually.
|
| 1413 |
+
# Everything outside of other's sparsity is NaN, and everything
|
| 1414 |
+
# inside it is either zero or defined by eldiv.
|
| 1415 |
+
out = np.empty(self.shape, dtype=self.dtype)
|
| 1416 |
+
out.fill(np.nan)
|
| 1417 |
+
coords = other.nonzero()
|
| 1418 |
+
if self.ndim == 1:
|
| 1419 |
+
coords = (coords[-1],)
|
| 1420 |
+
out[coords] = 0
|
| 1421 |
+
r = r.tocoo()
|
| 1422 |
+
out[r.coords] = r.data
|
| 1423 |
+
return self._container(out)
|
| 1424 |
+
else:
|
| 1425 |
+
# integers types go with nan <-> 0
|
| 1426 |
+
out = r
|
| 1427 |
+
return out
|
| 1428 |
+
|
| 1429 |
+
|
| 1430 |
+
def _make_diagonal_csr(data, is_array=False):
|
| 1431 |
+
"""build diagonal csc_array/csr_array => self._csr_container
|
| 1432 |
+
|
| 1433 |
+
Parameter `data` should be a raveled numpy array holding the
|
| 1434 |
+
values on the diagonal of the resulting sparse matrix.
|
| 1435 |
+
"""
|
| 1436 |
+
from ._csr import csr_array, csr_matrix
|
| 1437 |
+
csr_array = csr_array if is_array else csr_matrix
|
| 1438 |
+
|
| 1439 |
+
N = len(data)
|
| 1440 |
+
indptr = np.arange(N + 1)
|
| 1441 |
+
indices = indptr[:-1]
|
| 1442 |
+
|
| 1443 |
+
return csr_array((data, indices, indptr), shape=(N, N))
|
| 1444 |
+
|
| 1445 |
+
|
| 1446 |
+
def _process_slice(sl, num):
|
| 1447 |
+
if sl is None:
|
| 1448 |
+
i0, i1 = 0, num
|
| 1449 |
+
elif isinstance(sl, slice):
|
| 1450 |
+
i0, i1, stride = sl.indices(num)
|
| 1451 |
+
if stride != 1:
|
| 1452 |
+
raise ValueError('slicing with step != 1 not supported')
|
| 1453 |
+
i0 = min(i0, i1) # give an empty slice when i0 > i1
|
| 1454 |
+
elif isintlike(sl):
|
| 1455 |
+
if sl < 0:
|
| 1456 |
+
sl += num
|
| 1457 |
+
i0, i1 = sl, sl + 1
|
| 1458 |
+
if i0 < 0 or i1 > num:
|
| 1459 |
+
raise IndexError(f'index out of bounds: 0 <= {i0} < {i1} <= {num}')
|
| 1460 |
+
else:
|
| 1461 |
+
raise TypeError('expected slice or scalar')
|
| 1462 |
+
|
| 1463 |
+
return i0, i1
|
parrot/lib/python3.10/site-packages/scipy/sparse/_coo.py
ADDED
|
@@ -0,0 +1,866 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" A sparse matrix in COOrdinate or 'triplet' format"""
|
| 2 |
+
|
| 3 |
+
__docformat__ = "restructuredtext en"
|
| 4 |
+
|
| 5 |
+
__all__ = ['coo_array', 'coo_matrix', 'isspmatrix_coo']
|
| 6 |
+
|
| 7 |
+
import math
|
| 8 |
+
from warnings import warn
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
from .._lib._util import copy_if_needed
|
| 13 |
+
from ._matrix import spmatrix
|
| 14 |
+
from ._sparsetools import coo_tocsr, coo_todense, coo_matvec
|
| 15 |
+
from ._base import issparse, SparseEfficiencyWarning, _spbase, sparray
|
| 16 |
+
from ._data import _data_matrix, _minmax_mixin
|
| 17 |
+
from ._sputils import (upcast_char, to_native, isshape, getdtype,
|
| 18 |
+
getdata, downcast_intp_index, get_index_dtype,
|
| 19 |
+
check_shape, check_reshape_kwargs)
|
| 20 |
+
|
| 21 |
+
import operator
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _coo_base(_data_matrix, _minmax_mixin):
|
| 25 |
+
_format = 'coo'
|
| 26 |
+
|
| 27 |
+
def __init__(self, arg1, shape=None, dtype=None, copy=False):
|
| 28 |
+
_data_matrix.__init__(self, arg1)
|
| 29 |
+
is_array = isinstance(self, sparray)
|
| 30 |
+
if not copy:
|
| 31 |
+
copy = copy_if_needed
|
| 32 |
+
|
| 33 |
+
if isinstance(arg1, tuple):
|
| 34 |
+
if isshape(arg1, allow_1d=is_array):
|
| 35 |
+
self._shape = check_shape(arg1, allow_1d=is_array)
|
| 36 |
+
idx_dtype = self._get_index_dtype(maxval=max(self._shape))
|
| 37 |
+
data_dtype = getdtype(dtype, default=float)
|
| 38 |
+
self.coords = tuple(np.array([], dtype=idx_dtype)
|
| 39 |
+
for _ in range(len(self._shape)))
|
| 40 |
+
self.data = np.array([], dtype=data_dtype)
|
| 41 |
+
self.has_canonical_format = True
|
| 42 |
+
else:
|
| 43 |
+
try:
|
| 44 |
+
obj, coords = arg1
|
| 45 |
+
except (TypeError, ValueError) as e:
|
| 46 |
+
raise TypeError('invalid input format') from e
|
| 47 |
+
|
| 48 |
+
if shape is None:
|
| 49 |
+
if any(len(idx) == 0 for idx in coords):
|
| 50 |
+
raise ValueError('cannot infer dimensions from zero '
|
| 51 |
+
'sized index arrays')
|
| 52 |
+
shape = tuple(operator.index(np.max(idx)) + 1
|
| 53 |
+
for idx in coords)
|
| 54 |
+
self._shape = check_shape(shape, allow_1d=is_array)
|
| 55 |
+
|
| 56 |
+
idx_dtype = self._get_index_dtype(coords,
|
| 57 |
+
maxval=max(self.shape),
|
| 58 |
+
check_contents=True)
|
| 59 |
+
self.coords = tuple(np.array(idx, copy=copy, dtype=idx_dtype)
|
| 60 |
+
for idx in coords)
|
| 61 |
+
self.data = getdata(obj, copy=copy, dtype=dtype)
|
| 62 |
+
self.has_canonical_format = False
|
| 63 |
+
else:
|
| 64 |
+
if issparse(arg1):
|
| 65 |
+
if arg1.format == self.format and copy:
|
| 66 |
+
self.coords = tuple(idx.copy() for idx in arg1.coords)
|
| 67 |
+
self.data = arg1.data.copy()
|
| 68 |
+
self._shape = check_shape(arg1.shape, allow_1d=is_array)
|
| 69 |
+
self.has_canonical_format = arg1.has_canonical_format
|
| 70 |
+
else:
|
| 71 |
+
coo = arg1.tocoo()
|
| 72 |
+
self.coords = tuple(coo.coords)
|
| 73 |
+
self.data = coo.data
|
| 74 |
+
self._shape = check_shape(coo.shape, allow_1d=is_array)
|
| 75 |
+
self.has_canonical_format = False
|
| 76 |
+
else:
|
| 77 |
+
# dense argument
|
| 78 |
+
M = np.asarray(arg1)
|
| 79 |
+
if not is_array:
|
| 80 |
+
M = np.atleast_2d(M)
|
| 81 |
+
if M.ndim != 2:
|
| 82 |
+
raise TypeError(f'expected 2D array or matrix, not {M.ndim}D')
|
| 83 |
+
|
| 84 |
+
self._shape = check_shape(M.shape, allow_1d=is_array)
|
| 85 |
+
if shape is not None:
|
| 86 |
+
if check_shape(shape, allow_1d=is_array) != self._shape:
|
| 87 |
+
message = f'inconsistent shapes: {shape} != {self._shape}'
|
| 88 |
+
raise ValueError(message)
|
| 89 |
+
index_dtype = self._get_index_dtype(maxval=max(self._shape))
|
| 90 |
+
coords = M.nonzero()
|
| 91 |
+
self.coords = tuple(idx.astype(index_dtype, copy=False)
|
| 92 |
+
for idx in coords)
|
| 93 |
+
self.data = M[coords]
|
| 94 |
+
self.has_canonical_format = True
|
| 95 |
+
|
| 96 |
+
if dtype is not None:
|
| 97 |
+
self.data = self.data.astype(dtype, copy=False)
|
| 98 |
+
|
| 99 |
+
self._check()
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def row(self):
|
| 103 |
+
if self.ndim > 1:
|
| 104 |
+
return self.coords[-2]
|
| 105 |
+
result = np.zeros_like(self.col)
|
| 106 |
+
result.setflags(write=False)
|
| 107 |
+
return result
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@row.setter
|
| 111 |
+
def row(self, new_row):
|
| 112 |
+
if self.ndim < 2:
|
| 113 |
+
raise ValueError('cannot set row attribute of a 1-dimensional sparse array')
|
| 114 |
+
new_row = np.asarray(new_row, dtype=self.coords[-2].dtype)
|
| 115 |
+
self.coords = self.coords[:-2] + (new_row,) + self.coords[-1:]
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def col(self):
|
| 119 |
+
return self.coords[-1]
|
| 120 |
+
|
| 121 |
+
@col.setter
|
| 122 |
+
def col(self, new_col):
|
| 123 |
+
new_col = np.asarray(new_col, dtype=self.coords[-1].dtype)
|
| 124 |
+
self.coords = self.coords[:-1] + (new_col,)
|
| 125 |
+
|
| 126 |
+
def reshape(self, *args, **kwargs):
|
| 127 |
+
is_array = isinstance(self, sparray)
|
| 128 |
+
shape = check_shape(args, self.shape, allow_1d=is_array)
|
| 129 |
+
order, copy = check_reshape_kwargs(kwargs)
|
| 130 |
+
|
| 131 |
+
# Return early if reshape is not required
|
| 132 |
+
if shape == self.shape:
|
| 133 |
+
if copy:
|
| 134 |
+
return self.copy()
|
| 135 |
+
else:
|
| 136 |
+
return self
|
| 137 |
+
|
| 138 |
+
# When reducing the number of dimensions, we need to be careful about
|
| 139 |
+
# index overflow. This is why we can't simply call
|
| 140 |
+
# `np.ravel_multi_index()` followed by `np.unravel_index()` here.
|
| 141 |
+
flat_coords = _ravel_coords(self.coords, self.shape, order=order)
|
| 142 |
+
if len(shape) == 2:
|
| 143 |
+
if order == 'C':
|
| 144 |
+
new_coords = divmod(flat_coords, shape[1])
|
| 145 |
+
else:
|
| 146 |
+
new_coords = divmod(flat_coords, shape[0])[::-1]
|
| 147 |
+
else:
|
| 148 |
+
new_coords = np.unravel_index(flat_coords, shape, order=order)
|
| 149 |
+
|
| 150 |
+
# Handle copy here rather than passing on to the constructor so that no
|
| 151 |
+
# copy will be made of `new_coords` regardless.
|
| 152 |
+
if copy:
|
| 153 |
+
new_data = self.data.copy()
|
| 154 |
+
else:
|
| 155 |
+
new_data = self.data
|
| 156 |
+
|
| 157 |
+
return self.__class__((new_data, new_coords), shape=shape, copy=False)
|
| 158 |
+
|
| 159 |
+
reshape.__doc__ = _spbase.reshape.__doc__
|
| 160 |
+
|
| 161 |
+
def _getnnz(self, axis=None):
|
| 162 |
+
if axis is None or (axis == 0 and self.ndim == 1):
|
| 163 |
+
nnz = len(self.data)
|
| 164 |
+
if any(len(idx) != nnz for idx in self.coords):
|
| 165 |
+
raise ValueError('all index and data arrays must have the '
|
| 166 |
+
'same length')
|
| 167 |
+
|
| 168 |
+
if self.data.ndim != 1 or any(idx.ndim != 1 for idx in self.coords):
|
| 169 |
+
raise ValueError('row, column, and data arrays must be 1-D')
|
| 170 |
+
|
| 171 |
+
return int(nnz)
|
| 172 |
+
|
| 173 |
+
if axis < 0:
|
| 174 |
+
axis += self.ndim
|
| 175 |
+
if axis >= self.ndim:
|
| 176 |
+
raise ValueError('axis out of bounds')
|
| 177 |
+
if self.ndim > 2:
|
| 178 |
+
raise NotImplementedError('per-axis nnz for COO arrays with >2 '
|
| 179 |
+
'dimensions is not supported')
|
| 180 |
+
return np.bincount(downcast_intp_index(self.coords[1 - axis]),
|
| 181 |
+
minlength=self.shape[1 - axis])
|
| 182 |
+
|
| 183 |
+
_getnnz.__doc__ = _spbase._getnnz.__doc__
|
| 184 |
+
|
| 185 |
+
def _check(self):
|
| 186 |
+
""" Checks data structure for consistency """
|
| 187 |
+
if self.ndim != len(self.coords):
|
| 188 |
+
raise ValueError('mismatching number of index arrays for shape; '
|
| 189 |
+
f'got {len(self.coords)}, expected {self.ndim}')
|
| 190 |
+
|
| 191 |
+
# index arrays should have integer data types
|
| 192 |
+
for i, idx in enumerate(self.coords):
|
| 193 |
+
if idx.dtype.kind != 'i':
|
| 194 |
+
warn(f'index array {i} has non-integer dtype ({idx.dtype.name})',
|
| 195 |
+
stacklevel=3)
|
| 196 |
+
|
| 197 |
+
idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.shape))
|
| 198 |
+
self.coords = tuple(np.asarray(idx, dtype=idx_dtype)
|
| 199 |
+
for idx in self.coords)
|
| 200 |
+
self.data = to_native(self.data)
|
| 201 |
+
|
| 202 |
+
if self.nnz > 0:
|
| 203 |
+
for i, idx in enumerate(self.coords):
|
| 204 |
+
if idx.max() >= self.shape[i]:
|
| 205 |
+
raise ValueError(f'axis {i} index {idx.max()} exceeds '
|
| 206 |
+
f'matrix dimension {self.shape[i]}')
|
| 207 |
+
if idx.min() < 0:
|
| 208 |
+
raise ValueError(f'negative axis {i} index: {idx.min()}')
|
| 209 |
+
|
| 210 |
+
def transpose(self, axes=None, copy=False):
|
| 211 |
+
if axes is None:
|
| 212 |
+
axes = range(self.ndim)[::-1]
|
| 213 |
+
elif isinstance(self, sparray):
|
| 214 |
+
if len(axes) != self.ndim:
|
| 215 |
+
raise ValueError("axes don't match matrix dimensions")
|
| 216 |
+
if len(set(axes)) != self.ndim:
|
| 217 |
+
raise ValueError("repeated axis in transpose")
|
| 218 |
+
elif axes != (1, 0):
|
| 219 |
+
raise ValueError("Sparse matrices do not support an 'axes' "
|
| 220 |
+
"parameter because swapping dimensions is the "
|
| 221 |
+
"only logical permutation.")
|
| 222 |
+
|
| 223 |
+
permuted_shape = tuple(self._shape[i] for i in axes)
|
| 224 |
+
permuted_coords = tuple(self.coords[i] for i in axes)
|
| 225 |
+
return self.__class__((self.data, permuted_coords),
|
| 226 |
+
shape=permuted_shape, copy=copy)
|
| 227 |
+
|
| 228 |
+
transpose.__doc__ = _spbase.transpose.__doc__
|
| 229 |
+
|
| 230 |
+
def resize(self, *shape) -> None:
|
| 231 |
+
is_array = isinstance(self, sparray)
|
| 232 |
+
shape = check_shape(shape, allow_1d=is_array)
|
| 233 |
+
|
| 234 |
+
# Check for added dimensions.
|
| 235 |
+
if len(shape) > self.ndim:
|
| 236 |
+
flat_coords = _ravel_coords(self.coords, self.shape)
|
| 237 |
+
max_size = math.prod(shape)
|
| 238 |
+
self.coords = np.unravel_index(flat_coords[:max_size], shape)
|
| 239 |
+
self.data = self.data[:max_size]
|
| 240 |
+
self._shape = shape
|
| 241 |
+
return
|
| 242 |
+
|
| 243 |
+
# Check for removed dimensions.
|
| 244 |
+
if len(shape) < self.ndim:
|
| 245 |
+
tmp_shape = (
|
| 246 |
+
self._shape[:len(shape) - 1] # Original shape without last axis
|
| 247 |
+
+ (-1,) # Last axis is used to flatten the array
|
| 248 |
+
+ (1,) * (self.ndim - len(shape)) # Pad with ones
|
| 249 |
+
)
|
| 250 |
+
tmp = self.reshape(tmp_shape)
|
| 251 |
+
self.coords = tmp.coords[:len(shape)]
|
| 252 |
+
self._shape = tmp.shape[:len(shape)]
|
| 253 |
+
|
| 254 |
+
# Handle truncation of existing dimensions.
|
| 255 |
+
is_truncating = any(old > new for old, new in zip(self.shape, shape))
|
| 256 |
+
if is_truncating:
|
| 257 |
+
mask = np.logical_and.reduce([
|
| 258 |
+
idx < size for idx, size in zip(self.coords, shape)
|
| 259 |
+
])
|
| 260 |
+
if not mask.all():
|
| 261 |
+
self.coords = tuple(idx[mask] for idx in self.coords)
|
| 262 |
+
self.data = self.data[mask]
|
| 263 |
+
|
| 264 |
+
self._shape = shape
|
| 265 |
+
|
| 266 |
+
resize.__doc__ = _spbase.resize.__doc__
|
| 267 |
+
|
| 268 |
+
def toarray(self, order=None, out=None):
|
| 269 |
+
B = self._process_toarray_args(order, out)
|
| 270 |
+
fortran = int(B.flags.f_contiguous)
|
| 271 |
+
if not fortran and not B.flags.c_contiguous:
|
| 272 |
+
raise ValueError("Output array must be C or F contiguous")
|
| 273 |
+
if self.ndim > 2:
|
| 274 |
+
raise ValueError("Cannot densify higher-rank sparse array")
|
| 275 |
+
# This handles both 0D and 1D cases correctly regardless of the
|
| 276 |
+
# original shape.
|
| 277 |
+
M, N = self._shape_as_2d
|
| 278 |
+
coo_todense(M, N, self.nnz, self.row, self.col, self.data,
|
| 279 |
+
B.ravel('A'), fortran)
|
| 280 |
+
# Note: reshape() doesn't copy here, but does return a new array (view).
|
| 281 |
+
return B.reshape(self.shape)
|
| 282 |
+
|
| 283 |
+
toarray.__doc__ = _spbase.toarray.__doc__
|
| 284 |
+
|
| 285 |
+
def tocsc(self, copy=False):
|
| 286 |
+
"""Convert this array/matrix to Compressed Sparse Column format
|
| 287 |
+
|
| 288 |
+
Duplicate entries will be summed together.
|
| 289 |
+
|
| 290 |
+
Examples
|
| 291 |
+
--------
|
| 292 |
+
>>> from numpy import array
|
| 293 |
+
>>> from scipy.sparse import coo_array
|
| 294 |
+
>>> row = array([0, 0, 1, 3, 1, 0, 0])
|
| 295 |
+
>>> col = array([0, 2, 1, 3, 1, 0, 0])
|
| 296 |
+
>>> data = array([1, 1, 1, 1, 1, 1, 1])
|
| 297 |
+
>>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsc()
|
| 298 |
+
>>> A.toarray()
|
| 299 |
+
array([[3, 0, 1, 0],
|
| 300 |
+
[0, 2, 0, 0],
|
| 301 |
+
[0, 0, 0, 0],
|
| 302 |
+
[0, 0, 0, 1]])
|
| 303 |
+
|
| 304 |
+
"""
|
| 305 |
+
if self.ndim != 2:
|
| 306 |
+
raise ValueError("Cannot convert a 1d sparse array to csc format")
|
| 307 |
+
if self.nnz == 0:
|
| 308 |
+
return self._csc_container(self.shape, dtype=self.dtype)
|
| 309 |
+
else:
|
| 310 |
+
from ._csc import csc_array
|
| 311 |
+
indptr, indices, data, shape = self._coo_to_compressed(csc_array._swap)
|
| 312 |
+
|
| 313 |
+
x = self._csc_container((data, indices, indptr), shape=shape)
|
| 314 |
+
if not self.has_canonical_format:
|
| 315 |
+
x.sum_duplicates()
|
| 316 |
+
return x
|
| 317 |
+
|
| 318 |
+
def tocsr(self, copy=False):
|
| 319 |
+
"""Convert this array/matrix to Compressed Sparse Row format
|
| 320 |
+
|
| 321 |
+
Duplicate entries will be summed together.
|
| 322 |
+
|
| 323 |
+
Examples
|
| 324 |
+
--------
|
| 325 |
+
>>> from numpy import array
|
| 326 |
+
>>> from scipy.sparse import coo_array
|
| 327 |
+
>>> row = array([0, 0, 1, 3, 1, 0, 0])
|
| 328 |
+
>>> col = array([0, 2, 1, 3, 1, 0, 0])
|
| 329 |
+
>>> data = array([1, 1, 1, 1, 1, 1, 1])
|
| 330 |
+
>>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsr()
|
| 331 |
+
>>> A.toarray()
|
| 332 |
+
array([[3, 0, 1, 0],
|
| 333 |
+
[0, 2, 0, 0],
|
| 334 |
+
[0, 0, 0, 0],
|
| 335 |
+
[0, 0, 0, 1]])
|
| 336 |
+
|
| 337 |
+
"""
|
| 338 |
+
if self.nnz == 0:
|
| 339 |
+
return self._csr_container(self.shape, dtype=self.dtype)
|
| 340 |
+
else:
|
| 341 |
+
from ._csr import csr_array
|
| 342 |
+
arrays = self._coo_to_compressed(csr_array._swap, copy=copy)
|
| 343 |
+
indptr, indices, data, shape = arrays
|
| 344 |
+
|
| 345 |
+
x = self._csr_container((data, indices, indptr), shape=self.shape)
|
| 346 |
+
if not self.has_canonical_format:
|
| 347 |
+
x.sum_duplicates()
|
| 348 |
+
return x
|
| 349 |
+
|
| 350 |
+
def _coo_to_compressed(self, swap, copy=False):
|
| 351 |
+
"""convert (shape, coords, data) to (indptr, indices, data, shape)"""
|
| 352 |
+
M, N = swap(self._shape_as_2d)
|
| 353 |
+
# convert idx_dtype intc to int32 for pythran.
|
| 354 |
+
# tested in scipy/optimize/tests/test__numdiff.py::test_group_columns
|
| 355 |
+
idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.nnz, N))
|
| 356 |
+
|
| 357 |
+
if self.ndim == 1:
|
| 358 |
+
indices = self.coords[0].copy() if copy else self.coords[0]
|
| 359 |
+
nnz = len(indices)
|
| 360 |
+
indptr = np.array([0, nnz], dtype=idx_dtype)
|
| 361 |
+
data = self.data.copy() if copy else self.data
|
| 362 |
+
return indptr, indices, data, self.shape
|
| 363 |
+
|
| 364 |
+
# ndim == 2
|
| 365 |
+
major, minor = swap(self.coords)
|
| 366 |
+
nnz = len(major)
|
| 367 |
+
major = major.astype(idx_dtype, copy=False)
|
| 368 |
+
minor = minor.astype(idx_dtype, copy=False)
|
| 369 |
+
|
| 370 |
+
indptr = np.empty(M + 1, dtype=idx_dtype)
|
| 371 |
+
indices = np.empty_like(minor, dtype=idx_dtype)
|
| 372 |
+
data = np.empty_like(self.data, dtype=self.dtype)
|
| 373 |
+
|
| 374 |
+
coo_tocsr(M, N, nnz, major, minor, self.data, indptr, indices, data)
|
| 375 |
+
return indptr, indices, data, self.shape
|
| 376 |
+
|
| 377 |
+
def tocoo(self, copy=False):
|
| 378 |
+
if copy:
|
| 379 |
+
return self.copy()
|
| 380 |
+
else:
|
| 381 |
+
return self
|
| 382 |
+
|
| 383 |
+
tocoo.__doc__ = _spbase.tocoo.__doc__
|
| 384 |
+
|
| 385 |
+
def todia(self, copy=False):
|
| 386 |
+
if self.ndim != 2:
|
| 387 |
+
raise ValueError("Cannot convert a 1d sparse array to dia format")
|
| 388 |
+
self.sum_duplicates()
|
| 389 |
+
ks = self.col - self.row # the diagonal for each nonzero
|
| 390 |
+
diags, diag_idx = np.unique(ks, return_inverse=True)
|
| 391 |
+
|
| 392 |
+
if len(diags) > 100:
|
| 393 |
+
# probably undesired, should todia() have a maxdiags parameter?
|
| 394 |
+
warn("Constructing a DIA matrix with %d diagonals "
|
| 395 |
+
"is inefficient" % len(diags),
|
| 396 |
+
SparseEfficiencyWarning, stacklevel=2)
|
| 397 |
+
|
| 398 |
+
#initialize and fill in data array
|
| 399 |
+
if self.data.size == 0:
|
| 400 |
+
data = np.zeros((0, 0), dtype=self.dtype)
|
| 401 |
+
else:
|
| 402 |
+
data = np.zeros((len(diags), self.col.max()+1), dtype=self.dtype)
|
| 403 |
+
data[diag_idx, self.col] = self.data
|
| 404 |
+
|
| 405 |
+
return self._dia_container((data, diags), shape=self.shape)
|
| 406 |
+
|
| 407 |
+
todia.__doc__ = _spbase.todia.__doc__
|
| 408 |
+
|
| 409 |
+
def todok(self, copy=False):
|
| 410 |
+
self.sum_duplicates()
|
| 411 |
+
dok = self._dok_container(self.shape, dtype=self.dtype)
|
| 412 |
+
# ensure that 1d coordinates are not tuples
|
| 413 |
+
if self.ndim == 1:
|
| 414 |
+
coords = self.coords[0]
|
| 415 |
+
else:
|
| 416 |
+
coords = zip(*self.coords)
|
| 417 |
+
|
| 418 |
+
dok._dict = dict(zip(coords, self.data))
|
| 419 |
+
return dok
|
| 420 |
+
|
| 421 |
+
todok.__doc__ = _spbase.todok.__doc__
|
| 422 |
+
|
| 423 |
+
def diagonal(self, k=0):
|
| 424 |
+
if self.ndim != 2:
|
| 425 |
+
raise ValueError("diagonal requires two dimensions")
|
| 426 |
+
rows, cols = self.shape
|
| 427 |
+
if k <= -rows or k >= cols:
|
| 428 |
+
return np.empty(0, dtype=self.data.dtype)
|
| 429 |
+
diag = np.zeros(min(rows + min(k, 0), cols - max(k, 0)),
|
| 430 |
+
dtype=self.dtype)
|
| 431 |
+
diag_mask = (self.row + k) == self.col
|
| 432 |
+
|
| 433 |
+
if self.has_canonical_format:
|
| 434 |
+
row = self.row[diag_mask]
|
| 435 |
+
data = self.data[diag_mask]
|
| 436 |
+
else:
|
| 437 |
+
inds = tuple(idx[diag_mask] for idx in self.coords)
|
| 438 |
+
(row, _), data = self._sum_duplicates(inds, self.data[diag_mask])
|
| 439 |
+
diag[row + min(k, 0)] = data
|
| 440 |
+
|
| 441 |
+
return diag
|
| 442 |
+
|
| 443 |
+
diagonal.__doc__ = _data_matrix.diagonal.__doc__
|
| 444 |
+
|
| 445 |
+
def _setdiag(self, values, k):
|
| 446 |
+
if self.ndim != 2:
|
| 447 |
+
raise ValueError("setting a diagonal requires two dimensions")
|
| 448 |
+
M, N = self.shape
|
| 449 |
+
if values.ndim and not len(values):
|
| 450 |
+
return
|
| 451 |
+
idx_dtype = self.row.dtype
|
| 452 |
+
|
| 453 |
+
# Determine which triples to keep and where to put the new ones.
|
| 454 |
+
full_keep = self.col - self.row != k
|
| 455 |
+
if k < 0:
|
| 456 |
+
max_index = min(M+k, N)
|
| 457 |
+
if values.ndim:
|
| 458 |
+
max_index = min(max_index, len(values))
|
| 459 |
+
keep = np.logical_or(full_keep, self.col >= max_index)
|
| 460 |
+
new_row = np.arange(-k, -k + max_index, dtype=idx_dtype)
|
| 461 |
+
new_col = np.arange(max_index, dtype=idx_dtype)
|
| 462 |
+
else:
|
| 463 |
+
max_index = min(M, N-k)
|
| 464 |
+
if values.ndim:
|
| 465 |
+
max_index = min(max_index, len(values))
|
| 466 |
+
keep = np.logical_or(full_keep, self.row >= max_index)
|
| 467 |
+
new_row = np.arange(max_index, dtype=idx_dtype)
|
| 468 |
+
new_col = np.arange(k, k + max_index, dtype=idx_dtype)
|
| 469 |
+
|
| 470 |
+
# Define the array of data consisting of the entries to be added.
|
| 471 |
+
if values.ndim:
|
| 472 |
+
new_data = values[:max_index]
|
| 473 |
+
else:
|
| 474 |
+
new_data = np.empty(max_index, dtype=self.dtype)
|
| 475 |
+
new_data[:] = values
|
| 476 |
+
|
| 477 |
+
# Update the internal structure.
|
| 478 |
+
self.coords = (np.concatenate((self.row[keep], new_row)),
|
| 479 |
+
np.concatenate((self.col[keep], new_col)))
|
| 480 |
+
self.data = np.concatenate((self.data[keep], new_data))
|
| 481 |
+
self.has_canonical_format = False
|
| 482 |
+
|
| 483 |
+
# needed by _data_matrix
|
| 484 |
+
def _with_data(self, data, copy=True):
|
| 485 |
+
"""Returns a matrix with the same sparsity structure as self,
|
| 486 |
+
but with different data. By default the index arrays are copied.
|
| 487 |
+
"""
|
| 488 |
+
if copy:
|
| 489 |
+
coords = tuple(idx.copy() for idx in self.coords)
|
| 490 |
+
else:
|
| 491 |
+
coords = self.coords
|
| 492 |
+
return self.__class__((data, coords), shape=self.shape, dtype=data.dtype)
|
| 493 |
+
|
| 494 |
+
def sum_duplicates(self) -> None:
|
| 495 |
+
"""Eliminate duplicate entries by adding them together
|
| 496 |
+
|
| 497 |
+
This is an *in place* operation
|
| 498 |
+
"""
|
| 499 |
+
if self.has_canonical_format:
|
| 500 |
+
return
|
| 501 |
+
summed = self._sum_duplicates(self.coords, self.data)
|
| 502 |
+
self.coords, self.data = summed
|
| 503 |
+
self.has_canonical_format = True
|
| 504 |
+
|
| 505 |
+
def _sum_duplicates(self, coords, data):
|
| 506 |
+
# Assumes coords not in canonical format.
|
| 507 |
+
if len(data) == 0:
|
| 508 |
+
return coords, data
|
| 509 |
+
# Sort coords w.r.t. rows, then cols. This corresponds to C-order,
|
| 510 |
+
# which we rely on for argmin/argmax to return the first index in the
|
| 511 |
+
# same way that numpy does (in the case of ties).
|
| 512 |
+
order = np.lexsort(coords[::-1])
|
| 513 |
+
coords = tuple(idx[order] for idx in coords)
|
| 514 |
+
data = data[order]
|
| 515 |
+
unique_mask = np.logical_or.reduce([
|
| 516 |
+
idx[1:] != idx[:-1] for idx in coords
|
| 517 |
+
])
|
| 518 |
+
unique_mask = np.append(True, unique_mask)
|
| 519 |
+
coords = tuple(idx[unique_mask] for idx in coords)
|
| 520 |
+
unique_inds, = np.nonzero(unique_mask)
|
| 521 |
+
data = np.add.reduceat(data, unique_inds, dtype=self.dtype)
|
| 522 |
+
return coords, data
|
| 523 |
+
|
| 524 |
+
def eliminate_zeros(self):
|
| 525 |
+
"""Remove zero entries from the array/matrix
|
| 526 |
+
|
| 527 |
+
This is an *in place* operation
|
| 528 |
+
"""
|
| 529 |
+
mask = self.data != 0
|
| 530 |
+
self.data = self.data[mask]
|
| 531 |
+
self.coords = tuple(idx[mask] for idx in self.coords)
|
| 532 |
+
|
| 533 |
+
#######################
|
| 534 |
+
# Arithmetic handlers #
|
| 535 |
+
#######################
|
| 536 |
+
|
| 537 |
+
def _add_dense(self, other):
|
| 538 |
+
if other.shape != self.shape:
|
| 539 |
+
raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})')
|
| 540 |
+
dtype = upcast_char(self.dtype.char, other.dtype.char)
|
| 541 |
+
result = np.array(other, dtype=dtype, copy=True)
|
| 542 |
+
fortran = int(result.flags.f_contiguous)
|
| 543 |
+
M, N = self._shape_as_2d
|
| 544 |
+
coo_todense(M, N, self.nnz, self.row, self.col, self.data,
|
| 545 |
+
result.ravel('A'), fortran)
|
| 546 |
+
return self._container(result, copy=False)
|
| 547 |
+
|
| 548 |
+
def _matmul_vector(self, other):
|
| 549 |
+
result_shape = self.shape[0] if self.ndim > 1 else 1
|
| 550 |
+
result = np.zeros(result_shape,
|
| 551 |
+
dtype=upcast_char(self.dtype.char, other.dtype.char))
|
| 552 |
+
|
| 553 |
+
if self.ndim == 2:
|
| 554 |
+
col = self.col
|
| 555 |
+
row = self.row
|
| 556 |
+
elif self.ndim == 1:
|
| 557 |
+
col = self.coords[0]
|
| 558 |
+
row = np.zeros_like(col)
|
| 559 |
+
else:
|
| 560 |
+
raise NotImplementedError(
|
| 561 |
+
f"coo_matvec not implemented for ndim={self.ndim}")
|
| 562 |
+
|
| 563 |
+
coo_matvec(self.nnz, row, col, self.data, other, result)
|
| 564 |
+
# Array semantics return a scalar here, not a single-element array.
|
| 565 |
+
if isinstance(self, sparray) and result_shape == 1:
|
| 566 |
+
return result[0]
|
| 567 |
+
return result
|
| 568 |
+
|
| 569 |
+
def _matmul_multivector(self, other):
|
| 570 |
+
result_dtype = upcast_char(self.dtype.char, other.dtype.char)
|
| 571 |
+
if self.ndim == 2:
|
| 572 |
+
result_shape = (other.shape[1], self.shape[0])
|
| 573 |
+
col = self.col
|
| 574 |
+
row = self.row
|
| 575 |
+
elif self.ndim == 1:
|
| 576 |
+
result_shape = (other.shape[1],)
|
| 577 |
+
col = self.coords[0]
|
| 578 |
+
row = np.zeros_like(col)
|
| 579 |
+
else:
|
| 580 |
+
raise NotImplementedError(
|
| 581 |
+
f"coo_matvec not implemented for ndim={self.ndim}")
|
| 582 |
+
|
| 583 |
+
result = np.zeros(result_shape, dtype=result_dtype)
|
| 584 |
+
for i, other_col in enumerate(other.T):
|
| 585 |
+
coo_matvec(self.nnz, row, col, self.data, other_col, result[i:i + 1])
|
| 586 |
+
return result.T.view(type=type(other))
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def _ravel_coords(coords, shape, order='C'):
|
| 590 |
+
"""Like np.ravel_multi_index, but avoids some overflow issues."""
|
| 591 |
+
if len(coords) == 1:
|
| 592 |
+
return coords[0]
|
| 593 |
+
# Handle overflow as in https://github.com/scipy/scipy/pull/9132
|
| 594 |
+
if len(coords) == 2:
|
| 595 |
+
nrows, ncols = shape
|
| 596 |
+
row, col = coords
|
| 597 |
+
if order == 'C':
|
| 598 |
+
maxval = (ncols * max(0, nrows - 1) + max(0, ncols - 1))
|
| 599 |
+
idx_dtype = get_index_dtype(maxval=maxval)
|
| 600 |
+
return np.multiply(ncols, row, dtype=idx_dtype) + col
|
| 601 |
+
elif order == 'F':
|
| 602 |
+
maxval = (nrows * max(0, ncols - 1) + max(0, nrows - 1))
|
| 603 |
+
idx_dtype = get_index_dtype(maxval=maxval)
|
| 604 |
+
return np.multiply(nrows, col, dtype=idx_dtype) + row
|
| 605 |
+
else:
|
| 606 |
+
raise ValueError("'order' must be 'C' or 'F'")
|
| 607 |
+
return np.ravel_multi_index(coords, shape, order=order)
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def isspmatrix_coo(x):
|
| 611 |
+
"""Is `x` of coo_matrix type?
|
| 612 |
+
|
| 613 |
+
Parameters
|
| 614 |
+
----------
|
| 615 |
+
x
|
| 616 |
+
object to check for being a coo matrix
|
| 617 |
+
|
| 618 |
+
Returns
|
| 619 |
+
-------
|
| 620 |
+
bool
|
| 621 |
+
True if `x` is a coo matrix, False otherwise
|
| 622 |
+
|
| 623 |
+
Examples
|
| 624 |
+
--------
|
| 625 |
+
>>> from scipy.sparse import coo_array, coo_matrix, csr_matrix, isspmatrix_coo
|
| 626 |
+
>>> isspmatrix_coo(coo_matrix([[5]]))
|
| 627 |
+
True
|
| 628 |
+
>>> isspmatrix_coo(coo_array([[5]]))
|
| 629 |
+
False
|
| 630 |
+
>>> isspmatrix_coo(csr_matrix([[5]]))
|
| 631 |
+
False
|
| 632 |
+
"""
|
| 633 |
+
return isinstance(x, coo_matrix)
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
# This namespace class separates array from matrix with isinstance
|
| 637 |
+
class coo_array(_coo_base, sparray):
|
| 638 |
+
"""
|
| 639 |
+
A sparse array in COOrdinate format.
|
| 640 |
+
|
| 641 |
+
Also known as the 'ijv' or 'triplet' format.
|
| 642 |
+
|
| 643 |
+
This can be instantiated in several ways:
|
| 644 |
+
coo_array(D)
|
| 645 |
+
where D is an ndarray
|
| 646 |
+
|
| 647 |
+
coo_array(S)
|
| 648 |
+
with another sparse array or matrix S (equivalent to S.tocoo())
|
| 649 |
+
|
| 650 |
+
coo_array(shape, [dtype])
|
| 651 |
+
to construct an empty sparse array with shape `shape`
|
| 652 |
+
dtype is optional, defaulting to dtype='d'.
|
| 653 |
+
|
| 654 |
+
coo_array((data, coords), [shape])
|
| 655 |
+
to construct from existing data and index arrays:
|
| 656 |
+
1. data[:] the entries of the sparse array, in any order
|
| 657 |
+
2. coords[i][:] the axis-i coordinates of the data entries
|
| 658 |
+
|
| 659 |
+
Where ``A[coords] = data``, and coords is a tuple of index arrays.
|
| 660 |
+
When shape is not specified, it is inferred from the index arrays.
|
| 661 |
+
|
| 662 |
+
Attributes
|
| 663 |
+
----------
|
| 664 |
+
dtype : dtype
|
| 665 |
+
Data type of the sparse array
|
| 666 |
+
shape : tuple of integers
|
| 667 |
+
Shape of the sparse array
|
| 668 |
+
ndim : int
|
| 669 |
+
Number of dimensions of the sparse array
|
| 670 |
+
nnz
|
| 671 |
+
size
|
| 672 |
+
data
|
| 673 |
+
COO format data array of the sparse array
|
| 674 |
+
coords
|
| 675 |
+
COO format tuple of index arrays
|
| 676 |
+
has_canonical_format : bool
|
| 677 |
+
Whether the matrix has sorted coordinates and no duplicates
|
| 678 |
+
format
|
| 679 |
+
T
|
| 680 |
+
|
| 681 |
+
Notes
|
| 682 |
+
-----
|
| 683 |
+
|
| 684 |
+
Sparse arrays can be used in arithmetic operations: they support
|
| 685 |
+
addition, subtraction, multiplication, division, and matrix power.
|
| 686 |
+
|
| 687 |
+
Advantages of the COO format
|
| 688 |
+
- facilitates fast conversion among sparse formats
|
| 689 |
+
- permits duplicate entries (see example)
|
| 690 |
+
- very fast conversion to and from CSR/CSC formats
|
| 691 |
+
|
| 692 |
+
Disadvantages of the COO format
|
| 693 |
+
- does not directly support:
|
| 694 |
+
+ arithmetic operations
|
| 695 |
+
+ slicing
|
| 696 |
+
|
| 697 |
+
Intended Usage
|
| 698 |
+
- COO is a fast format for constructing sparse arrays
|
| 699 |
+
- Once a COO array has been constructed, convert to CSR or
|
| 700 |
+
CSC format for fast arithmetic and matrix vector operations
|
| 701 |
+
- By default when converting to CSR or CSC format, duplicate (i,j)
|
| 702 |
+
entries will be summed together. This facilitates efficient
|
| 703 |
+
construction of finite element matrices and the like. (see example)
|
| 704 |
+
|
| 705 |
+
Canonical format
|
| 706 |
+
- Entries and coordinates sorted by row, then column.
|
| 707 |
+
- There are no duplicate entries (i.e. duplicate (i,j) locations)
|
| 708 |
+
- Data arrays MAY have explicit zeros.
|
| 709 |
+
|
| 710 |
+
Examples
|
| 711 |
+
--------
|
| 712 |
+
|
| 713 |
+
>>> # Constructing an empty sparse array
|
| 714 |
+
>>> import numpy as np
|
| 715 |
+
>>> from scipy.sparse import coo_array
|
| 716 |
+
>>> coo_array((3, 4), dtype=np.int8).toarray()
|
| 717 |
+
array([[0, 0, 0, 0],
|
| 718 |
+
[0, 0, 0, 0],
|
| 719 |
+
[0, 0, 0, 0]], dtype=int8)
|
| 720 |
+
|
| 721 |
+
>>> # Constructing a sparse array using ijv format
|
| 722 |
+
>>> row = np.array([0, 3, 1, 0])
|
| 723 |
+
>>> col = np.array([0, 3, 1, 2])
|
| 724 |
+
>>> data = np.array([4, 5, 7, 9])
|
| 725 |
+
>>> coo_array((data, (row, col)), shape=(4, 4)).toarray()
|
| 726 |
+
array([[4, 0, 9, 0],
|
| 727 |
+
[0, 7, 0, 0],
|
| 728 |
+
[0, 0, 0, 0],
|
| 729 |
+
[0, 0, 0, 5]])
|
| 730 |
+
|
| 731 |
+
>>> # Constructing a sparse array with duplicate coordinates
|
| 732 |
+
>>> row = np.array([0, 0, 1, 3, 1, 0, 0])
|
| 733 |
+
>>> col = np.array([0, 2, 1, 3, 1, 0, 0])
|
| 734 |
+
>>> data = np.array([1, 1, 1, 1, 1, 1, 1])
|
| 735 |
+
>>> coo = coo_array((data, (row, col)), shape=(4, 4))
|
| 736 |
+
>>> # Duplicate coordinates are maintained until implicitly or explicitly summed
|
| 737 |
+
>>> np.max(coo.data)
|
| 738 |
+
1
|
| 739 |
+
>>> coo.toarray()
|
| 740 |
+
array([[3, 0, 1, 0],
|
| 741 |
+
[0, 2, 0, 0],
|
| 742 |
+
[0, 0, 0, 0],
|
| 743 |
+
[0, 0, 0, 1]])
|
| 744 |
+
|
| 745 |
+
"""
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
class coo_matrix(spmatrix, _coo_base):
|
| 749 |
+
"""
|
| 750 |
+
A sparse matrix in COOrdinate format.
|
| 751 |
+
|
| 752 |
+
Also known as the 'ijv' or 'triplet' format.
|
| 753 |
+
|
| 754 |
+
This can be instantiated in several ways:
|
| 755 |
+
coo_matrix(D)
|
| 756 |
+
where D is a 2-D ndarray
|
| 757 |
+
|
| 758 |
+
coo_matrix(S)
|
| 759 |
+
with another sparse array or matrix S (equivalent to S.tocoo())
|
| 760 |
+
|
| 761 |
+
coo_matrix((M, N), [dtype])
|
| 762 |
+
to construct an empty matrix with shape (M, N)
|
| 763 |
+
dtype is optional, defaulting to dtype='d'.
|
| 764 |
+
|
| 765 |
+
coo_matrix((data, (i, j)), [shape=(M, N)])
|
| 766 |
+
to construct from three arrays:
|
| 767 |
+
1. data[:] the entries of the matrix, in any order
|
| 768 |
+
2. i[:] the row indices of the matrix entries
|
| 769 |
+
3. j[:] the column indices of the matrix entries
|
| 770 |
+
|
| 771 |
+
Where ``A[i[k], j[k]] = data[k]``. When shape is not
|
| 772 |
+
specified, it is inferred from the index arrays
|
| 773 |
+
|
| 774 |
+
Attributes
|
| 775 |
+
----------
|
| 776 |
+
dtype : dtype
|
| 777 |
+
Data type of the matrix
|
| 778 |
+
shape : 2-tuple
|
| 779 |
+
Shape of the matrix
|
| 780 |
+
ndim : int
|
| 781 |
+
Number of dimensions (this is always 2)
|
| 782 |
+
nnz
|
| 783 |
+
size
|
| 784 |
+
data
|
| 785 |
+
COO format data array of the matrix
|
| 786 |
+
row
|
| 787 |
+
COO format row index array of the matrix
|
| 788 |
+
col
|
| 789 |
+
COO format column index array of the matrix
|
| 790 |
+
has_canonical_format : bool
|
| 791 |
+
Whether the matrix has sorted indices and no duplicates
|
| 792 |
+
format
|
| 793 |
+
T
|
| 794 |
+
|
| 795 |
+
Notes
|
| 796 |
+
-----
|
| 797 |
+
|
| 798 |
+
Sparse matrices can be used in arithmetic operations: they support
|
| 799 |
+
addition, subtraction, multiplication, division, and matrix power.
|
| 800 |
+
|
| 801 |
+
Advantages of the COO format
|
| 802 |
+
- facilitates fast conversion among sparse formats
|
| 803 |
+
- permits duplicate entries (see example)
|
| 804 |
+
- very fast conversion to and from CSR/CSC formats
|
| 805 |
+
|
| 806 |
+
Disadvantages of the COO format
|
| 807 |
+
- does not directly support:
|
| 808 |
+
+ arithmetic operations
|
| 809 |
+
+ slicing
|
| 810 |
+
|
| 811 |
+
Intended Usage
|
| 812 |
+
- COO is a fast format for constructing sparse matrices
|
| 813 |
+
- Once a COO matrix has been constructed, convert to CSR or
|
| 814 |
+
CSC format for fast arithmetic and matrix vector operations
|
| 815 |
+
- By default when converting to CSR or CSC format, duplicate (i,j)
|
| 816 |
+
entries will be summed together. This facilitates efficient
|
| 817 |
+
construction of finite element matrices and the like. (see example)
|
| 818 |
+
|
| 819 |
+
Canonical format
|
| 820 |
+
- Entries and coordinates sorted by row, then column.
|
| 821 |
+
- There are no duplicate entries (i.e. duplicate (i,j) locations)
|
| 822 |
+
- Data arrays MAY have explicit zeros.
|
| 823 |
+
|
| 824 |
+
Examples
|
| 825 |
+
--------
|
| 826 |
+
|
| 827 |
+
>>> # Constructing an empty matrix
|
| 828 |
+
>>> import numpy as np
|
| 829 |
+
>>> from scipy.sparse import coo_matrix
|
| 830 |
+
>>> coo_matrix((3, 4), dtype=np.int8).toarray()
|
| 831 |
+
array([[0, 0, 0, 0],
|
| 832 |
+
[0, 0, 0, 0],
|
| 833 |
+
[0, 0, 0, 0]], dtype=int8)
|
| 834 |
+
|
| 835 |
+
>>> # Constructing a matrix using ijv format
|
| 836 |
+
>>> row = np.array([0, 3, 1, 0])
|
| 837 |
+
>>> col = np.array([0, 3, 1, 2])
|
| 838 |
+
>>> data = np.array([4, 5, 7, 9])
|
| 839 |
+
>>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray()
|
| 840 |
+
array([[4, 0, 9, 0],
|
| 841 |
+
[0, 7, 0, 0],
|
| 842 |
+
[0, 0, 0, 0],
|
| 843 |
+
[0, 0, 0, 5]])
|
| 844 |
+
|
| 845 |
+
>>> # Constructing a matrix with duplicate coordinates
|
| 846 |
+
>>> row = np.array([0, 0, 1, 3, 1, 0, 0])
|
| 847 |
+
>>> col = np.array([0, 2, 1, 3, 1, 0, 0])
|
| 848 |
+
>>> data = np.array([1, 1, 1, 1, 1, 1, 1])
|
| 849 |
+
>>> coo = coo_matrix((data, (row, col)), shape=(4, 4))
|
| 850 |
+
>>> # Duplicate coordinates are maintained until implicitly or explicitly summed
|
| 851 |
+
>>> np.max(coo.data)
|
| 852 |
+
1
|
| 853 |
+
>>> coo.toarray()
|
| 854 |
+
array([[3, 0, 1, 0],
|
| 855 |
+
[0, 2, 0, 0],
|
| 856 |
+
[0, 0, 0, 0],
|
| 857 |
+
[0, 0, 0, 1]])
|
| 858 |
+
|
| 859 |
+
"""
|
| 860 |
+
|
| 861 |
+
def __setstate__(self, state):
|
| 862 |
+
if 'coords' not in state:
|
| 863 |
+
# For retro-compatibility with the previous attributes
|
| 864 |
+
# storing nnz coordinates for 2D COO matrix.
|
| 865 |
+
state['coords'] = (state.pop('row'), state.pop('col'))
|
| 866 |
+
self.__dict__.update(state)
|
parrot/lib/python3.10/site-packages/scipy/sparse/_csr.py
ADDED
|
@@ -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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compressed Sparse Row matrix format"""
|
| 2 |
+
|
| 3 |
+
__docformat__ = "restructuredtext en"
|
| 4 |
+
|
| 5 |
+
__all__ = ['csr_array', 'csr_matrix', 'isspmatrix_csr']
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
from ._matrix import spmatrix
|
| 10 |
+
from ._base import _spbase, sparray
|
| 11 |
+
from ._sparsetools import (csr_tocsc, csr_tobsr, csr_count_blocks,
|
| 12 |
+
get_csr_submatrix)
|
| 13 |
+
from ._sputils import upcast
|
| 14 |
+
|
| 15 |
+
from ._compressed import _cs_matrix
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class _csr_base(_cs_matrix):
|
| 19 |
+
_format = 'csr'
|
| 20 |
+
|
| 21 |
+
# override IndexMixin.__getitem__ for 1d case until fully implemented
|
| 22 |
+
def __getitem__(self, key):
|
| 23 |
+
if self.ndim == 2:
|
| 24 |
+
return super().__getitem__(key)
|
| 25 |
+
|
| 26 |
+
if isinstance(key, tuple) and len(key) == 1:
|
| 27 |
+
key = key[0]
|
| 28 |
+
INT_TYPES = (int, np.integer)
|
| 29 |
+
if isinstance(key, INT_TYPES):
|
| 30 |
+
if key < 0:
|
| 31 |
+
key += self.shape[-1]
|
| 32 |
+
if key < 0 or key >= self.shape[-1]:
|
| 33 |
+
raise IndexError('index value out of bounds')
|
| 34 |
+
return self._get_int(key)
|
| 35 |
+
else:
|
| 36 |
+
raise IndexError('array/slice index for 1d csr_array not yet supported')
|
| 37 |
+
|
| 38 |
+
# override IndexMixin.__setitem__ for 1d case until fully implemented
|
| 39 |
+
def __setitem__(self, key, value):
|
| 40 |
+
if self.ndim == 2:
|
| 41 |
+
return super().__setitem__(key, value)
|
| 42 |
+
|
| 43 |
+
if isinstance(key, tuple) and len(key) == 1:
|
| 44 |
+
key = key[0]
|
| 45 |
+
INT_TYPES = (int, np.integer)
|
| 46 |
+
if isinstance(key, INT_TYPES):
|
| 47 |
+
if key < 0:
|
| 48 |
+
key += self.shape[-1]
|
| 49 |
+
if key < 0 or key >= self.shape[-1]:
|
| 50 |
+
raise IndexError('index value out of bounds')
|
| 51 |
+
return self._set_int(key, value)
|
| 52 |
+
else:
|
| 53 |
+
raise IndexError('array index for 1d csr_array not yet provided')
|
| 54 |
+
|
| 55 |
+
def transpose(self, axes=None, copy=False):
|
| 56 |
+
if axes is not None and axes != (1, 0):
|
| 57 |
+
raise ValueError("Sparse arrays/matrices do not support "
|
| 58 |
+
"an 'axes' parameter because swapping "
|
| 59 |
+
"dimensions is the only logical permutation.")
|
| 60 |
+
|
| 61 |
+
if self.ndim == 1:
|
| 62 |
+
return self.copy() if copy else self
|
| 63 |
+
M, N = self.shape
|
| 64 |
+
return self._csc_container((self.data, self.indices,
|
| 65 |
+
self.indptr), shape=(N, M), copy=copy)
|
| 66 |
+
|
| 67 |
+
transpose.__doc__ = _spbase.transpose.__doc__
|
| 68 |
+
|
| 69 |
+
def tolil(self, copy=False):
|
| 70 |
+
if self.ndim != 2:
|
| 71 |
+
raise ValueError("Cannot convert a 1d sparse array to lil format")
|
| 72 |
+
lil = self._lil_container(self.shape, dtype=self.dtype)
|
| 73 |
+
|
| 74 |
+
self.sum_duplicates()
|
| 75 |
+
ptr,ind,dat = self.indptr,self.indices,self.data
|
| 76 |
+
rows, data = lil.rows, lil.data
|
| 77 |
+
|
| 78 |
+
for n in range(self.shape[0]):
|
| 79 |
+
start = ptr[n]
|
| 80 |
+
end = ptr[n+1]
|
| 81 |
+
rows[n] = ind[start:end].tolist()
|
| 82 |
+
data[n] = dat[start:end].tolist()
|
| 83 |
+
|
| 84 |
+
return lil
|
| 85 |
+
|
| 86 |
+
tolil.__doc__ = _spbase.tolil.__doc__
|
| 87 |
+
|
| 88 |
+
def tocsr(self, copy=False):
|
| 89 |
+
if copy:
|
| 90 |
+
return self.copy()
|
| 91 |
+
else:
|
| 92 |
+
return self
|
| 93 |
+
|
| 94 |
+
tocsr.__doc__ = _spbase.tocsr.__doc__
|
| 95 |
+
|
| 96 |
+
def tocsc(self, copy=False):
|
| 97 |
+
if self.ndim != 2:
|
| 98 |
+
raise ValueError("Cannot convert a 1d sparse array to csc format")
|
| 99 |
+
M, N = self.shape
|
| 100 |
+
idx_dtype = self._get_index_dtype((self.indptr, self.indices),
|
| 101 |
+
maxval=max(self.nnz, M))
|
| 102 |
+
indptr = np.empty(N + 1, dtype=idx_dtype)
|
| 103 |
+
indices = np.empty(self.nnz, dtype=idx_dtype)
|
| 104 |
+
data = np.empty(self.nnz, dtype=upcast(self.dtype))
|
| 105 |
+
|
| 106 |
+
csr_tocsc(M, N,
|
| 107 |
+
self.indptr.astype(idx_dtype),
|
| 108 |
+
self.indices.astype(idx_dtype),
|
| 109 |
+
self.data,
|
| 110 |
+
indptr,
|
| 111 |
+
indices,
|
| 112 |
+
data)
|
| 113 |
+
|
| 114 |
+
A = self._csc_container((data, indices, indptr), shape=self.shape)
|
| 115 |
+
A.has_sorted_indices = True
|
| 116 |
+
return A
|
| 117 |
+
|
| 118 |
+
tocsc.__doc__ = _spbase.tocsc.__doc__
|
| 119 |
+
|
| 120 |
+
def tobsr(self, blocksize=None, copy=True):
|
| 121 |
+
if self.ndim != 2:
|
| 122 |
+
raise ValueError("Cannot convert a 1d sparse array to bsr format")
|
| 123 |
+
if blocksize is None:
|
| 124 |
+
from ._spfuncs import estimate_blocksize
|
| 125 |
+
return self.tobsr(blocksize=estimate_blocksize(self))
|
| 126 |
+
|
| 127 |
+
elif blocksize == (1,1):
|
| 128 |
+
arg1 = (self.data.reshape(-1,1,1),self.indices,self.indptr)
|
| 129 |
+
return self._bsr_container(arg1, shape=self.shape, copy=copy)
|
| 130 |
+
|
| 131 |
+
else:
|
| 132 |
+
R,C = blocksize
|
| 133 |
+
M,N = self.shape
|
| 134 |
+
|
| 135 |
+
if R < 1 or C < 1 or M % R != 0 or N % C != 0:
|
| 136 |
+
raise ValueError('invalid blocksize %s' % blocksize)
|
| 137 |
+
|
| 138 |
+
blks = csr_count_blocks(M,N,R,C,self.indptr,self.indices)
|
| 139 |
+
|
| 140 |
+
idx_dtype = self._get_index_dtype((self.indptr, self.indices),
|
| 141 |
+
maxval=max(N//C, blks))
|
| 142 |
+
indptr = np.empty(M//R+1, dtype=idx_dtype)
|
| 143 |
+
indices = np.empty(blks, dtype=idx_dtype)
|
| 144 |
+
data = np.zeros((blks,R,C), dtype=self.dtype)
|
| 145 |
+
|
| 146 |
+
csr_tobsr(M, N, R, C,
|
| 147 |
+
self.indptr.astype(idx_dtype),
|
| 148 |
+
self.indices.astype(idx_dtype),
|
| 149 |
+
self.data,
|
| 150 |
+
indptr, indices, data.ravel())
|
| 151 |
+
|
| 152 |
+
return self._bsr_container(
|
| 153 |
+
(data, indices, indptr), shape=self.shape
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
tobsr.__doc__ = _spbase.tobsr.__doc__
|
| 157 |
+
|
| 158 |
+
# these functions are used by the parent class (_cs_matrix)
|
| 159 |
+
# to remove redundancy between csc_matrix and csr_array
|
| 160 |
+
@staticmethod
|
| 161 |
+
def _swap(x):
|
| 162 |
+
"""swap the members of x if this is a column-oriented matrix
|
| 163 |
+
"""
|
| 164 |
+
return x
|
| 165 |
+
|
| 166 |
+
def __iter__(self):
|
| 167 |
+
if self.ndim == 1:
|
| 168 |
+
zero = self.dtype.type(0)
|
| 169 |
+
u = 0
|
| 170 |
+
for v, d in zip(self.indices, self.data):
|
| 171 |
+
for _ in range(v - u):
|
| 172 |
+
yield zero
|
| 173 |
+
yield d
|
| 174 |
+
u = v + 1
|
| 175 |
+
for _ in range(self.shape[0] - u):
|
| 176 |
+
yield zero
|
| 177 |
+
return
|
| 178 |
+
|
| 179 |
+
indptr = np.zeros(2, dtype=self.indptr.dtype)
|
| 180 |
+
# return 1d (sparray) or 2drow (spmatrix)
|
| 181 |
+
shape = self.shape[1:] if isinstance(self, sparray) else (1, self.shape[1])
|
| 182 |
+
i0 = 0
|
| 183 |
+
for i1 in self.indptr[1:]:
|
| 184 |
+
indptr[1] = i1 - i0
|
| 185 |
+
indices = self.indices[i0:i1]
|
| 186 |
+
data = self.data[i0:i1]
|
| 187 |
+
yield self.__class__((data, indices, indptr), shape=shape, copy=True)
|
| 188 |
+
i0 = i1
|
| 189 |
+
|
| 190 |
+
def _getrow(self, i):
|
| 191 |
+
"""Returns a copy of row i of the matrix, as a (1 x n)
|
| 192 |
+
CSR matrix (row vector).
|
| 193 |
+
"""
|
| 194 |
+
if self.ndim == 1:
|
| 195 |
+
if i not in (0, -1):
|
| 196 |
+
raise IndexError(f'index ({i}) out of range')
|
| 197 |
+
return self.reshape((1, self.shape[0]), copy=True)
|
| 198 |
+
|
| 199 |
+
M, N = self.shape
|
| 200 |
+
i = int(i)
|
| 201 |
+
if i < 0:
|
| 202 |
+
i += M
|
| 203 |
+
if i < 0 or i >= M:
|
| 204 |
+
raise IndexError('index (%d) out of range' % i)
|
| 205 |
+
indptr, indices, data = get_csr_submatrix(
|
| 206 |
+
M, N, self.indptr, self.indices, self.data, i, i + 1, 0, N)
|
| 207 |
+
return self.__class__((data, indices, indptr), shape=(1, N),
|
| 208 |
+
dtype=self.dtype, copy=False)
|
| 209 |
+
|
| 210 |
+
def _getcol(self, i):
|
| 211 |
+
"""Returns a copy of column i. A (m x 1) sparse array (column vector).
|
| 212 |
+
"""
|
| 213 |
+
if self.ndim == 1:
|
| 214 |
+
raise ValueError("getcol not provided for 1d arrays. Use indexing A[j]")
|
| 215 |
+
M, N = self.shape
|
| 216 |
+
i = int(i)
|
| 217 |
+
if i < 0:
|
| 218 |
+
i += N
|
| 219 |
+
if i < 0 or i >= N:
|
| 220 |
+
raise IndexError('index (%d) out of range' % i)
|
| 221 |
+
indptr, indices, data = get_csr_submatrix(
|
| 222 |
+
M, N, self.indptr, self.indices, self.data, 0, M, i, i + 1)
|
| 223 |
+
return self.__class__((data, indices, indptr), shape=(M, 1),
|
| 224 |
+
dtype=self.dtype, copy=False)
|
| 225 |
+
|
| 226 |
+
def _get_intXarray(self, row, col):
|
| 227 |
+
return self._getrow(row)._minor_index_fancy(col)
|
| 228 |
+
|
| 229 |
+
def _get_intXslice(self, row, col):
|
| 230 |
+
if col.step in (1, None):
|
| 231 |
+
return self._get_submatrix(row, col, copy=True)
|
| 232 |
+
# TODO: uncomment this once it's faster:
|
| 233 |
+
# return self._getrow(row)._minor_slice(col)
|
| 234 |
+
|
| 235 |
+
M, N = self.shape
|
| 236 |
+
start, stop, stride = col.indices(N)
|
| 237 |
+
|
| 238 |
+
ii, jj = self.indptr[row:row+2]
|
| 239 |
+
row_indices = self.indices[ii:jj]
|
| 240 |
+
row_data = self.data[ii:jj]
|
| 241 |
+
|
| 242 |
+
if stride > 0:
|
| 243 |
+
ind = (row_indices >= start) & (row_indices < stop)
|
| 244 |
+
else:
|
| 245 |
+
ind = (row_indices <= start) & (row_indices > stop)
|
| 246 |
+
|
| 247 |
+
if abs(stride) > 1:
|
| 248 |
+
ind &= (row_indices - start) % stride == 0
|
| 249 |
+
|
| 250 |
+
row_indices = (row_indices[ind] - start) // stride
|
| 251 |
+
row_data = row_data[ind]
|
| 252 |
+
row_indptr = np.array([0, len(row_indices)])
|
| 253 |
+
|
| 254 |
+
if stride < 0:
|
| 255 |
+
row_data = row_data[::-1]
|
| 256 |
+
row_indices = abs(row_indices[::-1])
|
| 257 |
+
|
| 258 |
+
shape = (1, max(0, int(np.ceil(float(stop - start) / stride))))
|
| 259 |
+
return self.__class__((row_data, row_indices, row_indptr), shape=shape,
|
| 260 |
+
dtype=self.dtype, copy=False)
|
| 261 |
+
|
| 262 |
+
def _get_sliceXint(self, row, col):
|
| 263 |
+
if row.step in (1, None):
|
| 264 |
+
return self._get_submatrix(row, col, copy=True)
|
| 265 |
+
return self._major_slice(row)._get_submatrix(minor=col)
|
| 266 |
+
|
| 267 |
+
def _get_sliceXarray(self, row, col):
|
| 268 |
+
return self._major_slice(row)._minor_index_fancy(col)
|
| 269 |
+
|
| 270 |
+
def _get_arrayXint(self, row, col):
|
| 271 |
+
return self._major_index_fancy(row)._get_submatrix(minor=col)
|
| 272 |
+
|
| 273 |
+
def _get_arrayXslice(self, row, col):
|
| 274 |
+
if col.step not in (1, None):
|
| 275 |
+
col = np.arange(*col.indices(self.shape[1]))
|
| 276 |
+
return self._get_arrayXarray(row, col)
|
| 277 |
+
return self._major_index_fancy(row)._get_submatrix(minor=col)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def isspmatrix_csr(x):
|
| 281 |
+
"""Is `x` of csr_matrix type?
|
| 282 |
+
|
| 283 |
+
Parameters
|
| 284 |
+
----------
|
| 285 |
+
x
|
| 286 |
+
object to check for being a csr matrix
|
| 287 |
+
|
| 288 |
+
Returns
|
| 289 |
+
-------
|
| 290 |
+
bool
|
| 291 |
+
True if `x` is a csr matrix, False otherwise
|
| 292 |
+
|
| 293 |
+
Examples
|
| 294 |
+
--------
|
| 295 |
+
>>> from scipy.sparse import csr_array, csr_matrix, coo_matrix, isspmatrix_csr
|
| 296 |
+
>>> isspmatrix_csr(csr_matrix([[5]]))
|
| 297 |
+
True
|
| 298 |
+
>>> isspmatrix_csr(csr_array([[5]]))
|
| 299 |
+
False
|
| 300 |
+
>>> isspmatrix_csr(coo_matrix([[5]]))
|
| 301 |
+
False
|
| 302 |
+
"""
|
| 303 |
+
return isinstance(x, csr_matrix)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# This namespace class separates array from matrix with isinstance
|
| 307 |
+
class csr_array(_csr_base, sparray):
|
| 308 |
+
"""
|
| 309 |
+
Compressed Sparse Row array.
|
| 310 |
+
|
| 311 |
+
This can be instantiated in several ways:
|
| 312 |
+
csr_array(D)
|
| 313 |
+
where D is a 2-D ndarray
|
| 314 |
+
|
| 315 |
+
csr_array(S)
|
| 316 |
+
with another sparse array or matrix S (equivalent to S.tocsr())
|
| 317 |
+
|
| 318 |
+
csr_array((M, N), [dtype])
|
| 319 |
+
to construct an empty array with shape (M, N)
|
| 320 |
+
dtype is optional, defaulting to dtype='d'.
|
| 321 |
+
|
| 322 |
+
csr_array((data, (row_ind, col_ind)), [shape=(M, N)])
|
| 323 |
+
where ``data``, ``row_ind`` and ``col_ind`` satisfy the
|
| 324 |
+
relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
|
| 325 |
+
|
| 326 |
+
csr_array((data, indices, indptr), [shape=(M, N)])
|
| 327 |
+
is the standard CSR representation where the column indices for
|
| 328 |
+
row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their
|
| 329 |
+
corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``.
|
| 330 |
+
If the shape parameter is not supplied, the array dimensions
|
| 331 |
+
are inferred from the index arrays.
|
| 332 |
+
|
| 333 |
+
Attributes
|
| 334 |
+
----------
|
| 335 |
+
dtype : dtype
|
| 336 |
+
Data type of the array
|
| 337 |
+
shape : 2-tuple
|
| 338 |
+
Shape of the array
|
| 339 |
+
ndim : int
|
| 340 |
+
Number of dimensions (this is always 2)
|
| 341 |
+
nnz
|
| 342 |
+
size
|
| 343 |
+
data
|
| 344 |
+
CSR format data array of the array
|
| 345 |
+
indices
|
| 346 |
+
CSR format index array of the array
|
| 347 |
+
indptr
|
| 348 |
+
CSR format index pointer array of the array
|
| 349 |
+
has_sorted_indices
|
| 350 |
+
has_canonical_format
|
| 351 |
+
T
|
| 352 |
+
|
| 353 |
+
Notes
|
| 354 |
+
-----
|
| 355 |
+
|
| 356 |
+
Sparse arrays can be used in arithmetic operations: they support
|
| 357 |
+
addition, subtraction, multiplication, division, and matrix power.
|
| 358 |
+
|
| 359 |
+
Advantages of the CSR format
|
| 360 |
+
- efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
|
| 361 |
+
- efficient row slicing
|
| 362 |
+
- fast matrix vector products
|
| 363 |
+
|
| 364 |
+
Disadvantages of the CSR format
|
| 365 |
+
- slow column slicing operations (consider CSC)
|
| 366 |
+
- changes to the sparsity structure are expensive (consider LIL or DOK)
|
| 367 |
+
|
| 368 |
+
Canonical Format
|
| 369 |
+
- Within each row, indices are sorted by column.
|
| 370 |
+
- There are no duplicate entries.
|
| 371 |
+
|
| 372 |
+
Examples
|
| 373 |
+
--------
|
| 374 |
+
|
| 375 |
+
>>> import numpy as np
|
| 376 |
+
>>> from scipy.sparse import csr_array
|
| 377 |
+
>>> csr_array((3, 4), dtype=np.int8).toarray()
|
| 378 |
+
array([[0, 0, 0, 0],
|
| 379 |
+
[0, 0, 0, 0],
|
| 380 |
+
[0, 0, 0, 0]], dtype=int8)
|
| 381 |
+
|
| 382 |
+
>>> row = np.array([0, 0, 1, 2, 2, 2])
|
| 383 |
+
>>> col = np.array([0, 2, 2, 0, 1, 2])
|
| 384 |
+
>>> data = np.array([1, 2, 3, 4, 5, 6])
|
| 385 |
+
>>> csr_array((data, (row, col)), shape=(3, 3)).toarray()
|
| 386 |
+
array([[1, 0, 2],
|
| 387 |
+
[0, 0, 3],
|
| 388 |
+
[4, 5, 6]])
|
| 389 |
+
|
| 390 |
+
>>> indptr = np.array([0, 2, 3, 6])
|
| 391 |
+
>>> indices = np.array([0, 2, 2, 0, 1, 2])
|
| 392 |
+
>>> data = np.array([1, 2, 3, 4, 5, 6])
|
| 393 |
+
>>> csr_array((data, indices, indptr), shape=(3, 3)).toarray()
|
| 394 |
+
array([[1, 0, 2],
|
| 395 |
+
[0, 0, 3],
|
| 396 |
+
[4, 5, 6]])
|
| 397 |
+
|
| 398 |
+
Duplicate entries are summed together:
|
| 399 |
+
|
| 400 |
+
>>> row = np.array([0, 1, 2, 0])
|
| 401 |
+
>>> col = np.array([0, 1, 1, 0])
|
| 402 |
+
>>> data = np.array([1, 2, 4, 8])
|
| 403 |
+
>>> csr_array((data, (row, col)), shape=(3, 3)).toarray()
|
| 404 |
+
array([[9, 0, 0],
|
| 405 |
+
[0, 2, 0],
|
| 406 |
+
[0, 4, 0]])
|
| 407 |
+
|
| 408 |
+
As an example of how to construct a CSR array incrementally,
|
| 409 |
+
the following snippet builds a term-document array from texts:
|
| 410 |
+
|
| 411 |
+
>>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
|
| 412 |
+
>>> indptr = [0]
|
| 413 |
+
>>> indices = []
|
| 414 |
+
>>> data = []
|
| 415 |
+
>>> vocabulary = {}
|
| 416 |
+
>>> for d in docs:
|
| 417 |
+
... for term in d:
|
| 418 |
+
... index = vocabulary.setdefault(term, len(vocabulary))
|
| 419 |
+
... indices.append(index)
|
| 420 |
+
... data.append(1)
|
| 421 |
+
... indptr.append(len(indices))
|
| 422 |
+
...
|
| 423 |
+
>>> csr_array((data, indices, indptr), dtype=int).toarray()
|
| 424 |
+
array([[2, 1, 0, 0],
|
| 425 |
+
[0, 1, 1, 1]])
|
| 426 |
+
|
| 427 |
+
"""
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
class csr_matrix(spmatrix, _csr_base):
|
| 431 |
+
"""
|
| 432 |
+
Compressed Sparse Row matrix.
|
| 433 |
+
|
| 434 |
+
This can be instantiated in several ways:
|
| 435 |
+
csr_matrix(D)
|
| 436 |
+
where D is a 2-D ndarray
|
| 437 |
+
|
| 438 |
+
csr_matrix(S)
|
| 439 |
+
with another sparse array or matrix S (equivalent to S.tocsr())
|
| 440 |
+
|
| 441 |
+
csr_matrix((M, N), [dtype])
|
| 442 |
+
to construct an empty matrix with shape (M, N)
|
| 443 |
+
dtype is optional, defaulting to dtype='d'.
|
| 444 |
+
|
| 445 |
+
csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
|
| 446 |
+
where ``data``, ``row_ind`` and ``col_ind`` satisfy the
|
| 447 |
+
relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
|
| 448 |
+
|
| 449 |
+
csr_matrix((data, indices, indptr), [shape=(M, N)])
|
| 450 |
+
is the standard CSR representation where the column indices for
|
| 451 |
+
row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their
|
| 452 |
+
corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``.
|
| 453 |
+
If the shape parameter is not supplied, the matrix dimensions
|
| 454 |
+
are inferred from the index arrays.
|
| 455 |
+
|
| 456 |
+
Attributes
|
| 457 |
+
----------
|
| 458 |
+
dtype : dtype
|
| 459 |
+
Data type of the matrix
|
| 460 |
+
shape : 2-tuple
|
| 461 |
+
Shape of the matrix
|
| 462 |
+
ndim : int
|
| 463 |
+
Number of dimensions (this is always 2)
|
| 464 |
+
nnz
|
| 465 |
+
size
|
| 466 |
+
data
|
| 467 |
+
CSR format data array of the matrix
|
| 468 |
+
indices
|
| 469 |
+
CSR format index array of the matrix
|
| 470 |
+
indptr
|
| 471 |
+
CSR format index pointer array of the matrix
|
| 472 |
+
has_sorted_indices
|
| 473 |
+
has_canonical_format
|
| 474 |
+
T
|
| 475 |
+
|
| 476 |
+
Notes
|
| 477 |
+
-----
|
| 478 |
+
|
| 479 |
+
Sparse matrices can be used in arithmetic operations: they support
|
| 480 |
+
addition, subtraction, multiplication, division, and matrix power.
|
| 481 |
+
|
| 482 |
+
Advantages of the CSR format
|
| 483 |
+
- efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
|
| 484 |
+
- efficient row slicing
|
| 485 |
+
- fast matrix vector products
|
| 486 |
+
|
| 487 |
+
Disadvantages of the CSR format
|
| 488 |
+
- slow column slicing operations (consider CSC)
|
| 489 |
+
- changes to the sparsity structure are expensive (consider LIL or DOK)
|
| 490 |
+
|
| 491 |
+
Canonical Format
|
| 492 |
+
- Within each row, indices are sorted by column.
|
| 493 |
+
- There are no duplicate entries.
|
| 494 |
+
|
| 495 |
+
Examples
|
| 496 |
+
--------
|
| 497 |
+
|
| 498 |
+
>>> import numpy as np
|
| 499 |
+
>>> from scipy.sparse import csr_matrix
|
| 500 |
+
>>> csr_matrix((3, 4), dtype=np.int8).toarray()
|
| 501 |
+
array([[0, 0, 0, 0],
|
| 502 |
+
[0, 0, 0, 0],
|
| 503 |
+
[0, 0, 0, 0]], dtype=int8)
|
| 504 |
+
|
| 505 |
+
>>> row = np.array([0, 0, 1, 2, 2, 2])
|
| 506 |
+
>>> col = np.array([0, 2, 2, 0, 1, 2])
|
| 507 |
+
>>> data = np.array([1, 2, 3, 4, 5, 6])
|
| 508 |
+
>>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
|
| 509 |
+
array([[1, 0, 2],
|
| 510 |
+
[0, 0, 3],
|
| 511 |
+
[4, 5, 6]])
|
| 512 |
+
|
| 513 |
+
>>> indptr = np.array([0, 2, 3, 6])
|
| 514 |
+
>>> indices = np.array([0, 2, 2, 0, 1, 2])
|
| 515 |
+
>>> data = np.array([1, 2, 3, 4, 5, 6])
|
| 516 |
+
>>> csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()
|
| 517 |
+
array([[1, 0, 2],
|
| 518 |
+
[0, 0, 3],
|
| 519 |
+
[4, 5, 6]])
|
| 520 |
+
|
| 521 |
+
Duplicate entries are summed together:
|
| 522 |
+
|
| 523 |
+
>>> row = np.array([0, 1, 2, 0])
|
| 524 |
+
>>> col = np.array([0, 1, 1, 0])
|
| 525 |
+
>>> data = np.array([1, 2, 4, 8])
|
| 526 |
+
>>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
|
| 527 |
+
array([[9, 0, 0],
|
| 528 |
+
[0, 2, 0],
|
| 529 |
+
[0, 4, 0]])
|
| 530 |
+
|
| 531 |
+
As an example of how to construct a CSR matrix incrementally,
|
| 532 |
+
the following snippet builds a term-document matrix from texts:
|
| 533 |
+
|
| 534 |
+
>>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
|
| 535 |
+
>>> indptr = [0]
|
| 536 |
+
>>> indices = []
|
| 537 |
+
>>> data = []
|
| 538 |
+
>>> vocabulary = {}
|
| 539 |
+
>>> for d in docs:
|
| 540 |
+
... for term in d:
|
| 541 |
+
... index = vocabulary.setdefault(term, len(vocabulary))
|
| 542 |
+
... indices.append(index)
|
| 543 |
+
... data.append(1)
|
| 544 |
+
... indptr.append(len(indices))
|
| 545 |
+
...
|
| 546 |
+
>>> csr_matrix((data, indices, indptr), dtype=int).toarray()
|
| 547 |
+
array([[2, 1, 0, 0],
|
| 548 |
+
[0, 1, 1, 1]])
|
| 549 |
+
|
| 550 |
+
"""
|
| 551 |
+
|
parrot/lib/python3.10/site-packages/scipy/sparse/_data.py
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base class for sparse matrice with a .data attribute
|
| 2 |
+
|
| 3 |
+
subclasses must provide a _with_data() method that
|
| 4 |
+
creates a new matrix with the same sparsity pattern
|
| 5 |
+
as self but with a different data array
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import math
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
from ._base import _spbase, sparray, _ufuncs_with_fixed_point_at_zero
|
| 13 |
+
from ._sputils import isscalarlike, validateaxis
|
| 14 |
+
|
| 15 |
+
__all__ = []
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# TODO implement all relevant operations
|
| 19 |
+
# use .data.__methods__() instead of /=, *=, etc.
|
| 20 |
+
class _data_matrix(_spbase):
|
| 21 |
+
def __init__(self, arg1):
|
| 22 |
+
_spbase.__init__(self, arg1)
|
| 23 |
+
|
| 24 |
+
@property
|
| 25 |
+
def dtype(self):
|
| 26 |
+
return self.data.dtype
|
| 27 |
+
|
| 28 |
+
@dtype.setter
|
| 29 |
+
def dtype(self, newtype):
|
| 30 |
+
self.data.dtype = newtype
|
| 31 |
+
|
| 32 |
+
def _deduped_data(self):
|
| 33 |
+
if hasattr(self, 'sum_duplicates'):
|
| 34 |
+
self.sum_duplicates()
|
| 35 |
+
return self.data
|
| 36 |
+
|
| 37 |
+
def __abs__(self):
|
| 38 |
+
return self._with_data(abs(self._deduped_data()))
|
| 39 |
+
|
| 40 |
+
def __round__(self, ndigits=0):
|
| 41 |
+
return self._with_data(np.around(self._deduped_data(), decimals=ndigits))
|
| 42 |
+
|
| 43 |
+
def _real(self):
|
| 44 |
+
return self._with_data(self.data.real)
|
| 45 |
+
|
| 46 |
+
def _imag(self):
|
| 47 |
+
return self._with_data(self.data.imag)
|
| 48 |
+
|
| 49 |
+
def __neg__(self):
|
| 50 |
+
if self.dtype.kind == 'b':
|
| 51 |
+
raise NotImplementedError('negating a boolean sparse array is not '
|
| 52 |
+
'supported')
|
| 53 |
+
return self._with_data(-self.data)
|
| 54 |
+
|
| 55 |
+
def __imul__(self, other): # self *= other
|
| 56 |
+
if isscalarlike(other):
|
| 57 |
+
self.data *= other
|
| 58 |
+
return self
|
| 59 |
+
else:
|
| 60 |
+
return NotImplemented
|
| 61 |
+
|
| 62 |
+
def __itruediv__(self, other): # self /= other
|
| 63 |
+
if isscalarlike(other):
|
| 64 |
+
recip = 1.0 / other
|
| 65 |
+
self.data *= recip
|
| 66 |
+
return self
|
| 67 |
+
else:
|
| 68 |
+
return NotImplemented
|
| 69 |
+
|
| 70 |
+
def astype(self, dtype, casting='unsafe', copy=True):
|
| 71 |
+
dtype = np.dtype(dtype)
|
| 72 |
+
if self.dtype != dtype:
|
| 73 |
+
matrix = self._with_data(
|
| 74 |
+
self.data.astype(dtype, casting=casting, copy=True),
|
| 75 |
+
copy=True
|
| 76 |
+
)
|
| 77 |
+
return matrix._with_data(matrix._deduped_data(), copy=False)
|
| 78 |
+
elif copy:
|
| 79 |
+
return self.copy()
|
| 80 |
+
else:
|
| 81 |
+
return self
|
| 82 |
+
|
| 83 |
+
astype.__doc__ = _spbase.astype.__doc__
|
| 84 |
+
|
| 85 |
+
def conjugate(self, copy=True):
|
| 86 |
+
if np.issubdtype(self.dtype, np.complexfloating):
|
| 87 |
+
return self._with_data(self.data.conjugate(), copy=copy)
|
| 88 |
+
elif copy:
|
| 89 |
+
return self.copy()
|
| 90 |
+
else:
|
| 91 |
+
return self
|
| 92 |
+
|
| 93 |
+
conjugate.__doc__ = _spbase.conjugate.__doc__
|
| 94 |
+
|
| 95 |
+
def copy(self):
|
| 96 |
+
return self._with_data(self.data.copy(), copy=True)
|
| 97 |
+
|
| 98 |
+
copy.__doc__ = _spbase.copy.__doc__
|
| 99 |
+
|
| 100 |
+
def count_nonzero(self):
|
| 101 |
+
return np.count_nonzero(self._deduped_data())
|
| 102 |
+
|
| 103 |
+
count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
|
| 104 |
+
|
| 105 |
+
def power(self, n, dtype=None):
|
| 106 |
+
"""
|
| 107 |
+
This function performs element-wise power.
|
| 108 |
+
|
| 109 |
+
Parameters
|
| 110 |
+
----------
|
| 111 |
+
n : scalar
|
| 112 |
+
n is a non-zero scalar (nonzero avoids dense ones creation)
|
| 113 |
+
If zero power is desired, special case it to use `np.ones`
|
| 114 |
+
|
| 115 |
+
dtype : If dtype is not specified, the current dtype will be preserved.
|
| 116 |
+
|
| 117 |
+
Raises
|
| 118 |
+
------
|
| 119 |
+
NotImplementedError : if n is a zero scalar
|
| 120 |
+
If zero power is desired, special case it to use
|
| 121 |
+
`np.ones(A.shape, dtype=A.dtype)`
|
| 122 |
+
"""
|
| 123 |
+
if not isscalarlike(n):
|
| 124 |
+
raise NotImplementedError("input is not scalar")
|
| 125 |
+
if not n:
|
| 126 |
+
raise NotImplementedError(
|
| 127 |
+
"zero power is not supported as it would densify the matrix.\n"
|
| 128 |
+
"Use `np.ones(A.shape, dtype=A.dtype)` for this case."
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
data = self._deduped_data()
|
| 132 |
+
if dtype is not None:
|
| 133 |
+
data = data.astype(dtype)
|
| 134 |
+
return self._with_data(data ** n)
|
| 135 |
+
|
| 136 |
+
###########################
|
| 137 |
+
# Multiplication handlers #
|
| 138 |
+
###########################
|
| 139 |
+
|
| 140 |
+
def _mul_scalar(self, other):
|
| 141 |
+
return self._with_data(self.data * other)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# Add the numpy unary ufuncs for which func(0) = 0 to _data_matrix.
|
| 145 |
+
for npfunc in _ufuncs_with_fixed_point_at_zero:
|
| 146 |
+
name = npfunc.__name__
|
| 147 |
+
|
| 148 |
+
def _create_method(op):
|
| 149 |
+
def method(self):
|
| 150 |
+
result = op(self._deduped_data())
|
| 151 |
+
return self._with_data(result, copy=True)
|
| 152 |
+
|
| 153 |
+
method.__doc__ = (f"Element-wise {name}.\n\n"
|
| 154 |
+
f"See `numpy.{name}` for more information.")
|
| 155 |
+
method.__name__ = name
|
| 156 |
+
|
| 157 |
+
return method
|
| 158 |
+
|
| 159 |
+
setattr(_data_matrix, name, _create_method(npfunc))
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _find_missing_index(ind, n):
|
| 163 |
+
for k, a in enumerate(ind):
|
| 164 |
+
if k != a:
|
| 165 |
+
return k
|
| 166 |
+
|
| 167 |
+
k += 1
|
| 168 |
+
if k < n:
|
| 169 |
+
return k
|
| 170 |
+
else:
|
| 171 |
+
return -1
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class _minmax_mixin:
|
| 175 |
+
"""Mixin for min and max methods.
|
| 176 |
+
|
| 177 |
+
These are not implemented for dia_matrix, hence the separate class.
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
+
def _min_or_max_axis(self, axis, min_or_max):
|
| 181 |
+
N = self.shape[axis]
|
| 182 |
+
if N == 0:
|
| 183 |
+
raise ValueError("zero-size array to reduction operation")
|
| 184 |
+
M = self.shape[1 - axis]
|
| 185 |
+
idx_dtype = self._get_index_dtype(maxval=M)
|
| 186 |
+
|
| 187 |
+
mat = self.tocsc() if axis == 0 else self.tocsr()
|
| 188 |
+
mat.sum_duplicates()
|
| 189 |
+
|
| 190 |
+
major_index, value = mat._minor_reduce(min_or_max)
|
| 191 |
+
not_full = np.diff(mat.indptr)[major_index] < N
|
| 192 |
+
value[not_full] = min_or_max(value[not_full], 0)
|
| 193 |
+
|
| 194 |
+
mask = value != 0
|
| 195 |
+
major_index = np.compress(mask, major_index)
|
| 196 |
+
value = np.compress(mask, value)
|
| 197 |
+
|
| 198 |
+
if isinstance(self, sparray):
|
| 199 |
+
coords = (major_index,)
|
| 200 |
+
shape = (M,)
|
| 201 |
+
return self._coo_container((value, coords), shape=shape, dtype=self.dtype)
|
| 202 |
+
|
| 203 |
+
if axis == 0:
|
| 204 |
+
return self._coo_container(
|
| 205 |
+
(value, (np.zeros(len(value), dtype=idx_dtype), major_index)),
|
| 206 |
+
dtype=self.dtype, shape=(1, M)
|
| 207 |
+
)
|
| 208 |
+
else:
|
| 209 |
+
return self._coo_container(
|
| 210 |
+
(value, (major_index, np.zeros(len(value), dtype=idx_dtype))),
|
| 211 |
+
dtype=self.dtype, shape=(M, 1)
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def _min_or_max(self, axis, out, min_or_max):
|
| 215 |
+
if out is not None:
|
| 216 |
+
raise ValueError("Sparse arrays do not support an 'out' parameter.")
|
| 217 |
+
|
| 218 |
+
validateaxis(axis)
|
| 219 |
+
if self.ndim == 1:
|
| 220 |
+
if axis not in (None, 0, -1):
|
| 221 |
+
raise ValueError("axis out of range")
|
| 222 |
+
axis = None # avoid calling special axis case. no impact on 1d
|
| 223 |
+
|
| 224 |
+
if axis is None:
|
| 225 |
+
if 0 in self.shape:
|
| 226 |
+
raise ValueError("zero-size array to reduction operation")
|
| 227 |
+
|
| 228 |
+
zero = self.dtype.type(0)
|
| 229 |
+
if self.nnz == 0:
|
| 230 |
+
return zero
|
| 231 |
+
m = min_or_max.reduce(self._deduped_data().ravel())
|
| 232 |
+
if self.nnz != math.prod(self.shape):
|
| 233 |
+
m = min_or_max(zero, m)
|
| 234 |
+
return m
|
| 235 |
+
|
| 236 |
+
if axis < 0:
|
| 237 |
+
axis += 2
|
| 238 |
+
|
| 239 |
+
if (axis == 0) or (axis == 1):
|
| 240 |
+
return self._min_or_max_axis(axis, min_or_max)
|
| 241 |
+
else:
|
| 242 |
+
raise ValueError("axis out of range")
|
| 243 |
+
|
| 244 |
+
def _arg_min_or_max_axis(self, axis, argmin_or_argmax, compare):
|
| 245 |
+
if self.shape[axis] == 0:
|
| 246 |
+
raise ValueError("Cannot apply the operation along a zero-sized dimension.")
|
| 247 |
+
|
| 248 |
+
if axis < 0:
|
| 249 |
+
axis += 2
|
| 250 |
+
|
| 251 |
+
zero = self.dtype.type(0)
|
| 252 |
+
|
| 253 |
+
mat = self.tocsc() if axis == 0 else self.tocsr()
|
| 254 |
+
mat.sum_duplicates()
|
| 255 |
+
|
| 256 |
+
ret_size, line_size = mat._swap(mat.shape)
|
| 257 |
+
ret = np.zeros(ret_size, dtype=int)
|
| 258 |
+
|
| 259 |
+
nz_lines, = np.nonzero(np.diff(mat.indptr))
|
| 260 |
+
for i in nz_lines:
|
| 261 |
+
p, q = mat.indptr[i:i + 2]
|
| 262 |
+
data = mat.data[p:q]
|
| 263 |
+
indices = mat.indices[p:q]
|
| 264 |
+
extreme_index = argmin_or_argmax(data)
|
| 265 |
+
extreme_value = data[extreme_index]
|
| 266 |
+
if compare(extreme_value, zero) or q - p == line_size:
|
| 267 |
+
ret[i] = indices[extreme_index]
|
| 268 |
+
else:
|
| 269 |
+
zero_ind = _find_missing_index(indices, line_size)
|
| 270 |
+
if extreme_value == zero:
|
| 271 |
+
ret[i] = min(extreme_index, zero_ind)
|
| 272 |
+
else:
|
| 273 |
+
ret[i] = zero_ind
|
| 274 |
+
|
| 275 |
+
if isinstance(self, sparray):
|
| 276 |
+
return ret
|
| 277 |
+
|
| 278 |
+
if axis == 1:
|
| 279 |
+
ret = ret.reshape(-1, 1)
|
| 280 |
+
|
| 281 |
+
return self._ascontainer(ret)
|
| 282 |
+
|
| 283 |
+
def _arg_min_or_max(self, axis, out, argmin_or_argmax, compare):
|
| 284 |
+
if out is not None:
|
| 285 |
+
raise ValueError("Sparse types do not support an 'out' parameter.")
|
| 286 |
+
|
| 287 |
+
validateaxis(axis)
|
| 288 |
+
|
| 289 |
+
if self.ndim == 1:
|
| 290 |
+
if axis not in (None, 0, -1):
|
| 291 |
+
raise ValueError("axis out of range")
|
| 292 |
+
axis = None # avoid calling special axis case. no impact on 1d
|
| 293 |
+
|
| 294 |
+
if axis is not None:
|
| 295 |
+
return self._arg_min_or_max_axis(axis, argmin_or_argmax, compare)
|
| 296 |
+
|
| 297 |
+
if 0 in self.shape:
|
| 298 |
+
raise ValueError("Cannot apply the operation to an empty matrix.")
|
| 299 |
+
|
| 300 |
+
if self.nnz == 0:
|
| 301 |
+
return 0
|
| 302 |
+
|
| 303 |
+
zero = self.dtype.type(0)
|
| 304 |
+
mat = self.tocoo()
|
| 305 |
+
# Convert to canonical form: no duplicates, sorted indices.
|
| 306 |
+
mat.sum_duplicates()
|
| 307 |
+
extreme_index = argmin_or_argmax(mat.data)
|
| 308 |
+
extreme_value = mat.data[extreme_index]
|
| 309 |
+
num_col = mat.shape[-1]
|
| 310 |
+
|
| 311 |
+
# If the min value is less than zero, or max is greater than zero,
|
| 312 |
+
# then we do not need to worry about implicit zeros.
|
| 313 |
+
if compare(extreme_value, zero):
|
| 314 |
+
# cast to Python int to avoid overflow and RuntimeError
|
| 315 |
+
return int(mat.row[extreme_index]) * num_col + int(mat.col[extreme_index])
|
| 316 |
+
|
| 317 |
+
# Cheap test for the rare case where we have no implicit zeros.
|
| 318 |
+
size = math.prod(self.shape)
|
| 319 |
+
if size == mat.nnz:
|
| 320 |
+
return int(mat.row[extreme_index]) * num_col + int(mat.col[extreme_index])
|
| 321 |
+
|
| 322 |
+
# At this stage, any implicit zero could be the min or max value.
|
| 323 |
+
# After sum_duplicates(), the `row` and `col` arrays are guaranteed to
|
| 324 |
+
# be sorted in C-order, which means the linearized indices are sorted.
|
| 325 |
+
linear_indices = mat.row * num_col + mat.col
|
| 326 |
+
first_implicit_zero_index = _find_missing_index(linear_indices, size)
|
| 327 |
+
if extreme_value == zero:
|
| 328 |
+
return min(first_implicit_zero_index, extreme_index)
|
| 329 |
+
return first_implicit_zero_index
|
| 330 |
+
|
| 331 |
+
def max(self, axis=None, out=None):
|
| 332 |
+
"""
|
| 333 |
+
Return the maximum of the array/matrix or maximum along an axis.
|
| 334 |
+
This takes all elements into account, not just the non-zero ones.
|
| 335 |
+
|
| 336 |
+
Parameters
|
| 337 |
+
----------
|
| 338 |
+
axis : {-2, -1, 0, 1, None} optional
|
| 339 |
+
Axis along which the sum is computed. The default is to
|
| 340 |
+
compute the maximum over all elements, returning
|
| 341 |
+
a scalar (i.e., `axis` = `None`).
|
| 342 |
+
|
| 343 |
+
out : None, optional
|
| 344 |
+
This argument is in the signature *solely* for NumPy
|
| 345 |
+
compatibility reasons. Do not pass in anything except
|
| 346 |
+
for the default value, as this argument is not used.
|
| 347 |
+
|
| 348 |
+
Returns
|
| 349 |
+
-------
|
| 350 |
+
amax : coo_matrix or scalar
|
| 351 |
+
Maximum of `a`. If `axis` is None, the result is a scalar value.
|
| 352 |
+
If `axis` is given, the result is a sparse.coo_matrix of dimension
|
| 353 |
+
``a.ndim - 1``.
|
| 354 |
+
|
| 355 |
+
See Also
|
| 356 |
+
--------
|
| 357 |
+
min : The minimum value of a sparse array/matrix along a given axis.
|
| 358 |
+
numpy.matrix.max : NumPy's implementation of 'max' for matrices
|
| 359 |
+
|
| 360 |
+
"""
|
| 361 |
+
return self._min_or_max(axis, out, np.maximum)
|
| 362 |
+
|
| 363 |
+
def min(self, axis=None, out=None):
|
| 364 |
+
"""
|
| 365 |
+
Return the minimum of the array/matrix or maximum along an axis.
|
| 366 |
+
This takes all elements into account, not just the non-zero ones.
|
| 367 |
+
|
| 368 |
+
Parameters
|
| 369 |
+
----------
|
| 370 |
+
axis : {-2, -1, 0, 1, None} optional
|
| 371 |
+
Axis along which the sum is computed. The default is to
|
| 372 |
+
compute the minimum over all elements, returning
|
| 373 |
+
a scalar (i.e., `axis` = `None`).
|
| 374 |
+
|
| 375 |
+
out : None, optional
|
| 376 |
+
This argument is in the signature *solely* for NumPy
|
| 377 |
+
compatibility reasons. Do not pass in anything except for
|
| 378 |
+
the default value, as this argument is not used.
|
| 379 |
+
|
| 380 |
+
Returns
|
| 381 |
+
-------
|
| 382 |
+
amin : coo_matrix or scalar
|
| 383 |
+
Minimum of `a`. If `axis` is None, the result is a scalar value.
|
| 384 |
+
If `axis` is given, the result is a sparse.coo_matrix of dimension
|
| 385 |
+
``a.ndim - 1``.
|
| 386 |
+
|
| 387 |
+
See Also
|
| 388 |
+
--------
|
| 389 |
+
max : The maximum value of a sparse array/matrix along a given axis.
|
| 390 |
+
numpy.matrix.min : NumPy's implementation of 'min' for matrices
|
| 391 |
+
|
| 392 |
+
"""
|
| 393 |
+
return self._min_or_max(axis, out, np.minimum)
|
| 394 |
+
|
| 395 |
+
def nanmax(self, axis=None, out=None):
|
| 396 |
+
"""
|
| 397 |
+
Return the maximum of the array/matrix or maximum along an axis, ignoring any
|
| 398 |
+
NaNs. This takes all elements into account, not just the non-zero
|
| 399 |
+
ones.
|
| 400 |
+
|
| 401 |
+
.. versionadded:: 1.11.0
|
| 402 |
+
|
| 403 |
+
Parameters
|
| 404 |
+
----------
|
| 405 |
+
axis : {-2, -1, 0, 1, None} optional
|
| 406 |
+
Axis along which the maximum is computed. The default is to
|
| 407 |
+
compute the maximum over all elements, returning
|
| 408 |
+
a scalar (i.e., `axis` = `None`).
|
| 409 |
+
|
| 410 |
+
out : None, optional
|
| 411 |
+
This argument is in the signature *solely* for NumPy
|
| 412 |
+
compatibility reasons. Do not pass in anything except
|
| 413 |
+
for the default value, as this argument is not used.
|
| 414 |
+
|
| 415 |
+
Returns
|
| 416 |
+
-------
|
| 417 |
+
amax : coo_matrix or scalar
|
| 418 |
+
Maximum of `a`. If `axis` is None, the result is a scalar value.
|
| 419 |
+
If `axis` is given, the result is a sparse.coo_matrix of dimension
|
| 420 |
+
``a.ndim - 1``.
|
| 421 |
+
|
| 422 |
+
See Also
|
| 423 |
+
--------
|
| 424 |
+
nanmin : The minimum value of a sparse array/matrix along a given axis,
|
| 425 |
+
ignoring NaNs.
|
| 426 |
+
max : The maximum value of a sparse array/matrix along a given axis,
|
| 427 |
+
propagating NaNs.
|
| 428 |
+
numpy.nanmax : NumPy's implementation of 'nanmax'.
|
| 429 |
+
|
| 430 |
+
"""
|
| 431 |
+
return self._min_or_max(axis, out, np.fmax)
|
| 432 |
+
|
| 433 |
+
def nanmin(self, axis=None, out=None):
|
| 434 |
+
"""
|
| 435 |
+
Return the minimum of the array/matrix or minimum along an axis, ignoring any
|
| 436 |
+
NaNs. This takes all elements into account, not just the non-zero
|
| 437 |
+
ones.
|
| 438 |
+
|
| 439 |
+
.. versionadded:: 1.11.0
|
| 440 |
+
|
| 441 |
+
Parameters
|
| 442 |
+
----------
|
| 443 |
+
axis : {-2, -1, 0, 1, None} optional
|
| 444 |
+
Axis along which the minimum is computed. The default is to
|
| 445 |
+
compute the minimum over all elements, returning
|
| 446 |
+
a scalar (i.e., `axis` = `None`).
|
| 447 |
+
|
| 448 |
+
out : None, optional
|
| 449 |
+
This argument is in the signature *solely* for NumPy
|
| 450 |
+
compatibility reasons. Do not pass in anything except for
|
| 451 |
+
the default value, as this argument is not used.
|
| 452 |
+
|
| 453 |
+
Returns
|
| 454 |
+
-------
|
| 455 |
+
amin : coo_matrix or scalar
|
| 456 |
+
Minimum of `a`. If `axis` is None, the result is a scalar value.
|
| 457 |
+
If `axis` is given, the result is a sparse.coo_matrix of dimension
|
| 458 |
+
``a.ndim - 1``.
|
| 459 |
+
|
| 460 |
+
See Also
|
| 461 |
+
--------
|
| 462 |
+
nanmax : The maximum value of a sparse array/matrix along a given axis,
|
| 463 |
+
ignoring NaNs.
|
| 464 |
+
min : The minimum value of a sparse array/matrix along a given axis,
|
| 465 |
+
propagating NaNs.
|
| 466 |
+
numpy.nanmin : NumPy's implementation of 'nanmin'.
|
| 467 |
+
|
| 468 |
+
"""
|
| 469 |
+
return self._min_or_max(axis, out, np.fmin)
|
| 470 |
+
|
| 471 |
+
def argmax(self, axis=None, out=None):
|
| 472 |
+
"""Return indices of maximum elements along an axis.
|
| 473 |
+
|
| 474 |
+
Implicit zero elements are also taken into account. If there are
|
| 475 |
+
several maximum values, the index of the first occurrence is returned.
|
| 476 |
+
|
| 477 |
+
Parameters
|
| 478 |
+
----------
|
| 479 |
+
axis : {-2, -1, 0, 1, None}, optional
|
| 480 |
+
Axis along which the argmax is computed. If None (default), index
|
| 481 |
+
of the maximum element in the flatten data is returned.
|
| 482 |
+
out : None, optional
|
| 483 |
+
This argument is in the signature *solely* for NumPy
|
| 484 |
+
compatibility reasons. Do not pass in anything except for
|
| 485 |
+
the default value, as this argument is not used.
|
| 486 |
+
|
| 487 |
+
Returns
|
| 488 |
+
-------
|
| 489 |
+
ind : numpy.matrix or int
|
| 490 |
+
Indices of maximum elements. If matrix, its size along `axis` is 1.
|
| 491 |
+
"""
|
| 492 |
+
return self._arg_min_or_max(axis, out, np.argmax, np.greater)
|
| 493 |
+
|
| 494 |
+
def argmin(self, axis=None, out=None):
|
| 495 |
+
"""Return indices of minimum elements along an axis.
|
| 496 |
+
|
| 497 |
+
Implicit zero elements are also taken into account. If there are
|
| 498 |
+
several minimum values, the index of the first occurrence is returned.
|
| 499 |
+
|
| 500 |
+
Parameters
|
| 501 |
+
----------
|
| 502 |
+
axis : {-2, -1, 0, 1, None}, optional
|
| 503 |
+
Axis along which the argmin is computed. If None (default), index
|
| 504 |
+
of the minimum element in the flatten data is returned.
|
| 505 |
+
out : None, optional
|
| 506 |
+
This argument is in the signature *solely* for NumPy
|
| 507 |
+
compatibility reasons. Do not pass in anything except for
|
| 508 |
+
the default value, as this argument is not used.
|
| 509 |
+
|
| 510 |
+
Returns
|
| 511 |
+
-------
|
| 512 |
+
ind : numpy.matrix or int
|
| 513 |
+
Indices of minimum elements. If matrix, its size along `axis` is 1.
|
| 514 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dictionary Of Keys based matrix"""
|
| 2 |
+
|
| 3 |
+
__docformat__ = "restructuredtext en"
|
| 4 |
+
|
| 5 |
+
__all__ = ['dok_array', 'dok_matrix', 'isspmatrix_dok']
|
| 6 |
+
|
| 7 |
+
import itertools
|
| 8 |
+
from warnings import warn
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
from ._matrix import spmatrix
|
| 12 |
+
from ._base import _spbase, sparray, issparse
|
| 13 |
+
from ._index import IndexMixin
|
| 14 |
+
from ._sputils import (isdense, getdtype, isshape, isintlike, isscalarlike,
|
| 15 |
+
upcast, upcast_scalar, check_shape)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class _dok_base(_spbase, IndexMixin, dict):
|
| 19 |
+
_format = 'dok'
|
| 20 |
+
|
| 21 |
+
def __init__(self, arg1, shape=None, dtype=None, copy=False):
|
| 22 |
+
_spbase.__init__(self, arg1)
|
| 23 |
+
|
| 24 |
+
is_array = isinstance(self, sparray)
|
| 25 |
+
if isinstance(arg1, tuple) and isshape(arg1, allow_1d=is_array):
|
| 26 |
+
self._shape = check_shape(arg1, allow_1d=is_array)
|
| 27 |
+
self._dict = {}
|
| 28 |
+
self.dtype = getdtype(dtype, default=float)
|
| 29 |
+
elif issparse(arg1): # Sparse ctor
|
| 30 |
+
if arg1.format == self.format:
|
| 31 |
+
arg1 = arg1.copy() if copy else arg1
|
| 32 |
+
else:
|
| 33 |
+
arg1 = arg1.todok()
|
| 34 |
+
|
| 35 |
+
if dtype is not None:
|
| 36 |
+
arg1 = arg1.astype(dtype, copy=False)
|
| 37 |
+
|
| 38 |
+
self._dict = arg1._dict
|
| 39 |
+
self._shape = check_shape(arg1.shape, allow_1d=is_array)
|
| 40 |
+
self.dtype = arg1.dtype
|
| 41 |
+
else: # Dense ctor
|
| 42 |
+
try:
|
| 43 |
+
arg1 = np.asarray(arg1)
|
| 44 |
+
except Exception as e:
|
| 45 |
+
raise TypeError('Invalid input format.') from e
|
| 46 |
+
|
| 47 |
+
if arg1.ndim > 2:
|
| 48 |
+
raise TypeError('Expected rank <=2 dense array or matrix.')
|
| 49 |
+
|
| 50 |
+
if arg1.ndim == 1:
|
| 51 |
+
if dtype is not None:
|
| 52 |
+
arg1 = arg1.astype(dtype)
|
| 53 |
+
self._dict = {i: v for i, v in enumerate(arg1) if v != 0}
|
| 54 |
+
self.dtype = arg1.dtype
|
| 55 |
+
else:
|
| 56 |
+
d = self._coo_container(arg1, dtype=dtype).todok()
|
| 57 |
+
self._dict = d._dict
|
| 58 |
+
self.dtype = d.dtype
|
| 59 |
+
self._shape = check_shape(arg1.shape, allow_1d=is_array)
|
| 60 |
+
|
| 61 |
+
def update(self, val):
|
| 62 |
+
# Prevent direct usage of update
|
| 63 |
+
raise NotImplementedError("Direct update to DOK sparse format is not allowed.")
|
| 64 |
+
|
| 65 |
+
def _getnnz(self, axis=None):
|
| 66 |
+
if axis is not None:
|
| 67 |
+
raise NotImplementedError(
|
| 68 |
+
"_getnnz over an axis is not implemented for DOK format."
|
| 69 |
+
)
|
| 70 |
+
return len(self._dict)
|
| 71 |
+
|
| 72 |
+
def count_nonzero(self):
|
| 73 |
+
return sum(x != 0 for x in self.values())
|
| 74 |
+
|
| 75 |
+
_getnnz.__doc__ = _spbase._getnnz.__doc__
|
| 76 |
+
count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
|
| 77 |
+
|
| 78 |
+
def __len__(self):
|
| 79 |
+
return len(self._dict)
|
| 80 |
+
|
| 81 |
+
def __contains__(self, key):
|
| 82 |
+
return key in self._dict
|
| 83 |
+
|
| 84 |
+
def setdefault(self, key, default=None, /):
|
| 85 |
+
return self._dict.setdefault(key, default)
|
| 86 |
+
|
| 87 |
+
def __delitem__(self, key, /):
|
| 88 |
+
del self._dict[key]
|
| 89 |
+
|
| 90 |
+
def clear(self):
|
| 91 |
+
return self._dict.clear()
|
| 92 |
+
|
| 93 |
+
def pop(self, /, *args):
|
| 94 |
+
return self._dict.pop(*args)
|
| 95 |
+
|
| 96 |
+
def __reversed__(self):
|
| 97 |
+
raise TypeError("reversed is not defined for dok_array type")
|
| 98 |
+
|
| 99 |
+
def __or__(self, other):
|
| 100 |
+
type_names = f"{type(self).__name__} and {type(other).__name__}"
|
| 101 |
+
raise TypeError(f"unsupported operand type for |: {type_names}")
|
| 102 |
+
|
| 103 |
+
def __ror__(self, other):
|
| 104 |
+
type_names = f"{type(self).__name__} and {type(other).__name__}"
|
| 105 |
+
raise TypeError(f"unsupported operand type for |: {type_names}")
|
| 106 |
+
|
| 107 |
+
def __ior__(self, other):
|
| 108 |
+
type_names = f"{type(self).__name__} and {type(other).__name__}"
|
| 109 |
+
raise TypeError(f"unsupported operand type for |: {type_names}")
|
| 110 |
+
|
| 111 |
+
def popitem(self):
|
| 112 |
+
return self._dict.popitem()
|
| 113 |
+
|
| 114 |
+
def items(self):
|
| 115 |
+
return self._dict.items()
|
| 116 |
+
|
| 117 |
+
def keys(self):
|
| 118 |
+
return self._dict.keys()
|
| 119 |
+
|
| 120 |
+
def values(self):
|
| 121 |
+
return self._dict.values()
|
| 122 |
+
|
| 123 |
+
def get(self, key, default=0.0):
|
| 124 |
+
"""This provides dict.get method functionality with type checking"""
|
| 125 |
+
if key in self._dict:
|
| 126 |
+
return self._dict[key]
|
| 127 |
+
if isintlike(key) and self.ndim == 1:
|
| 128 |
+
key = (key,)
|
| 129 |
+
if self.ndim != len(key):
|
| 130 |
+
raise IndexError(f'Index {key} length needs to match self.shape')
|
| 131 |
+
try:
|
| 132 |
+
for i in key:
|
| 133 |
+
assert isintlike(i)
|
| 134 |
+
except (AssertionError, TypeError, ValueError) as e:
|
| 135 |
+
raise IndexError('Index must be or consist of integers.') from e
|
| 136 |
+
key = tuple(i + M if i < 0 else i for i, M in zip(key, self.shape))
|
| 137 |
+
if any(i < 0 or i >= M for i, M in zip(key, self.shape)):
|
| 138 |
+
raise IndexError('Index out of bounds.')
|
| 139 |
+
if self.ndim == 1:
|
| 140 |
+
key = key[0]
|
| 141 |
+
return self._dict.get(key, default)
|
| 142 |
+
|
| 143 |
+
# override IndexMixin.__getitem__ for 1d case until fully implemented
|
| 144 |
+
def __getitem__(self, key):
|
| 145 |
+
if self.ndim == 2:
|
| 146 |
+
return super().__getitem__(key)
|
| 147 |
+
|
| 148 |
+
if isinstance(key, tuple) and len(key) == 1:
|
| 149 |
+
key = key[0]
|
| 150 |
+
INT_TYPES = (int, np.integer)
|
| 151 |
+
if isinstance(key, INT_TYPES):
|
| 152 |
+
if key < 0:
|
| 153 |
+
key += self.shape[-1]
|
| 154 |
+
if key < 0 or key >= self.shape[-1]:
|
| 155 |
+
raise IndexError('index value out of bounds')
|
| 156 |
+
return self._get_int(key)
|
| 157 |
+
else:
|
| 158 |
+
raise IndexError('array/slice index for 1d dok_array not yet supported')
|
| 159 |
+
|
| 160 |
+
# 1D get methods
|
| 161 |
+
def _get_int(self, idx):
|
| 162 |
+
return self._dict.get(idx, self.dtype.type(0))
|
| 163 |
+
|
| 164 |
+
# 2D get methods
|
| 165 |
+
def _get_intXint(self, row, col):
|
| 166 |
+
return self._dict.get((row, col), self.dtype.type(0))
|
| 167 |
+
|
| 168 |
+
def _get_intXslice(self, row, col):
|
| 169 |
+
return self._get_sliceXslice(slice(row, row + 1), col)
|
| 170 |
+
|
| 171 |
+
def _get_sliceXint(self, row, col):
|
| 172 |
+
return self._get_sliceXslice(row, slice(col, col + 1))
|
| 173 |
+
|
| 174 |
+
def _get_sliceXslice(self, row, col):
|
| 175 |
+
row_start, row_stop, row_step = row.indices(self.shape[0])
|
| 176 |
+
col_start, col_stop, col_step = col.indices(self.shape[1])
|
| 177 |
+
row_range = range(row_start, row_stop, row_step)
|
| 178 |
+
col_range = range(col_start, col_stop, col_step)
|
| 179 |
+
shape = (len(row_range), len(col_range))
|
| 180 |
+
# Switch paths only when advantageous
|
| 181 |
+
# (count the iterations in the loops, adjust for complexity)
|
| 182 |
+
if len(self) >= 2 * shape[0] * shape[1]:
|
| 183 |
+
# O(nr*nc) path: loop over <row x col>
|
| 184 |
+
return self._get_columnXarray(row_range, col_range)
|
| 185 |
+
# O(nnz) path: loop over entries of self
|
| 186 |
+
newdok = self._dok_container(shape, dtype=self.dtype)
|
| 187 |
+
for key in self.keys():
|
| 188 |
+
i, ri = divmod(int(key[0]) - row_start, row_step)
|
| 189 |
+
if ri != 0 or i < 0 or i >= shape[0]:
|
| 190 |
+
continue
|
| 191 |
+
j, rj = divmod(int(key[1]) - col_start, col_step)
|
| 192 |
+
if rj != 0 or j < 0 or j >= shape[1]:
|
| 193 |
+
continue
|
| 194 |
+
newdok._dict[i, j] = self._dict[key]
|
| 195 |
+
return newdok
|
| 196 |
+
|
| 197 |
+
def _get_intXarray(self, row, col):
|
| 198 |
+
col = col.squeeze()
|
| 199 |
+
return self._get_columnXarray([row], col)
|
| 200 |
+
|
| 201 |
+
def _get_arrayXint(self, row, col):
|
| 202 |
+
row = row.squeeze()
|
| 203 |
+
return self._get_columnXarray(row, [col])
|
| 204 |
+
|
| 205 |
+
def _get_sliceXarray(self, row, col):
|
| 206 |
+
row = list(range(*row.indices(self.shape[0])))
|
| 207 |
+
return self._get_columnXarray(row, col)
|
| 208 |
+
|
| 209 |
+
def _get_arrayXslice(self, row, col):
|
| 210 |
+
col = list(range(*col.indices(self.shape[1])))
|
| 211 |
+
return self._get_columnXarray(row, col)
|
| 212 |
+
|
| 213 |
+
def _get_columnXarray(self, row, col):
|
| 214 |
+
# outer indexing
|
| 215 |
+
newdok = self._dok_container((len(row), len(col)), dtype=self.dtype)
|
| 216 |
+
|
| 217 |
+
for i, r in enumerate(row):
|
| 218 |
+
for j, c in enumerate(col):
|
| 219 |
+
v = self._dict.get((r, c), 0)
|
| 220 |
+
if v:
|
| 221 |
+
newdok._dict[i, j] = v
|
| 222 |
+
return newdok
|
| 223 |
+
|
| 224 |
+
def _get_arrayXarray(self, row, col):
|
| 225 |
+
# inner indexing
|
| 226 |
+
i, j = map(np.atleast_2d, np.broadcast_arrays(row, col))
|
| 227 |
+
newdok = self._dok_container(i.shape, dtype=self.dtype)
|
| 228 |
+
|
| 229 |
+
for key in itertools.product(range(i.shape[0]), range(i.shape[1])):
|
| 230 |
+
v = self._dict.get((i[key], j[key]), 0)
|
| 231 |
+
if v:
|
| 232 |
+
newdok._dict[key] = v
|
| 233 |
+
return newdok
|
| 234 |
+
|
| 235 |
+
# override IndexMixin.__setitem__ for 1d case until fully implemented
|
| 236 |
+
def __setitem__(self, key, value):
|
| 237 |
+
if self.ndim == 2:
|
| 238 |
+
return super().__setitem__(key, value)
|
| 239 |
+
|
| 240 |
+
if isinstance(key, tuple) and len(key) == 1:
|
| 241 |
+
key = key[0]
|
| 242 |
+
INT_TYPES = (int, np.integer)
|
| 243 |
+
if isinstance(key, INT_TYPES):
|
| 244 |
+
if key < 0:
|
| 245 |
+
key += self.shape[-1]
|
| 246 |
+
if key < 0 or key >= self.shape[-1]:
|
| 247 |
+
raise IndexError('index value out of bounds')
|
| 248 |
+
return self._set_int(key, value)
|
| 249 |
+
else:
|
| 250 |
+
raise IndexError('array index for 1d dok_array not yet provided')
|
| 251 |
+
|
| 252 |
+
# 1D set methods
|
| 253 |
+
def _set_int(self, idx, x):
|
| 254 |
+
if x:
|
| 255 |
+
self._dict[idx] = x
|
| 256 |
+
elif idx in self._dict:
|
| 257 |
+
del self._dict[idx]
|
| 258 |
+
|
| 259 |
+
# 2D set methods
|
| 260 |
+
def _set_intXint(self, row, col, x):
|
| 261 |
+
key = (row, col)
|
| 262 |
+
if x:
|
| 263 |
+
self._dict[key] = x
|
| 264 |
+
elif key in self._dict:
|
| 265 |
+
del self._dict[key]
|
| 266 |
+
|
| 267 |
+
def _set_arrayXarray(self, row, col, x):
|
| 268 |
+
row = list(map(int, row.ravel()))
|
| 269 |
+
col = list(map(int, col.ravel()))
|
| 270 |
+
x = x.ravel()
|
| 271 |
+
self._dict.update(zip(zip(row, col), x))
|
| 272 |
+
|
| 273 |
+
for i in np.nonzero(x == 0)[0]:
|
| 274 |
+
key = (row[i], col[i])
|
| 275 |
+
if self._dict[key] == 0:
|
| 276 |
+
# may have been superseded by later update
|
| 277 |
+
del self._dict[key]
|
| 278 |
+
|
| 279 |
+
def __add__(self, other):
|
| 280 |
+
if isscalarlike(other):
|
| 281 |
+
res_dtype = upcast_scalar(self.dtype, other)
|
| 282 |
+
new = self._dok_container(self.shape, dtype=res_dtype)
|
| 283 |
+
# Add this scalar to each element.
|
| 284 |
+
for key in itertools.product(*[range(d) for d in self.shape]):
|
| 285 |
+
aij = self._dict.get(key, 0) + other
|
| 286 |
+
if aij:
|
| 287 |
+
new[key] = aij
|
| 288 |
+
elif issparse(other):
|
| 289 |
+
if other.shape != self.shape:
|
| 290 |
+
raise ValueError("Matrix dimensions are not equal.")
|
| 291 |
+
res_dtype = upcast(self.dtype, other.dtype)
|
| 292 |
+
new = self._dok_container(self.shape, dtype=res_dtype)
|
| 293 |
+
new._dict = self._dict.copy()
|
| 294 |
+
if other.format == "dok":
|
| 295 |
+
o_items = other.items()
|
| 296 |
+
else:
|
| 297 |
+
other = other.tocoo()
|
| 298 |
+
if self.ndim == 1:
|
| 299 |
+
o_items = zip(other.coords[0], other.data)
|
| 300 |
+
else:
|
| 301 |
+
o_items = zip(zip(*other.coords), other.data)
|
| 302 |
+
with np.errstate(over='ignore'):
|
| 303 |
+
new._dict.update((k, new[k] + v) for k, v in o_items)
|
| 304 |
+
elif isdense(other):
|
| 305 |
+
new = self.todense() + other
|
| 306 |
+
else:
|
| 307 |
+
return NotImplemented
|
| 308 |
+
return new
|
| 309 |
+
|
| 310 |
+
def __radd__(self, other):
|
| 311 |
+
return self + other # addition is comutative
|
| 312 |
+
|
| 313 |
+
def __neg__(self):
|
| 314 |
+
if self.dtype.kind == 'b':
|
| 315 |
+
raise NotImplementedError(
|
| 316 |
+
'Negating a sparse boolean matrix is not supported.'
|
| 317 |
+
)
|
| 318 |
+
new = self._dok_container(self.shape, dtype=self.dtype)
|
| 319 |
+
new._dict.update((k, -v) for k, v in self.items())
|
| 320 |
+
return new
|
| 321 |
+
|
| 322 |
+
def _mul_scalar(self, other):
|
| 323 |
+
res_dtype = upcast_scalar(self.dtype, other)
|
| 324 |
+
# Multiply this scalar by every element.
|
| 325 |
+
new = self._dok_container(self.shape, dtype=res_dtype)
|
| 326 |
+
new._dict.update(((k, v * other) for k, v in self.items()))
|
| 327 |
+
return new
|
| 328 |
+
|
| 329 |
+
def _matmul_vector(self, other):
|
| 330 |
+
res_dtype = upcast(self.dtype, other.dtype)
|
| 331 |
+
|
| 332 |
+
# vector @ vector
|
| 333 |
+
if self.ndim == 1:
|
| 334 |
+
if issparse(other):
|
| 335 |
+
if other.format == "dok":
|
| 336 |
+
keys = self.keys() & other.keys()
|
| 337 |
+
else:
|
| 338 |
+
keys = self.keys() & other.tocoo().coords[0]
|
| 339 |
+
return res_dtype(sum(self._dict[k] * other._dict[k] for k in keys))
|
| 340 |
+
elif isdense(other):
|
| 341 |
+
return res_dtype(sum(other[k] * v for k, v in self.items()))
|
| 342 |
+
else:
|
| 343 |
+
return NotImplemented
|
| 344 |
+
|
| 345 |
+
# matrix @ vector
|
| 346 |
+
result = np.zeros(self.shape[0], dtype=res_dtype)
|
| 347 |
+
for (i, j), v in self.items():
|
| 348 |
+
result[i] += v * other[j]
|
| 349 |
+
return result
|
| 350 |
+
|
| 351 |
+
def _matmul_multivector(self, other):
|
| 352 |
+
result_dtype = upcast(self.dtype, other.dtype)
|
| 353 |
+
# vector @ multivector
|
| 354 |
+
if self.ndim == 1:
|
| 355 |
+
# works for other 1d or 2d
|
| 356 |
+
return sum(v * other[j] for j, v in self._dict.items())
|
| 357 |
+
|
| 358 |
+
# matrix @ multivector
|
| 359 |
+
M = self.shape[0]
|
| 360 |
+
new_shape = (M,) if other.ndim == 1 else (M, other.shape[1])
|
| 361 |
+
result = np.zeros(new_shape, dtype=result_dtype)
|
| 362 |
+
for (i, j), v in self.items():
|
| 363 |
+
result[i] += v * other[j]
|
| 364 |
+
return result
|
| 365 |
+
|
| 366 |
+
def __imul__(self, other):
|
| 367 |
+
if isscalarlike(other):
|
| 368 |
+
self._dict.update((k, v * other) for k, v in self.items())
|
| 369 |
+
return self
|
| 370 |
+
return NotImplemented
|
| 371 |
+
|
| 372 |
+
def __truediv__(self, other):
|
| 373 |
+
if isscalarlike(other):
|
| 374 |
+
res_dtype = upcast_scalar(self.dtype, other)
|
| 375 |
+
new = self._dok_container(self.shape, dtype=res_dtype)
|
| 376 |
+
new._dict.update(((k, v / other) for k, v in self.items()))
|
| 377 |
+
return new
|
| 378 |
+
return self.tocsr() / other
|
| 379 |
+
|
| 380 |
+
def __itruediv__(self, other):
|
| 381 |
+
if isscalarlike(other):
|
| 382 |
+
self._dict.update((k, v / other) for k, v in self.items())
|
| 383 |
+
return self
|
| 384 |
+
return NotImplemented
|
| 385 |
+
|
| 386 |
+
def __reduce__(self):
|
| 387 |
+
# this approach is necessary because __setstate__ is called after
|
| 388 |
+
# __setitem__ upon unpickling and since __init__ is not called there
|
| 389 |
+
# is no shape attribute hence it is not possible to unpickle it.
|
| 390 |
+
return dict.__reduce__(self)
|
| 391 |
+
|
| 392 |
+
def diagonal(self, k=0):
|
| 393 |
+
if self.ndim == 2:
|
| 394 |
+
return super().diagonal(k)
|
| 395 |
+
raise ValueError("diagonal requires two dimensions")
|
| 396 |
+
|
| 397 |
+
def transpose(self, axes=None, copy=False):
|
| 398 |
+
if self.ndim == 1:
|
| 399 |
+
return self.copy()
|
| 400 |
+
|
| 401 |
+
if axes is not None and axes != (1, 0):
|
| 402 |
+
raise ValueError(
|
| 403 |
+
"Sparse arrays/matrices do not support "
|
| 404 |
+
"an 'axes' parameter because swapping "
|
| 405 |
+
"dimensions is the only logical permutation."
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
M, N = self.shape
|
| 409 |
+
new = self._dok_container((N, M), dtype=self.dtype, copy=copy)
|
| 410 |
+
new._dict.update((((right, left), val) for (left, right), val in self.items()))
|
| 411 |
+
return new
|
| 412 |
+
|
| 413 |
+
transpose.__doc__ = _spbase.transpose.__doc__
|
| 414 |
+
|
| 415 |
+
def conjtransp(self):
|
| 416 |
+
"""DEPRECATED: Return the conjugate transpose.
|
| 417 |
+
|
| 418 |
+
.. deprecated:: 1.14.0
|
| 419 |
+
|
| 420 |
+
`conjtransp` is deprecated and will be removed in v1.16.0.
|
| 421 |
+
Use `.T.conj()` instead.
|
| 422 |
+
"""
|
| 423 |
+
msg = ("`conjtransp` is deprecated and will be removed in v1.16.0. "
|
| 424 |
+
"Use `.T.conj()` instead.")
|
| 425 |
+
warn(msg, DeprecationWarning, stacklevel=2)
|
| 426 |
+
|
| 427 |
+
if self.ndim == 1:
|
| 428 |
+
new = self.tocoo()
|
| 429 |
+
new.data = new.data.conjugate()
|
| 430 |
+
return new
|
| 431 |
+
|
| 432 |
+
M, N = self.shape
|
| 433 |
+
new = self._dok_container((N, M), dtype=self.dtype)
|
| 434 |
+
new._dict = {(right, left): np.conj(val) for (left, right), val in self.items()}
|
| 435 |
+
return new
|
| 436 |
+
|
| 437 |
+
def copy(self):
|
| 438 |
+
new = self._dok_container(self.shape, dtype=self.dtype)
|
| 439 |
+
new._dict.update(self._dict)
|
| 440 |
+
return new
|
| 441 |
+
|
| 442 |
+
copy.__doc__ = _spbase.copy.__doc__
|
| 443 |
+
|
| 444 |
+
@classmethod
|
| 445 |
+
def fromkeys(cls, iterable, value=1, /):
|
| 446 |
+
tmp = dict.fromkeys(iterable, value)
|
| 447 |
+
if isinstance(next(iter(tmp)), tuple):
|
| 448 |
+
shape = tuple(max(idx) + 1 for idx in zip(*tmp))
|
| 449 |
+
else:
|
| 450 |
+
shape = (max(tmp) + 1,)
|
| 451 |
+
result = cls(shape, dtype=type(value))
|
| 452 |
+
result._dict = tmp
|
| 453 |
+
return result
|
| 454 |
+
|
| 455 |
+
def tocoo(self, copy=False):
|
| 456 |
+
nnz = self.nnz
|
| 457 |
+
if nnz == 0:
|
| 458 |
+
return self._coo_container(self.shape, dtype=self.dtype)
|
| 459 |
+
|
| 460 |
+
idx_dtype = self._get_index_dtype(maxval=max(self.shape))
|
| 461 |
+
data = np.fromiter(self.values(), dtype=self.dtype, count=nnz)
|
| 462 |
+
# handle 1d keys specially b/c not a tuple
|
| 463 |
+
inds = zip(*self.keys()) if self.ndim > 1 else (self.keys(),)
|
| 464 |
+
coords = tuple(np.fromiter(ix, dtype=idx_dtype, count=nnz) for ix in inds)
|
| 465 |
+
A = self._coo_container((data, coords), shape=self.shape, dtype=self.dtype)
|
| 466 |
+
A.has_canonical_format = True
|
| 467 |
+
return A
|
| 468 |
+
|
| 469 |
+
tocoo.__doc__ = _spbase.tocoo.__doc__
|
| 470 |
+
|
| 471 |
+
def todok(self, copy=False):
|
| 472 |
+
if copy:
|
| 473 |
+
return self.copy()
|
| 474 |
+
return self
|
| 475 |
+
|
| 476 |
+
todok.__doc__ = _spbase.todok.__doc__
|
| 477 |
+
|
| 478 |
+
def tocsc(self, copy=False):
|
| 479 |
+
if self.ndim == 1:
|
| 480 |
+
raise NotImplementedError("tocsr() not valid for 1d sparse array")
|
| 481 |
+
return self.tocoo(copy=False).tocsc(copy=copy)
|
| 482 |
+
|
| 483 |
+
tocsc.__doc__ = _spbase.tocsc.__doc__
|
| 484 |
+
|
| 485 |
+
def resize(self, *shape):
|
| 486 |
+
is_array = isinstance(self, sparray)
|
| 487 |
+
shape = check_shape(shape, allow_1d=is_array)
|
| 488 |
+
if len(shape) != len(self.shape):
|
| 489 |
+
# TODO implement resize across dimensions
|
| 490 |
+
raise NotImplementedError
|
| 491 |
+
|
| 492 |
+
if self.ndim == 1:
|
| 493 |
+
newN = shape[-1]
|
| 494 |
+
for i in list(self._dict):
|
| 495 |
+
if i >= newN:
|
| 496 |
+
del self._dict[i]
|
| 497 |
+
self._shape = shape
|
| 498 |
+
return
|
| 499 |
+
|
| 500 |
+
newM, newN = shape
|
| 501 |
+
M, N = self.shape
|
| 502 |
+
if newM < M or newN < N:
|
| 503 |
+
# Remove all elements outside new dimensions
|
| 504 |
+
for i, j in list(self.keys()):
|
| 505 |
+
if i >= newM or j >= newN:
|
| 506 |
+
del self._dict[i, j]
|
| 507 |
+
self._shape = shape
|
| 508 |
+
|
| 509 |
+
resize.__doc__ = _spbase.resize.__doc__
|
| 510 |
+
|
| 511 |
+
# Added for 1d to avoid `tocsr` from _base.py
|
| 512 |
+
def astype(self, dtype, casting='unsafe', copy=True):
|
| 513 |
+
dtype = np.dtype(dtype)
|
| 514 |
+
if self.dtype != dtype:
|
| 515 |
+
result = self._dok_container(self.shape, dtype=dtype)
|
| 516 |
+
data = np.array(list(self._dict.values()), dtype=dtype)
|
| 517 |
+
result._dict = dict(zip(self._dict, data))
|
| 518 |
+
return result
|
| 519 |
+
elif copy:
|
| 520 |
+
return self.copy()
|
| 521 |
+
return self
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def isspmatrix_dok(x):
|
| 525 |
+
"""Is `x` of dok_array type?
|
| 526 |
+
|
| 527 |
+
Parameters
|
| 528 |
+
----------
|
| 529 |
+
x
|
| 530 |
+
object to check for being a dok matrix
|
| 531 |
+
|
| 532 |
+
Returns
|
| 533 |
+
-------
|
| 534 |
+
bool
|
| 535 |
+
True if `x` is a dok matrix, False otherwise
|
| 536 |
+
|
| 537 |
+
Examples
|
| 538 |
+
--------
|
| 539 |
+
>>> from scipy.sparse import dok_array, dok_matrix, coo_matrix, isspmatrix_dok
|
| 540 |
+
>>> isspmatrix_dok(dok_matrix([[5]]))
|
| 541 |
+
True
|
| 542 |
+
>>> isspmatrix_dok(dok_array([[5]]))
|
| 543 |
+
False
|
| 544 |
+
>>> isspmatrix_dok(coo_matrix([[5]]))
|
| 545 |
+
False
|
| 546 |
+
"""
|
| 547 |
+
return isinstance(x, dok_matrix)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
# This namespace class separates array from matrix with isinstance
|
| 551 |
+
class dok_array(_dok_base, sparray):
|
| 552 |
+
"""
|
| 553 |
+
Dictionary Of Keys based sparse array.
|
| 554 |
+
|
| 555 |
+
This is an efficient structure for constructing sparse
|
| 556 |
+
arrays incrementally.
|
| 557 |
+
|
| 558 |
+
This can be instantiated in several ways:
|
| 559 |
+
dok_array(D)
|
| 560 |
+
where D is a 2-D ndarray
|
| 561 |
+
|
| 562 |
+
dok_array(S)
|
| 563 |
+
with another sparse array or matrix S (equivalent to S.todok())
|
| 564 |
+
|
| 565 |
+
dok_array((M,N), [dtype])
|
| 566 |
+
create the array with initial shape (M,N)
|
| 567 |
+
dtype is optional, defaulting to dtype='d'
|
| 568 |
+
|
| 569 |
+
Attributes
|
| 570 |
+
----------
|
| 571 |
+
dtype : dtype
|
| 572 |
+
Data type of the array
|
| 573 |
+
shape : 2-tuple
|
| 574 |
+
Shape of the array
|
| 575 |
+
ndim : int
|
| 576 |
+
Number of dimensions (this is always 2)
|
| 577 |
+
nnz
|
| 578 |
+
Number of nonzero elements
|
| 579 |
+
size
|
| 580 |
+
T
|
| 581 |
+
|
| 582 |
+
Notes
|
| 583 |
+
-----
|
| 584 |
+
|
| 585 |
+
Sparse arrays can be used in arithmetic operations: they support
|
| 586 |
+
addition, subtraction, multiplication, division, and matrix power.
|
| 587 |
+
|
| 588 |
+
- Allows for efficient O(1) access of individual elements.
|
| 589 |
+
- Duplicates are not allowed.
|
| 590 |
+
- Can be efficiently converted to a coo_array once constructed.
|
| 591 |
+
|
| 592 |
+
Examples
|
| 593 |
+
--------
|
| 594 |
+
>>> import numpy as np
|
| 595 |
+
>>> from scipy.sparse import dok_array
|
| 596 |
+
>>> S = dok_array((5, 5), dtype=np.float32)
|
| 597 |
+
>>> for i in range(5):
|
| 598 |
+
... for j in range(5):
|
| 599 |
+
... S[i, j] = i + j # Update element
|
| 600 |
+
|
| 601 |
+
"""
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
class dok_matrix(spmatrix, _dok_base):
|
| 605 |
+
"""
|
| 606 |
+
Dictionary Of Keys based sparse matrix.
|
| 607 |
+
|
| 608 |
+
This is an efficient structure for constructing sparse
|
| 609 |
+
matrices incrementally.
|
| 610 |
+
|
| 611 |
+
This can be instantiated in several ways:
|
| 612 |
+
dok_matrix(D)
|
| 613 |
+
where D is a 2-D ndarray
|
| 614 |
+
|
| 615 |
+
dok_matrix(S)
|
| 616 |
+
with another sparse array or matrix S (equivalent to S.todok())
|
| 617 |
+
|
| 618 |
+
dok_matrix((M,N), [dtype])
|
| 619 |
+
create the matrix with initial shape (M,N)
|
| 620 |
+
dtype is optional, defaulting to dtype='d'
|
| 621 |
+
|
| 622 |
+
Attributes
|
| 623 |
+
----------
|
| 624 |
+
dtype : dtype
|
| 625 |
+
Data type of the matrix
|
| 626 |
+
shape : 2-tuple
|
| 627 |
+
Shape of the matrix
|
| 628 |
+
ndim : int
|
| 629 |
+
Number of dimensions (this is always 2)
|
| 630 |
+
nnz
|
| 631 |
+
Number of nonzero elements
|
| 632 |
+
size
|
| 633 |
+
T
|
| 634 |
+
|
| 635 |
+
Notes
|
| 636 |
+
-----
|
| 637 |
+
|
| 638 |
+
Sparse matrices can be used in arithmetic operations: they support
|
| 639 |
+
addition, subtraction, multiplication, division, and matrix power.
|
| 640 |
+
|
| 641 |
+
- Allows for efficient O(1) access of individual elements.
|
| 642 |
+
- Duplicates are not allowed.
|
| 643 |
+
- Can be efficiently converted to a coo_matrix once constructed.
|
| 644 |
+
|
| 645 |
+
Examples
|
| 646 |
+
--------
|
| 647 |
+
>>> import numpy as np
|
| 648 |
+
>>> from scipy.sparse import dok_matrix
|
| 649 |
+
>>> S = dok_matrix((5, 5), dtype=np.float32)
|
| 650 |
+
>>> for i in range(5):
|
| 651 |
+
... for j in range(5):
|
| 652 |
+
... S[i, j] = i + j # Update element
|
| 653 |
+
|
| 654 |
+
"""
|
| 655 |
+
|
| 656 |
+
def set_shape(self, shape):
|
| 657 |
+
new_matrix = self.reshape(shape, copy=False).asformat(self.format)
|
| 658 |
+
self.__dict__ = new_matrix.__dict__
|
| 659 |
+
|
| 660 |
+
def get_shape(self):
|
| 661 |
+
"""Get shape of a sparse matrix."""
|
| 662 |
+
return self._shape
|
| 663 |
+
|
| 664 |
+
shape = property(fget=get_shape, fset=set_shape)
|
| 665 |
+
|
| 666 |
+
def __reversed__(self):
|
| 667 |
+
return self._dict.__reversed__()
|
| 668 |
+
|
| 669 |
+
def __or__(self, other):
|
| 670 |
+
if isinstance(other, _dok_base):
|
| 671 |
+
return self._dict | other._dict
|
| 672 |
+
return self._dict | other
|
| 673 |
+
|
| 674 |
+
def __ror__(self, other):
|
| 675 |
+
if isinstance(other, _dok_base):
|
| 676 |
+
return self._dict | other._dict
|
| 677 |
+
return self._dict | other
|
| 678 |
+
|
| 679 |
+
def __ior__(self, other):
|
| 680 |
+
if isinstance(other, _dok_base):
|
| 681 |
+
self._dict |= other._dict
|
| 682 |
+
else:
|
| 683 |
+
self._dict |= other
|
| 684 |
+
return self
|
parrot/lib/python3.10/site-packages/scipy/sparse/_extract.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions to extract parts of sparse matrices
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
__docformat__ = "restructuredtext en"
|
| 5 |
+
|
| 6 |
+
__all__ = ['find', 'tril', 'triu']
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
from ._coo import coo_matrix, coo_array
|
| 10 |
+
from ._base import sparray
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def find(A):
|
| 14 |
+
"""Return the indices and values of the nonzero elements of a matrix
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
----------
|
| 18 |
+
A : dense or sparse array or matrix
|
| 19 |
+
Matrix whose nonzero elements are desired.
|
| 20 |
+
|
| 21 |
+
Returns
|
| 22 |
+
-------
|
| 23 |
+
(I,J,V) : tuple of arrays
|
| 24 |
+
I,J, and V contain the row indices, column indices, and values
|
| 25 |
+
of the nonzero entries.
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
Examples
|
| 29 |
+
--------
|
| 30 |
+
>>> from scipy.sparse import csr_array, find
|
| 31 |
+
>>> A = csr_array([[7.0, 8.0, 0],[0, 0, 9.0]])
|
| 32 |
+
>>> find(A)
|
| 33 |
+
(array([0, 0, 1], dtype=int32),
|
| 34 |
+
array([0, 1, 2], dtype=int32),
|
| 35 |
+
array([ 7., 8., 9.]))
|
| 36 |
+
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
A = coo_array(A, copy=True)
|
| 40 |
+
A.sum_duplicates()
|
| 41 |
+
# remove explicit zeros
|
| 42 |
+
nz_mask = A.data != 0
|
| 43 |
+
return A.row[nz_mask], A.col[nz_mask], A.data[nz_mask]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def tril(A, k=0, format=None):
|
| 47 |
+
"""Return the lower triangular portion of a sparse array or matrix
|
| 48 |
+
|
| 49 |
+
Returns the elements on or below the k-th diagonal of A.
|
| 50 |
+
- k = 0 corresponds to the main diagonal
|
| 51 |
+
- k > 0 is above the main diagonal
|
| 52 |
+
- k < 0 is below the main diagonal
|
| 53 |
+
|
| 54 |
+
Parameters
|
| 55 |
+
----------
|
| 56 |
+
A : dense or sparse array or matrix
|
| 57 |
+
Matrix whose lower trianglar portion is desired.
|
| 58 |
+
k : integer : optional
|
| 59 |
+
The top-most diagonal of the lower triangle.
|
| 60 |
+
format : string
|
| 61 |
+
Sparse format of the result, e.g. format="csr", etc.
|
| 62 |
+
|
| 63 |
+
Returns
|
| 64 |
+
-------
|
| 65 |
+
L : sparse matrix
|
| 66 |
+
Lower triangular portion of A in sparse format.
|
| 67 |
+
|
| 68 |
+
See Also
|
| 69 |
+
--------
|
| 70 |
+
triu : upper triangle in sparse format
|
| 71 |
+
|
| 72 |
+
Examples
|
| 73 |
+
--------
|
| 74 |
+
>>> from scipy.sparse import csr_array, tril
|
| 75 |
+
>>> A = csr_array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
|
| 76 |
+
... dtype='int32')
|
| 77 |
+
>>> A.toarray()
|
| 78 |
+
array([[1, 2, 0, 0, 3],
|
| 79 |
+
[4, 5, 0, 6, 7],
|
| 80 |
+
[0, 0, 8, 9, 0]])
|
| 81 |
+
>>> tril(A).toarray()
|
| 82 |
+
array([[1, 0, 0, 0, 0],
|
| 83 |
+
[4, 5, 0, 0, 0],
|
| 84 |
+
[0, 0, 8, 0, 0]])
|
| 85 |
+
>>> tril(A).nnz
|
| 86 |
+
4
|
| 87 |
+
>>> tril(A, k=1).toarray()
|
| 88 |
+
array([[1, 2, 0, 0, 0],
|
| 89 |
+
[4, 5, 0, 0, 0],
|
| 90 |
+
[0, 0, 8, 9, 0]])
|
| 91 |
+
>>> tril(A, k=-1).toarray()
|
| 92 |
+
array([[0, 0, 0, 0, 0],
|
| 93 |
+
[4, 0, 0, 0, 0],
|
| 94 |
+
[0, 0, 0, 0, 0]])
|
| 95 |
+
>>> tril(A, format='csc')
|
| 96 |
+
<Compressed Sparse Column sparse array of dtype 'int32'
|
| 97 |
+
with 4 stored elements and shape (3, 5)>
|
| 98 |
+
|
| 99 |
+
"""
|
| 100 |
+
coo_sparse = coo_array if isinstance(A, sparray) else coo_matrix
|
| 101 |
+
|
| 102 |
+
# convert to COOrdinate format where things are easy
|
| 103 |
+
A = coo_sparse(A, copy=False)
|
| 104 |
+
mask = A.row + k >= A.col
|
| 105 |
+
|
| 106 |
+
row = A.row[mask]
|
| 107 |
+
col = A.col[mask]
|
| 108 |
+
data = A.data[mask]
|
| 109 |
+
new_coo = coo_sparse((data, (row, col)), shape=A.shape, dtype=A.dtype)
|
| 110 |
+
return new_coo.asformat(format)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def triu(A, k=0, format=None):
|
| 114 |
+
"""Return the upper triangular portion of a sparse array or matrix
|
| 115 |
+
|
| 116 |
+
Returns the elements on or above the k-th diagonal of A.
|
| 117 |
+
- k = 0 corresponds to the main diagonal
|
| 118 |
+
- k > 0 is above the main diagonal
|
| 119 |
+
- k < 0 is below the main diagonal
|
| 120 |
+
|
| 121 |
+
Parameters
|
| 122 |
+
----------
|
| 123 |
+
A : dense or sparse array or matrix
|
| 124 |
+
Matrix whose upper trianglar portion is desired.
|
| 125 |
+
k : integer : optional
|
| 126 |
+
The bottom-most diagonal of the upper triangle.
|
| 127 |
+
format : string
|
| 128 |
+
Sparse format of the result, e.g. format="csr", etc.
|
| 129 |
+
|
| 130 |
+
Returns
|
| 131 |
+
-------
|
| 132 |
+
L : sparse array or matrix
|
| 133 |
+
Upper triangular portion of A in sparse format.
|
| 134 |
+
Sparse array if A is a sparse array, otherwise matrix.
|
| 135 |
+
|
| 136 |
+
See Also
|
| 137 |
+
--------
|
| 138 |
+
tril : lower triangle in sparse format
|
| 139 |
+
|
| 140 |
+
Examples
|
| 141 |
+
--------
|
| 142 |
+
>>> from scipy.sparse import csr_array, triu
|
| 143 |
+
>>> A = csr_array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
|
| 144 |
+
... dtype='int32')
|
| 145 |
+
>>> A.toarray()
|
| 146 |
+
array([[1, 2, 0, 0, 3],
|
| 147 |
+
[4, 5, 0, 6, 7],
|
| 148 |
+
[0, 0, 8, 9, 0]])
|
| 149 |
+
>>> triu(A).toarray()
|
| 150 |
+
array([[1, 2, 0, 0, 3],
|
| 151 |
+
[0, 5, 0, 6, 7],
|
| 152 |
+
[0, 0, 8, 9, 0]])
|
| 153 |
+
>>> triu(A).nnz
|
| 154 |
+
8
|
| 155 |
+
>>> triu(A, k=1).toarray()
|
| 156 |
+
array([[0, 2, 0, 0, 3],
|
| 157 |
+
[0, 0, 0, 6, 7],
|
| 158 |
+
[0, 0, 0, 9, 0]])
|
| 159 |
+
>>> triu(A, k=-1).toarray()
|
| 160 |
+
array([[1, 2, 0, 0, 3],
|
| 161 |
+
[4, 5, 0, 6, 7],
|
| 162 |
+
[0, 0, 8, 9, 0]])
|
| 163 |
+
>>> triu(A, format='csc')
|
| 164 |
+
<Compressed Sparse Column sparse array of dtype 'int32'
|
| 165 |
+
with 8 stored elements and shape (3, 5)>
|
| 166 |
+
|
| 167 |
+
"""
|
| 168 |
+
coo_sparse = coo_array if isinstance(A, sparray) else coo_matrix
|
| 169 |
+
|
| 170 |
+
# convert to COOrdinate format where things are easy
|
| 171 |
+
A = coo_sparse(A, copy=False)
|
| 172 |
+
mask = A.row + k <= A.col
|
| 173 |
+
|
| 174 |
+
row = A.row[mask]
|
| 175 |
+
col = A.col[mask]
|
| 176 |
+
data = A.data[mask]
|
| 177 |
+
new_coo = coo_sparse((data, (row, col)), shape=A.shape, dtype=A.dtype)
|
| 178 |
+
return new_coo.asformat(format)
|
parrot/lib/python3.10/site-packages/scipy/sparse/_index.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Indexing mixin for sparse array/matrix classes.
|
| 2 |
+
"""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import TYPE_CHECKING
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
from ._sputils import isintlike
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
import numpy.typing as npt
|
| 12 |
+
|
| 13 |
+
INT_TYPES = (int, np.integer)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _broadcast_arrays(a, b):
|
| 17 |
+
"""
|
| 18 |
+
Same as np.broadcast_arrays(a, b) but old writeability rules.
|
| 19 |
+
|
| 20 |
+
NumPy >= 1.17.0 transitions broadcast_arrays to return
|
| 21 |
+
read-only arrays. Set writeability explicitly to avoid warnings.
|
| 22 |
+
Retain the old writeability rules, as our Cython code assumes
|
| 23 |
+
the old behavior.
|
| 24 |
+
"""
|
| 25 |
+
x, y = np.broadcast_arrays(a, b)
|
| 26 |
+
x.flags.writeable = a.flags.writeable
|
| 27 |
+
y.flags.writeable = b.flags.writeable
|
| 28 |
+
return x, y
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class IndexMixin:
|
| 32 |
+
"""
|
| 33 |
+
This class provides common dispatching and validation logic for indexing.
|
| 34 |
+
"""
|
| 35 |
+
def _raise_on_1d_array_slice(self):
|
| 36 |
+
"""We do not currently support 1D sparse arrays.
|
| 37 |
+
|
| 38 |
+
This function is called each time that a 1D array would
|
| 39 |
+
result, raising an error instead.
|
| 40 |
+
|
| 41 |
+
Once 1D sparse arrays are implemented, it should be removed.
|
| 42 |
+
"""
|
| 43 |
+
from scipy.sparse import sparray
|
| 44 |
+
|
| 45 |
+
if isinstance(self, sparray):
|
| 46 |
+
raise NotImplementedError(
|
| 47 |
+
'We have not yet implemented 1D sparse slices; '
|
| 48 |
+
'please index using explicit indices, e.g. `x[:, [0]]`'
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def __getitem__(self, key):
|
| 52 |
+
row, col = self._validate_indices(key)
|
| 53 |
+
|
| 54 |
+
# Dispatch to specialized methods.
|
| 55 |
+
if isinstance(row, INT_TYPES):
|
| 56 |
+
if isinstance(col, INT_TYPES):
|
| 57 |
+
return self._get_intXint(row, col)
|
| 58 |
+
elif isinstance(col, slice):
|
| 59 |
+
self._raise_on_1d_array_slice()
|
| 60 |
+
return self._get_intXslice(row, col)
|
| 61 |
+
elif col.ndim == 1:
|
| 62 |
+
self._raise_on_1d_array_slice()
|
| 63 |
+
return self._get_intXarray(row, col)
|
| 64 |
+
elif col.ndim == 2:
|
| 65 |
+
return self._get_intXarray(row, col)
|
| 66 |
+
raise IndexError('index results in >2 dimensions')
|
| 67 |
+
elif isinstance(row, slice):
|
| 68 |
+
if isinstance(col, INT_TYPES):
|
| 69 |
+
self._raise_on_1d_array_slice()
|
| 70 |
+
return self._get_sliceXint(row, col)
|
| 71 |
+
elif isinstance(col, slice):
|
| 72 |
+
if row == slice(None) and row == col:
|
| 73 |
+
return self.copy()
|
| 74 |
+
return self._get_sliceXslice(row, col)
|
| 75 |
+
elif col.ndim == 1:
|
| 76 |
+
return self._get_sliceXarray(row, col)
|
| 77 |
+
raise IndexError('index results in >2 dimensions')
|
| 78 |
+
elif row.ndim == 1:
|
| 79 |
+
if isinstance(col, INT_TYPES):
|
| 80 |
+
self._raise_on_1d_array_slice()
|
| 81 |
+
return self._get_arrayXint(row, col)
|
| 82 |
+
elif isinstance(col, slice):
|
| 83 |
+
return self._get_arrayXslice(row, col)
|
| 84 |
+
else: # row.ndim == 2
|
| 85 |
+
if isinstance(col, INT_TYPES):
|
| 86 |
+
return self._get_arrayXint(row, col)
|
| 87 |
+
elif isinstance(col, slice):
|
| 88 |
+
raise IndexError('index results in >2 dimensions')
|
| 89 |
+
elif row.shape[1] == 1 and (col.ndim == 1 or col.shape[0] == 1):
|
| 90 |
+
# special case for outer indexing
|
| 91 |
+
return self._get_columnXarray(row[:,0], col.ravel())
|
| 92 |
+
|
| 93 |
+
# The only remaining case is inner (fancy) indexing
|
| 94 |
+
row, col = _broadcast_arrays(row, col)
|
| 95 |
+
if row.shape != col.shape:
|
| 96 |
+
raise IndexError('number of row and column indices differ')
|
| 97 |
+
if row.size == 0:
|
| 98 |
+
return self.__class__(np.atleast_2d(row).shape, dtype=self.dtype)
|
| 99 |
+
return self._get_arrayXarray(row, col)
|
| 100 |
+
|
| 101 |
+
def __setitem__(self, key, x):
|
| 102 |
+
row, col = self._validate_indices(key)
|
| 103 |
+
|
| 104 |
+
if isinstance(row, INT_TYPES) and isinstance(col, INT_TYPES):
|
| 105 |
+
x = np.asarray(x, dtype=self.dtype)
|
| 106 |
+
if x.size != 1:
|
| 107 |
+
raise ValueError('Trying to assign a sequence to an item')
|
| 108 |
+
self._set_intXint(row, col, x.flat[0])
|
| 109 |
+
return
|
| 110 |
+
|
| 111 |
+
if isinstance(row, slice):
|
| 112 |
+
row = np.arange(*row.indices(self.shape[0]))[:, None]
|
| 113 |
+
else:
|
| 114 |
+
row = np.atleast_1d(row)
|
| 115 |
+
|
| 116 |
+
if isinstance(col, slice):
|
| 117 |
+
col = np.arange(*col.indices(self.shape[1]))[None, :]
|
| 118 |
+
if row.ndim == 1:
|
| 119 |
+
row = row[:, None]
|
| 120 |
+
else:
|
| 121 |
+
col = np.atleast_1d(col)
|
| 122 |
+
|
| 123 |
+
i, j = _broadcast_arrays(row, col)
|
| 124 |
+
if i.shape != j.shape:
|
| 125 |
+
raise IndexError('number of row and column indices differ')
|
| 126 |
+
|
| 127 |
+
from ._base import issparse
|
| 128 |
+
if issparse(x):
|
| 129 |
+
if i.ndim == 1:
|
| 130 |
+
# Inner indexing, so treat them like row vectors.
|
| 131 |
+
i = i[None]
|
| 132 |
+
j = j[None]
|
| 133 |
+
broadcast_row = x.shape[0] == 1 and i.shape[0] != 1
|
| 134 |
+
broadcast_col = x.shape[1] == 1 and i.shape[1] != 1
|
| 135 |
+
if not ((broadcast_row or x.shape[0] == i.shape[0]) and
|
| 136 |
+
(broadcast_col or x.shape[1] == i.shape[1])):
|
| 137 |
+
raise ValueError('shape mismatch in assignment')
|
| 138 |
+
if x.shape[0] == 0 or x.shape[1] == 0:
|
| 139 |
+
return
|
| 140 |
+
x = x.tocoo(copy=True)
|
| 141 |
+
x.sum_duplicates()
|
| 142 |
+
self._set_arrayXarray_sparse(i, j, x)
|
| 143 |
+
else:
|
| 144 |
+
# Make x and i into the same shape
|
| 145 |
+
x = np.asarray(x, dtype=self.dtype)
|
| 146 |
+
if x.squeeze().shape != i.squeeze().shape:
|
| 147 |
+
x = np.broadcast_to(x, i.shape)
|
| 148 |
+
if x.size == 0:
|
| 149 |
+
return
|
| 150 |
+
x = x.reshape(i.shape)
|
| 151 |
+
self._set_arrayXarray(i, j, x)
|
| 152 |
+
|
| 153 |
+
def _validate_indices(self, key):
|
| 154 |
+
# First, check if indexing with single boolean matrix.
|
| 155 |
+
from ._base import _spbase
|
| 156 |
+
if (isinstance(key, (_spbase, np.ndarray)) and
|
| 157 |
+
key.ndim == 2 and key.dtype.kind == 'b'):
|
| 158 |
+
if key.shape != self.shape:
|
| 159 |
+
raise IndexError('boolean index shape does not match array shape')
|
| 160 |
+
row, col = key.nonzero()
|
| 161 |
+
else:
|
| 162 |
+
row, col = _unpack_index(key)
|
| 163 |
+
M, N = self.shape
|
| 164 |
+
|
| 165 |
+
def _validate_bool_idx(
|
| 166 |
+
idx: npt.NDArray[np.bool_],
|
| 167 |
+
axis_size: int,
|
| 168 |
+
axis_name: str
|
| 169 |
+
) -> npt.NDArray[np.int_]:
|
| 170 |
+
if len(idx) != axis_size:
|
| 171 |
+
raise IndexError(
|
| 172 |
+
f"boolean {axis_name} index has incorrect length: {len(idx)} "
|
| 173 |
+
f"instead of {axis_size}"
|
| 174 |
+
)
|
| 175 |
+
return _boolean_index_to_array(idx)
|
| 176 |
+
|
| 177 |
+
if isintlike(row):
|
| 178 |
+
row = int(row)
|
| 179 |
+
if row < -M or row >= M:
|
| 180 |
+
raise IndexError('row index (%d) out of range' % row)
|
| 181 |
+
if row < 0:
|
| 182 |
+
row += M
|
| 183 |
+
elif (bool_row := _compatible_boolean_index(row)) is not None:
|
| 184 |
+
row = _validate_bool_idx(bool_row, M, "row")
|
| 185 |
+
elif not isinstance(row, slice):
|
| 186 |
+
row = self._asindices(row, M)
|
| 187 |
+
|
| 188 |
+
if isintlike(col):
|
| 189 |
+
col = int(col)
|
| 190 |
+
if col < -N or col >= N:
|
| 191 |
+
raise IndexError('column index (%d) out of range' % col)
|
| 192 |
+
if col < 0:
|
| 193 |
+
col += N
|
| 194 |
+
elif (bool_col := _compatible_boolean_index(col)) is not None:
|
| 195 |
+
col = _validate_bool_idx(bool_col, N, "column")
|
| 196 |
+
elif not isinstance(col, slice):
|
| 197 |
+
col = self._asindices(col, N)
|
| 198 |
+
|
| 199 |
+
return row, col
|
| 200 |
+
|
| 201 |
+
def _asindices(self, idx, length):
|
| 202 |
+
"""Convert `idx` to a valid index for an axis with a given length.
|
| 203 |
+
|
| 204 |
+
Subclasses that need special validation can override this method.
|
| 205 |
+
"""
|
| 206 |
+
try:
|
| 207 |
+
x = np.asarray(idx)
|
| 208 |
+
except (ValueError, TypeError, MemoryError) as e:
|
| 209 |
+
raise IndexError('invalid index') from e
|
| 210 |
+
|
| 211 |
+
if x.ndim not in (1, 2):
|
| 212 |
+
raise IndexError('Index dimension must be 1 or 2')
|
| 213 |
+
|
| 214 |
+
if x.size == 0:
|
| 215 |
+
return x
|
| 216 |
+
|
| 217 |
+
# Check bounds
|
| 218 |
+
max_indx = x.max()
|
| 219 |
+
if max_indx >= length:
|
| 220 |
+
raise IndexError('index (%d) out of range' % max_indx)
|
| 221 |
+
|
| 222 |
+
min_indx = x.min()
|
| 223 |
+
if min_indx < 0:
|
| 224 |
+
if min_indx < -length:
|
| 225 |
+
raise IndexError('index (%d) out of range' % min_indx)
|
| 226 |
+
if x is idx or not x.flags.owndata:
|
| 227 |
+
x = x.copy()
|
| 228 |
+
x[x < 0] += length
|
| 229 |
+
return x
|
| 230 |
+
|
| 231 |
+
def _getrow(self, i):
|
| 232 |
+
"""Return a copy of row i of the matrix, as a (1 x n) row vector.
|
| 233 |
+
"""
|
| 234 |
+
M, N = self.shape
|
| 235 |
+
i = int(i)
|
| 236 |
+
if i < -M or i >= M:
|
| 237 |
+
raise IndexError('index (%d) out of range' % i)
|
| 238 |
+
if i < 0:
|
| 239 |
+
i += M
|
| 240 |
+
return self._get_intXslice(i, slice(None))
|
| 241 |
+
|
| 242 |
+
def _getcol(self, i):
|
| 243 |
+
"""Return a copy of column i of the matrix, as a (m x 1) column vector.
|
| 244 |
+
"""
|
| 245 |
+
M, N = self.shape
|
| 246 |
+
i = int(i)
|
| 247 |
+
if i < -N or i >= N:
|
| 248 |
+
raise IndexError('index (%d) out of range' % i)
|
| 249 |
+
if i < 0:
|
| 250 |
+
i += N
|
| 251 |
+
return self._get_sliceXint(slice(None), i)
|
| 252 |
+
|
| 253 |
+
def _get_intXint(self, row, col):
|
| 254 |
+
raise NotImplementedError()
|
| 255 |
+
|
| 256 |
+
def _get_intXarray(self, row, col):
|
| 257 |
+
raise NotImplementedError()
|
| 258 |
+
|
| 259 |
+
def _get_intXslice(self, row, col):
|
| 260 |
+
raise NotImplementedError()
|
| 261 |
+
|
| 262 |
+
def _get_sliceXint(self, row, col):
|
| 263 |
+
raise NotImplementedError()
|
| 264 |
+
|
| 265 |
+
def _get_sliceXslice(self, row, col):
|
| 266 |
+
raise NotImplementedError()
|
| 267 |
+
|
| 268 |
+
def _get_sliceXarray(self, row, col):
|
| 269 |
+
raise NotImplementedError()
|
| 270 |
+
|
| 271 |
+
def _get_arrayXint(self, row, col):
|
| 272 |
+
raise NotImplementedError()
|
| 273 |
+
|
| 274 |
+
def _get_arrayXslice(self, row, col):
|
| 275 |
+
raise NotImplementedError()
|
| 276 |
+
|
| 277 |
+
def _get_columnXarray(self, row, col):
|
| 278 |
+
raise NotImplementedError()
|
| 279 |
+
|
| 280 |
+
def _get_arrayXarray(self, row, col):
|
| 281 |
+
raise NotImplementedError()
|
| 282 |
+
|
| 283 |
+
def _set_intXint(self, row, col, x):
|
| 284 |
+
raise NotImplementedError()
|
| 285 |
+
|
| 286 |
+
def _set_arrayXarray(self, row, col, x):
|
| 287 |
+
raise NotImplementedError()
|
| 288 |
+
|
| 289 |
+
def _set_arrayXarray_sparse(self, row, col, x):
|
| 290 |
+
# Fall back to densifying x
|
| 291 |
+
x = np.asarray(x.toarray(), dtype=self.dtype)
|
| 292 |
+
x, _ = _broadcast_arrays(x, row)
|
| 293 |
+
self._set_arrayXarray(row, col, x)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _unpack_index(index) -> tuple[
|
| 297 |
+
int | slice | npt.NDArray[np.bool_ | np.int_],
|
| 298 |
+
int | slice | npt.NDArray[np.bool_ | np.int_]
|
| 299 |
+
]:
|
| 300 |
+
""" Parse index. Always return a tuple of the form (row, col).
|
| 301 |
+
Valid type for row/col is integer, slice, array of bool, or array of integers.
|
| 302 |
+
"""
|
| 303 |
+
# Parse any ellipses.
|
| 304 |
+
index = _check_ellipsis(index)
|
| 305 |
+
|
| 306 |
+
# Next, parse the tuple or object
|
| 307 |
+
if isinstance(index, tuple):
|
| 308 |
+
if len(index) == 2:
|
| 309 |
+
row, col = index
|
| 310 |
+
elif len(index) == 1:
|
| 311 |
+
row, col = index[0], slice(None)
|
| 312 |
+
else:
|
| 313 |
+
raise IndexError('invalid number of indices')
|
| 314 |
+
else:
|
| 315 |
+
idx = _compatible_boolean_index(index)
|
| 316 |
+
if idx is None:
|
| 317 |
+
row, col = index, slice(None)
|
| 318 |
+
elif idx.ndim < 2:
|
| 319 |
+
return idx, slice(None)
|
| 320 |
+
elif idx.ndim == 2:
|
| 321 |
+
return idx.nonzero()
|
| 322 |
+
# Next, check for validity and transform the index as needed.
|
| 323 |
+
from ._base import issparse
|
| 324 |
+
if issparse(row) or issparse(col):
|
| 325 |
+
# Supporting sparse boolean indexing with both row and col does
|
| 326 |
+
# not work because spmatrix.ndim is always 2.
|
| 327 |
+
raise IndexError(
|
| 328 |
+
'Indexing with sparse matrices is not supported '
|
| 329 |
+
'except boolean indexing where matrix and index '
|
| 330 |
+
'are equal shapes.')
|
| 331 |
+
return row, col
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def _check_ellipsis(index):
|
| 335 |
+
"""Process indices with Ellipsis. Returns modified index."""
|
| 336 |
+
if index is Ellipsis:
|
| 337 |
+
return (slice(None), slice(None))
|
| 338 |
+
|
| 339 |
+
if not isinstance(index, tuple):
|
| 340 |
+
return index
|
| 341 |
+
|
| 342 |
+
# Find any Ellipsis objects.
|
| 343 |
+
ellipsis_indices = [i for i, v in enumerate(index) if v is Ellipsis]
|
| 344 |
+
if not ellipsis_indices:
|
| 345 |
+
return index
|
| 346 |
+
if len(ellipsis_indices) > 1:
|
| 347 |
+
raise IndexError("an index can only have a single ellipsis ('...')")
|
| 348 |
+
|
| 349 |
+
# Replace the Ellipsis object with 0, 1, or 2 null-slices as needed.
|
| 350 |
+
i, = ellipsis_indices
|
| 351 |
+
num_slices = max(0, 3 - len(index))
|
| 352 |
+
return index[:i] + (slice(None),) * num_slices + index[i + 1:]
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _maybe_bool_ndarray(idx):
|
| 356 |
+
"""Returns a compatible array if elements are boolean.
|
| 357 |
+
"""
|
| 358 |
+
idx = np.asanyarray(idx)
|
| 359 |
+
if idx.dtype.kind == 'b':
|
| 360 |
+
return idx
|
| 361 |
+
return None
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _first_element_bool(idx, max_dim=2):
|
| 365 |
+
"""Returns True if first element of the incompatible
|
| 366 |
+
array type is boolean.
|
| 367 |
+
"""
|
| 368 |
+
if max_dim < 1:
|
| 369 |
+
return None
|
| 370 |
+
try:
|
| 371 |
+
first = next(iter(idx), None)
|
| 372 |
+
except TypeError:
|
| 373 |
+
return None
|
| 374 |
+
if isinstance(first, bool):
|
| 375 |
+
return True
|
| 376 |
+
return _first_element_bool(first, max_dim-1)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _compatible_boolean_index(idx):
|
| 380 |
+
"""Returns a boolean index array that can be converted to
|
| 381 |
+
integer array. Returns None if no such array exists.
|
| 382 |
+
"""
|
| 383 |
+
# Presence of attribute `ndim` indicates a compatible array type.
|
| 384 |
+
if hasattr(idx, 'ndim') or _first_element_bool(idx):
|
| 385 |
+
return _maybe_bool_ndarray(idx)
|
| 386 |
+
return None
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def _boolean_index_to_array(idx):
|
| 390 |
+
if idx.ndim > 1:
|
| 391 |
+
raise IndexError('invalid index shape')
|
| 392 |
+
return np.where(idx)[0]
|
parrot/lib/python3.10/site-packages/scipy/sparse/_lil.py
ADDED
|
@@ -0,0 +1,612 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""List of Lists sparse matrix class
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
__docformat__ = "restructuredtext en"
|
| 5 |
+
|
| 6 |
+
__all__ = ['lil_array', 'lil_matrix', 'isspmatrix_lil']
|
| 7 |
+
|
| 8 |
+
from bisect import bisect_left
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
from ._matrix import spmatrix
|
| 13 |
+
from ._base import _spbase, sparray, issparse
|
| 14 |
+
from ._index import IndexMixin, INT_TYPES, _broadcast_arrays
|
| 15 |
+
from ._sputils import (getdtype, isshape, isscalarlike, upcast_scalar,
|
| 16 |
+
check_shape, check_reshape_kwargs)
|
| 17 |
+
from . import _csparsetools
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class _lil_base(_spbase, IndexMixin):
|
| 21 |
+
_format = 'lil'
|
| 22 |
+
|
| 23 |
+
def __init__(self, arg1, shape=None, dtype=None, copy=False):
|
| 24 |
+
_spbase.__init__(self, arg1)
|
| 25 |
+
self.dtype = getdtype(dtype, arg1, default=float)
|
| 26 |
+
|
| 27 |
+
# First get the shape
|
| 28 |
+
if issparse(arg1):
|
| 29 |
+
if arg1.format == "lil" and copy:
|
| 30 |
+
A = arg1.copy()
|
| 31 |
+
else:
|
| 32 |
+
A = arg1.tolil()
|
| 33 |
+
|
| 34 |
+
if dtype is not None:
|
| 35 |
+
A = A.astype(dtype, copy=False)
|
| 36 |
+
|
| 37 |
+
self._shape = check_shape(A.shape)
|
| 38 |
+
self.dtype = A.dtype
|
| 39 |
+
self.rows = A.rows
|
| 40 |
+
self.data = A.data
|
| 41 |
+
elif isinstance(arg1,tuple):
|
| 42 |
+
if isshape(arg1):
|
| 43 |
+
if shape is not None:
|
| 44 |
+
raise ValueError('invalid use of shape parameter')
|
| 45 |
+
M, N = arg1
|
| 46 |
+
self._shape = check_shape((M, N))
|
| 47 |
+
self.rows = np.empty((M,), dtype=object)
|
| 48 |
+
self.data = np.empty((M,), dtype=object)
|
| 49 |
+
for i in range(M):
|
| 50 |
+
self.rows[i] = []
|
| 51 |
+
self.data[i] = []
|
| 52 |
+
else:
|
| 53 |
+
raise TypeError('unrecognized lil_array constructor usage')
|
| 54 |
+
else:
|
| 55 |
+
# assume A is dense
|
| 56 |
+
try:
|
| 57 |
+
A = self._ascontainer(arg1)
|
| 58 |
+
except TypeError as e:
|
| 59 |
+
raise TypeError('unsupported matrix type') from e
|
| 60 |
+
if isinstance(self, sparray) and A.ndim != 2:
|
| 61 |
+
raise ValueError(f"LIL arrays don't support {A.ndim}D input. Use 2D")
|
| 62 |
+
A = self._csr_container(A, dtype=dtype).tolil()
|
| 63 |
+
|
| 64 |
+
self._shape = check_shape(A.shape)
|
| 65 |
+
self.dtype = A.dtype
|
| 66 |
+
self.rows = A.rows
|
| 67 |
+
self.data = A.data
|
| 68 |
+
|
| 69 |
+
def __iadd__(self,other):
|
| 70 |
+
self[:,:] = self + other
|
| 71 |
+
return self
|
| 72 |
+
|
| 73 |
+
def __isub__(self,other):
|
| 74 |
+
self[:,:] = self - other
|
| 75 |
+
return self
|
| 76 |
+
|
| 77 |
+
def __imul__(self,other):
|
| 78 |
+
if isscalarlike(other):
|
| 79 |
+
self[:,:] = self * other
|
| 80 |
+
return self
|
| 81 |
+
else:
|
| 82 |
+
return NotImplemented
|
| 83 |
+
|
| 84 |
+
def __itruediv__(self,other):
|
| 85 |
+
if isscalarlike(other):
|
| 86 |
+
self[:,:] = self / other
|
| 87 |
+
return self
|
| 88 |
+
else:
|
| 89 |
+
return NotImplemented
|
| 90 |
+
|
| 91 |
+
# Whenever the dimensions change, empty lists should be created for each
|
| 92 |
+
# row
|
| 93 |
+
|
| 94 |
+
def _getnnz(self, axis=None):
|
| 95 |
+
if axis is None:
|
| 96 |
+
return sum([len(rowvals) for rowvals in self.data])
|
| 97 |
+
if axis < 0:
|
| 98 |
+
axis += 2
|
| 99 |
+
if axis == 0:
|
| 100 |
+
out = np.zeros(self.shape[1], dtype=np.intp)
|
| 101 |
+
for row in self.rows:
|
| 102 |
+
out[row] += 1
|
| 103 |
+
return out
|
| 104 |
+
elif axis == 1:
|
| 105 |
+
return np.array([len(rowvals) for rowvals in self.data], dtype=np.intp)
|
| 106 |
+
else:
|
| 107 |
+
raise ValueError('axis out of bounds')
|
| 108 |
+
|
| 109 |
+
def count_nonzero(self):
|
| 110 |
+
return sum(np.count_nonzero(rowvals) for rowvals in self.data)
|
| 111 |
+
|
| 112 |
+
_getnnz.__doc__ = _spbase._getnnz.__doc__
|
| 113 |
+
count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
|
| 114 |
+
|
| 115 |
+
def getrowview(self, i):
|
| 116 |
+
"""Returns a view of the 'i'th row (without copying).
|
| 117 |
+
"""
|
| 118 |
+
new = self._lil_container((1, self.shape[1]), dtype=self.dtype)
|
| 119 |
+
new.rows[0] = self.rows[i]
|
| 120 |
+
new.data[0] = self.data[i]
|
| 121 |
+
return new
|
| 122 |
+
|
| 123 |
+
def getrow(self, i):
|
| 124 |
+
"""Returns a copy of the 'i'th row.
|
| 125 |
+
"""
|
| 126 |
+
M, N = self.shape
|
| 127 |
+
if i < 0:
|
| 128 |
+
i += M
|
| 129 |
+
if i < 0 or i >= M:
|
| 130 |
+
raise IndexError('row index out of bounds')
|
| 131 |
+
new = self._lil_container((1, N), dtype=self.dtype)
|
| 132 |
+
new.rows[0] = self.rows[i][:]
|
| 133 |
+
new.data[0] = self.data[i][:]
|
| 134 |
+
return new
|
| 135 |
+
|
| 136 |
+
def __getitem__(self, key):
|
| 137 |
+
# Fast path for simple (int, int) indexing.
|
| 138 |
+
if (isinstance(key, tuple) and len(key) == 2 and
|
| 139 |
+
isinstance(key[0], INT_TYPES) and
|
| 140 |
+
isinstance(key[1], INT_TYPES)):
|
| 141 |
+
# lil_get1 handles validation for us.
|
| 142 |
+
return self._get_intXint(*key)
|
| 143 |
+
# Everything else takes the normal path.
|
| 144 |
+
return IndexMixin.__getitem__(self, key)
|
| 145 |
+
|
| 146 |
+
def _asindices(self, idx, N):
|
| 147 |
+
# LIL routines handle bounds-checking for us, so don't do it here.
|
| 148 |
+
try:
|
| 149 |
+
x = np.asarray(idx)
|
| 150 |
+
except (ValueError, TypeError, MemoryError) as e:
|
| 151 |
+
raise IndexError('invalid index') from e
|
| 152 |
+
if x.ndim not in (1, 2):
|
| 153 |
+
raise IndexError('Index dimension must be <= 2')
|
| 154 |
+
return x
|
| 155 |
+
|
| 156 |
+
def _get_intXint(self, row, col):
|
| 157 |
+
v = _csparsetools.lil_get1(self.shape[0], self.shape[1], self.rows,
|
| 158 |
+
self.data, row, col)
|
| 159 |
+
return self.dtype.type(v)
|
| 160 |
+
|
| 161 |
+
def _get_sliceXint(self, row, col):
|
| 162 |
+
row = range(*row.indices(self.shape[0]))
|
| 163 |
+
return self._get_row_ranges(row, slice(col, col+1))
|
| 164 |
+
|
| 165 |
+
def _get_arrayXint(self, row, col):
|
| 166 |
+
row = row.squeeze()
|
| 167 |
+
return self._get_row_ranges(row, slice(col, col+1))
|
| 168 |
+
|
| 169 |
+
def _get_intXslice(self, row, col):
|
| 170 |
+
return self._get_row_ranges((row,), col)
|
| 171 |
+
|
| 172 |
+
def _get_sliceXslice(self, row, col):
|
| 173 |
+
row = range(*row.indices(self.shape[0]))
|
| 174 |
+
return self._get_row_ranges(row, col)
|
| 175 |
+
|
| 176 |
+
def _get_arrayXslice(self, row, col):
|
| 177 |
+
return self._get_row_ranges(row, col)
|
| 178 |
+
|
| 179 |
+
def _get_intXarray(self, row, col):
|
| 180 |
+
row = np.array(row, dtype=col.dtype, ndmin=1)
|
| 181 |
+
return self._get_columnXarray(row, col)
|
| 182 |
+
|
| 183 |
+
def _get_sliceXarray(self, row, col):
|
| 184 |
+
row = np.arange(*row.indices(self.shape[0]))
|
| 185 |
+
return self._get_columnXarray(row, col)
|
| 186 |
+
|
| 187 |
+
def _get_columnXarray(self, row, col):
|
| 188 |
+
# outer indexing
|
| 189 |
+
row, col = _broadcast_arrays(row[:,None], col)
|
| 190 |
+
return self._get_arrayXarray(row, col)
|
| 191 |
+
|
| 192 |
+
def _get_arrayXarray(self, row, col):
|
| 193 |
+
# inner indexing
|
| 194 |
+
i, j = map(np.atleast_2d, _prepare_index_for_memoryview(row, col))
|
| 195 |
+
new = self._lil_container(i.shape, dtype=self.dtype)
|
| 196 |
+
_csparsetools.lil_fancy_get(self.shape[0], self.shape[1],
|
| 197 |
+
self.rows, self.data,
|
| 198 |
+
new.rows, new.data,
|
| 199 |
+
i, j)
|
| 200 |
+
return new
|
| 201 |
+
|
| 202 |
+
def _get_row_ranges(self, rows, col_slice):
|
| 203 |
+
"""
|
| 204 |
+
Fast path for indexing in the case where column index is slice.
|
| 205 |
+
|
| 206 |
+
This gains performance improvement over brute force by more
|
| 207 |
+
efficient skipping of zeros, by accessing the elements
|
| 208 |
+
column-wise in order.
|
| 209 |
+
|
| 210 |
+
Parameters
|
| 211 |
+
----------
|
| 212 |
+
rows : sequence or range
|
| 213 |
+
Rows indexed. If range, must be within valid bounds.
|
| 214 |
+
col_slice : slice
|
| 215 |
+
Columns indexed
|
| 216 |
+
|
| 217 |
+
"""
|
| 218 |
+
j_start, j_stop, j_stride = col_slice.indices(self.shape[1])
|
| 219 |
+
col_range = range(j_start, j_stop, j_stride)
|
| 220 |
+
nj = len(col_range)
|
| 221 |
+
new = self._lil_container((len(rows), nj), dtype=self.dtype)
|
| 222 |
+
|
| 223 |
+
_csparsetools.lil_get_row_ranges(self.shape[0], self.shape[1],
|
| 224 |
+
self.rows, self.data,
|
| 225 |
+
new.rows, new.data,
|
| 226 |
+
rows,
|
| 227 |
+
j_start, j_stop, j_stride, nj)
|
| 228 |
+
|
| 229 |
+
return new
|
| 230 |
+
|
| 231 |
+
def _set_intXint(self, row, col, x):
|
| 232 |
+
_csparsetools.lil_insert(self.shape[0], self.shape[1], self.rows,
|
| 233 |
+
self.data, row, col, x)
|
| 234 |
+
|
| 235 |
+
def _set_arrayXarray(self, row, col, x):
|
| 236 |
+
i, j, x = map(np.atleast_2d, _prepare_index_for_memoryview(row, col, x))
|
| 237 |
+
_csparsetools.lil_fancy_set(self.shape[0], self.shape[1],
|
| 238 |
+
self.rows, self.data,
|
| 239 |
+
i, j, x)
|
| 240 |
+
|
| 241 |
+
def _set_arrayXarray_sparse(self, row, col, x):
|
| 242 |
+
# Fall back to densifying x
|
| 243 |
+
x = np.asarray(x.toarray(), dtype=self.dtype)
|
| 244 |
+
x, _ = _broadcast_arrays(x, row)
|
| 245 |
+
self._set_arrayXarray(row, col, x)
|
| 246 |
+
|
| 247 |
+
def __setitem__(self, key, x):
|
| 248 |
+
if isinstance(key, tuple) and len(key) == 2:
|
| 249 |
+
row, col = key
|
| 250 |
+
# Fast path for simple (int, int) indexing.
|
| 251 |
+
if isinstance(row, INT_TYPES) and isinstance(col, INT_TYPES):
|
| 252 |
+
x = self.dtype.type(x)
|
| 253 |
+
if x.size > 1:
|
| 254 |
+
raise ValueError("Trying to assign a sequence to an item")
|
| 255 |
+
return self._set_intXint(row, col, x)
|
| 256 |
+
# Fast path for full-matrix sparse assignment.
|
| 257 |
+
if (isinstance(row, slice) and isinstance(col, slice) and
|
| 258 |
+
row == slice(None) and col == slice(None) and
|
| 259 |
+
issparse(x) and x.shape == self.shape):
|
| 260 |
+
x = self._lil_container(x, dtype=self.dtype)
|
| 261 |
+
self.rows = x.rows
|
| 262 |
+
self.data = x.data
|
| 263 |
+
return
|
| 264 |
+
# Everything else takes the normal path.
|
| 265 |
+
IndexMixin.__setitem__(self, key, x)
|
| 266 |
+
|
| 267 |
+
def _mul_scalar(self, other):
|
| 268 |
+
if other == 0:
|
| 269 |
+
# Multiply by zero: return the zero matrix
|
| 270 |
+
new = self._lil_container(self.shape, dtype=self.dtype)
|
| 271 |
+
else:
|
| 272 |
+
res_dtype = upcast_scalar(self.dtype, other)
|
| 273 |
+
|
| 274 |
+
new = self.copy()
|
| 275 |
+
new = new.astype(res_dtype)
|
| 276 |
+
# Multiply this scalar by every element.
|
| 277 |
+
for j, rowvals in enumerate(new.data):
|
| 278 |
+
new.data[j] = [val*other for val in rowvals]
|
| 279 |
+
return new
|
| 280 |
+
|
| 281 |
+
def __truediv__(self, other): # self / other
|
| 282 |
+
if isscalarlike(other):
|
| 283 |
+
new = self.copy()
|
| 284 |
+
new.dtype = np.result_type(self, other)
|
| 285 |
+
# Divide every element by this scalar
|
| 286 |
+
for j, rowvals in enumerate(new.data):
|
| 287 |
+
new.data[j] = [val/other for val in rowvals]
|
| 288 |
+
return new
|
| 289 |
+
else:
|
| 290 |
+
return self.tocsr() / other
|
| 291 |
+
|
| 292 |
+
def copy(self):
|
| 293 |
+
M, N = self.shape
|
| 294 |
+
new = self._lil_container(self.shape, dtype=self.dtype)
|
| 295 |
+
# This is ~14x faster than calling deepcopy() on rows and data.
|
| 296 |
+
_csparsetools.lil_get_row_ranges(M, N, self.rows, self.data,
|
| 297 |
+
new.rows, new.data, range(M),
|
| 298 |
+
0, N, 1, N)
|
| 299 |
+
return new
|
| 300 |
+
|
| 301 |
+
copy.__doc__ = _spbase.copy.__doc__
|
| 302 |
+
|
| 303 |
+
def reshape(self, *args, **kwargs):
|
| 304 |
+
shape = check_shape(args, self.shape)
|
| 305 |
+
order, copy = check_reshape_kwargs(kwargs)
|
| 306 |
+
|
| 307 |
+
# Return early if reshape is not required
|
| 308 |
+
if shape == self.shape:
|
| 309 |
+
if copy:
|
| 310 |
+
return self.copy()
|
| 311 |
+
else:
|
| 312 |
+
return self
|
| 313 |
+
|
| 314 |
+
new = self._lil_container(shape, dtype=self.dtype)
|
| 315 |
+
|
| 316 |
+
if order == 'C':
|
| 317 |
+
ncols = self.shape[1]
|
| 318 |
+
for i, row in enumerate(self.rows):
|
| 319 |
+
for col, j in enumerate(row):
|
| 320 |
+
new_r, new_c = np.unravel_index(i * ncols + j, shape)
|
| 321 |
+
new[new_r, new_c] = self[i, j]
|
| 322 |
+
elif order == 'F':
|
| 323 |
+
nrows = self.shape[0]
|
| 324 |
+
for i, row in enumerate(self.rows):
|
| 325 |
+
for col, j in enumerate(row):
|
| 326 |
+
new_r, new_c = np.unravel_index(i + j * nrows, shape, order)
|
| 327 |
+
new[new_r, new_c] = self[i, j]
|
| 328 |
+
else:
|
| 329 |
+
raise ValueError("'order' must be 'C' or 'F'")
|
| 330 |
+
|
| 331 |
+
return new
|
| 332 |
+
|
| 333 |
+
reshape.__doc__ = _spbase.reshape.__doc__
|
| 334 |
+
|
| 335 |
+
def resize(self, *shape):
|
| 336 |
+
shape = check_shape(shape)
|
| 337 |
+
new_M, new_N = shape
|
| 338 |
+
M, N = self.shape
|
| 339 |
+
|
| 340 |
+
if new_M < M:
|
| 341 |
+
self.rows = self.rows[:new_M]
|
| 342 |
+
self.data = self.data[:new_M]
|
| 343 |
+
elif new_M > M:
|
| 344 |
+
self.rows = np.resize(self.rows, new_M)
|
| 345 |
+
self.data = np.resize(self.data, new_M)
|
| 346 |
+
for i in range(M, new_M):
|
| 347 |
+
self.rows[i] = []
|
| 348 |
+
self.data[i] = []
|
| 349 |
+
|
| 350 |
+
if new_N < N:
|
| 351 |
+
for row, data in zip(self.rows, self.data):
|
| 352 |
+
trunc = bisect_left(row, new_N)
|
| 353 |
+
del row[trunc:]
|
| 354 |
+
del data[trunc:]
|
| 355 |
+
|
| 356 |
+
self._shape = shape
|
| 357 |
+
|
| 358 |
+
resize.__doc__ = _spbase.resize.__doc__
|
| 359 |
+
|
| 360 |
+
def toarray(self, order=None, out=None):
|
| 361 |
+
d = self._process_toarray_args(order, out)
|
| 362 |
+
for i, row in enumerate(self.rows):
|
| 363 |
+
for pos, j in enumerate(row):
|
| 364 |
+
d[i, j] = self.data[i][pos]
|
| 365 |
+
return d
|
| 366 |
+
|
| 367 |
+
toarray.__doc__ = _spbase.toarray.__doc__
|
| 368 |
+
|
| 369 |
+
def transpose(self, axes=None, copy=False):
|
| 370 |
+
return self.tocsr(copy=copy).transpose(axes=axes, copy=False).tolil(copy=False)
|
| 371 |
+
|
| 372 |
+
transpose.__doc__ = _spbase.transpose.__doc__
|
| 373 |
+
|
| 374 |
+
def tolil(self, copy=False):
|
| 375 |
+
if copy:
|
| 376 |
+
return self.copy()
|
| 377 |
+
else:
|
| 378 |
+
return self
|
| 379 |
+
|
| 380 |
+
tolil.__doc__ = _spbase.tolil.__doc__
|
| 381 |
+
|
| 382 |
+
def tocsr(self, copy=False):
|
| 383 |
+
M, N = self.shape
|
| 384 |
+
if M == 0 or N == 0:
|
| 385 |
+
return self._csr_container((M, N), dtype=self.dtype)
|
| 386 |
+
|
| 387 |
+
# construct indptr array
|
| 388 |
+
if M*N <= np.iinfo(np.int32).max:
|
| 389 |
+
# fast path: it is known that 64-bit indexing will not be needed.
|
| 390 |
+
idx_dtype = np.int32
|
| 391 |
+
indptr = np.empty(M + 1, dtype=idx_dtype)
|
| 392 |
+
indptr[0] = 0
|
| 393 |
+
_csparsetools.lil_get_lengths(self.rows, indptr[1:])
|
| 394 |
+
np.cumsum(indptr, out=indptr)
|
| 395 |
+
nnz = indptr[-1]
|
| 396 |
+
else:
|
| 397 |
+
idx_dtype = self._get_index_dtype(maxval=N)
|
| 398 |
+
lengths = np.empty(M, dtype=idx_dtype)
|
| 399 |
+
_csparsetools.lil_get_lengths(self.rows, lengths)
|
| 400 |
+
nnz = lengths.sum(dtype=np.int64)
|
| 401 |
+
idx_dtype = self._get_index_dtype(maxval=max(N, nnz))
|
| 402 |
+
indptr = np.empty(M + 1, dtype=idx_dtype)
|
| 403 |
+
indptr[0] = 0
|
| 404 |
+
np.cumsum(lengths, dtype=idx_dtype, out=indptr[1:])
|
| 405 |
+
|
| 406 |
+
indices = np.empty(nnz, dtype=idx_dtype)
|
| 407 |
+
data = np.empty(nnz, dtype=self.dtype)
|
| 408 |
+
_csparsetools.lil_flatten_to_array(self.rows, indices)
|
| 409 |
+
_csparsetools.lil_flatten_to_array(self.data, data)
|
| 410 |
+
|
| 411 |
+
# init csr matrix
|
| 412 |
+
return self._csr_container((data, indices, indptr), shape=self.shape)
|
| 413 |
+
|
| 414 |
+
tocsr.__doc__ = _spbase.tocsr.__doc__
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def _prepare_index_for_memoryview(i, j, x=None):
|
| 418 |
+
"""
|
| 419 |
+
Convert index and data arrays to form suitable for passing to the
|
| 420 |
+
Cython fancy getset routines.
|
| 421 |
+
|
| 422 |
+
The conversions are necessary since to (i) ensure the integer
|
| 423 |
+
index arrays are in one of the accepted types, and (ii) to ensure
|
| 424 |
+
the arrays are writable so that Cython memoryview support doesn't
|
| 425 |
+
choke on them.
|
| 426 |
+
|
| 427 |
+
Parameters
|
| 428 |
+
----------
|
| 429 |
+
i, j
|
| 430 |
+
Index arrays
|
| 431 |
+
x : optional
|
| 432 |
+
Data arrays
|
| 433 |
+
|
| 434 |
+
Returns
|
| 435 |
+
-------
|
| 436 |
+
i, j, x
|
| 437 |
+
Re-formatted arrays (x is omitted, if input was None)
|
| 438 |
+
|
| 439 |
+
"""
|
| 440 |
+
if i.dtype > j.dtype:
|
| 441 |
+
j = j.astype(i.dtype)
|
| 442 |
+
elif i.dtype < j.dtype:
|
| 443 |
+
i = i.astype(j.dtype)
|
| 444 |
+
|
| 445 |
+
if not i.flags.writeable or i.dtype not in (np.int32, np.int64):
|
| 446 |
+
i = i.astype(np.intp)
|
| 447 |
+
if not j.flags.writeable or j.dtype not in (np.int32, np.int64):
|
| 448 |
+
j = j.astype(np.intp)
|
| 449 |
+
|
| 450 |
+
if x is not None:
|
| 451 |
+
if not x.flags.writeable:
|
| 452 |
+
x = x.copy()
|
| 453 |
+
return i, j, x
|
| 454 |
+
else:
|
| 455 |
+
return i, j
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def isspmatrix_lil(x):
|
| 459 |
+
"""Is `x` of lil_matrix type?
|
| 460 |
+
|
| 461 |
+
Parameters
|
| 462 |
+
----------
|
| 463 |
+
x
|
| 464 |
+
object to check for being a lil matrix
|
| 465 |
+
|
| 466 |
+
Returns
|
| 467 |
+
-------
|
| 468 |
+
bool
|
| 469 |
+
True if `x` is a lil matrix, False otherwise
|
| 470 |
+
|
| 471 |
+
Examples
|
| 472 |
+
--------
|
| 473 |
+
>>> from scipy.sparse import lil_array, lil_matrix, coo_matrix, isspmatrix_lil
|
| 474 |
+
>>> isspmatrix_lil(lil_matrix([[5]]))
|
| 475 |
+
True
|
| 476 |
+
>>> isspmatrix_lil(lil_array([[5]]))
|
| 477 |
+
False
|
| 478 |
+
>>> isspmatrix_lil(coo_matrix([[5]]))
|
| 479 |
+
False
|
| 480 |
+
"""
|
| 481 |
+
return isinstance(x, lil_matrix)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
# This namespace class separates array from matrix with isinstance
|
| 485 |
+
class lil_array(_lil_base, sparray):
|
| 486 |
+
"""
|
| 487 |
+
Row-based LIst of Lists sparse array.
|
| 488 |
+
|
| 489 |
+
This is a structure for constructing sparse arrays incrementally.
|
| 490 |
+
Note that inserting a single item can take linear time in the worst case;
|
| 491 |
+
to construct the array efficiently, make sure the items are pre-sorted by
|
| 492 |
+
index, per row.
|
| 493 |
+
|
| 494 |
+
This can be instantiated in several ways:
|
| 495 |
+
lil_array(D)
|
| 496 |
+
where D is a 2-D ndarray
|
| 497 |
+
|
| 498 |
+
lil_array(S)
|
| 499 |
+
with another sparse array or matrix S (equivalent to S.tolil())
|
| 500 |
+
|
| 501 |
+
lil_array((M, N), [dtype])
|
| 502 |
+
to construct an empty array with shape (M, N)
|
| 503 |
+
dtype is optional, defaulting to dtype='d'.
|
| 504 |
+
|
| 505 |
+
Attributes
|
| 506 |
+
----------
|
| 507 |
+
dtype : dtype
|
| 508 |
+
Data type of the array
|
| 509 |
+
shape : 2-tuple
|
| 510 |
+
Shape of the array
|
| 511 |
+
ndim : int
|
| 512 |
+
Number of dimensions (this is always 2)
|
| 513 |
+
nnz
|
| 514 |
+
size
|
| 515 |
+
data
|
| 516 |
+
LIL format data array of the array
|
| 517 |
+
rows
|
| 518 |
+
LIL format row index array of the array
|
| 519 |
+
T
|
| 520 |
+
|
| 521 |
+
Notes
|
| 522 |
+
-----
|
| 523 |
+
Sparse arrays can be used in arithmetic operations: they support
|
| 524 |
+
addition, subtraction, multiplication, division, and matrix power.
|
| 525 |
+
|
| 526 |
+
Advantages of the LIL format
|
| 527 |
+
- supports flexible slicing
|
| 528 |
+
- changes to the array sparsity structure are efficient
|
| 529 |
+
|
| 530 |
+
Disadvantages of the LIL format
|
| 531 |
+
- arithmetic operations LIL + LIL are slow (consider CSR or CSC)
|
| 532 |
+
- slow column slicing (consider CSC)
|
| 533 |
+
- slow matrix vector products (consider CSR or CSC)
|
| 534 |
+
|
| 535 |
+
Intended Usage
|
| 536 |
+
- LIL is a convenient format for constructing sparse arrays
|
| 537 |
+
- once an array has been constructed, convert to CSR or
|
| 538 |
+
CSC format for fast arithmetic and matrix vector operations
|
| 539 |
+
- consider using the COO format when constructing large arrays
|
| 540 |
+
|
| 541 |
+
Data Structure
|
| 542 |
+
- An array (``self.rows``) of rows, each of which is a sorted
|
| 543 |
+
list of column indices of non-zero elements.
|
| 544 |
+
- The corresponding nonzero values are stored in similar
|
| 545 |
+
fashion in ``self.data``.
|
| 546 |
+
|
| 547 |
+
"""
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
class lil_matrix(spmatrix, _lil_base):
|
| 551 |
+
"""
|
| 552 |
+
Row-based LIst of Lists sparse matrix.
|
| 553 |
+
|
| 554 |
+
This is a structure for constructing sparse matrices incrementally.
|
| 555 |
+
Note that inserting a single item can take linear time in the worst case;
|
| 556 |
+
to construct the matrix efficiently, make sure the items are pre-sorted by
|
| 557 |
+
index, per row.
|
| 558 |
+
|
| 559 |
+
This can be instantiated in several ways:
|
| 560 |
+
lil_matrix(D)
|
| 561 |
+
where D is a 2-D ndarray
|
| 562 |
+
|
| 563 |
+
lil_matrix(S)
|
| 564 |
+
with another sparse array or matrix S (equivalent to S.tolil())
|
| 565 |
+
|
| 566 |
+
lil_matrix((M, N), [dtype])
|
| 567 |
+
to construct an empty matrix with shape (M, N)
|
| 568 |
+
dtype is optional, defaulting to dtype='d'.
|
| 569 |
+
|
| 570 |
+
Attributes
|
| 571 |
+
----------
|
| 572 |
+
dtype : dtype
|
| 573 |
+
Data type of the matrix
|
| 574 |
+
shape : 2-tuple
|
| 575 |
+
Shape of the matrix
|
| 576 |
+
ndim : int
|
| 577 |
+
Number of dimensions (this is always 2)
|
| 578 |
+
nnz
|
| 579 |
+
size
|
| 580 |
+
data
|
| 581 |
+
LIL format data array of the matrix
|
| 582 |
+
rows
|
| 583 |
+
LIL format row index array of the matrix
|
| 584 |
+
T
|
| 585 |
+
|
| 586 |
+
Notes
|
| 587 |
+
-----
|
| 588 |
+
Sparse matrices can be used in arithmetic operations: they support
|
| 589 |
+
addition, subtraction, multiplication, division, and matrix power.
|
| 590 |
+
|
| 591 |
+
Advantages of the LIL format
|
| 592 |
+
- supports flexible slicing
|
| 593 |
+
- changes to the matrix sparsity structure are efficient
|
| 594 |
+
|
| 595 |
+
Disadvantages of the LIL format
|
| 596 |
+
- arithmetic operations LIL + LIL are slow (consider CSR or CSC)
|
| 597 |
+
- slow column slicing (consider CSC)
|
| 598 |
+
- slow matrix vector products (consider CSR or CSC)
|
| 599 |
+
|
| 600 |
+
Intended Usage
|
| 601 |
+
- LIL is a convenient format for constructing sparse matrices
|
| 602 |
+
- once a matrix has been constructed, convert to CSR or
|
| 603 |
+
CSC format for fast arithmetic and matrix vector operations
|
| 604 |
+
- consider using the COO format when constructing large matrices
|
| 605 |
+
|
| 606 |
+
Data Structure
|
| 607 |
+
- An array (``self.rows``) of rows, each of which is a sorted
|
| 608 |
+
list of column indices of non-zero elements.
|
| 609 |
+
- The corresponding nonzero values are stored in similar
|
| 610 |
+
fashion in ``self.data``.
|
| 611 |
+
|
| 612 |
+
"""
|
parrot/lib/python3.10/site-packages/scipy/sparse/_matrix.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class spmatrix:
|
| 2 |
+
"""This class provides a base class for all sparse matrix classes.
|
| 3 |
+
|
| 4 |
+
It cannot be instantiated. Most of the work is provided by subclasses.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
@property
|
| 8 |
+
def _bsr_container(self):
|
| 9 |
+
from ._bsr import bsr_matrix
|
| 10 |
+
return bsr_matrix
|
| 11 |
+
|
| 12 |
+
@property
|
| 13 |
+
def _coo_container(self):
|
| 14 |
+
from ._coo import coo_matrix
|
| 15 |
+
return coo_matrix
|
| 16 |
+
|
| 17 |
+
@property
|
| 18 |
+
def _csc_container(self):
|
| 19 |
+
from ._csc import csc_matrix
|
| 20 |
+
return csc_matrix
|
| 21 |
+
|
| 22 |
+
@property
|
| 23 |
+
def _csr_container(self):
|
| 24 |
+
from ._csr import csr_matrix
|
| 25 |
+
return csr_matrix
|
| 26 |
+
|
| 27 |
+
@property
|
| 28 |
+
def _dia_container(self):
|
| 29 |
+
from ._dia import dia_matrix
|
| 30 |
+
return dia_matrix
|
| 31 |
+
|
| 32 |
+
@property
|
| 33 |
+
def _dok_container(self):
|
| 34 |
+
from ._dok import dok_matrix
|
| 35 |
+
return dok_matrix
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def _lil_container(self):
|
| 39 |
+
from ._lil import lil_matrix
|
| 40 |
+
return lil_matrix
|
| 41 |
+
|
| 42 |
+
# Restore matrix multiplication
|
| 43 |
+
def __mul__(self, other):
|
| 44 |
+
return self._matmul_dispatch(other)
|
| 45 |
+
|
| 46 |
+
def __rmul__(self, other):
|
| 47 |
+
return self._rmatmul_dispatch(other)
|
| 48 |
+
|
| 49 |
+
# Restore matrix power
|
| 50 |
+
def __pow__(self, power):
|
| 51 |
+
from .linalg import matrix_power
|
| 52 |
+
|
| 53 |
+
return matrix_power(self, power)
|
| 54 |
+
|
| 55 |
+
## Backward compatibility
|
| 56 |
+
|
| 57 |
+
def set_shape(self, shape):
|
| 58 |
+
"""Set the shape of the matrix in-place"""
|
| 59 |
+
# Make sure copy is False since this is in place
|
| 60 |
+
# Make sure format is unchanged because we are doing a __dict__ swap
|
| 61 |
+
new_self = self.reshape(shape, copy=False).asformat(self.format)
|
| 62 |
+
self.__dict__ = new_self.__dict__
|
| 63 |
+
|
| 64 |
+
def get_shape(self):
|
| 65 |
+
"""Get the shape of the matrix"""
|
| 66 |
+
return self._shape
|
| 67 |
+
|
| 68 |
+
shape = property(fget=get_shape, fset=set_shape,
|
| 69 |
+
doc="Shape of the matrix")
|
| 70 |
+
|
| 71 |
+
def asfptype(self):
|
| 72 |
+
"""Upcast matrix to a floating point format (if necessary)"""
|
| 73 |
+
return self._asfptype()
|
| 74 |
+
|
| 75 |
+
def getmaxprint(self):
|
| 76 |
+
"""Maximum number of elements to display when printed."""
|
| 77 |
+
return self._getmaxprint()
|
| 78 |
+
|
| 79 |
+
def getformat(self):
|
| 80 |
+
"""Matrix storage format"""
|
| 81 |
+
return self.format
|
| 82 |
+
|
| 83 |
+
def getnnz(self, axis=None):
|
| 84 |
+
"""Number of stored values, including explicit zeros.
|
| 85 |
+
|
| 86 |
+
Parameters
|
| 87 |
+
----------
|
| 88 |
+
axis : None, 0, or 1
|
| 89 |
+
Select between the number of values across the whole array, in
|
| 90 |
+
each column, or in each row.
|
| 91 |
+
"""
|
| 92 |
+
return self._getnnz(axis=axis)
|
| 93 |
+
|
| 94 |
+
def getH(self):
|
| 95 |
+
"""Return the Hermitian transpose of this matrix.
|
| 96 |
+
|
| 97 |
+
See Also
|
| 98 |
+
--------
|
| 99 |
+
numpy.matrix.getH : NumPy's implementation of `getH` for matrices
|
| 100 |
+
"""
|
| 101 |
+
return self.conjugate().transpose()
|
| 102 |
+
|
| 103 |
+
def getcol(self, j):
|
| 104 |
+
"""Returns a copy of column j of the matrix, as an (m x 1) sparse
|
| 105 |
+
matrix (column vector).
|
| 106 |
+
"""
|
| 107 |
+
return self._getcol(j)
|
| 108 |
+
|
| 109 |
+
def getrow(self, i):
|
| 110 |
+
"""Returns a copy of row i of the matrix, as a (1 x n) sparse
|
| 111 |
+
matrix (row vector).
|
| 112 |
+
"""
|
| 113 |
+
return self._getrow(i)
|
parrot/lib/python3.10/site-packages/scipy/sparse/_matrix_io.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import scipy as sp
|
| 3 |
+
|
| 4 |
+
__all__ = ['save_npz', 'load_npz']
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# Make loading safe vs. malicious input
|
| 8 |
+
PICKLE_KWARGS = dict(allow_pickle=False)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def save_npz(file, matrix, compressed=True):
|
| 12 |
+
""" Save a sparse matrix or array to a file using ``.npz`` format.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
----------
|
| 16 |
+
file : str or file-like object
|
| 17 |
+
Either the file name (string) or an open file (file-like object)
|
| 18 |
+
where the data will be saved. If file is a string, the ``.npz``
|
| 19 |
+
extension will be appended to the file name if it is not already
|
| 20 |
+
there.
|
| 21 |
+
matrix: spmatrix or sparray
|
| 22 |
+
The sparse matrix or array to save.
|
| 23 |
+
Supported formats: ``csc``, ``csr``, ``bsr``, ``dia`` or ``coo``.
|
| 24 |
+
compressed : bool, optional
|
| 25 |
+
Allow compressing the file. Default: True
|
| 26 |
+
|
| 27 |
+
See Also
|
| 28 |
+
--------
|
| 29 |
+
scipy.sparse.load_npz: Load a sparse matrix from a file using ``.npz`` format.
|
| 30 |
+
numpy.savez: Save several arrays into a ``.npz`` archive.
|
| 31 |
+
numpy.savez_compressed : Save several arrays into a compressed ``.npz`` archive.
|
| 32 |
+
|
| 33 |
+
Examples
|
| 34 |
+
--------
|
| 35 |
+
Store sparse matrix to disk, and load it again:
|
| 36 |
+
|
| 37 |
+
>>> import numpy as np
|
| 38 |
+
>>> import scipy as sp
|
| 39 |
+
>>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
|
| 40 |
+
>>> sparse_matrix
|
| 41 |
+
<Compressed Sparse Column sparse matrix of dtype 'int64'
|
| 42 |
+
with 2 stored elements and shape (2, 3)>
|
| 43 |
+
>>> sparse_matrix.toarray()
|
| 44 |
+
array([[0, 0, 3],
|
| 45 |
+
[4, 0, 0]], dtype=int64)
|
| 46 |
+
|
| 47 |
+
>>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
|
| 48 |
+
>>> sparse_matrix = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
|
| 49 |
+
|
| 50 |
+
>>> sparse_matrix
|
| 51 |
+
<Compressed Sparse Column sparse matrix of dtype 'int64'
|
| 52 |
+
with 2 stored elements and shape (2, 3)>
|
| 53 |
+
>>> sparse_matrix.toarray()
|
| 54 |
+
array([[0, 0, 3],
|
| 55 |
+
[4, 0, 0]], dtype=int64)
|
| 56 |
+
"""
|
| 57 |
+
arrays_dict = {}
|
| 58 |
+
if matrix.format in ('csc', 'csr', 'bsr'):
|
| 59 |
+
arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr)
|
| 60 |
+
elif matrix.format == 'dia':
|
| 61 |
+
arrays_dict.update(offsets=matrix.offsets)
|
| 62 |
+
elif matrix.format == 'coo':
|
| 63 |
+
arrays_dict.update(row=matrix.row, col=matrix.col)
|
| 64 |
+
else:
|
| 65 |
+
msg = f'Save is not implemented for sparse matrix of format {matrix.format}.'
|
| 66 |
+
raise NotImplementedError(msg)
|
| 67 |
+
arrays_dict.update(
|
| 68 |
+
format=matrix.format.encode('ascii'),
|
| 69 |
+
shape=matrix.shape,
|
| 70 |
+
data=matrix.data
|
| 71 |
+
)
|
| 72 |
+
if isinstance(matrix, sp.sparse.sparray):
|
| 73 |
+
arrays_dict.update(_is_array=True)
|
| 74 |
+
if compressed:
|
| 75 |
+
np.savez_compressed(file, **arrays_dict)
|
| 76 |
+
else:
|
| 77 |
+
np.savez(file, **arrays_dict)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def load_npz(file):
|
| 81 |
+
""" Load a sparse array/matrix from a file using ``.npz`` format.
|
| 82 |
+
|
| 83 |
+
Parameters
|
| 84 |
+
----------
|
| 85 |
+
file : str or file-like object
|
| 86 |
+
Either the file name (string) or an open file (file-like object)
|
| 87 |
+
where the data will be loaded.
|
| 88 |
+
|
| 89 |
+
Returns
|
| 90 |
+
-------
|
| 91 |
+
result : csc_array, csr_array, bsr_array, dia_array or coo_array
|
| 92 |
+
A sparse array/matrix containing the loaded data.
|
| 93 |
+
|
| 94 |
+
Raises
|
| 95 |
+
------
|
| 96 |
+
OSError
|
| 97 |
+
If the input file does not exist or cannot be read.
|
| 98 |
+
|
| 99 |
+
See Also
|
| 100 |
+
--------
|
| 101 |
+
scipy.sparse.save_npz: Save a sparse array/matrix to a file using ``.npz`` format.
|
| 102 |
+
numpy.load: Load several arrays from a ``.npz`` archive.
|
| 103 |
+
|
| 104 |
+
Examples
|
| 105 |
+
--------
|
| 106 |
+
Store sparse array/matrix to disk, and load it again:
|
| 107 |
+
|
| 108 |
+
>>> import numpy as np
|
| 109 |
+
>>> import scipy as sp
|
| 110 |
+
>>> sparse_array = sp.sparse.csc_array([[0, 0, 3], [4, 0, 0]])
|
| 111 |
+
>>> sparse_array
|
| 112 |
+
<Compressed Sparse Column sparse array of dtype 'int64'
|
| 113 |
+
with 2 stored elements and shape (2, 3)>
|
| 114 |
+
>>> sparse_array.toarray()
|
| 115 |
+
array([[0, 0, 3],
|
| 116 |
+
[4, 0, 0]], dtype=int64)
|
| 117 |
+
|
| 118 |
+
>>> sp.sparse.save_npz('/tmp/sparse_array.npz', sparse_array)
|
| 119 |
+
>>> sparse_array = sp.sparse.load_npz('/tmp/sparse_array.npz')
|
| 120 |
+
|
| 121 |
+
>>> sparse_array
|
| 122 |
+
<Compressed Sparse Column sparse array of dtype 'int64'
|
| 123 |
+
with 2 stored elements and shape (2, 3)>
|
| 124 |
+
>>> sparse_array.toarray()
|
| 125 |
+
array([[0, 0, 3],
|
| 126 |
+
[4, 0, 0]], dtype=int64)
|
| 127 |
+
|
| 128 |
+
In this example we force the result to be csr_array from csr_matrix
|
| 129 |
+
>>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
|
| 130 |
+
>>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
|
| 131 |
+
>>> tmp = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
|
| 132 |
+
>>> sparse_array = sp.sparse.csr_array(tmp)
|
| 133 |
+
"""
|
| 134 |
+
with np.load(file, **PICKLE_KWARGS) as loaded:
|
| 135 |
+
sparse_format = loaded.get('format')
|
| 136 |
+
if sparse_format is None:
|
| 137 |
+
raise ValueError(f'The file {file} does not contain '
|
| 138 |
+
f'a sparse array or matrix.')
|
| 139 |
+
sparse_format = sparse_format.item()
|
| 140 |
+
|
| 141 |
+
if not isinstance(sparse_format, str):
|
| 142 |
+
# Play safe with Python 2 vs 3 backward compatibility;
|
| 143 |
+
# files saved with SciPy < 1.0.0 may contain unicode or bytes.
|
| 144 |
+
sparse_format = sparse_format.decode('ascii')
|
| 145 |
+
|
| 146 |
+
if loaded.get('_is_array'):
|
| 147 |
+
sparse_type = sparse_format + '_array'
|
| 148 |
+
else:
|
| 149 |
+
sparse_type = sparse_format + '_matrix'
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
cls = getattr(sp.sparse, f'{sparse_type}')
|
| 153 |
+
except AttributeError as e:
|
| 154 |
+
raise ValueError(f'Unknown format "{sparse_type}"') from e
|
| 155 |
+
|
| 156 |
+
if sparse_format in ('csc', 'csr', 'bsr'):
|
| 157 |
+
return cls((loaded['data'], loaded['indices'], loaded['indptr']),
|
| 158 |
+
shape=loaded['shape'])
|
| 159 |
+
elif sparse_format == 'dia':
|
| 160 |
+
return cls((loaded['data'], loaded['offsets']),
|
| 161 |
+
shape=loaded['shape'])
|
| 162 |
+
elif sparse_format == 'coo':
|
| 163 |
+
return cls((loaded['data'], (loaded['row'], loaded['col'])),
|
| 164 |
+
shape=loaded['shape'])
|
| 165 |
+
else:
|
| 166 |
+
raise NotImplementedError(f'Load is not implemented for '
|
| 167 |
+
f'sparse matrix of format {sparse_format}.')
|
parrot/lib/python3.10/site-packages/scipy/sparse/_spfuncs.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Functions that operate on sparse matrices
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
__all__ = ['count_blocks','estimate_blocksize']
|
| 5 |
+
|
| 6 |
+
from ._base import issparse
|
| 7 |
+
from ._csr import csr_array
|
| 8 |
+
from ._sparsetools import csr_count_blocks
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def estimate_blocksize(A,efficiency=0.7):
|
| 12 |
+
"""Attempt to determine the blocksize of a sparse matrix
|
| 13 |
+
|
| 14 |
+
Returns a blocksize=(r,c) such that
|
| 15 |
+
- A.nnz / A.tobsr( (r,c) ).nnz > efficiency
|
| 16 |
+
"""
|
| 17 |
+
if not (issparse(A) and A.format in ("csc", "csr")):
|
| 18 |
+
A = csr_array(A)
|
| 19 |
+
|
| 20 |
+
if A.nnz == 0:
|
| 21 |
+
return (1,1)
|
| 22 |
+
|
| 23 |
+
if not 0 < efficiency < 1.0:
|
| 24 |
+
raise ValueError('efficiency must satisfy 0.0 < efficiency < 1.0')
|
| 25 |
+
|
| 26 |
+
high_efficiency = (1.0 + efficiency) / 2.0
|
| 27 |
+
nnz = float(A.nnz)
|
| 28 |
+
M,N = A.shape
|
| 29 |
+
|
| 30 |
+
if M % 2 == 0 and N % 2 == 0:
|
| 31 |
+
e22 = nnz / (4 * count_blocks(A,(2,2)))
|
| 32 |
+
else:
|
| 33 |
+
e22 = 0.0
|
| 34 |
+
|
| 35 |
+
if M % 3 == 0 and N % 3 == 0:
|
| 36 |
+
e33 = nnz / (9 * count_blocks(A,(3,3)))
|
| 37 |
+
else:
|
| 38 |
+
e33 = 0.0
|
| 39 |
+
|
| 40 |
+
if e22 > high_efficiency and e33 > high_efficiency:
|
| 41 |
+
e66 = nnz / (36 * count_blocks(A,(6,6)))
|
| 42 |
+
if e66 > efficiency:
|
| 43 |
+
return (6,6)
|
| 44 |
+
else:
|
| 45 |
+
return (3,3)
|
| 46 |
+
else:
|
| 47 |
+
if M % 4 == 0 and N % 4 == 0:
|
| 48 |
+
e44 = nnz / (16 * count_blocks(A,(4,4)))
|
| 49 |
+
else:
|
| 50 |
+
e44 = 0.0
|
| 51 |
+
|
| 52 |
+
if e44 > efficiency:
|
| 53 |
+
return (4,4)
|
| 54 |
+
elif e33 > efficiency:
|
| 55 |
+
return (3,3)
|
| 56 |
+
elif e22 > efficiency:
|
| 57 |
+
return (2,2)
|
| 58 |
+
else:
|
| 59 |
+
return (1,1)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def count_blocks(A,blocksize):
|
| 63 |
+
"""For a given blocksize=(r,c) count the number of occupied
|
| 64 |
+
blocks in a sparse matrix A
|
| 65 |
+
"""
|
| 66 |
+
r,c = blocksize
|
| 67 |
+
if r < 1 or c < 1:
|
| 68 |
+
raise ValueError('r and c must be positive')
|
| 69 |
+
|
| 70 |
+
if issparse(A):
|
| 71 |
+
if A.format == "csr":
|
| 72 |
+
M,N = A.shape
|
| 73 |
+
return csr_count_blocks(M,N,r,c,A.indptr,A.indices)
|
| 74 |
+
elif A.format == "csc":
|
| 75 |
+
return count_blocks(A.T,(c,r))
|
| 76 |
+
return count_blocks(csr_array(A),blocksize)
|
parrot/lib/python3.10/site-packages/scipy/sparse/_sputils.py
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Utility functions for sparse matrix module
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from typing import Any, Literal, Optional, Union
|
| 6 |
+
import operator
|
| 7 |
+
import numpy as np
|
| 8 |
+
from math import prod
|
| 9 |
+
import scipy.sparse as sp
|
| 10 |
+
from scipy._lib._util import np_long, np_ulong
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
__all__ = ['upcast', 'getdtype', 'getdata', 'isscalarlike', 'isintlike',
|
| 14 |
+
'isshape', 'issequence', 'isdense', 'ismatrix', 'get_sum_dtype']
|
| 15 |
+
|
| 16 |
+
supported_dtypes = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc,
|
| 17 |
+
np.uintc, np_long, np_ulong, np.longlong, np.ulonglong,
|
| 18 |
+
np.float32, np.float64, np.longdouble,
|
| 19 |
+
np.complex64, np.complex128, np.clongdouble]
|
| 20 |
+
|
| 21 |
+
_upcast_memo = {}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def upcast(*args):
|
| 25 |
+
"""Returns the nearest supported sparse dtype for the
|
| 26 |
+
combination of one or more types.
|
| 27 |
+
|
| 28 |
+
upcast(t0, t1, ..., tn) -> T where T is a supported dtype
|
| 29 |
+
|
| 30 |
+
Examples
|
| 31 |
+
--------
|
| 32 |
+
>>> from scipy.sparse._sputils import upcast
|
| 33 |
+
>>> upcast('int32')
|
| 34 |
+
<type 'numpy.int32'>
|
| 35 |
+
>>> upcast('bool')
|
| 36 |
+
<type 'numpy.bool_'>
|
| 37 |
+
>>> upcast('int32','float32')
|
| 38 |
+
<type 'numpy.float64'>
|
| 39 |
+
>>> upcast('bool',complex,float)
|
| 40 |
+
<type 'numpy.complex128'>
|
| 41 |
+
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
t = _upcast_memo.get(hash(args))
|
| 45 |
+
if t is not None:
|
| 46 |
+
return t
|
| 47 |
+
|
| 48 |
+
upcast = np.result_type(*args)
|
| 49 |
+
|
| 50 |
+
for t in supported_dtypes:
|
| 51 |
+
if np.can_cast(upcast, t):
|
| 52 |
+
_upcast_memo[hash(args)] = t
|
| 53 |
+
return t
|
| 54 |
+
|
| 55 |
+
raise TypeError(f'no supported conversion for types: {args!r}')
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def upcast_char(*args):
|
| 59 |
+
"""Same as `upcast` but taking dtype.char as input (faster)."""
|
| 60 |
+
t = _upcast_memo.get(args)
|
| 61 |
+
if t is not None:
|
| 62 |
+
return t
|
| 63 |
+
t = upcast(*map(np.dtype, args))
|
| 64 |
+
_upcast_memo[args] = t
|
| 65 |
+
return t
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def upcast_scalar(dtype, scalar):
|
| 69 |
+
"""Determine data type for binary operation between an array of
|
| 70 |
+
type `dtype` and a scalar.
|
| 71 |
+
"""
|
| 72 |
+
return (np.array([0], dtype=dtype) * scalar).dtype
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def downcast_intp_index(arr):
|
| 76 |
+
"""
|
| 77 |
+
Down-cast index array to np.intp dtype if it is of a larger dtype.
|
| 78 |
+
|
| 79 |
+
Raise an error if the array contains a value that is too large for
|
| 80 |
+
intp.
|
| 81 |
+
"""
|
| 82 |
+
if arr.dtype.itemsize > np.dtype(np.intp).itemsize:
|
| 83 |
+
if arr.size == 0:
|
| 84 |
+
return arr.astype(np.intp)
|
| 85 |
+
maxval = arr.max()
|
| 86 |
+
minval = arr.min()
|
| 87 |
+
if maxval > np.iinfo(np.intp).max or minval < np.iinfo(np.intp).min:
|
| 88 |
+
raise ValueError("Cannot deal with arrays with indices larger "
|
| 89 |
+
"than the machine maximum address size "
|
| 90 |
+
"(e.g. 64-bit indices on 32-bit machine).")
|
| 91 |
+
return arr.astype(np.intp)
|
| 92 |
+
return arr
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def to_native(A):
|
| 96 |
+
"""
|
| 97 |
+
Ensure that the data type of the NumPy array `A` has native byte order.
|
| 98 |
+
|
| 99 |
+
`A` must be a NumPy array. If the data type of `A` does not have native
|
| 100 |
+
byte order, a copy of `A` with a native byte order is returned. Otherwise
|
| 101 |
+
`A` is returned.
|
| 102 |
+
"""
|
| 103 |
+
dt = A.dtype
|
| 104 |
+
if dt.isnative:
|
| 105 |
+
# Don't call `asarray()` if A is already native, to avoid unnecessarily
|
| 106 |
+
# creating a view of the input array.
|
| 107 |
+
return A
|
| 108 |
+
return np.asarray(A, dtype=dt.newbyteorder('native'))
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def getdtype(dtype, a=None, default=None):
|
| 112 |
+
"""Function used to simplify argument processing. If 'dtype' is not
|
| 113 |
+
specified (is None), returns a.dtype; otherwise returns a np.dtype
|
| 114 |
+
object created from the specified dtype argument. If 'dtype' and 'a'
|
| 115 |
+
are both None, construct a data type out of the 'default' parameter.
|
| 116 |
+
Furthermore, 'dtype' must be in 'allowed' set.
|
| 117 |
+
"""
|
| 118 |
+
# TODO is this really what we want?
|
| 119 |
+
if dtype is None:
|
| 120 |
+
try:
|
| 121 |
+
newdtype = a.dtype
|
| 122 |
+
except AttributeError as e:
|
| 123 |
+
if default is not None:
|
| 124 |
+
newdtype = np.dtype(default)
|
| 125 |
+
else:
|
| 126 |
+
raise TypeError("could not interpret data type") from e
|
| 127 |
+
else:
|
| 128 |
+
newdtype = np.dtype(dtype)
|
| 129 |
+
if newdtype == np.object_:
|
| 130 |
+
raise ValueError(
|
| 131 |
+
"object dtype is not supported by sparse matrices"
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
return newdtype
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def getdata(obj, dtype=None, copy=False) -> np.ndarray:
|
| 138 |
+
"""
|
| 139 |
+
This is a wrapper of `np.array(obj, dtype=dtype, copy=copy)`
|
| 140 |
+
that will generate a warning if the result is an object array.
|
| 141 |
+
"""
|
| 142 |
+
data = np.array(obj, dtype=dtype, copy=copy)
|
| 143 |
+
# Defer to getdtype for checking that the dtype is OK.
|
| 144 |
+
# This is called for the validation only; we don't need the return value.
|
| 145 |
+
getdtype(data.dtype)
|
| 146 |
+
return data
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def get_index_dtype(arrays=(), maxval=None, check_contents=False):
|
| 150 |
+
"""
|
| 151 |
+
Based on input (integer) arrays `a`, determine a suitable index data
|
| 152 |
+
type that can hold the data in the arrays.
|
| 153 |
+
|
| 154 |
+
Parameters
|
| 155 |
+
----------
|
| 156 |
+
arrays : tuple of array_like
|
| 157 |
+
Input arrays whose types/contents to check
|
| 158 |
+
maxval : float, optional
|
| 159 |
+
Maximum value needed
|
| 160 |
+
check_contents : bool, optional
|
| 161 |
+
Whether to check the values in the arrays and not just their types.
|
| 162 |
+
Default: False (check only the types)
|
| 163 |
+
|
| 164 |
+
Returns
|
| 165 |
+
-------
|
| 166 |
+
dtype : dtype
|
| 167 |
+
Suitable index data type (int32 or int64)
|
| 168 |
+
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
int32min = np.int32(np.iinfo(np.int32).min)
|
| 172 |
+
int32max = np.int32(np.iinfo(np.int32).max)
|
| 173 |
+
|
| 174 |
+
# not using intc directly due to misinteractions with pythran
|
| 175 |
+
dtype = np.int32 if np.intc().itemsize == 4 else np.int64
|
| 176 |
+
if maxval is not None:
|
| 177 |
+
maxval = np.int64(maxval)
|
| 178 |
+
if maxval > int32max:
|
| 179 |
+
dtype = np.int64
|
| 180 |
+
|
| 181 |
+
if isinstance(arrays, np.ndarray):
|
| 182 |
+
arrays = (arrays,)
|
| 183 |
+
|
| 184 |
+
for arr in arrays:
|
| 185 |
+
arr = np.asarray(arr)
|
| 186 |
+
if not np.can_cast(arr.dtype, np.int32):
|
| 187 |
+
if check_contents:
|
| 188 |
+
if arr.size == 0:
|
| 189 |
+
# a bigger type not needed
|
| 190 |
+
continue
|
| 191 |
+
elif np.issubdtype(arr.dtype, np.integer):
|
| 192 |
+
maxval = arr.max()
|
| 193 |
+
minval = arr.min()
|
| 194 |
+
if minval >= int32min and maxval <= int32max:
|
| 195 |
+
# a bigger type not needed
|
| 196 |
+
continue
|
| 197 |
+
|
| 198 |
+
dtype = np.int64
|
| 199 |
+
break
|
| 200 |
+
|
| 201 |
+
return dtype
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def get_sum_dtype(dtype: np.dtype) -> np.dtype:
|
| 205 |
+
"""Mimic numpy's casting for np.sum"""
|
| 206 |
+
if dtype.kind == 'u' and np.can_cast(dtype, np.uint):
|
| 207 |
+
return np.uint
|
| 208 |
+
if np.can_cast(dtype, np.int_):
|
| 209 |
+
return np.int_
|
| 210 |
+
return dtype
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def isscalarlike(x) -> bool:
|
| 214 |
+
"""Is x either a scalar, an array scalar, or a 0-dim array?"""
|
| 215 |
+
return np.isscalar(x) or (isdense(x) and x.ndim == 0)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def isintlike(x) -> bool:
|
| 219 |
+
"""Is x appropriate as an index into a sparse matrix? Returns True
|
| 220 |
+
if it can be cast safely to a machine int.
|
| 221 |
+
"""
|
| 222 |
+
# Fast-path check to eliminate non-scalar values. operator.index would
|
| 223 |
+
# catch this case too, but the exception catching is slow.
|
| 224 |
+
if np.ndim(x) != 0:
|
| 225 |
+
return False
|
| 226 |
+
try:
|
| 227 |
+
operator.index(x)
|
| 228 |
+
except (TypeError, ValueError):
|
| 229 |
+
try:
|
| 230 |
+
loose_int = bool(int(x) == x)
|
| 231 |
+
except (TypeError, ValueError):
|
| 232 |
+
return False
|
| 233 |
+
if loose_int:
|
| 234 |
+
msg = "Inexact indices into sparse matrices are not allowed"
|
| 235 |
+
raise ValueError(msg)
|
| 236 |
+
return loose_int
|
| 237 |
+
return True
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def isshape(x, nonneg=False, *, allow_1d=False) -> bool:
|
| 241 |
+
"""Is x a valid tuple of dimensions?
|
| 242 |
+
|
| 243 |
+
If nonneg, also checks that the dimensions are non-negative.
|
| 244 |
+
If allow_1d, shapes of length 1 or 2 are allowed.
|
| 245 |
+
"""
|
| 246 |
+
ndim = len(x)
|
| 247 |
+
if ndim != 2 and not (allow_1d and ndim == 1):
|
| 248 |
+
return False
|
| 249 |
+
for d in x:
|
| 250 |
+
if not isintlike(d):
|
| 251 |
+
return False
|
| 252 |
+
if nonneg and d < 0:
|
| 253 |
+
return False
|
| 254 |
+
return True
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def issequence(t) -> bool:
|
| 258 |
+
return ((isinstance(t, (list, tuple)) and
|
| 259 |
+
(len(t) == 0 or np.isscalar(t[0]))) or
|
| 260 |
+
(isinstance(t, np.ndarray) and (t.ndim == 1)))
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def ismatrix(t) -> bool:
|
| 264 |
+
return ((isinstance(t, (list, tuple)) and
|
| 265 |
+
len(t) > 0 and issequence(t[0])) or
|
| 266 |
+
(isinstance(t, np.ndarray) and t.ndim == 2))
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def isdense(x) -> bool:
|
| 270 |
+
return isinstance(x, np.ndarray)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def validateaxis(axis) -> None:
|
| 274 |
+
if axis is None:
|
| 275 |
+
return
|
| 276 |
+
axis_type = type(axis)
|
| 277 |
+
|
| 278 |
+
# In NumPy, you can pass in tuples for 'axis', but they are
|
| 279 |
+
# not very useful for sparse matrices given their limited
|
| 280 |
+
# dimensions, so let's make it explicit that they are not
|
| 281 |
+
# allowed to be passed in
|
| 282 |
+
if axis_type == tuple:
|
| 283 |
+
raise TypeError("Tuples are not accepted for the 'axis' parameter. "
|
| 284 |
+
"Please pass in one of the following: "
|
| 285 |
+
"{-2, -1, 0, 1, None}.")
|
| 286 |
+
|
| 287 |
+
# If not a tuple, check that the provided axis is actually
|
| 288 |
+
# an integer and raise a TypeError similar to NumPy's
|
| 289 |
+
if not np.issubdtype(np.dtype(axis_type), np.integer):
|
| 290 |
+
raise TypeError(f"axis must be an integer, not {axis_type.__name__}")
|
| 291 |
+
|
| 292 |
+
if not (-2 <= axis <= 1):
|
| 293 |
+
raise ValueError("axis out of range")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def check_shape(args, current_shape=None, *, allow_1d=False) -> tuple[int, ...]:
|
| 297 |
+
"""Imitate numpy.matrix handling of shape arguments
|
| 298 |
+
|
| 299 |
+
Parameters
|
| 300 |
+
----------
|
| 301 |
+
args : array_like
|
| 302 |
+
Data structures providing information about the shape of the sparse array.
|
| 303 |
+
current_shape : tuple, optional
|
| 304 |
+
The current shape of the sparse array or matrix.
|
| 305 |
+
If None (default), the current shape will be inferred from args.
|
| 306 |
+
allow_1d : bool, optional
|
| 307 |
+
If True, then 1-D or 2-D arrays are accepted.
|
| 308 |
+
If False (default), then only 2-D arrays are accepted and an error is
|
| 309 |
+
raised otherwise.
|
| 310 |
+
|
| 311 |
+
Returns
|
| 312 |
+
-------
|
| 313 |
+
new_shape: tuple
|
| 314 |
+
The new shape after validation.
|
| 315 |
+
"""
|
| 316 |
+
if len(args) == 0:
|
| 317 |
+
raise TypeError("function missing 1 required positional argument: "
|
| 318 |
+
"'shape'")
|
| 319 |
+
if len(args) == 1:
|
| 320 |
+
try:
|
| 321 |
+
shape_iter = iter(args[0])
|
| 322 |
+
except TypeError:
|
| 323 |
+
new_shape = (operator.index(args[0]), )
|
| 324 |
+
else:
|
| 325 |
+
new_shape = tuple(operator.index(arg) for arg in shape_iter)
|
| 326 |
+
else:
|
| 327 |
+
new_shape = tuple(operator.index(arg) for arg in args)
|
| 328 |
+
|
| 329 |
+
if current_shape is None:
|
| 330 |
+
if allow_1d:
|
| 331 |
+
if len(new_shape) not in (1, 2):
|
| 332 |
+
raise ValueError('shape must be a 1- or 2-tuple of positive '
|
| 333 |
+
'integers')
|
| 334 |
+
elif len(new_shape) != 2:
|
| 335 |
+
raise ValueError('shape must be a 2-tuple of positive integers')
|
| 336 |
+
if any(d < 0 for d in new_shape):
|
| 337 |
+
raise ValueError("'shape' elements cannot be negative")
|
| 338 |
+
else:
|
| 339 |
+
# Check the current size only if needed
|
| 340 |
+
current_size = prod(current_shape)
|
| 341 |
+
|
| 342 |
+
# Check for negatives
|
| 343 |
+
negative_indexes = [i for i, x in enumerate(new_shape) if x < 0]
|
| 344 |
+
if not negative_indexes:
|
| 345 |
+
new_size = prod(new_shape)
|
| 346 |
+
if new_size != current_size:
|
| 347 |
+
raise ValueError('cannot reshape array of size {} into shape {}'
|
| 348 |
+
.format(current_size, new_shape))
|
| 349 |
+
elif len(negative_indexes) == 1:
|
| 350 |
+
skip = negative_indexes[0]
|
| 351 |
+
specified = prod(new_shape[:skip] + new_shape[skip+1:])
|
| 352 |
+
unspecified, remainder = divmod(current_size, specified)
|
| 353 |
+
if remainder != 0:
|
| 354 |
+
err_shape = tuple('newshape' if x < 0 else x for x in new_shape)
|
| 355 |
+
raise ValueError('cannot reshape array of size {} into shape {}'
|
| 356 |
+
''.format(current_size, err_shape))
|
| 357 |
+
new_shape = new_shape[:skip] + (unspecified,) + new_shape[skip+1:]
|
| 358 |
+
else:
|
| 359 |
+
raise ValueError('can only specify one unknown dimension')
|
| 360 |
+
|
| 361 |
+
if len(new_shape) != 2 and not (allow_1d and len(new_shape) == 1):
|
| 362 |
+
raise ValueError('matrix shape must be two-dimensional')
|
| 363 |
+
|
| 364 |
+
return new_shape
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def check_reshape_kwargs(kwargs):
|
| 368 |
+
"""Unpack keyword arguments for reshape function.
|
| 369 |
+
|
| 370 |
+
This is useful because keyword arguments after star arguments are not
|
| 371 |
+
allowed in Python 2, but star keyword arguments are. This function unpacks
|
| 372 |
+
'order' and 'copy' from the star keyword arguments (with defaults) and
|
| 373 |
+
throws an error for any remaining.
|
| 374 |
+
"""
|
| 375 |
+
|
| 376 |
+
order = kwargs.pop('order', 'C')
|
| 377 |
+
copy = kwargs.pop('copy', False)
|
| 378 |
+
if kwargs: # Some unused kwargs remain
|
| 379 |
+
raise TypeError('reshape() got unexpected keywords arguments: {}'
|
| 380 |
+
.format(', '.join(kwargs.keys())))
|
| 381 |
+
return order, copy
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def is_pydata_spmatrix(m) -> bool:
|
| 385 |
+
"""
|
| 386 |
+
Check whether object is pydata/sparse matrix, avoiding importing the module.
|
| 387 |
+
"""
|
| 388 |
+
base_cls = getattr(sys.modules.get('sparse'), 'SparseArray', None)
|
| 389 |
+
return base_cls is not None and isinstance(m, base_cls)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def convert_pydata_sparse_to_scipy(
|
| 393 |
+
arg: Any, target_format: Optional[Literal["csc", "csr"]] = None
|
| 394 |
+
) -> Union[Any, "sp.spmatrix"]:
|
| 395 |
+
"""
|
| 396 |
+
Convert a pydata/sparse array to scipy sparse matrix,
|
| 397 |
+
pass through anything else.
|
| 398 |
+
"""
|
| 399 |
+
if is_pydata_spmatrix(arg):
|
| 400 |
+
arg = arg.to_scipy_sparse()
|
| 401 |
+
if target_format is not None:
|
| 402 |
+
arg = arg.asformat(target_format)
|
| 403 |
+
elif arg.format not in ("csc", "csr"):
|
| 404 |
+
arg = arg.tocsc()
|
| 405 |
+
return arg
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
###############################################################################
|
| 409 |
+
# Wrappers for NumPy types that are deprecated
|
| 410 |
+
|
| 411 |
+
# Numpy versions of these functions raise deprecation warnings, the
|
| 412 |
+
# ones below do not.
|
| 413 |
+
|
| 414 |
+
def matrix(*args, **kwargs):
|
| 415 |
+
return np.array(*args, **kwargs).view(np.matrix)
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def asmatrix(data, dtype=None):
|
| 419 |
+
if isinstance(data, np.matrix) and (dtype is None or data.dtype == dtype):
|
| 420 |
+
return data
|
| 421 |
+
return np.asarray(data, dtype=dtype).view(np.matrix)
|
| 422 |
+
|
| 423 |
+
###############################################################################
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def _todata(s) -> np.ndarray:
|
| 427 |
+
"""Access nonzero values, possibly after summing duplicates.
|
| 428 |
+
|
| 429 |
+
Parameters
|
| 430 |
+
----------
|
| 431 |
+
s : sparse array
|
| 432 |
+
Input sparse array.
|
| 433 |
+
|
| 434 |
+
Returns
|
| 435 |
+
-------
|
| 436 |
+
data: ndarray
|
| 437 |
+
Nonzero values of the array, with shape (s.nnz,)
|
| 438 |
+
|
| 439 |
+
"""
|
| 440 |
+
if isinstance(s, sp._data._data_matrix):
|
| 441 |
+
return s._deduped_data()
|
| 442 |
+
|
| 443 |
+
if isinstance(s, sp.dok_array):
|
| 444 |
+
return np.fromiter(s.values(), dtype=s.dtype, count=s.nnz)
|
| 445 |
+
|
| 446 |
+
if isinstance(s, sp.lil_array):
|
| 447 |
+
data = np.empty(s.nnz, dtype=s.dtype)
|
| 448 |
+
sp._csparsetools.lil_flatten_to_array(s.data, data)
|
| 449 |
+
return data
|
| 450 |
+
|
| 451 |
+
return s.tocoo()._deduped_data()
|
parrot/lib/python3.10/site-packages/scipy/sparse/base.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'MAXPRINT',
|
| 10 |
+
'SparseEfficiencyWarning',
|
| 11 |
+
'SparseFormatWarning',
|
| 12 |
+
'SparseWarning',
|
| 13 |
+
'asmatrix',
|
| 14 |
+
'check_reshape_kwargs',
|
| 15 |
+
'check_shape',
|
| 16 |
+
'get_sum_dtype',
|
| 17 |
+
'isdense',
|
| 18 |
+
'isscalarlike',
|
| 19 |
+
'issparse',
|
| 20 |
+
'isspmatrix',
|
| 21 |
+
'spmatrix',
|
| 22 |
+
'validateaxis',
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def __dir__():
|
| 27 |
+
return __all__
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def __getattr__(name):
|
| 31 |
+
return _sub_module_deprecation(sub_package="sparse", module="base",
|
| 32 |
+
private_modules=["_base"], all=__all__,
|
| 33 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/bsr.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'bsr_matmat',
|
| 10 |
+
'bsr_matrix',
|
| 11 |
+
'bsr_matvec',
|
| 12 |
+
'bsr_matvecs',
|
| 13 |
+
'bsr_sort_indices',
|
| 14 |
+
'bsr_tocsr',
|
| 15 |
+
'bsr_transpose',
|
| 16 |
+
'check_shape',
|
| 17 |
+
'csr_matmat_maxnnz',
|
| 18 |
+
'getdata',
|
| 19 |
+
'getdtype',
|
| 20 |
+
'isshape',
|
| 21 |
+
'isspmatrix_bsr',
|
| 22 |
+
'spmatrix',
|
| 23 |
+
'to_native',
|
| 24 |
+
'upcast',
|
| 25 |
+
'warn',
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def __dir__():
|
| 30 |
+
return __all__
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def __getattr__(name):
|
| 34 |
+
return _sub_module_deprecation(sub_package="sparse", module="bsr",
|
| 35 |
+
private_modules=["_bsr"], all=__all__,
|
| 36 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/compressed.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'IndexMixin',
|
| 10 |
+
'SparseEfficiencyWarning',
|
| 11 |
+
'check_shape',
|
| 12 |
+
'csr_column_index1',
|
| 13 |
+
'csr_column_index2',
|
| 14 |
+
'csr_row_index',
|
| 15 |
+
'csr_row_slice',
|
| 16 |
+
'csr_sample_offsets',
|
| 17 |
+
'csr_sample_values',
|
| 18 |
+
'csr_todense',
|
| 19 |
+
'downcast_intp_index',
|
| 20 |
+
'get_csr_submatrix',
|
| 21 |
+
'get_sum_dtype',
|
| 22 |
+
'getdtype',
|
| 23 |
+
'is_pydata_spmatrix',
|
| 24 |
+
'isdense',
|
| 25 |
+
'isintlike',
|
| 26 |
+
'isscalarlike',
|
| 27 |
+
'isshape',
|
| 28 |
+
'operator',
|
| 29 |
+
'to_native',
|
| 30 |
+
'upcast',
|
| 31 |
+
'upcast_char',
|
| 32 |
+
'warn',
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def __dir__():
|
| 37 |
+
return __all__
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def __getattr__(name):
|
| 41 |
+
return _sub_module_deprecation(sub_package="sparse", module="compressed",
|
| 42 |
+
private_modules=["_compressed"], all=__all__,
|
| 43 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/construct.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'block_diag',
|
| 10 |
+
'bmat',
|
| 11 |
+
'bsr_matrix',
|
| 12 |
+
'check_random_state',
|
| 13 |
+
'coo_matrix',
|
| 14 |
+
'csc_matrix',
|
| 15 |
+
'csr_hstack',
|
| 16 |
+
'csr_matrix',
|
| 17 |
+
'dia_matrix',
|
| 18 |
+
'diags',
|
| 19 |
+
'eye',
|
| 20 |
+
'get_index_dtype',
|
| 21 |
+
'hstack',
|
| 22 |
+
'identity',
|
| 23 |
+
'isscalarlike',
|
| 24 |
+
'issparse',
|
| 25 |
+
'kron',
|
| 26 |
+
'kronsum',
|
| 27 |
+
'numbers',
|
| 28 |
+
'rand',
|
| 29 |
+
'random',
|
| 30 |
+
'rng_integers',
|
| 31 |
+
'spdiags',
|
| 32 |
+
'upcast',
|
| 33 |
+
'vstack',
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def __dir__():
|
| 38 |
+
return __all__
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def __getattr__(name):
|
| 42 |
+
return _sub_module_deprecation(sub_package="sparse", module="construct",
|
| 43 |
+
private_modules=["_construct"], all=__all__,
|
| 44 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/coo.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'SparseEfficiencyWarning',
|
| 10 |
+
'check_reshape_kwargs',
|
| 11 |
+
'check_shape',
|
| 12 |
+
'coo_matrix',
|
| 13 |
+
'coo_matvec',
|
| 14 |
+
'coo_tocsr',
|
| 15 |
+
'coo_todense',
|
| 16 |
+
'downcast_intp_index',
|
| 17 |
+
'getdata',
|
| 18 |
+
'getdtype',
|
| 19 |
+
'isshape',
|
| 20 |
+
'isspmatrix_coo',
|
| 21 |
+
'operator',
|
| 22 |
+
'spmatrix',
|
| 23 |
+
'to_native',
|
| 24 |
+
'upcast',
|
| 25 |
+
'upcast_char',
|
| 26 |
+
'warn',
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def __dir__():
|
| 31 |
+
return __all__
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def __getattr__(name):
|
| 35 |
+
return _sub_module_deprecation(sub_package="sparse", module="coo",
|
| 36 |
+
private_modules=["_coo"], all=__all__,
|
| 37 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/csc.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'csc_matrix',
|
| 10 |
+
'csc_tocsr',
|
| 11 |
+
'expandptr',
|
| 12 |
+
'isspmatrix_csc',
|
| 13 |
+
'spmatrix',
|
| 14 |
+
'upcast',
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def __dir__():
|
| 19 |
+
return __all__
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def __getattr__(name):
|
| 23 |
+
return _sub_module_deprecation(sub_package="sparse", module="csc",
|
| 24 |
+
private_modules=["_csc"], all=__all__,
|
| 25 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/csr.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'csr_count_blocks',
|
| 10 |
+
'csr_matrix',
|
| 11 |
+
'csr_tobsr',
|
| 12 |
+
'csr_tocsc',
|
| 13 |
+
'get_csr_submatrix',
|
| 14 |
+
'isspmatrix_csr',
|
| 15 |
+
'spmatrix',
|
| 16 |
+
'upcast',
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def __dir__():
|
| 21 |
+
return __all__
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def __getattr__(name):
|
| 25 |
+
return _sub_module_deprecation(sub_package="sparse", module="csr",
|
| 26 |
+
private_modules=["_csr"], all=__all__,
|
| 27 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/data.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'isscalarlike',
|
| 10 |
+
'name',
|
| 11 |
+
'npfunc',
|
| 12 |
+
'validateaxis',
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def __dir__():
|
| 17 |
+
return __all__
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def __getattr__(name):
|
| 21 |
+
return _sub_module_deprecation(sub_package="sparse", module="data",
|
| 22 |
+
private_modules=["_data"], all=__all__,
|
| 23 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/dia.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'check_shape',
|
| 10 |
+
'dia_matrix',
|
| 11 |
+
'dia_matvec',
|
| 12 |
+
'get_sum_dtype',
|
| 13 |
+
'getdtype',
|
| 14 |
+
'isshape',
|
| 15 |
+
'isspmatrix_dia',
|
| 16 |
+
'spmatrix',
|
| 17 |
+
'upcast_char',
|
| 18 |
+
'validateaxis',
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def __dir__():
|
| 23 |
+
return __all__
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def __getattr__(name):
|
| 27 |
+
return _sub_module_deprecation(sub_package="sparse", module="dia",
|
| 28 |
+
private_modules=["_dia"], all=__all__,
|
| 29 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/dok.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'IndexMixin',
|
| 10 |
+
'check_shape',
|
| 11 |
+
'dok_matrix',
|
| 12 |
+
'getdtype',
|
| 13 |
+
'isdense',
|
| 14 |
+
'isintlike',
|
| 15 |
+
'isscalarlike',
|
| 16 |
+
'isshape',
|
| 17 |
+
'isspmatrix_dok',
|
| 18 |
+
'itertools',
|
| 19 |
+
'spmatrix',
|
| 20 |
+
'upcast',
|
| 21 |
+
'upcast_scalar',
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def __dir__():
|
| 26 |
+
return __all__
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def __getattr__(name):
|
| 30 |
+
return _sub_module_deprecation(sub_package="sparse", module="dok",
|
| 31 |
+
private_modules=["_dok"], all=__all__,
|
| 32 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/lil.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'isspmatrix_lil',
|
| 10 |
+
'lil_array',
|
| 11 |
+
'lil_matrix',
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def __dir__():
|
| 16 |
+
return __all__
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def __getattr__(name):
|
| 20 |
+
return _sub_module_deprecation(sub_package="sparse", module="lil",
|
| 21 |
+
private_modules=["_lil"], all=__all__,
|
| 22 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/linalg/__init__.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Sparse linear algebra (:mod:`scipy.sparse.linalg`)
|
| 3 |
+
==================================================
|
| 4 |
+
|
| 5 |
+
.. currentmodule:: scipy.sparse.linalg
|
| 6 |
+
|
| 7 |
+
Abstract linear operators
|
| 8 |
+
-------------------------
|
| 9 |
+
|
| 10 |
+
.. autosummary::
|
| 11 |
+
:toctree: generated/
|
| 12 |
+
|
| 13 |
+
LinearOperator -- abstract representation of a linear operator
|
| 14 |
+
aslinearoperator -- convert an object to an abstract linear operator
|
| 15 |
+
|
| 16 |
+
Matrix Operations
|
| 17 |
+
-----------------
|
| 18 |
+
|
| 19 |
+
.. autosummary::
|
| 20 |
+
:toctree: generated/
|
| 21 |
+
|
| 22 |
+
inv -- compute the sparse matrix inverse
|
| 23 |
+
expm -- compute the sparse matrix exponential
|
| 24 |
+
expm_multiply -- compute the product of a matrix exponential and a matrix
|
| 25 |
+
matrix_power -- compute the matrix power by raising a matrix to an exponent
|
| 26 |
+
|
| 27 |
+
Matrix norms
|
| 28 |
+
------------
|
| 29 |
+
|
| 30 |
+
.. autosummary::
|
| 31 |
+
:toctree: generated/
|
| 32 |
+
|
| 33 |
+
norm -- Norm of a sparse matrix
|
| 34 |
+
onenormest -- Estimate the 1-norm of a sparse matrix
|
| 35 |
+
|
| 36 |
+
Solving linear problems
|
| 37 |
+
-----------------------
|
| 38 |
+
|
| 39 |
+
Direct methods for linear equation systems:
|
| 40 |
+
|
| 41 |
+
.. autosummary::
|
| 42 |
+
:toctree: generated/
|
| 43 |
+
|
| 44 |
+
spsolve -- Solve the sparse linear system Ax=b
|
| 45 |
+
spsolve_triangular -- Solve sparse linear system Ax=b for a triangular A.
|
| 46 |
+
factorized -- Pre-factorize matrix to a function solving a linear system
|
| 47 |
+
MatrixRankWarning -- Warning on exactly singular matrices
|
| 48 |
+
use_solver -- Select direct solver to use
|
| 49 |
+
|
| 50 |
+
Iterative methods for linear equation systems:
|
| 51 |
+
|
| 52 |
+
.. autosummary::
|
| 53 |
+
:toctree: generated/
|
| 54 |
+
|
| 55 |
+
bicg -- Use BIConjugate Gradient iteration to solve Ax = b
|
| 56 |
+
bicgstab -- Use BIConjugate Gradient STABilized iteration to solve Ax = b
|
| 57 |
+
cg -- Use Conjugate Gradient iteration to solve Ax = b
|
| 58 |
+
cgs -- Use Conjugate Gradient Squared iteration to solve Ax = b
|
| 59 |
+
gmres -- Use Generalized Minimal RESidual iteration to solve Ax = b
|
| 60 |
+
lgmres -- Solve a matrix equation using the LGMRES algorithm
|
| 61 |
+
minres -- Use MINimum RESidual iteration to solve Ax = b
|
| 62 |
+
qmr -- Use Quasi-Minimal Residual iteration to solve Ax = b
|
| 63 |
+
gcrotmk -- Solve a matrix equation using the GCROT(m,k) algorithm
|
| 64 |
+
tfqmr -- Use Transpose-Free Quasi-Minimal Residual iteration to solve Ax = b
|
| 65 |
+
|
| 66 |
+
Iterative methods for least-squares problems:
|
| 67 |
+
|
| 68 |
+
.. autosummary::
|
| 69 |
+
:toctree: generated/
|
| 70 |
+
|
| 71 |
+
lsqr -- Find the least-squares solution to a sparse linear equation system
|
| 72 |
+
lsmr -- Find the least-squares solution to a sparse linear equation system
|
| 73 |
+
|
| 74 |
+
Matrix factorizations
|
| 75 |
+
---------------------
|
| 76 |
+
|
| 77 |
+
Eigenvalue problems:
|
| 78 |
+
|
| 79 |
+
.. autosummary::
|
| 80 |
+
:toctree: generated/
|
| 81 |
+
|
| 82 |
+
eigs -- Find k eigenvalues and eigenvectors of the square matrix A
|
| 83 |
+
eigsh -- Find k eigenvalues and eigenvectors of a symmetric matrix
|
| 84 |
+
lobpcg -- Solve symmetric partial eigenproblems with optional preconditioning
|
| 85 |
+
|
| 86 |
+
Singular values problems:
|
| 87 |
+
|
| 88 |
+
.. autosummary::
|
| 89 |
+
:toctree: generated/
|
| 90 |
+
|
| 91 |
+
svds -- Compute k singular values/vectors for a sparse matrix
|
| 92 |
+
|
| 93 |
+
The `svds` function supports the following solvers:
|
| 94 |
+
|
| 95 |
+
.. toctree::
|
| 96 |
+
|
| 97 |
+
sparse.linalg.svds-arpack
|
| 98 |
+
sparse.linalg.svds-lobpcg
|
| 99 |
+
sparse.linalg.svds-propack
|
| 100 |
+
|
| 101 |
+
Complete or incomplete LU factorizations
|
| 102 |
+
|
| 103 |
+
.. autosummary::
|
| 104 |
+
:toctree: generated/
|
| 105 |
+
|
| 106 |
+
splu -- Compute a LU decomposition for a sparse matrix
|
| 107 |
+
spilu -- Compute an incomplete LU decomposition for a sparse matrix
|
| 108 |
+
SuperLU -- Object representing an LU factorization
|
| 109 |
+
|
| 110 |
+
Sparse arrays with structure
|
| 111 |
+
----------------------------
|
| 112 |
+
|
| 113 |
+
.. autosummary::
|
| 114 |
+
:toctree: generated/
|
| 115 |
+
|
| 116 |
+
LaplacianNd -- Laplacian on a uniform rectangular grid in ``N`` dimensions
|
| 117 |
+
|
| 118 |
+
Exceptions
|
| 119 |
+
----------
|
| 120 |
+
|
| 121 |
+
.. autosummary::
|
| 122 |
+
:toctree: generated/
|
| 123 |
+
|
| 124 |
+
ArpackNoConvergence
|
| 125 |
+
ArpackError
|
| 126 |
+
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
from ._isolve import *
|
| 130 |
+
from ._dsolve import *
|
| 131 |
+
from ._interface import *
|
| 132 |
+
from ._eigen import *
|
| 133 |
+
from ._matfuncs import *
|
| 134 |
+
from ._onenormest import *
|
| 135 |
+
from ._norm import *
|
| 136 |
+
from ._expm_multiply import *
|
| 137 |
+
from ._special_sparse_arrays import *
|
| 138 |
+
|
| 139 |
+
# Deprecated namespaces, to be removed in v2.0.0
|
| 140 |
+
from . import isolve, dsolve, interface, eigen, matfuncs
|
| 141 |
+
|
| 142 |
+
__all__ = [s for s in dir() if not s.startswith('_')]
|
| 143 |
+
|
| 144 |
+
from scipy._lib._testutils import PytestTester
|
| 145 |
+
test = PytestTester(__name__)
|
| 146 |
+
del PytestTester
|
parrot/lib/python3.10/site-packages/scipy/sparse/linalg/_expm_multiply.py
ADDED
|
@@ -0,0 +1,810 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compute the action of the matrix exponential."""
|
| 2 |
+
from warnings import warn
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
import scipy.linalg
|
| 7 |
+
import scipy.sparse.linalg
|
| 8 |
+
from scipy.linalg._decomp_qr import qr
|
| 9 |
+
from scipy.sparse._sputils import is_pydata_spmatrix
|
| 10 |
+
from scipy.sparse.linalg import aslinearoperator
|
| 11 |
+
from scipy.sparse.linalg._interface import IdentityOperator
|
| 12 |
+
from scipy.sparse.linalg._onenormest import onenormest
|
| 13 |
+
|
| 14 |
+
__all__ = ['expm_multiply']
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _exact_inf_norm(A):
|
| 18 |
+
# A compatibility function which should eventually disappear.
|
| 19 |
+
if scipy.sparse.issparse(A):
|
| 20 |
+
return max(abs(A).sum(axis=1).flat)
|
| 21 |
+
elif is_pydata_spmatrix(A):
|
| 22 |
+
return max(abs(A).sum(axis=1))
|
| 23 |
+
else:
|
| 24 |
+
return np.linalg.norm(A, np.inf)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _exact_1_norm(A):
|
| 28 |
+
# A compatibility function which should eventually disappear.
|
| 29 |
+
if scipy.sparse.issparse(A):
|
| 30 |
+
return max(abs(A).sum(axis=0).flat)
|
| 31 |
+
elif is_pydata_spmatrix(A):
|
| 32 |
+
return max(abs(A).sum(axis=0))
|
| 33 |
+
else:
|
| 34 |
+
return np.linalg.norm(A, 1)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _trace(A):
|
| 38 |
+
# A compatibility function which should eventually disappear.
|
| 39 |
+
if is_pydata_spmatrix(A):
|
| 40 |
+
return A.to_scipy_sparse().trace()
|
| 41 |
+
else:
|
| 42 |
+
return A.trace()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def traceest(A, m3, seed=None):
|
| 46 |
+
"""Estimate `np.trace(A)` using `3*m3` matrix-vector products.
|
| 47 |
+
|
| 48 |
+
The result is not deterministic.
|
| 49 |
+
|
| 50 |
+
Parameters
|
| 51 |
+
----------
|
| 52 |
+
A : LinearOperator
|
| 53 |
+
Linear operator whose trace will be estimated. Has to be square.
|
| 54 |
+
m3 : int
|
| 55 |
+
Number of matrix-vector products divided by 3 used to estimate the
|
| 56 |
+
trace.
|
| 57 |
+
seed : optional
|
| 58 |
+
Seed for `numpy.random.default_rng`.
|
| 59 |
+
Can be provided to obtain deterministic results.
|
| 60 |
+
|
| 61 |
+
Returns
|
| 62 |
+
-------
|
| 63 |
+
trace : LinearOperator.dtype
|
| 64 |
+
Estimate of the trace
|
| 65 |
+
|
| 66 |
+
Notes
|
| 67 |
+
-----
|
| 68 |
+
This is the Hutch++ algorithm given in [1]_.
|
| 69 |
+
|
| 70 |
+
References
|
| 71 |
+
----------
|
| 72 |
+
.. [1] Meyer, Raphael A., Cameron Musco, Christopher Musco, and David P.
|
| 73 |
+
Woodruff. "Hutch++: Optimal Stochastic Trace Estimation." In Symposium
|
| 74 |
+
on Simplicity in Algorithms (SOSA), pp. 142-155. Society for Industrial
|
| 75 |
+
and Applied Mathematics, 2021
|
| 76 |
+
https://doi.org/10.1137/1.9781611976496.16
|
| 77 |
+
|
| 78 |
+
"""
|
| 79 |
+
rng = np.random.default_rng(seed)
|
| 80 |
+
if len(A.shape) != 2 or A.shape[-1] != A.shape[-2]:
|
| 81 |
+
raise ValueError("Expected A to be like a square matrix.")
|
| 82 |
+
n = A.shape[-1]
|
| 83 |
+
S = rng.choice([-1.0, +1.0], [n, m3])
|
| 84 |
+
Q, _ = qr(A.matmat(S), overwrite_a=True, mode='economic')
|
| 85 |
+
trQAQ = np.trace(Q.conj().T @ A.matmat(Q))
|
| 86 |
+
G = rng.choice([-1, +1], [n, m3])
|
| 87 |
+
right = G - Q@(Q.conj().T @ G)
|
| 88 |
+
trGAG = np.trace(right.conj().T @ A.matmat(right))
|
| 89 |
+
return trQAQ + trGAG/m3
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _ident_like(A):
|
| 93 |
+
# A compatibility function which should eventually disappear.
|
| 94 |
+
if scipy.sparse.issparse(A):
|
| 95 |
+
# Creates a sparse matrix in dia format
|
| 96 |
+
out = scipy.sparse.eye(A.shape[0], A.shape[1], dtype=A.dtype)
|
| 97 |
+
if isinstance(A, scipy.sparse.spmatrix):
|
| 98 |
+
return out.asformat(A.format)
|
| 99 |
+
return scipy.sparse.dia_array(out).asformat(A.format)
|
| 100 |
+
elif is_pydata_spmatrix(A):
|
| 101 |
+
import sparse
|
| 102 |
+
return sparse.eye(A.shape[0], A.shape[1], dtype=A.dtype)
|
| 103 |
+
elif isinstance(A, scipy.sparse.linalg.LinearOperator):
|
| 104 |
+
return IdentityOperator(A.shape, dtype=A.dtype)
|
| 105 |
+
else:
|
| 106 |
+
return np.eye(A.shape[0], A.shape[1], dtype=A.dtype)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def expm_multiply(A, B, start=None, stop=None, num=None,
|
| 110 |
+
endpoint=None, traceA=None):
|
| 111 |
+
"""
|
| 112 |
+
Compute the action of the matrix exponential of A on B.
|
| 113 |
+
|
| 114 |
+
Parameters
|
| 115 |
+
----------
|
| 116 |
+
A : transposable linear operator
|
| 117 |
+
The operator whose exponential is of interest.
|
| 118 |
+
B : ndarray
|
| 119 |
+
The matrix or vector to be multiplied by the matrix exponential of A.
|
| 120 |
+
start : scalar, optional
|
| 121 |
+
The starting time point of the sequence.
|
| 122 |
+
stop : scalar, optional
|
| 123 |
+
The end time point of the sequence, unless `endpoint` is set to False.
|
| 124 |
+
In that case, the sequence consists of all but the last of ``num + 1``
|
| 125 |
+
evenly spaced time points, so that `stop` is excluded.
|
| 126 |
+
Note that the step size changes when `endpoint` is False.
|
| 127 |
+
num : int, optional
|
| 128 |
+
Number of time points to use.
|
| 129 |
+
endpoint : bool, optional
|
| 130 |
+
If True, `stop` is the last time point. Otherwise, it is not included.
|
| 131 |
+
traceA : scalar, optional
|
| 132 |
+
Trace of `A`. If not given the trace is estimated for linear operators,
|
| 133 |
+
or calculated exactly for sparse matrices. It is used to precondition
|
| 134 |
+
`A`, thus an approximate trace is acceptable.
|
| 135 |
+
For linear operators, `traceA` should be provided to ensure performance
|
| 136 |
+
as the estimation is not guaranteed to be reliable for all cases.
|
| 137 |
+
|
| 138 |
+
.. versionadded:: 1.9.0
|
| 139 |
+
|
| 140 |
+
Returns
|
| 141 |
+
-------
|
| 142 |
+
expm_A_B : ndarray
|
| 143 |
+
The result of the action :math:`e^{t_k A} B`.
|
| 144 |
+
|
| 145 |
+
Warns
|
| 146 |
+
-----
|
| 147 |
+
UserWarning
|
| 148 |
+
If `A` is a linear operator and ``traceA=None`` (default).
|
| 149 |
+
|
| 150 |
+
Notes
|
| 151 |
+
-----
|
| 152 |
+
The optional arguments defining the sequence of evenly spaced time points
|
| 153 |
+
are compatible with the arguments of `numpy.linspace`.
|
| 154 |
+
|
| 155 |
+
The output ndarray shape is somewhat complicated so I explain it here.
|
| 156 |
+
The ndim of the output could be either 1, 2, or 3.
|
| 157 |
+
It would be 1 if you are computing the expm action on a single vector
|
| 158 |
+
at a single time point.
|
| 159 |
+
It would be 2 if you are computing the expm action on a vector
|
| 160 |
+
at multiple time points, or if you are computing the expm action
|
| 161 |
+
on a matrix at a single time point.
|
| 162 |
+
It would be 3 if you want the action on a matrix with multiple
|
| 163 |
+
columns at multiple time points.
|
| 164 |
+
If multiple time points are requested, expm_A_B[0] will always
|
| 165 |
+
be the action of the expm at the first time point,
|
| 166 |
+
regardless of whether the action is on a vector or a matrix.
|
| 167 |
+
|
| 168 |
+
References
|
| 169 |
+
----------
|
| 170 |
+
.. [1] Awad H. Al-Mohy and Nicholas J. Higham (2011)
|
| 171 |
+
"Computing the Action of the Matrix Exponential,
|
| 172 |
+
with an Application to Exponential Integrators."
|
| 173 |
+
SIAM Journal on Scientific Computing,
|
| 174 |
+
33 (2). pp. 488-511. ISSN 1064-8275
|
| 175 |
+
http://eprints.ma.man.ac.uk/1591/
|
| 176 |
+
|
| 177 |
+
.. [2] Nicholas J. Higham and Awad H. Al-Mohy (2010)
|
| 178 |
+
"Computing Matrix Functions."
|
| 179 |
+
Acta Numerica,
|
| 180 |
+
19. 159-208. ISSN 0962-4929
|
| 181 |
+
http://eprints.ma.man.ac.uk/1451/
|
| 182 |
+
|
| 183 |
+
Examples
|
| 184 |
+
--------
|
| 185 |
+
>>> import numpy as np
|
| 186 |
+
>>> from scipy.sparse import csc_matrix
|
| 187 |
+
>>> from scipy.sparse.linalg import expm, expm_multiply
|
| 188 |
+
>>> A = csc_matrix([[1, 0], [0, 1]])
|
| 189 |
+
>>> A.toarray()
|
| 190 |
+
array([[1, 0],
|
| 191 |
+
[0, 1]], dtype=int64)
|
| 192 |
+
>>> B = np.array([np.exp(-1.), np.exp(-2.)])
|
| 193 |
+
>>> B
|
| 194 |
+
array([ 0.36787944, 0.13533528])
|
| 195 |
+
>>> expm_multiply(A, B, start=1, stop=2, num=3, endpoint=True)
|
| 196 |
+
array([[ 1. , 0.36787944],
|
| 197 |
+
[ 1.64872127, 0.60653066],
|
| 198 |
+
[ 2.71828183, 1. ]])
|
| 199 |
+
>>> expm(A).dot(B) # Verify 1st timestep
|
| 200 |
+
array([ 1. , 0.36787944])
|
| 201 |
+
>>> expm(1.5*A).dot(B) # Verify 2nd timestep
|
| 202 |
+
array([ 1.64872127, 0.60653066])
|
| 203 |
+
>>> expm(2*A).dot(B) # Verify 3rd timestep
|
| 204 |
+
array([ 2.71828183, 1. ])
|
| 205 |
+
"""
|
| 206 |
+
if all(arg is None for arg in (start, stop, num, endpoint)):
|
| 207 |
+
X = _expm_multiply_simple(A, B, traceA=traceA)
|
| 208 |
+
else:
|
| 209 |
+
X, status = _expm_multiply_interval(A, B, start, stop, num,
|
| 210 |
+
endpoint, traceA=traceA)
|
| 211 |
+
return X
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _expm_multiply_simple(A, B, t=1.0, traceA=None, balance=False):
|
| 215 |
+
"""
|
| 216 |
+
Compute the action of the matrix exponential at a single time point.
|
| 217 |
+
|
| 218 |
+
Parameters
|
| 219 |
+
----------
|
| 220 |
+
A : transposable linear operator
|
| 221 |
+
The operator whose exponential is of interest.
|
| 222 |
+
B : ndarray
|
| 223 |
+
The matrix to be multiplied by the matrix exponential of A.
|
| 224 |
+
t : float
|
| 225 |
+
A time point.
|
| 226 |
+
traceA : scalar, optional
|
| 227 |
+
Trace of `A`. If not given the trace is estimated for linear operators,
|
| 228 |
+
or calculated exactly for sparse matrices. It is used to precondition
|
| 229 |
+
`A`, thus an approximate trace is acceptable
|
| 230 |
+
balance : bool
|
| 231 |
+
Indicates whether or not to apply balancing.
|
| 232 |
+
|
| 233 |
+
Returns
|
| 234 |
+
-------
|
| 235 |
+
F : ndarray
|
| 236 |
+
:math:`e^{t A} B`
|
| 237 |
+
|
| 238 |
+
Notes
|
| 239 |
+
-----
|
| 240 |
+
This is algorithm (3.2) in Al-Mohy and Higham (2011).
|
| 241 |
+
|
| 242 |
+
"""
|
| 243 |
+
if balance:
|
| 244 |
+
raise NotImplementedError
|
| 245 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
| 246 |
+
raise ValueError('expected A to be like a square matrix')
|
| 247 |
+
if A.shape[1] != B.shape[0]:
|
| 248 |
+
raise ValueError('shapes of matrices A {} and B {} are incompatible'
|
| 249 |
+
.format(A.shape, B.shape))
|
| 250 |
+
ident = _ident_like(A)
|
| 251 |
+
is_linear_operator = isinstance(A, scipy.sparse.linalg.LinearOperator)
|
| 252 |
+
n = A.shape[0]
|
| 253 |
+
if len(B.shape) == 1:
|
| 254 |
+
n0 = 1
|
| 255 |
+
elif len(B.shape) == 2:
|
| 256 |
+
n0 = B.shape[1]
|
| 257 |
+
else:
|
| 258 |
+
raise ValueError('expected B to be like a matrix or a vector')
|
| 259 |
+
u_d = 2**-53
|
| 260 |
+
tol = u_d
|
| 261 |
+
if traceA is None:
|
| 262 |
+
if is_linear_operator:
|
| 263 |
+
warn("Trace of LinearOperator not available, it will be estimated."
|
| 264 |
+
" Provide `traceA` to ensure performance.", stacklevel=3)
|
| 265 |
+
# m3=1 is bit arbitrary choice, a more accurate trace (larger m3) might
|
| 266 |
+
# speed up exponential calculation, but trace estimation is more costly
|
| 267 |
+
traceA = traceest(A, m3=1) if is_linear_operator else _trace(A)
|
| 268 |
+
mu = traceA / float(n)
|
| 269 |
+
A = A - mu * ident
|
| 270 |
+
A_1_norm = onenormest(A) if is_linear_operator else _exact_1_norm(A)
|
| 271 |
+
if t*A_1_norm == 0:
|
| 272 |
+
m_star, s = 0, 1
|
| 273 |
+
else:
|
| 274 |
+
ell = 2
|
| 275 |
+
norm_info = LazyOperatorNormInfo(t*A, A_1_norm=t*A_1_norm, ell=ell)
|
| 276 |
+
m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell)
|
| 277 |
+
return _expm_multiply_simple_core(A, B, t, mu, m_star, s, tol, balance)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def _expm_multiply_simple_core(A, B, t, mu, m_star, s, tol=None, balance=False):
|
| 281 |
+
"""
|
| 282 |
+
A helper function.
|
| 283 |
+
"""
|
| 284 |
+
if balance:
|
| 285 |
+
raise NotImplementedError
|
| 286 |
+
if tol is None:
|
| 287 |
+
u_d = 2 ** -53
|
| 288 |
+
tol = u_d
|
| 289 |
+
F = B
|
| 290 |
+
eta = np.exp(t*mu / float(s))
|
| 291 |
+
for i in range(s):
|
| 292 |
+
c1 = _exact_inf_norm(B)
|
| 293 |
+
for j in range(m_star):
|
| 294 |
+
coeff = t / float(s*(j+1))
|
| 295 |
+
B = coeff * A.dot(B)
|
| 296 |
+
c2 = _exact_inf_norm(B)
|
| 297 |
+
F = F + B
|
| 298 |
+
if c1 + c2 <= tol * _exact_inf_norm(F):
|
| 299 |
+
break
|
| 300 |
+
c1 = c2
|
| 301 |
+
F = eta * F
|
| 302 |
+
B = F
|
| 303 |
+
return F
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# This table helps to compute bounds.
|
| 307 |
+
# They seem to have been difficult to calculate, involving symbolic
|
| 308 |
+
# manipulation of equations, followed by numerical root finding.
|
| 309 |
+
_theta = {
|
| 310 |
+
# The first 30 values are from table A.3 of Computing Matrix Functions.
|
| 311 |
+
1: 2.29e-16,
|
| 312 |
+
2: 2.58e-8,
|
| 313 |
+
3: 1.39e-5,
|
| 314 |
+
4: 3.40e-4,
|
| 315 |
+
5: 2.40e-3,
|
| 316 |
+
6: 9.07e-3,
|
| 317 |
+
7: 2.38e-2,
|
| 318 |
+
8: 5.00e-2,
|
| 319 |
+
9: 8.96e-2,
|
| 320 |
+
10: 1.44e-1,
|
| 321 |
+
# 11
|
| 322 |
+
11: 2.14e-1,
|
| 323 |
+
12: 3.00e-1,
|
| 324 |
+
13: 4.00e-1,
|
| 325 |
+
14: 5.14e-1,
|
| 326 |
+
15: 6.41e-1,
|
| 327 |
+
16: 7.81e-1,
|
| 328 |
+
17: 9.31e-1,
|
| 329 |
+
18: 1.09,
|
| 330 |
+
19: 1.26,
|
| 331 |
+
20: 1.44,
|
| 332 |
+
# 21
|
| 333 |
+
21: 1.62,
|
| 334 |
+
22: 1.82,
|
| 335 |
+
23: 2.01,
|
| 336 |
+
24: 2.22,
|
| 337 |
+
25: 2.43,
|
| 338 |
+
26: 2.64,
|
| 339 |
+
27: 2.86,
|
| 340 |
+
28: 3.08,
|
| 341 |
+
29: 3.31,
|
| 342 |
+
30: 3.54,
|
| 343 |
+
# The rest are from table 3.1 of
|
| 344 |
+
# Computing the Action of the Matrix Exponential.
|
| 345 |
+
35: 4.7,
|
| 346 |
+
40: 6.0,
|
| 347 |
+
45: 7.2,
|
| 348 |
+
50: 8.5,
|
| 349 |
+
55: 9.9,
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def _onenormest_matrix_power(A, p,
|
| 354 |
+
t=2, itmax=5, compute_v=False, compute_w=False):
|
| 355 |
+
"""
|
| 356 |
+
Efficiently estimate the 1-norm of A^p.
|
| 357 |
+
|
| 358 |
+
Parameters
|
| 359 |
+
----------
|
| 360 |
+
A : ndarray
|
| 361 |
+
Matrix whose 1-norm of a power is to be computed.
|
| 362 |
+
p : int
|
| 363 |
+
Non-negative integer power.
|
| 364 |
+
t : int, optional
|
| 365 |
+
A positive parameter controlling the tradeoff between
|
| 366 |
+
accuracy versus time and memory usage.
|
| 367 |
+
Larger values take longer and use more memory
|
| 368 |
+
but give more accurate output.
|
| 369 |
+
itmax : int, optional
|
| 370 |
+
Use at most this many iterations.
|
| 371 |
+
compute_v : bool, optional
|
| 372 |
+
Request a norm-maximizing linear operator input vector if True.
|
| 373 |
+
compute_w : bool, optional
|
| 374 |
+
Request a norm-maximizing linear operator output vector if True.
|
| 375 |
+
|
| 376 |
+
Returns
|
| 377 |
+
-------
|
| 378 |
+
est : float
|
| 379 |
+
An underestimate of the 1-norm of the sparse matrix.
|
| 380 |
+
v : ndarray, optional
|
| 381 |
+
The vector such that ||Av||_1 == est*||v||_1.
|
| 382 |
+
It can be thought of as an input to the linear operator
|
| 383 |
+
that gives an output with particularly large norm.
|
| 384 |
+
w : ndarray, optional
|
| 385 |
+
The vector Av which has relatively large 1-norm.
|
| 386 |
+
It can be thought of as an output of the linear operator
|
| 387 |
+
that is relatively large in norm compared to the input.
|
| 388 |
+
|
| 389 |
+
"""
|
| 390 |
+
#XXX Eventually turn this into an API function in the _onenormest module,
|
| 391 |
+
#XXX and remove its underscore,
|
| 392 |
+
#XXX but wait until expm_multiply goes into scipy.
|
| 393 |
+
from scipy.sparse.linalg._onenormest import onenormest
|
| 394 |
+
return onenormest(aslinearoperator(A) ** p)
|
| 395 |
+
|
| 396 |
+
class LazyOperatorNormInfo:
|
| 397 |
+
"""
|
| 398 |
+
Information about an operator is lazily computed.
|
| 399 |
+
|
| 400 |
+
The information includes the exact 1-norm of the operator,
|
| 401 |
+
in addition to estimates of 1-norms of powers of the operator.
|
| 402 |
+
This uses the notation of Computing the Action (2011).
|
| 403 |
+
This class is specialized enough to probably not be of general interest
|
| 404 |
+
outside of this module.
|
| 405 |
+
|
| 406 |
+
"""
|
| 407 |
+
|
| 408 |
+
def __init__(self, A, A_1_norm=None, ell=2, scale=1):
|
| 409 |
+
"""
|
| 410 |
+
Provide the operator and some norm-related information.
|
| 411 |
+
|
| 412 |
+
Parameters
|
| 413 |
+
----------
|
| 414 |
+
A : linear operator
|
| 415 |
+
The operator of interest.
|
| 416 |
+
A_1_norm : float, optional
|
| 417 |
+
The exact 1-norm of A.
|
| 418 |
+
ell : int, optional
|
| 419 |
+
A technical parameter controlling norm estimation quality.
|
| 420 |
+
scale : int, optional
|
| 421 |
+
If specified, return the norms of scale*A instead of A.
|
| 422 |
+
|
| 423 |
+
"""
|
| 424 |
+
self._A = A
|
| 425 |
+
self._A_1_norm = A_1_norm
|
| 426 |
+
self._ell = ell
|
| 427 |
+
self._d = {}
|
| 428 |
+
self._scale = scale
|
| 429 |
+
|
| 430 |
+
def set_scale(self,scale):
|
| 431 |
+
"""
|
| 432 |
+
Set the scale parameter.
|
| 433 |
+
"""
|
| 434 |
+
self._scale = scale
|
| 435 |
+
|
| 436 |
+
def onenorm(self):
|
| 437 |
+
"""
|
| 438 |
+
Compute the exact 1-norm.
|
| 439 |
+
"""
|
| 440 |
+
if self._A_1_norm is None:
|
| 441 |
+
self._A_1_norm = _exact_1_norm(self._A)
|
| 442 |
+
return self._scale*self._A_1_norm
|
| 443 |
+
|
| 444 |
+
def d(self, p):
|
| 445 |
+
"""
|
| 446 |
+
Lazily estimate :math:`d_p(A) ~= || A^p ||^(1/p)` where :math:`||.||` is the 1-norm.
|
| 447 |
+
"""
|
| 448 |
+
if p not in self._d:
|
| 449 |
+
est = _onenormest_matrix_power(self._A, p, self._ell)
|
| 450 |
+
self._d[p] = est ** (1.0 / p)
|
| 451 |
+
return self._scale*self._d[p]
|
| 452 |
+
|
| 453 |
+
def alpha(self, p):
|
| 454 |
+
"""
|
| 455 |
+
Lazily compute max(d(p), d(p+1)).
|
| 456 |
+
"""
|
| 457 |
+
return max(self.d(p), self.d(p+1))
|
| 458 |
+
|
| 459 |
+
def _compute_cost_div_m(m, p, norm_info):
|
| 460 |
+
"""
|
| 461 |
+
A helper function for computing bounds.
|
| 462 |
+
|
| 463 |
+
This is equation (3.10).
|
| 464 |
+
It measures cost in terms of the number of required matrix products.
|
| 465 |
+
|
| 466 |
+
Parameters
|
| 467 |
+
----------
|
| 468 |
+
m : int
|
| 469 |
+
A valid key of _theta.
|
| 470 |
+
p : int
|
| 471 |
+
A matrix power.
|
| 472 |
+
norm_info : LazyOperatorNormInfo
|
| 473 |
+
Information about 1-norms of related operators.
|
| 474 |
+
|
| 475 |
+
Returns
|
| 476 |
+
-------
|
| 477 |
+
cost_div_m : int
|
| 478 |
+
Required number of matrix products divided by m.
|
| 479 |
+
|
| 480 |
+
"""
|
| 481 |
+
return int(np.ceil(norm_info.alpha(p) / _theta[m]))
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def _compute_p_max(m_max):
|
| 485 |
+
"""
|
| 486 |
+
Compute the largest positive integer p such that p*(p-1) <= m_max + 1.
|
| 487 |
+
|
| 488 |
+
Do this in a slightly dumb way, but safe and not too slow.
|
| 489 |
+
|
| 490 |
+
Parameters
|
| 491 |
+
----------
|
| 492 |
+
m_max : int
|
| 493 |
+
A count related to bounds.
|
| 494 |
+
|
| 495 |
+
"""
|
| 496 |
+
sqrt_m_max = np.sqrt(m_max)
|
| 497 |
+
p_low = int(np.floor(sqrt_m_max))
|
| 498 |
+
p_high = int(np.ceil(sqrt_m_max + 1))
|
| 499 |
+
return max(p for p in range(p_low, p_high+1) if p*(p-1) <= m_max + 1)
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def _fragment_3_1(norm_info, n0, tol, m_max=55, ell=2):
|
| 503 |
+
"""
|
| 504 |
+
A helper function for the _expm_multiply_* functions.
|
| 505 |
+
|
| 506 |
+
Parameters
|
| 507 |
+
----------
|
| 508 |
+
norm_info : LazyOperatorNormInfo
|
| 509 |
+
Information about norms of certain linear operators of interest.
|
| 510 |
+
n0 : int
|
| 511 |
+
Number of columns in the _expm_multiply_* B matrix.
|
| 512 |
+
tol : float
|
| 513 |
+
Expected to be
|
| 514 |
+
:math:`2^{-24}` for single precision or
|
| 515 |
+
:math:`2^{-53}` for double precision.
|
| 516 |
+
m_max : int
|
| 517 |
+
A value related to a bound.
|
| 518 |
+
ell : int
|
| 519 |
+
The number of columns used in the 1-norm approximation.
|
| 520 |
+
This is usually taken to be small, maybe between 1 and 5.
|
| 521 |
+
|
| 522 |
+
Returns
|
| 523 |
+
-------
|
| 524 |
+
best_m : int
|
| 525 |
+
Related to bounds for error control.
|
| 526 |
+
best_s : int
|
| 527 |
+
Amount of scaling.
|
| 528 |
+
|
| 529 |
+
Notes
|
| 530 |
+
-----
|
| 531 |
+
This is code fragment (3.1) in Al-Mohy and Higham (2011).
|
| 532 |
+
The discussion of default values for m_max and ell
|
| 533 |
+
is given between the definitions of equation (3.11)
|
| 534 |
+
and the definition of equation (3.12).
|
| 535 |
+
|
| 536 |
+
"""
|
| 537 |
+
if ell < 1:
|
| 538 |
+
raise ValueError('expected ell to be a positive integer')
|
| 539 |
+
best_m = None
|
| 540 |
+
best_s = None
|
| 541 |
+
if _condition_3_13(norm_info.onenorm(), n0, m_max, ell):
|
| 542 |
+
for m, theta in _theta.items():
|
| 543 |
+
s = int(np.ceil(norm_info.onenorm() / theta))
|
| 544 |
+
if best_m is None or m * s < best_m * best_s:
|
| 545 |
+
best_m = m
|
| 546 |
+
best_s = s
|
| 547 |
+
else:
|
| 548 |
+
# Equation (3.11).
|
| 549 |
+
for p in range(2, _compute_p_max(m_max) + 1):
|
| 550 |
+
for m in range(p*(p-1)-1, m_max+1):
|
| 551 |
+
if m in _theta:
|
| 552 |
+
s = _compute_cost_div_m(m, p, norm_info)
|
| 553 |
+
if best_m is None or m * s < best_m * best_s:
|
| 554 |
+
best_m = m
|
| 555 |
+
best_s = s
|
| 556 |
+
best_s = max(best_s, 1)
|
| 557 |
+
return best_m, best_s
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def _condition_3_13(A_1_norm, n0, m_max, ell):
|
| 561 |
+
"""
|
| 562 |
+
A helper function for the _expm_multiply_* functions.
|
| 563 |
+
|
| 564 |
+
Parameters
|
| 565 |
+
----------
|
| 566 |
+
A_1_norm : float
|
| 567 |
+
The precomputed 1-norm of A.
|
| 568 |
+
n0 : int
|
| 569 |
+
Number of columns in the _expm_multiply_* B matrix.
|
| 570 |
+
m_max : int
|
| 571 |
+
A value related to a bound.
|
| 572 |
+
ell : int
|
| 573 |
+
The number of columns used in the 1-norm approximation.
|
| 574 |
+
This is usually taken to be small, maybe between 1 and 5.
|
| 575 |
+
|
| 576 |
+
Returns
|
| 577 |
+
-------
|
| 578 |
+
value : bool
|
| 579 |
+
Indicates whether or not the condition has been met.
|
| 580 |
+
|
| 581 |
+
Notes
|
| 582 |
+
-----
|
| 583 |
+
This is condition (3.13) in Al-Mohy and Higham (2011).
|
| 584 |
+
|
| 585 |
+
"""
|
| 586 |
+
|
| 587 |
+
# This is the rhs of equation (3.12).
|
| 588 |
+
p_max = _compute_p_max(m_max)
|
| 589 |
+
a = 2 * ell * p_max * (p_max + 3)
|
| 590 |
+
|
| 591 |
+
# Evaluate the condition (3.13).
|
| 592 |
+
b = _theta[m_max] / float(n0 * m_max)
|
| 593 |
+
return A_1_norm <= a * b
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def _expm_multiply_interval(A, B, start=None, stop=None, num=None,
|
| 597 |
+
endpoint=None, traceA=None, balance=False,
|
| 598 |
+
status_only=False):
|
| 599 |
+
"""
|
| 600 |
+
Compute the action of the matrix exponential at multiple time points.
|
| 601 |
+
|
| 602 |
+
Parameters
|
| 603 |
+
----------
|
| 604 |
+
A : transposable linear operator
|
| 605 |
+
The operator whose exponential is of interest.
|
| 606 |
+
B : ndarray
|
| 607 |
+
The matrix to be multiplied by the matrix exponential of A.
|
| 608 |
+
start : scalar, optional
|
| 609 |
+
The starting time point of the sequence.
|
| 610 |
+
stop : scalar, optional
|
| 611 |
+
The end time point of the sequence, unless `endpoint` is set to False.
|
| 612 |
+
In that case, the sequence consists of all but the last of ``num + 1``
|
| 613 |
+
evenly spaced time points, so that `stop` is excluded.
|
| 614 |
+
Note that the step size changes when `endpoint` is False.
|
| 615 |
+
num : int, optional
|
| 616 |
+
Number of time points to use.
|
| 617 |
+
traceA : scalar, optional
|
| 618 |
+
Trace of `A`. If not given the trace is estimated for linear operators,
|
| 619 |
+
or calculated exactly for sparse matrices. It is used to precondition
|
| 620 |
+
`A`, thus an approximate trace is acceptable
|
| 621 |
+
endpoint : bool, optional
|
| 622 |
+
If True, `stop` is the last time point. Otherwise, it is not included.
|
| 623 |
+
balance : bool
|
| 624 |
+
Indicates whether or not to apply balancing.
|
| 625 |
+
status_only : bool
|
| 626 |
+
A flag that is set to True for some debugging and testing operations.
|
| 627 |
+
|
| 628 |
+
Returns
|
| 629 |
+
-------
|
| 630 |
+
F : ndarray
|
| 631 |
+
:math:`e^{t_k A} B`
|
| 632 |
+
status : int
|
| 633 |
+
An integer status for testing and debugging.
|
| 634 |
+
|
| 635 |
+
Notes
|
| 636 |
+
-----
|
| 637 |
+
This is algorithm (5.2) in Al-Mohy and Higham (2011).
|
| 638 |
+
|
| 639 |
+
There seems to be a typo, where line 15 of the algorithm should be
|
| 640 |
+
moved to line 6.5 (between lines 6 and 7).
|
| 641 |
+
|
| 642 |
+
"""
|
| 643 |
+
if balance:
|
| 644 |
+
raise NotImplementedError
|
| 645 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
| 646 |
+
raise ValueError('expected A to be like a square matrix')
|
| 647 |
+
if A.shape[1] != B.shape[0]:
|
| 648 |
+
raise ValueError('shapes of matrices A {} and B {} are incompatible'
|
| 649 |
+
.format(A.shape, B.shape))
|
| 650 |
+
ident = _ident_like(A)
|
| 651 |
+
is_linear_operator = isinstance(A, scipy.sparse.linalg.LinearOperator)
|
| 652 |
+
n = A.shape[0]
|
| 653 |
+
if len(B.shape) == 1:
|
| 654 |
+
n0 = 1
|
| 655 |
+
elif len(B.shape) == 2:
|
| 656 |
+
n0 = B.shape[1]
|
| 657 |
+
else:
|
| 658 |
+
raise ValueError('expected B to be like a matrix or a vector')
|
| 659 |
+
u_d = 2**-53
|
| 660 |
+
tol = u_d
|
| 661 |
+
if traceA is None:
|
| 662 |
+
if is_linear_operator:
|
| 663 |
+
warn("Trace of LinearOperator not available, it will be estimated."
|
| 664 |
+
" Provide `traceA` to ensure performance.", stacklevel=3)
|
| 665 |
+
# m3=5 is bit arbitrary choice, a more accurate trace (larger m3) might
|
| 666 |
+
# speed up exponential calculation, but trace estimation is also costly
|
| 667 |
+
# an educated guess would need to consider the number of time points
|
| 668 |
+
traceA = traceest(A, m3=5) if is_linear_operator else _trace(A)
|
| 669 |
+
mu = traceA / float(n)
|
| 670 |
+
|
| 671 |
+
# Get the linspace samples, attempting to preserve the linspace defaults.
|
| 672 |
+
linspace_kwargs = {'retstep': True}
|
| 673 |
+
if num is not None:
|
| 674 |
+
linspace_kwargs['num'] = num
|
| 675 |
+
if endpoint is not None:
|
| 676 |
+
linspace_kwargs['endpoint'] = endpoint
|
| 677 |
+
samples, step = np.linspace(start, stop, **linspace_kwargs)
|
| 678 |
+
|
| 679 |
+
# Convert the linspace output to the notation used by the publication.
|
| 680 |
+
nsamples = len(samples)
|
| 681 |
+
if nsamples < 2:
|
| 682 |
+
raise ValueError('at least two time points are required')
|
| 683 |
+
q = nsamples - 1
|
| 684 |
+
h = step
|
| 685 |
+
t_0 = samples[0]
|
| 686 |
+
t_q = samples[q]
|
| 687 |
+
|
| 688 |
+
# Define the output ndarray.
|
| 689 |
+
# Use an ndim=3 shape, such that the last two indices
|
| 690 |
+
# are the ones that may be involved in level 3 BLAS operations.
|
| 691 |
+
X_shape = (nsamples,) + B.shape
|
| 692 |
+
X = np.empty(X_shape, dtype=np.result_type(A.dtype, B.dtype, float))
|
| 693 |
+
t = t_q - t_0
|
| 694 |
+
A = A - mu * ident
|
| 695 |
+
A_1_norm = onenormest(A) if is_linear_operator else _exact_1_norm(A)
|
| 696 |
+
ell = 2
|
| 697 |
+
norm_info = LazyOperatorNormInfo(t*A, A_1_norm=t*A_1_norm, ell=ell)
|
| 698 |
+
if t*A_1_norm == 0:
|
| 699 |
+
m_star, s = 0, 1
|
| 700 |
+
else:
|
| 701 |
+
m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell)
|
| 702 |
+
|
| 703 |
+
# Compute the expm action up to the initial time point.
|
| 704 |
+
X[0] = _expm_multiply_simple_core(A, B, t_0, mu, m_star, s)
|
| 705 |
+
|
| 706 |
+
# Compute the expm action at the rest of the time points.
|
| 707 |
+
if q <= s:
|
| 708 |
+
if status_only:
|
| 709 |
+
return 0
|
| 710 |
+
else:
|
| 711 |
+
return _expm_multiply_interval_core_0(A, X,
|
| 712 |
+
h, mu, q, norm_info, tol, ell,n0)
|
| 713 |
+
elif not (q % s):
|
| 714 |
+
if status_only:
|
| 715 |
+
return 1
|
| 716 |
+
else:
|
| 717 |
+
return _expm_multiply_interval_core_1(A, X,
|
| 718 |
+
h, mu, m_star, s, q, tol)
|
| 719 |
+
elif (q % s):
|
| 720 |
+
if status_only:
|
| 721 |
+
return 2
|
| 722 |
+
else:
|
| 723 |
+
return _expm_multiply_interval_core_2(A, X,
|
| 724 |
+
h, mu, m_star, s, q, tol)
|
| 725 |
+
else:
|
| 726 |
+
raise Exception('internal error')
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def _expm_multiply_interval_core_0(A, X, h, mu, q, norm_info, tol, ell, n0):
|
| 730 |
+
"""
|
| 731 |
+
A helper function, for the case q <= s.
|
| 732 |
+
"""
|
| 733 |
+
|
| 734 |
+
# Compute the new values of m_star and s which should be applied
|
| 735 |
+
# over intervals of size t/q
|
| 736 |
+
if norm_info.onenorm() == 0:
|
| 737 |
+
m_star, s = 0, 1
|
| 738 |
+
else:
|
| 739 |
+
norm_info.set_scale(1./q)
|
| 740 |
+
m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell)
|
| 741 |
+
norm_info.set_scale(1)
|
| 742 |
+
|
| 743 |
+
for k in range(q):
|
| 744 |
+
X[k+1] = _expm_multiply_simple_core(A, X[k], h, mu, m_star, s)
|
| 745 |
+
return X, 0
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
def _expm_multiply_interval_core_1(A, X, h, mu, m_star, s, q, tol):
|
| 749 |
+
"""
|
| 750 |
+
A helper function, for the case q > s and q % s == 0.
|
| 751 |
+
"""
|
| 752 |
+
d = q // s
|
| 753 |
+
input_shape = X.shape[1:]
|
| 754 |
+
K_shape = (m_star + 1, ) + input_shape
|
| 755 |
+
K = np.empty(K_shape, dtype=X.dtype)
|
| 756 |
+
for i in range(s):
|
| 757 |
+
Z = X[i*d]
|
| 758 |
+
K[0] = Z
|
| 759 |
+
high_p = 0
|
| 760 |
+
for k in range(1, d+1):
|
| 761 |
+
F = K[0]
|
| 762 |
+
c1 = _exact_inf_norm(F)
|
| 763 |
+
for p in range(1, m_star+1):
|
| 764 |
+
if p > high_p:
|
| 765 |
+
K[p] = h * A.dot(K[p-1]) / float(p)
|
| 766 |
+
coeff = float(pow(k, p))
|
| 767 |
+
F = F + coeff * K[p]
|
| 768 |
+
inf_norm_K_p_1 = _exact_inf_norm(K[p])
|
| 769 |
+
c2 = coeff * inf_norm_K_p_1
|
| 770 |
+
if c1 + c2 <= tol * _exact_inf_norm(F):
|
| 771 |
+
break
|
| 772 |
+
c1 = c2
|
| 773 |
+
X[k + i*d] = np.exp(k*h*mu) * F
|
| 774 |
+
return X, 1
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
def _expm_multiply_interval_core_2(A, X, h, mu, m_star, s, q, tol):
|
| 778 |
+
"""
|
| 779 |
+
A helper function, for the case q > s and q % s > 0.
|
| 780 |
+
"""
|
| 781 |
+
d = q // s
|
| 782 |
+
j = q // d
|
| 783 |
+
r = q - d * j
|
| 784 |
+
input_shape = X.shape[1:]
|
| 785 |
+
K_shape = (m_star + 1, ) + input_shape
|
| 786 |
+
K = np.empty(K_shape, dtype=X.dtype)
|
| 787 |
+
for i in range(j + 1):
|
| 788 |
+
Z = X[i*d]
|
| 789 |
+
K[0] = Z
|
| 790 |
+
high_p = 0
|
| 791 |
+
if i < j:
|
| 792 |
+
effective_d = d
|
| 793 |
+
else:
|
| 794 |
+
effective_d = r
|
| 795 |
+
for k in range(1, effective_d+1):
|
| 796 |
+
F = K[0]
|
| 797 |
+
c1 = _exact_inf_norm(F)
|
| 798 |
+
for p in range(1, m_star+1):
|
| 799 |
+
if p == high_p + 1:
|
| 800 |
+
K[p] = h * A.dot(K[p-1]) / float(p)
|
| 801 |
+
high_p = p
|
| 802 |
+
coeff = float(pow(k, p))
|
| 803 |
+
F = F + coeff * K[p]
|
| 804 |
+
inf_norm_K_p_1 =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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Sparse matrix functions
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
#
|
| 6 |
+
# Authors: Travis Oliphant, March 2002
|
| 7 |
+
# Anthony Scopatz, August 2012 (Sparse Updates)
|
| 8 |
+
# Jake Vanderplas, August 2012 (Sparse Updates)
|
| 9 |
+
#
|
| 10 |
+
|
| 11 |
+
__all__ = ['expm', 'inv', 'matrix_power']
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from scipy.linalg._basic import solve, solve_triangular
|
| 15 |
+
|
| 16 |
+
from scipy.sparse._base import issparse
|
| 17 |
+
from scipy.sparse.linalg import spsolve
|
| 18 |
+
from scipy.sparse._sputils import is_pydata_spmatrix, isintlike
|
| 19 |
+
|
| 20 |
+
import scipy.sparse
|
| 21 |
+
import scipy.sparse.linalg
|
| 22 |
+
from scipy.sparse.linalg._interface import LinearOperator
|
| 23 |
+
from scipy.sparse._construct import eye
|
| 24 |
+
|
| 25 |
+
from ._expm_multiply import _ident_like, _exact_1_norm as _onenorm
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
UPPER_TRIANGULAR = 'upper_triangular'
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def inv(A):
|
| 32 |
+
"""
|
| 33 |
+
Compute the inverse of a sparse matrix
|
| 34 |
+
|
| 35 |
+
Parameters
|
| 36 |
+
----------
|
| 37 |
+
A : (M, M) sparse matrix
|
| 38 |
+
square matrix to be inverted
|
| 39 |
+
|
| 40 |
+
Returns
|
| 41 |
+
-------
|
| 42 |
+
Ainv : (M, M) sparse matrix
|
| 43 |
+
inverse of `A`
|
| 44 |
+
|
| 45 |
+
Notes
|
| 46 |
+
-----
|
| 47 |
+
This computes the sparse inverse of `A`. If the inverse of `A` is expected
|
| 48 |
+
to be non-sparse, it will likely be faster to convert `A` to dense and use
|
| 49 |
+
`scipy.linalg.inv`.
|
| 50 |
+
|
| 51 |
+
Examples
|
| 52 |
+
--------
|
| 53 |
+
>>> from scipy.sparse import csc_matrix
|
| 54 |
+
>>> from scipy.sparse.linalg import inv
|
| 55 |
+
>>> A = csc_matrix([[1., 0.], [1., 2.]])
|
| 56 |
+
>>> Ainv = inv(A)
|
| 57 |
+
>>> Ainv
|
| 58 |
+
<Compressed Sparse Column sparse matrix of dtype 'float64'
|
| 59 |
+
with 3 stored elements and shape (2, 2)>
|
| 60 |
+
>>> A.dot(Ainv)
|
| 61 |
+
<Compressed Sparse Column sparse matrix of dtype 'float64'
|
| 62 |
+
with 2 stored elements and shape (2, 2)>
|
| 63 |
+
>>> A.dot(Ainv).toarray()
|
| 64 |
+
array([[ 1., 0.],
|
| 65 |
+
[ 0., 1.]])
|
| 66 |
+
|
| 67 |
+
.. versionadded:: 0.12.0
|
| 68 |
+
|
| 69 |
+
"""
|
| 70 |
+
# Check input
|
| 71 |
+
if not (scipy.sparse.issparse(A) or is_pydata_spmatrix(A)):
|
| 72 |
+
raise TypeError('Input must be a sparse matrix')
|
| 73 |
+
|
| 74 |
+
# Use sparse direct solver to solve "AX = I" accurately
|
| 75 |
+
I = _ident_like(A)
|
| 76 |
+
Ainv = spsolve(A, I)
|
| 77 |
+
return Ainv
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _onenorm_matrix_power_nnm(A, p):
|
| 81 |
+
"""
|
| 82 |
+
Compute the 1-norm of a non-negative integer power of a non-negative matrix.
|
| 83 |
+
|
| 84 |
+
Parameters
|
| 85 |
+
----------
|
| 86 |
+
A : a square ndarray or matrix or sparse matrix
|
| 87 |
+
Input matrix with non-negative entries.
|
| 88 |
+
p : non-negative integer
|
| 89 |
+
The power to which the matrix is to be raised.
|
| 90 |
+
|
| 91 |
+
Returns
|
| 92 |
+
-------
|
| 93 |
+
out : float
|
| 94 |
+
The 1-norm of the matrix power p of A.
|
| 95 |
+
|
| 96 |
+
"""
|
| 97 |
+
# Check input
|
| 98 |
+
if int(p) != p or p < 0:
|
| 99 |
+
raise ValueError('expected non-negative integer p')
|
| 100 |
+
p = int(p)
|
| 101 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
| 102 |
+
raise ValueError('expected A to be like a square matrix')
|
| 103 |
+
|
| 104 |
+
# Explicitly make a column vector so that this works when A is a
|
| 105 |
+
# numpy matrix (in addition to ndarray and sparse matrix).
|
| 106 |
+
v = np.ones((A.shape[0], 1), dtype=float)
|
| 107 |
+
M = A.T
|
| 108 |
+
for i in range(p):
|
| 109 |
+
v = M.dot(v)
|
| 110 |
+
return np.max(v)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _is_upper_triangular(A):
|
| 114 |
+
# This function could possibly be of wider interest.
|
| 115 |
+
if issparse(A):
|
| 116 |
+
lower_part = scipy.sparse.tril(A, -1)
|
| 117 |
+
# Check structural upper triangularity,
|
| 118 |
+
# then coincidental upper triangularity if needed.
|
| 119 |
+
return lower_part.nnz == 0 or lower_part.count_nonzero() == 0
|
| 120 |
+
elif is_pydata_spmatrix(A):
|
| 121 |
+
import sparse
|
| 122 |
+
lower_part = sparse.tril(A, -1)
|
| 123 |
+
return lower_part.nnz == 0
|
| 124 |
+
else:
|
| 125 |
+
return not np.tril(A, -1).any()
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _smart_matrix_product(A, B, alpha=None, structure=None):
|
| 129 |
+
"""
|
| 130 |
+
A matrix product that knows about sparse and structured matrices.
|
| 131 |
+
|
| 132 |
+
Parameters
|
| 133 |
+
----------
|
| 134 |
+
A : 2d ndarray
|
| 135 |
+
First matrix.
|
| 136 |
+
B : 2d ndarray
|
| 137 |
+
Second matrix.
|
| 138 |
+
alpha : float
|
| 139 |
+
The matrix product will be scaled by this constant.
|
| 140 |
+
structure : str, optional
|
| 141 |
+
A string describing the structure of both matrices `A` and `B`.
|
| 142 |
+
Only `upper_triangular` is currently supported.
|
| 143 |
+
|
| 144 |
+
Returns
|
| 145 |
+
-------
|
| 146 |
+
M : 2d ndarray
|
| 147 |
+
Matrix product of A and B.
|
| 148 |
+
|
| 149 |
+
"""
|
| 150 |
+
if len(A.shape) != 2:
|
| 151 |
+
raise ValueError('expected A to be a rectangular matrix')
|
| 152 |
+
if len(B.shape) != 2:
|
| 153 |
+
raise ValueError('expected B to be a rectangular matrix')
|
| 154 |
+
f = None
|
| 155 |
+
if structure == UPPER_TRIANGULAR:
|
| 156 |
+
if (not issparse(A) and not issparse(B)
|
| 157 |
+
and not is_pydata_spmatrix(A) and not is_pydata_spmatrix(B)):
|
| 158 |
+
f, = scipy.linalg.get_blas_funcs(('trmm',), (A, B))
|
| 159 |
+
if f is not None:
|
| 160 |
+
if alpha is None:
|
| 161 |
+
alpha = 1.
|
| 162 |
+
out = f(alpha, A, B)
|
| 163 |
+
else:
|
| 164 |
+
if alpha is None:
|
| 165 |
+
out = A.dot(B)
|
| 166 |
+
else:
|
| 167 |
+
out = alpha * A.dot(B)
|
| 168 |
+
return out
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class MatrixPowerOperator(LinearOperator):
|
| 172 |
+
|
| 173 |
+
def __init__(self, A, p, structure=None):
|
| 174 |
+
if A.ndim != 2 or A.shape[0] != A.shape[1]:
|
| 175 |
+
raise ValueError('expected A to be like a square matrix')
|
| 176 |
+
if p < 0:
|
| 177 |
+
raise ValueError('expected p to be a non-negative integer')
|
| 178 |
+
self._A = A
|
| 179 |
+
self._p = p
|
| 180 |
+
self._structure = structure
|
| 181 |
+
self.dtype = A.dtype
|
| 182 |
+
self.ndim = A.ndim
|
| 183 |
+
self.shape = A.shape
|
| 184 |
+
|
| 185 |
+
def _matvec(self, x):
|
| 186 |
+
for i in range(self._p):
|
| 187 |
+
x = self._A.dot(x)
|
| 188 |
+
return x
|
| 189 |
+
|
| 190 |
+
def _rmatvec(self, x):
|
| 191 |
+
A_T = self._A.T
|
| 192 |
+
x = x.ravel()
|
| 193 |
+
for i in range(self._p):
|
| 194 |
+
x = A_T.dot(x)
|
| 195 |
+
return x
|
| 196 |
+
|
| 197 |
+
def _matmat(self, X):
|
| 198 |
+
for i in range(self._p):
|
| 199 |
+
X = _smart_matrix_product(self._A, X, structure=self._structure)
|
| 200 |
+
return X
|
| 201 |
+
|
| 202 |
+
@property
|
| 203 |
+
def T(self):
|
| 204 |
+
return MatrixPowerOperator(self._A.T, self._p)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class ProductOperator(LinearOperator):
|
| 208 |
+
"""
|
| 209 |
+
For now, this is limited to products of multiple square matrices.
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
def __init__(self, *args, **kwargs):
|
| 213 |
+
self._structure = kwargs.get('structure', None)
|
| 214 |
+
for A in args:
|
| 215 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
| 216 |
+
raise ValueError(
|
| 217 |
+
'For now, the ProductOperator implementation is '
|
| 218 |
+
'limited to the product of multiple square matrices.')
|
| 219 |
+
if args:
|
| 220 |
+
n = args[0].shape[0]
|
| 221 |
+
for A in args:
|
| 222 |
+
for d in A.shape:
|
| 223 |
+
if d != n:
|
| 224 |
+
raise ValueError(
|
| 225 |
+
'The square matrices of the ProductOperator '
|
| 226 |
+
'must all have the same shape.')
|
| 227 |
+
self.shape = (n, n)
|
| 228 |
+
self.ndim = len(self.shape)
|
| 229 |
+
self.dtype = np.result_type(*[x.dtype for x in args])
|
| 230 |
+
self._operator_sequence = args
|
| 231 |
+
|
| 232 |
+
def _matvec(self, x):
|
| 233 |
+
for A in reversed(self._operator_sequence):
|
| 234 |
+
x = A.dot(x)
|
| 235 |
+
return x
|
| 236 |
+
|
| 237 |
+
def _rmatvec(self, x):
|
| 238 |
+
x = x.ravel()
|
| 239 |
+
for A in self._operator_sequence:
|
| 240 |
+
x = A.T.dot(x)
|
| 241 |
+
return x
|
| 242 |
+
|
| 243 |
+
def _matmat(self, X):
|
| 244 |
+
for A in reversed(self._operator_sequence):
|
| 245 |
+
X = _smart_matrix_product(A, X, structure=self._structure)
|
| 246 |
+
return X
|
| 247 |
+
|
| 248 |
+
@property
|
| 249 |
+
def T(self):
|
| 250 |
+
T_args = [A.T for A in reversed(self._operator_sequence)]
|
| 251 |
+
return ProductOperator(*T_args)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _onenormest_matrix_power(A, p,
|
| 255 |
+
t=2, itmax=5, compute_v=False, compute_w=False, structure=None):
|
| 256 |
+
"""
|
| 257 |
+
Efficiently estimate the 1-norm of A^p.
|
| 258 |
+
|
| 259 |
+
Parameters
|
| 260 |
+
----------
|
| 261 |
+
A : ndarray
|
| 262 |
+
Matrix whose 1-norm of a power is to be computed.
|
| 263 |
+
p : int
|
| 264 |
+
Non-negative integer power.
|
| 265 |
+
t : int, optional
|
| 266 |
+
A positive parameter controlling the tradeoff between
|
| 267 |
+
accuracy versus time and memory usage.
|
| 268 |
+
Larger values take longer and use more memory
|
| 269 |
+
but give more accurate output.
|
| 270 |
+
itmax : int, optional
|
| 271 |
+
Use at most this many iterations.
|
| 272 |
+
compute_v : bool, optional
|
| 273 |
+
Request a norm-maximizing linear operator input vector if True.
|
| 274 |
+
compute_w : bool, optional
|
| 275 |
+
Request a norm-maximizing linear operator output vector if True.
|
| 276 |
+
|
| 277 |
+
Returns
|
| 278 |
+
-------
|
| 279 |
+
est : float
|
| 280 |
+
An underestimate of the 1-norm of the sparse matrix.
|
| 281 |
+
v : ndarray, optional
|
| 282 |
+
The vector such that ||Av||_1 == est*||v||_1.
|
| 283 |
+
It can be thought of as an input to the linear operator
|
| 284 |
+
that gives an output with particularly large norm.
|
| 285 |
+
w : ndarray, optional
|
| 286 |
+
The vector Av which has relatively large 1-norm.
|
| 287 |
+
It can be thought of as an output of the linear operator
|
| 288 |
+
that is relatively large in norm compared to the input.
|
| 289 |
+
|
| 290 |
+
"""
|
| 291 |
+
return scipy.sparse.linalg.onenormest(
|
| 292 |
+
MatrixPowerOperator(A, p, structure=structure))
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _onenormest_product(operator_seq,
|
| 296 |
+
t=2, itmax=5, compute_v=False, compute_w=False, structure=None):
|
| 297 |
+
"""
|
| 298 |
+
Efficiently estimate the 1-norm of the matrix product of the args.
|
| 299 |
+
|
| 300 |
+
Parameters
|
| 301 |
+
----------
|
| 302 |
+
operator_seq : linear operator sequence
|
| 303 |
+
Matrices whose 1-norm of product is to be computed.
|
| 304 |
+
t : int, optional
|
| 305 |
+
A positive parameter controlling the tradeoff between
|
| 306 |
+
accuracy versus time and memory usage.
|
| 307 |
+
Larger values take longer and use more memory
|
| 308 |
+
but give more accurate output.
|
| 309 |
+
itmax : int, optional
|
| 310 |
+
Use at most this many iterations.
|
| 311 |
+
compute_v : bool, optional
|
| 312 |
+
Request a norm-maximizing linear operator input vector if True.
|
| 313 |
+
compute_w : bool, optional
|
| 314 |
+
Request a norm-maximizing linear operator output vector if True.
|
| 315 |
+
structure : str, optional
|
| 316 |
+
A string describing the structure of all operators.
|
| 317 |
+
Only `upper_triangular` is currently supported.
|
| 318 |
+
|
| 319 |
+
Returns
|
| 320 |
+
-------
|
| 321 |
+
est : float
|
| 322 |
+
An underestimate of the 1-norm of the sparse matrix.
|
| 323 |
+
v : ndarray, optional
|
| 324 |
+
The vector such that ||Av||_1 == est*||v||_1.
|
| 325 |
+
It can be thought of as an input to the linear operator
|
| 326 |
+
that gives an output with particularly large norm.
|
| 327 |
+
w : ndarray, optional
|
| 328 |
+
The vector Av which has relatively large 1-norm.
|
| 329 |
+
It can be thought of as an output of the linear operator
|
| 330 |
+
that is relatively large in norm compared to the input.
|
| 331 |
+
|
| 332 |
+
"""
|
| 333 |
+
return scipy.sparse.linalg.onenormest(
|
| 334 |
+
ProductOperator(*operator_seq, structure=structure))
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class _ExpmPadeHelper:
|
| 338 |
+
"""
|
| 339 |
+
Help lazily evaluate a matrix exponential.
|
| 340 |
+
|
| 341 |
+
The idea is to not do more work than we need for high expm precision,
|
| 342 |
+
so we lazily compute matrix powers and store or precompute
|
| 343 |
+
other properties of the matrix.
|
| 344 |
+
|
| 345 |
+
"""
|
| 346 |
+
|
| 347 |
+
def __init__(self, A, structure=None, use_exact_onenorm=False):
|
| 348 |
+
"""
|
| 349 |
+
Initialize the object.
|
| 350 |
+
|
| 351 |
+
Parameters
|
| 352 |
+
----------
|
| 353 |
+
A : a dense or sparse square numpy matrix or ndarray
|
| 354 |
+
The matrix to be exponentiated.
|
| 355 |
+
structure : str, optional
|
| 356 |
+
A string describing the structure of matrix `A`.
|
| 357 |
+
Only `upper_triangular` is currently supported.
|
| 358 |
+
use_exact_onenorm : bool, optional
|
| 359 |
+
If True then only the exact one-norm of matrix powers and products
|
| 360 |
+
will be used. Otherwise, the one-norm of powers and products
|
| 361 |
+
may initially be estimated.
|
| 362 |
+
"""
|
| 363 |
+
self.A = A
|
| 364 |
+
self._A2 = None
|
| 365 |
+
self._A4 = None
|
| 366 |
+
self._A6 = None
|
| 367 |
+
self._A8 = None
|
| 368 |
+
self._A10 = None
|
| 369 |
+
self._d4_exact = None
|
| 370 |
+
self._d6_exact = None
|
| 371 |
+
self._d8_exact = None
|
| 372 |
+
self._d10_exact = None
|
| 373 |
+
self._d4_approx = None
|
| 374 |
+
self._d6_approx = None
|
| 375 |
+
self._d8_approx = None
|
| 376 |
+
self._d10_approx = None
|
| 377 |
+
self.ident = _ident_like(A)
|
| 378 |
+
self.structure = structure
|
| 379 |
+
self.use_exact_onenorm = use_exact_onenorm
|
| 380 |
+
|
| 381 |
+
@property
|
| 382 |
+
def A2(self):
|
| 383 |
+
if self._A2 is None:
|
| 384 |
+
self._A2 = _smart_matrix_product(
|
| 385 |
+
self.A, self.A, structure=self.structure)
|
| 386 |
+
return self._A2
|
| 387 |
+
|
| 388 |
+
@property
|
| 389 |
+
def A4(self):
|
| 390 |
+
if self._A4 is None:
|
| 391 |
+
self._A4 = _smart_matrix_product(
|
| 392 |
+
self.A2, self.A2, structure=self.structure)
|
| 393 |
+
return self._A4
|
| 394 |
+
|
| 395 |
+
@property
|
| 396 |
+
def A6(self):
|
| 397 |
+
if self._A6 is None:
|
| 398 |
+
self._A6 = _smart_matrix_product(
|
| 399 |
+
self.A4, self.A2, structure=self.structure)
|
| 400 |
+
return self._A6
|
| 401 |
+
|
| 402 |
+
@property
|
| 403 |
+
def A8(self):
|
| 404 |
+
if self._A8 is None:
|
| 405 |
+
self._A8 = _smart_matrix_product(
|
| 406 |
+
self.A6, self.A2, structure=self.structure)
|
| 407 |
+
return self._A8
|
| 408 |
+
|
| 409 |
+
@property
|
| 410 |
+
def A10(self):
|
| 411 |
+
if self._A10 is None:
|
| 412 |
+
self._A10 = _smart_matrix_product(
|
| 413 |
+
self.A4, self.A6, structure=self.structure)
|
| 414 |
+
return self._A10
|
| 415 |
+
|
| 416 |
+
@property
|
| 417 |
+
def d4_tight(self):
|
| 418 |
+
if self._d4_exact is None:
|
| 419 |
+
self._d4_exact = _onenorm(self.A4)**(1/4.)
|
| 420 |
+
return self._d4_exact
|
| 421 |
+
|
| 422 |
+
@property
|
| 423 |
+
def d6_tight(self):
|
| 424 |
+
if self._d6_exact is None:
|
| 425 |
+
self._d6_exact = _onenorm(self.A6)**(1/6.)
|
| 426 |
+
return self._d6_exact
|
| 427 |
+
|
| 428 |
+
@property
|
| 429 |
+
def d8_tight(self):
|
| 430 |
+
if self._d8_exact is None:
|
| 431 |
+
self._d8_exact = _onenorm(self.A8)**(1/8.)
|
| 432 |
+
return self._d8_exact
|
| 433 |
+
|
| 434 |
+
@property
|
| 435 |
+
def d10_tight(self):
|
| 436 |
+
if self._d10_exact is None:
|
| 437 |
+
self._d10_exact = _onenorm(self.A10)**(1/10.)
|
| 438 |
+
return self._d10_exact
|
| 439 |
+
|
| 440 |
+
@property
|
| 441 |
+
def d4_loose(self):
|
| 442 |
+
if self.use_exact_onenorm:
|
| 443 |
+
return self.d4_tight
|
| 444 |
+
if self._d4_exact is not None:
|
| 445 |
+
return self._d4_exact
|
| 446 |
+
else:
|
| 447 |
+
if self._d4_approx is None:
|
| 448 |
+
self._d4_approx = _onenormest_matrix_power(self.A2, 2,
|
| 449 |
+
structure=self.structure)**(1/4.)
|
| 450 |
+
return self._d4_approx
|
| 451 |
+
|
| 452 |
+
@property
|
| 453 |
+
def d6_loose(self):
|
| 454 |
+
if self.use_exact_onenorm:
|
| 455 |
+
return self.d6_tight
|
| 456 |
+
if self._d6_exact is not None:
|
| 457 |
+
return self._d6_exact
|
| 458 |
+
else:
|
| 459 |
+
if self._d6_approx is None:
|
| 460 |
+
self._d6_approx = _onenormest_matrix_power(self.A2, 3,
|
| 461 |
+
structure=self.structure)**(1/6.)
|
| 462 |
+
return self._d6_approx
|
| 463 |
+
|
| 464 |
+
@property
|
| 465 |
+
def d8_loose(self):
|
| 466 |
+
if self.use_exact_onenorm:
|
| 467 |
+
return self.d8_tight
|
| 468 |
+
if self._d8_exact is not None:
|
| 469 |
+
return self._d8_exact
|
| 470 |
+
else:
|
| 471 |
+
if self._d8_approx is None:
|
| 472 |
+
self._d8_approx = _onenormest_matrix_power(self.A4, 2,
|
| 473 |
+
structure=self.structure)**(1/8.)
|
| 474 |
+
return self._d8_approx
|
| 475 |
+
|
| 476 |
+
@property
|
| 477 |
+
def d10_loose(self):
|
| 478 |
+
if self.use_exact_onenorm:
|
| 479 |
+
return self.d10_tight
|
| 480 |
+
if self._d10_exact is not None:
|
| 481 |
+
return self._d10_exact
|
| 482 |
+
else:
|
| 483 |
+
if self._d10_approx is None:
|
| 484 |
+
self._d10_approx = _onenormest_product((self.A4, self.A6),
|
| 485 |
+
structure=self.structure)**(1/10.)
|
| 486 |
+
return self._d10_approx
|
| 487 |
+
|
| 488 |
+
def pade3(self):
|
| 489 |
+
b = (120., 60., 12., 1.)
|
| 490 |
+
U = _smart_matrix_product(self.A,
|
| 491 |
+
b[3]*self.A2 + b[1]*self.ident,
|
| 492 |
+
structure=self.structure)
|
| 493 |
+
V = b[2]*self.A2 + b[0]*self.ident
|
| 494 |
+
return U, V
|
| 495 |
+
|
| 496 |
+
def pade5(self):
|
| 497 |
+
b = (30240., 15120., 3360., 420., 30., 1.)
|
| 498 |
+
U = _smart_matrix_product(self.A,
|
| 499 |
+
b[5]*self.A4 + b[3]*self.A2 + b[1]*self.ident,
|
| 500 |
+
structure=self.structure)
|
| 501 |
+
V = b[4]*self.A4 + b[2]*self.A2 + b[0]*self.ident
|
| 502 |
+
return U, V
|
| 503 |
+
|
| 504 |
+
def pade7(self):
|
| 505 |
+
b = (17297280., 8648640., 1995840., 277200., 25200., 1512., 56., 1.)
|
| 506 |
+
U = _smart_matrix_product(self.A,
|
| 507 |
+
b[7]*self.A6 + b[5]*self.A4 + b[3]*self.A2 + b[1]*self.ident,
|
| 508 |
+
structure=self.structure)
|
| 509 |
+
V = b[6]*self.A6 + b[4]*self.A4 + b[2]*self.A2 + b[0]*self.ident
|
| 510 |
+
return U, V
|
| 511 |
+
|
| 512 |
+
def pade9(self):
|
| 513 |
+
b = (17643225600., 8821612800., 2075673600., 302702400., 30270240.,
|
| 514 |
+
2162160., 110880., 3960., 90., 1.)
|
| 515 |
+
U = _smart_matrix_product(self.A,
|
| 516 |
+
(b[9]*self.A8 + b[7]*self.A6 + b[5]*self.A4 +
|
| 517 |
+
b[3]*self.A2 + b[1]*self.ident),
|
| 518 |
+
structure=self.structure)
|
| 519 |
+
V = (b[8]*self.A8 + b[6]*self.A6 + b[4]*self.A4 +
|
| 520 |
+
b[2]*self.A2 + b[0]*self.ident)
|
| 521 |
+
return U, V
|
| 522 |
+
|
| 523 |
+
def pade13_scaled(self, s):
|
| 524 |
+
b = (64764752532480000., 32382376266240000., 7771770303897600.,
|
| 525 |
+
1187353796428800., 129060195264000., 10559470521600.,
|
| 526 |
+
670442572800., 33522128640., 1323241920., 40840800., 960960.,
|
| 527 |
+
16380., 182., 1.)
|
| 528 |
+
B = self.A * 2**-s
|
| 529 |
+
B2 = self.A2 * 2**(-2*s)
|
| 530 |
+
B4 = self.A4 * 2**(-4*s)
|
| 531 |
+
B6 = self.A6 * 2**(-6*s)
|
| 532 |
+
U2 = _smart_matrix_product(B6,
|
| 533 |
+
b[13]*B6 + b[11]*B4 + b[9]*B2,
|
| 534 |
+
structure=self.structure)
|
| 535 |
+
U = _smart_matrix_product(B,
|
| 536 |
+
(U2 + b[7]*B6 + b[5]*B4 +
|
| 537 |
+
b[3]*B2 + b[1]*self.ident),
|
| 538 |
+
structure=self.structure)
|
| 539 |
+
V2 = _smart_matrix_product(B6,
|
| 540 |
+
b[12]*B6 + b[10]*B4 + b[8]*B2,
|
| 541 |
+
structure=self.structure)
|
| 542 |
+
V = V2 + b[6]*B6 + b[4]*B4 + b[2]*B2 + b[0]*self.ident
|
| 543 |
+
return U, V
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def expm(A):
|
| 547 |
+
"""
|
| 548 |
+
Compute the matrix exponential using Pade approximation.
|
| 549 |
+
|
| 550 |
+
Parameters
|
| 551 |
+
----------
|
| 552 |
+
A : (M,M) array_like or sparse matrix
|
| 553 |
+
2D Array or Matrix (sparse or dense) to be exponentiated
|
| 554 |
+
|
| 555 |
+
Returns
|
| 556 |
+
-------
|
| 557 |
+
expA : (M,M) ndarray
|
| 558 |
+
Matrix exponential of `A`
|
| 559 |
+
|
| 560 |
+
Notes
|
| 561 |
+
-----
|
| 562 |
+
This is algorithm (6.1) which is a simplification of algorithm (5.1).
|
| 563 |
+
|
| 564 |
+
.. versionadded:: 0.12.0
|
| 565 |
+
|
| 566 |
+
References
|
| 567 |
+
----------
|
| 568 |
+
.. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009)
|
| 569 |
+
"A New Scaling and Squaring Algorithm for the Matrix Exponential."
|
| 570 |
+
SIAM Journal on Matrix Analysis and Applications.
|
| 571 |
+
31 (3). pp. 970-989. ISSN 1095-7162
|
| 572 |
+
|
| 573 |
+
Examples
|
| 574 |
+
--------
|
| 575 |
+
>>> from scipy.sparse import csc_matrix
|
| 576 |
+
>>> from scipy.sparse.linalg import expm
|
| 577 |
+
>>> A = csc_matrix([[1, 0, 0], [0, 2, 0], [0, 0, 3]])
|
| 578 |
+
>>> A.toarray()
|
| 579 |
+
array([[1, 0, 0],
|
| 580 |
+
[0, 2, 0],
|
| 581 |
+
[0, 0, 3]], dtype=int64)
|
| 582 |
+
>>> Aexp = expm(A)
|
| 583 |
+
>>> Aexp
|
| 584 |
+
<Compressed Sparse Column sparse matrix of dtype 'float64'
|
| 585 |
+
with 3 stored elements and shape (3, 3)>
|
| 586 |
+
>>> Aexp.toarray()
|
| 587 |
+
array([[ 2.71828183, 0. , 0. ],
|
| 588 |
+
[ 0. , 7.3890561 , 0. ],
|
| 589 |
+
[ 0. , 0. , 20.08553692]])
|
| 590 |
+
"""
|
| 591 |
+
return _expm(A, use_exact_onenorm='auto')
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def _expm(A, use_exact_onenorm):
|
| 595 |
+
# Core of expm, separated to allow testing exact and approximate
|
| 596 |
+
# algorithms.
|
| 597 |
+
|
| 598 |
+
# Avoid indiscriminate asarray() to allow sparse or other strange arrays.
|
| 599 |
+
if isinstance(A, (list, tuple, np.matrix)):
|
| 600 |
+
A = np.asarray(A)
|
| 601 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
| 602 |
+
raise ValueError('expected a square matrix')
|
| 603 |
+
|
| 604 |
+
# gracefully handle size-0 input,
|
| 605 |
+
# carefully handling sparse scenario
|
| 606 |
+
if A.shape == (0, 0):
|
| 607 |
+
out = np.zeros([0, 0], dtype=A.dtype)
|
| 608 |
+
if issparse(A) or is_pydata_spmatrix(A):
|
| 609 |
+
return A.__class__(out)
|
| 610 |
+
return out
|
| 611 |
+
|
| 612 |
+
# Trivial case
|
| 613 |
+
if A.shape == (1, 1):
|
| 614 |
+
out = [[np.exp(A[0, 0])]]
|
| 615 |
+
|
| 616 |
+
# Avoid indiscriminate casting to ndarray to
|
| 617 |
+
# allow for sparse or other strange arrays
|
| 618 |
+
if issparse(A) or is_pydata_spmatrix(A):
|
| 619 |
+
return A.__class__(out)
|
| 620 |
+
|
| 621 |
+
return np.array(out)
|
| 622 |
+
|
| 623 |
+
# Ensure input is of float type, to avoid integer overflows etc.
|
| 624 |
+
if ((isinstance(A, np.ndarray) or issparse(A) or is_pydata_spmatrix(A))
|
| 625 |
+
and not np.issubdtype(A.dtype, np.inexact)):
|
| 626 |
+
A = A.astype(float)
|
| 627 |
+
|
| 628 |
+
# Detect upper triangularity.
|
| 629 |
+
structure = UPPER_TRIANGULAR if _is_upper_triangular(A) else None
|
| 630 |
+
|
| 631 |
+
if use_exact_onenorm == "auto":
|
| 632 |
+
# Hardcode a matrix order threshold for exact vs. estimated one-norms.
|
| 633 |
+
use_exact_onenorm = A.shape[0] < 200
|
| 634 |
+
|
| 635 |
+
# Track functions of A to help compute the matrix exponential.
|
| 636 |
+
h = _ExpmPadeHelper(
|
| 637 |
+
A, structure=structure, use_exact_onenorm=use_exact_onenorm)
|
| 638 |
+
|
| 639 |
+
# Try Pade order 3.
|
| 640 |
+
eta_1 = max(h.d4_loose, h.d6_loose)
|
| 641 |
+
if eta_1 < 1.495585217958292e-002 and _ell(h.A, 3) == 0:
|
| 642 |
+
U, V = h.pade3()
|
| 643 |
+
return _solve_P_Q(U, V, structure=structure)
|
| 644 |
+
|
| 645 |
+
# Try Pade order 5.
|
| 646 |
+
eta_2 = max(h.d4_tight, h.d6_loose)
|
| 647 |
+
if eta_2 < 2.539398330063230e-001 and _ell(h.A, 5) == 0:
|
| 648 |
+
U, V = h.pade5()
|
| 649 |
+
return _solve_P_Q(U, V, structure=structure)
|
| 650 |
+
|
| 651 |
+
# Try Pade orders 7 and 9.
|
| 652 |
+
eta_3 = max(h.d6_tight, h.d8_loose)
|
| 653 |
+
if eta_3 < 9.504178996162932e-001 and _ell(h.A, 7) == 0:
|
| 654 |
+
U, V = h.pade7()
|
| 655 |
+
return _solve_P_Q(U, V, structure=structure)
|
| 656 |
+
if eta_3 < 2.097847961257068e+000 and _ell(h.A, 9) == 0:
|
| 657 |
+
U, V = h.pade9()
|
| 658 |
+
return _solve_P_Q(U, V, structure=structure)
|
| 659 |
+
|
| 660 |
+
# Use Pade order 13.
|
| 661 |
+
eta_4 = max(h.d8_loose, h.d10_loose)
|
| 662 |
+
eta_5 = min(eta_3, eta_4)
|
| 663 |
+
theta_13 = 4.25
|
| 664 |
+
|
| 665 |
+
# Choose smallest s>=0 such that 2**(-s) eta_5 <= theta_13
|
| 666 |
+
if eta_5 == 0:
|
| 667 |
+
# Nilpotent special case
|
| 668 |
+
s = 0
|
| 669 |
+
else:
|
| 670 |
+
s = max(int(np.ceil(np.log2(eta_5 / theta_13))), 0)
|
| 671 |
+
s = s + _ell(2**-s * h.A, 13)
|
| 672 |
+
U, V = h.pade13_scaled(s)
|
| 673 |
+
X = _solve_P_Q(U, V, structure=structure)
|
| 674 |
+
if structure == UPPER_TRIANGULAR:
|
| 675 |
+
# Invoke Code Fragment 2.1.
|
| 676 |
+
X = _fragment_2_1(X, h.A, s)
|
| 677 |
+
else:
|
| 678 |
+
# X = r_13(A)^(2^s) by repeated squaring.
|
| 679 |
+
for i in range(s):
|
| 680 |
+
X = X.dot(X)
|
| 681 |
+
return X
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def _solve_P_Q(U, V, structure=None):
|
| 685 |
+
"""
|
| 686 |
+
A helper function for expm_2009.
|
| 687 |
+
|
| 688 |
+
Parameters
|
| 689 |
+
----------
|
| 690 |
+
U : ndarray
|
| 691 |
+
Pade numerator.
|
| 692 |
+
V : ndarray
|
| 693 |
+
Pade denominator.
|
| 694 |
+
structure : str, optional
|
| 695 |
+
A string describing the structure of both matrices `U` and `V`.
|
| 696 |
+
Only `upper_triangular` is currently supported.
|
| 697 |
+
|
| 698 |
+
Notes
|
| 699 |
+
-----
|
| 700 |
+
The `structure` argument is inspired by similar args
|
| 701 |
+
for theano and cvxopt functions.
|
| 702 |
+
|
| 703 |
+
"""
|
| 704 |
+
P = U + V
|
| 705 |
+
Q = -U + V
|
| 706 |
+
if issparse(U) or is_pydata_spmatrix(U):
|
| 707 |
+
return spsolve(Q, P)
|
| 708 |
+
elif structure is None:
|
| 709 |
+
return solve(Q, P)
|
| 710 |
+
elif structure == UPPER_TRIANGULAR:
|
| 711 |
+
return solve_triangular(Q, P)
|
| 712 |
+
else:
|
| 713 |
+
raise ValueError('unsupported matrix structure: ' + str(structure))
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def _exp_sinch(a, x):
|
| 717 |
+
"""
|
| 718 |
+
Stably evaluate exp(a)*sinh(x)/x
|
| 719 |
+
|
| 720 |
+
Notes
|
| 721 |
+
-----
|
| 722 |
+
The strategy of falling back to a sixth order Taylor expansion
|
| 723 |
+
was suggested by the Spallation Neutron Source docs
|
| 724 |
+
which was found on the internet by google search.
|
| 725 |
+
http://www.ornl.gov/~t6p/resources/xal/javadoc/gov/sns/tools/math/ElementaryFunction.html
|
| 726 |
+
The details of the cutoff point and the Horner-like evaluation
|
| 727 |
+
was picked without reference to anything in particular.
|
| 728 |
+
|
| 729 |
+
Note that sinch is not currently implemented in scipy.special,
|
| 730 |
+
whereas the "engineer's" definition of sinc is implemented.
|
| 731 |
+
The implementation of sinc involves a scaling factor of pi
|
| 732 |
+
that distinguishes it from the "mathematician's" version of sinc.
|
| 733 |
+
|
| 734 |
+
"""
|
| 735 |
+
|
| 736 |
+
# If x is small then use sixth order Taylor expansion.
|
| 737 |
+
# How small is small? I am using the point where the relative error
|
| 738 |
+
# of the approximation is less than 1e-14.
|
| 739 |
+
# If x is large then directly evaluate sinh(x) / x.
|
| 740 |
+
if abs(x) < 0.0135:
|
| 741 |
+
x2 = x*x
|
| 742 |
+
return np.exp(a) * (1 + (x2/6.)*(1 + (x2/20.)*(1 + (x2/42.))))
|
| 743 |
+
else:
|
| 744 |
+
return (np.exp(a + x) - np.exp(a - x)) / (2*x)
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
def _eq_10_42(lam_1, lam_2, t_12):
|
| 748 |
+
"""
|
| 749 |
+
Equation (10.42) of Functions of Matrices: Theory and Computation.
|
| 750 |
+
|
| 751 |
+
Notes
|
| 752 |
+
-----
|
| 753 |
+
This is a helper function for _fragment_2_1 of expm_2009.
|
| 754 |
+
Equation (10.42) is on page 251 in the section on Schur algorithms.
|
| 755 |
+
In particular, section 10.4.3 explains the Schur-Parlett algorithm.
|
| 756 |
+
expm([[lam_1, t_12], [0, lam_1])
|
| 757 |
+
=
|
| 758 |
+
[[exp(lam_1), t_12*exp((lam_1 + lam_2)/2)*sinch((lam_1 - lam_2)/2)],
|
| 759 |
+
[0, exp(lam_2)]
|
| 760 |
+
"""
|
| 761 |
+
|
| 762 |
+
# The plain formula t_12 * (exp(lam_2) - exp(lam_2)) / (lam_2 - lam_1)
|
| 763 |
+
# apparently suffers from cancellation, according to Higham's textbook.
|
| 764 |
+
# A nice implementation of sinch, defined as sinh(x)/x,
|
| 765 |
+
# will apparently work around the cancellation.
|
| 766 |
+
a = 0.5 * (lam_1 + lam_2)
|
| 767 |
+
b = 0.5 * (lam_1 - lam_2)
|
| 768 |
+
return t_12 * _exp_sinch(a, b)
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
def _fragment_2_1(X, T, s):
|
| 772 |
+
"""
|
| 773 |
+
A helper function for expm_2009.
|
| 774 |
+
|
| 775 |
+
Notes
|
| 776 |
+
-----
|
| 777 |
+
The argument X is modified in-place, but this modification is not the same
|
| 778 |
+
as the returned value of the function.
|
| 779 |
+
This function also takes pains to do things in ways that are compatible
|
| 780 |
+
with sparse matrices, for example by avoiding fancy indexing
|
| 781 |
+
and by using methods of the matrices whenever possible instead of
|
| 782 |
+
using functions of the numpy or scipy libraries themselves.
|
| 783 |
+
|
| 784 |
+
"""
|
| 785 |
+
# Form X = r_m(2^-s T)
|
| 786 |
+
# Replace diag(X) by exp(2^-s diag(T)).
|
| 787 |
+
n = X.shape[0]
|
| 788 |
+
diag_T = np.ravel(T.diagonal().copy())
|
| 789 |
+
|
| 790 |
+
# Replace diag(X) by exp(2^-s diag(T)).
|
| 791 |
+
scale = 2 ** -s
|
| 792 |
+
exp_diag = np.exp(scale * diag_T)
|
| 793 |
+
for k in range(n):
|
| 794 |
+
X[k, k] = exp_diag[k]
|
| 795 |
+
|
| 796 |
+
for i in range(s-1, -1, -1):
|
| 797 |
+
X = X.dot(X)
|
| 798 |
+
|
| 799 |
+
# Replace diag(X) by exp(2^-i diag(T)).
|
| 800 |
+
scale = 2 ** -i
|
| 801 |
+
exp_diag = np.exp(scale * diag_T)
|
| 802 |
+
for k in range(n):
|
| 803 |
+
X[k, k] = exp_diag[k]
|
| 804 |
+
|
| 805 |
+
# Replace (first) superdiagonal of X by explicit formula
|
| 806 |
+
# for superdiagonal of exp(2^-i T) from Eq (10.42) of
|
| 807 |
+
# the author's 2008 textbook
|
| 808 |
+
# Functions of Matrices: Theory and Computation.
|
| 809 |
+
for k in range(n-1):
|
| 810 |
+
lam_1 = scale * diag_T[k]
|
| 811 |
+
lam_2 = scale * diag_T[k+1]
|
| 812 |
+
t_12 = scale * T[k, k+1]
|
| 813 |
+
value = _eq_10_42(lam_1, lam_2, t_12)
|
| 814 |
+
X[k, k+1] = value
|
| 815 |
+
|
| 816 |
+
# Return the updated X matrix.
|
| 817 |
+
return X
|
| 818 |
+
|
| 819 |
+
|
| 820 |
+
def _ell(A, m):
|
| 821 |
+
"""
|
| 822 |
+
A helper function for expm_2009.
|
| 823 |
+
|
| 824 |
+
Parameters
|
| 825 |
+
----------
|
| 826 |
+
A : linear operator
|
| 827 |
+
A linear operator whose norm of power we care about.
|
| 828 |
+
m : int
|
| 829 |
+
The power of the linear operator
|
| 830 |
+
|
| 831 |
+
Returns
|
| 832 |
+
-------
|
| 833 |
+
value : int
|
| 834 |
+
A value related to a bound.
|
| 835 |
+
|
| 836 |
+
"""
|
| 837 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
| 838 |
+
raise ValueError('expected A to be like a square matrix')
|
| 839 |
+
|
| 840 |
+
# The c_i are explained in (2.2) and (2.6) of the 2005 expm paper.
|
| 841 |
+
# They are coefficients of terms of a generating function series expansion.
|
| 842 |
+
c_i = {3: 100800.,
|
| 843 |
+
5: 10059033600.,
|
| 844 |
+
7: 4487938430976000.,
|
| 845 |
+
9: 5914384781877411840000.,
|
| 846 |
+
13: 113250775606021113483283660800000000.
|
| 847 |
+
}
|
| 848 |
+
abs_c_recip = c_i[m]
|
| 849 |
+
|
| 850 |
+
# This is explained after Eq. (1.2) of the 2009 expm paper.
|
| 851 |
+
# It is the "unit roundoff" of IEEE double precision arithmetic.
|
| 852 |
+
u = 2**-53
|
| 853 |
+
|
| 854 |
+
# Compute the one-norm of matrix power p of abs(A).
|
| 855 |
+
A_abs_onenorm = _onenorm_matrix_power_nnm(abs(A), 2*m + 1)
|
| 856 |
+
|
| 857 |
+
# Treat zero norm as a special case.
|
| 858 |
+
if not A_abs_onenorm:
|
| 859 |
+
return 0
|
| 860 |
+
|
| 861 |
+
alpha = A_abs_onenorm / (_onenorm(A) * abs_c_recip)
|
| 862 |
+
log2_alpha_div_u = np.log2(alpha/u)
|
| 863 |
+
value = int(np.ceil(log2_alpha_div_u / (2 * m)))
|
| 864 |
+
return max(value, 0)
|
| 865 |
+
|
| 866 |
+
def matrix_power(A, power):
|
| 867 |
+
"""
|
| 868 |
+
Raise a square matrix to the integer power, `power`.
|
| 869 |
+
|
| 870 |
+
For non-negative integers, ``A**power`` is computed using repeated
|
| 871 |
+
matrix multiplications. Negative integers are not supported.
|
| 872 |
+
|
| 873 |
+
Parameters
|
| 874 |
+
----------
|
| 875 |
+
A : (M, M) square sparse array or matrix
|
| 876 |
+
sparse array that will be raised to power `power`
|
| 877 |
+
power : int
|
| 878 |
+
Exponent used to raise sparse array `A`
|
| 879 |
+
|
| 880 |
+
Returns
|
| 881 |
+
-------
|
| 882 |
+
A**power : (M, M) sparse array or matrix
|
| 883 |
+
The output matrix will be the same shape as A, and will preserve
|
| 884 |
+
the class of A, but the format of the output may be changed.
|
| 885 |
+
|
| 886 |
+
Notes
|
| 887 |
+
-----
|
| 888 |
+
This uses a recursive implementation of the matrix power. For computing
|
| 889 |
+
the matrix power using a reasonably large `power`, this may be less efficient
|
| 890 |
+
than computing the product directly, using A @ A @ ... @ A.
|
| 891 |
+
This is contingent upon the number of nonzero entries in the matrix.
|
| 892 |
+
|
| 893 |
+
.. versionadded:: 1.12.0
|
| 894 |
+
|
| 895 |
+
Examples
|
| 896 |
+
--------
|
| 897 |
+
>>> from scipy import sparse
|
| 898 |
+
>>> A = sparse.csc_array([[0,1,0],[1,0,1],[0,1,0]])
|
| 899 |
+
>>> A.todense()
|
| 900 |
+
array([[0, 1, 0],
|
| 901 |
+
[1, 0, 1],
|
| 902 |
+
[0, 1, 0]])
|
| 903 |
+
>>> (A @ A).todense()
|
| 904 |
+
array([[1, 0, 1],
|
| 905 |
+
[0, 2, 0],
|
| 906 |
+
[1, 0, 1]])
|
| 907 |
+
>>> A2 = sparse.linalg.matrix_power(A, 2)
|
| 908 |
+
>>> A2.todense()
|
| 909 |
+
array([[1, 0, 1],
|
| 910 |
+
[0, 2, 0],
|
| 911 |
+
[1, 0, 1]])
|
| 912 |
+
>>> A4 = sparse.linalg.matrix_power(A, 4)
|
| 913 |
+
>>> A4.todense()
|
| 914 |
+
array([[2, 0, 2],
|
| 915 |
+
[0, 4, 0],
|
| 916 |
+
[2, 0, 2]])
|
| 917 |
+
|
| 918 |
+
"""
|
| 919 |
+
M, N = A.shape
|
| 920 |
+
if M != N:
|
| 921 |
+
raise TypeError('sparse matrix is not square')
|
| 922 |
+
|
| 923 |
+
if isintlike(power):
|
| 924 |
+
power = int(power)
|
| 925 |
+
if power < 0:
|
| 926 |
+
raise ValueError('exponent must be >= 0')
|
| 927 |
+
|
| 928 |
+
if power == 0:
|
| 929 |
+
return eye(M, dtype=A.dtype)
|
| 930 |
+
|
| 931 |
+
if power == 1:
|
| 932 |
+
return A.copy()
|
| 933 |
+
|
| 934 |
+
tmp = matrix_power(A, power // 2)
|
| 935 |
+
if power % 2:
|
| 936 |
+
return A @ tmp @ tmp
|
| 937 |
+
else:
|
| 938 |
+
return tmp @ tmp
|
| 939 |
+
else:
|
| 940 |
+
raise ValueError("exponent must be an integer")
|
parrot/lib/python3.10/site-packages/scipy/sparse/linalg/_special_sparse_arrays.py
ADDED
|
@@ -0,0 +1,948 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from scipy.sparse.linalg import LinearOperator
|
| 3 |
+
from scipy.sparse import kron, eye, dia_array
|
| 4 |
+
|
| 5 |
+
__all__ = ['LaplacianNd']
|
| 6 |
+
# Sakurai and Mikota classes are intended for tests and benchmarks
|
| 7 |
+
# and explicitly not included in the public API of this module.
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class LaplacianNd(LinearOperator):
|
| 11 |
+
"""
|
| 12 |
+
The grid Laplacian in ``N`` dimensions and its eigenvalues/eigenvectors.
|
| 13 |
+
|
| 14 |
+
Construct Laplacian on a uniform rectangular grid in `N` dimensions
|
| 15 |
+
and output its eigenvalues and eigenvectors.
|
| 16 |
+
The Laplacian ``L`` is square, negative definite, real symmetric array
|
| 17 |
+
with signed integer entries and zeros otherwise.
|
| 18 |
+
|
| 19 |
+
Parameters
|
| 20 |
+
----------
|
| 21 |
+
grid_shape : tuple
|
| 22 |
+
A tuple of integers of length ``N`` (corresponding to the dimension of
|
| 23 |
+
the Lapacian), where each entry gives the size of that dimension. The
|
| 24 |
+
Laplacian matrix is square of the size ``np.prod(grid_shape)``.
|
| 25 |
+
boundary_conditions : {'neumann', 'dirichlet', 'periodic'}, optional
|
| 26 |
+
The type of the boundary conditions on the boundaries of the grid.
|
| 27 |
+
Valid values are ``'dirichlet'`` or ``'neumann'``(default) or
|
| 28 |
+
``'periodic'``.
|
| 29 |
+
dtype : dtype
|
| 30 |
+
Numerical type of the array. Default is ``np.int8``.
|
| 31 |
+
|
| 32 |
+
Methods
|
| 33 |
+
-------
|
| 34 |
+
toarray()
|
| 35 |
+
Construct a dense array from Laplacian data
|
| 36 |
+
tosparse()
|
| 37 |
+
Construct a sparse array from Laplacian data
|
| 38 |
+
eigenvalues(m=None)
|
| 39 |
+
Construct a 1D array of `m` largest (smallest in absolute value)
|
| 40 |
+
eigenvalues of the Laplacian matrix in ascending order.
|
| 41 |
+
eigenvectors(m=None):
|
| 42 |
+
Construct the array with columns made of `m` eigenvectors (``float``)
|
| 43 |
+
of the ``Nd`` Laplacian corresponding to the `m` ordered eigenvalues.
|
| 44 |
+
|
| 45 |
+
.. versionadded:: 1.12.0
|
| 46 |
+
|
| 47 |
+
Notes
|
| 48 |
+
-----
|
| 49 |
+
Compared to the MATLAB/Octave implementation [1] of 1-, 2-, and 3-D
|
| 50 |
+
Laplacian, this code allows the arbitrary N-D case and the matrix-free
|
| 51 |
+
callable option, but is currently limited to pure Dirichlet, Neumann or
|
| 52 |
+
Periodic boundary conditions only.
|
| 53 |
+
|
| 54 |
+
The Laplacian matrix of a graph (`scipy.sparse.csgraph.laplacian`) of a
|
| 55 |
+
rectangular grid corresponds to the negative Laplacian with the Neumann
|
| 56 |
+
conditions, i.e., ``boundary_conditions = 'neumann'``.
|
| 57 |
+
|
| 58 |
+
All eigenvalues and eigenvectors of the discrete Laplacian operator for
|
| 59 |
+
an ``N``-dimensional regular grid of shape `grid_shape` with the grid
|
| 60 |
+
step size ``h=1`` are analytically known [2].
|
| 61 |
+
|
| 62 |
+
References
|
| 63 |
+
----------
|
| 64 |
+
.. [1] https://github.com/lobpcg/blopex/blob/master/blopex_\
|
| 65 |
+
tools/matlab/laplacian/laplacian.m
|
| 66 |
+
.. [2] "Eigenvalues and eigenvectors of the second derivative", Wikipedia
|
| 67 |
+
https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors_\
|
| 68 |
+
of_the_second_derivative
|
| 69 |
+
|
| 70 |
+
Examples
|
| 71 |
+
--------
|
| 72 |
+
>>> import numpy as np
|
| 73 |
+
>>> from scipy.sparse.linalg import LaplacianNd
|
| 74 |
+
>>> from scipy.sparse import diags, csgraph
|
| 75 |
+
>>> from scipy.linalg import eigvalsh
|
| 76 |
+
|
| 77 |
+
The one-dimensional Laplacian demonstrated below for pure Neumann boundary
|
| 78 |
+
conditions on a regular grid with ``n=6`` grid points is exactly the
|
| 79 |
+
negative graph Laplacian for the undirected linear graph with ``n``
|
| 80 |
+
vertices using the sparse adjacency matrix ``G`` represented by the
|
| 81 |
+
famous tri-diagonal matrix:
|
| 82 |
+
|
| 83 |
+
>>> n = 6
|
| 84 |
+
>>> G = diags(np.ones(n - 1), 1, format='csr')
|
| 85 |
+
>>> Lf = csgraph.laplacian(G, symmetrized=True, form='function')
|
| 86 |
+
>>> grid_shape = (n, )
|
| 87 |
+
>>> lap = LaplacianNd(grid_shape, boundary_conditions='neumann')
|
| 88 |
+
>>> np.array_equal(lap.matmat(np.eye(n)), -Lf(np.eye(n)))
|
| 89 |
+
True
|
| 90 |
+
|
| 91 |
+
Since all matrix entries of the Laplacian are integers, ``'int8'`` is
|
| 92 |
+
the default dtype for storing matrix representations.
|
| 93 |
+
|
| 94 |
+
>>> lap.tosparse()
|
| 95 |
+
<DIAgonal sparse array of dtype 'int8'
|
| 96 |
+
with 16 stored elements (3 diagonals) and shape (6, 6)>
|
| 97 |
+
>>> lap.toarray()
|
| 98 |
+
array([[-1, 1, 0, 0, 0, 0],
|
| 99 |
+
[ 1, -2, 1, 0, 0, 0],
|
| 100 |
+
[ 0, 1, -2, 1, 0, 0],
|
| 101 |
+
[ 0, 0, 1, -2, 1, 0],
|
| 102 |
+
[ 0, 0, 0, 1, -2, 1],
|
| 103 |
+
[ 0, 0, 0, 0, 1, -1]], dtype=int8)
|
| 104 |
+
>>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
|
| 105 |
+
True
|
| 106 |
+
>>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
|
| 107 |
+
True
|
| 108 |
+
|
| 109 |
+
Any number of extreme eigenvalues and/or eigenvectors can be computed.
|
| 110 |
+
|
| 111 |
+
>>> lap = LaplacianNd(grid_shape, boundary_conditions='periodic')
|
| 112 |
+
>>> lap.eigenvalues()
|
| 113 |
+
array([-4., -3., -3., -1., -1., 0.])
|
| 114 |
+
>>> lap.eigenvalues()[-2:]
|
| 115 |
+
array([-1., 0.])
|
| 116 |
+
>>> lap.eigenvalues(2)
|
| 117 |
+
array([-1., 0.])
|
| 118 |
+
>>> lap.eigenvectors(1)
|
| 119 |
+
array([[0.40824829],
|
| 120 |
+
[0.40824829],
|
| 121 |
+
[0.40824829],
|
| 122 |
+
[0.40824829],
|
| 123 |
+
[0.40824829],
|
| 124 |
+
[0.40824829]])
|
| 125 |
+
>>> lap.eigenvectors(2)
|
| 126 |
+
array([[ 0.5 , 0.40824829],
|
| 127 |
+
[ 0. , 0.40824829],
|
| 128 |
+
[-0.5 , 0.40824829],
|
| 129 |
+
[-0.5 , 0.40824829],
|
| 130 |
+
[ 0. , 0.40824829],
|
| 131 |
+
[ 0.5 , 0.40824829]])
|
| 132 |
+
>>> lap.eigenvectors()
|
| 133 |
+
array([[ 0.40824829, 0.28867513, 0.28867513, 0.5 , 0.5 ,
|
| 134 |
+
0.40824829],
|
| 135 |
+
[-0.40824829, -0.57735027, -0.57735027, 0. , 0. ,
|
| 136 |
+
0.40824829],
|
| 137 |
+
[ 0.40824829, 0.28867513, 0.28867513, -0.5 , -0.5 ,
|
| 138 |
+
0.40824829],
|
| 139 |
+
[-0.40824829, 0.28867513, 0.28867513, -0.5 , -0.5 ,
|
| 140 |
+
0.40824829],
|
| 141 |
+
[ 0.40824829, -0.57735027, -0.57735027, 0. , 0. ,
|
| 142 |
+
0.40824829],
|
| 143 |
+
[-0.40824829, 0.28867513, 0.28867513, 0.5 , 0.5 ,
|
| 144 |
+
0.40824829]])
|
| 145 |
+
|
| 146 |
+
The two-dimensional Laplacian is illustrated on a regular grid with
|
| 147 |
+
``grid_shape = (2, 3)`` points in each dimension.
|
| 148 |
+
|
| 149 |
+
>>> grid_shape = (2, 3)
|
| 150 |
+
>>> n = np.prod(grid_shape)
|
| 151 |
+
|
| 152 |
+
Numeration of grid points is as follows:
|
| 153 |
+
|
| 154 |
+
>>> np.arange(n).reshape(grid_shape + (-1,))
|
| 155 |
+
array([[[0],
|
| 156 |
+
[1],
|
| 157 |
+
[2]],
|
| 158 |
+
<BLANKLINE>
|
| 159 |
+
[[3],
|
| 160 |
+
[4],
|
| 161 |
+
[5]]])
|
| 162 |
+
|
| 163 |
+
Each of the boundary conditions ``'dirichlet'``, ``'periodic'``, and
|
| 164 |
+
``'neumann'`` is illustrated separately; with ``'dirichlet'``
|
| 165 |
+
|
| 166 |
+
>>> lap = LaplacianNd(grid_shape, boundary_conditions='dirichlet')
|
| 167 |
+
>>> lap.tosparse()
|
| 168 |
+
<Compressed Sparse Row sparse array of dtype 'int8'
|
| 169 |
+
with 20 stored elements and shape (6, 6)>
|
| 170 |
+
>>> lap.toarray()
|
| 171 |
+
array([[-4, 1, 0, 1, 0, 0],
|
| 172 |
+
[ 1, -4, 1, 0, 1, 0],
|
| 173 |
+
[ 0, 1, -4, 0, 0, 1],
|
| 174 |
+
[ 1, 0, 0, -4, 1, 0],
|
| 175 |
+
[ 0, 1, 0, 1, -4, 1],
|
| 176 |
+
[ 0, 0, 1, 0, 1, -4]], dtype=int8)
|
| 177 |
+
>>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
|
| 178 |
+
True
|
| 179 |
+
>>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
|
| 180 |
+
True
|
| 181 |
+
>>> lap.eigenvalues()
|
| 182 |
+
array([-6.41421356, -5. , -4.41421356, -3.58578644, -3. ,
|
| 183 |
+
-1.58578644])
|
| 184 |
+
>>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
|
| 185 |
+
>>> np.allclose(lap.eigenvalues(), eigvals)
|
| 186 |
+
True
|
| 187 |
+
>>> np.allclose(lap.toarray() @ lap.eigenvectors(),
|
| 188 |
+
... lap.eigenvectors() @ np.diag(lap.eigenvalues()))
|
| 189 |
+
True
|
| 190 |
+
|
| 191 |
+
with ``'periodic'``
|
| 192 |
+
|
| 193 |
+
>>> lap = LaplacianNd(grid_shape, boundary_conditions='periodic')
|
| 194 |
+
>>> lap.tosparse()
|
| 195 |
+
<Compressed Sparse Row sparse array of dtype 'int8'
|
| 196 |
+
with 24 stored elements and shape (6, 6)>
|
| 197 |
+
>>> lap.toarray()
|
| 198 |
+
array([[-4, 1, 1, 2, 0, 0],
|
| 199 |
+
[ 1, -4, 1, 0, 2, 0],
|
| 200 |
+
[ 1, 1, -4, 0, 0, 2],
|
| 201 |
+
[ 2, 0, 0, -4, 1, 1],
|
| 202 |
+
[ 0, 2, 0, 1, -4, 1],
|
| 203 |
+
[ 0, 0, 2, 1, 1, -4]], dtype=int8)
|
| 204 |
+
>>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
|
| 205 |
+
True
|
| 206 |
+
>>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
|
| 207 |
+
True
|
| 208 |
+
>>> lap.eigenvalues()
|
| 209 |
+
array([-7., -7., -4., -3., -3., 0.])
|
| 210 |
+
>>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
|
| 211 |
+
>>> np.allclose(lap.eigenvalues(), eigvals)
|
| 212 |
+
True
|
| 213 |
+
>>> np.allclose(lap.toarray() @ lap.eigenvectors(),
|
| 214 |
+
... lap.eigenvectors() @ np.diag(lap.eigenvalues()))
|
| 215 |
+
True
|
| 216 |
+
|
| 217 |
+
and with ``'neumann'``
|
| 218 |
+
|
| 219 |
+
>>> lap = LaplacianNd(grid_shape, boundary_conditions='neumann')
|
| 220 |
+
>>> lap.tosparse()
|
| 221 |
+
<Compressed Sparse Row sparse array of dtype 'int8'
|
| 222 |
+
with 20 stored elements and shape (6, 6)>
|
| 223 |
+
>>> lap.toarray()
|
| 224 |
+
array([[-2, 1, 0, 1, 0, 0],
|
| 225 |
+
[ 1, -3, 1, 0, 1, 0],
|
| 226 |
+
[ 0, 1, -2, 0, 0, 1],
|
| 227 |
+
[ 1, 0, 0, -2, 1, 0],
|
| 228 |
+
[ 0, 1, 0, 1, -3, 1],
|
| 229 |
+
[ 0, 0, 1, 0, 1, -2]])
|
| 230 |
+
>>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
|
| 231 |
+
True
|
| 232 |
+
>>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
|
| 233 |
+
True
|
| 234 |
+
>>> lap.eigenvalues()
|
| 235 |
+
array([-5., -3., -3., -2., -1., 0.])
|
| 236 |
+
>>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
|
| 237 |
+
>>> np.allclose(lap.eigenvalues(), eigvals)
|
| 238 |
+
True
|
| 239 |
+
>>> np.allclose(lap.toarray() @ lap.eigenvectors(),
|
| 240 |
+
... lap.eigenvectors() @ np.diag(lap.eigenvalues()))
|
| 241 |
+
True
|
| 242 |
+
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
def __init__(self, grid_shape, *,
|
| 246 |
+
boundary_conditions='neumann',
|
| 247 |
+
dtype=np.int8):
|
| 248 |
+
|
| 249 |
+
if boundary_conditions not in ('dirichlet', 'neumann', 'periodic'):
|
| 250 |
+
raise ValueError(
|
| 251 |
+
f"Unknown value {boundary_conditions!r} is given for "
|
| 252 |
+
"'boundary_conditions' parameter. The valid options are "
|
| 253 |
+
"'dirichlet', 'periodic', and 'neumann' (default)."
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
self.grid_shape = grid_shape
|
| 257 |
+
self.boundary_conditions = boundary_conditions
|
| 258 |
+
# LaplacianNd folds all dimensions in `grid_shape` into a single one
|
| 259 |
+
N = np.prod(grid_shape)
|
| 260 |
+
super().__init__(dtype=dtype, shape=(N, N))
|
| 261 |
+
|
| 262 |
+
def _eigenvalue_ordering(self, m):
|
| 263 |
+
"""Compute `m` largest eigenvalues in each of the ``N`` directions,
|
| 264 |
+
i.e., up to ``m * N`` total, order them and return `m` largest.
|
| 265 |
+
"""
|
| 266 |
+
grid_shape = self.grid_shape
|
| 267 |
+
if m is None:
|
| 268 |
+
indices = np.indices(grid_shape)
|
| 269 |
+
Leig = np.zeros(grid_shape)
|
| 270 |
+
else:
|
| 271 |
+
grid_shape_min = min(grid_shape,
|
| 272 |
+
tuple(np.ones_like(grid_shape) * m))
|
| 273 |
+
indices = np.indices(grid_shape_min)
|
| 274 |
+
Leig = np.zeros(grid_shape_min)
|
| 275 |
+
|
| 276 |
+
for j, n in zip(indices, grid_shape):
|
| 277 |
+
if self.boundary_conditions == 'dirichlet':
|
| 278 |
+
Leig += -4 * np.sin(np.pi * (j + 1) / (2 * (n + 1))) ** 2
|
| 279 |
+
elif self.boundary_conditions == 'neumann':
|
| 280 |
+
Leig += -4 * np.sin(np.pi * j / (2 * n)) ** 2
|
| 281 |
+
else: # boundary_conditions == 'periodic'
|
| 282 |
+
Leig += -4 * np.sin(np.pi * np.floor((j + 1) / 2) / n) ** 2
|
| 283 |
+
|
| 284 |
+
Leig_ravel = Leig.ravel()
|
| 285 |
+
ind = np.argsort(Leig_ravel)
|
| 286 |
+
eigenvalues = Leig_ravel[ind]
|
| 287 |
+
if m is not None:
|
| 288 |
+
eigenvalues = eigenvalues[-m:]
|
| 289 |
+
ind = ind[-m:]
|
| 290 |
+
|
| 291 |
+
return eigenvalues, ind
|
| 292 |
+
|
| 293 |
+
def eigenvalues(self, m=None):
|
| 294 |
+
"""Return the requested number of eigenvalues.
|
| 295 |
+
|
| 296 |
+
Parameters
|
| 297 |
+
----------
|
| 298 |
+
m : int, optional
|
| 299 |
+
The positive number of smallest eigenvalues to return.
|
| 300 |
+
If not provided, then all eigenvalues will be returned.
|
| 301 |
+
|
| 302 |
+
Returns
|
| 303 |
+
-------
|
| 304 |
+
eigenvalues : float array
|
| 305 |
+
The requested `m` smallest or all eigenvalues, in ascending order.
|
| 306 |
+
"""
|
| 307 |
+
eigenvalues, _ = self._eigenvalue_ordering(m)
|
| 308 |
+
return eigenvalues
|
| 309 |
+
|
| 310 |
+
def _ev1d(self, j, n):
|
| 311 |
+
"""Return 1 eigenvector in 1d with index `j`
|
| 312 |
+
and number of grid points `n` where ``j < n``.
|
| 313 |
+
"""
|
| 314 |
+
if self.boundary_conditions == 'dirichlet':
|
| 315 |
+
i = np.pi * (np.arange(n) + 1) / (n + 1)
|
| 316 |
+
ev = np.sqrt(2. / (n + 1.)) * np.sin(i * (j + 1))
|
| 317 |
+
elif self.boundary_conditions == 'neumann':
|
| 318 |
+
i = np.pi * (np.arange(n) + 0.5) / n
|
| 319 |
+
ev = np.sqrt((1. if j == 0 else 2.) / n) * np.cos(i * j)
|
| 320 |
+
else: # boundary_conditions == 'periodic'
|
| 321 |
+
if j == 0:
|
| 322 |
+
ev = np.sqrt(1. / n) * np.ones(n)
|
| 323 |
+
elif j + 1 == n and n % 2 == 0:
|
| 324 |
+
ev = np.sqrt(1. / n) * np.tile([1, -1], n//2)
|
| 325 |
+
else:
|
| 326 |
+
i = 2. * np.pi * (np.arange(n) + 0.5) / n
|
| 327 |
+
ev = np.sqrt(2. / n) * np.cos(i * np.floor((j + 1) / 2))
|
| 328 |
+
# make small values exact zeros correcting round-off errors
|
| 329 |
+
# due to symmetry of eigenvectors the exact 0. is correct
|
| 330 |
+
ev[np.abs(ev) < np.finfo(np.float64).eps] = 0.
|
| 331 |
+
return ev
|
| 332 |
+
|
| 333 |
+
def _one_eve(self, k):
|
| 334 |
+
"""Return 1 eigenvector in Nd with multi-index `j`
|
| 335 |
+
as a tensor product of the corresponding 1d eigenvectors.
|
| 336 |
+
"""
|
| 337 |
+
phi = [self._ev1d(j, n) for j, n in zip(k, self.grid_shape)]
|
| 338 |
+
result = phi[0]
|
| 339 |
+
for phi in phi[1:]:
|
| 340 |
+
result = np.tensordot(result, phi, axes=0)
|
| 341 |
+
return np.asarray(result).ravel()
|
| 342 |
+
|
| 343 |
+
def eigenvectors(self, m=None):
|
| 344 |
+
"""Return the requested number of eigenvectors for ordered eigenvalues.
|
| 345 |
+
|
| 346 |
+
Parameters
|
| 347 |
+
----------
|
| 348 |
+
m : int, optional
|
| 349 |
+
The positive number of eigenvectors to return. If not provided,
|
| 350 |
+
then all eigenvectors will be returned.
|
| 351 |
+
|
| 352 |
+
Returns
|
| 353 |
+
-------
|
| 354 |
+
eigenvectors : float array
|
| 355 |
+
An array with columns made of the requested `m` or all eigenvectors.
|
| 356 |
+
The columns are ordered according to the `m` ordered eigenvalues.
|
| 357 |
+
"""
|
| 358 |
+
_, ind = self._eigenvalue_ordering(m)
|
| 359 |
+
if m is None:
|
| 360 |
+
grid_shape_min = self.grid_shape
|
| 361 |
+
else:
|
| 362 |
+
grid_shape_min = min(self.grid_shape,
|
| 363 |
+
tuple(np.ones_like(self.grid_shape) * m))
|
| 364 |
+
|
| 365 |
+
N_indices = np.unravel_index(ind, grid_shape_min)
|
| 366 |
+
N_indices = [tuple(x) for x in zip(*N_indices)]
|
| 367 |
+
eigenvectors_list = [self._one_eve(k) for k in N_indices]
|
| 368 |
+
return np.column_stack(eigenvectors_list)
|
| 369 |
+
|
| 370 |
+
def toarray(self):
|
| 371 |
+
"""
|
| 372 |
+
Converts the Laplacian data to a dense array.
|
| 373 |
+
|
| 374 |
+
Returns
|
| 375 |
+
-------
|
| 376 |
+
L : ndarray
|
| 377 |
+
The shape is ``(N, N)`` where ``N = np.prod(grid_shape)``.
|
| 378 |
+
|
| 379 |
+
"""
|
| 380 |
+
grid_shape = self.grid_shape
|
| 381 |
+
n = np.prod(grid_shape)
|
| 382 |
+
L = np.zeros([n, n], dtype=np.int8)
|
| 383 |
+
# Scratch arrays
|
| 384 |
+
L_i = np.empty_like(L)
|
| 385 |
+
Ltemp = np.empty_like(L)
|
| 386 |
+
|
| 387 |
+
for ind, dim in enumerate(grid_shape):
|
| 388 |
+
# Start zeroing out L_i
|
| 389 |
+
L_i[:] = 0
|
| 390 |
+
# Allocate the top left corner with the kernel of L_i
|
| 391 |
+
# Einsum returns writable view of arrays
|
| 392 |
+
np.einsum("ii->i", L_i[:dim, :dim])[:] = -2
|
| 393 |
+
np.einsum("ii->i", L_i[: dim - 1, 1:dim])[:] = 1
|
| 394 |
+
np.einsum("ii->i", L_i[1:dim, : dim - 1])[:] = 1
|
| 395 |
+
|
| 396 |
+
if self.boundary_conditions == 'neumann':
|
| 397 |
+
L_i[0, 0] = -1
|
| 398 |
+
L_i[dim - 1, dim - 1] = -1
|
| 399 |
+
elif self.boundary_conditions == 'periodic':
|
| 400 |
+
if dim > 1:
|
| 401 |
+
L_i[0, dim - 1] += 1
|
| 402 |
+
L_i[dim - 1, 0] += 1
|
| 403 |
+
else:
|
| 404 |
+
L_i[0, 0] += 1
|
| 405 |
+
|
| 406 |
+
# kron is too slow for large matrices hence the next two tricks
|
| 407 |
+
# 1- kron(eye, mat) is block_diag(mat, mat, ...)
|
| 408 |
+
# 2- kron(mat, eye) can be performed by 4d stride trick
|
| 409 |
+
|
| 410 |
+
# 1-
|
| 411 |
+
new_dim = dim
|
| 412 |
+
# for block_diag we tile the top left portion on the diagonal
|
| 413 |
+
if ind > 0:
|
| 414 |
+
tiles = np.prod(grid_shape[:ind])
|
| 415 |
+
for j in range(1, tiles):
|
| 416 |
+
L_i[j*dim:(j+1)*dim, j*dim:(j+1)*dim] = L_i[:dim, :dim]
|
| 417 |
+
new_dim += dim
|
| 418 |
+
# 2-
|
| 419 |
+
# we need the keep L_i, but reset the array
|
| 420 |
+
Ltemp[:new_dim, :new_dim] = L_i[:new_dim, :new_dim]
|
| 421 |
+
tiles = int(np.prod(grid_shape[ind+1:]))
|
| 422 |
+
# Zero out the top left, the rest is already 0
|
| 423 |
+
L_i[:new_dim, :new_dim] = 0
|
| 424 |
+
idx = [x for x in range(tiles)]
|
| 425 |
+
L_i.reshape(
|
| 426 |
+
(new_dim, tiles,
|
| 427 |
+
new_dim, tiles)
|
| 428 |
+
)[:, idx, :, idx] = Ltemp[:new_dim, :new_dim]
|
| 429 |
+
|
| 430 |
+
L += L_i
|
| 431 |
+
|
| 432 |
+
return L.astype(self.dtype)
|
| 433 |
+
|
| 434 |
+
def tosparse(self):
|
| 435 |
+
"""
|
| 436 |
+
Constructs a sparse array from the Laplacian data. The returned sparse
|
| 437 |
+
array format is dependent on the selected boundary conditions.
|
| 438 |
+
|
| 439 |
+
Returns
|
| 440 |
+
-------
|
| 441 |
+
L : scipy.sparse.sparray
|
| 442 |
+
The shape is ``(N, N)`` where ``N = np.prod(grid_shape)``.
|
| 443 |
+
|
| 444 |
+
"""
|
| 445 |
+
N = len(self.grid_shape)
|
| 446 |
+
p = np.prod(self.grid_shape)
|
| 447 |
+
L = dia_array((p, p), dtype=np.int8)
|
| 448 |
+
|
| 449 |
+
for i in range(N):
|
| 450 |
+
dim = self.grid_shape[i]
|
| 451 |
+
data = np.ones([3, dim], dtype=np.int8)
|
| 452 |
+
data[1, :] *= -2
|
| 453 |
+
|
| 454 |
+
if self.boundary_conditions == 'neumann':
|
| 455 |
+
data[1, 0] = -1
|
| 456 |
+
data[1, -1] = -1
|
| 457 |
+
|
| 458 |
+
L_i = dia_array((data, [-1, 0, 1]), shape=(dim, dim),
|
| 459 |
+
dtype=np.int8
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
if self.boundary_conditions == 'periodic':
|
| 463 |
+
t = dia_array((dim, dim), dtype=np.int8)
|
| 464 |
+
t.setdiag([1], k=-dim+1)
|
| 465 |
+
t.setdiag([1], k=dim-1)
|
| 466 |
+
L_i += t
|
| 467 |
+
|
| 468 |
+
for j in range(i):
|
| 469 |
+
L_i = kron(eye(self.grid_shape[j], dtype=np.int8), L_i)
|
| 470 |
+
for j in range(i + 1, N):
|
| 471 |
+
L_i = kron(L_i, eye(self.grid_shape[j], dtype=np.int8))
|
| 472 |
+
L += L_i
|
| 473 |
+
return L.astype(self.dtype)
|
| 474 |
+
|
| 475 |
+
def _matvec(self, x):
|
| 476 |
+
grid_shape = self.grid_shape
|
| 477 |
+
N = len(grid_shape)
|
| 478 |
+
X = x.reshape(grid_shape + (-1,))
|
| 479 |
+
Y = -2 * N * X
|
| 480 |
+
for i in range(N):
|
| 481 |
+
Y += np.roll(X, 1, axis=i)
|
| 482 |
+
Y += np.roll(X, -1, axis=i)
|
| 483 |
+
if self.boundary_conditions in ('neumann', 'dirichlet'):
|
| 484 |
+
Y[(slice(None),)*i + (0,) + (slice(None),)*(N-i-1)
|
| 485 |
+
] -= np.roll(X, 1, axis=i)[
|
| 486 |
+
(slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
|
| 487 |
+
]
|
| 488 |
+
Y[
|
| 489 |
+
(slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
|
| 490 |
+
] -= np.roll(X, -1, axis=i)[
|
| 491 |
+
(slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
|
| 492 |
+
]
|
| 493 |
+
|
| 494 |
+
if self.boundary_conditions == 'neumann':
|
| 495 |
+
Y[
|
| 496 |
+
(slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
|
| 497 |
+
] += np.roll(X, 0, axis=i)[
|
| 498 |
+
(slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
|
| 499 |
+
]
|
| 500 |
+
Y[
|
| 501 |
+
(slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
|
| 502 |
+
] += np.roll(X, 0, axis=i)[
|
| 503 |
+
(slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
|
| 504 |
+
]
|
| 505 |
+
|
| 506 |
+
return Y.reshape(-1, X.shape[-1])
|
| 507 |
+
|
| 508 |
+
def _matmat(self, x):
|
| 509 |
+
return self._matvec(x)
|
| 510 |
+
|
| 511 |
+
def _adjoint(self):
|
| 512 |
+
return self
|
| 513 |
+
|
| 514 |
+
def _transpose(self):
|
| 515 |
+
return self
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
class Sakurai(LinearOperator):
|
| 519 |
+
"""
|
| 520 |
+
Construct a Sakurai matrix in various formats and its eigenvalues.
|
| 521 |
+
|
| 522 |
+
Constructs the "Sakurai" matrix motivated by reference [1]_:
|
| 523 |
+
square real symmetric positive definite and 5-diagonal
|
| 524 |
+
with the main digonal ``[5, 6, 6, ..., 6, 6, 5], the ``+1`` and ``-1``
|
| 525 |
+
diagonals filled with ``-4``, and the ``+2`` and ``-2`` diagonals
|
| 526 |
+
made of ``1``. Its eigenvalues are analytically known to be
|
| 527 |
+
``16. * np.power(np.cos(0.5 * k * np.pi / (n + 1)), 4)``.
|
| 528 |
+
The matrix gets ill-conditioned with its size growing.
|
| 529 |
+
It is useful for testing and benchmarking sparse eigenvalue solvers
|
| 530 |
+
especially those taking advantage of its banded 5-diagonal structure.
|
| 531 |
+
See the notes below for details.
|
| 532 |
+
|
| 533 |
+
Parameters
|
| 534 |
+
----------
|
| 535 |
+
n : int
|
| 536 |
+
The size of the matrix.
|
| 537 |
+
dtype : dtype
|
| 538 |
+
Numerical type of the array. Default is ``np.int8``.
|
| 539 |
+
|
| 540 |
+
Methods
|
| 541 |
+
-------
|
| 542 |
+
toarray()
|
| 543 |
+
Construct a dense array from Laplacian data
|
| 544 |
+
tosparse()
|
| 545 |
+
Construct a sparse array from Laplacian data
|
| 546 |
+
tobanded()
|
| 547 |
+
The Sakurai matrix in the format for banded symmetric matrices,
|
| 548 |
+
i.e., (3, n) ndarray with 3 upper diagonals
|
| 549 |
+
placing the main diagonal at the bottom.
|
| 550 |
+
eigenvalues
|
| 551 |
+
All eigenvalues of the Sakurai matrix ordered ascending.
|
| 552 |
+
|
| 553 |
+
Notes
|
| 554 |
+
-----
|
| 555 |
+
Reference [1]_ introduces a generalized eigenproblem for the matrix pair
|
| 556 |
+
`A` and `B` where `A` is the identity so we turn it into an eigenproblem
|
| 557 |
+
just for the matrix `B` that this function outputs in various formats
|
| 558 |
+
together with its eigenvalues.
|
| 559 |
+
|
| 560 |
+
.. versionadded:: 1.12.0
|
| 561 |
+
|
| 562 |
+
References
|
| 563 |
+
----------
|
| 564 |
+
.. [1] T. Sakurai, H. Tadano, Y. Inadomi, and U. Nagashima,
|
| 565 |
+
"A moment-based method for large-scale generalized
|
| 566 |
+
eigenvalue problems",
|
| 567 |
+
Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004).
|
| 568 |
+
|
| 569 |
+
Examples
|
| 570 |
+
--------
|
| 571 |
+
>>> import numpy as np
|
| 572 |
+
>>> from scipy.sparse.linalg._special_sparse_arrays import Sakurai
|
| 573 |
+
>>> from scipy.linalg import eig_banded
|
| 574 |
+
>>> n = 6
|
| 575 |
+
>>> sak = Sakurai(n)
|
| 576 |
+
|
| 577 |
+
Since all matrix entries are small integers, ``'int8'`` is
|
| 578 |
+
the default dtype for storing matrix representations.
|
| 579 |
+
|
| 580 |
+
>>> sak.toarray()
|
| 581 |
+
array([[ 5, -4, 1, 0, 0, 0],
|
| 582 |
+
[-4, 6, -4, 1, 0, 0],
|
| 583 |
+
[ 1, -4, 6, -4, 1, 0],
|
| 584 |
+
[ 0, 1, -4, 6, -4, 1],
|
| 585 |
+
[ 0, 0, 1, -4, 6, -4],
|
| 586 |
+
[ 0, 0, 0, 1, -4, 5]], dtype=int8)
|
| 587 |
+
>>> sak.tobanded()
|
| 588 |
+
array([[ 1, 1, 1, 1, 1, 1],
|
| 589 |
+
[-4, -4, -4, -4, -4, -4],
|
| 590 |
+
[ 5, 6, 6, 6, 6, 5]], dtype=int8)
|
| 591 |
+
>>> sak.tosparse()
|
| 592 |
+
<DIAgonal sparse array of dtype 'int8'
|
| 593 |
+
with 24 stored elements (5 diagonals) and shape (6, 6)>
|
| 594 |
+
>>> np.array_equal(sak.dot(np.eye(n)), sak.tosparse().toarray())
|
| 595 |
+
True
|
| 596 |
+
>>> sak.eigenvalues()
|
| 597 |
+
array([0.03922866, 0.56703972, 2.41789479, 5.97822974,
|
| 598 |
+
10.54287655, 14.45473055])
|
| 599 |
+
>>> sak.eigenvalues(2)
|
| 600 |
+
array([0.03922866, 0.56703972])
|
| 601 |
+
|
| 602 |
+
The banded form can be used in scipy functions for banded matrices, e.g.,
|
| 603 |
+
|
| 604 |
+
>>> e = eig_banded(sak.tobanded(), eigvals_only=True)
|
| 605 |
+
>>> np.allclose(sak.eigenvalues, e, atol= n * n * n * np.finfo(float).eps)
|
| 606 |
+
True
|
| 607 |
+
|
| 608 |
+
"""
|
| 609 |
+
def __init__(self, n, dtype=np.int8):
|
| 610 |
+
self.n = n
|
| 611 |
+
self.dtype = dtype
|
| 612 |
+
shape = (n, n)
|
| 613 |
+
super().__init__(dtype, shape)
|
| 614 |
+
|
| 615 |
+
def eigenvalues(self, m=None):
|
| 616 |
+
"""Return the requested number of eigenvalues.
|
| 617 |
+
|
| 618 |
+
Parameters
|
| 619 |
+
----------
|
| 620 |
+
m : int, optional
|
| 621 |
+
The positive number of smallest eigenvalues to return.
|
| 622 |
+
If not provided, then all eigenvalues will be returned.
|
| 623 |
+
|
| 624 |
+
Returns
|
| 625 |
+
-------
|
| 626 |
+
eigenvalues : `np.float64` array
|
| 627 |
+
The requested `m` smallest or all eigenvalues, in ascending order.
|
| 628 |
+
"""
|
| 629 |
+
if m is None:
|
| 630 |
+
m = self.n
|
| 631 |
+
k = np.arange(self.n + 1 -m, self.n + 1)
|
| 632 |
+
return np.flip(16. * np.power(np.cos(0.5 * k * np.pi / (self.n + 1)), 4))
|
| 633 |
+
|
| 634 |
+
def tobanded(self):
|
| 635 |
+
"""
|
| 636 |
+
Construct the Sakurai matrix as a banded array.
|
| 637 |
+
"""
|
| 638 |
+
d0 = np.r_[5, 6 * np.ones(self.n - 2, dtype=self.dtype), 5]
|
| 639 |
+
d1 = -4 * np.ones(self.n, dtype=self.dtype)
|
| 640 |
+
d2 = np.ones(self.n, dtype=self.dtype)
|
| 641 |
+
return np.array([d2, d1, d0]).astype(self.dtype)
|
| 642 |
+
|
| 643 |
+
def tosparse(self):
|
| 644 |
+
"""
|
| 645 |
+
Construct the Sakurai matrix is a sparse format.
|
| 646 |
+
"""
|
| 647 |
+
from scipy.sparse import spdiags
|
| 648 |
+
d = self.tobanded()
|
| 649 |
+
# the banded format has the main diagonal at the bottom
|
| 650 |
+
# `spdiags` has no `dtype` parameter so inherits dtype from banded
|
| 651 |
+
return spdiags([d[0], d[1], d[2], d[1], d[0]], [-2, -1, 0, 1, 2],
|
| 652 |
+
self.n, self.n)
|
| 653 |
+
|
| 654 |
+
def toarray(self):
|
| 655 |
+
return self.tosparse().toarray()
|
| 656 |
+
|
| 657 |
+
def _matvec(self, x):
|
| 658 |
+
"""
|
| 659 |
+
Construct matrix-free callable banded-matrix-vector multiplication by
|
| 660 |
+
the Sakurai matrix without constructing or storing the matrix itself
|
| 661 |
+
using the knowledge of its entries and the 5-diagonal format.
|
| 662 |
+
"""
|
| 663 |
+
x = x.reshape(self.n, -1)
|
| 664 |
+
result_dtype = np.promote_types(x.dtype, self.dtype)
|
| 665 |
+
sx = np.zeros_like(x, dtype=result_dtype)
|
| 666 |
+
sx[0, :] = 5 * x[0, :] - 4 * x[1, :] + x[2, :]
|
| 667 |
+
sx[-1, :] = 5 * x[-1, :] - 4 * x[-2, :] + x[-3, :]
|
| 668 |
+
sx[1: -1, :] = (6 * x[1: -1, :] - 4 * (x[:-2, :] + x[2:, :])
|
| 669 |
+
+ np.pad(x[:-3, :], ((1, 0), (0, 0)))
|
| 670 |
+
+ np.pad(x[3:, :], ((0, 1), (0, 0))))
|
| 671 |
+
return sx
|
| 672 |
+
|
| 673 |
+
def _matmat(self, x):
|
| 674 |
+
"""
|
| 675 |
+
Construct matrix-free callable matrix-matrix multiplication by
|
| 676 |
+
the Sakurai matrix without constructing or storing the matrix itself
|
| 677 |
+
by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
|
| 678 |
+
"""
|
| 679 |
+
return self._matvec(x)
|
| 680 |
+
|
| 681 |
+
def _adjoint(self):
|
| 682 |
+
return self
|
| 683 |
+
|
| 684 |
+
def _transpose(self):
|
| 685 |
+
return self
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
class MikotaM(LinearOperator):
|
| 689 |
+
"""
|
| 690 |
+
Construct a mass matrix in various formats of Mikota pair.
|
| 691 |
+
|
| 692 |
+
The mass matrix `M` is square real diagonal
|
| 693 |
+
positive definite with entries that are reciprocal to integers.
|
| 694 |
+
|
| 695 |
+
Parameters
|
| 696 |
+
----------
|
| 697 |
+
shape : tuple of int
|
| 698 |
+
The shape of the matrix.
|
| 699 |
+
dtype : dtype
|
| 700 |
+
Numerical type of the array. Default is ``np.float64``.
|
| 701 |
+
|
| 702 |
+
Methods
|
| 703 |
+
-------
|
| 704 |
+
toarray()
|
| 705 |
+
Construct a dense array from Mikota data
|
| 706 |
+
tosparse()
|
| 707 |
+
Construct a sparse array from Mikota data
|
| 708 |
+
tobanded()
|
| 709 |
+
The format for banded symmetric matrices,
|
| 710 |
+
i.e., (1, n) ndarray with the main diagonal.
|
| 711 |
+
"""
|
| 712 |
+
def __init__(self, shape, dtype=np.float64):
|
| 713 |
+
self.shape = shape
|
| 714 |
+
self.dtype = dtype
|
| 715 |
+
super().__init__(dtype, shape)
|
| 716 |
+
|
| 717 |
+
def _diag(self):
|
| 718 |
+
# The matrix is constructed from its diagonal 1 / [1, ..., N+1];
|
| 719 |
+
# compute in a function to avoid duplicated code & storage footprint
|
| 720 |
+
return (1. / np.arange(1, self.shape[0] + 1)).astype(self.dtype)
|
| 721 |
+
|
| 722 |
+
def tobanded(self):
|
| 723 |
+
return self._diag()
|
| 724 |
+
|
| 725 |
+
def tosparse(self):
|
| 726 |
+
from scipy.sparse import diags
|
| 727 |
+
return diags([self._diag()], [0], shape=self.shape, dtype=self.dtype)
|
| 728 |
+
|
| 729 |
+
def toarray(self):
|
| 730 |
+
return np.diag(self._diag()).astype(self.dtype)
|
| 731 |
+
|
| 732 |
+
def _matvec(self, x):
|
| 733 |
+
"""
|
| 734 |
+
Construct matrix-free callable banded-matrix-vector multiplication by
|
| 735 |
+
the Mikota mass matrix without constructing or storing the matrix itself
|
| 736 |
+
using the knowledge of its entries and the diagonal format.
|
| 737 |
+
"""
|
| 738 |
+
x = x.reshape(self.shape[0], -1)
|
| 739 |
+
return self._diag()[:, np.newaxis] * x
|
| 740 |
+
|
| 741 |
+
def _matmat(self, x):
|
| 742 |
+
"""
|
| 743 |
+
Construct matrix-free callable matrix-matrix multiplication by
|
| 744 |
+
the Mikota mass matrix without constructing or storing the matrix itself
|
| 745 |
+
by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
|
| 746 |
+
"""
|
| 747 |
+
return self._matvec(x)
|
| 748 |
+
|
| 749 |
+
def _adjoint(self):
|
| 750 |
+
return self
|
| 751 |
+
|
| 752 |
+
def _transpose(self):
|
| 753 |
+
return self
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
class MikotaK(LinearOperator):
|
| 757 |
+
"""
|
| 758 |
+
Construct a stiffness matrix in various formats of Mikota pair.
|
| 759 |
+
|
| 760 |
+
The stiffness matrix `K` is square real tri-diagonal symmetric
|
| 761 |
+
positive definite with integer entries.
|
| 762 |
+
|
| 763 |
+
Parameters
|
| 764 |
+
----------
|
| 765 |
+
shape : tuple of int
|
| 766 |
+
The shape of the matrix.
|
| 767 |
+
dtype : dtype
|
| 768 |
+
Numerical type of the array. Default is ``np.int32``.
|
| 769 |
+
|
| 770 |
+
Methods
|
| 771 |
+
-------
|
| 772 |
+
toarray()
|
| 773 |
+
Construct a dense array from Mikota data
|
| 774 |
+
tosparse()
|
| 775 |
+
Construct a sparse array from Mikota data
|
| 776 |
+
tobanded()
|
| 777 |
+
The format for banded symmetric matrices,
|
| 778 |
+
i.e., (2, n) ndarray with 2 upper diagonals
|
| 779 |
+
placing the main diagonal at the bottom.
|
| 780 |
+
"""
|
| 781 |
+
def __init__(self, shape, dtype=np.int32):
|
| 782 |
+
self.shape = shape
|
| 783 |
+
self.dtype = dtype
|
| 784 |
+
super().__init__(dtype, shape)
|
| 785 |
+
# The matrix is constructed from its diagonals;
|
| 786 |
+
# we precompute these to avoid duplicating the computation
|
| 787 |
+
n = shape[0]
|
| 788 |
+
self._diag0 = np.arange(2 * n - 1, 0, -2, dtype=self.dtype)
|
| 789 |
+
self._diag1 = - np.arange(n - 1, 0, -1, dtype=self.dtype)
|
| 790 |
+
|
| 791 |
+
def tobanded(self):
|
| 792 |
+
return np.array([np.pad(self._diag1, (1, 0), 'constant'), self._diag0])
|
| 793 |
+
|
| 794 |
+
def tosparse(self):
|
| 795 |
+
from scipy.sparse import diags
|
| 796 |
+
return diags([self._diag1, self._diag0, self._diag1], [-1, 0, 1],
|
| 797 |
+
shape=self.shape, dtype=self.dtype)
|
| 798 |
+
|
| 799 |
+
def toarray(self):
|
| 800 |
+
return self.tosparse().toarray()
|
| 801 |
+
|
| 802 |
+
def _matvec(self, x):
|
| 803 |
+
"""
|
| 804 |
+
Construct matrix-free callable banded-matrix-vector multiplication by
|
| 805 |
+
the Mikota stiffness matrix without constructing or storing the matrix
|
| 806 |
+
itself using the knowledge of its entries and the 3-diagonal format.
|
| 807 |
+
"""
|
| 808 |
+
x = x.reshape(self.shape[0], -1)
|
| 809 |
+
result_dtype = np.promote_types(x.dtype, self.dtype)
|
| 810 |
+
kx = np.zeros_like(x, dtype=result_dtype)
|
| 811 |
+
d1 = self._diag1
|
| 812 |
+
d0 = self._diag0
|
| 813 |
+
kx[0, :] = d0[0] * x[0, :] + d1[0] * x[1, :]
|
| 814 |
+
kx[-1, :] = d1[-1] * x[-2, :] + d0[-1] * x[-1, :]
|
| 815 |
+
kx[1: -1, :] = (d1[:-1, None] * x[: -2, :]
|
| 816 |
+
+ d0[1: -1, None] * x[1: -1, :]
|
| 817 |
+
+ d1[1:, None] * x[2:, :])
|
| 818 |
+
return kx
|
| 819 |
+
|
| 820 |
+
def _matmat(self, x):
|
| 821 |
+
"""
|
| 822 |
+
Construct matrix-free callable matrix-matrix multiplication by
|
| 823 |
+
the Stiffness mass matrix without constructing or storing the matrix itself
|
| 824 |
+
by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
|
| 825 |
+
"""
|
| 826 |
+
return self._matvec(x)
|
| 827 |
+
|
| 828 |
+
def _adjoint(self):
|
| 829 |
+
return self
|
| 830 |
+
|
| 831 |
+
def _transpose(self):
|
| 832 |
+
return self
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
class MikotaPair:
|
| 836 |
+
"""
|
| 837 |
+
Construct the Mikota pair of matrices in various formats and
|
| 838 |
+
eigenvalues of the generalized eigenproblem with them.
|
| 839 |
+
|
| 840 |
+
The Mikota pair of matrices [1, 2]_ models a vibration problem
|
| 841 |
+
of a linear mass-spring system with the ends attached where
|
| 842 |
+
the stiffness of the springs and the masses increase along
|
| 843 |
+
the system length such that vibration frequencies are subsequent
|
| 844 |
+
integers 1, 2, ..., `n` where `n` is the number of the masses. Thus,
|
| 845 |
+
eigenvalues of the generalized eigenvalue problem for
|
| 846 |
+
the matrix pair `K` and `M` where `K` is the system stiffness matrix
|
| 847 |
+
and `M` is the system mass matrix are the squares of the integers,
|
| 848 |
+
i.e., 1, 4, 9, ..., ``n * n``.
|
| 849 |
+
|
| 850 |
+
The stiffness matrix `K` is square real tri-diagonal symmetric
|
| 851 |
+
positive definite. The mass matrix `M` is diagonal with diagonal
|
| 852 |
+
entries 1, 1/2, 1/3, ...., ``1/n``. Both matrices get
|
| 853 |
+
ill-conditioned with `n` growing.
|
| 854 |
+
|
| 855 |
+
Parameters
|
| 856 |
+
----------
|
| 857 |
+
n : int
|
| 858 |
+
The size of the matrices of the Mikota pair.
|
| 859 |
+
dtype : dtype
|
| 860 |
+
Numerical type of the array. Default is ``np.float64``.
|
| 861 |
+
|
| 862 |
+
Attributes
|
| 863 |
+
----------
|
| 864 |
+
eigenvalues : 1D ndarray, ``np.uint64``
|
| 865 |
+
All eigenvalues of the Mikota pair ordered ascending.
|
| 866 |
+
|
| 867 |
+
Methods
|
| 868 |
+
-------
|
| 869 |
+
MikotaK()
|
| 870 |
+
A `LinearOperator` custom object for the stiffness matrix.
|
| 871 |
+
MikotaM()
|
| 872 |
+
A `LinearOperator` custom object for the mass matrix.
|
| 873 |
+
|
| 874 |
+
.. versionadded:: 1.12.0
|
| 875 |
+
|
| 876 |
+
References
|
| 877 |
+
----------
|
| 878 |
+
.. [1] J. Mikota, "Frequency tuning of chain structure multibody oscillators
|
| 879 |
+
to place the natural frequencies at omega1 and N-1 integer multiples
|
| 880 |
+
omega2,..., omegaN", Z. Angew. Math. Mech. 81 (2001), S2, S201-S202.
|
| 881 |
+
Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004).
|
| 882 |
+
.. [2] Peter C. Muller and Metin Gurgoze,
|
| 883 |
+
"Natural frequencies of a multi-degree-of-freedom vibration system",
|
| 884 |
+
Proc. Appl. Math. Mech. 6, 319-320 (2006).
|
| 885 |
+
http://dx.doi.org/10.1002/pamm.200610141.
|
| 886 |
+
|
| 887 |
+
Examples
|
| 888 |
+
--------
|
| 889 |
+
>>> import numpy as np
|
| 890 |
+
>>> from scipy.sparse.linalg._special_sparse_arrays import MikotaPair
|
| 891 |
+
>>> n = 6
|
| 892 |
+
>>> mik = MikotaPair(n)
|
| 893 |
+
>>> mik_k = mik.k
|
| 894 |
+
>>> mik_m = mik.m
|
| 895 |
+
>>> mik_k.toarray()
|
| 896 |
+
array([[11., -5., 0., 0., 0., 0.],
|
| 897 |
+
[-5., 9., -4., 0., 0., 0.],
|
| 898 |
+
[ 0., -4., 7., -3., 0., 0.],
|
| 899 |
+
[ 0., 0., -3., 5., -2., 0.],
|
| 900 |
+
[ 0., 0., 0., -2., 3., -1.],
|
| 901 |
+
[ 0., 0., 0., 0., -1., 1.]])
|
| 902 |
+
>>> mik_k.tobanded()
|
| 903 |
+
array([[ 0., -5., -4., -3., -2., -1.],
|
| 904 |
+
[11., 9., 7., 5., 3., 1.]])
|
| 905 |
+
>>> mik_m.tobanded()
|
| 906 |
+
array([1. , 0.5 , 0.33333333, 0.25 , 0.2 ,
|
| 907 |
+
0.16666667])
|
| 908 |
+
>>> mik_k.tosparse()
|
| 909 |
+
<DIAgonal sparse array of dtype 'float64'
|
| 910 |
+
with 20 stored elements (3 diagonals) and shape (6, 6)>
|
| 911 |
+
>>> mik_m.tosparse()
|
| 912 |
+
<DIAgonal sparse array of dtype 'float64'
|
| 913 |
+
with 6 stored elements (1 diagonals) and shape (6, 6)>
|
| 914 |
+
>>> np.array_equal(mik_k(np.eye(n)), mik_k.toarray())
|
| 915 |
+
True
|
| 916 |
+
>>> np.array_equal(mik_m(np.eye(n)), mik_m.toarray())
|
| 917 |
+
True
|
| 918 |
+
>>> mik.eigenvalues()
|
| 919 |
+
array([ 1, 4, 9, 16, 25, 36])
|
| 920 |
+
>>> mik.eigenvalues(2)
|
| 921 |
+
array([ 1, 4])
|
| 922 |
+
|
| 923 |
+
"""
|
| 924 |
+
def __init__(self, n, dtype=np.float64):
|
| 925 |
+
self.n = n
|
| 926 |
+
self.dtype = dtype
|
| 927 |
+
self.shape = (n, n)
|
| 928 |
+
self.m = MikotaM(self.shape, self.dtype)
|
| 929 |
+
self.k = MikotaK(self.shape, self.dtype)
|
| 930 |
+
|
| 931 |
+
def eigenvalues(self, m=None):
|
| 932 |
+
"""Return the requested number of eigenvalues.
|
| 933 |
+
|
| 934 |
+
Parameters
|
| 935 |
+
----------
|
| 936 |
+
m : int, optional
|
| 937 |
+
The positive number of smallest eigenvalues to return.
|
| 938 |
+
If not provided, then all eigenvalues will be returned.
|
| 939 |
+
|
| 940 |
+
Returns
|
| 941 |
+
-------
|
| 942 |
+
eigenvalues : `np.uint64` array
|
| 943 |
+
The requested `m` smallest or all eigenvalues, in ascending order.
|
| 944 |
+
"""
|
| 945 |
+
if m is None:
|
| 946 |
+
m = self.n
|
| 947 |
+
arange_plus1 = np.arange(1, m + 1, dtype=np.uint64)
|
| 948 |
+
return arange_plus1 * arange_plus1
|
parrot/lib/python3.10/site-packages/scipy/sparse/linalg/matfuncs.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse.linalg` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = ["expm", "inv", "spsolve", "LinearOperator"] # noqa: F822
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def __dir__():
|
| 12 |
+
return __all__
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def __getattr__(name):
|
| 16 |
+
return _sub_module_deprecation(sub_package="sparse.linalg", module="matfuncs",
|
| 17 |
+
private_modules=["_matfuncs"], all=__all__,
|
| 18 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/sparsetools.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__: list[str] = []
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="sparse", module="sparsetools",
|
| 16 |
+
private_modules=["_sparsetools"], all=__all__,
|
| 17 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/spfuncs.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__: list[str] = []
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="sparse", module="spfuncs",
|
| 16 |
+
private_modules=["_spfuncs"], all=__all__,
|
| 17 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/sputils.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.sparse` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__: list[str] = []
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="sparse", module="sputils",
|
| 16 |
+
private_modules=["_sputils"], all=__all__,
|
| 17 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/__init__.py
ADDED
|
File without changes
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_arithmetic1d.cpython-310.pyc
ADDED
|
Binary file (10.5 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_coo.cpython-310.pyc
ADDED
|
Binary file (9.19 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_csc.cpython-310.pyc
ADDED
|
Binary file (2.44 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_minmax1d.cpython-310.pyc
ADDED
|
Binary file (4.11 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_spfuncs.cpython-310.pyc
ADDED
|
Binary file (3.67 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_sputils.cpython-310.pyc
ADDED
|
Binary file (5.82 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_arithmetic1d.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test of 1D arithmetic operations"""
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from numpy.testing import assert_equal, assert_allclose
|
| 7 |
+
|
| 8 |
+
from scipy.sparse import coo_array, csr_array
|
| 9 |
+
from scipy.sparse._sputils import isscalarlike
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
spcreators = [coo_array, csr_array]
|
| 13 |
+
math_dtypes = [np.int64, np.float64, np.complex128]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def toarray(a):
|
| 17 |
+
if isinstance(a, np.ndarray) or isscalarlike(a):
|
| 18 |
+
return a
|
| 19 |
+
return a.toarray()
|
| 20 |
+
|
| 21 |
+
@pytest.fixture
|
| 22 |
+
def dat1d():
|
| 23 |
+
return np.array([3, 0, 1, 0], 'd')
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@pytest.fixture
|
| 27 |
+
def datsp_math_dtypes(dat1d):
|
| 28 |
+
dat_dtypes = {dtype: dat1d.astype(dtype) for dtype in math_dtypes}
|
| 29 |
+
return {
|
| 30 |
+
sp: [(dtype, dat, sp(dat)) for dtype, dat in dat_dtypes.items()]
|
| 31 |
+
for sp in spcreators
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@pytest.mark.parametrize("spcreator", spcreators)
|
| 36 |
+
class TestArithmetic1D:
|
| 37 |
+
def test_empty_arithmetic(self, spcreator):
|
| 38 |
+
shape = (5,)
|
| 39 |
+
for mytype in [
|
| 40 |
+
np.dtype('int32'),
|
| 41 |
+
np.dtype('float32'),
|
| 42 |
+
np.dtype('float64'),
|
| 43 |
+
np.dtype('complex64'),
|
| 44 |
+
np.dtype('complex128'),
|
| 45 |
+
]:
|
| 46 |
+
a = spcreator(shape, dtype=mytype)
|
| 47 |
+
b = a + a
|
| 48 |
+
c = 2 * a
|
| 49 |
+
assert isinstance(a @ a.tocsr(), np.ndarray)
|
| 50 |
+
assert isinstance(a @ a.tocoo(), np.ndarray)
|
| 51 |
+
for m in [a, b, c]:
|
| 52 |
+
assert m @ m == a.toarray() @ a.toarray()
|
| 53 |
+
assert m.dtype == mytype
|
| 54 |
+
assert toarray(m).dtype == mytype
|
| 55 |
+
|
| 56 |
+
def test_abs(self, spcreator):
|
| 57 |
+
A = np.array([-1, 0, 17, 0, -5, 0, 1, -4, 0, 0, 0, 0], 'd')
|
| 58 |
+
assert_equal(abs(A), abs(spcreator(A)).toarray())
|
| 59 |
+
|
| 60 |
+
def test_round(self, spcreator):
|
| 61 |
+
A = np.array([-1.35, 0.56, 17.25, -5.98], 'd')
|
| 62 |
+
Asp = spcreator(A)
|
| 63 |
+
assert_equal(np.around(A, decimals=1), round(Asp, ndigits=1).toarray())
|
| 64 |
+
|
| 65 |
+
def test_elementwise_power(self, spcreator):
|
| 66 |
+
A = np.array([-4, -3, -2, -1, 0, 1, 2, 3, 4], 'd')
|
| 67 |
+
Asp = spcreator(A)
|
| 68 |
+
assert_equal(np.power(A, 2), Asp.power(2).toarray())
|
| 69 |
+
|
| 70 |
+
# element-wise power function needs a scalar power
|
| 71 |
+
with pytest.raises(NotImplementedError, match='input is not scalar'):
|
| 72 |
+
spcreator(A).power(A)
|
| 73 |
+
|
| 74 |
+
def test_real(self, spcreator):
|
| 75 |
+
D = np.array([1 + 3j, 2 - 4j])
|
| 76 |
+
A = spcreator(D)
|
| 77 |
+
assert_equal(A.real.toarray(), D.real)
|
| 78 |
+
|
| 79 |
+
def test_imag(self, spcreator):
|
| 80 |
+
D = np.array([1 + 3j, 2 - 4j])
|
| 81 |
+
A = spcreator(D)
|
| 82 |
+
assert_equal(A.imag.toarray(), D.imag)
|
| 83 |
+
|
| 84 |
+
def test_mul_scalar(self, spcreator, datsp_math_dtypes):
|
| 85 |
+
for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
|
| 86 |
+
assert_equal(dat * 2, (datsp * 2).toarray())
|
| 87 |
+
assert_equal(dat * 17.3, (datsp * 17.3).toarray())
|
| 88 |
+
|
| 89 |
+
def test_rmul_scalar(self, spcreator, datsp_math_dtypes):
|
| 90 |
+
for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
|
| 91 |
+
assert_equal(2 * dat, (2 * datsp).toarray())
|
| 92 |
+
assert_equal(17.3 * dat, (17.3 * datsp).toarray())
|
| 93 |
+
|
| 94 |
+
def test_sub(self, spcreator, datsp_math_dtypes):
|
| 95 |
+
for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
|
| 96 |
+
if dtype == np.dtype('bool'):
|
| 97 |
+
# boolean array subtraction deprecated in 1.9.0
|
| 98 |
+
continue
|
| 99 |
+
|
| 100 |
+
assert_equal((datsp - datsp).toarray(), np.zeros(4))
|
| 101 |
+
assert_equal((datsp - 0).toarray(), dat)
|
| 102 |
+
|
| 103 |
+
A = spcreator([1, -4, 0, 2], dtype='d')
|
| 104 |
+
assert_equal((datsp - A).toarray(), dat - A.toarray())
|
| 105 |
+
assert_equal((A - datsp).toarray(), A.toarray() - dat)
|
| 106 |
+
|
| 107 |
+
# test broadcasting
|
| 108 |
+
assert_equal(datsp.toarray() - dat[0], dat - dat[0])
|
| 109 |
+
|
| 110 |
+
def test_add0(self, spcreator, datsp_math_dtypes):
|
| 111 |
+
for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
|
| 112 |
+
# Adding 0 to a sparse matrix
|
| 113 |
+
assert_equal((datsp + 0).toarray(), dat)
|
| 114 |
+
# use sum (which takes 0 as a starting value)
|
| 115 |
+
sumS = sum([k * datsp for k in range(1, 3)])
|
| 116 |
+
sumD = sum([k * dat for k in range(1, 3)])
|
| 117 |
+
assert_allclose(sumS.toarray(), sumD)
|
| 118 |
+
|
| 119 |
+
def test_elementwise_multiply(self, spcreator):
|
| 120 |
+
# real/real
|
| 121 |
+
A = np.array([4, 0, 9])
|
| 122 |
+
B = np.array([0, 7, -1])
|
| 123 |
+
Asp = spcreator(A)
|
| 124 |
+
Bsp = spcreator(B)
|
| 125 |
+
assert_allclose(Asp.multiply(Bsp).toarray(), A * B) # sparse/sparse
|
| 126 |
+
assert_allclose(Asp.multiply(B).toarray(), A * B) # sparse/dense
|
| 127 |
+
|
| 128 |
+
# complex/complex
|
| 129 |
+
C = np.array([1 - 2j, 0 + 5j, -1 + 0j])
|
| 130 |
+
D = np.array([5 + 2j, 7 - 3j, -2 + 1j])
|
| 131 |
+
Csp = spcreator(C)
|
| 132 |
+
Dsp = spcreator(D)
|
| 133 |
+
assert_allclose(Csp.multiply(Dsp).toarray(), C * D) # sparse/sparse
|
| 134 |
+
assert_allclose(Csp.multiply(D).toarray(), C * D) # sparse/dense
|
| 135 |
+
|
| 136 |
+
# real/complex
|
| 137 |
+
assert_allclose(Asp.multiply(Dsp).toarray(), A * D) # sparse/sparse
|
| 138 |
+
assert_allclose(Asp.multiply(D).toarray(), A * D) # sparse/dense
|
| 139 |
+
|
| 140 |
+
def test_elementwise_multiply_broadcast(self, spcreator):
|
| 141 |
+
A = np.array([4])
|
| 142 |
+
B = np.array([[-9]])
|
| 143 |
+
C = np.array([1, -1, 0])
|
| 144 |
+
D = np.array([[7, 9, -9]])
|
| 145 |
+
E = np.array([[3], [2], [1]])
|
| 146 |
+
F = np.array([[8, 6, 3], [-4, 3, 2], [6, 6, 6]])
|
| 147 |
+
G = [1, 2, 3]
|
| 148 |
+
H = np.ones((3, 4))
|
| 149 |
+
J = H.T
|
| 150 |
+
K = np.array([[0]])
|
| 151 |
+
L = np.array([[[1, 2], [0, 1]]])
|
| 152 |
+
|
| 153 |
+
# Some arrays can't be cast as spmatrices (A, C, L) so leave
|
| 154 |
+
# them out.
|
| 155 |
+
Asp = spcreator(A)
|
| 156 |
+
Csp = spcreator(C)
|
| 157 |
+
Gsp = spcreator(G)
|
| 158 |
+
# 2d arrays
|
| 159 |
+
Bsp = spcreator(B)
|
| 160 |
+
Dsp = spcreator(D)
|
| 161 |
+
Esp = spcreator(E)
|
| 162 |
+
Fsp = spcreator(F)
|
| 163 |
+
Hsp = spcreator(H)
|
| 164 |
+
Hspp = spcreator(H[0, None])
|
| 165 |
+
Jsp = spcreator(J)
|
| 166 |
+
Jspp = spcreator(J[:, 0, None])
|
| 167 |
+
Ksp = spcreator(K)
|
| 168 |
+
|
| 169 |
+
matrices = [A, B, C, D, E, F, G, H, J, K, L]
|
| 170 |
+
spmatrices = [Asp, Bsp, Csp, Dsp, Esp, Fsp, Gsp, Hsp, Hspp, Jsp, Jspp, Ksp]
|
| 171 |
+
sp1dmatrices = [Asp, Csp, Gsp]
|
| 172 |
+
|
| 173 |
+
# sparse/sparse
|
| 174 |
+
for i in sp1dmatrices:
|
| 175 |
+
for j in spmatrices:
|
| 176 |
+
try:
|
| 177 |
+
dense_mult = i.toarray() * j.toarray()
|
| 178 |
+
except ValueError:
|
| 179 |
+
with pytest.raises(ValueError, match='inconsistent shapes'):
|
| 180 |
+
i.multiply(j)
|
| 181 |
+
continue
|
| 182 |
+
sp_mult = i.multiply(j)
|
| 183 |
+
assert_allclose(sp_mult.toarray(), dense_mult)
|
| 184 |
+
|
| 185 |
+
# sparse/dense
|
| 186 |
+
for i in sp1dmatrices:
|
| 187 |
+
for j in matrices:
|
| 188 |
+
try:
|
| 189 |
+
dense_mult = i.toarray() * j
|
| 190 |
+
except TypeError:
|
| 191 |
+
continue
|
| 192 |
+
except ValueError:
|
| 193 |
+
matchme = 'broadcast together|inconsistent shapes'
|
| 194 |
+
with pytest.raises(ValueError, match=matchme):
|
| 195 |
+
i.multiply(j)
|
| 196 |
+
continue
|
| 197 |
+
sp_mult = i.multiply(j)
|
| 198 |
+
assert_allclose(toarray(sp_mult), dense_mult)
|
| 199 |
+
|
| 200 |
+
def test_elementwise_divide(self, spcreator, dat1d):
|
| 201 |
+
datsp = spcreator(dat1d)
|
| 202 |
+
expected = np.array([1, np.nan, 1, np.nan])
|
| 203 |
+
actual = datsp / datsp
|
| 204 |
+
# need assert_array_equal to handle nan values
|
| 205 |
+
np.testing.assert_array_equal(actual, expected)
|
| 206 |
+
|
| 207 |
+
denom = spcreator([1, 0, 0, 4], dtype='d')
|
| 208 |
+
expected = [3, np.nan, np.inf, 0]
|
| 209 |
+
np.testing.assert_array_equal(datsp / denom, expected)
|
| 210 |
+
|
| 211 |
+
# complex
|
| 212 |
+
A = np.array([1 - 2j, 0 + 5j, -1 + 0j])
|
| 213 |
+
B = np.array([5 + 2j, 7 - 3j, -2 + 1j])
|
| 214 |
+
Asp = spcreator(A)
|
| 215 |
+
Bsp = spcreator(B)
|
| 216 |
+
assert_allclose(Asp / Bsp, A / B)
|
| 217 |
+
|
| 218 |
+
# integer
|
| 219 |
+
A = np.array([1, 2, 3])
|
| 220 |
+
B = np.array([0, 1, 2])
|
| 221 |
+
Asp = spcreator(A)
|
| 222 |
+
Bsp = spcreator(B)
|
| 223 |
+
with np.errstate(divide='ignore'):
|
| 224 |
+
assert_equal(Asp / Bsp, A / B)
|
| 225 |
+
|
| 226 |
+
# mismatching sparsity patterns
|
| 227 |
+
A = np.array([0, 1])
|
| 228 |
+
B = np.array([1, 0])
|
| 229 |
+
Asp = spcreator(A)
|
| 230 |
+
Bsp = spcreator(B)
|
| 231 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
| 232 |
+
assert_equal(Asp / Bsp, A / B)
|
| 233 |
+
|
| 234 |
+
def test_pow(self, spcreator):
|
| 235 |
+
A = np.array([1, 0, 2, 0])
|
| 236 |
+
B = spcreator(A)
|
| 237 |
+
|
| 238 |
+
# unusual exponents
|
| 239 |
+
with pytest.raises(ValueError, match='negative integer powers'):
|
| 240 |
+
B**-1
|
| 241 |
+
with pytest.raises(NotImplementedError, match='zero power'):
|
| 242 |
+
B**0
|
| 243 |
+
|
| 244 |
+
for exponent in [1, 2, 3, 2.2]:
|
| 245 |
+
ret_sp = B**exponent
|
| 246 |
+
ret_np = A**exponent
|
| 247 |
+
assert_equal(ret_sp.toarray(), ret_np)
|
| 248 |
+
assert_equal(ret_sp.dtype, ret_np.dtype)
|
| 249 |
+
|
| 250 |
+
def test_dot_scalar(self, spcreator, dat1d):
|
| 251 |
+
A = spcreator(dat1d)
|
| 252 |
+
scalar = 10
|
| 253 |
+
actual = A.dot(scalar)
|
| 254 |
+
expected = A * scalar
|
| 255 |
+
|
| 256 |
+
assert_allclose(actual.toarray(), expected.toarray())
|
| 257 |
+
|
| 258 |
+
def test_matmul(self, spcreator):
|
| 259 |
+
Msp = spcreator([2, 0, 3.0])
|
| 260 |
+
B = spcreator(np.array([[0, 1], [1, 0], [0, 2]], 'd'))
|
| 261 |
+
col = np.array([[1, 2, 3]]).T
|
| 262 |
+
|
| 263 |
+
# check sparse @ dense 2d column
|
| 264 |
+
assert_allclose(Msp @ col, Msp.toarray() @ col)
|
| 265 |
+
|
| 266 |
+
# check sparse1d @ sparse2d, sparse1d @ dense2d, dense1d @ sparse2d
|
| 267 |
+
assert_allclose((Msp @ B).toarray(), (Msp @ B).toarray())
|
| 268 |
+
assert_allclose(Msp.toarray() @ B, (Msp @ B).toarray())
|
| 269 |
+
assert_allclose(Msp @ B.toarray(), (Msp @ B).toarray())
|
| 270 |
+
|
| 271 |
+
# check sparse1d @ dense1d, sparse1d @ sparse1d
|
| 272 |
+
V = np.array([0, 0, 1])
|
| 273 |
+
assert_allclose(Msp @ V, Msp.toarray() @ V)
|
| 274 |
+
|
| 275 |
+
Vsp = spcreator(V)
|
| 276 |
+
Msp_Vsp = Msp @ Vsp
|
| 277 |
+
assert isinstance(Msp_Vsp, np.ndarray)
|
| 278 |
+
assert Msp_Vsp.shape == ()
|
| 279 |
+
|
| 280 |
+
# output is 0-dim ndarray
|
| 281 |
+
assert_allclose(np.array(3), Msp_Vsp)
|
| 282 |
+
assert_allclose(np.array(3), Msp.toarray() @ Vsp)
|
| 283 |
+
assert_allclose(np.array(3), Msp @ Vsp.toarray())
|
| 284 |
+
assert_allclose(np.array(3), Msp.toarray() @ Vsp.toarray())
|
| 285 |
+
|
| 286 |
+
# check error on matrix-scalar
|
| 287 |
+
with pytest.raises(ValueError, match='Scalar operands are not allowed'):
|
| 288 |
+
Msp @ 1
|
| 289 |
+
with pytest.raises(ValueError, match='Scalar operands are not allowed'):
|
| 290 |
+
1 @ Msp
|
| 291 |
+
|
| 292 |
+
def test_sub_dense(self, spcreator, datsp_math_dtypes):
|
| 293 |
+
# subtracting a dense matrix to/from a sparse matrix
|
| 294 |
+
for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
|
| 295 |
+
if dtype == np.dtype('bool'):
|
| 296 |
+
# boolean array subtraction deprecated in 1.9.0
|
| 297 |
+
continue
|
| 298 |
+
|
| 299 |
+
# Manually add to avoid upcasting from scalar
|
| 300 |
+
# multiplication.
|
| 301 |
+
sum1 = (dat + dat + dat) - datsp
|
| 302 |
+
assert_equal(sum1, dat + dat)
|
| 303 |
+
sum2 = (datsp + datsp + datsp) - dat
|
| 304 |
+
assert_equal(sum2, dat + dat)
|
| 305 |
+
|
| 306 |
+
def test_size_zero_matrix_arithmetic(self, spcreator):
|
| 307 |
+
# Test basic matrix arithmetic with shapes like 0, (1, 0), (0, 3), etc.
|
| 308 |
+
mat = np.array([])
|
| 309 |
+
a = mat.reshape(0)
|
| 310 |
+
d = mat.reshape((1, 0))
|
| 311 |
+
f = np.ones([5, 5])
|
| 312 |
+
|
| 313 |
+
asp = spcreator(a)
|
| 314 |
+
dsp = spcreator(d)
|
| 315 |
+
# bad shape for addition
|
| 316 |
+
with pytest.raises(ValueError, match='inconsistent shapes'):
|
| 317 |
+
asp.__add__(dsp)
|
| 318 |
+
|
| 319 |
+
# matrix product.
|
| 320 |
+
assert_equal(asp.dot(asp), np.dot(a, a))
|
| 321 |
+
|
| 322 |
+
# bad matrix products
|
| 323 |
+
with pytest.raises(ValueError, match='dimension mismatch'):
|
| 324 |
+
asp.dot(f)
|
| 325 |
+
|
| 326 |
+
# elemente-wise multiplication
|
| 327 |
+
assert_equal(asp.multiply(asp).toarray(), np.multiply(a, a))
|
| 328 |
+
|
| 329 |
+
assert_equal(asp.multiply(a).toarray(), np.multiply(a, a))
|
| 330 |
+
|
| 331 |
+
assert_equal(asp.multiply(6).toarray(), np.multiply(a, 6))
|
| 332 |
+
|
| 333 |
+
# bad element-wise multiplication
|
| 334 |
+
with pytest.raises(ValueError, match='inconsistent shapes'):
|
| 335 |
+
asp.multiply(f)
|
| 336 |
+
|
| 337 |
+
# Addition
|
| 338 |
+
assert_equal(asp.__add__(asp).toarray(), a.__add__(a))
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_base.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_construct.py
ADDED
|
@@ -0,0 +1,836 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""test sparse matrix construction functions"""
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from numpy import array
|
| 5 |
+
from numpy.testing import (assert_equal, assert_,
|
| 6 |
+
assert_array_equal, assert_array_almost_equal_nulp)
|
| 7 |
+
import pytest
|
| 8 |
+
from pytest import raises as assert_raises
|
| 9 |
+
from scipy._lib._testutils import check_free_memory
|
| 10 |
+
from scipy._lib._util import check_random_state
|
| 11 |
+
|
| 12 |
+
from scipy.sparse import (csr_matrix, coo_matrix,
|
| 13 |
+
csr_array, coo_array,
|
| 14 |
+
csc_array, bsr_array,
|
| 15 |
+
dia_array, dok_array,
|
| 16 |
+
lil_array, csc_matrix,
|
| 17 |
+
bsr_matrix, dia_matrix,
|
| 18 |
+
lil_matrix, sparray, spmatrix,
|
| 19 |
+
_construct as construct)
|
| 20 |
+
from scipy.sparse._construct import rand as sprand
|
| 21 |
+
|
| 22 |
+
sparse_formats = ['csr','csc','coo','bsr','dia','lil','dok']
|
| 23 |
+
|
| 24 |
+
#TODO check whether format=XXX is respected
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _sprandn(m, n, density=0.01, format="coo", dtype=None, random_state=None):
|
| 28 |
+
# Helper function for testing.
|
| 29 |
+
random_state = check_random_state(random_state)
|
| 30 |
+
data_rvs = random_state.standard_normal
|
| 31 |
+
return construct.random(m, n, density, format, dtype,
|
| 32 |
+
random_state, data_rvs)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _sprandn_array(m, n, density=0.01, format="coo", dtype=None, random_state=None):
|
| 36 |
+
# Helper function for testing.
|
| 37 |
+
random_state = check_random_state(random_state)
|
| 38 |
+
data_sampler = random_state.standard_normal
|
| 39 |
+
return construct.random_array((m, n), density=density, format=format, dtype=dtype,
|
| 40 |
+
random_state=random_state, data_sampler=data_sampler)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class TestConstructUtils:
|
| 44 |
+
|
| 45 |
+
@pytest.mark.parametrize("cls", [
|
| 46 |
+
csc_array, csr_array, coo_array, bsr_array,
|
| 47 |
+
dia_array, dok_array, lil_array
|
| 48 |
+
])
|
| 49 |
+
def test_singleton_array_constructor(self, cls):
|
| 50 |
+
with pytest.raises(
|
| 51 |
+
ValueError,
|
| 52 |
+
match=(
|
| 53 |
+
'scipy sparse array classes do not support '
|
| 54 |
+
'instantiation from a scalar'
|
| 55 |
+
)
|
| 56 |
+
):
|
| 57 |
+
cls(0)
|
| 58 |
+
|
| 59 |
+
@pytest.mark.parametrize("cls", [
|
| 60 |
+
csc_matrix, csr_matrix, coo_matrix,
|
| 61 |
+
bsr_matrix, dia_matrix, lil_matrix
|
| 62 |
+
])
|
| 63 |
+
def test_singleton_matrix_constructor(self, cls):
|
| 64 |
+
"""
|
| 65 |
+
This test is for backwards compatibility post scipy 1.13.
|
| 66 |
+
The behavior observed here is what is to be expected
|
| 67 |
+
with the older matrix classes. This test comes with the
|
| 68 |
+
exception of dok_matrix, which was not working pre scipy1.12
|
| 69 |
+
(unlike the rest of these).
|
| 70 |
+
"""
|
| 71 |
+
assert cls(0).shape == (1, 1)
|
| 72 |
+
|
| 73 |
+
def test_spdiags(self):
|
| 74 |
+
diags1 = array([[1, 2, 3, 4, 5]])
|
| 75 |
+
diags2 = array([[1, 2, 3, 4, 5],
|
| 76 |
+
[6, 7, 8, 9,10]])
|
| 77 |
+
diags3 = array([[1, 2, 3, 4, 5],
|
| 78 |
+
[6, 7, 8, 9,10],
|
| 79 |
+
[11,12,13,14,15]])
|
| 80 |
+
|
| 81 |
+
cases = []
|
| 82 |
+
cases.append((diags1, 0, 1, 1, [[1]]))
|
| 83 |
+
cases.append((diags1, [0], 1, 1, [[1]]))
|
| 84 |
+
cases.append((diags1, [0], 2, 1, [[1],[0]]))
|
| 85 |
+
cases.append((diags1, [0], 1, 2, [[1,0]]))
|
| 86 |
+
cases.append((diags1, [1], 1, 2, [[0,2]]))
|
| 87 |
+
cases.append((diags1,[-1], 1, 2, [[0,0]]))
|
| 88 |
+
cases.append((diags1, [0], 2, 2, [[1,0],[0,2]]))
|
| 89 |
+
cases.append((diags1,[-1], 2, 2, [[0,0],[1,0]]))
|
| 90 |
+
cases.append((diags1, [3], 2, 2, [[0,0],[0,0]]))
|
| 91 |
+
cases.append((diags1, [0], 3, 4, [[1,0,0,0],[0,2,0,0],[0,0,3,0]]))
|
| 92 |
+
cases.append((diags1, [1], 3, 4, [[0,2,0,0],[0,0,3,0],[0,0,0,4]]))
|
| 93 |
+
cases.append((diags1, [2], 3, 5, [[0,0,3,0,0],[0,0,0,4,0],[0,0,0,0,5]]))
|
| 94 |
+
|
| 95 |
+
cases.append((diags2, [0,2], 3, 3, [[1,0,8],[0,2,0],[0,0,3]]))
|
| 96 |
+
cases.append((diags2, [-1,0], 3, 4, [[6,0,0,0],[1,7,0,0],[0,2,8,0]]))
|
| 97 |
+
cases.append((diags2, [2,-3], 6, 6, [[0,0,3,0,0,0],
|
| 98 |
+
[0,0,0,4,0,0],
|
| 99 |
+
[0,0,0,0,5,0],
|
| 100 |
+
[6,0,0,0,0,0],
|
| 101 |
+
[0,7,0,0,0,0],
|
| 102 |
+
[0,0,8,0,0,0]]))
|
| 103 |
+
|
| 104 |
+
cases.append((diags3, [-1,0,1], 6, 6, [[6,12, 0, 0, 0, 0],
|
| 105 |
+
[1, 7,13, 0, 0, 0],
|
| 106 |
+
[0, 2, 8,14, 0, 0],
|
| 107 |
+
[0, 0, 3, 9,15, 0],
|
| 108 |
+
[0, 0, 0, 4,10, 0],
|
| 109 |
+
[0, 0, 0, 0, 5, 0]]))
|
| 110 |
+
cases.append((diags3, [-4,2,-1], 6, 5, [[0, 0, 8, 0, 0],
|
| 111 |
+
[11, 0, 0, 9, 0],
|
| 112 |
+
[0,12, 0, 0,10],
|
| 113 |
+
[0, 0,13, 0, 0],
|
| 114 |
+
[1, 0, 0,14, 0],
|
| 115 |
+
[0, 2, 0, 0,15]]))
|
| 116 |
+
cases.append((diags3, [-1, 1, 2], len(diags3[0]), len(diags3[0]),
|
| 117 |
+
[[0, 7, 13, 0, 0],
|
| 118 |
+
[1, 0, 8, 14, 0],
|
| 119 |
+
[0, 2, 0, 9, 15],
|
| 120 |
+
[0, 0, 3, 0, 10],
|
| 121 |
+
[0, 0, 0, 4, 0]]))
|
| 122 |
+
|
| 123 |
+
for d, o, m, n, result in cases:
|
| 124 |
+
if len(d[0]) == m and m == n:
|
| 125 |
+
assert_equal(construct.spdiags(d, o).toarray(), result)
|
| 126 |
+
assert_equal(construct.spdiags(d, o, m, n).toarray(), result)
|
| 127 |
+
assert_equal(construct.spdiags(d, o, (m, n)).toarray(), result)
|
| 128 |
+
|
| 129 |
+
def test_diags(self):
|
| 130 |
+
a = array([1, 2, 3, 4, 5])
|
| 131 |
+
b = array([6, 7, 8, 9, 10])
|
| 132 |
+
c = array([11, 12, 13, 14, 15])
|
| 133 |
+
|
| 134 |
+
cases = []
|
| 135 |
+
cases.append((a[:1], 0, (1, 1), [[1]]))
|
| 136 |
+
cases.append(([a[:1]], [0], (1, 1), [[1]]))
|
| 137 |
+
cases.append(([a[:1]], [0], (2, 1), [[1],[0]]))
|
| 138 |
+
cases.append(([a[:1]], [0], (1, 2), [[1,0]]))
|
| 139 |
+
cases.append(([a[:1]], [1], (1, 2), [[0,1]]))
|
| 140 |
+
cases.append(([a[:2]], [0], (2, 2), [[1,0],[0,2]]))
|
| 141 |
+
cases.append(([a[:1]],[-1], (2, 2), [[0,0],[1,0]]))
|
| 142 |
+
cases.append(([a[:3]], [0], (3, 4), [[1,0,0,0],[0,2,0,0],[0,0,3,0]]))
|
| 143 |
+
cases.append(([a[:3]], [1], (3, 4), [[0,1,0,0],[0,0,2,0],[0,0,0,3]]))
|
| 144 |
+
cases.append(([a[:1]], [-2], (3, 5), [[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,0]]))
|
| 145 |
+
cases.append(([a[:2]], [-1], (3, 5), [[0,0,0,0,0],[1,0,0,0,0],[0,2,0,0,0]]))
|
| 146 |
+
cases.append(([a[:3]], [0], (3, 5), [[1,0,0,0,0],[0,2,0,0,0],[0,0,3,0,0]]))
|
| 147 |
+
cases.append(([a[:3]], [1], (3, 5), [[0,1,0,0,0],[0,0,2,0,0],[0,0,0,3,0]]))
|
| 148 |
+
cases.append(([a[:3]], [2], (3, 5), [[0,0,1,0,0],[0,0,0,2,0],[0,0,0,0,3]]))
|
| 149 |
+
cases.append(([a[:2]], [3], (3, 5), [[0,0,0,1,0],[0,0,0,0,2],[0,0,0,0,0]]))
|
| 150 |
+
cases.append(([a[:1]], [4], (3, 5), [[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0]]))
|
| 151 |
+
cases.append(([a[:1]], [-4], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[1,0,0]]))
|
| 152 |
+
cases.append(([a[:2]], [-3], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[1,0,0],[0,2,0]]))
|
| 153 |
+
cases.append(([a[:3]], [-2], (5, 3), [[0,0,0],[0,0,0],[1,0,0],[0,2,0],[0,0,3]]))
|
| 154 |
+
cases.append(([a[:3]], [-1], (5, 3), [[0,0,0],[1,0,0],[0,2,0],[0,0,3],[0,0,0]]))
|
| 155 |
+
cases.append(([a[:3]], [0], (5, 3), [[1,0,0],[0,2,0],[0,0,3],[0,0,0],[0,0,0]]))
|
| 156 |
+
cases.append(([a[:2]], [1], (5, 3), [[0,1,0],[0,0,2],[0,0,0],[0,0,0],[0,0,0]]))
|
| 157 |
+
cases.append(([a[:1]], [2], (5, 3), [[0,0,1],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]))
|
| 158 |
+
|
| 159 |
+
cases.append(([a[:3],b[:1]], [0,2], (3, 3), [[1,0,6],[0,2,0],[0,0,3]]))
|
| 160 |
+
cases.append(([a[:2],b[:3]], [-1,0], (3, 4), [[6,0,0,0],[1,7,0,0],[0,2,8,0]]))
|
| 161 |
+
cases.append(([a[:4],b[:3]], [2,-3], (6, 6), [[0,0,1,0,0,0],
|
| 162 |
+
[0,0,0,2,0,0],
|
| 163 |
+
[0,0,0,0,3,0],
|
| 164 |
+
[6,0,0,0,0,4],
|
| 165 |
+
[0,7,0,0,0,0],
|
| 166 |
+
[0,0,8,0,0,0]]))
|
| 167 |
+
|
| 168 |
+
cases.append(([a[:4],b,c[:4]], [-1,0,1], (5, 5), [[6,11, 0, 0, 0],
|
| 169 |
+
[1, 7,12, 0, 0],
|
| 170 |
+
[0, 2, 8,13, 0],
|
| 171 |
+
[0, 0, 3, 9,14],
|
| 172 |
+
[0, 0, 0, 4,10]]))
|
| 173 |
+
cases.append(([a[:2],b[:3],c], [-4,2,-1], (6, 5), [[0, 0, 6, 0, 0],
|
| 174 |
+
[11, 0, 0, 7, 0],
|
| 175 |
+
[0,12, 0, 0, 8],
|
| 176 |
+
[0, 0,13, 0, 0],
|
| 177 |
+
[1, 0, 0,14, 0],
|
| 178 |
+
[0, 2, 0, 0,15]]))
|
| 179 |
+
|
| 180 |
+
# too long arrays are OK
|
| 181 |
+
cases.append(([a], [0], (1, 1), [[1]]))
|
| 182 |
+
cases.append(([a[:3],b], [0,2], (3, 3), [[1, 0, 6], [0, 2, 0], [0, 0, 3]]))
|
| 183 |
+
cases.append((
|
| 184 |
+
np.array([[1, 2, 3], [4, 5, 6]]),
|
| 185 |
+
[0,-1],
|
| 186 |
+
(3, 3),
|
| 187 |
+
[[1, 0, 0], [4, 2, 0], [0, 5, 3]]
|
| 188 |
+
))
|
| 189 |
+
|
| 190 |
+
# scalar case: broadcasting
|
| 191 |
+
cases.append(([1,-2,1], [1,0,-1], (3, 3), [[-2, 1, 0],
|
| 192 |
+
[1, -2, 1],
|
| 193 |
+
[0, 1, -2]]))
|
| 194 |
+
|
| 195 |
+
for d, o, shape, result in cases:
|
| 196 |
+
err_msg = f"{d!r} {o!r} {shape!r} {result!r}"
|
| 197 |
+
assert_equal(construct.diags(d, offsets=o, shape=shape).toarray(),
|
| 198 |
+
result, err_msg=err_msg)
|
| 199 |
+
|
| 200 |
+
if (shape[0] == shape[1]
|
| 201 |
+
and hasattr(d[0], '__len__')
|
| 202 |
+
and len(d[0]) <= max(shape)):
|
| 203 |
+
# should be able to find the shape automatically
|
| 204 |
+
assert_equal(construct.diags(d, offsets=o).toarray(), result,
|
| 205 |
+
err_msg=err_msg)
|
| 206 |
+
|
| 207 |
+
def test_diags_default(self):
|
| 208 |
+
a = array([1, 2, 3, 4, 5])
|
| 209 |
+
assert_equal(construct.diags(a).toarray(), np.diag(a))
|
| 210 |
+
|
| 211 |
+
def test_diags_default_bad(self):
|
| 212 |
+
a = array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])
|
| 213 |
+
assert_raises(ValueError, construct.diags, a)
|
| 214 |
+
|
| 215 |
+
def test_diags_bad(self):
|
| 216 |
+
a = array([1, 2, 3, 4, 5])
|
| 217 |
+
b = array([6, 7, 8, 9, 10])
|
| 218 |
+
c = array([11, 12, 13, 14, 15])
|
| 219 |
+
|
| 220 |
+
cases = []
|
| 221 |
+
cases.append(([a[:0]], 0, (1, 1)))
|
| 222 |
+
cases.append(([a[:4],b,c[:3]], [-1,0,1], (5, 5)))
|
| 223 |
+
cases.append(([a[:2],c,b[:3]], [-4,2,-1], (6, 5)))
|
| 224 |
+
cases.append(([a[:2],c,b[:3]], [-4,2,-1], None))
|
| 225 |
+
cases.append(([], [-4,2,-1], None))
|
| 226 |
+
cases.append(([1], [-5], (4, 4)))
|
| 227 |
+
cases.append(([a], 0, None))
|
| 228 |
+
|
| 229 |
+
for d, o, shape in cases:
|
| 230 |
+
assert_raises(ValueError, construct.diags, d, offsets=o, shape=shape)
|
| 231 |
+
|
| 232 |
+
assert_raises(TypeError, construct.diags, [[None]], offsets=[0])
|
| 233 |
+
|
| 234 |
+
def test_diags_vs_diag(self):
|
| 235 |
+
# Check that
|
| 236 |
+
#
|
| 237 |
+
# diags([a, b, ...], [i, j, ...]) == diag(a, i) + diag(b, j) + ...
|
| 238 |
+
#
|
| 239 |
+
|
| 240 |
+
np.random.seed(1234)
|
| 241 |
+
|
| 242 |
+
for n_diags in [1, 2, 3, 4, 5, 10]:
|
| 243 |
+
n = 1 + n_diags//2 + np.random.randint(0, 10)
|
| 244 |
+
|
| 245 |
+
offsets = np.arange(-n+1, n-1)
|
| 246 |
+
np.random.shuffle(offsets)
|
| 247 |
+
offsets = offsets[:n_diags]
|
| 248 |
+
|
| 249 |
+
diagonals = [np.random.rand(n - abs(q)) for q in offsets]
|
| 250 |
+
|
| 251 |
+
mat = construct.diags(diagonals, offsets=offsets)
|
| 252 |
+
dense_mat = sum([np.diag(x, j) for x, j in zip(diagonals, offsets)])
|
| 253 |
+
|
| 254 |
+
assert_array_almost_equal_nulp(mat.toarray(), dense_mat)
|
| 255 |
+
|
| 256 |
+
if len(offsets) == 1:
|
| 257 |
+
mat = construct.diags(diagonals[0], offsets=offsets[0])
|
| 258 |
+
dense_mat = np.diag(diagonals[0], offsets[0])
|
| 259 |
+
assert_array_almost_equal_nulp(mat.toarray(), dense_mat)
|
| 260 |
+
|
| 261 |
+
def test_diags_dtype(self):
|
| 262 |
+
x = construct.diags([2.2], offsets=[0], shape=(2, 2), dtype=int)
|
| 263 |
+
assert_equal(x.dtype, int)
|
| 264 |
+
assert_equal(x.toarray(), [[2, 0], [0, 2]])
|
| 265 |
+
|
| 266 |
+
def test_diags_one_diagonal(self):
|
| 267 |
+
d = list(range(5))
|
| 268 |
+
for k in range(-5, 6):
|
| 269 |
+
assert_equal(construct.diags(d, offsets=k).toarray(),
|
| 270 |
+
construct.diags([d], offsets=[k]).toarray())
|
| 271 |
+
|
| 272 |
+
def test_diags_empty(self):
|
| 273 |
+
x = construct.diags([])
|
| 274 |
+
assert_equal(x.shape, (0, 0))
|
| 275 |
+
|
| 276 |
+
@pytest.mark.parametrize("identity", [construct.identity, construct.eye_array])
|
| 277 |
+
def test_identity(self, identity):
|
| 278 |
+
assert_equal(identity(1).toarray(), [[1]])
|
| 279 |
+
assert_equal(identity(2).toarray(), [[1,0],[0,1]])
|
| 280 |
+
|
| 281 |
+
I = identity(3, dtype='int8', format='dia')
|
| 282 |
+
assert_equal(I.dtype, np.dtype('int8'))
|
| 283 |
+
assert_equal(I.format, 'dia')
|
| 284 |
+
|
| 285 |
+
for fmt in sparse_formats:
|
| 286 |
+
I = identity(3, format=fmt)
|
| 287 |
+
assert_equal(I.format, fmt)
|
| 288 |
+
assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]])
|
| 289 |
+
|
| 290 |
+
@pytest.mark.parametrize("eye", [construct.eye, construct.eye_array])
|
| 291 |
+
def test_eye(self, eye):
|
| 292 |
+
assert_equal(eye(1,1).toarray(), [[1]])
|
| 293 |
+
assert_equal(eye(2,3).toarray(), [[1,0,0],[0,1,0]])
|
| 294 |
+
assert_equal(eye(3,2).toarray(), [[1,0],[0,1],[0,0]])
|
| 295 |
+
assert_equal(eye(3,3).toarray(), [[1,0,0],[0,1,0],[0,0,1]])
|
| 296 |
+
|
| 297 |
+
assert_equal(eye(3,3,dtype='int16').dtype, np.dtype('int16'))
|
| 298 |
+
|
| 299 |
+
for m in [3, 5]:
|
| 300 |
+
for n in [3, 5]:
|
| 301 |
+
for k in range(-5,6):
|
| 302 |
+
# scipy.sparse.eye deviates from np.eye here. np.eye will
|
| 303 |
+
# create arrays of all 0's when the diagonal offset is
|
| 304 |
+
# greater than the size of the array. For sparse arrays
|
| 305 |
+
# this makes less sense, especially as it results in dia
|
| 306 |
+
# arrays with negative diagonals. Therefore sp.sparse.eye
|
| 307 |
+
# validates that diagonal offsets fall within the shape of
|
| 308 |
+
# the array. See gh-18555.
|
| 309 |
+
if (k > 0 and k > n) or (k < 0 and abs(k) > m):
|
| 310 |
+
with pytest.raises(
|
| 311 |
+
ValueError, match="Offset.*out of bounds"
|
| 312 |
+
):
|
| 313 |
+
eye(m, n, k=k)
|
| 314 |
+
|
| 315 |
+
else:
|
| 316 |
+
assert_equal(
|
| 317 |
+
eye(m, n, k=k).toarray(),
|
| 318 |
+
np.eye(m, n, k=k)
|
| 319 |
+
)
|
| 320 |
+
if m == n:
|
| 321 |
+
assert_equal(
|
| 322 |
+
eye(m, k=k).toarray(),
|
| 323 |
+
np.eye(m, n, k=k)
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
@pytest.mark.parametrize("eye", [construct.eye, construct.eye_array])
|
| 327 |
+
def test_eye_one(self, eye):
|
| 328 |
+
assert_equal(eye(1).toarray(), [[1]])
|
| 329 |
+
assert_equal(eye(2).toarray(), [[1,0],[0,1]])
|
| 330 |
+
|
| 331 |
+
I = eye(3, dtype='int8', format='dia')
|
| 332 |
+
assert_equal(I.dtype, np.dtype('int8'))
|
| 333 |
+
assert_equal(I.format, 'dia')
|
| 334 |
+
|
| 335 |
+
for fmt in sparse_formats:
|
| 336 |
+
I = eye(3, format=fmt)
|
| 337 |
+
assert_equal(I.format, fmt)
|
| 338 |
+
assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]])
|
| 339 |
+
|
| 340 |
+
def test_eye_array_vs_matrix(self):
|
| 341 |
+
assert isinstance(construct.eye_array(3), sparray)
|
| 342 |
+
assert not isinstance(construct.eye(3), sparray)
|
| 343 |
+
|
| 344 |
+
def test_kron(self):
|
| 345 |
+
cases = []
|
| 346 |
+
|
| 347 |
+
cases.append(array([[0]]))
|
| 348 |
+
cases.append(array([[-1]]))
|
| 349 |
+
cases.append(array([[4]]))
|
| 350 |
+
cases.append(array([[10]]))
|
| 351 |
+
cases.append(array([[0],[0]]))
|
| 352 |
+
cases.append(array([[0,0]]))
|
| 353 |
+
cases.append(array([[1,2],[3,4]]))
|
| 354 |
+
cases.append(array([[0,2],[5,0]]))
|
| 355 |
+
cases.append(array([[0,2,-6],[8,0,14]]))
|
| 356 |
+
cases.append(array([[5,4],[0,0],[6,0]]))
|
| 357 |
+
cases.append(array([[5,4,4],[1,0,0],[6,0,8]]))
|
| 358 |
+
cases.append(array([[0,1,0,2,0,5,8]]))
|
| 359 |
+
cases.append(array([[0.5,0.125,0,3.25],[0,2.5,0,0]]))
|
| 360 |
+
|
| 361 |
+
# test all cases with some formats
|
| 362 |
+
for a in cases:
|
| 363 |
+
ca = csr_array(a)
|
| 364 |
+
for b in cases:
|
| 365 |
+
cb = csr_array(b)
|
| 366 |
+
expected = np.kron(a, b)
|
| 367 |
+
for fmt in sparse_formats[1:4]:
|
| 368 |
+
result = construct.kron(ca, cb, format=fmt)
|
| 369 |
+
assert_equal(result.format, fmt)
|
| 370 |
+
assert_array_equal(result.toarray(), expected)
|
| 371 |
+
assert isinstance(result, sparray)
|
| 372 |
+
|
| 373 |
+
# test one case with all formats
|
| 374 |
+
a = cases[-1]
|
| 375 |
+
b = cases[-3]
|
| 376 |
+
ca = csr_array(a)
|
| 377 |
+
cb = csr_array(b)
|
| 378 |
+
|
| 379 |
+
expected = np.kron(a, b)
|
| 380 |
+
for fmt in sparse_formats:
|
| 381 |
+
result = construct.kron(ca, cb, format=fmt)
|
| 382 |
+
assert_equal(result.format, fmt)
|
| 383 |
+
assert_array_equal(result.toarray(), expected)
|
| 384 |
+
assert isinstance(result, sparray)
|
| 385 |
+
|
| 386 |
+
# check that spmatrix returned when both inputs are spmatrix
|
| 387 |
+
result = construct.kron(csr_matrix(a), csr_matrix(b), format=fmt)
|
| 388 |
+
assert_equal(result.format, fmt)
|
| 389 |
+
assert_array_equal(result.toarray(), expected)
|
| 390 |
+
assert isinstance(result, spmatrix)
|
| 391 |
+
|
| 392 |
+
def test_kron_ndim_exceptions(self):
|
| 393 |
+
with pytest.raises(ValueError, match='requires 2D input'):
|
| 394 |
+
construct.kron([[0], [1]], csr_array([0, 1]))
|
| 395 |
+
with pytest.raises(ValueError, match='requires 2D input'):
|
| 396 |
+
construct.kron(csr_array([0, 1]), [[0], [1]])
|
| 397 |
+
# no exception if sparse arrays are not input (spmatrix inferred)
|
| 398 |
+
construct.kron([[0], [1]], [0, 1])
|
| 399 |
+
|
| 400 |
+
def test_kron_large(self):
|
| 401 |
+
n = 2**16
|
| 402 |
+
a = construct.diags_array([1], shape=(1, n), offsets=n-1)
|
| 403 |
+
b = construct.diags_array([1], shape=(n, 1), offsets=1-n)
|
| 404 |
+
|
| 405 |
+
construct.kron(a, a)
|
| 406 |
+
construct.kron(b, b)
|
| 407 |
+
|
| 408 |
+
def test_kronsum(self):
|
| 409 |
+
cases = []
|
| 410 |
+
|
| 411 |
+
cases.append(array([[0]]))
|
| 412 |
+
cases.append(array([[-1]]))
|
| 413 |
+
cases.append(array([[4]]))
|
| 414 |
+
cases.append(array([[10]]))
|
| 415 |
+
cases.append(array([[1,2],[3,4]]))
|
| 416 |
+
cases.append(array([[0,2],[5,0]]))
|
| 417 |
+
cases.append(array([[0,2,-6],[8,0,14],[0,3,0]]))
|
| 418 |
+
cases.append(array([[1,0,0],[0,5,-1],[4,-2,8]]))
|
| 419 |
+
|
| 420 |
+
# test all cases with default format
|
| 421 |
+
for a in cases:
|
| 422 |
+
for b in cases:
|
| 423 |
+
result = construct.kronsum(csr_array(a), csr_array(b)).toarray()
|
| 424 |
+
expected = (np.kron(np.eye(b.shape[0]), a)
|
| 425 |
+
+ np.kron(b, np.eye(a.shape[0])))
|
| 426 |
+
assert_array_equal(result, expected)
|
| 427 |
+
|
| 428 |
+
# check that spmatrix returned when both inputs are spmatrix
|
| 429 |
+
result = construct.kronsum(csr_matrix(a), csr_matrix(b)).toarray()
|
| 430 |
+
assert_array_equal(result, expected)
|
| 431 |
+
|
| 432 |
+
def test_kronsum_ndim_exceptions(self):
|
| 433 |
+
with pytest.raises(ValueError, match='requires 2D input'):
|
| 434 |
+
construct.kronsum([[0], [1]], csr_array([0, 1]))
|
| 435 |
+
with pytest.raises(ValueError, match='requires 2D input'):
|
| 436 |
+
construct.kronsum(csr_array([0, 1]), [[0], [1]])
|
| 437 |
+
# no exception if sparse arrays are not input (spmatrix inferred)
|
| 438 |
+
construct.kronsum([[0, 1], [1, 0]], [2])
|
| 439 |
+
|
| 440 |
+
@pytest.mark.parametrize("coo_cls", [coo_matrix, coo_array])
|
| 441 |
+
def test_vstack(self, coo_cls):
|
| 442 |
+
A = coo_cls([[1,2],[3,4]])
|
| 443 |
+
B = coo_cls([[5,6]])
|
| 444 |
+
|
| 445 |
+
expected = array([[1, 2],
|
| 446 |
+
[3, 4],
|
| 447 |
+
[5, 6]])
|
| 448 |
+
assert_equal(construct.vstack([A, B]).toarray(), expected)
|
| 449 |
+
assert_equal(construct.vstack([A, B], dtype=np.float32).dtype,
|
| 450 |
+
np.float32)
|
| 451 |
+
|
| 452 |
+
assert_equal(construct.vstack([A.todok(), B.todok()]).toarray(), expected)
|
| 453 |
+
|
| 454 |
+
assert_equal(construct.vstack([A.tocsr(), B.tocsr()]).toarray(),
|
| 455 |
+
expected)
|
| 456 |
+
result = construct.vstack([A.tocsr(), B.tocsr()],
|
| 457 |
+
format="csr", dtype=np.float32)
|
| 458 |
+
assert_equal(result.dtype, np.float32)
|
| 459 |
+
assert_equal(result.indices.dtype, np.int32)
|
| 460 |
+
assert_equal(result.indptr.dtype, np.int32)
|
| 461 |
+
|
| 462 |
+
assert_equal(construct.vstack([A.tocsc(), B.tocsc()]).toarray(),
|
| 463 |
+
expected)
|
| 464 |
+
result = construct.vstack([A.tocsc(), B.tocsc()],
|
| 465 |
+
format="csc", dtype=np.float32)
|
| 466 |
+
assert_equal(result.dtype, np.float32)
|
| 467 |
+
assert_equal(result.indices.dtype, np.int32)
|
| 468 |
+
assert_equal(result.indptr.dtype, np.int32)
|
| 469 |
+
|
| 470 |
+
def test_vstack_matrix_or_array(self):
|
| 471 |
+
A = [[1,2],[3,4]]
|
| 472 |
+
B = [[5,6]]
|
| 473 |
+
assert isinstance(construct.vstack([coo_array(A), coo_array(B)]), sparray)
|
| 474 |
+
assert isinstance(construct.vstack([coo_array(A), coo_matrix(B)]), sparray)
|
| 475 |
+
assert isinstance(construct.vstack([coo_matrix(A), coo_array(B)]), sparray)
|
| 476 |
+
assert isinstance(construct.vstack([coo_matrix(A), coo_matrix(B)]), spmatrix)
|
| 477 |
+
|
| 478 |
+
def test_vstack_1d_with_2d(self):
|
| 479 |
+
# fixes gh-21064
|
| 480 |
+
arr = csr_array([[1, 0, 0], [0, 1, 0]])
|
| 481 |
+
arr1d = csr_array([1, 0, 0])
|
| 482 |
+
arr1dcoo = coo_array([1, 0, 0])
|
| 483 |
+
assert construct.vstack([arr, np.array([0, 0, 0])]).shape == (3, 3)
|
| 484 |
+
assert construct.hstack([arr1d, np.array([[0]])]).shape == (1, 4)
|
| 485 |
+
assert construct.hstack([arr1d, arr1d]).shape == (1, 6)
|
| 486 |
+
assert construct.vstack([arr1d, arr1d]).shape == (2, 3)
|
| 487 |
+
|
| 488 |
+
# check csr specialty stacking code like _stack_along_minor_axis
|
| 489 |
+
assert construct.hstack([arr, arr]).shape == (2, 6)
|
| 490 |
+
assert construct.hstack([arr1d, arr1d]).shape == (1, 6)
|
| 491 |
+
|
| 492 |
+
assert construct.hstack([arr1d, arr1dcoo]).shape == (1, 6)
|
| 493 |
+
assert construct.vstack([arr, arr1dcoo]).shape == (3, 3)
|
| 494 |
+
assert construct.vstack([arr1d, arr1dcoo]).shape == (2, 3)
|
| 495 |
+
|
| 496 |
+
with pytest.raises(ValueError, match="incompatible row dimensions"):
|
| 497 |
+
construct.hstack([arr, np.array([0, 0])])
|
| 498 |
+
with pytest.raises(ValueError, match="incompatible column dimensions"):
|
| 499 |
+
construct.vstack([arr, np.array([0, 0])])
|
| 500 |
+
|
| 501 |
+
@pytest.mark.parametrize("coo_cls", [coo_matrix, coo_array])
|
| 502 |
+
def test_hstack(self, coo_cls):
|
| 503 |
+
A = coo_cls([[1,2],[3,4]])
|
| 504 |
+
B = coo_cls([[5],[6]])
|
| 505 |
+
|
| 506 |
+
expected = array([[1, 2, 5],
|
| 507 |
+
[3, 4, 6]])
|
| 508 |
+
assert_equal(construct.hstack([A, B]).toarray(), expected)
|
| 509 |
+
assert_equal(construct.hstack([A, B], dtype=np.float32).dtype,
|
| 510 |
+
np.float32)
|
| 511 |
+
|
| 512 |
+
assert_equal(construct.hstack([A.todok(), B.todok()]).toarray(), expected)
|
| 513 |
+
|
| 514 |
+
assert_equal(construct.hstack([A.tocsc(), B.tocsc()]).toarray(),
|
| 515 |
+
expected)
|
| 516 |
+
assert_equal(construct.hstack([A.tocsc(), B.tocsc()],
|
| 517 |
+
dtype=np.float32).dtype,
|
| 518 |
+
np.float32)
|
| 519 |
+
assert_equal(construct.hstack([A.tocsr(), B.tocsr()]).toarray(),
|
| 520 |
+
expected)
|
| 521 |
+
assert_equal(construct.hstack([A.tocsr(), B.tocsr()],
|
| 522 |
+
dtype=np.float32).dtype,
|
| 523 |
+
np.float32)
|
| 524 |
+
|
| 525 |
+
def test_hstack_matrix_or_array(self):
|
| 526 |
+
A = [[1,2],[3,4]]
|
| 527 |
+
B = [[5],[6]]
|
| 528 |
+
assert isinstance(construct.hstack([coo_array(A), coo_array(B)]), sparray)
|
| 529 |
+
assert isinstance(construct.hstack([coo_array(A), coo_matrix(B)]), sparray)
|
| 530 |
+
assert isinstance(construct.hstack([coo_matrix(A), coo_array(B)]), sparray)
|
| 531 |
+
assert isinstance(construct.hstack([coo_matrix(A), coo_matrix(B)]), spmatrix)
|
| 532 |
+
|
| 533 |
+
@pytest.mark.parametrize("block_array", (construct.bmat, construct.block_array))
|
| 534 |
+
def test_block_creation(self, block_array):
|
| 535 |
+
|
| 536 |
+
A = coo_array([[1, 2], [3, 4]])
|
| 537 |
+
B = coo_array([[5],[6]])
|
| 538 |
+
C = coo_array([[7]])
|
| 539 |
+
D = coo_array((0, 0))
|
| 540 |
+
|
| 541 |
+
expected = array([[1, 2, 5],
|
| 542 |
+
[3, 4, 6],
|
| 543 |
+
[0, 0, 7]])
|
| 544 |
+
assert_equal(block_array([[A, B], [None, C]]).toarray(), expected)
|
| 545 |
+
E = csr_array((1, 2), dtype=np.int32)
|
| 546 |
+
assert_equal(block_array([[A.tocsr(), B.tocsr()],
|
| 547 |
+
[E, C.tocsr()]]).toarray(),
|
| 548 |
+
expected)
|
| 549 |
+
assert_equal(block_array([[A.tocsc(), B.tocsc()],
|
| 550 |
+
[E.tocsc(), C.tocsc()]]).toarray(),
|
| 551 |
+
expected)
|
| 552 |
+
|
| 553 |
+
expected = array([[1, 2, 0],
|
| 554 |
+
[3, 4, 0],
|
| 555 |
+
[0, 0, 7]])
|
| 556 |
+
assert_equal(block_array([[A, None], [None, C]]).toarray(), expected)
|
| 557 |
+
assert_equal(block_array([[A.tocsr(), E.T.tocsr()],
|
| 558 |
+
[E, C.tocsr()]]).toarray(),
|
| 559 |
+
expected)
|
| 560 |
+
assert_equal(block_array([[A.tocsc(), E.T.tocsc()],
|
| 561 |
+
[E.tocsc(), C.tocsc()]]).toarray(),
|
| 562 |
+
expected)
|
| 563 |
+
|
| 564 |
+
Z = csr_array((1, 1), dtype=np.int32)
|
| 565 |
+
expected = array([[0, 5],
|
| 566 |
+
[0, 6],
|
| 567 |
+
[7, 0]])
|
| 568 |
+
assert_equal(block_array([[None, B], [C, None]]).toarray(), expected)
|
| 569 |
+
assert_equal(block_array([[E.T.tocsr(), B.tocsr()],
|
| 570 |
+
[C.tocsr(), Z]]).toarray(),
|
| 571 |
+
expected)
|
| 572 |
+
assert_equal(block_array([[E.T.tocsc(), B.tocsc()],
|
| 573 |
+
[C.tocsc(), Z.tocsc()]]).toarray(),
|
| 574 |
+
expected)
|
| 575 |
+
|
| 576 |
+
expected = np.empty((0, 0))
|
| 577 |
+
assert_equal(block_array([[None, None]]).toarray(), expected)
|
| 578 |
+
assert_equal(block_array([[None, D], [D, None]]).toarray(),
|
| 579 |
+
expected)
|
| 580 |
+
|
| 581 |
+
# test bug reported in gh-5976
|
| 582 |
+
expected = array([[7]])
|
| 583 |
+
assert_equal(block_array([[None, D], [C, None]]).toarray(),
|
| 584 |
+
expected)
|
| 585 |
+
|
| 586 |
+
# test failure cases
|
| 587 |
+
with assert_raises(ValueError) as excinfo:
|
| 588 |
+
block_array([[A], [B]])
|
| 589 |
+
excinfo.match(r'Got blocks\[1,0\]\.shape\[1\] == 1, expected 2')
|
| 590 |
+
|
| 591 |
+
with assert_raises(ValueError) as excinfo:
|
| 592 |
+
block_array([[A.tocsr()], [B.tocsr()]])
|
| 593 |
+
excinfo.match(r'incompatible dimensions for axis 1')
|
| 594 |
+
|
| 595 |
+
with assert_raises(ValueError) as excinfo:
|
| 596 |
+
block_array([[A.tocsc()], [B.tocsc()]])
|
| 597 |
+
excinfo.match(r'Mismatching dimensions along axis 1: ({1, 2}|{2, 1})')
|
| 598 |
+
|
| 599 |
+
with assert_raises(ValueError) as excinfo:
|
| 600 |
+
block_array([[A, C]])
|
| 601 |
+
excinfo.match(r'Got blocks\[0,1\]\.shape\[0\] == 1, expected 2')
|
| 602 |
+
|
| 603 |
+
with assert_raises(ValueError) as excinfo:
|
| 604 |
+
block_array([[A.tocsr(), C.tocsr()]])
|
| 605 |
+
excinfo.match(r'Mismatching dimensions along axis 0: ({1, 2}|{2, 1})')
|
| 606 |
+
|
| 607 |
+
with assert_raises(ValueError) as excinfo:
|
| 608 |
+
block_array([[A.tocsc(), C.tocsc()]])
|
| 609 |
+
excinfo.match(r'incompatible dimensions for axis 0')
|
| 610 |
+
|
| 611 |
+
def test_block_return_type(self):
|
| 612 |
+
block = construct.block_array
|
| 613 |
+
|
| 614 |
+
# csr format ensures we hit _compressed_sparse_stack
|
| 615 |
+
# shape of F,G ensure we hit _stack_along_minor_axis
|
| 616 |
+
# list version ensure we hit the path with neither helper function
|
| 617 |
+
Fl, Gl = [[1, 2],[3, 4]], [[7], [5]]
|
| 618 |
+
Fm, Gm = csr_matrix(Fl), csr_matrix(Gl)
|
| 619 |
+
assert isinstance(block([[None, Fl], [Gl, None]], format="csr"), sparray)
|
| 620 |
+
assert isinstance(block([[None, Fm], [Gm, None]], format="csr"), sparray)
|
| 621 |
+
assert isinstance(block([[Fm, Gm]], format="csr"), sparray)
|
| 622 |
+
|
| 623 |
+
def test_bmat_return_type(self):
|
| 624 |
+
"""This can be removed after sparse matrix is removed"""
|
| 625 |
+
bmat = construct.bmat
|
| 626 |
+
# check return type. if any input _is_array output array, else matrix
|
| 627 |
+
Fl, Gl = [[1, 2],[3, 4]], [[7], [5]]
|
| 628 |
+
Fm, Gm = csr_matrix(Fl), csr_matrix(Gl)
|
| 629 |
+
Fa, Ga = csr_array(Fl), csr_array(Gl)
|
| 630 |
+
assert isinstance(bmat([[Fa, Ga]], format="csr"), sparray)
|
| 631 |
+
assert isinstance(bmat([[Fm, Gm]], format="csr"), spmatrix)
|
| 632 |
+
assert isinstance(bmat([[None, Fa], [Ga, None]], format="csr"), sparray)
|
| 633 |
+
assert isinstance(bmat([[None, Fm], [Ga, None]], format="csr"), sparray)
|
| 634 |
+
assert isinstance(bmat([[None, Fm], [Gm, None]], format="csr"), spmatrix)
|
| 635 |
+
assert isinstance(bmat([[None, Fl], [Gl, None]], format="csr"), spmatrix)
|
| 636 |
+
|
| 637 |
+
# type returned by _compressed_sparse_stack (all csr)
|
| 638 |
+
assert isinstance(bmat([[Ga, Ga]], format="csr"), sparray)
|
| 639 |
+
assert isinstance(bmat([[Gm, Ga]], format="csr"), sparray)
|
| 640 |
+
assert isinstance(bmat([[Ga, Gm]], format="csr"), sparray)
|
| 641 |
+
assert isinstance(bmat([[Gm, Gm]], format="csr"), spmatrix)
|
| 642 |
+
# shape is 2x2 so no _stack_along_minor_axis
|
| 643 |
+
assert isinstance(bmat([[Fa, Fm]], format="csr"), sparray)
|
| 644 |
+
assert isinstance(bmat([[Fm, Fm]], format="csr"), spmatrix)
|
| 645 |
+
|
| 646 |
+
# type returned by _compressed_sparse_stack (all csc)
|
| 647 |
+
assert isinstance(bmat([[Gm.tocsc(), Ga.tocsc()]], format="csc"), sparray)
|
| 648 |
+
assert isinstance(bmat([[Gm.tocsc(), Gm.tocsc()]], format="csc"), spmatrix)
|
| 649 |
+
# shape is 2x2 so no _stack_along_minor_axis
|
| 650 |
+
assert isinstance(bmat([[Fa.tocsc(), Fm.tocsc()]], format="csr"), sparray)
|
| 651 |
+
assert isinstance(bmat([[Fm.tocsc(), Fm.tocsc()]], format="csr"), spmatrix)
|
| 652 |
+
|
| 653 |
+
# type returned when mixed input
|
| 654 |
+
assert isinstance(bmat([[Gl, Ga]], format="csr"), sparray)
|
| 655 |
+
assert isinstance(bmat([[Gm.tocsc(), Ga]], format="csr"), sparray)
|
| 656 |
+
assert isinstance(bmat([[Gm.tocsc(), Gm]], format="csr"), spmatrix)
|
| 657 |
+
assert isinstance(bmat([[Gm, Gm]], format="csc"), spmatrix)
|
| 658 |
+
|
| 659 |
+
@pytest.mark.slow
|
| 660 |
+
@pytest.mark.xfail_on_32bit("Can't create large array for test")
|
| 661 |
+
def test_concatenate_int32_overflow(self):
|
| 662 |
+
""" test for indptr overflow when concatenating matrices """
|
| 663 |
+
check_free_memory(30000)
|
| 664 |
+
|
| 665 |
+
n = 33000
|
| 666 |
+
A = csr_array(np.ones((n, n), dtype=bool))
|
| 667 |
+
B = A.copy()
|
| 668 |
+
C = construct._compressed_sparse_stack((A, B), axis=0,
|
| 669 |
+
return_spmatrix=False)
|
| 670 |
+
|
| 671 |
+
assert_(np.all(np.equal(np.diff(C.indptr), n)))
|
| 672 |
+
assert_equal(C.indices.dtype, np.int64)
|
| 673 |
+
assert_equal(C.indptr.dtype, np.int64)
|
| 674 |
+
|
| 675 |
+
def test_block_diag_basic(self):
|
| 676 |
+
""" basic test for block_diag """
|
| 677 |
+
A = coo_array([[1,2],[3,4]])
|
| 678 |
+
B = coo_array([[5],[6]])
|
| 679 |
+
C = coo_array([[7]])
|
| 680 |
+
|
| 681 |
+
expected = array([[1, 2, 0, 0],
|
| 682 |
+
[3, 4, 0, 0],
|
| 683 |
+
[0, 0, 5, 0],
|
| 684 |
+
[0, 0, 6, 0],
|
| 685 |
+
[0, 0, 0, 7]])
|
| 686 |
+
|
| 687 |
+
assert_equal(construct.block_diag((A, B, C)).toarray(), expected)
|
| 688 |
+
|
| 689 |
+
def test_block_diag_scalar_1d_args(self):
|
| 690 |
+
""" block_diag with scalar and 1d arguments """
|
| 691 |
+
# one 1d matrix and a scalar
|
| 692 |
+
assert_array_equal(construct.block_diag([[2,3], 4]).toarray(),
|
| 693 |
+
[[2, 3, 0], [0, 0, 4]])
|
| 694 |
+
# 1d sparse arrays
|
| 695 |
+
A = coo_array([1,0,3])
|
| 696 |
+
B = coo_array([0,4])
|
| 697 |
+
assert_array_equal(construct.block_diag([A, B]).toarray(),
|
| 698 |
+
[[1, 0, 3, 0, 0], [0, 0, 0, 0, 4]])
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def test_block_diag_1(self):
|
| 702 |
+
""" block_diag with one matrix """
|
| 703 |
+
assert_equal(construct.block_diag([[1, 0]]).toarray(),
|
| 704 |
+
array([[1, 0]]))
|
| 705 |
+
assert_equal(construct.block_diag([[[1, 0]]]).toarray(),
|
| 706 |
+
array([[1, 0]]))
|
| 707 |
+
assert_equal(construct.block_diag([[[1], [0]]]).toarray(),
|
| 708 |
+
array([[1], [0]]))
|
| 709 |
+
# just on scalar
|
| 710 |
+
assert_equal(construct.block_diag([1]).toarray(),
|
| 711 |
+
array([[1]]))
|
| 712 |
+
|
| 713 |
+
def test_block_diag_sparse_arrays(self):
|
| 714 |
+
""" block_diag with sparse arrays """
|
| 715 |
+
|
| 716 |
+
A = coo_array([[1, 2, 3]], shape=(1, 3))
|
| 717 |
+
B = coo_array([[4, 5]], shape=(1, 2))
|
| 718 |
+
assert_equal(construct.block_diag([A, B]).toarray(),
|
| 719 |
+
array([[1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]))
|
| 720 |
+
|
| 721 |
+
A = coo_array([[1], [2], [3]], shape=(3, 1))
|
| 722 |
+
B = coo_array([[4], [5]], shape=(2, 1))
|
| 723 |
+
assert_equal(construct.block_diag([A, B]).toarray(),
|
| 724 |
+
array([[1, 0], [2, 0], [3, 0], [0, 4], [0, 5]]))
|
| 725 |
+
|
| 726 |
+
def test_block_diag_return_type(self):
|
| 727 |
+
A, B = coo_array([[1, 2, 3]]), coo_matrix([[2, 3, 4]])
|
| 728 |
+
assert isinstance(construct.block_diag([A, A]), sparray)
|
| 729 |
+
assert isinstance(construct.block_diag([A, B]), sparray)
|
| 730 |
+
assert isinstance(construct.block_diag([B, A]), sparray)
|
| 731 |
+
assert isinstance(construct.block_diag([B, B]), spmatrix)
|
| 732 |
+
|
| 733 |
+
def test_random_sampling(self):
|
| 734 |
+
# Simple sanity checks for sparse random sampling.
|
| 735 |
+
for f in sprand, _sprandn:
|
| 736 |
+
for t in [np.float32, np.float64, np.longdouble,
|
| 737 |
+
np.int32, np.int64, np.complex64, np.complex128]:
|
| 738 |
+
x = f(5, 10, density=0.1, dtype=t)
|
| 739 |
+
assert_equal(x.dtype, t)
|
| 740 |
+
assert_equal(x.shape, (5, 10))
|
| 741 |
+
assert_equal(x.nnz, 5)
|
| 742 |
+
|
| 743 |
+
x1 = f(5, 10, density=0.1, random_state=4321)
|
| 744 |
+
assert_equal(x1.dtype, np.float64)
|
| 745 |
+
|
| 746 |
+
x2 = f(5, 10, density=0.1,
|
| 747 |
+
random_state=np.random.RandomState(4321))
|
| 748 |
+
|
| 749 |
+
assert_array_equal(x1.data, x2.data)
|
| 750 |
+
assert_array_equal(x1.row, x2.row)
|
| 751 |
+
assert_array_equal(x1.col, x2.col)
|
| 752 |
+
|
| 753 |
+
for density in [0.0, 0.1, 0.5, 1.0]:
|
| 754 |
+
x = f(5, 10, density=density)
|
| 755 |
+
assert_equal(x.nnz, int(density * np.prod(x.shape)))
|
| 756 |
+
|
| 757 |
+
for fmt in ['coo', 'csc', 'csr', 'lil']:
|
| 758 |
+
x = f(5, 10, format=fmt)
|
| 759 |
+
assert_equal(x.format, fmt)
|
| 760 |
+
|
| 761 |
+
assert_raises(ValueError, lambda: f(5, 10, 1.1))
|
| 762 |
+
assert_raises(ValueError, lambda: f(5, 10, -0.1))
|
| 763 |
+
|
| 764 |
+
def test_rand(self):
|
| 765 |
+
# Simple distributional checks for sparse.rand.
|
| 766 |
+
random_states = [None, 4321, np.random.RandomState()]
|
| 767 |
+
try:
|
| 768 |
+
gen = np.random.default_rng()
|
| 769 |
+
random_states.append(gen)
|
| 770 |
+
except AttributeError:
|
| 771 |
+
pass
|
| 772 |
+
|
| 773 |
+
for random_state in random_states:
|
| 774 |
+
x = sprand(10, 20, density=0.5, dtype=np.float64,
|
| 775 |
+
random_state=random_state)
|
| 776 |
+
assert_(np.all(np.less_equal(0, x.data)))
|
| 777 |
+
assert_(np.all(np.less_equal(x.data, 1)))
|
| 778 |
+
|
| 779 |
+
def test_randn(self):
|
| 780 |
+
# Simple distributional checks for sparse.randn.
|
| 781 |
+
# Statistically, some of these should be negative
|
| 782 |
+
# and some should be greater than 1.
|
| 783 |
+
random_states = [None, 4321, np.random.RandomState()]
|
| 784 |
+
try:
|
| 785 |
+
gen = np.random.default_rng()
|
| 786 |
+
random_states.append(gen)
|
| 787 |
+
except AttributeError:
|
| 788 |
+
pass
|
| 789 |
+
|
| 790 |
+
for rs in random_states:
|
| 791 |
+
x = _sprandn(10, 20, density=0.5, dtype=np.float64, random_state=rs)
|
| 792 |
+
assert_(np.any(np.less(x.data, 0)))
|
| 793 |
+
assert_(np.any(np.less(1, x.data)))
|
| 794 |
+
x = _sprandn_array(10, 20, density=0.5, dtype=np.float64, random_state=rs)
|
| 795 |
+
assert_(np.any(np.less(x.data, 0)))
|
| 796 |
+
assert_(np.any(np.less(1, x.data)))
|
| 797 |
+
|
| 798 |
+
def test_random_accept_str_dtype(self):
|
| 799 |
+
# anything that np.dtype can convert to a dtype should be accepted
|
| 800 |
+
# for the dtype
|
| 801 |
+
construct.random(10, 10, dtype='d')
|
| 802 |
+
construct.random_array((10, 10), dtype='d')
|
| 803 |
+
|
| 804 |
+
def test_random_sparse_matrix_returns_correct_number_of_non_zero_elements(self):
|
| 805 |
+
# A 10 x 10 matrix, with density of 12.65%, should have 13 nonzero elements.
|
| 806 |
+
# 10 x 10 x 0.1265 = 12.65, which should be rounded up to 13, not 12.
|
| 807 |
+
sparse_matrix = construct.random(10, 10, density=0.1265)
|
| 808 |
+
assert_equal(sparse_matrix.count_nonzero(),13)
|
| 809 |
+
# check random_array
|
| 810 |
+
sparse_array = construct.random_array((10, 10), density=0.1265)
|
| 811 |
+
assert_equal(sparse_array.count_nonzero(),13)
|
| 812 |
+
assert isinstance(sparse_array, sparray)
|
| 813 |
+
# check big size
|
| 814 |
+
shape = (2**33, 2**33)
|
| 815 |
+
sparse_array = construct.random_array(shape, density=2.7105e-17)
|
| 816 |
+
assert_equal(sparse_array.count_nonzero(),2000)
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
def test_diags_array():
|
| 820 |
+
"""Tests of diags_array that do not rely on diags wrapper."""
|
| 821 |
+
diag = np.arange(1, 5)
|
| 822 |
+
|
| 823 |
+
assert_array_equal(construct.diags_array(diag).toarray(), np.diag(diag))
|
| 824 |
+
|
| 825 |
+
assert_array_equal(
|
| 826 |
+
construct.diags_array(diag, offsets=2).toarray(), np.diag(diag, k=2)
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
assert_array_equal(
|
| 830 |
+
construct.diags_array(diag, offsets=2, shape=(4, 4)).toarray(),
|
| 831 |
+
np.diag(diag, k=2)[:4, :4]
|
| 832 |
+
)
|
| 833 |
+
|
| 834 |
+
# Offset outside bounds when shape specified
|
| 835 |
+
with pytest.raises(ValueError, match=".*out of bounds"):
|
| 836 |
+
construct.diags(np.arange(1, 5), 5, shape=(4, 4))
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_coo.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from numpy.testing import assert_equal
|
| 3 |
+
import pytest
|
| 4 |
+
from scipy.sparse import coo_array
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_shape_constructor():
|
| 8 |
+
empty1d = coo_array((3,))
|
| 9 |
+
assert empty1d.shape == (3,)
|
| 10 |
+
assert_equal(empty1d.toarray(), np.zeros((3,)))
|
| 11 |
+
|
| 12 |
+
empty2d = coo_array((3, 2))
|
| 13 |
+
assert empty2d.shape == (3, 2)
|
| 14 |
+
assert_equal(empty2d.toarray(), np.zeros((3, 2)))
|
| 15 |
+
|
| 16 |
+
with pytest.raises(TypeError, match='invalid input format'):
|
| 17 |
+
coo_array((3, 2, 2))
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def test_dense_constructor():
|
| 21 |
+
res1d = coo_array([1, 2, 3])
|
| 22 |
+
assert res1d.shape == (3,)
|
| 23 |
+
assert_equal(res1d.toarray(), np.array([1, 2, 3]))
|
| 24 |
+
|
| 25 |
+
res2d = coo_array([[1, 2, 3], [4, 5, 6]])
|
| 26 |
+
assert res2d.shape == (2, 3)
|
| 27 |
+
assert_equal(res2d.toarray(), np.array([[1, 2, 3], [4, 5, 6]]))
|
| 28 |
+
|
| 29 |
+
with pytest.raises(ValueError, match='shape must be a 1- or 2-tuple'):
|
| 30 |
+
coo_array([[[3]], [[4]]])
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_dense_constructor_with_shape():
|
| 34 |
+
res1d = coo_array([1, 2, 3], shape=(3,))
|
| 35 |
+
assert res1d.shape == (3,)
|
| 36 |
+
assert_equal(res1d.toarray(), np.array([1, 2, 3]))
|
| 37 |
+
|
| 38 |
+
res2d = coo_array([[1, 2, 3], [4, 5, 6]], shape=(2, 3))
|
| 39 |
+
assert res2d.shape == (2, 3)
|
| 40 |
+
assert_equal(res2d.toarray(), np.array([[1, 2, 3], [4, 5, 6]]))
|
| 41 |
+
|
| 42 |
+
with pytest.raises(ValueError, match='shape must be a 1- or 2-tuple'):
|
| 43 |
+
coo_array([[[3]], [[4]]], shape=(2, 1, 1))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_dense_constructor_with_inconsistent_shape():
|
| 47 |
+
with pytest.raises(ValueError, match='inconsistent shapes'):
|
| 48 |
+
coo_array([1, 2, 3], shape=(4,))
|
| 49 |
+
|
| 50 |
+
with pytest.raises(ValueError, match='inconsistent shapes'):
|
| 51 |
+
coo_array([1, 2, 3], shape=(3, 1))
|
| 52 |
+
|
| 53 |
+
with pytest.raises(ValueError, match='inconsistent shapes'):
|
| 54 |
+
coo_array([[1, 2, 3]], shape=(3,))
|
| 55 |
+
|
| 56 |
+
with pytest.raises(ValueError,
|
| 57 |
+
match='axis 0 index 2 exceeds matrix dimension 2'):
|
| 58 |
+
coo_array(([1], ([2],)), shape=(2,))
|
| 59 |
+
|
| 60 |
+
with pytest.raises(ValueError, match='negative axis 0 index: -1'):
|
| 61 |
+
coo_array(([1], ([-1],)))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_1d_sparse_constructor():
|
| 65 |
+
empty1d = coo_array((3,))
|
| 66 |
+
res = coo_array(empty1d)
|
| 67 |
+
assert res.shape == (3,)
|
| 68 |
+
assert_equal(res.toarray(), np.zeros((3,)))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_1d_tuple_constructor():
|
| 72 |
+
res = coo_array(([9,8], ([1,2],)))
|
| 73 |
+
assert res.shape == (3,)
|
| 74 |
+
assert_equal(res.toarray(), np.array([0, 9, 8]))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_1d_tuple_constructor_with_shape():
|
| 78 |
+
res = coo_array(([9,8], ([1,2],)), shape=(4,))
|
| 79 |
+
assert res.shape == (4,)
|
| 80 |
+
assert_equal(res.toarray(), np.array([0, 9, 8, 0]))
|
| 81 |
+
|
| 82 |
+
def test_non_subscriptability():
|
| 83 |
+
coo_2d = coo_array((2, 2))
|
| 84 |
+
|
| 85 |
+
with pytest.raises(TypeError,
|
| 86 |
+
match="'coo_array' object does not support item assignment"):
|
| 87 |
+
coo_2d[0, 0] = 1
|
| 88 |
+
|
| 89 |
+
with pytest.raises(TypeError,
|
| 90 |
+
match="'coo_array' object is not subscriptable"):
|
| 91 |
+
coo_2d[0, :]
|
| 92 |
+
|
| 93 |
+
def test_reshape():
|
| 94 |
+
arr1d = coo_array([1, 0, 3])
|
| 95 |
+
assert arr1d.shape == (3,)
|
| 96 |
+
|
| 97 |
+
col_vec = arr1d.reshape((3, 1))
|
| 98 |
+
assert col_vec.shape == (3, 1)
|
| 99 |
+
assert_equal(col_vec.toarray(), np.array([[1], [0], [3]]))
|
| 100 |
+
|
| 101 |
+
row_vec = arr1d.reshape((1, 3))
|
| 102 |
+
assert row_vec.shape == (1, 3)
|
| 103 |
+
assert_equal(row_vec.toarray(), np.array([[1, 0, 3]]))
|
| 104 |
+
|
| 105 |
+
arr2d = coo_array([[1, 2, 0], [0, 0, 3]])
|
| 106 |
+
assert arr2d.shape == (2, 3)
|
| 107 |
+
|
| 108 |
+
flat = arr2d.reshape((6,))
|
| 109 |
+
assert flat.shape == (6,)
|
| 110 |
+
assert_equal(flat.toarray(), np.array([1, 2, 0, 0, 0, 3]))
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_nnz():
|
| 114 |
+
arr1d = coo_array([1, 0, 3])
|
| 115 |
+
assert arr1d.shape == (3,)
|
| 116 |
+
assert arr1d.nnz == 2
|
| 117 |
+
|
| 118 |
+
arr2d = coo_array([[1, 2, 0], [0, 0, 3]])
|
| 119 |
+
assert arr2d.shape == (2, 3)
|
| 120 |
+
assert arr2d.nnz == 3
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_transpose():
|
| 124 |
+
arr1d = coo_array([1, 0, 3]).T
|
| 125 |
+
assert arr1d.shape == (3,)
|
| 126 |
+
assert_equal(arr1d.toarray(), np.array([1, 0, 3]))
|
| 127 |
+
|
| 128 |
+
arr2d = coo_array([[1, 2, 0], [0, 0, 3]]).T
|
| 129 |
+
assert arr2d.shape == (3, 2)
|
| 130 |
+
assert_equal(arr2d.toarray(), np.array([[1, 0], [2, 0], [0, 3]]))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_transpose_with_axis():
|
| 134 |
+
arr1d = coo_array([1, 0, 3]).transpose(axes=(0,))
|
| 135 |
+
assert arr1d.shape == (3,)
|
| 136 |
+
assert_equal(arr1d.toarray(), np.array([1, 0, 3]))
|
| 137 |
+
|
| 138 |
+
arr2d = coo_array([[1, 2, 0], [0, 0, 3]]).transpose(axes=(0, 1))
|
| 139 |
+
assert arr2d.shape == (2, 3)
|
| 140 |
+
assert_equal(arr2d.toarray(), np.array([[1, 2, 0], [0, 0, 3]]))
|
| 141 |
+
|
| 142 |
+
with pytest.raises(ValueError, match="axes don't match matrix dimensions"):
|
| 143 |
+
coo_array([1, 0, 3]).transpose(axes=(0, 1))
|
| 144 |
+
|
| 145 |
+
with pytest.raises(ValueError, match="repeated axis in transpose"):
|
| 146 |
+
coo_array([[1, 2, 0], [0, 0, 3]]).transpose(axes=(1, 1))
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_1d_row_and_col():
|
| 150 |
+
res = coo_array([1, -2, -3])
|
| 151 |
+
assert_equal(res.col, np.array([0, 1, 2]))
|
| 152 |
+
assert_equal(res.row, np.zeros_like(res.col))
|
| 153 |
+
assert res.row.dtype == res.col.dtype
|
| 154 |
+
assert res.row.flags.writeable is False
|
| 155 |
+
|
| 156 |
+
res.col = [1, 2, 3]
|
| 157 |
+
assert len(res.coords) == 1
|
| 158 |
+
assert_equal(res.col, np.array([1, 2, 3]))
|
| 159 |
+
assert res.row.dtype == res.col.dtype
|
| 160 |
+
|
| 161 |
+
with pytest.raises(ValueError, match="cannot set row attribute"):
|
| 162 |
+
res.row = [1, 2, 3]
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def test_1d_toformats():
|
| 166 |
+
res = coo_array([1, -2, -3])
|
| 167 |
+
for f in [res.tobsr, res.tocsc, res.todia, res.tolil]:
|
| 168 |
+
with pytest.raises(ValueError, match='Cannot convert'):
|
| 169 |
+
f()
|
| 170 |
+
for f in [res.tocoo, res.tocsr, res.todok]:
|
| 171 |
+
assert_equal(f().toarray(), res.toarray())
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@pytest.mark.parametrize('arg', [1, 2, 4, 5, 8])
|
| 175 |
+
def test_1d_resize(arg: int):
|
| 176 |
+
den = np.array([1, -2, -3])
|
| 177 |
+
res = coo_array(den)
|
| 178 |
+
den.resize(arg, refcheck=False)
|
| 179 |
+
res.resize(arg)
|
| 180 |
+
assert res.shape == den.shape
|
| 181 |
+
assert_equal(res.toarray(), den)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@pytest.mark.parametrize('arg', zip([1, 2, 3, 4], [1, 2, 3, 4]))
|
| 185 |
+
def test_1d_to_2d_resize(arg: tuple[int, int]):
|
| 186 |
+
den = np.array([1, 0, 3])
|
| 187 |
+
res = coo_array(den)
|
| 188 |
+
|
| 189 |
+
den.resize(arg, refcheck=False)
|
| 190 |
+
res.resize(arg)
|
| 191 |
+
assert res.shape == den.shape
|
| 192 |
+
assert_equal(res.toarray(), den)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@pytest.mark.parametrize('arg', [1, 4, 6, 8])
|
| 196 |
+
def test_2d_to_1d_resize(arg: int):
|
| 197 |
+
den = np.array([[1, 0, 3], [4, 0, 0]])
|
| 198 |
+
res = coo_array(den)
|
| 199 |
+
den.resize(arg, refcheck=False)
|
| 200 |
+
res.resize(arg)
|
| 201 |
+
assert res.shape == den.shape
|
| 202 |
+
assert_equal(res.toarray(), den)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def test_sum_duplicates():
|
| 206 |
+
arr1d = coo_array(([2, 2, 2], ([1, 0, 1],)))
|
| 207 |
+
assert arr1d.nnz == 3
|
| 208 |
+
assert_equal(arr1d.toarray(), np.array([2, 4]))
|
| 209 |
+
arr1d.sum_duplicates()
|
| 210 |
+
assert arr1d.nnz == 2
|
| 211 |
+
assert_equal(arr1d.toarray(), np.array([2, 4]))
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def test_eliminate_zeros():
|
| 215 |
+
arr1d = coo_array(([0, 0, 1], ([1, 0, 1],)))
|
| 216 |
+
assert arr1d.nnz == 3
|
| 217 |
+
assert arr1d.count_nonzero() == 1
|
| 218 |
+
assert_equal(arr1d.toarray(), np.array([0, 1]))
|
| 219 |
+
arr1d.eliminate_zeros()
|
| 220 |
+
assert arr1d.nnz == 1
|
| 221 |
+
assert arr1d.count_nonzero() == 1
|
| 222 |
+
assert_equal(arr1d.toarray(), np.array([0, 1]))
|
| 223 |
+
assert_equal(arr1d.col, np.array([1]))
|
| 224 |
+
assert_equal(arr1d.row, np.array([0]))
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def test_1d_add_dense():
|
| 228 |
+
den_a = np.array([0, -2, -3, 0])
|
| 229 |
+
den_b = np.array([0, 1, 2, 3])
|
| 230 |
+
exp = den_a + den_b
|
| 231 |
+
res = coo_array(den_a) + den_b
|
| 232 |
+
assert type(res) == type(exp)
|
| 233 |
+
assert_equal(res, exp)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def test_1d_add_sparse():
|
| 237 |
+
den_a = np.array([0, -2, -3, 0])
|
| 238 |
+
den_b = np.array([0, 1, 2, 3])
|
| 239 |
+
dense_sum = den_a + den_b
|
| 240 |
+
# this routes through CSR format
|
| 241 |
+
sparse_sum = coo_array(den_a) + coo_array(den_b)
|
| 242 |
+
assert_equal(dense_sum, sparse_sum.toarray())
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def test_1d_matmul_vector():
|
| 246 |
+
den_a = np.array([0, -2, -3, 0])
|
| 247 |
+
den_b = np.array([0, 1, 2, 3])
|
| 248 |
+
exp = den_a @ den_b
|
| 249 |
+
res = coo_array(den_a) @ den_b
|
| 250 |
+
assert np.ndim(res) == 0
|
| 251 |
+
assert_equal(res, exp)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def test_1d_matmul_multivector():
|
| 255 |
+
den = np.array([0, -2, -3, 0])
|
| 256 |
+
other = np.array([[0, 1, 2, 3], [3, 2, 1, 0]]).T
|
| 257 |
+
exp = den @ other
|
| 258 |
+
res = coo_array(den) @ other
|
| 259 |
+
assert type(res) == type(exp)
|
| 260 |
+
assert_equal(res, exp)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def test_2d_matmul_multivector():
|
| 264 |
+
den = np.array([[0, 1, 2, 3], [3, 2, 1, 0]])
|
| 265 |
+
arr2d = coo_array(den)
|
| 266 |
+
exp = den @ den.T
|
| 267 |
+
res = arr2d @ arr2d.T
|
| 268 |
+
assert_equal(res.toarray(), exp)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def test_1d_diagonal():
|
| 272 |
+
den = np.array([0, -2, -3, 0])
|
| 273 |
+
with pytest.raises(ValueError, match='diagonal requires two dimensions'):
|
| 274 |
+
coo_array(den).diagonal()
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_csc.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from numpy.testing import assert_array_almost_equal, assert_
|
| 3 |
+
from scipy.sparse import csr_matrix, csc_matrix, lil_matrix
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_csc_getrow():
|
| 9 |
+
N = 10
|
| 10 |
+
np.random.seed(0)
|
| 11 |
+
X = np.random.random((N, N))
|
| 12 |
+
X[X > 0.7] = 0
|
| 13 |
+
Xcsc = csc_matrix(X)
|
| 14 |
+
|
| 15 |
+
for i in range(N):
|
| 16 |
+
arr_row = X[i:i + 1, :]
|
| 17 |
+
csc_row = Xcsc.getrow(i)
|
| 18 |
+
|
| 19 |
+
assert_array_almost_equal(arr_row, csc_row.toarray())
|
| 20 |
+
assert_(type(csc_row) is csr_matrix)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_csc_getcol():
|
| 24 |
+
N = 10
|
| 25 |
+
np.random.seed(0)
|
| 26 |
+
X = np.random.random((N, N))
|
| 27 |
+
X[X > 0.7] = 0
|
| 28 |
+
Xcsc = csc_matrix(X)
|
| 29 |
+
|
| 30 |
+
for i in range(N):
|
| 31 |
+
arr_col = X[:, i:i + 1]
|
| 32 |
+
csc_col = Xcsc.getcol(i)
|
| 33 |
+
|
| 34 |
+
assert_array_almost_equal(arr_col, csc_col.toarray())
|
| 35 |
+
assert_(type(csc_col) is csc_matrix)
|
| 36 |
+
|
| 37 |
+
@pytest.mark.parametrize("matrix_input, axis, expected_shape",
|
| 38 |
+
[(csc_matrix([[1, 0],
|
| 39 |
+
[0, 0],
|
| 40 |
+
[0, 2]]),
|
| 41 |
+
0, (0, 2)),
|
| 42 |
+
(csc_matrix([[1, 0],
|
| 43 |
+
[0, 0],
|
| 44 |
+
[0, 2]]),
|
| 45 |
+
1, (3, 0)),
|
| 46 |
+
(csc_matrix([[1, 0],
|
| 47 |
+
[0, 0],
|
| 48 |
+
[0, 2]]),
|
| 49 |
+
'both', (0, 0)),
|
| 50 |
+
(csc_matrix([[0, 1, 0, 0, 0, 0],
|
| 51 |
+
[0, 0, 0, 0, 0, 0],
|
| 52 |
+
[0, 0, 2, 3, 0, 1]]),
|
| 53 |
+
0, (0, 6))])
|
| 54 |
+
def test_csc_empty_slices(matrix_input, axis, expected_shape):
|
| 55 |
+
# see gh-11127 for related discussion
|
| 56 |
+
slice_1 = matrix_input.toarray().shape[0] - 1
|
| 57 |
+
slice_2 = slice_1
|
| 58 |
+
slice_3 = slice_2 - 1
|
| 59 |
+
|
| 60 |
+
if axis == 0:
|
| 61 |
+
actual_shape_1 = matrix_input[slice_1:slice_2, :].toarray().shape
|
| 62 |
+
actual_shape_2 = matrix_input[slice_1:slice_3, :].toarray().shape
|
| 63 |
+
elif axis == 1:
|
| 64 |
+
actual_shape_1 = matrix_input[:, slice_1:slice_2].toarray().shape
|
| 65 |
+
actual_shape_2 = matrix_input[:, slice_1:slice_3].toarray().shape
|
| 66 |
+
elif axis == 'both':
|
| 67 |
+
actual_shape_1 = matrix_input[slice_1:slice_2, slice_1:slice_2].toarray().shape
|
| 68 |
+
actual_shape_2 = matrix_input[slice_1:slice_3, slice_1:slice_3].toarray().shape
|
| 69 |
+
|
| 70 |
+
assert actual_shape_1 == expected_shape
|
| 71 |
+
assert actual_shape_1 == actual_shape_2
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@pytest.mark.parametrize('ax', (-2, -1, 0, 1, None))
|
| 75 |
+
def test_argmax_overflow(ax):
|
| 76 |
+
# See gh-13646: Windows integer overflow for large sparse matrices.
|
| 77 |
+
dim = (100000, 100000)
|
| 78 |
+
A = lil_matrix(dim)
|
| 79 |
+
A[-2, -2] = 42
|
| 80 |
+
A[-3, -3] = 0.1234
|
| 81 |
+
A = csc_matrix(A)
|
| 82 |
+
idx = A.argmax(axis=ax)
|
| 83 |
+
|
| 84 |
+
if ax is None:
|
| 85 |
+
# idx is a single flattened index
|
| 86 |
+
# that we need to convert to a 2d index pair;
|
| 87 |
+
# can't do this with np.unravel_index because
|
| 88 |
+
# the dimensions are too large
|
| 89 |
+
ii = idx % dim[0]
|
| 90 |
+
jj = idx // dim[0]
|
| 91 |
+
else:
|
| 92 |
+
# idx is an array of size of A.shape[ax];
|
| 93 |
+
# check the max index to make sure no overflows
|
| 94 |
+
# we encountered
|
| 95 |
+
assert np.count_nonzero(idx) == A.nnz
|
| 96 |
+
ii, jj = np.max(idx), np.argmax(idx)
|
| 97 |
+
|
| 98 |
+
assert A[ii, jj] == A[-2, -2]
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_dok.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.fixture
|
| 9 |
+
def d():
|
| 10 |
+
return {(0, 1): 1, (0, 2): 2}
|
| 11 |
+
|
| 12 |
+
@pytest.fixture
|
| 13 |
+
def A():
|
| 14 |
+
return np.array([[0, 1, 2], [0, 0, 0], [0, 0, 0]])
|
| 15 |
+
|
| 16 |
+
@pytest.fixture(params=[dok_array, dok_matrix])
|
| 17 |
+
def Asp(request):
|
| 18 |
+
A = request.param((3, 3))
|
| 19 |
+
A[(0, 1)] = 1
|
| 20 |
+
A[(0, 2)] = 2
|
| 21 |
+
yield A
|
| 22 |
+
|
| 23 |
+
# Note: __iter__ and comparison dunders act like ndarrays for DOK, not dict.
|
| 24 |
+
# Dunders reversed, or, ror, ior work as dict for dok_matrix, raise for dok_array
|
| 25 |
+
# All other dict methods on DOK format act like dict methods (with extra checks).
|
| 26 |
+
|
| 27 |
+
# Start of tests
|
| 28 |
+
################
|
| 29 |
+
def test_dict_methods_covered(d, Asp):
|
| 30 |
+
d_methods = set(dir(d)) - {"__class_getitem__"}
|
| 31 |
+
asp_methods = set(dir(Asp))
|
| 32 |
+
assert d_methods < asp_methods
|
| 33 |
+
|
| 34 |
+
def test_clear(d, Asp):
|
| 35 |
+
assert d.items() == Asp.items()
|
| 36 |
+
d.clear()
|
| 37 |
+
Asp.clear()
|
| 38 |
+
assert d.items() == Asp.items()
|
| 39 |
+
|
| 40 |
+
def test_copy(d, Asp):
|
| 41 |
+
assert d.items() == Asp.items()
|
| 42 |
+
dd = d.copy()
|
| 43 |
+
asp = Asp.copy()
|
| 44 |
+
assert dd.items() == asp.items()
|
| 45 |
+
assert asp.items() == Asp.items()
|
| 46 |
+
asp[(0, 1)] = 3
|
| 47 |
+
assert Asp[(0, 1)] == 1
|
| 48 |
+
|
| 49 |
+
def test_fromkeys_default():
|
| 50 |
+
# test with default value
|
| 51 |
+
edges = [(0, 2), (1, 0), (2, 1)]
|
| 52 |
+
Xdok = dok_array.fromkeys(edges)
|
| 53 |
+
X = [[0, 0, 1], [1, 0, 0], [0, 1, 0]]
|
| 54 |
+
assert_equal(Xdok.toarray(), X)
|
| 55 |
+
|
| 56 |
+
def test_fromkeys_positional():
|
| 57 |
+
# test with positional value
|
| 58 |
+
edges = [(0, 2), (1, 0), (2, 1)]
|
| 59 |
+
Xdok = dok_array.fromkeys(edges, -1)
|
| 60 |
+
X = [[0, 0, -1], [-1, 0, 0], [0, -1, 0]]
|
| 61 |
+
assert_equal(Xdok.toarray(), X)
|
| 62 |
+
|
| 63 |
+
def test_fromkeys_iterator():
|
| 64 |
+
it = ((a, a % 2) for a in range(4))
|
| 65 |
+
Xdok = dok_array.fromkeys(it)
|
| 66 |
+
X = [[1, 0], [0, 1], [1, 0], [0, 1]]
|
| 67 |
+
assert_equal(Xdok.toarray(), X)
|
| 68 |
+
|
| 69 |
+
def test_get(d, Asp):
|
| 70 |
+
assert Asp.get((0, 1)) == d.get((0, 1))
|
| 71 |
+
assert Asp.get((0, 0), 99) == d.get((0, 0), 99)
|
| 72 |
+
with pytest.raises(IndexError, match="out of bounds"):
|
| 73 |
+
Asp.get((0, 4), 99)
|
| 74 |
+
|
| 75 |
+
def test_items(d, Asp):
|
| 76 |
+
assert Asp.items() == d.items()
|
| 77 |
+
|
| 78 |
+
def test_keys(d, Asp):
|
| 79 |
+
assert Asp.keys() == d.keys()
|
| 80 |
+
|
| 81 |
+
def test_pop(d, Asp):
|
| 82 |
+
assert d.pop((0, 1)) == 1
|
| 83 |
+
assert Asp.pop((0, 1)) == 1
|
| 84 |
+
assert d.items() == Asp.items()
|
| 85 |
+
|
| 86 |
+
assert Asp.pop((22, 21), None) is None
|
| 87 |
+
assert Asp.pop((22, 21), "other") == "other"
|
| 88 |
+
with pytest.raises(KeyError, match="(22, 21)"):
|
| 89 |
+
Asp.pop((22, 21))
|
| 90 |
+
with pytest.raises(TypeError, match="got an unexpected keyword argument"):
|
| 91 |
+
Asp.pop((22, 21), default=5)
|
| 92 |
+
|
| 93 |
+
def test_popitem(d, Asp):
|
| 94 |
+
assert d.popitem() == Asp.popitem()
|
| 95 |
+
assert d.items() == Asp.items()
|
| 96 |
+
|
| 97 |
+
def test_setdefault(d, Asp):
|
| 98 |
+
assert Asp.setdefault((0, 1), 4) == 1
|
| 99 |
+
assert Asp.setdefault((2, 2), 4) == 4
|
| 100 |
+
d.setdefault((0, 1), 4)
|
| 101 |
+
d.setdefault((2, 2), 4)
|
| 102 |
+
assert d.items() == Asp.items()
|
| 103 |
+
|
| 104 |
+
def test_update(d, Asp):
|
| 105 |
+
with pytest.raises(NotImplementedError):
|
| 106 |
+
Asp.update(Asp)
|
| 107 |
+
|
| 108 |
+
def test_values(d, Asp):
|
| 109 |
+
# Note: dict.values are strange: d={1: 1}; d.values() == d.values() is False
|
| 110 |
+
# Using list(d.values()) makes them comparable.
|
| 111 |
+
assert list(Asp.values()) == list(d.values())
|
| 112 |
+
|
| 113 |
+
def test_dunder_getitem(d, Asp):
|
| 114 |
+
assert Asp[(0, 1)] == d[(0, 1)]
|
| 115 |
+
|
| 116 |
+
def test_dunder_setitem(d, Asp):
|
| 117 |
+
Asp[(1, 1)] = 5
|
| 118 |
+
d[(1, 1)] = 5
|
| 119 |
+
assert d.items() == Asp.items()
|
| 120 |
+
|
| 121 |
+
def test_dunder_delitem(d, Asp):
|
| 122 |
+
del Asp[(0, 1)]
|
| 123 |
+
del d[(0, 1)]
|
| 124 |
+
assert d.items() == Asp.items()
|
| 125 |
+
|
| 126 |
+
def test_dunder_contains(d, Asp):
|
| 127 |
+
assert ((0, 1) in d) == ((0, 1) in Asp)
|
| 128 |
+
assert ((0, 0) in d) == ((0, 0) in Asp)
|
| 129 |
+
|
| 130 |
+
def test_dunder_len(d, Asp):
|
| 131 |
+
assert len(d) == len(Asp)
|
| 132 |
+
|
| 133 |
+
# Note: dunders reversed, or, ror, ior work as dict for dok_matrix, raise for dok_array
|
| 134 |
+
def test_dunder_reversed(d, Asp):
|
| 135 |
+
if isinstance(Asp, dok_array):
|
| 136 |
+
with pytest.raises(TypeError):
|
| 137 |
+
list(reversed(Asp))
|
| 138 |
+
else:
|
| 139 |
+
list(reversed(Asp)) == list(reversed(d))
|
| 140 |
+
|
| 141 |
+
def test_dunder_ior(d, Asp):
|
| 142 |
+
if isinstance(Asp, dok_array):
|
| 143 |
+
with pytest.raises(TypeError):
|
| 144 |
+
Asp |= Asp
|
| 145 |
+
else:
|
| 146 |
+
dd = {(0, 0): 5}
|
| 147 |
+
Asp |= dd
|
| 148 |
+
assert Asp[(0, 0)] == 5
|
| 149 |
+
d |= dd
|
| 150 |
+
assert d.items() == Asp.items()
|
| 151 |
+
dd |= Asp
|
| 152 |
+
assert dd.items() == Asp.items()
|
| 153 |
+
|
| 154 |
+
def test_dunder_or(d, Asp):
|
| 155 |
+
if isinstance(Asp, dok_array):
|
| 156 |
+
with pytest.raises(TypeError):
|
| 157 |
+
Asp | Asp
|
| 158 |
+
else:
|
| 159 |
+
assert d | d == Asp | d
|
| 160 |
+
assert d | d == Asp | Asp
|
| 161 |
+
|
| 162 |
+
def test_dunder_ror(d, Asp):
|
| 163 |
+
if isinstance(Asp, dok_array):
|
| 164 |
+
with pytest.raises(TypeError):
|
| 165 |
+
Asp | Asp
|
| 166 |
+
with pytest.raises(TypeError):
|
| 167 |
+
d | Asp
|
| 168 |
+
else:
|
| 169 |
+
assert Asp.__ror__(d) == Asp.__ror__(Asp)
|
| 170 |
+
assert d.__ror__(d) == Asp.__ror__(d)
|
| 171 |
+
assert d | Asp
|
| 172 |
+
|
| 173 |
+
# Note: comparison dunders, e.g. ==, >=, etc follow np.array not dict
|
| 174 |
+
def test_dunder_eq(A, Asp):
|
| 175 |
+
with np.testing.suppress_warnings() as sup:
|
| 176 |
+
sup.filter(sp.sparse.SparseEfficiencyWarning)
|
| 177 |
+
assert (Asp == Asp).toarray().all()
|
| 178 |
+
assert (A == Asp).all()
|
| 179 |
+
|
| 180 |
+
def test_dunder_ne(A, Asp):
|
| 181 |
+
assert not (Asp != Asp).toarray().any()
|
| 182 |
+
assert not (A != Asp).any()
|
| 183 |
+
|
| 184 |
+
def test_dunder_lt(A, Asp):
|
| 185 |
+
assert not (Asp < Asp).toarray().any()
|
| 186 |
+
assert not (A < Asp).any()
|
| 187 |
+
|
| 188 |
+
def test_dunder_gt(A, Asp):
|
| 189 |
+
assert not (Asp > Asp).toarray().any()
|
| 190 |
+
assert not (A > Asp).any()
|
| 191 |
+
|
| 192 |
+
def test_dunder_le(A, Asp):
|
| 193 |
+
with np.testing.suppress_warnings() as sup:
|
| 194 |
+
sup.filter(sp.sparse.SparseEfficiencyWarning)
|
| 195 |
+
assert (Asp <= Asp).toarray().all()
|
| 196 |
+
assert (A <= Asp).all()
|
| 197 |
+
|
| 198 |
+
def test_dunder_ge(A, Asp):
|
| 199 |
+
with np.testing.suppress_warnings() as sup:
|
| 200 |
+
sup.filter(sp.sparse.SparseEfficiencyWarning)
|
| 201 |
+
assert (Asp >= Asp).toarray().all()
|
| 202 |
+
assert (A >= Asp).all()
|
| 203 |
+
|
| 204 |
+
# Note: iter dunder follows np.array not dict
|
| 205 |
+
def test_dunder_iter(A, Asp):
|
| 206 |
+
if isinstance(Asp, dok_array):
|
| 207 |
+
with pytest.raises(NotImplementedError):
|
| 208 |
+
[a.toarray() for a in Asp]
|
| 209 |
+
else:
|
| 210 |
+
assert all((a == asp).all() for a, asp in zip(A, Asp))
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_extract.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""test sparse matrix construction functions"""
|
| 2 |
+
|
| 3 |
+
from numpy.testing import assert_equal
|
| 4 |
+
from scipy.sparse import csr_matrix, csr_array, sparray
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from scipy.sparse import _extract
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestExtract:
|
| 11 |
+
def setup_method(self):
|
| 12 |
+
self.cases = [
|
| 13 |
+
csr_array([[1,2]]),
|
| 14 |
+
csr_array([[1,0]]),
|
| 15 |
+
csr_array([[0,0]]),
|
| 16 |
+
csr_array([[1],[2]]),
|
| 17 |
+
csr_array([[1],[0]]),
|
| 18 |
+
csr_array([[0],[0]]),
|
| 19 |
+
csr_array([[1,2],[3,4]]),
|
| 20 |
+
csr_array([[0,1],[0,0]]),
|
| 21 |
+
csr_array([[0,0],[1,0]]),
|
| 22 |
+
csr_array([[0,0],[0,0]]),
|
| 23 |
+
csr_array([[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]]),
|
| 24 |
+
csr_array([[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]]).T,
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
def test_find(self):
|
| 28 |
+
for A in self.cases:
|
| 29 |
+
I,J,V = _extract.find(A)
|
| 30 |
+
B = csr_array((V,(I,J)), shape=A.shape)
|
| 31 |
+
assert_equal(A.toarray(), B.toarray())
|
| 32 |
+
|
| 33 |
+
def test_tril(self):
|
| 34 |
+
for A in self.cases:
|
| 35 |
+
B = A.toarray()
|
| 36 |
+
for k in [-3,-2,-1,0,1,2,3]:
|
| 37 |
+
assert_equal(_extract.tril(A,k=k).toarray(), np.tril(B,k=k))
|
| 38 |
+
|
| 39 |
+
def test_triu(self):
|
| 40 |
+
for A in self.cases:
|
| 41 |
+
B = A.toarray()
|
| 42 |
+
for k in [-3,-2,-1,0,1,2,3]:
|
| 43 |
+
assert_equal(_extract.triu(A,k=k).toarray(), np.triu(B,k=k))
|
| 44 |
+
|
| 45 |
+
def test_array_vs_matrix(self):
|
| 46 |
+
for A in self.cases:
|
| 47 |
+
assert isinstance(_extract.tril(A), sparray)
|
| 48 |
+
assert isinstance(_extract.triu(A), sparray)
|
| 49 |
+
M = csr_matrix(A)
|
| 50 |
+
assert not isinstance(_extract.tril(M), sparray)
|
| 51 |
+
assert not isinstance(_extract.triu(M), sparray)
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_matrix_io.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import tempfile
|
| 4 |
+
|
| 5 |
+
from pytest import raises as assert_raises
|
| 6 |
+
from numpy.testing import assert_equal, assert_
|
| 7 |
+
|
| 8 |
+
from scipy.sparse import (sparray, csc_matrix, csr_matrix, bsr_matrix, dia_matrix,
|
| 9 |
+
coo_matrix, dok_matrix, csr_array, save_npz, load_npz)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _save_and_load(matrix):
|
| 16 |
+
fd, tmpfile = tempfile.mkstemp(suffix='.npz')
|
| 17 |
+
os.close(fd)
|
| 18 |
+
try:
|
| 19 |
+
save_npz(tmpfile, matrix)
|
| 20 |
+
loaded_matrix = load_npz(tmpfile)
|
| 21 |
+
finally:
|
| 22 |
+
os.remove(tmpfile)
|
| 23 |
+
return loaded_matrix
|
| 24 |
+
|
| 25 |
+
def _check_save_and_load(dense_matrix):
|
| 26 |
+
for matrix_class in [csc_matrix, csr_matrix, bsr_matrix, dia_matrix, coo_matrix]:
|
| 27 |
+
matrix = matrix_class(dense_matrix)
|
| 28 |
+
loaded_matrix = _save_and_load(matrix)
|
| 29 |
+
assert_(type(loaded_matrix) is matrix_class)
|
| 30 |
+
assert_(loaded_matrix.shape == dense_matrix.shape)
|
| 31 |
+
assert_(loaded_matrix.dtype == dense_matrix.dtype)
|
| 32 |
+
assert_equal(loaded_matrix.toarray(), dense_matrix)
|
| 33 |
+
|
| 34 |
+
def test_save_and_load_random():
|
| 35 |
+
N = 10
|
| 36 |
+
np.random.seed(0)
|
| 37 |
+
dense_matrix = np.random.random((N, N))
|
| 38 |
+
dense_matrix[dense_matrix > 0.7] = 0
|
| 39 |
+
_check_save_and_load(dense_matrix)
|
| 40 |
+
|
| 41 |
+
def test_save_and_load_empty():
|
| 42 |
+
dense_matrix = np.zeros((4,6))
|
| 43 |
+
_check_save_and_load(dense_matrix)
|
| 44 |
+
|
| 45 |
+
def test_save_and_load_one_entry():
|
| 46 |
+
dense_matrix = np.zeros((4,6))
|
| 47 |
+
dense_matrix[1,2] = 1
|
| 48 |
+
_check_save_and_load(dense_matrix)
|
| 49 |
+
|
| 50 |
+
def test_sparray_vs_spmatrix():
|
| 51 |
+
#save/load matrix
|
| 52 |
+
fd, tmpfile = tempfile.mkstemp(suffix='.npz')
|
| 53 |
+
os.close(fd)
|
| 54 |
+
try:
|
| 55 |
+
save_npz(tmpfile, csr_matrix([[1.2, 0, 0.9], [0, 0.3, 0]]))
|
| 56 |
+
loaded_matrix = load_npz(tmpfile)
|
| 57 |
+
finally:
|
| 58 |
+
os.remove(tmpfile)
|
| 59 |
+
|
| 60 |
+
#save/load array
|
| 61 |
+
fd, tmpfile = tempfile.mkstemp(suffix='.npz')
|
| 62 |
+
os.close(fd)
|
| 63 |
+
try:
|
| 64 |
+
save_npz(tmpfile, csr_array([[1.2, 0, 0.9], [0, 0.3, 0]]))
|
| 65 |
+
loaded_array = load_npz(tmpfile)
|
| 66 |
+
finally:
|
| 67 |
+
os.remove(tmpfile)
|
| 68 |
+
|
| 69 |
+
assert not isinstance(loaded_matrix, sparray)
|
| 70 |
+
assert isinstance(loaded_array, sparray)
|
| 71 |
+
assert_(loaded_matrix.dtype == loaded_array.dtype)
|
| 72 |
+
assert_equal(loaded_matrix.toarray(), loaded_array.toarray())
|
| 73 |
+
|
| 74 |
+
def test_malicious_load():
|
| 75 |
+
class Executor:
|
| 76 |
+
def __reduce__(self):
|
| 77 |
+
return (assert_, (False, 'unexpected code execution'))
|
| 78 |
+
|
| 79 |
+
fd, tmpfile = tempfile.mkstemp(suffix='.npz')
|
| 80 |
+
os.close(fd)
|
| 81 |
+
try:
|
| 82 |
+
np.savez(tmpfile, format=Executor())
|
| 83 |
+
|
| 84 |
+
# Should raise a ValueError, not execute code
|
| 85 |
+
assert_raises(ValueError, load_npz, tmpfile)
|
| 86 |
+
finally:
|
| 87 |
+
os.remove(tmpfile)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def test_py23_compatibility():
|
| 91 |
+
# Try loading files saved on Python 2 and Python 3. They are not
|
| 92 |
+
# the same, since files saved with SciPy versions < 1.0.0 may
|
| 93 |
+
# contain unicode.
|
| 94 |
+
|
| 95 |
+
a = load_npz(os.path.join(DATA_DIR, 'csc_py2.npz'))
|
| 96 |
+
b = load_npz(os.path.join(DATA_DIR, 'csc_py3.npz'))
|
| 97 |
+
c = csc_matrix([[0]])
|
| 98 |
+
|
| 99 |
+
assert_equal(a.toarray(), c.toarray())
|
| 100 |
+
assert_equal(b.toarray(), c.toarray())
|
| 101 |
+
|
| 102 |
+
def test_implemented_error():
|
| 103 |
+
# Attempts to save an unsupported type and checks that an
|
| 104 |
+
# NotImplementedError is raised.
|
| 105 |
+
|
| 106 |
+
x = dok_matrix((2,3))
|
| 107 |
+
x[0,1] = 1
|
| 108 |
+
|
| 109 |
+
assert_raises(NotImplementedError, save_npz, 'x.npz', x)
|
parrot/lib/python3.10/site-packages/scipy/sparse/tests/test_minmax1d.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test of min-max 1D features of sparse array classes"""
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from numpy.testing import assert_equal, assert_array_equal
|
| 8 |
+
|
| 9 |
+
from scipy.sparse import coo_array, csr_array, csc_array, bsr_array
|
| 10 |
+
from scipy.sparse import coo_matrix, csr_matrix, csc_matrix, bsr_matrix
|
| 11 |
+
from scipy.sparse._sputils import isscalarlike
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def toarray(a):
|
| 15 |
+
if isinstance(a, np.ndarray) or isscalarlike(a):
|
| 16 |
+
return a
|
| 17 |
+
return a.toarray()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
formats_for_minmax = [bsr_array, coo_array, csc_array, csr_array]
|
| 21 |
+
formats_for_minmax_supporting_1d = [coo_array, csr_array]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.mark.parametrize("spcreator", formats_for_minmax_supporting_1d)
|
| 25 |
+
class Test_MinMaxMixin1D:
|
| 26 |
+
def test_minmax(self, spcreator):
|
| 27 |
+
D = np.arange(5)
|
| 28 |
+
X = spcreator(D)
|
| 29 |
+
|
| 30 |
+
assert_equal(X.min(), 0)
|
| 31 |
+
assert_equal(X.max(), 4)
|
| 32 |
+
assert_equal((-X).min(), -4)
|
| 33 |
+
assert_equal((-X).max(), 0)
|
| 34 |
+
|
| 35 |
+
def test_minmax_axis(self, spcreator):
|
| 36 |
+
D = np.arange(50)
|
| 37 |
+
X = spcreator(D)
|
| 38 |
+
|
| 39 |
+
for axis in [0, -1]:
|
| 40 |
+
assert_array_equal(
|
| 41 |
+
toarray(X.max(axis=axis)), D.max(axis=axis, keepdims=True)
|
| 42 |
+
)
|
| 43 |
+
assert_array_equal(
|
| 44 |
+
toarray(X.min(axis=axis)), D.min(axis=axis, keepdims=True)
|
| 45 |
+
)
|
| 46 |
+
for axis in [-2, 1]:
|
| 47 |
+
with pytest.raises(ValueError, match="axis out of range"):
|
| 48 |
+
X.min(axis=axis)
|
| 49 |
+
with pytest.raises(ValueError, match="axis out of range"):
|
| 50 |
+
X.max(axis=axis)
|
| 51 |
+
|
| 52 |
+
def test_numpy_minmax(self, spcreator):
|
| 53 |
+
dat = np.array([0, 1, 2])
|
| 54 |
+
datsp = spcreator(dat)
|
| 55 |
+
assert_array_equal(np.min(datsp), np.min(dat))
|
| 56 |
+
assert_array_equal(np.max(datsp), np.max(dat))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_argmax(self, spcreator):
|
| 60 |
+
D1 = np.array([-1, 5, 2, 3])
|
| 61 |
+
D2 = np.array([0, 0, -1, -2])
|
| 62 |
+
D3 = np.array([-1, -2, -3, -4])
|
| 63 |
+
D4 = np.array([1, 2, 3, 4])
|
| 64 |
+
D5 = np.array([1, 2, 0, 0])
|
| 65 |
+
|
| 66 |
+
for D in [D1, D2, D3, D4, D5]:
|
| 67 |
+
mat = spcreator(D)
|
| 68 |
+
|
| 69 |
+
assert_equal(mat.argmax(), np.argmax(D))
|
| 70 |
+
assert_equal(mat.argmin(), np.argmin(D))
|
| 71 |
+
|
| 72 |
+
assert_equal(mat.argmax(axis=0), np.argmax(D, axis=0))
|
| 73 |
+
assert_equal(mat.argmin(axis=0), np.argmin(D, axis=0))
|
| 74 |
+
|
| 75 |
+
D6 = np.empty((0,))
|
| 76 |
+
|
| 77 |
+
for axis in [None, 0]:
|
| 78 |
+
mat = spcreator(D6)
|
| 79 |
+
with pytest.raises(ValueError, match="to an empty matrix"):
|
| 80 |
+
mat.argmin(axis=axis)
|
| 81 |
+
with pytest.raises(ValueError, match="to an empty matrix"):
|
| 82 |
+
mat.argmax(axis=axis)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@pytest.mark.parametrize("spcreator", formats_for_minmax)
|
| 86 |
+
class Test_ShapeMinMax2DWithAxis:
|
| 87 |
+
def test_minmax(self, spcreator):
|
| 88 |
+
dat = np.array([[-1, 5, 0, 3], [0, 0, -1, -2], [0, 0, 1, 2]])
|
| 89 |
+
datsp = spcreator(dat)
|
| 90 |
+
|
| 91 |
+
for (spminmax, npminmax) in [
|
| 92 |
+
(datsp.min, np.min),
|
| 93 |
+
(datsp.max, np.max),
|
| 94 |
+
(datsp.nanmin, np.nanmin),
|
| 95 |
+
(datsp.nanmax, np.nanmax),
|
| 96 |
+
]:
|
| 97 |
+
for ax, result_shape in [(0, (4,)), (1, (3,))]:
|
| 98 |
+
assert_equal(toarray(spminmax(axis=ax)), npminmax(dat, axis=ax))
|
| 99 |
+
assert_equal(spminmax(axis=ax).shape, result_shape)
|
| 100 |
+
assert spminmax(axis=ax).format == "coo"
|
| 101 |
+
|
| 102 |
+
for spminmax in [datsp.argmin, datsp.argmax]:
|
| 103 |
+
for ax in [0, 1]:
|
| 104 |
+
assert isinstance(spminmax(axis=ax), np.ndarray)
|
| 105 |
+
|
| 106 |
+
# verify spmatrix behavior
|
| 107 |
+
spmat_form = {
|
| 108 |
+
'coo': coo_matrix,
|
| 109 |
+
'csr': csr_matrix,
|
| 110 |
+
'csc': csc_matrix,
|
| 111 |
+
'bsr': bsr_matrix,
|
| 112 |
+
}
|
| 113 |
+
datspm = spmat_form[datsp.format](dat)
|
| 114 |
+
|
| 115 |
+
for spm, npm in [
|
| 116 |
+
(datspm.min, np.min),
|
| 117 |
+
(datspm.max, np.max),
|
| 118 |
+
(datspm.nanmin, np.nanmin),
|
| 119 |
+
(datspm.nanmax, np.nanmax),
|
| 120 |
+
]:
|
| 121 |
+
for ax, result_shape in [(0, (1, 4)), (1, (3, 1))]:
|
| 122 |
+
assert_equal(toarray(spm(axis=ax)), npm(dat, axis=ax, keepdims=True))
|
| 123 |
+
assert_equal(spm(axis=ax).shape, result_shape)
|
| 124 |
+
assert spm(axis=ax).format == "coo"
|
| 125 |
+
|
| 126 |
+
for spminmax in [datspm.argmin, datspm.argmax]:
|
| 127 |
+
for ax in [0, 1]:
|
| 128 |
+
assert isinstance(spminmax(axis=ax), np.ndarray)
|