Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__init__.py +236 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_interpolative_backend.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_solvers.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_testutils.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/lapack.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/misc.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_basic.py +1919 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi +16 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py +221 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py +374 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi +6 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py +111 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py +430 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py +517 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py +413 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_interpolative.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_interpolative_backend.py +1681 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi +6 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py +886 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_sketches.py +179 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_solve_toeplitz.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_solvers.py +846 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_testutils.py +63 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd +169 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx +1422 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp.py +25 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.py +22 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py +20 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp_schur.py +22 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/interpolative.py +1015 -0
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__init__.py
ADDED
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
====================================
|
3 |
+
Linear algebra (:mod:`scipy.linalg`)
|
4 |
+
====================================
|
5 |
+
|
6 |
+
.. currentmodule:: scipy.linalg
|
7 |
+
|
8 |
+
.. toctree::
|
9 |
+
:hidden:
|
10 |
+
|
11 |
+
linalg.blas
|
12 |
+
linalg.cython_blas
|
13 |
+
linalg.cython_lapack
|
14 |
+
linalg.interpolative
|
15 |
+
linalg.lapack
|
16 |
+
|
17 |
+
Linear algebra functions.
|
18 |
+
|
19 |
+
.. eventually, we should replace the numpy.linalg HTML link with just `numpy.linalg`
|
20 |
+
|
21 |
+
.. seealso::
|
22 |
+
|
23 |
+
`numpy.linalg <https://www.numpy.org/devdocs/reference/routines.linalg.html>`__
|
24 |
+
for more linear algebra functions. Note that
|
25 |
+
although `scipy.linalg` imports most of them, identically named
|
26 |
+
functions from `scipy.linalg` may offer more or slightly differing
|
27 |
+
functionality.
|
28 |
+
|
29 |
+
|
30 |
+
Basics
|
31 |
+
======
|
32 |
+
|
33 |
+
.. autosummary::
|
34 |
+
:toctree: generated/
|
35 |
+
|
36 |
+
inv - Find the inverse of a square matrix
|
37 |
+
solve - Solve a linear system of equations
|
38 |
+
solve_banded - Solve a banded linear system
|
39 |
+
solveh_banded - Solve a Hermitian or symmetric banded system
|
40 |
+
solve_circulant - Solve a circulant system
|
41 |
+
solve_triangular - Solve a triangular matrix
|
42 |
+
solve_toeplitz - Solve a toeplitz matrix
|
43 |
+
matmul_toeplitz - Multiply a Toeplitz matrix with an array.
|
44 |
+
det - Find the determinant of a square matrix
|
45 |
+
norm - Matrix and vector norm
|
46 |
+
lstsq - Solve a linear least-squares problem
|
47 |
+
pinv - Pseudo-inverse (Moore-Penrose) using lstsq
|
48 |
+
pinvh - Pseudo-inverse of hermitian matrix
|
49 |
+
kron - Kronecker product of two arrays
|
50 |
+
khatri_rao - Khatri-Rao product of two arrays
|
51 |
+
orthogonal_procrustes - Solve an orthogonal Procrustes problem
|
52 |
+
matrix_balance - Balance matrix entries with a similarity transformation
|
53 |
+
subspace_angles - Compute the subspace angles between two matrices
|
54 |
+
bandwidth - Return the lower and upper bandwidth of an array
|
55 |
+
issymmetric - Check if a square 2D array is symmetric
|
56 |
+
ishermitian - Check if a square 2D array is Hermitian
|
57 |
+
LinAlgError
|
58 |
+
LinAlgWarning
|
59 |
+
|
60 |
+
Eigenvalue Problems
|
61 |
+
===================
|
62 |
+
|
63 |
+
.. autosummary::
|
64 |
+
:toctree: generated/
|
65 |
+
|
66 |
+
eig - Find the eigenvalues and eigenvectors of a square matrix
|
67 |
+
eigvals - Find just the eigenvalues of a square matrix
|
68 |
+
eigh - Find the e-vals and e-vectors of a Hermitian or symmetric matrix
|
69 |
+
eigvalsh - Find just the eigenvalues of a Hermitian or symmetric matrix
|
70 |
+
eig_banded - Find the eigenvalues and eigenvectors of a banded matrix
|
71 |
+
eigvals_banded - Find just the eigenvalues of a banded matrix
|
72 |
+
eigh_tridiagonal - Find the eigenvalues and eigenvectors of a tridiagonal matrix
|
73 |
+
eigvalsh_tridiagonal - Find just the eigenvalues of a tridiagonal matrix
|
74 |
+
|
75 |
+
Decompositions
|
76 |
+
==============
|
77 |
+
|
78 |
+
.. autosummary::
|
79 |
+
:toctree: generated/
|
80 |
+
|
81 |
+
lu - LU decomposition of a matrix
|
82 |
+
lu_factor - LU decomposition returning unordered matrix and pivots
|
83 |
+
lu_solve - Solve Ax=b using back substitution with output of lu_factor
|
84 |
+
svd - Singular value decomposition of a matrix
|
85 |
+
svdvals - Singular values of a matrix
|
86 |
+
diagsvd - Construct matrix of singular values from output of svd
|
87 |
+
orth - Construct orthonormal basis for the range of A using svd
|
88 |
+
null_space - Construct orthonormal basis for the null space of A using svd
|
89 |
+
ldl - LDL.T decomposition of a Hermitian or a symmetric matrix.
|
90 |
+
cholesky - Cholesky decomposition of a matrix
|
91 |
+
cholesky_banded - Cholesky decomp. of a sym. or Hermitian banded matrix
|
92 |
+
cho_factor - Cholesky decomposition for use in solving a linear system
|
93 |
+
cho_solve - Solve previously factored linear system
|
94 |
+
cho_solve_banded - Solve previously factored banded linear system
|
95 |
+
polar - Compute the polar decomposition.
|
96 |
+
qr - QR decomposition of a matrix
|
97 |
+
qr_multiply - QR decomposition and multiplication by Q
|
98 |
+
qr_update - Rank k QR update
|
99 |
+
qr_delete - QR downdate on row or column deletion
|
100 |
+
qr_insert - QR update on row or column insertion
|
101 |
+
rq - RQ decomposition of a matrix
|
102 |
+
qz - QZ decomposition of a pair of matrices
|
103 |
+
ordqz - QZ decomposition of a pair of matrices with reordering
|
104 |
+
schur - Schur decomposition of a matrix
|
105 |
+
rsf2csf - Real to complex Schur form
|
106 |
+
hessenberg - Hessenberg form of a matrix
|
107 |
+
cdf2rdf - Complex diagonal form to real diagonal block form
|
108 |
+
cossin - Cosine sine decomposition of a unitary or orthogonal matrix
|
109 |
+
|
110 |
+
.. seealso::
|
111 |
+
|
112 |
+
`scipy.linalg.interpolative` -- Interpolative matrix decompositions
|
113 |
+
|
114 |
+
|
115 |
+
Matrix Functions
|
116 |
+
================
|
117 |
+
|
118 |
+
.. autosummary::
|
119 |
+
:toctree: generated/
|
120 |
+
|
121 |
+
expm - Matrix exponential
|
122 |
+
logm - Matrix logarithm
|
123 |
+
cosm - Matrix cosine
|
124 |
+
sinm - Matrix sine
|
125 |
+
tanm - Matrix tangent
|
126 |
+
coshm - Matrix hyperbolic cosine
|
127 |
+
sinhm - Matrix hyperbolic sine
|
128 |
+
tanhm - Matrix hyperbolic tangent
|
129 |
+
signm - Matrix sign
|
130 |
+
sqrtm - Matrix square root
|
131 |
+
funm - Evaluating an arbitrary matrix function
|
132 |
+
expm_frechet - Frechet derivative of the matrix exponential
|
133 |
+
expm_cond - Relative condition number of expm in the Frobenius norm
|
134 |
+
fractional_matrix_power - Fractional matrix power
|
135 |
+
|
136 |
+
|
137 |
+
Matrix Equation Solvers
|
138 |
+
=======================
|
139 |
+
|
140 |
+
.. autosummary::
|
141 |
+
:toctree: generated/
|
142 |
+
|
143 |
+
solve_sylvester - Solve the Sylvester matrix equation
|
144 |
+
solve_continuous_are - Solve the continuous-time algebraic Riccati equation
|
145 |
+
solve_discrete_are - Solve the discrete-time algebraic Riccati equation
|
146 |
+
solve_continuous_lyapunov - Solve the continuous-time Lyapunov equation
|
147 |
+
solve_discrete_lyapunov - Solve the discrete-time Lyapunov equation
|
148 |
+
|
149 |
+
|
150 |
+
Sketches and Random Projections
|
151 |
+
===============================
|
152 |
+
|
153 |
+
.. autosummary::
|
154 |
+
:toctree: generated/
|
155 |
+
|
156 |
+
clarkson_woodruff_transform - Applies the Clarkson Woodruff Sketch (a.k.a CountMin Sketch)
|
157 |
+
|
158 |
+
Special Matrices
|
159 |
+
================
|
160 |
+
|
161 |
+
.. autosummary::
|
162 |
+
:toctree: generated/
|
163 |
+
|
164 |
+
block_diag - Construct a block diagonal matrix from submatrices
|
165 |
+
circulant - Circulant matrix
|
166 |
+
companion - Companion matrix
|
167 |
+
convolution_matrix - Convolution matrix
|
168 |
+
dft - Discrete Fourier transform matrix
|
169 |
+
fiedler - Fiedler matrix
|
170 |
+
fiedler_companion - Fiedler companion matrix
|
171 |
+
hadamard - Hadamard matrix of order 2**n
|
172 |
+
hankel - Hankel matrix
|
173 |
+
helmert - Helmert matrix
|
174 |
+
hilbert - Hilbert matrix
|
175 |
+
invhilbert - Inverse Hilbert matrix
|
176 |
+
leslie - Leslie matrix
|
177 |
+
pascal - Pascal matrix
|
178 |
+
invpascal - Inverse Pascal matrix
|
179 |
+
toeplitz - Toeplitz matrix
|
180 |
+
|
181 |
+
Low-level routines
|
182 |
+
==================
|
183 |
+
|
184 |
+
.. autosummary::
|
185 |
+
:toctree: generated/
|
186 |
+
|
187 |
+
get_blas_funcs
|
188 |
+
get_lapack_funcs
|
189 |
+
find_best_blas_type
|
190 |
+
|
191 |
+
.. seealso::
|
192 |
+
|
193 |
+
`scipy.linalg.blas` -- Low-level BLAS functions
|
194 |
+
|
195 |
+
`scipy.linalg.lapack` -- Low-level LAPACK functions
|
196 |
+
|
197 |
+
`scipy.linalg.cython_blas` -- Low-level BLAS functions for Cython
|
198 |
+
|
199 |
+
`scipy.linalg.cython_lapack` -- Low-level LAPACK functions for Cython
|
200 |
+
|
201 |
+
""" # noqa: E501
|
202 |
+
|
203 |
+
from ._misc import *
|
204 |
+
from ._cythonized_array_utils import *
|
205 |
+
from ._basic import *
|
206 |
+
from ._decomp import *
|
207 |
+
from ._decomp_lu import *
|
208 |
+
from ._decomp_ldl import *
|
209 |
+
from ._decomp_cholesky import *
|
210 |
+
from ._decomp_qr import *
|
211 |
+
from ._decomp_qz import *
|
212 |
+
from ._decomp_svd import *
|
213 |
+
from ._decomp_schur import *
|
214 |
+
from ._decomp_polar import *
|
215 |
+
from ._matfuncs import *
|
216 |
+
from .blas import *
|
217 |
+
from .lapack import *
|
218 |
+
from ._special_matrices import *
|
219 |
+
from ._solvers import *
|
220 |
+
from ._procrustes import *
|
221 |
+
from ._decomp_update import *
|
222 |
+
from ._sketches import *
|
223 |
+
from ._decomp_cossin import *
|
224 |
+
|
225 |
+
# Deprecated namespaces, to be removed in v2.0.0
|
226 |
+
from . import (
|
227 |
+
decomp, decomp_cholesky, decomp_lu, decomp_qr, decomp_svd, decomp_schur,
|
228 |
+
basic, misc, special_matrices, matfuncs,
|
229 |
+
)
|
230 |
+
|
231 |
+
__all__ = [s for s in dir() if not s.startswith('_')]
|
232 |
+
|
233 |
+
|
234 |
+
from scipy._lib._testutils import PytestTester
|
235 |
+
test = PytestTester(__name__)
|
236 |
+
del PytestTester
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (7.74 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-310.pyc
ADDED
Binary file (11.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc
ADDED
Binary file (8.12 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-310.pyc
ADDED
Binary file (11 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc
ADDED
Binary file (11.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-310.pyc
ADDED
Binary file (3.76 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc
ADDED
Binary file (14.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-310.pyc
ADDED
Binary file (10.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-310.pyc
ADDED
Binary file (14.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_interpolative_backend.cpython-310.pyc
ADDED
Binary file (40.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc
ADDED
Binary file (5.81 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc
ADDED
Binary file (6.31 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_solvers.cpython-310.pyc
ADDED
Binary file (23.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc
ADDED
Binary file (35.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_testutils.cpython-310.pyc
ADDED
Binary file (2.48 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc
ADDED
Binary file (675 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc
ADDED
Binary file (647 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc
ADDED
Binary file (714 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc
ADDED
Binary file (28.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/lapack.cpython-310.pyc
ADDED
Binary file (14.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/misc.cpython-310.pyc
ADDED
Binary file (651 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_basic.py
ADDED
@@ -0,0 +1,1919 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# Author: Pearu Peterson, March 2002
|
3 |
+
#
|
4 |
+
# w/ additions by Travis Oliphant, March 2002
|
5 |
+
# and Jake Vanderplas, August 2012
|
6 |
+
|
7 |
+
from warnings import warn
|
8 |
+
from itertools import product
|
9 |
+
import numpy as np
|
10 |
+
from numpy import atleast_1d, atleast_2d
|
11 |
+
from .lapack import get_lapack_funcs, _compute_lwork
|
12 |
+
from ._misc import LinAlgError, _datacopied, LinAlgWarning
|
13 |
+
from ._decomp import _asarray_validated
|
14 |
+
from . import _decomp, _decomp_svd
|
15 |
+
from ._solve_toeplitz import levinson
|
16 |
+
from ._cythonized_array_utils import find_det_from_lu
|
17 |
+
from scipy._lib.deprecation import _NoValue, _deprecate_positional_args
|
18 |
+
|
19 |
+
__all__ = ['solve', 'solve_triangular', 'solveh_banded', 'solve_banded',
|
20 |
+
'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq',
|
21 |
+
'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz']
|
22 |
+
|
23 |
+
|
24 |
+
# The numpy facilities for type-casting checks are too slow for small sized
|
25 |
+
# arrays and eat away the time budget for the checkups. Here we set a
|
26 |
+
# precomputed dict container of the numpy.can_cast() table.
|
27 |
+
|
28 |
+
# It can be used to determine quickly what a dtype can be cast to LAPACK
|
29 |
+
# compatible types, i.e., 'float32, float64, complex64, complex128'.
|
30 |
+
# Then it can be checked via "casting_dict[arr.dtype.char]"
|
31 |
+
lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)])
|
32 |
+
for x in np.typecodes['All']}
|
33 |
+
|
34 |
+
|
35 |
+
# Linear equations
|
36 |
+
def _solve_check(n, info, lamch=None, rcond=None):
|
37 |
+
""" Check arguments during the different steps of the solution phase """
|
38 |
+
if info < 0:
|
39 |
+
raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument.')
|
40 |
+
elif 0 < info:
|
41 |
+
raise LinAlgError('Matrix is singular.')
|
42 |
+
|
43 |
+
if lamch is None:
|
44 |
+
return
|
45 |
+
E = lamch('E')
|
46 |
+
if rcond < E:
|
47 |
+
warn(f'Ill-conditioned matrix (rcond={rcond:.6g}): '
|
48 |
+
'result may not be accurate.',
|
49 |
+
LinAlgWarning, stacklevel=3)
|
50 |
+
|
51 |
+
|
52 |
+
def solve(a, b, lower=False, overwrite_a=False,
|
53 |
+
overwrite_b=False, check_finite=True, assume_a='gen',
|
54 |
+
transposed=False):
|
55 |
+
"""
|
56 |
+
Solves the linear equation set ``a @ x == b`` for the unknown ``x``
|
57 |
+
for square `a` matrix.
|
58 |
+
|
59 |
+
If the data matrix is known to be a particular type then supplying the
|
60 |
+
corresponding string to ``assume_a`` key chooses the dedicated solver.
|
61 |
+
The available options are
|
62 |
+
|
63 |
+
=================== ========
|
64 |
+
generic matrix 'gen'
|
65 |
+
symmetric 'sym'
|
66 |
+
hermitian 'her'
|
67 |
+
positive definite 'pos'
|
68 |
+
=================== ========
|
69 |
+
|
70 |
+
If omitted, ``'gen'`` is the default structure.
|
71 |
+
|
72 |
+
The datatype of the arrays define which solver is called regardless
|
73 |
+
of the values. In other words, even when the complex array entries have
|
74 |
+
precisely zero imaginary parts, the complex solver will be called based
|
75 |
+
on the data type of the array.
|
76 |
+
|
77 |
+
Parameters
|
78 |
+
----------
|
79 |
+
a : (N, N) array_like
|
80 |
+
Square input data
|
81 |
+
b : (N, NRHS) array_like
|
82 |
+
Input data for the right hand side.
|
83 |
+
lower : bool, default: False
|
84 |
+
Ignored if ``assume_a == 'gen'`` (the default). If True, the
|
85 |
+
calculation uses only the data in the lower triangle of `a`;
|
86 |
+
entries above the diagonal are ignored. If False (default), the
|
87 |
+
calculation uses only the data in the upper triangle of `a`; entries
|
88 |
+
below the diagonal are ignored.
|
89 |
+
overwrite_a : bool, default: False
|
90 |
+
Allow overwriting data in `a` (may enhance performance).
|
91 |
+
overwrite_b : bool, default: False
|
92 |
+
Allow overwriting data in `b` (may enhance performance).
|
93 |
+
check_finite : bool, default: True
|
94 |
+
Whether to check that the input matrices contain only finite numbers.
|
95 |
+
Disabling may give a performance gain, but may result in problems
|
96 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
97 |
+
assume_a : str, {'gen', 'sym', 'her', 'pos'}
|
98 |
+
Valid entries are explained above.
|
99 |
+
transposed : bool, default: False
|
100 |
+
If True, solve ``a.T @ x == b``. Raises `NotImplementedError`
|
101 |
+
for complex `a`.
|
102 |
+
|
103 |
+
Returns
|
104 |
+
-------
|
105 |
+
x : (N, NRHS) ndarray
|
106 |
+
The solution array.
|
107 |
+
|
108 |
+
Raises
|
109 |
+
------
|
110 |
+
ValueError
|
111 |
+
If size mismatches detected or input a is not square.
|
112 |
+
LinAlgError
|
113 |
+
If the matrix is singular.
|
114 |
+
LinAlgWarning
|
115 |
+
If an ill-conditioned input a is detected.
|
116 |
+
NotImplementedError
|
117 |
+
If transposed is True and input a is a complex matrix.
|
118 |
+
|
119 |
+
Notes
|
120 |
+
-----
|
121 |
+
If the input b matrix is a 1-D array with N elements, when supplied
|
122 |
+
together with an NxN input a, it is assumed as a valid column vector
|
123 |
+
despite the apparent size mismatch. This is compatible with the
|
124 |
+
numpy.dot() behavior and the returned result is still 1-D array.
|
125 |
+
|
126 |
+
The generic, symmetric, Hermitian and positive definite solutions are
|
127 |
+
obtained via calling ?GESV, ?SYSV, ?HESV, and ?POSV routines of
|
128 |
+
LAPACK respectively.
|
129 |
+
|
130 |
+
Examples
|
131 |
+
--------
|
132 |
+
Given `a` and `b`, solve for `x`:
|
133 |
+
|
134 |
+
>>> import numpy as np
|
135 |
+
>>> a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
|
136 |
+
>>> b = np.array([2, 4, -1])
|
137 |
+
>>> from scipy import linalg
|
138 |
+
>>> x = linalg.solve(a, b)
|
139 |
+
>>> x
|
140 |
+
array([ 2., -2., 9.])
|
141 |
+
>>> np.dot(a, x) == b
|
142 |
+
array([ True, True, True], dtype=bool)
|
143 |
+
|
144 |
+
"""
|
145 |
+
# Flags for 1-D or N-D right-hand side
|
146 |
+
b_is_1D = False
|
147 |
+
|
148 |
+
a1 = atleast_2d(_asarray_validated(a, check_finite=check_finite))
|
149 |
+
b1 = atleast_1d(_asarray_validated(b, check_finite=check_finite))
|
150 |
+
n = a1.shape[0]
|
151 |
+
|
152 |
+
overwrite_a = overwrite_a or _datacopied(a1, a)
|
153 |
+
overwrite_b = overwrite_b or _datacopied(b1, b)
|
154 |
+
|
155 |
+
if a1.shape[0] != a1.shape[1]:
|
156 |
+
raise ValueError('Input a needs to be a square matrix.')
|
157 |
+
|
158 |
+
if n != b1.shape[0]:
|
159 |
+
# Last chance to catch 1x1 scalar a and 1-D b arrays
|
160 |
+
if not (n == 1 and b1.size != 0):
|
161 |
+
raise ValueError('Input b has to have same number of rows as '
|
162 |
+
'input a')
|
163 |
+
|
164 |
+
# accommodate empty arrays
|
165 |
+
if b1.size == 0:
|
166 |
+
return np.asfortranarray(b1.copy())
|
167 |
+
|
168 |
+
# regularize 1-D b arrays to 2D
|
169 |
+
if b1.ndim == 1:
|
170 |
+
if n == 1:
|
171 |
+
b1 = b1[None, :]
|
172 |
+
else:
|
173 |
+
b1 = b1[:, None]
|
174 |
+
b_is_1D = True
|
175 |
+
|
176 |
+
if assume_a not in ('gen', 'sym', 'her', 'pos'):
|
177 |
+
raise ValueError(f'{assume_a} is not a recognized matrix structure')
|
178 |
+
|
179 |
+
# for a real matrix, describe it as "symmetric", not "hermitian"
|
180 |
+
# (lapack doesn't know what to do with real hermitian matrices)
|
181 |
+
if assume_a == 'her' and not np.iscomplexobj(a1):
|
182 |
+
assume_a = 'sym'
|
183 |
+
|
184 |
+
# Get the correct lamch function.
|
185 |
+
# The LAMCH functions only exists for S and D
|
186 |
+
# So for complex values we have to convert to real/double.
|
187 |
+
if a1.dtype.char in 'fF': # single precision
|
188 |
+
lamch = get_lapack_funcs('lamch', dtype='f')
|
189 |
+
else:
|
190 |
+
lamch = get_lapack_funcs('lamch', dtype='d')
|
191 |
+
|
192 |
+
# Currently we do not have the other forms of the norm calculators
|
193 |
+
# lansy, lanpo, lanhe.
|
194 |
+
# However, in any case they only reduce computations slightly...
|
195 |
+
lange = get_lapack_funcs('lange', (a1,))
|
196 |
+
|
197 |
+
# Since the I-norm and 1-norm are the same for symmetric matrices
|
198 |
+
# we can collect them all in this one call
|
199 |
+
# Note however, that when issuing 'gen' and form!='none', then
|
200 |
+
# the I-norm should be used
|
201 |
+
if transposed:
|
202 |
+
trans = 1
|
203 |
+
norm = 'I'
|
204 |
+
if np.iscomplexobj(a1):
|
205 |
+
raise NotImplementedError('scipy.linalg.solve can currently '
|
206 |
+
'not solve a^T x = b or a^H x = b '
|
207 |
+
'for complex matrices.')
|
208 |
+
else:
|
209 |
+
trans = 0
|
210 |
+
norm = '1'
|
211 |
+
|
212 |
+
anorm = lange(norm, a1)
|
213 |
+
|
214 |
+
# Generalized case 'gesv'
|
215 |
+
if assume_a == 'gen':
|
216 |
+
gecon, getrf, getrs = get_lapack_funcs(('gecon', 'getrf', 'getrs'),
|
217 |
+
(a1, b1))
|
218 |
+
lu, ipvt, info = getrf(a1, overwrite_a=overwrite_a)
|
219 |
+
_solve_check(n, info)
|
220 |
+
x, info = getrs(lu, ipvt, b1,
|
221 |
+
trans=trans, overwrite_b=overwrite_b)
|
222 |
+
_solve_check(n, info)
|
223 |
+
rcond, info = gecon(lu, anorm, norm=norm)
|
224 |
+
# Hermitian case 'hesv'
|
225 |
+
elif assume_a == 'her':
|
226 |
+
hecon, hesv, hesv_lw = get_lapack_funcs(('hecon', 'hesv',
|
227 |
+
'hesv_lwork'), (a1, b1))
|
228 |
+
lwork = _compute_lwork(hesv_lw, n, lower)
|
229 |
+
lu, ipvt, x, info = hesv(a1, b1, lwork=lwork,
|
230 |
+
lower=lower,
|
231 |
+
overwrite_a=overwrite_a,
|
232 |
+
overwrite_b=overwrite_b)
|
233 |
+
_solve_check(n, info)
|
234 |
+
rcond, info = hecon(lu, ipvt, anorm)
|
235 |
+
# Symmetric case 'sysv'
|
236 |
+
elif assume_a == 'sym':
|
237 |
+
sycon, sysv, sysv_lw = get_lapack_funcs(('sycon', 'sysv',
|
238 |
+
'sysv_lwork'), (a1, b1))
|
239 |
+
lwork = _compute_lwork(sysv_lw, n, lower)
|
240 |
+
lu, ipvt, x, info = sysv(a1, b1, lwork=lwork,
|
241 |
+
lower=lower,
|
242 |
+
overwrite_a=overwrite_a,
|
243 |
+
overwrite_b=overwrite_b)
|
244 |
+
_solve_check(n, info)
|
245 |
+
rcond, info = sycon(lu, ipvt, anorm)
|
246 |
+
# Positive definite case 'posv'
|
247 |
+
else:
|
248 |
+
pocon, posv = get_lapack_funcs(('pocon', 'posv'),
|
249 |
+
(a1, b1))
|
250 |
+
lu, x, info = posv(a1, b1, lower=lower,
|
251 |
+
overwrite_a=overwrite_a,
|
252 |
+
overwrite_b=overwrite_b)
|
253 |
+
_solve_check(n, info)
|
254 |
+
rcond, info = pocon(lu, anorm)
|
255 |
+
|
256 |
+
_solve_check(n, info, lamch, rcond)
|
257 |
+
|
258 |
+
if b_is_1D:
|
259 |
+
x = x.ravel()
|
260 |
+
|
261 |
+
return x
|
262 |
+
|
263 |
+
|
264 |
+
def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False,
|
265 |
+
overwrite_b=False, check_finite=True):
|
266 |
+
"""
|
267 |
+
Solve the equation `a x = b` for `x`, assuming a is a triangular matrix.
|
268 |
+
|
269 |
+
Parameters
|
270 |
+
----------
|
271 |
+
a : (M, M) array_like
|
272 |
+
A triangular matrix
|
273 |
+
b : (M,) or (M, N) array_like
|
274 |
+
Right-hand side matrix in `a x = b`
|
275 |
+
lower : bool, optional
|
276 |
+
Use only data contained in the lower triangle of `a`.
|
277 |
+
Default is to use upper triangle.
|
278 |
+
trans : {0, 1, 2, 'N', 'T', 'C'}, optional
|
279 |
+
Type of system to solve:
|
280 |
+
|
281 |
+
======== =========
|
282 |
+
trans system
|
283 |
+
======== =========
|
284 |
+
0 or 'N' a x = b
|
285 |
+
1 or 'T' a^T x = b
|
286 |
+
2 or 'C' a^H x = b
|
287 |
+
======== =========
|
288 |
+
unit_diagonal : bool, optional
|
289 |
+
If True, diagonal elements of `a` are assumed to be 1 and
|
290 |
+
will not be referenced.
|
291 |
+
overwrite_b : bool, optional
|
292 |
+
Allow overwriting data in `b` (may enhance performance)
|
293 |
+
check_finite : bool, optional
|
294 |
+
Whether to check that the input matrices contain only finite numbers.
|
295 |
+
Disabling may give a performance gain, but may result in problems
|
296 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
297 |
+
|
298 |
+
Returns
|
299 |
+
-------
|
300 |
+
x : (M,) or (M, N) ndarray
|
301 |
+
Solution to the system `a x = b`. Shape of return matches `b`.
|
302 |
+
|
303 |
+
Raises
|
304 |
+
------
|
305 |
+
LinAlgError
|
306 |
+
If `a` is singular
|
307 |
+
|
308 |
+
Notes
|
309 |
+
-----
|
310 |
+
.. versionadded:: 0.9.0
|
311 |
+
|
312 |
+
Examples
|
313 |
+
--------
|
314 |
+
Solve the lower triangular system a x = b, where::
|
315 |
+
|
316 |
+
[3 0 0 0] [4]
|
317 |
+
a = [2 1 0 0] b = [2]
|
318 |
+
[1 0 1 0] [4]
|
319 |
+
[1 1 1 1] [2]
|
320 |
+
|
321 |
+
>>> import numpy as np
|
322 |
+
>>> from scipy.linalg import solve_triangular
|
323 |
+
>>> a = np.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]])
|
324 |
+
>>> b = np.array([4, 2, 4, 2])
|
325 |
+
>>> x = solve_triangular(a, b, lower=True)
|
326 |
+
>>> x
|
327 |
+
array([ 1.33333333, -0.66666667, 2.66666667, -1.33333333])
|
328 |
+
>>> a.dot(x) # Check the result
|
329 |
+
array([ 4., 2., 4., 2.])
|
330 |
+
|
331 |
+
"""
|
332 |
+
|
333 |
+
a1 = _asarray_validated(a, check_finite=check_finite)
|
334 |
+
b1 = _asarray_validated(b, check_finite=check_finite)
|
335 |
+
if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
|
336 |
+
raise ValueError('expected square matrix')
|
337 |
+
if a1.shape[0] != b1.shape[0]:
|
338 |
+
raise ValueError(f'shapes of a {a1.shape} and b {b1.shape} are incompatible')
|
339 |
+
overwrite_b = overwrite_b or _datacopied(b1, b)
|
340 |
+
|
341 |
+
trans = {'N': 0, 'T': 1, 'C': 2}.get(trans, trans)
|
342 |
+
trtrs, = get_lapack_funcs(('trtrs',), (a1, b1))
|
343 |
+
if a1.flags.f_contiguous or trans == 2:
|
344 |
+
x, info = trtrs(a1, b1, overwrite_b=overwrite_b, lower=lower,
|
345 |
+
trans=trans, unitdiag=unit_diagonal)
|
346 |
+
else:
|
347 |
+
# transposed system is solved since trtrs expects Fortran ordering
|
348 |
+
x, info = trtrs(a1.T, b1, overwrite_b=overwrite_b, lower=not lower,
|
349 |
+
trans=not trans, unitdiag=unit_diagonal)
|
350 |
+
|
351 |
+
if info == 0:
|
352 |
+
return x
|
353 |
+
if info > 0:
|
354 |
+
raise LinAlgError("singular matrix: resolution failed at diagonal %d" %
|
355 |
+
(info-1))
|
356 |
+
raise ValueError('illegal value in %dth argument of internal trtrs' %
|
357 |
+
(-info))
|
358 |
+
|
359 |
+
|
360 |
+
def solve_banded(l_and_u, ab, b, overwrite_ab=False, overwrite_b=False,
|
361 |
+
check_finite=True):
|
362 |
+
"""
|
363 |
+
Solve the equation a x = b for x, assuming a is banded matrix.
|
364 |
+
|
365 |
+
The matrix a is stored in `ab` using the matrix diagonal ordered form::
|
366 |
+
|
367 |
+
ab[u + i - j, j] == a[i,j]
|
368 |
+
|
369 |
+
Example of `ab` (shape of a is (6,6), `u` =1, `l` =2)::
|
370 |
+
|
371 |
+
* a01 a12 a23 a34 a45
|
372 |
+
a00 a11 a22 a33 a44 a55
|
373 |
+
a10 a21 a32 a43 a54 *
|
374 |
+
a20 a31 a42 a53 * *
|
375 |
+
|
376 |
+
Parameters
|
377 |
+
----------
|
378 |
+
(l, u) : (integer, integer)
|
379 |
+
Number of non-zero lower and upper diagonals
|
380 |
+
ab : (`l` + `u` + 1, M) array_like
|
381 |
+
Banded matrix
|
382 |
+
b : (M,) or (M, K) array_like
|
383 |
+
Right-hand side
|
384 |
+
overwrite_ab : bool, optional
|
385 |
+
Discard data in `ab` (may enhance performance)
|
386 |
+
overwrite_b : bool, optional
|
387 |
+
Discard data in `b` (may enhance performance)
|
388 |
+
check_finite : bool, optional
|
389 |
+
Whether to check that the input matrices contain only finite numbers.
|
390 |
+
Disabling may give a performance gain, but may result in problems
|
391 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
392 |
+
|
393 |
+
Returns
|
394 |
+
-------
|
395 |
+
x : (M,) or (M, K) ndarray
|
396 |
+
The solution to the system a x = b. Returned shape depends on the
|
397 |
+
shape of `b`.
|
398 |
+
|
399 |
+
Examples
|
400 |
+
--------
|
401 |
+
Solve the banded system a x = b, where::
|
402 |
+
|
403 |
+
[5 2 -1 0 0] [0]
|
404 |
+
[1 4 2 -1 0] [1]
|
405 |
+
a = [0 1 3 2 -1] b = [2]
|
406 |
+
[0 0 1 2 2] [2]
|
407 |
+
[0 0 0 1 1] [3]
|
408 |
+
|
409 |
+
There is one nonzero diagonal below the main diagonal (l = 1), and
|
410 |
+
two above (u = 2). The diagonal banded form of the matrix is::
|
411 |
+
|
412 |
+
[* * -1 -1 -1]
|
413 |
+
ab = [* 2 2 2 2]
|
414 |
+
[5 4 3 2 1]
|
415 |
+
[1 1 1 1 *]
|
416 |
+
|
417 |
+
>>> import numpy as np
|
418 |
+
>>> from scipy.linalg import solve_banded
|
419 |
+
>>> ab = np.array([[0, 0, -1, -1, -1],
|
420 |
+
... [0, 2, 2, 2, 2],
|
421 |
+
... [5, 4, 3, 2, 1],
|
422 |
+
... [1, 1, 1, 1, 0]])
|
423 |
+
>>> b = np.array([0, 1, 2, 2, 3])
|
424 |
+
>>> x = solve_banded((1, 2), ab, b)
|
425 |
+
>>> x
|
426 |
+
array([-2.37288136, 3.93220339, -4. , 4.3559322 , -1.3559322 ])
|
427 |
+
|
428 |
+
"""
|
429 |
+
|
430 |
+
a1 = _asarray_validated(ab, check_finite=check_finite, as_inexact=True)
|
431 |
+
b1 = _asarray_validated(b, check_finite=check_finite, as_inexact=True)
|
432 |
+
# Validate shapes.
|
433 |
+
if a1.shape[-1] != b1.shape[0]:
|
434 |
+
raise ValueError("shapes of ab and b are not compatible.")
|
435 |
+
(nlower, nupper) = l_and_u
|
436 |
+
if nlower + nupper + 1 != a1.shape[0]:
|
437 |
+
raise ValueError("invalid values for the number of lower and upper "
|
438 |
+
"diagonals: l+u+1 (%d) does not equal ab.shape[0] "
|
439 |
+
"(%d)" % (nlower + nupper + 1, ab.shape[0]))
|
440 |
+
|
441 |
+
overwrite_b = overwrite_b or _datacopied(b1, b)
|
442 |
+
if a1.shape[-1] == 1:
|
443 |
+
b2 = np.array(b1, copy=(not overwrite_b))
|
444 |
+
b2 /= a1[1, 0]
|
445 |
+
return b2
|
446 |
+
if nlower == nupper == 1:
|
447 |
+
overwrite_ab = overwrite_ab or _datacopied(a1, ab)
|
448 |
+
gtsv, = get_lapack_funcs(('gtsv',), (a1, b1))
|
449 |
+
du = a1[0, 1:]
|
450 |
+
d = a1[1, :]
|
451 |
+
dl = a1[2, :-1]
|
452 |
+
du2, d, du, x, info = gtsv(dl, d, du, b1, overwrite_ab, overwrite_ab,
|
453 |
+
overwrite_ab, overwrite_b)
|
454 |
+
else:
|
455 |
+
gbsv, = get_lapack_funcs(('gbsv',), (a1, b1))
|
456 |
+
a2 = np.zeros((2*nlower + nupper + 1, a1.shape[1]), dtype=gbsv.dtype)
|
457 |
+
a2[nlower:, :] = a1
|
458 |
+
lu, piv, x, info = gbsv(nlower, nupper, a2, b1, overwrite_ab=True,
|
459 |
+
overwrite_b=overwrite_b)
|
460 |
+
if info == 0:
|
461 |
+
return x
|
462 |
+
if info > 0:
|
463 |
+
raise LinAlgError("singular matrix")
|
464 |
+
raise ValueError('illegal value in %d-th argument of internal '
|
465 |
+
'gbsv/gtsv' % -info)
|
466 |
+
|
467 |
+
|
468 |
+
def solveh_banded(ab, b, overwrite_ab=False, overwrite_b=False, lower=False,
|
469 |
+
check_finite=True):
|
470 |
+
"""
|
471 |
+
Solve equation a x = b. a is Hermitian positive-definite banded matrix.
|
472 |
+
|
473 |
+
Uses Thomas' Algorithm, which is more efficient than standard LU
|
474 |
+
factorization, but should only be used for Hermitian positive-definite
|
475 |
+
matrices.
|
476 |
+
|
477 |
+
The matrix ``a`` is stored in `ab` either in lower diagonal or upper
|
478 |
+
diagonal ordered form:
|
479 |
+
|
480 |
+
ab[u + i - j, j] == a[i,j] (if upper form; i <= j)
|
481 |
+
ab[ i - j, j] == a[i,j] (if lower form; i >= j)
|
482 |
+
|
483 |
+
Example of `ab` (shape of ``a`` is (6, 6), number of upper diagonals,
|
484 |
+
``u`` =2)::
|
485 |
+
|
486 |
+
upper form:
|
487 |
+
* * a02 a13 a24 a35
|
488 |
+
* a01 a12 a23 a34 a45
|
489 |
+
a00 a11 a22 a33 a44 a55
|
490 |
+
|
491 |
+
lower form:
|
492 |
+
a00 a11 a22 a33 a44 a55
|
493 |
+
a10 a21 a32 a43 a54 *
|
494 |
+
a20 a31 a42 a53 * *
|
495 |
+
|
496 |
+
Cells marked with * are not used.
|
497 |
+
|
498 |
+
Parameters
|
499 |
+
----------
|
500 |
+
ab : (``u`` + 1, M) array_like
|
501 |
+
Banded matrix
|
502 |
+
b : (M,) or (M, K) array_like
|
503 |
+
Right-hand side
|
504 |
+
overwrite_ab : bool, optional
|
505 |
+
Discard data in `ab` (may enhance performance)
|
506 |
+
overwrite_b : bool, optional
|
507 |
+
Discard data in `b` (may enhance performance)
|
508 |
+
lower : bool, optional
|
509 |
+
Is the matrix in the lower form. (Default is upper form)
|
510 |
+
check_finite : bool, optional
|
511 |
+
Whether to check that the input matrices contain only finite numbers.
|
512 |
+
Disabling may give a performance gain, but may result in problems
|
513 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
514 |
+
|
515 |
+
Returns
|
516 |
+
-------
|
517 |
+
x : (M,) or (M, K) ndarray
|
518 |
+
The solution to the system ``a x = b``. Shape of return matches shape
|
519 |
+
of `b`.
|
520 |
+
|
521 |
+
Notes
|
522 |
+
-----
|
523 |
+
In the case of a non-positive definite matrix ``a``, the solver
|
524 |
+
`solve_banded` may be used.
|
525 |
+
|
526 |
+
Examples
|
527 |
+
--------
|
528 |
+
Solve the banded system ``A x = b``, where::
|
529 |
+
|
530 |
+
[ 4 2 -1 0 0 0] [1]
|
531 |
+
[ 2 5 2 -1 0 0] [2]
|
532 |
+
A = [-1 2 6 2 -1 0] b = [2]
|
533 |
+
[ 0 -1 2 7 2 -1] [3]
|
534 |
+
[ 0 0 -1 2 8 2] [3]
|
535 |
+
[ 0 0 0 -1 2 9] [3]
|
536 |
+
|
537 |
+
>>> import numpy as np
|
538 |
+
>>> from scipy.linalg import solveh_banded
|
539 |
+
|
540 |
+
``ab`` contains the main diagonal and the nonzero diagonals below the
|
541 |
+
main diagonal. That is, we use the lower form:
|
542 |
+
|
543 |
+
>>> ab = np.array([[ 4, 5, 6, 7, 8, 9],
|
544 |
+
... [ 2, 2, 2, 2, 2, 0],
|
545 |
+
... [-1, -1, -1, -1, 0, 0]])
|
546 |
+
>>> b = np.array([1, 2, 2, 3, 3, 3])
|
547 |
+
>>> x = solveh_banded(ab, b, lower=True)
|
548 |
+
>>> x
|
549 |
+
array([ 0.03431373, 0.45938375, 0.05602241, 0.47759104, 0.17577031,
|
550 |
+
0.34733894])
|
551 |
+
|
552 |
+
|
553 |
+
Solve the Hermitian banded system ``H x = b``, where::
|
554 |
+
|
555 |
+
[ 8 2-1j 0 0 ] [ 1 ]
|
556 |
+
H = [2+1j 5 1j 0 ] b = [1+1j]
|
557 |
+
[ 0 -1j 9 -2-1j] [1-2j]
|
558 |
+
[ 0 0 -2+1j 6 ] [ 0 ]
|
559 |
+
|
560 |
+
In this example, we put the upper diagonals in the array ``hb``:
|
561 |
+
|
562 |
+
>>> hb = np.array([[0, 2-1j, 1j, -2-1j],
|
563 |
+
... [8, 5, 9, 6 ]])
|
564 |
+
>>> b = np.array([1, 1+1j, 1-2j, 0])
|
565 |
+
>>> x = solveh_banded(hb, b)
|
566 |
+
>>> x
|
567 |
+
array([ 0.07318536-0.02939412j, 0.11877624+0.17696461j,
|
568 |
+
0.10077984-0.23035393j, -0.00479904-0.09358128j])
|
569 |
+
|
570 |
+
"""
|
571 |
+
a1 = _asarray_validated(ab, check_finite=check_finite)
|
572 |
+
b1 = _asarray_validated(b, check_finite=check_finite)
|
573 |
+
# Validate shapes.
|
574 |
+
if a1.shape[-1] != b1.shape[0]:
|
575 |
+
raise ValueError("shapes of ab and b are not compatible.")
|
576 |
+
|
577 |
+
overwrite_b = overwrite_b or _datacopied(b1, b)
|
578 |
+
overwrite_ab = overwrite_ab or _datacopied(a1, ab)
|
579 |
+
|
580 |
+
if a1.shape[0] == 2:
|
581 |
+
ptsv, = get_lapack_funcs(('ptsv',), (a1, b1))
|
582 |
+
if lower:
|
583 |
+
d = a1[0, :].real
|
584 |
+
e = a1[1, :-1]
|
585 |
+
else:
|
586 |
+
d = a1[1, :].real
|
587 |
+
e = a1[0, 1:].conj()
|
588 |
+
d, du, x, info = ptsv(d, e, b1, overwrite_ab, overwrite_ab,
|
589 |
+
overwrite_b)
|
590 |
+
else:
|
591 |
+
pbsv, = get_lapack_funcs(('pbsv',), (a1, b1))
|
592 |
+
c, x, info = pbsv(a1, b1, lower=lower, overwrite_ab=overwrite_ab,
|
593 |
+
overwrite_b=overwrite_b)
|
594 |
+
if info > 0:
|
595 |
+
raise LinAlgError("%dth leading minor not positive definite" % info)
|
596 |
+
if info < 0:
|
597 |
+
raise ValueError('illegal value in %dth argument of internal '
|
598 |
+
'pbsv' % -info)
|
599 |
+
return x
|
600 |
+
|
601 |
+
|
602 |
+
def solve_toeplitz(c_or_cr, b, check_finite=True):
|
603 |
+
"""Solve a Toeplitz system using Levinson Recursion
|
604 |
+
|
605 |
+
The Toeplitz matrix has constant diagonals, with c as its first column
|
606 |
+
and r as its first row. If r is not given, ``r == conjugate(c)`` is
|
607 |
+
assumed.
|
608 |
+
|
609 |
+
Parameters
|
610 |
+
----------
|
611 |
+
c_or_cr : array_like or tuple of (array_like, array_like)
|
612 |
+
The vector ``c``, or a tuple of arrays (``c``, ``r``). Whatever the
|
613 |
+
actual shape of ``c``, it will be converted to a 1-D array. If not
|
614 |
+
supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
|
615 |
+
real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
|
616 |
+
of the Toeplitz matrix is ``[c[0], r[1:]]``. Whatever the actual shape
|
617 |
+
of ``r``, it will be converted to a 1-D array.
|
618 |
+
b : (M,) or (M, K) array_like
|
619 |
+
Right-hand side in ``T x = b``.
|
620 |
+
check_finite : bool, optional
|
621 |
+
Whether to check that the input matrices contain only finite numbers.
|
622 |
+
Disabling may give a performance gain, but may result in problems
|
623 |
+
(result entirely NaNs) if the inputs do contain infinities or NaNs.
|
624 |
+
|
625 |
+
Returns
|
626 |
+
-------
|
627 |
+
x : (M,) or (M, K) ndarray
|
628 |
+
The solution to the system ``T x = b``. Shape of return matches shape
|
629 |
+
of `b`.
|
630 |
+
|
631 |
+
See Also
|
632 |
+
--------
|
633 |
+
toeplitz : Toeplitz matrix
|
634 |
+
|
635 |
+
Notes
|
636 |
+
-----
|
637 |
+
The solution is computed using Levinson-Durbin recursion, which is faster
|
638 |
+
than generic least-squares methods, but can be less numerically stable.
|
639 |
+
|
640 |
+
Examples
|
641 |
+
--------
|
642 |
+
Solve the Toeplitz system T x = b, where::
|
643 |
+
|
644 |
+
[ 1 -1 -2 -3] [1]
|
645 |
+
T = [ 3 1 -1 -2] b = [2]
|
646 |
+
[ 6 3 1 -1] [2]
|
647 |
+
[10 6 3 1] [5]
|
648 |
+
|
649 |
+
To specify the Toeplitz matrix, only the first column and the first
|
650 |
+
row are needed.
|
651 |
+
|
652 |
+
>>> import numpy as np
|
653 |
+
>>> c = np.array([1, 3, 6, 10]) # First column of T
|
654 |
+
>>> r = np.array([1, -1, -2, -3]) # First row of T
|
655 |
+
>>> b = np.array([1, 2, 2, 5])
|
656 |
+
|
657 |
+
>>> from scipy.linalg import solve_toeplitz, toeplitz
|
658 |
+
>>> x = solve_toeplitz((c, r), b)
|
659 |
+
>>> x
|
660 |
+
array([ 1.66666667, -1. , -2.66666667, 2.33333333])
|
661 |
+
|
662 |
+
Check the result by creating the full Toeplitz matrix and
|
663 |
+
multiplying it by `x`. We should get `b`.
|
664 |
+
|
665 |
+
>>> T = toeplitz(c, r)
|
666 |
+
>>> T.dot(x)
|
667 |
+
array([ 1., 2., 2., 5.])
|
668 |
+
|
669 |
+
"""
|
670 |
+
# If numerical stability of this algorithm is a problem, a future
|
671 |
+
# developer might consider implementing other O(N^2) Toeplitz solvers,
|
672 |
+
# such as GKO (https://www.jstor.org/stable/2153371) or Bareiss.
|
673 |
+
|
674 |
+
r, c, b, dtype, b_shape = _validate_args_for_toeplitz_ops(
|
675 |
+
c_or_cr, b, check_finite, keep_b_shape=True)
|
676 |
+
|
677 |
+
# Form a 1-D array of values to be used in the matrix, containing a
|
678 |
+
# reversed copy of r[1:], followed by c.
|
679 |
+
vals = np.concatenate((r[-1:0:-1], c))
|
680 |
+
if b is None:
|
681 |
+
raise ValueError('illegal value, `b` is a required argument')
|
682 |
+
|
683 |
+
if b.ndim == 1:
|
684 |
+
x, _ = levinson(vals, np.ascontiguousarray(b))
|
685 |
+
else:
|
686 |
+
x = np.column_stack([levinson(vals, np.ascontiguousarray(b[:, i]))[0]
|
687 |
+
for i in range(b.shape[1])])
|
688 |
+
x = x.reshape(*b_shape)
|
689 |
+
|
690 |
+
return x
|
691 |
+
|
692 |
+
|
693 |
+
def _get_axis_len(aname, a, axis):
|
694 |
+
ax = axis
|
695 |
+
if ax < 0:
|
696 |
+
ax += a.ndim
|
697 |
+
if 0 <= ax < a.ndim:
|
698 |
+
return a.shape[ax]
|
699 |
+
raise ValueError(f"'{aname}axis' entry is out of bounds")
|
700 |
+
|
701 |
+
|
702 |
+
def solve_circulant(c, b, singular='raise', tol=None,
|
703 |
+
caxis=-1, baxis=0, outaxis=0):
|
704 |
+
"""Solve C x = b for x, where C is a circulant matrix.
|
705 |
+
|
706 |
+
`C` is the circulant matrix associated with the vector `c`.
|
707 |
+
|
708 |
+
The system is solved by doing division in Fourier space. The
|
709 |
+
calculation is::
|
710 |
+
|
711 |
+
x = ifft(fft(b) / fft(c))
|
712 |
+
|
713 |
+
where `fft` and `ifft` are the fast Fourier transform and its inverse,
|
714 |
+
respectively. For a large vector `c`, this is *much* faster than
|
715 |
+
solving the system with the full circulant matrix.
|
716 |
+
|
717 |
+
Parameters
|
718 |
+
----------
|
719 |
+
c : array_like
|
720 |
+
The coefficients of the circulant matrix.
|
721 |
+
b : array_like
|
722 |
+
Right-hand side matrix in ``a x = b``.
|
723 |
+
singular : str, optional
|
724 |
+
This argument controls how a near singular circulant matrix is
|
725 |
+
handled. If `singular` is "raise" and the circulant matrix is
|
726 |
+
near singular, a `LinAlgError` is raised. If `singular` is
|
727 |
+
"lstsq", the least squares solution is returned. Default is "raise".
|
728 |
+
tol : float, optional
|
729 |
+
If any eigenvalue of the circulant matrix has an absolute value
|
730 |
+
that is less than or equal to `tol`, the matrix is considered to be
|
731 |
+
near singular. If not given, `tol` is set to::
|
732 |
+
|
733 |
+
tol = abs_eigs.max() * abs_eigs.size * np.finfo(np.float64).eps
|
734 |
+
|
735 |
+
where `abs_eigs` is the array of absolute values of the eigenvalues
|
736 |
+
of the circulant matrix.
|
737 |
+
caxis : int
|
738 |
+
When `c` has dimension greater than 1, it is viewed as a collection
|
739 |
+
of circulant vectors. In this case, `caxis` is the axis of `c` that
|
740 |
+
holds the vectors of circulant coefficients.
|
741 |
+
baxis : int
|
742 |
+
When `b` has dimension greater than 1, it is viewed as a collection
|
743 |
+
of vectors. In this case, `baxis` is the axis of `b` that holds the
|
744 |
+
right-hand side vectors.
|
745 |
+
outaxis : int
|
746 |
+
When `c` or `b` are multidimensional, the value returned by
|
747 |
+
`solve_circulant` is multidimensional. In this case, `outaxis` is
|
748 |
+
the axis of the result that holds the solution vectors.
|
749 |
+
|
750 |
+
Returns
|
751 |
+
-------
|
752 |
+
x : ndarray
|
753 |
+
Solution to the system ``C x = b``.
|
754 |
+
|
755 |
+
Raises
|
756 |
+
------
|
757 |
+
LinAlgError
|
758 |
+
If the circulant matrix associated with `c` is near singular.
|
759 |
+
|
760 |
+
See Also
|
761 |
+
--------
|
762 |
+
circulant : circulant matrix
|
763 |
+
|
764 |
+
Notes
|
765 |
+
-----
|
766 |
+
For a 1-D vector `c` with length `m`, and an array `b`
|
767 |
+
with shape ``(m, ...)``,
|
768 |
+
|
769 |
+
solve_circulant(c, b)
|
770 |
+
|
771 |
+
returns the same result as
|
772 |
+
|
773 |
+
solve(circulant(c), b)
|
774 |
+
|
775 |
+
where `solve` and `circulant` are from `scipy.linalg`.
|
776 |
+
|
777 |
+
.. versionadded:: 0.16.0
|
778 |
+
|
779 |
+
Examples
|
780 |
+
--------
|
781 |
+
>>> import numpy as np
|
782 |
+
>>> from scipy.linalg import solve_circulant, solve, circulant, lstsq
|
783 |
+
|
784 |
+
>>> c = np.array([2, 2, 4])
|
785 |
+
>>> b = np.array([1, 2, 3])
|
786 |
+
>>> solve_circulant(c, b)
|
787 |
+
array([ 0.75, -0.25, 0.25])
|
788 |
+
|
789 |
+
Compare that result to solving the system with `scipy.linalg.solve`:
|
790 |
+
|
791 |
+
>>> solve(circulant(c), b)
|
792 |
+
array([ 0.75, -0.25, 0.25])
|
793 |
+
|
794 |
+
A singular example:
|
795 |
+
|
796 |
+
>>> c = np.array([1, 1, 0, 0])
|
797 |
+
>>> b = np.array([1, 2, 3, 4])
|
798 |
+
|
799 |
+
Calling ``solve_circulant(c, b)`` will raise a `LinAlgError`. For the
|
800 |
+
least square solution, use the option ``singular='lstsq'``:
|
801 |
+
|
802 |
+
>>> solve_circulant(c, b, singular='lstsq')
|
803 |
+
array([ 0.25, 1.25, 2.25, 1.25])
|
804 |
+
|
805 |
+
Compare to `scipy.linalg.lstsq`:
|
806 |
+
|
807 |
+
>>> x, resid, rnk, s = lstsq(circulant(c), b)
|
808 |
+
>>> x
|
809 |
+
array([ 0.25, 1.25, 2.25, 1.25])
|
810 |
+
|
811 |
+
A broadcasting example:
|
812 |
+
|
813 |
+
Suppose we have the vectors of two circulant matrices stored in an array
|
814 |
+
with shape (2, 5), and three `b` vectors stored in an array with shape
|
815 |
+
(3, 5). For example,
|
816 |
+
|
817 |
+
>>> c = np.array([[1.5, 2, 3, 0, 0], [1, 1, 4, 3, 2]])
|
818 |
+
>>> b = np.arange(15).reshape(-1, 5)
|
819 |
+
|
820 |
+
We want to solve all combinations of circulant matrices and `b` vectors,
|
821 |
+
with the result stored in an array with shape (2, 3, 5). When we
|
822 |
+
disregard the axes of `c` and `b` that hold the vectors of coefficients,
|
823 |
+
the shapes of the collections are (2,) and (3,), respectively, which are
|
824 |
+
not compatible for broadcasting. To have a broadcast result with shape
|
825 |
+
(2, 3), we add a trivial dimension to `c`: ``c[:, np.newaxis, :]`` has
|
826 |
+
shape (2, 1, 5). The last dimension holds the coefficients of the
|
827 |
+
circulant matrices, so when we call `solve_circulant`, we can use the
|
828 |
+
default ``caxis=-1``. The coefficients of the `b` vectors are in the last
|
829 |
+
dimension of the array `b`, so we use ``baxis=-1``. If we use the
|
830 |
+
default `outaxis`, the result will have shape (5, 2, 3), so we'll use
|
831 |
+
``outaxis=-1`` to put the solution vectors in the last dimension.
|
832 |
+
|
833 |
+
>>> x = solve_circulant(c[:, np.newaxis, :], b, baxis=-1, outaxis=-1)
|
834 |
+
>>> x.shape
|
835 |
+
(2, 3, 5)
|
836 |
+
>>> np.set_printoptions(precision=3) # For compact output of numbers.
|
837 |
+
>>> x
|
838 |
+
array([[[-0.118, 0.22 , 1.277, -0.142, 0.302],
|
839 |
+
[ 0.651, 0.989, 2.046, 0.627, 1.072],
|
840 |
+
[ 1.42 , 1.758, 2.816, 1.396, 1.841]],
|
841 |
+
[[ 0.401, 0.304, 0.694, -0.867, 0.377],
|
842 |
+
[ 0.856, 0.758, 1.149, -0.412, 0.831],
|
843 |
+
[ 1.31 , 1.213, 1.603, 0.042, 1.286]]])
|
844 |
+
|
845 |
+
Check by solving one pair of `c` and `b` vectors (cf. ``x[1, 1, :]``):
|
846 |
+
|
847 |
+
>>> solve_circulant(c[1], b[1, :])
|
848 |
+
array([ 0.856, 0.758, 1.149, -0.412, 0.831])
|
849 |
+
|
850 |
+
"""
|
851 |
+
c = np.atleast_1d(c)
|
852 |
+
nc = _get_axis_len("c", c, caxis)
|
853 |
+
b = np.atleast_1d(b)
|
854 |
+
nb = _get_axis_len("b", b, baxis)
|
855 |
+
if nc != nb:
|
856 |
+
raise ValueError(f'Shapes of c {c.shape} and b {b.shape} are incompatible')
|
857 |
+
|
858 |
+
fc = np.fft.fft(np.moveaxis(c, caxis, -1), axis=-1)
|
859 |
+
abs_fc = np.abs(fc)
|
860 |
+
if tol is None:
|
861 |
+
# This is the same tolerance as used in np.linalg.matrix_rank.
|
862 |
+
tol = abs_fc.max(axis=-1) * nc * np.finfo(np.float64).eps
|
863 |
+
if tol.shape != ():
|
864 |
+
tol.shape = tol.shape + (1,)
|
865 |
+
else:
|
866 |
+
tol = np.atleast_1d(tol)
|
867 |
+
|
868 |
+
near_zeros = abs_fc <= tol
|
869 |
+
is_near_singular = np.any(near_zeros)
|
870 |
+
if is_near_singular:
|
871 |
+
if singular == 'raise':
|
872 |
+
raise LinAlgError("near singular circulant matrix.")
|
873 |
+
else:
|
874 |
+
# Replace the small values with 1 to avoid errors in the
|
875 |
+
# division fb/fc below.
|
876 |
+
fc[near_zeros] = 1
|
877 |
+
|
878 |
+
fb = np.fft.fft(np.moveaxis(b, baxis, -1), axis=-1)
|
879 |
+
|
880 |
+
q = fb / fc
|
881 |
+
|
882 |
+
if is_near_singular:
|
883 |
+
# `near_zeros` is a boolean array, same shape as `c`, that is
|
884 |
+
# True where `fc` is (near) zero. `q` is the broadcasted result
|
885 |
+
# of fb / fc, so to set the values of `q` to 0 where `fc` is near
|
886 |
+
# zero, we use a mask that is the broadcast result of an array
|
887 |
+
# of True values shaped like `b` with `near_zeros`.
|
888 |
+
mask = np.ones_like(b, dtype=bool) & near_zeros
|
889 |
+
q[mask] = 0
|
890 |
+
|
891 |
+
x = np.fft.ifft(q, axis=-1)
|
892 |
+
if not (np.iscomplexobj(c) or np.iscomplexobj(b)):
|
893 |
+
x = x.real
|
894 |
+
if outaxis != -1:
|
895 |
+
x = np.moveaxis(x, -1, outaxis)
|
896 |
+
return x
|
897 |
+
|
898 |
+
|
899 |
+
# matrix inversion
|
900 |
+
def inv(a, overwrite_a=False, check_finite=True):
|
901 |
+
"""
|
902 |
+
Compute the inverse of a matrix.
|
903 |
+
|
904 |
+
Parameters
|
905 |
+
----------
|
906 |
+
a : array_like
|
907 |
+
Square matrix to be inverted.
|
908 |
+
overwrite_a : bool, optional
|
909 |
+
Discard data in `a` (may improve performance). Default is False.
|
910 |
+
check_finite : bool, optional
|
911 |
+
Whether to check that the input matrix contains only finite numbers.
|
912 |
+
Disabling may give a performance gain, but may result in problems
|
913 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
914 |
+
|
915 |
+
Returns
|
916 |
+
-------
|
917 |
+
ainv : ndarray
|
918 |
+
Inverse of the matrix `a`.
|
919 |
+
|
920 |
+
Raises
|
921 |
+
------
|
922 |
+
LinAlgError
|
923 |
+
If `a` is singular.
|
924 |
+
ValueError
|
925 |
+
If `a` is not square, or not 2D.
|
926 |
+
|
927 |
+
Examples
|
928 |
+
--------
|
929 |
+
>>> import numpy as np
|
930 |
+
>>> from scipy import linalg
|
931 |
+
>>> a = np.array([[1., 2.], [3., 4.]])
|
932 |
+
>>> linalg.inv(a)
|
933 |
+
array([[-2. , 1. ],
|
934 |
+
[ 1.5, -0.5]])
|
935 |
+
>>> np.dot(a, linalg.inv(a))
|
936 |
+
array([[ 1., 0.],
|
937 |
+
[ 0., 1.]])
|
938 |
+
|
939 |
+
"""
|
940 |
+
a1 = _asarray_validated(a, check_finite=check_finite)
|
941 |
+
if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
|
942 |
+
raise ValueError('expected square matrix')
|
943 |
+
overwrite_a = overwrite_a or _datacopied(a1, a)
|
944 |
+
getrf, getri, getri_lwork = get_lapack_funcs(('getrf', 'getri',
|
945 |
+
'getri_lwork'),
|
946 |
+
(a1,))
|
947 |
+
lu, piv, info = getrf(a1, overwrite_a=overwrite_a)
|
948 |
+
if info == 0:
|
949 |
+
lwork = _compute_lwork(getri_lwork, a1.shape[0])
|
950 |
+
|
951 |
+
# XXX: the following line fixes curious SEGFAULT when
|
952 |
+
# benchmarking 500x500 matrix inverse. This seems to
|
953 |
+
# be a bug in LAPACK ?getri routine because if lwork is
|
954 |
+
# minimal (when using lwork[0] instead of lwork[1]) then
|
955 |
+
# all tests pass. Further investigation is required if
|
956 |
+
# more such SEGFAULTs occur.
|
957 |
+
lwork = int(1.01 * lwork)
|
958 |
+
inv_a, info = getri(lu, piv, lwork=lwork, overwrite_lu=1)
|
959 |
+
if info > 0:
|
960 |
+
raise LinAlgError("singular matrix")
|
961 |
+
if info < 0:
|
962 |
+
raise ValueError('illegal value in %d-th argument of internal '
|
963 |
+
'getrf|getri' % -info)
|
964 |
+
return inv_a
|
965 |
+
|
966 |
+
|
967 |
+
# Determinant
|
968 |
+
|
969 |
+
def det(a, overwrite_a=False, check_finite=True):
|
970 |
+
"""
|
971 |
+
Compute the determinant of a matrix
|
972 |
+
|
973 |
+
The determinant is a scalar that is a function of the associated square
|
974 |
+
matrix coefficients. The determinant value is zero for singular matrices.
|
975 |
+
|
976 |
+
Parameters
|
977 |
+
----------
|
978 |
+
a : (..., M, M) array_like
|
979 |
+
Input array to compute determinants for.
|
980 |
+
overwrite_a : bool, optional
|
981 |
+
Allow overwriting data in a (may enhance performance).
|
982 |
+
check_finite : bool, optional
|
983 |
+
Whether to check that the input matrix contains only finite numbers.
|
984 |
+
Disabling may give a performance gain, but may result in problems
|
985 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
986 |
+
|
987 |
+
Returns
|
988 |
+
-------
|
989 |
+
det : (...) float or complex
|
990 |
+
Determinant of `a`. For stacked arrays, a scalar is returned for each
|
991 |
+
(m, m) slice in the last two dimensions of the input. For example, an
|
992 |
+
input of shape (p, q, m, m) will produce a result of shape (p, q). If
|
993 |
+
all dimensions are 1 a scalar is returned regardless of ndim.
|
994 |
+
|
995 |
+
Notes
|
996 |
+
-----
|
997 |
+
The determinant is computed by performing an LU factorization of the
|
998 |
+
input with LAPACK routine 'getrf', and then calculating the product of
|
999 |
+
diagonal entries of the U factor.
|
1000 |
+
|
1001 |
+
Even the input array is single precision (float32 or complex64), the result
|
1002 |
+
will be returned in double precision (float64 or complex128) to prevent
|
1003 |
+
overflows.
|
1004 |
+
|
1005 |
+
Examples
|
1006 |
+
--------
|
1007 |
+
>>> import numpy as np
|
1008 |
+
>>> from scipy import linalg
|
1009 |
+
>>> a = np.array([[1,2,3], [4,5,6], [7,8,9]]) # A singular matrix
|
1010 |
+
>>> linalg.det(a)
|
1011 |
+
0.0
|
1012 |
+
>>> b = np.array([[0,2,3], [4,5,6], [7,8,9]])
|
1013 |
+
>>> linalg.det(b)
|
1014 |
+
3.0
|
1015 |
+
>>> # An array with the shape (3, 2, 2, 2)
|
1016 |
+
>>> c = np.array([[[[1., 2.], [3., 4.]],
|
1017 |
+
... [[5., 6.], [7., 8.]]],
|
1018 |
+
... [[[9., 10.], [11., 12.]],
|
1019 |
+
... [[13., 14.], [15., 16.]]],
|
1020 |
+
... [[[17., 18.], [19., 20.]],
|
1021 |
+
... [[21., 22.], [23., 24.]]]])
|
1022 |
+
>>> linalg.det(c) # The resulting shape is (3, 2)
|
1023 |
+
array([[-2., -2.],
|
1024 |
+
[-2., -2.],
|
1025 |
+
[-2., -2.]])
|
1026 |
+
>>> linalg.det(c[0, 0]) # Confirm the (0, 0) slice, [[1, 2], [3, 4]]
|
1027 |
+
-2.0
|
1028 |
+
"""
|
1029 |
+
# The goal is to end up with a writable contiguous array to pass to Cython
|
1030 |
+
|
1031 |
+
# First we check and make arrays.
|
1032 |
+
a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a)
|
1033 |
+
if a1.ndim < 2:
|
1034 |
+
raise ValueError('The input array must be at least two-dimensional.')
|
1035 |
+
if a1.shape[-1] != a1.shape[-2]:
|
1036 |
+
raise ValueError('Last 2 dimensions of the array must be square'
|
1037 |
+
f' but received shape {a1.shape}.')
|
1038 |
+
|
1039 |
+
# Also check if dtype is LAPACK compatible
|
1040 |
+
if a1.dtype.char not in 'fdFD':
|
1041 |
+
dtype_char = lapack_cast_dict[a1.dtype.char]
|
1042 |
+
if not dtype_char: # No casting possible
|
1043 |
+
raise TypeError(f'The dtype "{a1.dtype.name}" cannot be cast '
|
1044 |
+
'to float(32, 64) or complex(64, 128).')
|
1045 |
+
|
1046 |
+
a1 = a1.astype(dtype_char[0]) # makes a copy, free to scratch
|
1047 |
+
overwrite_a = True
|
1048 |
+
|
1049 |
+
# Empty array has determinant 1 because math.
|
1050 |
+
if min(*a1.shape) == 0:
|
1051 |
+
if a1.ndim == 2:
|
1052 |
+
return np.float64(1.)
|
1053 |
+
else:
|
1054 |
+
return np.ones(shape=a1.shape[:-2], dtype=np.float64)
|
1055 |
+
|
1056 |
+
# Scalar case
|
1057 |
+
if a1.shape[-2:] == (1, 1):
|
1058 |
+
# Either ndarray with spurious singletons or a single element
|
1059 |
+
if max(*a1.shape) > 1:
|
1060 |
+
temp = np.squeeze(a1)
|
1061 |
+
if a1.dtype.char in 'dD':
|
1062 |
+
return temp
|
1063 |
+
else:
|
1064 |
+
return (temp.astype('d') if a1.dtype.char == 'f' else
|
1065 |
+
temp.astype('D'))
|
1066 |
+
else:
|
1067 |
+
return (np.float64(a1.item()) if a1.dtype.char in 'fd' else
|
1068 |
+
np.complex128(a1.item()))
|
1069 |
+
|
1070 |
+
# Then check overwrite permission
|
1071 |
+
if not _datacopied(a1, a): # "a" still alive through "a1"
|
1072 |
+
if not overwrite_a:
|
1073 |
+
# Data belongs to "a" so make a copy
|
1074 |
+
a1 = a1.copy(order='C')
|
1075 |
+
# else: Do nothing we'll use "a" if possible
|
1076 |
+
# else: a1 has its own data thus free to scratch
|
1077 |
+
|
1078 |
+
# Then layout checks, might happen that overwrite is allowed but original
|
1079 |
+
# array was read-only or non-C-contiguous.
|
1080 |
+
if not (a1.flags['C_CONTIGUOUS'] and a1.flags['WRITEABLE']):
|
1081 |
+
a1 = a1.copy(order='C')
|
1082 |
+
|
1083 |
+
if a1.ndim == 2:
|
1084 |
+
det = find_det_from_lu(a1)
|
1085 |
+
# Convert float, complex to to NumPy scalars
|
1086 |
+
return (np.float64(det) if np.isrealobj(det) else np.complex128(det))
|
1087 |
+
|
1088 |
+
# loop over the stacked array, and avoid overflows for single precision
|
1089 |
+
# Cf. np.linalg.det(np.diag([1e+38, 1e+38]).astype(np.float32))
|
1090 |
+
dtype_char = a1.dtype.char
|
1091 |
+
if dtype_char in 'fF':
|
1092 |
+
dtype_char = 'd' if dtype_char.islower() else 'D'
|
1093 |
+
|
1094 |
+
det = np.empty(a1.shape[:-2], dtype=dtype_char)
|
1095 |
+
for ind in product(*[range(x) for x in a1.shape[:-2]]):
|
1096 |
+
det[ind] = find_det_from_lu(a1[ind])
|
1097 |
+
return det
|
1098 |
+
|
1099 |
+
|
1100 |
+
# Linear Least Squares
|
1101 |
+
def lstsq(a, b, cond=None, overwrite_a=False, overwrite_b=False,
|
1102 |
+
check_finite=True, lapack_driver=None):
|
1103 |
+
"""
|
1104 |
+
Compute least-squares solution to equation Ax = b.
|
1105 |
+
|
1106 |
+
Compute a vector x such that the 2-norm ``|b - A x|`` is minimized.
|
1107 |
+
|
1108 |
+
Parameters
|
1109 |
+
----------
|
1110 |
+
a : (M, N) array_like
|
1111 |
+
Left-hand side array
|
1112 |
+
b : (M,) or (M, K) array_like
|
1113 |
+
Right hand side array
|
1114 |
+
cond : float, optional
|
1115 |
+
Cutoff for 'small' singular values; used to determine effective
|
1116 |
+
rank of a. Singular values smaller than
|
1117 |
+
``cond * largest_singular_value`` are considered zero.
|
1118 |
+
overwrite_a : bool, optional
|
1119 |
+
Discard data in `a` (may enhance performance). Default is False.
|
1120 |
+
overwrite_b : bool, optional
|
1121 |
+
Discard data in `b` (may enhance performance). Default is False.
|
1122 |
+
check_finite : bool, optional
|
1123 |
+
Whether to check that the input matrices contain only finite numbers.
|
1124 |
+
Disabling may give a performance gain, but may result in problems
|
1125 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
1126 |
+
lapack_driver : str, optional
|
1127 |
+
Which LAPACK driver is used to solve the least-squares problem.
|
1128 |
+
Options are ``'gelsd'``, ``'gelsy'``, ``'gelss'``. Default
|
1129 |
+
(``'gelsd'``) is a good choice. However, ``'gelsy'`` can be slightly
|
1130 |
+
faster on many problems. ``'gelss'`` was used historically. It is
|
1131 |
+
generally slow but uses less memory.
|
1132 |
+
|
1133 |
+
.. versionadded:: 0.17.0
|
1134 |
+
|
1135 |
+
Returns
|
1136 |
+
-------
|
1137 |
+
x : (N,) or (N, K) ndarray
|
1138 |
+
Least-squares solution.
|
1139 |
+
residues : (K,) ndarray or float
|
1140 |
+
Square of the 2-norm for each column in ``b - a x``, if ``M > N`` and
|
1141 |
+
``rank(A) == n`` (returns a scalar if ``b`` is 1-D). Otherwise a
|
1142 |
+
(0,)-shaped array is returned.
|
1143 |
+
rank : int
|
1144 |
+
Effective rank of `a`.
|
1145 |
+
s : (min(M, N),) ndarray or None
|
1146 |
+
Singular values of `a`. The condition number of ``a`` is
|
1147 |
+
``s[0] / s[-1]``.
|
1148 |
+
|
1149 |
+
Raises
|
1150 |
+
------
|
1151 |
+
LinAlgError
|
1152 |
+
If computation does not converge.
|
1153 |
+
|
1154 |
+
ValueError
|
1155 |
+
When parameters are not compatible.
|
1156 |
+
|
1157 |
+
See Also
|
1158 |
+
--------
|
1159 |
+
scipy.optimize.nnls : linear least squares with non-negativity constraint
|
1160 |
+
|
1161 |
+
Notes
|
1162 |
+
-----
|
1163 |
+
When ``'gelsy'`` is used as a driver, `residues` is set to a (0,)-shaped
|
1164 |
+
array and `s` is always ``None``.
|
1165 |
+
|
1166 |
+
Examples
|
1167 |
+
--------
|
1168 |
+
>>> import numpy as np
|
1169 |
+
>>> from scipy.linalg import lstsq
|
1170 |
+
>>> import matplotlib.pyplot as plt
|
1171 |
+
|
1172 |
+
Suppose we have the following data:
|
1173 |
+
|
1174 |
+
>>> x = np.array([1, 2.5, 3.5, 4, 5, 7, 8.5])
|
1175 |
+
>>> y = np.array([0.3, 1.1, 1.5, 2.0, 3.2, 6.6, 8.6])
|
1176 |
+
|
1177 |
+
We want to fit a quadratic polynomial of the form ``y = a + b*x**2``
|
1178 |
+
to this data. We first form the "design matrix" M, with a constant
|
1179 |
+
column of 1s and a column containing ``x**2``:
|
1180 |
+
|
1181 |
+
>>> M = x[:, np.newaxis]**[0, 2]
|
1182 |
+
>>> M
|
1183 |
+
array([[ 1. , 1. ],
|
1184 |
+
[ 1. , 6.25],
|
1185 |
+
[ 1. , 12.25],
|
1186 |
+
[ 1. , 16. ],
|
1187 |
+
[ 1. , 25. ],
|
1188 |
+
[ 1. , 49. ],
|
1189 |
+
[ 1. , 72.25]])
|
1190 |
+
|
1191 |
+
We want to find the least-squares solution to ``M.dot(p) = y``,
|
1192 |
+
where ``p`` is a vector with length 2 that holds the parameters
|
1193 |
+
``a`` and ``b``.
|
1194 |
+
|
1195 |
+
>>> p, res, rnk, s = lstsq(M, y)
|
1196 |
+
>>> p
|
1197 |
+
array([ 0.20925829, 0.12013861])
|
1198 |
+
|
1199 |
+
Plot the data and the fitted curve.
|
1200 |
+
|
1201 |
+
>>> plt.plot(x, y, 'o', label='data')
|
1202 |
+
>>> xx = np.linspace(0, 9, 101)
|
1203 |
+
>>> yy = p[0] + p[1]*xx**2
|
1204 |
+
>>> plt.plot(xx, yy, label='least squares fit, $y = a + bx^2$')
|
1205 |
+
>>> plt.xlabel('x')
|
1206 |
+
>>> plt.ylabel('y')
|
1207 |
+
>>> plt.legend(framealpha=1, shadow=True)
|
1208 |
+
>>> plt.grid(alpha=0.25)
|
1209 |
+
>>> plt.show()
|
1210 |
+
|
1211 |
+
"""
|
1212 |
+
a1 = _asarray_validated(a, check_finite=check_finite)
|
1213 |
+
b1 = _asarray_validated(b, check_finite=check_finite)
|
1214 |
+
if len(a1.shape) != 2:
|
1215 |
+
raise ValueError('Input array a should be 2D')
|
1216 |
+
m, n = a1.shape
|
1217 |
+
if len(b1.shape) == 2:
|
1218 |
+
nrhs = b1.shape[1]
|
1219 |
+
else:
|
1220 |
+
nrhs = 1
|
1221 |
+
if m != b1.shape[0]:
|
1222 |
+
raise ValueError('Shape mismatch: a and b should have the same number'
|
1223 |
+
f' of rows ({m} != {b1.shape[0]}).')
|
1224 |
+
if m == 0 or n == 0: # Zero-sized problem, confuses LAPACK
|
1225 |
+
x = np.zeros((n,) + b1.shape[1:], dtype=np.common_type(a1, b1))
|
1226 |
+
if n == 0:
|
1227 |
+
residues = np.linalg.norm(b1, axis=0)**2
|
1228 |
+
else:
|
1229 |
+
residues = np.empty((0,))
|
1230 |
+
return x, residues, 0, np.empty((0,))
|
1231 |
+
|
1232 |
+
driver = lapack_driver
|
1233 |
+
if driver is None:
|
1234 |
+
driver = lstsq.default_lapack_driver
|
1235 |
+
if driver not in ('gelsd', 'gelsy', 'gelss'):
|
1236 |
+
raise ValueError('LAPACK driver "%s" is not found' % driver)
|
1237 |
+
|
1238 |
+
lapack_func, lapack_lwork = get_lapack_funcs((driver,
|
1239 |
+
'%s_lwork' % driver),
|
1240 |
+
(a1, b1))
|
1241 |
+
real_data = True if (lapack_func.dtype.kind == 'f') else False
|
1242 |
+
|
1243 |
+
if m < n:
|
1244 |
+
# need to extend b matrix as it will be filled with
|
1245 |
+
# a larger solution matrix
|
1246 |
+
if len(b1.shape) == 2:
|
1247 |
+
b2 = np.zeros((n, nrhs), dtype=lapack_func.dtype)
|
1248 |
+
b2[:m, :] = b1
|
1249 |
+
else:
|
1250 |
+
b2 = np.zeros(n, dtype=lapack_func.dtype)
|
1251 |
+
b2[:m] = b1
|
1252 |
+
b1 = b2
|
1253 |
+
|
1254 |
+
overwrite_a = overwrite_a or _datacopied(a1, a)
|
1255 |
+
overwrite_b = overwrite_b or _datacopied(b1, b)
|
1256 |
+
|
1257 |
+
if cond is None:
|
1258 |
+
cond = np.finfo(lapack_func.dtype).eps
|
1259 |
+
|
1260 |
+
if driver in ('gelss', 'gelsd'):
|
1261 |
+
if driver == 'gelss':
|
1262 |
+
lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
|
1263 |
+
v, x, s, rank, work, info = lapack_func(a1, b1, cond, lwork,
|
1264 |
+
overwrite_a=overwrite_a,
|
1265 |
+
overwrite_b=overwrite_b)
|
1266 |
+
|
1267 |
+
elif driver == 'gelsd':
|
1268 |
+
if real_data:
|
1269 |
+
lwork, iwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
|
1270 |
+
x, s, rank, info = lapack_func(a1, b1, lwork,
|
1271 |
+
iwork, cond, False, False)
|
1272 |
+
else: # complex data
|
1273 |
+
lwork, rwork, iwork = _compute_lwork(lapack_lwork, m, n,
|
1274 |
+
nrhs, cond)
|
1275 |
+
x, s, rank, info = lapack_func(a1, b1, lwork, rwork, iwork,
|
1276 |
+
cond, False, False)
|
1277 |
+
if info > 0:
|
1278 |
+
raise LinAlgError("SVD did not converge in Linear Least Squares")
|
1279 |
+
if info < 0:
|
1280 |
+
raise ValueError('illegal value in %d-th argument of internal %s'
|
1281 |
+
% (-info, lapack_driver))
|
1282 |
+
resids = np.asarray([], dtype=x.dtype)
|
1283 |
+
if m > n:
|
1284 |
+
x1 = x[:n]
|
1285 |
+
if rank == n:
|
1286 |
+
resids = np.sum(np.abs(x[n:])**2, axis=0)
|
1287 |
+
x = x1
|
1288 |
+
return x, resids, rank, s
|
1289 |
+
|
1290 |
+
elif driver == 'gelsy':
|
1291 |
+
lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
|
1292 |
+
jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
|
1293 |
+
v, x, j, rank, info = lapack_func(a1, b1, jptv, cond,
|
1294 |
+
lwork, False, False)
|
1295 |
+
if info < 0:
|
1296 |
+
raise ValueError("illegal value in %d-th argument of internal "
|
1297 |
+
"gelsy" % -info)
|
1298 |
+
if m > n:
|
1299 |
+
x1 = x[:n]
|
1300 |
+
x = x1
|
1301 |
+
return x, np.array([], x.dtype), rank, None
|
1302 |
+
|
1303 |
+
|
1304 |
+
lstsq.default_lapack_driver = 'gelsd'
|
1305 |
+
|
1306 |
+
|
1307 |
+
@_deprecate_positional_args(version="1.14")
|
1308 |
+
def pinv(a, *, atol=None, rtol=None, return_rank=False, check_finite=True,
|
1309 |
+
cond=_NoValue, rcond=_NoValue):
|
1310 |
+
"""
|
1311 |
+
Compute the (Moore-Penrose) pseudo-inverse of a matrix.
|
1312 |
+
|
1313 |
+
Calculate a generalized inverse of a matrix using its
|
1314 |
+
singular-value decomposition ``U @ S @ V`` in the economy mode and picking
|
1315 |
+
up only the columns/rows that are associated with significant singular
|
1316 |
+
values.
|
1317 |
+
|
1318 |
+
If ``s`` is the maximum singular value of ``a``, then the
|
1319 |
+
significance cut-off value is determined by ``atol + rtol * s``. Any
|
1320 |
+
singular value below this value is assumed insignificant.
|
1321 |
+
|
1322 |
+
Parameters
|
1323 |
+
----------
|
1324 |
+
a : (M, N) array_like
|
1325 |
+
Matrix to be pseudo-inverted.
|
1326 |
+
atol : float, optional
|
1327 |
+
Absolute threshold term, default value is 0.
|
1328 |
+
|
1329 |
+
.. versionadded:: 1.7.0
|
1330 |
+
|
1331 |
+
rtol : float, optional
|
1332 |
+
Relative threshold term, default value is ``max(M, N) * eps`` where
|
1333 |
+
``eps`` is the machine precision value of the datatype of ``a``.
|
1334 |
+
|
1335 |
+
.. versionadded:: 1.7.0
|
1336 |
+
|
1337 |
+
return_rank : bool, optional
|
1338 |
+
If True, return the effective rank of the matrix.
|
1339 |
+
check_finite : bool, optional
|
1340 |
+
Whether to check that the input matrix contains only finite numbers.
|
1341 |
+
Disabling may give a performance gain, but may result in problems
|
1342 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
1343 |
+
cond, rcond : float, optional
|
1344 |
+
In older versions, these values were meant to be used as ``atol`` with
|
1345 |
+
``rtol=0``. If both were given ``rcond`` overwrote ``cond`` and hence
|
1346 |
+
the code was not correct. Thus using these are strongly discouraged and
|
1347 |
+
the tolerances above are recommended instead. In fact, if provided,
|
1348 |
+
atol, rtol takes precedence over these keywords.
|
1349 |
+
|
1350 |
+
.. deprecated:: 1.7.0
|
1351 |
+
Deprecated in favor of ``rtol`` and ``atol`` parameters above and
|
1352 |
+
will be removed in SciPy 1.14.0.
|
1353 |
+
|
1354 |
+
.. versionchanged:: 1.3.0
|
1355 |
+
Previously the default cutoff value was just ``eps*f`` where ``f``
|
1356 |
+
was ``1e3`` for single precision and ``1e6`` for double precision.
|
1357 |
+
|
1358 |
+
Returns
|
1359 |
+
-------
|
1360 |
+
B : (N, M) ndarray
|
1361 |
+
The pseudo-inverse of matrix `a`.
|
1362 |
+
rank : int
|
1363 |
+
The effective rank of the matrix. Returned if `return_rank` is True.
|
1364 |
+
|
1365 |
+
Raises
|
1366 |
+
------
|
1367 |
+
LinAlgError
|
1368 |
+
If SVD computation does not converge.
|
1369 |
+
|
1370 |
+
See Also
|
1371 |
+
--------
|
1372 |
+
pinvh : Moore-Penrose pseudoinverse of a hermitian matrix.
|
1373 |
+
|
1374 |
+
Notes
|
1375 |
+
-----
|
1376 |
+
If ``A`` is invertible then the Moore-Penrose pseudoinverse is exactly
|
1377 |
+
the inverse of ``A`` [1]_. If ``A`` is not invertible then the
|
1378 |
+
Moore-Penrose pseudoinverse computes the ``x`` solution to ``Ax = b`` such
|
1379 |
+
that ``||Ax - b||`` is minimized [1]_.
|
1380 |
+
|
1381 |
+
References
|
1382 |
+
----------
|
1383 |
+
.. [1] Penrose, R. (1956). On best approximate solutions of linear matrix
|
1384 |
+
equations. Mathematical Proceedings of the Cambridge Philosophical
|
1385 |
+
Society, 52(1), 17-19. doi:10.1017/S0305004100030929
|
1386 |
+
|
1387 |
+
Examples
|
1388 |
+
--------
|
1389 |
+
|
1390 |
+
Given an ``m x n`` matrix ``A`` and an ``n x m`` matrix ``B`` the four
|
1391 |
+
Moore-Penrose conditions are:
|
1392 |
+
|
1393 |
+
1. ``ABA = A`` (``B`` is a generalized inverse of ``A``),
|
1394 |
+
2. ``BAB = B`` (``A`` is a generalized inverse of ``B``),
|
1395 |
+
3. ``(AB)* = AB`` (``AB`` is hermitian),
|
1396 |
+
4. ``(BA)* = BA`` (``BA`` is hermitian) [1]_.
|
1397 |
+
|
1398 |
+
Here, ``A*`` denotes the conjugate transpose. The Moore-Penrose
|
1399 |
+
pseudoinverse is a unique ``B`` that satisfies all four of these
|
1400 |
+
conditions and exists for any ``A``. Note that, unlike the standard
|
1401 |
+
matrix inverse, ``A`` does not have to be a square matrix or have
|
1402 |
+
linearly independent columns/rows.
|
1403 |
+
|
1404 |
+
As an example, we can calculate the Moore-Penrose pseudoinverse of a
|
1405 |
+
random non-square matrix and verify it satisfies the four conditions.
|
1406 |
+
|
1407 |
+
>>> import numpy as np
|
1408 |
+
>>> from scipy import linalg
|
1409 |
+
>>> rng = np.random.default_rng()
|
1410 |
+
>>> A = rng.standard_normal((9, 6))
|
1411 |
+
>>> B = linalg.pinv(A)
|
1412 |
+
>>> np.allclose(A @ B @ A, A) # Condition 1
|
1413 |
+
True
|
1414 |
+
>>> np.allclose(B @ A @ B, B) # Condition 2
|
1415 |
+
True
|
1416 |
+
>>> np.allclose((A @ B).conj().T, A @ B) # Condition 3
|
1417 |
+
True
|
1418 |
+
>>> np.allclose((B @ A).conj().T, B @ A) # Condition 4
|
1419 |
+
True
|
1420 |
+
|
1421 |
+
"""
|
1422 |
+
a = _asarray_validated(a, check_finite=check_finite)
|
1423 |
+
u, s, vh = _decomp_svd.svd(a, full_matrices=False, check_finite=False)
|
1424 |
+
t = u.dtype.char.lower()
|
1425 |
+
maxS = np.max(s)
|
1426 |
+
|
1427 |
+
if rcond is not _NoValue or cond is not _NoValue:
|
1428 |
+
warn('Use of the "cond" and "rcond" keywords are deprecated and '
|
1429 |
+
'will be removed in SciPy 1.14.0. Use "atol" and '
|
1430 |
+
'"rtol" keywords instead', DeprecationWarning, stacklevel=2)
|
1431 |
+
|
1432 |
+
# backwards compatible only atol and rtol are both missing
|
1433 |
+
if ((rcond not in (_NoValue, None) or cond not in (_NoValue, None))
|
1434 |
+
and (atol is None) and (rtol is None)):
|
1435 |
+
atol = rcond if rcond not in (_NoValue, None) else cond
|
1436 |
+
rtol = 0.
|
1437 |
+
|
1438 |
+
atol = 0. if atol is None else atol
|
1439 |
+
rtol = max(a.shape) * np.finfo(t).eps if (rtol is None) else rtol
|
1440 |
+
|
1441 |
+
if (atol < 0.) or (rtol < 0.):
|
1442 |
+
raise ValueError("atol and rtol values must be positive.")
|
1443 |
+
|
1444 |
+
val = atol + maxS * rtol
|
1445 |
+
rank = np.sum(s > val)
|
1446 |
+
|
1447 |
+
u = u[:, :rank]
|
1448 |
+
u /= s[:rank]
|
1449 |
+
B = (u @ vh[:rank]).conj().T
|
1450 |
+
|
1451 |
+
if return_rank:
|
1452 |
+
return B, rank
|
1453 |
+
else:
|
1454 |
+
return B
|
1455 |
+
|
1456 |
+
|
1457 |
+
def pinvh(a, atol=None, rtol=None, lower=True, return_rank=False,
|
1458 |
+
check_finite=True):
|
1459 |
+
"""
|
1460 |
+
Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix.
|
1461 |
+
|
1462 |
+
Calculate a generalized inverse of a complex Hermitian/real symmetric
|
1463 |
+
matrix using its eigenvalue decomposition and including all eigenvalues
|
1464 |
+
with 'large' absolute value.
|
1465 |
+
|
1466 |
+
Parameters
|
1467 |
+
----------
|
1468 |
+
a : (N, N) array_like
|
1469 |
+
Real symmetric or complex hermetian matrix to be pseudo-inverted
|
1470 |
+
|
1471 |
+
atol : float, optional
|
1472 |
+
Absolute threshold term, default value is 0.
|
1473 |
+
|
1474 |
+
.. versionadded:: 1.7.0
|
1475 |
+
|
1476 |
+
rtol : float, optional
|
1477 |
+
Relative threshold term, default value is ``N * eps`` where
|
1478 |
+
``eps`` is the machine precision value of the datatype of ``a``.
|
1479 |
+
|
1480 |
+
.. versionadded:: 1.7.0
|
1481 |
+
|
1482 |
+
lower : bool, optional
|
1483 |
+
Whether the pertinent array data is taken from the lower or upper
|
1484 |
+
triangle of `a`. (Default: lower)
|
1485 |
+
return_rank : bool, optional
|
1486 |
+
If True, return the effective rank of the matrix.
|
1487 |
+
check_finite : bool, optional
|
1488 |
+
Whether to check that the input matrix contains only finite numbers.
|
1489 |
+
Disabling may give a performance gain, but may result in problems
|
1490 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
1491 |
+
|
1492 |
+
Returns
|
1493 |
+
-------
|
1494 |
+
B : (N, N) ndarray
|
1495 |
+
The pseudo-inverse of matrix `a`.
|
1496 |
+
rank : int
|
1497 |
+
The effective rank of the matrix. Returned if `return_rank` is True.
|
1498 |
+
|
1499 |
+
Raises
|
1500 |
+
------
|
1501 |
+
LinAlgError
|
1502 |
+
If eigenvalue algorithm does not converge.
|
1503 |
+
|
1504 |
+
See Also
|
1505 |
+
--------
|
1506 |
+
pinv : Moore-Penrose pseudoinverse of a matrix.
|
1507 |
+
|
1508 |
+
Examples
|
1509 |
+
--------
|
1510 |
+
|
1511 |
+
For a more detailed example see `pinv`.
|
1512 |
+
|
1513 |
+
>>> import numpy as np
|
1514 |
+
>>> from scipy.linalg import pinvh
|
1515 |
+
>>> rng = np.random.default_rng()
|
1516 |
+
>>> a = rng.standard_normal((9, 6))
|
1517 |
+
>>> a = np.dot(a, a.T)
|
1518 |
+
>>> B = pinvh(a)
|
1519 |
+
>>> np.allclose(a, a @ B @ a)
|
1520 |
+
True
|
1521 |
+
>>> np.allclose(B, B @ a @ B)
|
1522 |
+
True
|
1523 |
+
|
1524 |
+
"""
|
1525 |
+
a = _asarray_validated(a, check_finite=check_finite)
|
1526 |
+
s, u = _decomp.eigh(a, lower=lower, check_finite=False)
|
1527 |
+
t = u.dtype.char.lower()
|
1528 |
+
maxS = np.max(np.abs(s))
|
1529 |
+
|
1530 |
+
atol = 0. if atol is None else atol
|
1531 |
+
rtol = max(a.shape) * np.finfo(t).eps if (rtol is None) else rtol
|
1532 |
+
|
1533 |
+
if (atol < 0.) or (rtol < 0.):
|
1534 |
+
raise ValueError("atol and rtol values must be positive.")
|
1535 |
+
|
1536 |
+
val = atol + maxS * rtol
|
1537 |
+
above_cutoff = (abs(s) > val)
|
1538 |
+
|
1539 |
+
psigma_diag = 1.0 / s[above_cutoff]
|
1540 |
+
u = u[:, above_cutoff]
|
1541 |
+
|
1542 |
+
B = (u * psigma_diag) @ u.conj().T
|
1543 |
+
|
1544 |
+
if return_rank:
|
1545 |
+
return B, len(psigma_diag)
|
1546 |
+
else:
|
1547 |
+
return B
|
1548 |
+
|
1549 |
+
|
1550 |
+
def matrix_balance(A, permute=True, scale=True, separate=False,
|
1551 |
+
overwrite_a=False):
|
1552 |
+
"""
|
1553 |
+
Compute a diagonal similarity transformation for row/column balancing.
|
1554 |
+
|
1555 |
+
The balancing tries to equalize the row and column 1-norms by applying
|
1556 |
+
a similarity transformation such that the magnitude variation of the
|
1557 |
+
matrix entries is reflected to the scaling matrices.
|
1558 |
+
|
1559 |
+
Moreover, if enabled, the matrix is first permuted to isolate the upper
|
1560 |
+
triangular parts of the matrix and, again if scaling is also enabled,
|
1561 |
+
only the remaining subblocks are subjected to scaling.
|
1562 |
+
|
1563 |
+
The balanced matrix satisfies the following equality
|
1564 |
+
|
1565 |
+
.. math::
|
1566 |
+
|
1567 |
+
B = T^{-1} A T
|
1568 |
+
|
1569 |
+
The scaling coefficients are approximated to the nearest power of 2
|
1570 |
+
to avoid round-off errors.
|
1571 |
+
|
1572 |
+
Parameters
|
1573 |
+
----------
|
1574 |
+
A : (n, n) array_like
|
1575 |
+
Square data matrix for the balancing.
|
1576 |
+
permute : bool, optional
|
1577 |
+
The selector to define whether permutation of A is also performed
|
1578 |
+
prior to scaling.
|
1579 |
+
scale : bool, optional
|
1580 |
+
The selector to turn on and off the scaling. If False, the matrix
|
1581 |
+
will not be scaled.
|
1582 |
+
separate : bool, optional
|
1583 |
+
This switches from returning a full matrix of the transformation
|
1584 |
+
to a tuple of two separate 1-D permutation and scaling arrays.
|
1585 |
+
overwrite_a : bool, optional
|
1586 |
+
This is passed to xGEBAL directly. Essentially, overwrites the result
|
1587 |
+
to the data. It might increase the space efficiency. See LAPACK manual
|
1588 |
+
for details. This is False by default.
|
1589 |
+
|
1590 |
+
Returns
|
1591 |
+
-------
|
1592 |
+
B : (n, n) ndarray
|
1593 |
+
Balanced matrix
|
1594 |
+
T : (n, n) ndarray
|
1595 |
+
A possibly permuted diagonal matrix whose nonzero entries are
|
1596 |
+
integer powers of 2 to avoid numerical truncation errors.
|
1597 |
+
scale, perm : (n,) ndarray
|
1598 |
+
If ``separate`` keyword is set to True then instead of the array
|
1599 |
+
``T`` above, the scaling and the permutation vectors are given
|
1600 |
+
separately as a tuple without allocating the full array ``T``.
|
1601 |
+
|
1602 |
+
Notes
|
1603 |
+
-----
|
1604 |
+
This algorithm is particularly useful for eigenvalue and matrix
|
1605 |
+
decompositions and in many cases it is already called by various
|
1606 |
+
LAPACK routines.
|
1607 |
+
|
1608 |
+
The algorithm is based on the well-known technique of [1]_ and has
|
1609 |
+
been modified to account for special cases. See [2]_ for details
|
1610 |
+
which have been implemented since LAPACK v3.5.0. Before this version
|
1611 |
+
there are corner cases where balancing can actually worsen the
|
1612 |
+
conditioning. See [3]_ for such examples.
|
1613 |
+
|
1614 |
+
The code is a wrapper around LAPACK's xGEBAL routine family for matrix
|
1615 |
+
balancing.
|
1616 |
+
|
1617 |
+
.. versionadded:: 0.19.0
|
1618 |
+
|
1619 |
+
References
|
1620 |
+
----------
|
1621 |
+
.. [1] B.N. Parlett and C. Reinsch, "Balancing a Matrix for
|
1622 |
+
Calculation of Eigenvalues and Eigenvectors", Numerische Mathematik,
|
1623 |
+
Vol.13(4), 1969, :doi:`10.1007/BF02165404`
|
1624 |
+
.. [2] R. James, J. Langou, B.R. Lowery, "On matrix balancing and
|
1625 |
+
eigenvector computation", 2014, :arxiv:`1401.5766`
|
1626 |
+
.. [3] D.S. Watkins. A case where balancing is harmful.
|
1627 |
+
Electron. Trans. Numer. Anal, Vol.23, 2006.
|
1628 |
+
|
1629 |
+
Examples
|
1630 |
+
--------
|
1631 |
+
>>> import numpy as np
|
1632 |
+
>>> from scipy import linalg
|
1633 |
+
>>> x = np.array([[1,2,0], [9,1,0.01], [1,2,10*np.pi]])
|
1634 |
+
|
1635 |
+
>>> y, permscale = linalg.matrix_balance(x)
|
1636 |
+
>>> np.abs(x).sum(axis=0) / np.abs(x).sum(axis=1)
|
1637 |
+
array([ 3.66666667, 0.4995005 , 0.91312162])
|
1638 |
+
|
1639 |
+
>>> np.abs(y).sum(axis=0) / np.abs(y).sum(axis=1)
|
1640 |
+
array([ 1.2 , 1.27041742, 0.92658316]) # may vary
|
1641 |
+
|
1642 |
+
>>> permscale # only powers of 2 (0.5 == 2^(-1))
|
1643 |
+
array([[ 0.5, 0. , 0. ], # may vary
|
1644 |
+
[ 0. , 1. , 0. ],
|
1645 |
+
[ 0. , 0. , 1. ]])
|
1646 |
+
|
1647 |
+
"""
|
1648 |
+
|
1649 |
+
A = np.atleast_2d(_asarray_validated(A, check_finite=True))
|
1650 |
+
|
1651 |
+
if not np.equal(*A.shape):
|
1652 |
+
raise ValueError('The data matrix for balancing should be square.')
|
1653 |
+
|
1654 |
+
gebal = get_lapack_funcs(('gebal'), (A,))
|
1655 |
+
B, lo, hi, ps, info = gebal(A, scale=scale, permute=permute,
|
1656 |
+
overwrite_a=overwrite_a)
|
1657 |
+
|
1658 |
+
if info < 0:
|
1659 |
+
raise ValueError('xGEBAL exited with the internal error '
|
1660 |
+
f'"illegal value in argument number {-info}.". See '
|
1661 |
+
'LAPACK documentation for the xGEBAL error codes.')
|
1662 |
+
|
1663 |
+
# Separate the permutations from the scalings and then convert to int
|
1664 |
+
scaling = np.ones_like(ps, dtype=float)
|
1665 |
+
scaling[lo:hi+1] = ps[lo:hi+1]
|
1666 |
+
|
1667 |
+
# gebal uses 1-indexing
|
1668 |
+
ps = ps.astype(int, copy=False) - 1
|
1669 |
+
n = A.shape[0]
|
1670 |
+
perm = np.arange(n)
|
1671 |
+
|
1672 |
+
# LAPACK permutes with the ordering n --> hi, then 0--> lo
|
1673 |
+
if hi < n:
|
1674 |
+
for ind, x in enumerate(ps[hi+1:][::-1], 1):
|
1675 |
+
if n-ind == x:
|
1676 |
+
continue
|
1677 |
+
perm[[x, n-ind]] = perm[[n-ind, x]]
|
1678 |
+
|
1679 |
+
if lo > 0:
|
1680 |
+
for ind, x in enumerate(ps[:lo]):
|
1681 |
+
if ind == x:
|
1682 |
+
continue
|
1683 |
+
perm[[x, ind]] = perm[[ind, x]]
|
1684 |
+
|
1685 |
+
if separate:
|
1686 |
+
return B, (scaling, perm)
|
1687 |
+
|
1688 |
+
# get the inverse permutation
|
1689 |
+
iperm = np.empty_like(perm)
|
1690 |
+
iperm[perm] = np.arange(n)
|
1691 |
+
|
1692 |
+
return B, np.diag(scaling)[iperm, :]
|
1693 |
+
|
1694 |
+
|
1695 |
+
def _validate_args_for_toeplitz_ops(c_or_cr, b, check_finite, keep_b_shape,
|
1696 |
+
enforce_square=True):
|
1697 |
+
"""Validate arguments and format inputs for toeplitz functions
|
1698 |
+
|
1699 |
+
Parameters
|
1700 |
+
----------
|
1701 |
+
c_or_cr : array_like or tuple of (array_like, array_like)
|
1702 |
+
The vector ``c``, or a tuple of arrays (``c``, ``r``). Whatever the
|
1703 |
+
actual shape of ``c``, it will be converted to a 1-D array. If not
|
1704 |
+
supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
|
1705 |
+
real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
|
1706 |
+
of the Toeplitz matrix is ``[c[0], r[1:]]``. Whatever the actual shape
|
1707 |
+
of ``r``, it will be converted to a 1-D array.
|
1708 |
+
b : (M,) or (M, K) array_like
|
1709 |
+
Right-hand side in ``T x = b``.
|
1710 |
+
check_finite : bool
|
1711 |
+
Whether to check that the input matrices contain only finite numbers.
|
1712 |
+
Disabling may give a performance gain, but may result in problems
|
1713 |
+
(result entirely NaNs) if the inputs do contain infinities or NaNs.
|
1714 |
+
keep_b_shape : bool
|
1715 |
+
Whether to convert a (M,) dimensional b into a (M, 1) dimensional
|
1716 |
+
matrix.
|
1717 |
+
enforce_square : bool, optional
|
1718 |
+
If True (default), this verifies that the Toeplitz matrix is square.
|
1719 |
+
|
1720 |
+
Returns
|
1721 |
+
-------
|
1722 |
+
r : array
|
1723 |
+
1d array corresponding to the first row of the Toeplitz matrix.
|
1724 |
+
c: array
|
1725 |
+
1d array corresponding to the first column of the Toeplitz matrix.
|
1726 |
+
b: array
|
1727 |
+
(M,), (M, 1) or (M, K) dimensional array, post validation,
|
1728 |
+
corresponding to ``b``.
|
1729 |
+
dtype: numpy datatype
|
1730 |
+
``dtype`` stores the datatype of ``r``, ``c`` and ``b``. If any of
|
1731 |
+
``r``, ``c`` or ``b`` are complex, ``dtype`` is ``np.complex128``,
|
1732 |
+
otherwise, it is ``np.float``.
|
1733 |
+
b_shape: tuple
|
1734 |
+
Shape of ``b`` after passing it through ``_asarray_validated``.
|
1735 |
+
|
1736 |
+
"""
|
1737 |
+
|
1738 |
+
if isinstance(c_or_cr, tuple):
|
1739 |
+
c, r = c_or_cr
|
1740 |
+
c = _asarray_validated(c, check_finite=check_finite).ravel()
|
1741 |
+
r = _asarray_validated(r, check_finite=check_finite).ravel()
|
1742 |
+
else:
|
1743 |
+
c = _asarray_validated(c_or_cr, check_finite=check_finite).ravel()
|
1744 |
+
r = c.conjugate()
|
1745 |
+
|
1746 |
+
if b is None:
|
1747 |
+
raise ValueError('`b` must be an array, not None.')
|
1748 |
+
|
1749 |
+
b = _asarray_validated(b, check_finite=check_finite)
|
1750 |
+
b_shape = b.shape
|
1751 |
+
|
1752 |
+
is_not_square = r.shape[0] != c.shape[0]
|
1753 |
+
if (enforce_square and is_not_square) or b.shape[0] != r.shape[0]:
|
1754 |
+
raise ValueError('Incompatible dimensions.')
|
1755 |
+
|
1756 |
+
is_cmplx = np.iscomplexobj(r) or np.iscomplexobj(c) or np.iscomplexobj(b)
|
1757 |
+
dtype = np.complex128 if is_cmplx else np.float64
|
1758 |
+
r, c, b = (np.asarray(i, dtype=dtype) for i in (r, c, b))
|
1759 |
+
|
1760 |
+
if b.ndim == 1 and not keep_b_shape:
|
1761 |
+
b = b.reshape(-1, 1)
|
1762 |
+
elif b.ndim != 1:
|
1763 |
+
b = b.reshape(b.shape[0], -1)
|
1764 |
+
|
1765 |
+
return r, c, b, dtype, b_shape
|
1766 |
+
|
1767 |
+
|
1768 |
+
def matmul_toeplitz(c_or_cr, x, check_finite=False, workers=None):
|
1769 |
+
"""Efficient Toeplitz Matrix-Matrix Multiplication using FFT
|
1770 |
+
|
1771 |
+
This function returns the matrix multiplication between a Toeplitz
|
1772 |
+
matrix and a dense matrix.
|
1773 |
+
|
1774 |
+
The Toeplitz matrix has constant diagonals, with c as its first column
|
1775 |
+
and r as its first row. If r is not given, ``r == conjugate(c)`` is
|
1776 |
+
assumed.
|
1777 |
+
|
1778 |
+
Parameters
|
1779 |
+
----------
|
1780 |
+
c_or_cr : array_like or tuple of (array_like, array_like)
|
1781 |
+
The vector ``c``, or a tuple of arrays (``c``, ``r``). Whatever the
|
1782 |
+
actual shape of ``c``, it will be converted to a 1-D array. If not
|
1783 |
+
supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
|
1784 |
+
real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
|
1785 |
+
of the Toeplitz matrix is ``[c[0], r[1:]]``. Whatever the actual shape
|
1786 |
+
of ``r``, it will be converted to a 1-D array.
|
1787 |
+
x : (M,) or (M, K) array_like
|
1788 |
+
Matrix with which to multiply.
|
1789 |
+
check_finite : bool, optional
|
1790 |
+
Whether to check that the input matrices contain only finite numbers.
|
1791 |
+
Disabling may give a performance gain, but may result in problems
|
1792 |
+
(result entirely NaNs) if the inputs do contain infinities or NaNs.
|
1793 |
+
workers : int, optional
|
1794 |
+
To pass to scipy.fft.fft and ifft. Maximum number of workers to use
|
1795 |
+
for parallel computation. If negative, the value wraps around from
|
1796 |
+
``os.cpu_count()``. See scipy.fft.fft for more details.
|
1797 |
+
|
1798 |
+
Returns
|
1799 |
+
-------
|
1800 |
+
T @ x : (M,) or (M, K) ndarray
|
1801 |
+
The result of the matrix multiplication ``T @ x``. Shape of return
|
1802 |
+
matches shape of `x`.
|
1803 |
+
|
1804 |
+
See Also
|
1805 |
+
--------
|
1806 |
+
toeplitz : Toeplitz matrix
|
1807 |
+
solve_toeplitz : Solve a Toeplitz system using Levinson Recursion
|
1808 |
+
|
1809 |
+
Notes
|
1810 |
+
-----
|
1811 |
+
The Toeplitz matrix is embedded in a circulant matrix and the FFT is used
|
1812 |
+
to efficiently calculate the matrix-matrix product.
|
1813 |
+
|
1814 |
+
Because the computation is based on the FFT, integer inputs will
|
1815 |
+
result in floating point outputs. This is unlike NumPy's `matmul`,
|
1816 |
+
which preserves the data type of the input.
|
1817 |
+
|
1818 |
+
This is partly based on the implementation that can be found in [1]_,
|
1819 |
+
licensed under the MIT license. More information about the method can be
|
1820 |
+
found in reference [2]_. References [3]_ and [4]_ have more reference
|
1821 |
+
implementations in Python.
|
1822 |
+
|
1823 |
+
.. versionadded:: 1.6.0
|
1824 |
+
|
1825 |
+
References
|
1826 |
+
----------
|
1827 |
+
.. [1] Jacob R Gardner, Geoff Pleiss, David Bindel, Kilian
|
1828 |
+
Q Weinberger, Andrew Gordon Wilson, "GPyTorch: Blackbox Matrix-Matrix
|
1829 |
+
Gaussian Process Inference with GPU Acceleration" with contributions
|
1830 |
+
from Max Balandat and Ruihan Wu. Available online:
|
1831 |
+
https://github.com/cornellius-gp/gpytorch
|
1832 |
+
|
1833 |
+
.. [2] J. Demmel, P. Koev, and X. Li, "A Brief Survey of Direct Linear
|
1834 |
+
Solvers". In Z. Bai, J. Demmel, J. Dongarra, A. Ruhe, and H. van der
|
1835 |
+
Vorst, editors. Templates for the Solution of Algebraic Eigenvalue
|
1836 |
+
Problems: A Practical Guide. SIAM, Philadelphia, 2000. Available at:
|
1837 |
+
http://www.netlib.org/utk/people/JackDongarra/etemplates/node384.html
|
1838 |
+
|
1839 |
+
.. [3] R. Scheibler, E. Bezzam, I. Dokmanic, Pyroomacoustics: A Python
|
1840 |
+
package for audio room simulations and array processing algorithms,
|
1841 |
+
Proc. IEEE ICASSP, Calgary, CA, 2018.
|
1842 |
+
https://github.com/LCAV/pyroomacoustics/blob/pypi-release/
|
1843 |
+
pyroomacoustics/adaptive/util.py
|
1844 |
+
|
1845 |
+
.. [4] Marano S, Edwards B, Ferrari G and Fah D (2017), "Fitting
|
1846 |
+
Earthquake Spectra: Colored Noise and Incomplete Data", Bulletin of
|
1847 |
+
the Seismological Society of America., January, 2017. Vol. 107(1),
|
1848 |
+
pp. 276-291.
|
1849 |
+
|
1850 |
+
Examples
|
1851 |
+
--------
|
1852 |
+
Multiply the Toeplitz matrix T with matrix x::
|
1853 |
+
|
1854 |
+
[ 1 -1 -2 -3] [1 10]
|
1855 |
+
T = [ 3 1 -1 -2] x = [2 11]
|
1856 |
+
[ 6 3 1 -1] [2 11]
|
1857 |
+
[10 6 3 1] [5 19]
|
1858 |
+
|
1859 |
+
To specify the Toeplitz matrix, only the first column and the first
|
1860 |
+
row are needed.
|
1861 |
+
|
1862 |
+
>>> import numpy as np
|
1863 |
+
>>> c = np.array([1, 3, 6, 10]) # First column of T
|
1864 |
+
>>> r = np.array([1, -1, -2, -3]) # First row of T
|
1865 |
+
>>> x = np.array([[1, 10], [2, 11], [2, 11], [5, 19]])
|
1866 |
+
|
1867 |
+
>>> from scipy.linalg import toeplitz, matmul_toeplitz
|
1868 |
+
>>> matmul_toeplitz((c, r), x)
|
1869 |
+
array([[-20., -80.],
|
1870 |
+
[ -7., -8.],
|
1871 |
+
[ 9., 85.],
|
1872 |
+
[ 33., 218.]])
|
1873 |
+
|
1874 |
+
Check the result by creating the full Toeplitz matrix and
|
1875 |
+
multiplying it by ``x``.
|
1876 |
+
|
1877 |
+
>>> toeplitz(c, r) @ x
|
1878 |
+
array([[-20, -80],
|
1879 |
+
[ -7, -8],
|
1880 |
+
[ 9, 85],
|
1881 |
+
[ 33, 218]])
|
1882 |
+
|
1883 |
+
The full matrix is never formed explicitly, so this routine
|
1884 |
+
is suitable for very large Toeplitz matrices.
|
1885 |
+
|
1886 |
+
>>> n = 1000000
|
1887 |
+
>>> matmul_toeplitz([1] + [0]*(n-1), np.ones(n))
|
1888 |
+
array([1., 1., 1., ..., 1., 1., 1.])
|
1889 |
+
|
1890 |
+
"""
|
1891 |
+
|
1892 |
+
from ..fft import fft, ifft, rfft, irfft
|
1893 |
+
|
1894 |
+
r, c, x, dtype, x_shape = _validate_args_for_toeplitz_ops(
|
1895 |
+
c_or_cr, x, check_finite, keep_b_shape=False, enforce_square=False)
|
1896 |
+
n, m = x.shape
|
1897 |
+
|
1898 |
+
T_nrows = len(c)
|
1899 |
+
T_ncols = len(r)
|
1900 |
+
p = T_nrows + T_ncols - 1 # equivalent to len(embedded_col)
|
1901 |
+
|
1902 |
+
embedded_col = np.concatenate((c, r[-1:0:-1]))
|
1903 |
+
|
1904 |
+
if np.iscomplexobj(embedded_col) or np.iscomplexobj(x):
|
1905 |
+
fft_mat = fft(embedded_col, axis=0, workers=workers).reshape(-1, 1)
|
1906 |
+
fft_x = fft(x, n=p, axis=0, workers=workers)
|
1907 |
+
|
1908 |
+
mat_times_x = ifft(fft_mat*fft_x, axis=0,
|
1909 |
+
workers=workers)[:T_nrows, :]
|
1910 |
+
else:
|
1911 |
+
# Real inputs; using rfft is faster
|
1912 |
+
fft_mat = rfft(embedded_col, axis=0, workers=workers).reshape(-1, 1)
|
1913 |
+
fft_x = rfft(x, n=p, axis=0, workers=workers)
|
1914 |
+
|
1915 |
+
mat_times_x = irfft(fft_mat*fft_x, axis=0,
|
1916 |
+
workers=workers, n=p)[:T_nrows, :]
|
1917 |
+
|
1918 |
+
return_shape = (T_nrows,) if len(x_shape) == 1 else (T_nrows, m)
|
1919 |
+
return mat_times_x.reshape(*return_shape)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from numpy.typing import NDArray
|
2 |
+
from typing import Any
|
3 |
+
|
4 |
+
def bandwidth(a: NDArray[Any]) -> tuple[int, int]: ...
|
5 |
+
|
6 |
+
def issymmetric(
|
7 |
+
a: NDArray[Any],
|
8 |
+
atol: None | float = ...,
|
9 |
+
rtol: None | float = ...,
|
10 |
+
) -> bool: ...
|
11 |
+
|
12 |
+
def ishermitian(
|
13 |
+
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
from collections.abc import Iterable
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
from scipy._lib._util import _asarray_validated
|
5 |
+
from scipy.linalg import block_diag, LinAlgError
|
6 |
+
from .lapack import _compute_lwork, get_lapack_funcs
|
7 |
+
|
8 |
+
__all__ = ['cossin']
|
9 |
+
|
10 |
+
|
11 |
+
def cossin(X, p=None, q=None, separate=False,
|
12 |
+
swap_sign=False, compute_u=True, compute_vh=True):
|
13 |
+
"""
|
14 |
+
Compute the cosine-sine (CS) decomposition of an orthogonal/unitary matrix.
|
15 |
+
|
16 |
+
X is an ``(m, m)`` orthogonal/unitary matrix, partitioned as the following
|
17 |
+
where upper left block has the shape of ``(p, q)``::
|
18 |
+
|
19 |
+
┌ ┐
|
20 |
+
│ I 0 0 │ 0 0 0 │
|
21 |
+
┌ ┐ ┌ ┐│ 0 C 0 │ 0 -S 0 │┌ ┐*
|
22 |
+
│ X11 │ X12 │ │ U1 │ ││ 0 0 0 │ 0 0 -I ││ V1 │ │
|
23 |
+
│ ────┼──── │ = │────┼────││─────────┼─────────││────┼────│
|
24 |
+
│ X21 │ X22 │ │ │ U2 ││ 0 0 0 │ I 0 0 ││ │ V2 │
|
25 |
+
└ ┘ └ ┘│ 0 S 0 │ 0 C 0 │└ ┘
|
26 |
+
│ 0 0 I │ 0 0 0 │
|
27 |
+
└ ┘
|
28 |
+
|
29 |
+
``U1``, ``U2``, ``V1``, ``V2`` are square orthogonal/unitary matrices of
|
30 |
+
dimensions ``(p,p)``, ``(m-p,m-p)``, ``(q,q)``, and ``(m-q,m-q)``
|
31 |
+
respectively, and ``C`` and ``S`` are ``(r, r)`` nonnegative diagonal
|
32 |
+
matrices satisfying ``C^2 + S^2 = I`` where ``r = min(p, m-p, q, m-q)``.
|
33 |
+
|
34 |
+
Moreover, the rank of the identity matrices are ``min(p, q) - r``,
|
35 |
+
``min(p, m - q) - r``, ``min(m - p, q) - r``, and ``min(m - p, m - q) - r``
|
36 |
+
respectively.
|
37 |
+
|
38 |
+
X can be supplied either by itself and block specifications p, q or its
|
39 |
+
subblocks in an iterable from which the shapes would be derived. See the
|
40 |
+
examples below.
|
41 |
+
|
42 |
+
Parameters
|
43 |
+
----------
|
44 |
+
X : array_like, iterable
|
45 |
+
complex unitary or real orthogonal matrix to be decomposed, or iterable
|
46 |
+
of subblocks ``X11``, ``X12``, ``X21``, ``X22``, when ``p``, ``q`` are
|
47 |
+
omitted.
|
48 |
+
p : int, optional
|
49 |
+
Number of rows of the upper left block ``X11``, used only when X is
|
50 |
+
given as an array.
|
51 |
+
q : int, optional
|
52 |
+
Number of columns of the upper left block ``X11``, used only when X is
|
53 |
+
given as an array.
|
54 |
+
separate : bool, optional
|
55 |
+
if ``True``, the low level components are returned instead of the
|
56 |
+
matrix factors, i.e. ``(u1,u2)``, ``theta``, ``(v1h,v2h)`` instead of
|
57 |
+
``u``, ``cs``, ``vh``.
|
58 |
+
swap_sign : bool, optional
|
59 |
+
if ``True``, the ``-S``, ``-I`` block will be the bottom left,
|
60 |
+
otherwise (by default) they will be in the upper right block.
|
61 |
+
compute_u : bool, optional
|
62 |
+
if ``False``, ``u`` won't be computed and an empty array is returned.
|
63 |
+
compute_vh : bool, optional
|
64 |
+
if ``False``, ``vh`` won't be computed and an empty array is returned.
|
65 |
+
|
66 |
+
Returns
|
67 |
+
-------
|
68 |
+
u : ndarray
|
69 |
+
When ``compute_u=True``, contains the block diagonal orthogonal/unitary
|
70 |
+
matrix consisting of the blocks ``U1`` (``p`` x ``p``) and ``U2``
|
71 |
+
(``m-p`` x ``m-p``) orthogonal/unitary matrices. If ``separate=True``,
|
72 |
+
this contains the tuple of ``(U1, U2)``.
|
73 |
+
cs : ndarray
|
74 |
+
The cosine-sine factor with the structure described above.
|
75 |
+
If ``separate=True``, this contains the ``theta`` array containing the
|
76 |
+
angles in radians.
|
77 |
+
vh : ndarray
|
78 |
+
When ``compute_vh=True`, contains the block diagonal orthogonal/unitary
|
79 |
+
matrix consisting of the blocks ``V1H`` (``q`` x ``q``) and ``V2H``
|
80 |
+
(``m-q`` x ``m-q``) orthogonal/unitary matrices. If ``separate=True``,
|
81 |
+
this contains the tuple of ``(V1H, V2H)``.
|
82 |
+
|
83 |
+
References
|
84 |
+
----------
|
85 |
+
.. [1] Brian D. Sutton. Computing the complete CS decomposition. Numer.
|
86 |
+
Algorithms, 50(1):33-65, 2009.
|
87 |
+
|
88 |
+
Examples
|
89 |
+
--------
|
90 |
+
>>> import numpy as np
|
91 |
+
>>> from scipy.linalg import cossin
|
92 |
+
>>> from scipy.stats import unitary_group
|
93 |
+
>>> x = unitary_group.rvs(4)
|
94 |
+
>>> u, cs, vdh = cossin(x, p=2, q=2)
|
95 |
+
>>> np.allclose(x, u @ cs @ vdh)
|
96 |
+
True
|
97 |
+
|
98 |
+
Same can be entered via subblocks without the need of ``p`` and ``q``. Also
|
99 |
+
let's skip the computation of ``u``
|
100 |
+
|
101 |
+
>>> ue, cs, vdh = cossin((x[:2, :2], x[:2, 2:], x[2:, :2], x[2:, 2:]),
|
102 |
+
... compute_u=False)
|
103 |
+
>>> print(ue)
|
104 |
+
[]
|
105 |
+
>>> np.allclose(x, u @ cs @ vdh)
|
106 |
+
True
|
107 |
+
|
108 |
+
"""
|
109 |
+
|
110 |
+
if p or q:
|
111 |
+
p = 1 if p is None else int(p)
|
112 |
+
q = 1 if q is None else int(q)
|
113 |
+
X = _asarray_validated(X, check_finite=True)
|
114 |
+
if not np.equal(*X.shape):
|
115 |
+
raise ValueError("Cosine Sine decomposition only supports square"
|
116 |
+
f" matrices, got {X.shape}")
|
117 |
+
m = X.shape[0]
|
118 |
+
if p >= m or p <= 0:
|
119 |
+
raise ValueError(f"invalid p={p}, 0<p<{X.shape[0]} must hold")
|
120 |
+
if q >= m or q <= 0:
|
121 |
+
raise ValueError(f"invalid q={q}, 0<q<{X.shape[0]} must hold")
|
122 |
+
|
123 |
+
x11, x12, x21, x22 = X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:]
|
124 |
+
elif not isinstance(X, Iterable):
|
125 |
+
raise ValueError("When p and q are None, X must be an Iterable"
|
126 |
+
" containing the subblocks of X")
|
127 |
+
else:
|
128 |
+
if len(X) != 4:
|
129 |
+
raise ValueError("When p and q are None, exactly four arrays"
|
130 |
+
f" should be in X, got {len(X)}")
|
131 |
+
|
132 |
+
x11, x12, x21, x22 = (np.atleast_2d(x) for x in X)
|
133 |
+
for name, block in zip(["x11", "x12", "x21", "x22"],
|
134 |
+
[x11, x12, x21, x22]):
|
135 |
+
if block.shape[1] == 0:
|
136 |
+
raise ValueError(f"{name} can't be empty")
|
137 |
+
p, q = x11.shape
|
138 |
+
mmp, mmq = x22.shape
|
139 |
+
|
140 |
+
if x12.shape != (p, mmq):
|
141 |
+
raise ValueError(f"Invalid x12 dimensions: desired {(p, mmq)}, "
|
142 |
+
f"got {x12.shape}")
|
143 |
+
|
144 |
+
if x21.shape != (mmp, q):
|
145 |
+
raise ValueError(f"Invalid x21 dimensions: desired {(mmp, q)}, "
|
146 |
+
f"got {x21.shape}")
|
147 |
+
|
148 |
+
if p + mmp != q + mmq:
|
149 |
+
raise ValueError("The subblocks have compatible sizes but "
|
150 |
+
"don't form a square array (instead they form a"
|
151 |
+
" {}x{} array). This might be due to missing "
|
152 |
+
"p, q arguments.".format(p + mmp, q + mmq))
|
153 |
+
|
154 |
+
m = p + mmp
|
155 |
+
|
156 |
+
cplx = any([np.iscomplexobj(x) for x in [x11, x12, x21, x22]])
|
157 |
+
driver = "uncsd" if cplx else "orcsd"
|
158 |
+
csd, csd_lwork = get_lapack_funcs([driver, driver + "_lwork"],
|
159 |
+
[x11, x12, x21, x22])
|
160 |
+
lwork = _compute_lwork(csd_lwork, m=m, p=p, q=q)
|
161 |
+
lwork_args = ({'lwork': lwork[0], 'lrwork': lwork[1]} if cplx else
|
162 |
+
{'lwork': lwork})
|
163 |
+
*_, theta, u1, u2, v1h, v2h, info = csd(x11=x11, x12=x12, x21=x21, x22=x22,
|
164 |
+
compute_u1=compute_u,
|
165 |
+
compute_u2=compute_u,
|
166 |
+
compute_v1t=compute_vh,
|
167 |
+
compute_v2t=compute_vh,
|
168 |
+
trans=False, signs=swap_sign,
|
169 |
+
**lwork_args)
|
170 |
+
|
171 |
+
method_name = csd.typecode + driver
|
172 |
+
if info < 0:
|
173 |
+
raise ValueError(f'illegal value in argument {-info} '
|
174 |
+
f'of internal {method_name}')
|
175 |
+
if info > 0:
|
176 |
+
raise LinAlgError(f"{method_name} did not converge: {info}")
|
177 |
+
|
178 |
+
if separate:
|
179 |
+
return (u1, u2), theta, (v1h, v2h)
|
180 |
+
|
181 |
+
U = block_diag(u1, u2)
|
182 |
+
VDH = block_diag(v1h, v2h)
|
183 |
+
|
184 |
+
# Construct the middle factor CS
|
185 |
+
c = np.diag(np.cos(theta))
|
186 |
+
s = np.diag(np.sin(theta))
|
187 |
+
r = min(p, q, m - p, m - q)
|
188 |
+
n11 = min(p, q) - r
|
189 |
+
n12 = min(p, m - q) - r
|
190 |
+
n21 = min(m - p, q) - r
|
191 |
+
n22 = min(m - p, m - q) - r
|
192 |
+
Id = np.eye(np.max([n11, n12, n21, n22, r]), dtype=theta.dtype)
|
193 |
+
CS = np.zeros((m, m), dtype=theta.dtype)
|
194 |
+
|
195 |
+
CS[:n11, :n11] = Id[:n11, :n11]
|
196 |
+
|
197 |
+
xs = n11 + r
|
198 |
+
xe = n11 + r + n12
|
199 |
+
ys = n11 + n21 + n22 + 2 * r
|
200 |
+
ye = n11 + n21 + n22 + 2 * r + n12
|
201 |
+
CS[xs: xe, ys:ye] = Id[:n12, :n12] if swap_sign else -Id[:n12, :n12]
|
202 |
+
|
203 |
+
xs = p + n22 + r
|
204 |
+
xe = p + n22 + r + + n21
|
205 |
+
ys = n11 + r
|
206 |
+
ye = n11 + r + n21
|
207 |
+
CS[xs:xe, ys:ye] = -Id[:n21, :n21] if swap_sign else Id[:n21, :n21]
|
208 |
+
|
209 |
+
CS[p:p + n22, q:q + n22] = Id[:n22, :n22]
|
210 |
+
CS[n11:n11 + r, n11:n11 + r] = c
|
211 |
+
CS[p + n22:p + n22 + r, r + n21 + n22:2 * r + n21 + n22] = c
|
212 |
+
|
213 |
+
xs = n11
|
214 |
+
xe = n11 + r
|
215 |
+
ys = n11 + n21 + n22 + r
|
216 |
+
ye = n11 + n21 + n22 + 2 * r
|
217 |
+
CS[xs:xe, ys:ye] = s if swap_sign else -s
|
218 |
+
|
219 |
+
CS[p + n22:p + n22 + r, n11:n11 + r] = -s if swap_sign else s
|
220 |
+
|
221 |
+
return U, CS, VDH
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py
ADDED
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""LU decomposition functions."""
|
2 |
+
|
3 |
+
from warnings import warn
|
4 |
+
|
5 |
+
from numpy import asarray, asarray_chkfinite
|
6 |
+
import numpy as np
|
7 |
+
from itertools import product
|
8 |
+
|
9 |
+
# Local imports
|
10 |
+
from ._misc import _datacopied, LinAlgWarning
|
11 |
+
from .lapack import get_lapack_funcs
|
12 |
+
from ._decomp_lu_cython import lu_dispatcher
|
13 |
+
|
14 |
+
lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)])
|
15 |
+
for x in np.typecodes['All']}
|
16 |
+
|
17 |
+
__all__ = ['lu', 'lu_solve', 'lu_factor']
|
18 |
+
|
19 |
+
|
20 |
+
def lu_factor(a, overwrite_a=False, check_finite=True):
|
21 |
+
"""
|
22 |
+
Compute pivoted LU decomposition of a matrix.
|
23 |
+
|
24 |
+
The decomposition is::
|
25 |
+
|
26 |
+
A = P L U
|
27 |
+
|
28 |
+
where P is a permutation matrix, L lower triangular with unit
|
29 |
+
diagonal elements, and U upper triangular.
|
30 |
+
|
31 |
+
Parameters
|
32 |
+
----------
|
33 |
+
a : (M, N) array_like
|
34 |
+
Matrix to decompose
|
35 |
+
overwrite_a : bool, optional
|
36 |
+
Whether to overwrite data in A (may increase performance)
|
37 |
+
check_finite : bool, optional
|
38 |
+
Whether to check that the input matrix contains only finite numbers.
|
39 |
+
Disabling may give a performance gain, but may result in problems
|
40 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
41 |
+
|
42 |
+
Returns
|
43 |
+
-------
|
44 |
+
lu : (M, N) ndarray
|
45 |
+
Matrix containing U in its upper triangle, and L in its lower triangle.
|
46 |
+
The unit diagonal elements of L are not stored.
|
47 |
+
piv : (K,) ndarray
|
48 |
+
Pivot indices representing the permutation matrix P:
|
49 |
+
row i of matrix was interchanged with row piv[i].
|
50 |
+
Of shape ``(K,)``, with ``K = min(M, N)``.
|
51 |
+
|
52 |
+
See Also
|
53 |
+
--------
|
54 |
+
lu : gives lu factorization in more user-friendly format
|
55 |
+
lu_solve : solve an equation system using the LU factorization of a matrix
|
56 |
+
|
57 |
+
Notes
|
58 |
+
-----
|
59 |
+
This is a wrapper to the ``*GETRF`` routines from LAPACK. Unlike
|
60 |
+
:func:`lu`, it outputs the L and U factors into a single array
|
61 |
+
and returns pivot indices instead of a permutation matrix.
|
62 |
+
|
63 |
+
While the underlying ``*GETRF`` routines return 1-based pivot indices, the
|
64 |
+
``piv`` array returned by ``lu_factor`` contains 0-based indices.
|
65 |
+
|
66 |
+
Examples
|
67 |
+
--------
|
68 |
+
>>> import numpy as np
|
69 |
+
>>> from scipy.linalg import lu_factor
|
70 |
+
>>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
|
71 |
+
>>> lu, piv = lu_factor(A)
|
72 |
+
>>> piv
|
73 |
+
array([2, 2, 3, 3], dtype=int32)
|
74 |
+
|
75 |
+
Convert LAPACK's ``piv`` array to NumPy index and test the permutation
|
76 |
+
|
77 |
+
>>> def pivot_to_permutation(piv):
|
78 |
+
... perm = np.arange(len(piv))
|
79 |
+
... for i in range(len(piv)):
|
80 |
+
... perm[i], perm[piv[i]] = perm[piv[i]], perm[i]
|
81 |
+
... return perm
|
82 |
+
...
|
83 |
+
>>> p_inv = pivot_to_permutation(piv)
|
84 |
+
>>> p_inv
|
85 |
+
array([2, 0, 3, 1])
|
86 |
+
>>> L, U = np.tril(lu, k=-1) + np.eye(4), np.triu(lu)
|
87 |
+
>>> np.allclose(A[p_inv] - L @ U, np.zeros((4, 4)))
|
88 |
+
True
|
89 |
+
|
90 |
+
The P matrix in P L U is defined by the inverse permutation and
|
91 |
+
can be recovered using argsort:
|
92 |
+
|
93 |
+
>>> p = np.argsort(p_inv)
|
94 |
+
>>> p
|
95 |
+
array([1, 3, 0, 2])
|
96 |
+
>>> np.allclose(A - L[p] @ U, np.zeros((4, 4)))
|
97 |
+
True
|
98 |
+
|
99 |
+
or alternatively:
|
100 |
+
|
101 |
+
>>> P = np.eye(4)[p]
|
102 |
+
>>> np.allclose(A - P @ L @ U, np.zeros((4, 4)))
|
103 |
+
True
|
104 |
+
"""
|
105 |
+
if check_finite:
|
106 |
+
a1 = asarray_chkfinite(a)
|
107 |
+
else:
|
108 |
+
a1 = asarray(a)
|
109 |
+
overwrite_a = overwrite_a or (_datacopied(a1, a))
|
110 |
+
getrf, = get_lapack_funcs(('getrf',), (a1,))
|
111 |
+
lu, piv, info = getrf(a1, overwrite_a=overwrite_a)
|
112 |
+
if info < 0:
|
113 |
+
raise ValueError('illegal value in %dth argument of '
|
114 |
+
'internal getrf (lu_factor)' % -info)
|
115 |
+
if info > 0:
|
116 |
+
warn("Diagonal number %d is exactly zero. Singular matrix." % info,
|
117 |
+
LinAlgWarning, stacklevel=2)
|
118 |
+
return lu, piv
|
119 |
+
|
120 |
+
|
121 |
+
def lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True):
|
122 |
+
"""Solve an equation system, a x = b, given the LU factorization of a
|
123 |
+
|
124 |
+
Parameters
|
125 |
+
----------
|
126 |
+
(lu, piv)
|
127 |
+
Factorization of the coefficient matrix a, as given by lu_factor.
|
128 |
+
In particular piv are 0-indexed pivot indices.
|
129 |
+
b : array
|
130 |
+
Right-hand side
|
131 |
+
trans : {0, 1, 2}, optional
|
132 |
+
Type of system to solve:
|
133 |
+
|
134 |
+
===== =========
|
135 |
+
trans system
|
136 |
+
===== =========
|
137 |
+
0 a x = b
|
138 |
+
1 a^T x = b
|
139 |
+
2 a^H x = b
|
140 |
+
===== =========
|
141 |
+
overwrite_b : bool, optional
|
142 |
+
Whether to overwrite data in b (may increase performance)
|
143 |
+
check_finite : bool, optional
|
144 |
+
Whether to check that the input matrices contain only finite numbers.
|
145 |
+
Disabling may give a performance gain, but may result in problems
|
146 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
147 |
+
|
148 |
+
Returns
|
149 |
+
-------
|
150 |
+
x : array
|
151 |
+
Solution to the system
|
152 |
+
|
153 |
+
See Also
|
154 |
+
--------
|
155 |
+
lu_factor : LU factorize a matrix
|
156 |
+
|
157 |
+
Examples
|
158 |
+
--------
|
159 |
+
>>> import numpy as np
|
160 |
+
>>> from scipy.linalg import lu_factor, lu_solve
|
161 |
+
>>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
|
162 |
+
>>> b = np.array([1, 1, 1, 1])
|
163 |
+
>>> lu, piv = lu_factor(A)
|
164 |
+
>>> x = lu_solve((lu, piv), b)
|
165 |
+
>>> np.allclose(A @ x - b, np.zeros((4,)))
|
166 |
+
True
|
167 |
+
|
168 |
+
"""
|
169 |
+
(lu, piv) = lu_and_piv
|
170 |
+
if check_finite:
|
171 |
+
b1 = asarray_chkfinite(b)
|
172 |
+
else:
|
173 |
+
b1 = asarray(b)
|
174 |
+
overwrite_b = overwrite_b or _datacopied(b1, b)
|
175 |
+
if lu.shape[0] != b1.shape[0]:
|
176 |
+
raise ValueError(f"Shapes of lu {lu.shape} and b {b1.shape} are incompatible")
|
177 |
+
|
178 |
+
getrs, = get_lapack_funcs(('getrs',), (lu, b1))
|
179 |
+
x, info = getrs(lu, piv, b1, trans=trans, overwrite_b=overwrite_b)
|
180 |
+
if info == 0:
|
181 |
+
return x
|
182 |
+
raise ValueError('illegal value in %dth argument of internal gesv|posv'
|
183 |
+
% -info)
|
184 |
+
|
185 |
+
|
186 |
+
def lu(a, permute_l=False, overwrite_a=False, check_finite=True,
|
187 |
+
p_indices=False):
|
188 |
+
"""
|
189 |
+
Compute LU decomposition of a matrix with partial pivoting.
|
190 |
+
|
191 |
+
The decomposition satisfies::
|
192 |
+
|
193 |
+
A = P @ L @ U
|
194 |
+
|
195 |
+
where ``P`` is a permutation matrix, ``L`` lower triangular with unit
|
196 |
+
diagonal elements, and ``U`` upper triangular. If `permute_l` is set to
|
197 |
+
``True`` then ``L`` is returned already permuted and hence satisfying
|
198 |
+
``A = L @ U``.
|
199 |
+
|
200 |
+
Parameters
|
201 |
+
----------
|
202 |
+
a : (M, N) array_like
|
203 |
+
Array to decompose
|
204 |
+
permute_l : bool, optional
|
205 |
+
Perform the multiplication P*L (Default: do not permute)
|
206 |
+
overwrite_a : bool, optional
|
207 |
+
Whether to overwrite data in a (may improve performance)
|
208 |
+
check_finite : bool, optional
|
209 |
+
Whether to check that the input matrix contains only finite numbers.
|
210 |
+
Disabling may give a performance gain, but may result in problems
|
211 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
212 |
+
p_indices : bool, optional
|
213 |
+
If ``True`` the permutation information is returned as row indices.
|
214 |
+
The default is ``False`` for backwards-compatibility reasons.
|
215 |
+
|
216 |
+
Returns
|
217 |
+
-------
|
218 |
+
**(If `permute_l` is ``False``)**
|
219 |
+
|
220 |
+
p : (..., M, M) ndarray
|
221 |
+
Permutation arrays or vectors depending on `p_indices`
|
222 |
+
l : (..., M, K) ndarray
|
223 |
+
Lower triangular or trapezoidal array with unit diagonal.
|
224 |
+
``K = min(M, N)``
|
225 |
+
u : (..., K, N) ndarray
|
226 |
+
Upper triangular or trapezoidal array
|
227 |
+
|
228 |
+
**(If `permute_l` is ``True``)**
|
229 |
+
|
230 |
+
pl : (..., M, K) ndarray
|
231 |
+
Permuted L matrix.
|
232 |
+
``K = min(M, N)``
|
233 |
+
u : (..., K, N) ndarray
|
234 |
+
Upper triangular or trapezoidal array
|
235 |
+
|
236 |
+
Notes
|
237 |
+
-----
|
238 |
+
Permutation matrices are costly since they are nothing but row reorder of
|
239 |
+
``L`` and hence indices are strongly recommended to be used instead if the
|
240 |
+
permutation is required. The relation in the 2D case then becomes simply
|
241 |
+
``A = L[P, :] @ U``. In higher dimensions, it is better to use `permute_l`
|
242 |
+
to avoid complicated indexing tricks.
|
243 |
+
|
244 |
+
In 2D case, if one has the indices however, for some reason, the
|
245 |
+
permutation matrix is still needed then it can be constructed by
|
246 |
+
``np.eye(M)[P, :]``.
|
247 |
+
|
248 |
+
Examples
|
249 |
+
--------
|
250 |
+
|
251 |
+
>>> import numpy as np
|
252 |
+
>>> from scipy.linalg import lu
|
253 |
+
>>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
|
254 |
+
>>> p, l, u = lu(A)
|
255 |
+
>>> np.allclose(A, p @ l @ u)
|
256 |
+
True
|
257 |
+
>>> p # Permutation matrix
|
258 |
+
array([[0., 1., 0., 0.], # Row index 1
|
259 |
+
[0., 0., 0., 1.], # Row index 3
|
260 |
+
[1., 0., 0., 0.], # Row index 0
|
261 |
+
[0., 0., 1., 0.]]) # Row index 2
|
262 |
+
>>> p, _, _ = lu(A, p_indices=True)
|
263 |
+
>>> p
|
264 |
+
array([1, 3, 0, 2]) # as given by row indices above
|
265 |
+
>>> np.allclose(A, l[p, :] @ u)
|
266 |
+
True
|
267 |
+
|
268 |
+
We can also use nd-arrays, for example, a demonstration with 4D array:
|
269 |
+
|
270 |
+
>>> rng = np.random.default_rng()
|
271 |
+
>>> A = rng.uniform(low=-4, high=4, size=[3, 2, 4, 8])
|
272 |
+
>>> p, l, u = lu(A)
|
273 |
+
>>> p.shape, l.shape, u.shape
|
274 |
+
((3, 2, 4, 4), (3, 2, 4, 4), (3, 2, 4, 8))
|
275 |
+
>>> np.allclose(A, p @ l @ u)
|
276 |
+
True
|
277 |
+
>>> PL, U = lu(A, permute_l=True)
|
278 |
+
>>> np.allclose(A, PL @ U)
|
279 |
+
True
|
280 |
+
|
281 |
+
"""
|
282 |
+
a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a)
|
283 |
+
if a1.ndim < 2:
|
284 |
+
raise ValueError('The input array must be at least two-dimensional.')
|
285 |
+
|
286 |
+
# Also check if dtype is LAPACK compatible
|
287 |
+
if a1.dtype.char not in 'fdFD':
|
288 |
+
dtype_char = lapack_cast_dict[a1.dtype.char]
|
289 |
+
if not dtype_char: # No casting possible
|
290 |
+
raise TypeError(f'The dtype {a1.dtype} cannot be cast '
|
291 |
+
'to float(32, 64) or complex(64, 128).')
|
292 |
+
|
293 |
+
a1 = a1.astype(dtype_char[0]) # makes a copy, free to scratch
|
294 |
+
overwrite_a = True
|
295 |
+
|
296 |
+
*nd, m, n = a1.shape
|
297 |
+
k = min(m, n)
|
298 |
+
real_dchar = 'f' if a1.dtype.char in 'fF' else 'd'
|
299 |
+
|
300 |
+
# Empty input
|
301 |
+
if min(*a1.shape) == 0:
|
302 |
+
if permute_l:
|
303 |
+
PL = np.empty(shape=[*nd, m, k], dtype=a1.dtype)
|
304 |
+
U = np.empty(shape=[*nd, k, n], dtype=a1.dtype)
|
305 |
+
return PL, U
|
306 |
+
else:
|
307 |
+
P = (np.empty([*nd, 0], dtype=np.int32) if p_indices else
|
308 |
+
np.empty([*nd, 0, 0], dtype=real_dchar))
|
309 |
+
L = np.empty(shape=[*nd, m, k], dtype=a1.dtype)
|
310 |
+
U = np.empty(shape=[*nd, k, n], dtype=a1.dtype)
|
311 |
+
return P, L, U
|
312 |
+
|
313 |
+
# Scalar case
|
314 |
+
if a1.shape[-2:] == (1, 1):
|
315 |
+
if permute_l:
|
316 |
+
return np.ones_like(a1), (a1 if overwrite_a else a1.copy())
|
317 |
+
else:
|
318 |
+
P = (np.zeros(shape=[*nd, m], dtype=int) if p_indices
|
319 |
+
else np.ones_like(a1))
|
320 |
+
return P, np.ones_like(a1), (a1 if overwrite_a else a1.copy())
|
321 |
+
|
322 |
+
# Then check overwrite permission
|
323 |
+
if not _datacopied(a1, a): # "a" still alive through "a1"
|
324 |
+
if not overwrite_a:
|
325 |
+
# Data belongs to "a" so make a copy
|
326 |
+
a1 = a1.copy(order='C')
|
327 |
+
# else: Do nothing we'll use "a" if possible
|
328 |
+
# else: a1 has its own data thus free to scratch
|
329 |
+
|
330 |
+
# Then layout checks, might happen that overwrite is allowed but original
|
331 |
+
# array was read-only or non-contiguous.
|
332 |
+
|
333 |
+
if not (a1.flags['C_CONTIGUOUS'] and a1.flags['WRITEABLE']):
|
334 |
+
a1 = a1.copy(order='C')
|
335 |
+
|
336 |
+
if not nd: # 2D array
|
337 |
+
|
338 |
+
p = np.empty(m, dtype=np.int32)
|
339 |
+
u = np.zeros([k, k], dtype=a1.dtype)
|
340 |
+
lu_dispatcher(a1, u, p, permute_l)
|
341 |
+
P, L, U = (p, a1, u) if m > n else (p, u, a1)
|
342 |
+
|
343 |
+
else: # Stacked array
|
344 |
+
|
345 |
+
# Prepare the contiguous data holders
|
346 |
+
P = np.empty([*nd, m], dtype=np.int32) # perm vecs
|
347 |
+
|
348 |
+
if m > n: # Tall arrays, U will be created
|
349 |
+
U = np.zeros([*nd, k, k], dtype=a1.dtype)
|
350 |
+
for ind in product(*[range(x) for x in a1.shape[:-2]]):
|
351 |
+
lu_dispatcher(a1[ind], U[ind], P[ind], permute_l)
|
352 |
+
L = a1
|
353 |
+
|
354 |
+
else: # Fat arrays, L will be created
|
355 |
+
L = np.zeros([*nd, k, k], dtype=a1.dtype)
|
356 |
+
for ind in product(*[range(x) for x in a1.shape[:-2]]):
|
357 |
+
lu_dispatcher(a1[ind], L[ind], P[ind], permute_l)
|
358 |
+
U = a1
|
359 |
+
|
360 |
+
# Convert permutation vecs to permutation arrays
|
361 |
+
# permute_l=False needed to enter here to avoid wasted efforts
|
362 |
+
if (not p_indices) and (not permute_l):
|
363 |
+
if nd:
|
364 |
+
Pa = np.zeros([*nd, m, m], dtype=real_dchar)
|
365 |
+
# An unreadable index hack - One-hot encoding for perm matrices
|
366 |
+
nd_ix = np.ix_(*([np.arange(x) for x in nd]+[np.arange(m)]))
|
367 |
+
Pa[(*nd_ix, P)] = 1
|
368 |
+
P = Pa
|
369 |
+
else: # 2D case
|
370 |
+
Pa = np.zeros([m, m], dtype=real_dchar)
|
371 |
+
Pa[np.arange(m), P] = 1
|
372 |
+
P = Pa
|
373 |
+
|
374 |
+
return (L, U) if permute_l else (P, L, U)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (271 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from numpy.typing import NDArray
|
2 |
+
from typing import Any
|
3 |
+
|
4 |
+
def lu_decompose(a: NDArray[Any], lu: NDArray[Any], perm: NDArray[Any], permute_l: bool) -> None: ... # noqa: E501
|
5 |
+
|
6 |
+
def lu_dispatcher(a: NDArray[Any], lu: NDArray[Any], perm: NDArray[Any], permute_l: bool) -> None: ... # noqa: E501
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from scipy.linalg import svd
|
3 |
+
|
4 |
+
|
5 |
+
__all__ = ['polar']
|
6 |
+
|
7 |
+
|
8 |
+
def polar(a, side="right"):
|
9 |
+
"""
|
10 |
+
Compute the polar decomposition.
|
11 |
+
|
12 |
+
Returns the factors of the polar decomposition [1]_ `u` and `p` such
|
13 |
+
that ``a = up`` (if `side` is "right") or ``a = pu`` (if `side` is
|
14 |
+
"left"), where `p` is positive semidefinite. Depending on the shape
|
15 |
+
of `a`, either the rows or columns of `u` are orthonormal. When `a`
|
16 |
+
is a square array, `u` is a square unitary array. When `a` is not
|
17 |
+
square, the "canonical polar decomposition" [2]_ is computed.
|
18 |
+
|
19 |
+
Parameters
|
20 |
+
----------
|
21 |
+
a : (m, n) array_like
|
22 |
+
The array to be factored.
|
23 |
+
side : {'left', 'right'}, optional
|
24 |
+
Determines whether a right or left polar decomposition is computed.
|
25 |
+
If `side` is "right", then ``a = up``. If `side` is "left", then
|
26 |
+
``a = pu``. The default is "right".
|
27 |
+
|
28 |
+
Returns
|
29 |
+
-------
|
30 |
+
u : (m, n) ndarray
|
31 |
+
If `a` is square, then `u` is unitary. If m > n, then the columns
|
32 |
+
of `a` are orthonormal, and if m < n, then the rows of `u` are
|
33 |
+
orthonormal.
|
34 |
+
p : ndarray
|
35 |
+
`p` is Hermitian positive semidefinite. If `a` is nonsingular, `p`
|
36 |
+
is positive definite. The shape of `p` is (n, n) or (m, m), depending
|
37 |
+
on whether `side` is "right" or "left", respectively.
|
38 |
+
|
39 |
+
References
|
40 |
+
----------
|
41 |
+
.. [1] R. A. Horn and C. R. Johnson, "Matrix Analysis", Cambridge
|
42 |
+
University Press, 1985.
|
43 |
+
.. [2] N. J. Higham, "Functions of Matrices: Theory and Computation",
|
44 |
+
SIAM, 2008.
|
45 |
+
|
46 |
+
Examples
|
47 |
+
--------
|
48 |
+
>>> import numpy as np
|
49 |
+
>>> from scipy.linalg import polar
|
50 |
+
>>> a = np.array([[1, -1], [2, 4]])
|
51 |
+
>>> u, p = polar(a)
|
52 |
+
>>> u
|
53 |
+
array([[ 0.85749293, -0.51449576],
|
54 |
+
[ 0.51449576, 0.85749293]])
|
55 |
+
>>> p
|
56 |
+
array([[ 1.88648444, 1.2004901 ],
|
57 |
+
[ 1.2004901 , 3.94446746]])
|
58 |
+
|
59 |
+
A non-square example, with m < n:
|
60 |
+
|
61 |
+
>>> b = np.array([[0.5, 1, 2], [1.5, 3, 4]])
|
62 |
+
>>> u, p = polar(b)
|
63 |
+
>>> u
|
64 |
+
array([[-0.21196618, -0.42393237, 0.88054056],
|
65 |
+
[ 0.39378971, 0.78757942, 0.4739708 ]])
|
66 |
+
>>> p
|
67 |
+
array([[ 0.48470147, 0.96940295, 1.15122648],
|
68 |
+
[ 0.96940295, 1.9388059 , 2.30245295],
|
69 |
+
[ 1.15122648, 2.30245295, 3.65696431]])
|
70 |
+
>>> u.dot(p) # Verify the decomposition.
|
71 |
+
array([[ 0.5, 1. , 2. ],
|
72 |
+
[ 1.5, 3. , 4. ]])
|
73 |
+
>>> u.dot(u.T) # The rows of u are orthonormal.
|
74 |
+
array([[ 1.00000000e+00, -2.07353665e-17],
|
75 |
+
[ -2.07353665e-17, 1.00000000e+00]])
|
76 |
+
|
77 |
+
Another non-square example, with m > n:
|
78 |
+
|
79 |
+
>>> c = b.T
|
80 |
+
>>> u, p = polar(c)
|
81 |
+
>>> u
|
82 |
+
array([[-0.21196618, 0.39378971],
|
83 |
+
[-0.42393237, 0.78757942],
|
84 |
+
[ 0.88054056, 0.4739708 ]])
|
85 |
+
>>> p
|
86 |
+
array([[ 1.23116567, 1.93241587],
|
87 |
+
[ 1.93241587, 4.84930602]])
|
88 |
+
>>> u.dot(p) # Verify the decomposition.
|
89 |
+
array([[ 0.5, 1.5],
|
90 |
+
[ 1. , 3. ],
|
91 |
+
[ 2. , 4. ]])
|
92 |
+
>>> u.T.dot(u) # The columns of u are orthonormal.
|
93 |
+
array([[ 1.00000000e+00, -1.26363763e-16],
|
94 |
+
[ -1.26363763e-16, 1.00000000e+00]])
|
95 |
+
|
96 |
+
"""
|
97 |
+
if side not in ['right', 'left']:
|
98 |
+
raise ValueError("`side` must be either 'right' or 'left'")
|
99 |
+
a = np.asarray(a)
|
100 |
+
if a.ndim != 2:
|
101 |
+
raise ValueError("`a` must be a 2-D array.")
|
102 |
+
|
103 |
+
w, s, vh = svd(a, full_matrices=False)
|
104 |
+
u = w.dot(vh)
|
105 |
+
if side == 'right':
|
106 |
+
# a = up
|
107 |
+
p = (vh.T.conj() * s).dot(vh)
|
108 |
+
else:
|
109 |
+
# a = pu
|
110 |
+
p = (w * s).dot(w.T.conj())
|
111 |
+
return u, p
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py
ADDED
@@ -0,0 +1,430 @@
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""QR decomposition functions."""
|
2 |
+
import numpy
|
3 |
+
|
4 |
+
# Local imports
|
5 |
+
from .lapack import get_lapack_funcs
|
6 |
+
from ._misc import _datacopied
|
7 |
+
|
8 |
+
__all__ = ['qr', 'qr_multiply', 'rq']
|
9 |
+
|
10 |
+
|
11 |
+
def safecall(f, name, *args, **kwargs):
|
12 |
+
"""Call a LAPACK routine, determining lwork automatically and handling
|
13 |
+
error return values"""
|
14 |
+
lwork = kwargs.get("lwork", None)
|
15 |
+
if lwork in (None, -1):
|
16 |
+
kwargs['lwork'] = -1
|
17 |
+
ret = f(*args, **kwargs)
|
18 |
+
kwargs['lwork'] = ret[-2][0].real.astype(numpy.int_)
|
19 |
+
ret = f(*args, **kwargs)
|
20 |
+
if ret[-1] < 0:
|
21 |
+
raise ValueError("illegal value in %dth argument of internal %s"
|
22 |
+
% (-ret[-1], name))
|
23 |
+
return ret[:-2]
|
24 |
+
|
25 |
+
|
26 |
+
def qr(a, overwrite_a=False, lwork=None, mode='full', pivoting=False,
|
27 |
+
check_finite=True):
|
28 |
+
"""
|
29 |
+
Compute QR decomposition of a matrix.
|
30 |
+
|
31 |
+
Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal
|
32 |
+
and R upper triangular.
|
33 |
+
|
34 |
+
Parameters
|
35 |
+
----------
|
36 |
+
a : (M, N) array_like
|
37 |
+
Matrix to be decomposed
|
38 |
+
overwrite_a : bool, optional
|
39 |
+
Whether data in `a` is overwritten (may improve performance if
|
40 |
+
`overwrite_a` is set to True by reusing the existing input data
|
41 |
+
structure rather than creating a new one.)
|
42 |
+
lwork : int, optional
|
43 |
+
Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
|
44 |
+
is computed.
|
45 |
+
mode : {'full', 'r', 'economic', 'raw'}, optional
|
46 |
+
Determines what information is to be returned: either both Q and R
|
47 |
+
('full', default), only R ('r') or both Q and R but computed in
|
48 |
+
economy-size ('economic', see Notes). The final option 'raw'
|
49 |
+
(added in SciPy 0.11) makes the function return two matrices
|
50 |
+
(Q, TAU) in the internal format used by LAPACK.
|
51 |
+
pivoting : bool, optional
|
52 |
+
Whether or not factorization should include pivoting for rank-revealing
|
53 |
+
qr decomposition. If pivoting, compute the decomposition
|
54 |
+
``A[:, P] = Q @ R`` as above, but where P is chosen such that the
|
55 |
+
diagonal of R is non-increasing.
|
56 |
+
check_finite : bool, optional
|
57 |
+
Whether to check that the input matrix contains only finite numbers.
|
58 |
+
Disabling may give a performance gain, but may result in problems
|
59 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
60 |
+
|
61 |
+
Returns
|
62 |
+
-------
|
63 |
+
Q : float or complex ndarray
|
64 |
+
Of shape (M, M), or (M, K) for ``mode='economic'``. Not returned
|
65 |
+
if ``mode='r'``. Replaced by tuple ``(Q, TAU)`` if ``mode='raw'``.
|
66 |
+
R : float or complex ndarray
|
67 |
+
Of shape (M, N), or (K, N) for ``mode in ['economic', 'raw']``.
|
68 |
+
``K = min(M, N)``.
|
69 |
+
P : int ndarray
|
70 |
+
Of shape (N,) for ``pivoting=True``. Not returned if
|
71 |
+
``pivoting=False``.
|
72 |
+
|
73 |
+
Raises
|
74 |
+
------
|
75 |
+
LinAlgError
|
76 |
+
Raised if decomposition fails
|
77 |
+
|
78 |
+
Notes
|
79 |
+
-----
|
80 |
+
This is an interface to the LAPACK routines dgeqrf, zgeqrf,
|
81 |
+
dorgqr, zungqr, dgeqp3, and zgeqp3.
|
82 |
+
|
83 |
+
If ``mode=economic``, the shapes of Q and R are (M, K) and (K, N) instead
|
84 |
+
of (M,M) and (M,N), with ``K=min(M,N)``.
|
85 |
+
|
86 |
+
Examples
|
87 |
+
--------
|
88 |
+
>>> import numpy as np
|
89 |
+
>>> from scipy import linalg
|
90 |
+
>>> rng = np.random.default_rng()
|
91 |
+
>>> a = rng.standard_normal((9, 6))
|
92 |
+
|
93 |
+
>>> q, r = linalg.qr(a)
|
94 |
+
>>> np.allclose(a, np.dot(q, r))
|
95 |
+
True
|
96 |
+
>>> q.shape, r.shape
|
97 |
+
((9, 9), (9, 6))
|
98 |
+
|
99 |
+
>>> r2 = linalg.qr(a, mode='r')
|
100 |
+
>>> np.allclose(r, r2)
|
101 |
+
True
|
102 |
+
|
103 |
+
>>> q3, r3 = linalg.qr(a, mode='economic')
|
104 |
+
>>> q3.shape, r3.shape
|
105 |
+
((9, 6), (6, 6))
|
106 |
+
|
107 |
+
>>> q4, r4, p4 = linalg.qr(a, pivoting=True)
|
108 |
+
>>> d = np.abs(np.diag(r4))
|
109 |
+
>>> np.all(d[1:] <= d[:-1])
|
110 |
+
True
|
111 |
+
>>> np.allclose(a[:, p4], np.dot(q4, r4))
|
112 |
+
True
|
113 |
+
>>> q4.shape, r4.shape, p4.shape
|
114 |
+
((9, 9), (9, 6), (6,))
|
115 |
+
|
116 |
+
>>> q5, r5, p5 = linalg.qr(a, mode='economic', pivoting=True)
|
117 |
+
>>> q5.shape, r5.shape, p5.shape
|
118 |
+
((9, 6), (6, 6), (6,))
|
119 |
+
|
120 |
+
"""
|
121 |
+
# 'qr' was the old default, equivalent to 'full'. Neither 'full' nor
|
122 |
+
# 'qr' are used below.
|
123 |
+
# 'raw' is used internally by qr_multiply
|
124 |
+
if mode not in ['full', 'qr', 'r', 'economic', 'raw']:
|
125 |
+
raise ValueError("Mode argument should be one of ['full', 'r',"
|
126 |
+
"'economic', 'raw']")
|
127 |
+
|
128 |
+
if check_finite:
|
129 |
+
a1 = numpy.asarray_chkfinite(a)
|
130 |
+
else:
|
131 |
+
a1 = numpy.asarray(a)
|
132 |
+
if len(a1.shape) != 2:
|
133 |
+
raise ValueError("expected a 2-D array")
|
134 |
+
M, N = a1.shape
|
135 |
+
overwrite_a = overwrite_a or (_datacopied(a1, a))
|
136 |
+
|
137 |
+
if pivoting:
|
138 |
+
geqp3, = get_lapack_funcs(('geqp3',), (a1,))
|
139 |
+
qr, jpvt, tau = safecall(geqp3, "geqp3", a1, overwrite_a=overwrite_a)
|
140 |
+
jpvt -= 1 # geqp3 returns a 1-based index array, so subtract 1
|
141 |
+
else:
|
142 |
+
geqrf, = get_lapack_funcs(('geqrf',), (a1,))
|
143 |
+
qr, tau = safecall(geqrf, "geqrf", a1, lwork=lwork,
|
144 |
+
overwrite_a=overwrite_a)
|
145 |
+
|
146 |
+
if mode not in ['economic', 'raw'] or M < N:
|
147 |
+
R = numpy.triu(qr)
|
148 |
+
else:
|
149 |
+
R = numpy.triu(qr[:N, :])
|
150 |
+
|
151 |
+
if pivoting:
|
152 |
+
Rj = R, jpvt
|
153 |
+
else:
|
154 |
+
Rj = R,
|
155 |
+
|
156 |
+
if mode == 'r':
|
157 |
+
return Rj
|
158 |
+
elif mode == 'raw':
|
159 |
+
return ((qr, tau),) + Rj
|
160 |
+
|
161 |
+
gor_un_gqr, = get_lapack_funcs(('orgqr',), (qr,))
|
162 |
+
|
163 |
+
if M < N:
|
164 |
+
Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qr[:, :M], tau,
|
165 |
+
lwork=lwork, overwrite_a=1)
|
166 |
+
elif mode == 'economic':
|
167 |
+
Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qr, tau, lwork=lwork,
|
168 |
+
overwrite_a=1)
|
169 |
+
else:
|
170 |
+
t = qr.dtype.char
|
171 |
+
qqr = numpy.empty((M, M), dtype=t)
|
172 |
+
qqr[:, :N] = qr
|
173 |
+
Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qqr, tau, lwork=lwork,
|
174 |
+
overwrite_a=1)
|
175 |
+
|
176 |
+
return (Q,) + Rj
|
177 |
+
|
178 |
+
|
179 |
+
def qr_multiply(a, c, mode='right', pivoting=False, conjugate=False,
|
180 |
+
overwrite_a=False, overwrite_c=False):
|
181 |
+
"""
|
182 |
+
Calculate the QR decomposition and multiply Q with a matrix.
|
183 |
+
|
184 |
+
Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal
|
185 |
+
and R upper triangular. Multiply Q with a vector or a matrix c.
|
186 |
+
|
187 |
+
Parameters
|
188 |
+
----------
|
189 |
+
a : (M, N), array_like
|
190 |
+
Input array
|
191 |
+
c : array_like
|
192 |
+
Input array to be multiplied by ``q``.
|
193 |
+
mode : {'left', 'right'}, optional
|
194 |
+
``Q @ c`` is returned if mode is 'left', ``c @ Q`` is returned if
|
195 |
+
mode is 'right'.
|
196 |
+
The shape of c must be appropriate for the matrix multiplications,
|
197 |
+
if mode is 'left', ``min(a.shape) == c.shape[0]``,
|
198 |
+
if mode is 'right', ``a.shape[0] == c.shape[1]``.
|
199 |
+
pivoting : bool, optional
|
200 |
+
Whether or not factorization should include pivoting for rank-revealing
|
201 |
+
qr decomposition, see the documentation of qr.
|
202 |
+
conjugate : bool, optional
|
203 |
+
Whether Q should be complex-conjugated. This might be faster
|
204 |
+
than explicit conjugation.
|
205 |
+
overwrite_a : bool, optional
|
206 |
+
Whether data in a is overwritten (may improve performance)
|
207 |
+
overwrite_c : bool, optional
|
208 |
+
Whether data in c is overwritten (may improve performance).
|
209 |
+
If this is used, c must be big enough to keep the result,
|
210 |
+
i.e. ``c.shape[0]`` = ``a.shape[0]`` if mode is 'left'.
|
211 |
+
|
212 |
+
Returns
|
213 |
+
-------
|
214 |
+
CQ : ndarray
|
215 |
+
The product of ``Q`` and ``c``.
|
216 |
+
R : (K, N), ndarray
|
217 |
+
R array of the resulting QR factorization where ``K = min(M, N)``.
|
218 |
+
P : (N,) ndarray
|
219 |
+
Integer pivot array. Only returned when ``pivoting=True``.
|
220 |
+
|
221 |
+
Raises
|
222 |
+
------
|
223 |
+
LinAlgError
|
224 |
+
Raised if QR decomposition fails.
|
225 |
+
|
226 |
+
Notes
|
227 |
+
-----
|
228 |
+
This is an interface to the LAPACK routines ``?GEQRF``, ``?ORMQR``,
|
229 |
+
``?UNMQR``, and ``?GEQP3``.
|
230 |
+
|
231 |
+
.. versionadded:: 0.11.0
|
232 |
+
|
233 |
+
Examples
|
234 |
+
--------
|
235 |
+
>>> import numpy as np
|
236 |
+
>>> from scipy.linalg import qr_multiply, qr
|
237 |
+
>>> A = np.array([[1, 3, 3], [2, 3, 2], [2, 3, 3], [1, 3, 2]])
|
238 |
+
>>> qc, r1, piv1 = qr_multiply(A, 2*np.eye(4), pivoting=1)
|
239 |
+
>>> qc
|
240 |
+
array([[-1., 1., -1.],
|
241 |
+
[-1., -1., 1.],
|
242 |
+
[-1., -1., -1.],
|
243 |
+
[-1., 1., 1.]])
|
244 |
+
>>> r1
|
245 |
+
array([[-6., -3., -5. ],
|
246 |
+
[ 0., -1., -1.11022302e-16],
|
247 |
+
[ 0., 0., -1. ]])
|
248 |
+
>>> piv1
|
249 |
+
array([1, 0, 2], dtype=int32)
|
250 |
+
>>> q2, r2, piv2 = qr(A, mode='economic', pivoting=1)
|
251 |
+
>>> np.allclose(2*q2 - qc, np.zeros((4, 3)))
|
252 |
+
True
|
253 |
+
|
254 |
+
"""
|
255 |
+
if mode not in ['left', 'right']:
|
256 |
+
raise ValueError("Mode argument can only be 'left' or 'right' but "
|
257 |
+
f"not '{mode}'")
|
258 |
+
c = numpy.asarray_chkfinite(c)
|
259 |
+
if c.ndim < 2:
|
260 |
+
onedim = True
|
261 |
+
c = numpy.atleast_2d(c)
|
262 |
+
if mode == "left":
|
263 |
+
c = c.T
|
264 |
+
else:
|
265 |
+
onedim = False
|
266 |
+
|
267 |
+
a = numpy.atleast_2d(numpy.asarray(a)) # chkfinite done in qr
|
268 |
+
M, N = a.shape
|
269 |
+
|
270 |
+
if mode == 'left':
|
271 |
+
if c.shape[0] != min(M, N + overwrite_c*(M-N)):
|
272 |
+
raise ValueError('Array shapes are not compatible for Q @ c'
|
273 |
+
f' operation: {a.shape} vs {c.shape}')
|
274 |
+
else:
|
275 |
+
if M != c.shape[1]:
|
276 |
+
raise ValueError('Array shapes are not compatible for c @ Q'
|
277 |
+
f' operation: {c.shape} vs {a.shape}')
|
278 |
+
|
279 |
+
raw = qr(a, overwrite_a, None, "raw", pivoting)
|
280 |
+
Q, tau = raw[0]
|
281 |
+
|
282 |
+
gor_un_mqr, = get_lapack_funcs(('ormqr',), (Q,))
|
283 |
+
if gor_un_mqr.typecode in ('s', 'd'):
|
284 |
+
trans = "T"
|
285 |
+
else:
|
286 |
+
trans = "C"
|
287 |
+
|
288 |
+
Q = Q[:, :min(M, N)]
|
289 |
+
if M > N and mode == "left" and not overwrite_c:
|
290 |
+
if conjugate:
|
291 |
+
cc = numpy.zeros((c.shape[1], M), dtype=c.dtype, order="F")
|
292 |
+
cc[:, :N] = c.T
|
293 |
+
else:
|
294 |
+
cc = numpy.zeros((M, c.shape[1]), dtype=c.dtype, order="F")
|
295 |
+
cc[:N, :] = c
|
296 |
+
trans = "N"
|
297 |
+
if conjugate:
|
298 |
+
lr = "R"
|
299 |
+
else:
|
300 |
+
lr = "L"
|
301 |
+
overwrite_c = True
|
302 |
+
elif c.flags["C_CONTIGUOUS"] and trans == "T" or conjugate:
|
303 |
+
cc = c.T
|
304 |
+
if mode == "left":
|
305 |
+
lr = "R"
|
306 |
+
else:
|
307 |
+
lr = "L"
|
308 |
+
else:
|
309 |
+
trans = "N"
|
310 |
+
cc = c
|
311 |
+
if mode == "left":
|
312 |
+
lr = "L"
|
313 |
+
else:
|
314 |
+
lr = "R"
|
315 |
+
cQ, = safecall(gor_un_mqr, "gormqr/gunmqr", lr, trans, Q, tau, cc,
|
316 |
+
overwrite_c=overwrite_c)
|
317 |
+
if trans != "N":
|
318 |
+
cQ = cQ.T
|
319 |
+
if mode == "right":
|
320 |
+
cQ = cQ[:, :min(M, N)]
|
321 |
+
if onedim:
|
322 |
+
cQ = cQ.ravel()
|
323 |
+
|
324 |
+
return (cQ,) + raw[1:]
|
325 |
+
|
326 |
+
|
327 |
+
def rq(a, overwrite_a=False, lwork=None, mode='full', check_finite=True):
|
328 |
+
"""
|
329 |
+
Compute RQ decomposition of a matrix.
|
330 |
+
|
331 |
+
Calculate the decomposition ``A = R Q`` where Q is unitary/orthogonal
|
332 |
+
and R upper triangular.
|
333 |
+
|
334 |
+
Parameters
|
335 |
+
----------
|
336 |
+
a : (M, N) array_like
|
337 |
+
Matrix to be decomposed
|
338 |
+
overwrite_a : bool, optional
|
339 |
+
Whether data in a is overwritten (may improve performance)
|
340 |
+
lwork : int, optional
|
341 |
+
Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
|
342 |
+
is computed.
|
343 |
+
mode : {'full', 'r', 'economic'}, optional
|
344 |
+
Determines what information is to be returned: either both Q and R
|
345 |
+
('full', default), only R ('r') or both Q and R but computed in
|
346 |
+
economy-size ('economic', see Notes).
|
347 |
+
check_finite : bool, optional
|
348 |
+
Whether to check that the input matrix contains only finite numbers.
|
349 |
+
Disabling may give a performance gain, but may result in problems
|
350 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
351 |
+
|
352 |
+
Returns
|
353 |
+
-------
|
354 |
+
R : float or complex ndarray
|
355 |
+
Of shape (M, N) or (M, K) for ``mode='economic'``. ``K = min(M, N)``.
|
356 |
+
Q : float or complex ndarray
|
357 |
+
Of shape (N, N) or (K, N) for ``mode='economic'``. Not returned
|
358 |
+
if ``mode='r'``.
|
359 |
+
|
360 |
+
Raises
|
361 |
+
------
|
362 |
+
LinAlgError
|
363 |
+
If decomposition fails.
|
364 |
+
|
365 |
+
Notes
|
366 |
+
-----
|
367 |
+
This is an interface to the LAPACK routines sgerqf, dgerqf, cgerqf, zgerqf,
|
368 |
+
sorgrq, dorgrq, cungrq and zungrq.
|
369 |
+
|
370 |
+
If ``mode=economic``, the shapes of Q and R are (K, N) and (M, K) instead
|
371 |
+
of (N,N) and (M,N), with ``K=min(M,N)``.
|
372 |
+
|
373 |
+
Examples
|
374 |
+
--------
|
375 |
+
>>> import numpy as np
|
376 |
+
>>> from scipy import linalg
|
377 |
+
>>> rng = np.random.default_rng()
|
378 |
+
>>> a = rng.standard_normal((6, 9))
|
379 |
+
>>> r, q = linalg.rq(a)
|
380 |
+
>>> np.allclose(a, r @ q)
|
381 |
+
True
|
382 |
+
>>> r.shape, q.shape
|
383 |
+
((6, 9), (9, 9))
|
384 |
+
>>> r2 = linalg.rq(a, mode='r')
|
385 |
+
>>> np.allclose(r, r2)
|
386 |
+
True
|
387 |
+
>>> r3, q3 = linalg.rq(a, mode='economic')
|
388 |
+
>>> r3.shape, q3.shape
|
389 |
+
((6, 6), (6, 9))
|
390 |
+
|
391 |
+
"""
|
392 |
+
if mode not in ['full', 'r', 'economic']:
|
393 |
+
raise ValueError(
|
394 |
+
"Mode argument should be one of ['full', 'r', 'economic']")
|
395 |
+
|
396 |
+
if check_finite:
|
397 |
+
a1 = numpy.asarray_chkfinite(a)
|
398 |
+
else:
|
399 |
+
a1 = numpy.asarray(a)
|
400 |
+
if len(a1.shape) != 2:
|
401 |
+
raise ValueError('expected matrix')
|
402 |
+
M, N = a1.shape
|
403 |
+
overwrite_a = overwrite_a or (_datacopied(a1, a))
|
404 |
+
|
405 |
+
gerqf, = get_lapack_funcs(('gerqf',), (a1,))
|
406 |
+
rq, tau = safecall(gerqf, 'gerqf', a1, lwork=lwork,
|
407 |
+
overwrite_a=overwrite_a)
|
408 |
+
if not mode == 'economic' or N < M:
|
409 |
+
R = numpy.triu(rq, N-M)
|
410 |
+
else:
|
411 |
+
R = numpy.triu(rq[-M:, -M:])
|
412 |
+
|
413 |
+
if mode == 'r':
|
414 |
+
return R
|
415 |
+
|
416 |
+
gor_un_grq, = get_lapack_funcs(('orgrq',), (rq,))
|
417 |
+
|
418 |
+
if N < M:
|
419 |
+
Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq[-N:], tau, lwork=lwork,
|
420 |
+
overwrite_a=1)
|
421 |
+
elif mode == 'economic':
|
422 |
+
Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq, tau, lwork=lwork,
|
423 |
+
overwrite_a=1)
|
424 |
+
else:
|
425 |
+
rq1 = numpy.empty((N, N), dtype=rq.dtype)
|
426 |
+
rq1[-M:] = rq
|
427 |
+
Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq1, tau, lwork=lwork,
|
428 |
+
overwrite_a=1)
|
429 |
+
|
430 |
+
return R, Q
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py
ADDED
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""SVD decomposition functions."""
|
2 |
+
import numpy
|
3 |
+
from numpy import zeros, r_, diag, dot, arccos, arcsin, where, clip
|
4 |
+
|
5 |
+
# Local imports.
|
6 |
+
from ._misc import LinAlgError, _datacopied
|
7 |
+
from .lapack import get_lapack_funcs, _compute_lwork
|
8 |
+
from ._decomp import _asarray_validated
|
9 |
+
|
10 |
+
__all__ = ['svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space']
|
11 |
+
|
12 |
+
|
13 |
+
def svd(a, full_matrices=True, compute_uv=True, overwrite_a=False,
|
14 |
+
check_finite=True, lapack_driver='gesdd'):
|
15 |
+
"""
|
16 |
+
Singular Value Decomposition.
|
17 |
+
|
18 |
+
Factorizes the matrix `a` into two unitary matrices ``U`` and ``Vh``, and
|
19 |
+
a 1-D array ``s`` of singular values (real, non-negative) such that
|
20 |
+
``a == U @ S @ Vh``, where ``S`` is a suitably shaped matrix of zeros with
|
21 |
+
main diagonal ``s``.
|
22 |
+
|
23 |
+
Parameters
|
24 |
+
----------
|
25 |
+
a : (M, N) array_like
|
26 |
+
Matrix to decompose.
|
27 |
+
full_matrices : bool, optional
|
28 |
+
If True (default), `U` and `Vh` are of shape ``(M, M)``, ``(N, N)``.
|
29 |
+
If False, the shapes are ``(M, K)`` and ``(K, N)``, where
|
30 |
+
``K = min(M, N)``.
|
31 |
+
compute_uv : bool, optional
|
32 |
+
Whether to compute also ``U`` and ``Vh`` in addition to ``s``.
|
33 |
+
Default is True.
|
34 |
+
overwrite_a : bool, optional
|
35 |
+
Whether to overwrite `a`; may improve performance.
|
36 |
+
Default is False.
|
37 |
+
check_finite : bool, optional
|
38 |
+
Whether to check that the input matrix contains only finite numbers.
|
39 |
+
Disabling may give a performance gain, but may result in problems
|
40 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
41 |
+
lapack_driver : {'gesdd', 'gesvd'}, optional
|
42 |
+
Whether to use the more efficient divide-and-conquer approach
|
43 |
+
(``'gesdd'``) or general rectangular approach (``'gesvd'``)
|
44 |
+
to compute the SVD. MATLAB and Octave use the ``'gesvd'`` approach.
|
45 |
+
Default is ``'gesdd'``.
|
46 |
+
|
47 |
+
.. versionadded:: 0.18
|
48 |
+
|
49 |
+
Returns
|
50 |
+
-------
|
51 |
+
U : ndarray
|
52 |
+
Unitary matrix having left singular vectors as columns.
|
53 |
+
Of shape ``(M, M)`` or ``(M, K)``, depending on `full_matrices`.
|
54 |
+
s : ndarray
|
55 |
+
The singular values, sorted in non-increasing order.
|
56 |
+
Of shape (K,), with ``K = min(M, N)``.
|
57 |
+
Vh : ndarray
|
58 |
+
Unitary matrix having right singular vectors as rows.
|
59 |
+
Of shape ``(N, N)`` or ``(K, N)`` depending on `full_matrices`.
|
60 |
+
|
61 |
+
For ``compute_uv=False``, only ``s`` is returned.
|
62 |
+
|
63 |
+
Raises
|
64 |
+
------
|
65 |
+
LinAlgError
|
66 |
+
If SVD computation does not converge.
|
67 |
+
|
68 |
+
See Also
|
69 |
+
--------
|
70 |
+
svdvals : Compute singular values of a matrix.
|
71 |
+
diagsvd : Construct the Sigma matrix, given the vector s.
|
72 |
+
|
73 |
+
Examples
|
74 |
+
--------
|
75 |
+
>>> import numpy as np
|
76 |
+
>>> from scipy import linalg
|
77 |
+
>>> rng = np.random.default_rng()
|
78 |
+
>>> m, n = 9, 6
|
79 |
+
>>> a = rng.standard_normal((m, n)) + 1.j*rng.standard_normal((m, n))
|
80 |
+
>>> U, s, Vh = linalg.svd(a)
|
81 |
+
>>> U.shape, s.shape, Vh.shape
|
82 |
+
((9, 9), (6,), (6, 6))
|
83 |
+
|
84 |
+
Reconstruct the original matrix from the decomposition:
|
85 |
+
|
86 |
+
>>> sigma = np.zeros((m, n))
|
87 |
+
>>> for i in range(min(m, n)):
|
88 |
+
... sigma[i, i] = s[i]
|
89 |
+
>>> a1 = np.dot(U, np.dot(sigma, Vh))
|
90 |
+
>>> np.allclose(a, a1)
|
91 |
+
True
|
92 |
+
|
93 |
+
Alternatively, use ``full_matrices=False`` (notice that the shape of
|
94 |
+
``U`` is then ``(m, n)`` instead of ``(m, m)``):
|
95 |
+
|
96 |
+
>>> U, s, Vh = linalg.svd(a, full_matrices=False)
|
97 |
+
>>> U.shape, s.shape, Vh.shape
|
98 |
+
((9, 6), (6,), (6, 6))
|
99 |
+
>>> S = np.diag(s)
|
100 |
+
>>> np.allclose(a, np.dot(U, np.dot(S, Vh)))
|
101 |
+
True
|
102 |
+
|
103 |
+
>>> s2 = linalg.svd(a, compute_uv=False)
|
104 |
+
>>> np.allclose(s, s2)
|
105 |
+
True
|
106 |
+
|
107 |
+
"""
|
108 |
+
a1 = _asarray_validated(a, check_finite=check_finite)
|
109 |
+
if len(a1.shape) != 2:
|
110 |
+
raise ValueError('expected matrix')
|
111 |
+
m, n = a1.shape
|
112 |
+
overwrite_a = overwrite_a or (_datacopied(a1, a))
|
113 |
+
|
114 |
+
if not isinstance(lapack_driver, str):
|
115 |
+
raise TypeError('lapack_driver must be a string')
|
116 |
+
if lapack_driver not in ('gesdd', 'gesvd'):
|
117 |
+
message = f'lapack_driver must be "gesdd" or "gesvd", not "{lapack_driver}"'
|
118 |
+
raise ValueError(message)
|
119 |
+
|
120 |
+
if lapack_driver == 'gesdd' and compute_uv:
|
121 |
+
# XXX: revisit int32 when ILP64 lapack becomes a thing
|
122 |
+
max_mn, min_mn = (m, n) if m > n else (n, m)
|
123 |
+
if full_matrices:
|
124 |
+
if max_mn*max_mn > numpy.iinfo(numpy.int32).max:
|
125 |
+
raise ValueError(f"Indexing a matrix size {max_mn} x {max_mn} "
|
126 |
+
" would incur integer overflow in LAPACK.")
|
127 |
+
else:
|
128 |
+
sz = max(m * min_mn, n * min_mn)
|
129 |
+
if max(m * min_mn, n * min_mn) > numpy.iinfo(numpy.int32).max:
|
130 |
+
raise ValueError(f"Indexing a matrix of {sz} elements would "
|
131 |
+
"incur an in integer overflow in LAPACK.")
|
132 |
+
|
133 |
+
funcs = (lapack_driver, lapack_driver + '_lwork')
|
134 |
+
gesXd, gesXd_lwork = get_lapack_funcs(funcs, (a1,), ilp64='preferred')
|
135 |
+
|
136 |
+
# compute optimal lwork
|
137 |
+
lwork = _compute_lwork(gesXd_lwork, a1.shape[0], a1.shape[1],
|
138 |
+
compute_uv=compute_uv, full_matrices=full_matrices)
|
139 |
+
|
140 |
+
# perform decomposition
|
141 |
+
u, s, v, info = gesXd(a1, compute_uv=compute_uv, lwork=lwork,
|
142 |
+
full_matrices=full_matrices, overwrite_a=overwrite_a)
|
143 |
+
|
144 |
+
if info > 0:
|
145 |
+
raise LinAlgError("SVD did not converge")
|
146 |
+
if info < 0:
|
147 |
+
raise ValueError('illegal value in %dth argument of internal gesdd'
|
148 |
+
% -info)
|
149 |
+
if compute_uv:
|
150 |
+
return u, s, v
|
151 |
+
else:
|
152 |
+
return s
|
153 |
+
|
154 |
+
|
155 |
+
def svdvals(a, overwrite_a=False, check_finite=True):
|
156 |
+
"""
|
157 |
+
Compute singular values of a matrix.
|
158 |
+
|
159 |
+
Parameters
|
160 |
+
----------
|
161 |
+
a : (M, N) array_like
|
162 |
+
Matrix to decompose.
|
163 |
+
overwrite_a : bool, optional
|
164 |
+
Whether to overwrite `a`; may improve performance.
|
165 |
+
Default is False.
|
166 |
+
check_finite : bool, optional
|
167 |
+
Whether to check that the input matrix contains only finite numbers.
|
168 |
+
Disabling may give a performance gain, but may result in problems
|
169 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
170 |
+
|
171 |
+
Returns
|
172 |
+
-------
|
173 |
+
s : (min(M, N),) ndarray
|
174 |
+
The singular values, sorted in decreasing order.
|
175 |
+
|
176 |
+
Raises
|
177 |
+
------
|
178 |
+
LinAlgError
|
179 |
+
If SVD computation does not converge.
|
180 |
+
|
181 |
+
See Also
|
182 |
+
--------
|
183 |
+
svd : Compute the full singular value decomposition of a matrix.
|
184 |
+
diagsvd : Construct the Sigma matrix, given the vector s.
|
185 |
+
|
186 |
+
Notes
|
187 |
+
-----
|
188 |
+
``svdvals(a)`` only differs from ``svd(a, compute_uv=False)`` by its
|
189 |
+
handling of the edge case of empty ``a``, where it returns an
|
190 |
+
empty sequence:
|
191 |
+
|
192 |
+
>>> import numpy as np
|
193 |
+
>>> a = np.empty((0, 2))
|
194 |
+
>>> from scipy.linalg import svdvals
|
195 |
+
>>> svdvals(a)
|
196 |
+
array([], dtype=float64)
|
197 |
+
|
198 |
+
Examples
|
199 |
+
--------
|
200 |
+
>>> import numpy as np
|
201 |
+
>>> from scipy.linalg import svdvals
|
202 |
+
>>> m = np.array([[1.0, 0.0],
|
203 |
+
... [2.0, 3.0],
|
204 |
+
... [1.0, 1.0],
|
205 |
+
... [0.0, 2.0],
|
206 |
+
... [1.0, 0.0]])
|
207 |
+
>>> svdvals(m)
|
208 |
+
array([ 4.28091555, 1.63516424])
|
209 |
+
|
210 |
+
We can verify the maximum singular value of `m` by computing the maximum
|
211 |
+
length of `m.dot(u)` over all the unit vectors `u` in the (x,y) plane.
|
212 |
+
We approximate "all" the unit vectors with a large sample. Because
|
213 |
+
of linearity, we only need the unit vectors with angles in [0, pi].
|
214 |
+
|
215 |
+
>>> t = np.linspace(0, np.pi, 2000)
|
216 |
+
>>> u = np.array([np.cos(t), np.sin(t)])
|
217 |
+
>>> np.linalg.norm(m.dot(u), axis=0).max()
|
218 |
+
4.2809152422538475
|
219 |
+
|
220 |
+
`p` is a projection matrix with rank 1. With exact arithmetic,
|
221 |
+
its singular values would be [1, 0, 0, 0].
|
222 |
+
|
223 |
+
>>> v = np.array([0.1, 0.3, 0.9, 0.3])
|
224 |
+
>>> p = np.outer(v, v)
|
225 |
+
>>> svdvals(p)
|
226 |
+
array([ 1.00000000e+00, 2.02021698e-17, 1.56692500e-17,
|
227 |
+
8.15115104e-34])
|
228 |
+
|
229 |
+
The singular values of an orthogonal matrix are all 1. Here, we
|
230 |
+
create a random orthogonal matrix by using the `rvs()` method of
|
231 |
+
`scipy.stats.ortho_group`.
|
232 |
+
|
233 |
+
>>> from scipy.stats import ortho_group
|
234 |
+
>>> orth = ortho_group.rvs(4)
|
235 |
+
>>> svdvals(orth)
|
236 |
+
array([ 1., 1., 1., 1.])
|
237 |
+
|
238 |
+
"""
|
239 |
+
a = _asarray_validated(a, check_finite=check_finite)
|
240 |
+
if a.size:
|
241 |
+
return svd(a, compute_uv=0, overwrite_a=overwrite_a,
|
242 |
+
check_finite=False)
|
243 |
+
elif len(a.shape) != 2:
|
244 |
+
raise ValueError('expected matrix')
|
245 |
+
else:
|
246 |
+
return numpy.empty(0)
|
247 |
+
|
248 |
+
|
249 |
+
def diagsvd(s, M, N):
|
250 |
+
"""
|
251 |
+
Construct the sigma matrix in SVD from singular values and size M, N.
|
252 |
+
|
253 |
+
Parameters
|
254 |
+
----------
|
255 |
+
s : (M,) or (N,) array_like
|
256 |
+
Singular values
|
257 |
+
M : int
|
258 |
+
Size of the matrix whose singular values are `s`.
|
259 |
+
N : int
|
260 |
+
Size of the matrix whose singular values are `s`.
|
261 |
+
|
262 |
+
Returns
|
263 |
+
-------
|
264 |
+
S : (M, N) ndarray
|
265 |
+
The S-matrix in the singular value decomposition
|
266 |
+
|
267 |
+
See Also
|
268 |
+
--------
|
269 |
+
svd : Singular value decomposition of a matrix
|
270 |
+
svdvals : Compute singular values of a matrix.
|
271 |
+
|
272 |
+
Examples
|
273 |
+
--------
|
274 |
+
>>> import numpy as np
|
275 |
+
>>> from scipy.linalg import diagsvd
|
276 |
+
>>> vals = np.array([1, 2, 3]) # The array representing the computed svd
|
277 |
+
>>> diagsvd(vals, 3, 4)
|
278 |
+
array([[1, 0, 0, 0],
|
279 |
+
[0, 2, 0, 0],
|
280 |
+
[0, 0, 3, 0]])
|
281 |
+
>>> diagsvd(vals, 4, 3)
|
282 |
+
array([[1, 0, 0],
|
283 |
+
[0, 2, 0],
|
284 |
+
[0, 0, 3],
|
285 |
+
[0, 0, 0]])
|
286 |
+
|
287 |
+
"""
|
288 |
+
part = diag(s)
|
289 |
+
typ = part.dtype.char
|
290 |
+
MorN = len(s)
|
291 |
+
if MorN == M:
|
292 |
+
return numpy.hstack((part, zeros((M, N - M), dtype=typ)))
|
293 |
+
elif MorN == N:
|
294 |
+
return r_[part, zeros((M - N, N), dtype=typ)]
|
295 |
+
else:
|
296 |
+
raise ValueError("Length of s must be M or N.")
|
297 |
+
|
298 |
+
|
299 |
+
# Orthonormal decomposition
|
300 |
+
|
301 |
+
def orth(A, rcond=None):
|
302 |
+
"""
|
303 |
+
Construct an orthonormal basis for the range of A using SVD
|
304 |
+
|
305 |
+
Parameters
|
306 |
+
----------
|
307 |
+
A : (M, N) array_like
|
308 |
+
Input array
|
309 |
+
rcond : float, optional
|
310 |
+
Relative condition number. Singular values ``s`` smaller than
|
311 |
+
``rcond * max(s)`` are considered zero.
|
312 |
+
Default: floating point eps * max(M,N).
|
313 |
+
|
314 |
+
Returns
|
315 |
+
-------
|
316 |
+
Q : (M, K) ndarray
|
317 |
+
Orthonormal basis for the range of A.
|
318 |
+
K = effective rank of A, as determined by rcond
|
319 |
+
|
320 |
+
See Also
|
321 |
+
--------
|
322 |
+
svd : Singular value decomposition of a matrix
|
323 |
+
null_space : Matrix null space
|
324 |
+
|
325 |
+
Examples
|
326 |
+
--------
|
327 |
+
>>> import numpy as np
|
328 |
+
>>> from scipy.linalg import orth
|
329 |
+
>>> A = np.array([[2, 0, 0], [0, 5, 0]]) # rank 2 array
|
330 |
+
>>> orth(A)
|
331 |
+
array([[0., 1.],
|
332 |
+
[1., 0.]])
|
333 |
+
>>> orth(A.T)
|
334 |
+
array([[0., 1.],
|
335 |
+
[1., 0.],
|
336 |
+
[0., 0.]])
|
337 |
+
|
338 |
+
"""
|
339 |
+
u, s, vh = svd(A, full_matrices=False)
|
340 |
+
M, N = u.shape[0], vh.shape[1]
|
341 |
+
if rcond is None:
|
342 |
+
rcond = numpy.finfo(s.dtype).eps * max(M, N)
|
343 |
+
tol = numpy.amax(s) * rcond
|
344 |
+
num = numpy.sum(s > tol, dtype=int)
|
345 |
+
Q = u[:, :num]
|
346 |
+
return Q
|
347 |
+
|
348 |
+
|
349 |
+
def null_space(A, rcond=None):
|
350 |
+
"""
|
351 |
+
Construct an orthonormal basis for the null space of A using SVD
|
352 |
+
|
353 |
+
Parameters
|
354 |
+
----------
|
355 |
+
A : (M, N) array_like
|
356 |
+
Input array
|
357 |
+
rcond : float, optional
|
358 |
+
Relative condition number. Singular values ``s`` smaller than
|
359 |
+
``rcond * max(s)`` are considered zero.
|
360 |
+
Default: floating point eps * max(M,N).
|
361 |
+
|
362 |
+
Returns
|
363 |
+
-------
|
364 |
+
Z : (N, K) ndarray
|
365 |
+
Orthonormal basis for the null space of A.
|
366 |
+
K = dimension of effective null space, as determined by rcond
|
367 |
+
|
368 |
+
See Also
|
369 |
+
--------
|
370 |
+
svd : Singular value decomposition of a matrix
|
371 |
+
orth : Matrix range
|
372 |
+
|
373 |
+
Examples
|
374 |
+
--------
|
375 |
+
1-D null space:
|
376 |
+
|
377 |
+
>>> import numpy as np
|
378 |
+
>>> from scipy.linalg import null_space
|
379 |
+
>>> A = np.array([[1, 1], [1, 1]])
|
380 |
+
>>> ns = null_space(A)
|
381 |
+
>>> ns * np.copysign(1, ns[0,0]) # Remove the sign ambiguity of the vector
|
382 |
+
array([[ 0.70710678],
|
383 |
+
[-0.70710678]])
|
384 |
+
|
385 |
+
2-D null space:
|
386 |
+
|
387 |
+
>>> from numpy.random import default_rng
|
388 |
+
>>> rng = default_rng()
|
389 |
+
>>> B = rng.random((3, 5))
|
390 |
+
>>> Z = null_space(B)
|
391 |
+
>>> Z.shape
|
392 |
+
(5, 2)
|
393 |
+
>>> np.allclose(B.dot(Z), 0)
|
394 |
+
True
|
395 |
+
|
396 |
+
The basis vectors are orthonormal (up to rounding error):
|
397 |
+
|
398 |
+
>>> Z.T.dot(Z)
|
399 |
+
array([[ 1.00000000e+00, 6.92087741e-17],
|
400 |
+
[ 6.92087741e-17, 1.00000000e+00]])
|
401 |
+
|
402 |
+
"""
|
403 |
+
u, s, vh = svd(A, full_matrices=True)
|
404 |
+
M, N = u.shape[0], vh.shape[1]
|
405 |
+
if rcond is None:
|
406 |
+
rcond = numpy.finfo(s.dtype).eps * max(M, N)
|
407 |
+
tol = numpy.amax(s) * rcond
|
408 |
+
num = numpy.sum(s > tol, dtype=int)
|
409 |
+
Q = vh[num:,:].T.conj()
|
410 |
+
return Q
|
411 |
+
|
412 |
+
|
413 |
+
def subspace_angles(A, B):
|
414 |
+
r"""
|
415 |
+
Compute the subspace angles between two matrices.
|
416 |
+
|
417 |
+
Parameters
|
418 |
+
----------
|
419 |
+
A : (M, N) array_like
|
420 |
+
The first input array.
|
421 |
+
B : (M, K) array_like
|
422 |
+
The second input array.
|
423 |
+
|
424 |
+
Returns
|
425 |
+
-------
|
426 |
+
angles : ndarray, shape (min(N, K),)
|
427 |
+
The subspace angles between the column spaces of `A` and `B` in
|
428 |
+
descending order.
|
429 |
+
|
430 |
+
See Also
|
431 |
+
--------
|
432 |
+
orth
|
433 |
+
svd
|
434 |
+
|
435 |
+
Notes
|
436 |
+
-----
|
437 |
+
This computes the subspace angles according to the formula
|
438 |
+
provided in [1]_. For equivalence with MATLAB and Octave behavior,
|
439 |
+
use ``angles[0]``.
|
440 |
+
|
441 |
+
.. versionadded:: 1.0
|
442 |
+
|
443 |
+
References
|
444 |
+
----------
|
445 |
+
.. [1] Knyazev A, Argentati M (2002) Principal Angles between Subspaces
|
446 |
+
in an A-Based Scalar Product: Algorithms and Perturbation
|
447 |
+
Estimates. SIAM J. Sci. Comput. 23:2008-2040.
|
448 |
+
|
449 |
+
Examples
|
450 |
+
--------
|
451 |
+
An Hadamard matrix, which has orthogonal columns, so we expect that
|
452 |
+
the suspace angle to be :math:`\frac{\pi}{2}`:
|
453 |
+
|
454 |
+
>>> import numpy as np
|
455 |
+
>>> from scipy.linalg import hadamard, subspace_angles
|
456 |
+
>>> rng = np.random.default_rng()
|
457 |
+
>>> H = hadamard(4)
|
458 |
+
>>> print(H)
|
459 |
+
[[ 1 1 1 1]
|
460 |
+
[ 1 -1 1 -1]
|
461 |
+
[ 1 1 -1 -1]
|
462 |
+
[ 1 -1 -1 1]]
|
463 |
+
>>> np.rad2deg(subspace_angles(H[:, :2], H[:, 2:]))
|
464 |
+
array([ 90., 90.])
|
465 |
+
|
466 |
+
And the subspace angle of a matrix to itself should be zero:
|
467 |
+
|
468 |
+
>>> subspace_angles(H[:, :2], H[:, :2]) <= 2 * np.finfo(float).eps
|
469 |
+
array([ True, True], dtype=bool)
|
470 |
+
|
471 |
+
The angles between non-orthogonal subspaces are in between these extremes:
|
472 |
+
|
473 |
+
>>> x = rng.standard_normal((4, 3))
|
474 |
+
>>> np.rad2deg(subspace_angles(x[:, :2], x[:, [2]]))
|
475 |
+
array([ 55.832]) # random
|
476 |
+
"""
|
477 |
+
# Steps here omit the U and V calculation steps from the paper
|
478 |
+
|
479 |
+
# 1. Compute orthonormal bases of column-spaces
|
480 |
+
A = _asarray_validated(A, check_finite=True)
|
481 |
+
if len(A.shape) != 2:
|
482 |
+
raise ValueError(f'expected 2D array, got shape {A.shape}')
|
483 |
+
QA = orth(A)
|
484 |
+
del A
|
485 |
+
|
486 |
+
B = _asarray_validated(B, check_finite=True)
|
487 |
+
if len(B.shape) != 2:
|
488 |
+
raise ValueError(f'expected 2D array, got shape {B.shape}')
|
489 |
+
if len(B) != len(QA):
|
490 |
+
raise ValueError('A and B must have the same number of rows, got '
|
491 |
+
f'{QA.shape[0]} and {B.shape[0]}')
|
492 |
+
QB = orth(B)
|
493 |
+
del B
|
494 |
+
|
495 |
+
# 2. Compute SVD for cosine
|
496 |
+
QA_H_QB = dot(QA.T.conj(), QB)
|
497 |
+
sigma = svdvals(QA_H_QB)
|
498 |
+
|
499 |
+
# 3. Compute matrix B
|
500 |
+
if QA.shape[1] >= QB.shape[1]:
|
501 |
+
B = QB - dot(QA, QA_H_QB)
|
502 |
+
else:
|
503 |
+
B = QA - dot(QB, QA_H_QB.T.conj())
|
504 |
+
del QA, QB, QA_H_QB
|
505 |
+
|
506 |
+
# 4. Compute SVD for sine
|
507 |
+
mask = sigma ** 2 >= 0.5
|
508 |
+
if mask.any():
|
509 |
+
mu_arcsin = arcsin(clip(svdvals(B, overwrite_a=True), -1., 1.))
|
510 |
+
else:
|
511 |
+
mu_arcsin = 0.
|
512 |
+
|
513 |
+
# 5. Compute the principal angles
|
514 |
+
# with reverse ordering of sigma because smallest sigma belongs to largest
|
515 |
+
# ang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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Frechet derivative of the matrix exponential."""
|
2 |
+
import numpy as np
|
3 |
+
import scipy.linalg
|
4 |
+
|
5 |
+
__all__ = ['expm_frechet', 'expm_cond']
|
6 |
+
|
7 |
+
|
8 |
+
def expm_frechet(A, E, method=None, compute_expm=True, check_finite=True):
|
9 |
+
"""
|
10 |
+
Frechet derivative of the matrix exponential of A in the direction E.
|
11 |
+
|
12 |
+
Parameters
|
13 |
+
----------
|
14 |
+
A : (N, N) array_like
|
15 |
+
Matrix of which to take the matrix exponential.
|
16 |
+
E : (N, N) array_like
|
17 |
+
Matrix direction in which to take the Frechet derivative.
|
18 |
+
method : str, optional
|
19 |
+
Choice of algorithm. Should be one of
|
20 |
+
|
21 |
+
- `SPS` (default)
|
22 |
+
- `blockEnlarge`
|
23 |
+
|
24 |
+
compute_expm : bool, optional
|
25 |
+
Whether to compute also `expm_A` in addition to `expm_frechet_AE`.
|
26 |
+
Default is True.
|
27 |
+
check_finite : bool, optional
|
28 |
+
Whether to check that the input matrix contains only finite numbers.
|
29 |
+
Disabling may give a performance gain, but may result in problems
|
30 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
31 |
+
|
32 |
+
Returns
|
33 |
+
-------
|
34 |
+
expm_A : ndarray
|
35 |
+
Matrix exponential of A.
|
36 |
+
expm_frechet_AE : ndarray
|
37 |
+
Frechet derivative of the matrix exponential of A in the direction E.
|
38 |
+
For ``compute_expm = False``, only `expm_frechet_AE` is returned.
|
39 |
+
|
40 |
+
See Also
|
41 |
+
--------
|
42 |
+
expm : Compute the exponential of a matrix.
|
43 |
+
|
44 |
+
Notes
|
45 |
+
-----
|
46 |
+
This section describes the available implementations that can be selected
|
47 |
+
by the `method` parameter. The default method is *SPS*.
|
48 |
+
|
49 |
+
Method *blockEnlarge* is a naive algorithm.
|
50 |
+
|
51 |
+
Method *SPS* is Scaling-Pade-Squaring [1]_.
|
52 |
+
It is a sophisticated implementation which should take
|
53 |
+
only about 3/8 as much time as the naive implementation.
|
54 |
+
The asymptotics are the same.
|
55 |
+
|
56 |
+
.. versionadded:: 0.13.0
|
57 |
+
|
58 |
+
References
|
59 |
+
----------
|
60 |
+
.. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009)
|
61 |
+
Computing the Frechet Derivative of the Matrix Exponential,
|
62 |
+
with an application to Condition Number Estimation.
|
63 |
+
SIAM Journal On Matrix Analysis and Applications.,
|
64 |
+
30 (4). pp. 1639-1657. ISSN 1095-7162
|
65 |
+
|
66 |
+
Examples
|
67 |
+
--------
|
68 |
+
>>> import numpy as np
|
69 |
+
>>> from scipy import linalg
|
70 |
+
>>> rng = np.random.default_rng()
|
71 |
+
|
72 |
+
>>> A = rng.standard_normal((3, 3))
|
73 |
+
>>> E = rng.standard_normal((3, 3))
|
74 |
+
>>> expm_A, expm_frechet_AE = linalg.expm_frechet(A, E)
|
75 |
+
>>> expm_A.shape, expm_frechet_AE.shape
|
76 |
+
((3, 3), (3, 3))
|
77 |
+
|
78 |
+
Create a 6x6 matrix containing [[A, E], [0, A]]:
|
79 |
+
|
80 |
+
>>> M = np.zeros((6, 6))
|
81 |
+
>>> M[:3, :3] = A
|
82 |
+
>>> M[:3, 3:] = E
|
83 |
+
>>> M[3:, 3:] = A
|
84 |
+
|
85 |
+
>>> expm_M = linalg.expm(M)
|
86 |
+
>>> np.allclose(expm_A, expm_M[:3, :3])
|
87 |
+
True
|
88 |
+
>>> np.allclose(expm_frechet_AE, expm_M[:3, 3:])
|
89 |
+
True
|
90 |
+
|
91 |
+
"""
|
92 |
+
if check_finite:
|
93 |
+
A = np.asarray_chkfinite(A)
|
94 |
+
E = np.asarray_chkfinite(E)
|
95 |
+
else:
|
96 |
+
A = np.asarray(A)
|
97 |
+
E = np.asarray(E)
|
98 |
+
if A.ndim != 2 or A.shape[0] != A.shape[1]:
|
99 |
+
raise ValueError('expected A to be a square matrix')
|
100 |
+
if E.ndim != 2 or E.shape[0] != E.shape[1]:
|
101 |
+
raise ValueError('expected E to be a square matrix')
|
102 |
+
if A.shape != E.shape:
|
103 |
+
raise ValueError('expected A and E to be the same shape')
|
104 |
+
if method is None:
|
105 |
+
method = 'SPS'
|
106 |
+
if method == 'SPS':
|
107 |
+
expm_A, expm_frechet_AE = expm_frechet_algo_64(A, E)
|
108 |
+
elif method == 'blockEnlarge':
|
109 |
+
expm_A, expm_frechet_AE = expm_frechet_block_enlarge(A, E)
|
110 |
+
else:
|
111 |
+
raise ValueError('Unknown implementation %s' % method)
|
112 |
+
if compute_expm:
|
113 |
+
return expm_A, expm_frechet_AE
|
114 |
+
else:
|
115 |
+
return expm_frechet_AE
|
116 |
+
|
117 |
+
|
118 |
+
def expm_frechet_block_enlarge(A, E):
|
119 |
+
"""
|
120 |
+
This is a helper function, mostly for testing and profiling.
|
121 |
+
Return expm(A), frechet(A, E)
|
122 |
+
"""
|
123 |
+
n = A.shape[0]
|
124 |
+
M = np.vstack([
|
125 |
+
np.hstack([A, E]),
|
126 |
+
np.hstack([np.zeros_like(A), A])])
|
127 |
+
expm_M = scipy.linalg.expm(M)
|
128 |
+
return expm_M[:n, :n], expm_M[:n, n:]
|
129 |
+
|
130 |
+
|
131 |
+
"""
|
132 |
+
Maximal values ell_m of ||2**-s A|| such that the backward error bound
|
133 |
+
does not exceed 2**-53.
|
134 |
+
"""
|
135 |
+
ell_table_61 = (
|
136 |
+
None,
|
137 |
+
# 1
|
138 |
+
2.11e-8,
|
139 |
+
3.56e-4,
|
140 |
+
1.08e-2,
|
141 |
+
6.49e-2,
|
142 |
+
2.00e-1,
|
143 |
+
4.37e-1,
|
144 |
+
7.83e-1,
|
145 |
+
1.23e0,
|
146 |
+
1.78e0,
|
147 |
+
2.42e0,
|
148 |
+
# 11
|
149 |
+
3.13e0,
|
150 |
+
3.90e0,
|
151 |
+
4.74e0,
|
152 |
+
5.63e0,
|
153 |
+
6.56e0,
|
154 |
+
7.52e0,
|
155 |
+
8.53e0,
|
156 |
+
9.56e0,
|
157 |
+
1.06e1,
|
158 |
+
1.17e1,
|
159 |
+
)
|
160 |
+
|
161 |
+
|
162 |
+
# The b vectors and U and V are copypasted
|
163 |
+
# from scipy.sparse.linalg.matfuncs.py.
|
164 |
+
# M, Lu, Lv follow (6.11), (6.12), (6.13), (3.3)
|
165 |
+
|
166 |
+
def _diff_pade3(A, E, ident):
|
167 |
+
b = (120., 60., 12., 1.)
|
168 |
+
A2 = A.dot(A)
|
169 |
+
M2 = np.dot(A, E) + np.dot(E, A)
|
170 |
+
U = A.dot(b[3]*A2 + b[1]*ident)
|
171 |
+
V = b[2]*A2 + b[0]*ident
|
172 |
+
Lu = A.dot(b[3]*M2) + E.dot(b[3]*A2 + b[1]*ident)
|
173 |
+
Lv = b[2]*M2
|
174 |
+
return U, V, Lu, Lv
|
175 |
+
|
176 |
+
|
177 |
+
def _diff_pade5(A, E, ident):
|
178 |
+
b = (30240., 15120., 3360., 420., 30., 1.)
|
179 |
+
A2 = A.dot(A)
|
180 |
+
M2 = np.dot(A, E) + np.dot(E, A)
|
181 |
+
A4 = np.dot(A2, A2)
|
182 |
+
M4 = np.dot(A2, M2) + np.dot(M2, A2)
|
183 |
+
U = A.dot(b[5]*A4 + b[3]*A2 + b[1]*ident)
|
184 |
+
V = b[4]*A4 + b[2]*A2 + b[0]*ident
|
185 |
+
Lu = (A.dot(b[5]*M4 + b[3]*M2) +
|
186 |
+
E.dot(b[5]*A4 + b[3]*A2 + b[1]*ident))
|
187 |
+
Lv = b[4]*M4 + b[2]*M2
|
188 |
+
return U, V, Lu, Lv
|
189 |
+
|
190 |
+
|
191 |
+
def _diff_pade7(A, E, ident):
|
192 |
+
b = (17297280., 8648640., 1995840., 277200., 25200., 1512., 56., 1.)
|
193 |
+
A2 = A.dot(A)
|
194 |
+
M2 = np.dot(A, E) + np.dot(E, A)
|
195 |
+
A4 = np.dot(A2, A2)
|
196 |
+
M4 = np.dot(A2, M2) + np.dot(M2, A2)
|
197 |
+
A6 = np.dot(A2, A4)
|
198 |
+
M6 = np.dot(A4, M2) + np.dot(M4, A2)
|
199 |
+
U = A.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)
|
200 |
+
V = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
|
201 |
+
Lu = (A.dot(b[7]*M6 + b[5]*M4 + b[3]*M2) +
|
202 |
+
E.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident))
|
203 |
+
Lv = b[6]*M6 + b[4]*M4 + b[2]*M2
|
204 |
+
return U, V, Lu, Lv
|
205 |
+
|
206 |
+
|
207 |
+
def _diff_pade9(A, E, ident):
|
208 |
+
b = (17643225600., 8821612800., 2075673600., 302702400., 30270240.,
|
209 |
+
2162160., 110880., 3960., 90., 1.)
|
210 |
+
A2 = A.dot(A)
|
211 |
+
M2 = np.dot(A, E) + np.dot(E, A)
|
212 |
+
A4 = np.dot(A2, A2)
|
213 |
+
M4 = np.dot(A2, M2) + np.dot(M2, A2)
|
214 |
+
A6 = np.dot(A2, A4)
|
215 |
+
M6 = np.dot(A4, M2) + np.dot(M4, A2)
|
216 |
+
A8 = np.dot(A4, A4)
|
217 |
+
M8 = np.dot(A4, M4) + np.dot(M4, A4)
|
218 |
+
U = A.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)
|
219 |
+
V = b[8]*A8 + b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
|
220 |
+
Lu = (A.dot(b[9]*M8 + b[7]*M6 + b[5]*M4 + b[3]*M2) +
|
221 |
+
E.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident))
|
222 |
+
Lv = b[8]*M8 + b[6]*M6 + b[4]*M4 + b[2]*M2
|
223 |
+
return U, V, Lu, Lv
|
224 |
+
|
225 |
+
|
226 |
+
def expm_frechet_algo_64(A, E):
|
227 |
+
n = A.shape[0]
|
228 |
+
s = None
|
229 |
+
ident = np.identity(n)
|
230 |
+
A_norm_1 = scipy.linalg.norm(A, 1)
|
231 |
+
m_pade_pairs = (
|
232 |
+
(3, _diff_pade3),
|
233 |
+
(5, _diff_pade5),
|
234 |
+
(7, _diff_pade7),
|
235 |
+
(9, _diff_pade9))
|
236 |
+
for m, pade in m_pade_pairs:
|
237 |
+
if A_norm_1 <= ell_table_61[m]:
|
238 |
+
U, V, Lu, Lv = pade(A, E, ident)
|
239 |
+
s = 0
|
240 |
+
break
|
241 |
+
if s is None:
|
242 |
+
# scaling
|
243 |
+
s = max(0, int(np.ceil(np.log2(A_norm_1 / ell_table_61[13]))))
|
244 |
+
A = A * 2.0**-s
|
245 |
+
E = E * 2.0**-s
|
246 |
+
# pade order 13
|
247 |
+
A2 = np.dot(A, A)
|
248 |
+
M2 = np.dot(A, E) + np.dot(E, A)
|
249 |
+
A4 = np.dot(A2, A2)
|
250 |
+
M4 = np.dot(A2, M2) + np.dot(M2, A2)
|
251 |
+
A6 = np.dot(A2, A4)
|
252 |
+
M6 = np.dot(A4, M2) + np.dot(M4, A2)
|
253 |
+
b = (64764752532480000., 32382376266240000., 7771770303897600.,
|
254 |
+
1187353796428800., 129060195264000., 10559470521600.,
|
255 |
+
670442572800., 33522128640., 1323241920., 40840800., 960960.,
|
256 |
+
16380., 182., 1.)
|
257 |
+
W1 = b[13]*A6 + b[11]*A4 + b[9]*A2
|
258 |
+
W2 = b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident
|
259 |
+
Z1 = b[12]*A6 + b[10]*A4 + b[8]*A2
|
260 |
+
Z2 = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
|
261 |
+
W = np.dot(A6, W1) + W2
|
262 |
+
U = np.dot(A, W)
|
263 |
+
V = np.dot(A6, Z1) + Z2
|
264 |
+
Lw1 = b[13]*M6 + b[11]*M4 + b[9]*M2
|
265 |
+
Lw2 = b[7]*M6 + b[5]*M4 + b[3]*M2
|
266 |
+
Lz1 = b[12]*M6 + b[10]*M4 + b[8]*M2
|
267 |
+
Lz2 = b[6]*M6 + b[4]*M4 + b[2]*M2
|
268 |
+
Lw = np.dot(A6, Lw1) + np.dot(M6, W1) + Lw2
|
269 |
+
Lu = np.dot(A, Lw) + np.dot(E, W)
|
270 |
+
Lv = np.dot(A6, Lz1) + np.dot(M6, Z1) + Lz2
|
271 |
+
# factor once and solve twice
|
272 |
+
lu_piv = scipy.linalg.lu_factor(-U + V)
|
273 |
+
R = scipy.linalg.lu_solve(lu_piv, U + V)
|
274 |
+
L = scipy.linalg.lu_solve(lu_piv, Lu + Lv + np.dot((Lu - Lv), R))
|
275 |
+
# squaring
|
276 |
+
for k in range(s):
|
277 |
+
L = np.dot(R, L) + np.dot(L, R)
|
278 |
+
R = np.dot(R, R)
|
279 |
+
return R, L
|
280 |
+
|
281 |
+
|
282 |
+
def vec(M):
|
283 |
+
"""
|
284 |
+
Stack columns of M to construct a single vector.
|
285 |
+
|
286 |
+
This is somewhat standard notation in linear algebra.
|
287 |
+
|
288 |
+
Parameters
|
289 |
+
----------
|
290 |
+
M : 2-D array_like
|
291 |
+
Input matrix
|
292 |
+
|
293 |
+
Returns
|
294 |
+
-------
|
295 |
+
v : 1-D ndarray
|
296 |
+
Output vector
|
297 |
+
|
298 |
+
"""
|
299 |
+
return M.T.ravel()
|
300 |
+
|
301 |
+
|
302 |
+
def expm_frechet_kronform(A, method=None, check_finite=True):
|
303 |
+
"""
|
304 |
+
Construct the Kronecker form of the Frechet derivative of expm.
|
305 |
+
|
306 |
+
Parameters
|
307 |
+
----------
|
308 |
+
A : array_like with shape (N, N)
|
309 |
+
Matrix to be expm'd.
|
310 |
+
method : str, optional
|
311 |
+
Extra keyword to be passed to expm_frechet.
|
312 |
+
check_finite : bool, optional
|
313 |
+
Whether to check that the input matrix contains only finite numbers.
|
314 |
+
Disabling may give a performance gain, but may result in problems
|
315 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
316 |
+
|
317 |
+
Returns
|
318 |
+
-------
|
319 |
+
K : 2-D ndarray with shape (N*N, N*N)
|
320 |
+
Kronecker form of the Frechet derivative of the matrix exponential.
|
321 |
+
|
322 |
+
Notes
|
323 |
+
-----
|
324 |
+
This function is used to help compute the condition number
|
325 |
+
of the matrix exponential.
|
326 |
+
|
327 |
+
See Also
|
328 |
+
--------
|
329 |
+
expm : Compute a matrix exponential.
|
330 |
+
expm_frechet : Compute the Frechet derivative of the matrix exponential.
|
331 |
+
expm_cond : Compute the relative condition number of the matrix exponential
|
332 |
+
in the Frobenius norm.
|
333 |
+
|
334 |
+
"""
|
335 |
+
if check_finite:
|
336 |
+
A = np.asarray_chkfinite(A)
|
337 |
+
else:
|
338 |
+
A = np.asarray(A)
|
339 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
340 |
+
raise ValueError('expected a square matrix')
|
341 |
+
|
342 |
+
n = A.shape[0]
|
343 |
+
ident = np.identity(n)
|
344 |
+
cols = []
|
345 |
+
for i in range(n):
|
346 |
+
for j in range(n):
|
347 |
+
E = np.outer(ident[i], ident[j])
|
348 |
+
F = expm_frechet(A, E,
|
349 |
+
method=method, compute_expm=False, check_finite=False)
|
350 |
+
cols.append(vec(F))
|
351 |
+
return np.vstack(cols).T
|
352 |
+
|
353 |
+
|
354 |
+
def expm_cond(A, check_finite=True):
|
355 |
+
"""
|
356 |
+
Relative condition number of the matrix exponential in the Frobenius norm.
|
357 |
+
|
358 |
+
Parameters
|
359 |
+
----------
|
360 |
+
A : 2-D array_like
|
361 |
+
Square input matrix with shape (N, N).
|
362 |
+
check_finite : bool, optional
|
363 |
+
Whether to check that the input matrix contains only finite numbers.
|
364 |
+
Disabling may give a performance gain, but may result in problems
|
365 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
366 |
+
|
367 |
+
Returns
|
368 |
+
-------
|
369 |
+
kappa : float
|
370 |
+
The relative condition number of the matrix exponential
|
371 |
+
in the Frobenius norm
|
372 |
+
|
373 |
+
See Also
|
374 |
+
--------
|
375 |
+
expm : Compute the exponential of a matrix.
|
376 |
+
expm_frechet : Compute the Frechet derivative of the matrix exponential.
|
377 |
+
|
378 |
+
Notes
|
379 |
+
-----
|
380 |
+
A faster estimate for the condition number in the 1-norm
|
381 |
+
has been published but is not yet implemented in SciPy.
|
382 |
+
|
383 |
+
.. versionadded:: 0.14.0
|
384 |
+
|
385 |
+
Examples
|
386 |
+
--------
|
387 |
+
>>> import numpy as np
|
388 |
+
>>> from scipy.linalg import expm_cond
|
389 |
+
>>> A = np.array([[-0.3, 0.2, 0.6], [0.6, 0.3, -0.1], [-0.7, 1.2, 0.9]])
|
390 |
+
>>> k = expm_cond(A)
|
391 |
+
>>> k
|
392 |
+
1.7787805864469866
|
393 |
+
|
394 |
+
"""
|
395 |
+
if check_finite:
|
396 |
+
A = np.asarray_chkfinite(A)
|
397 |
+
else:
|
398 |
+
A = np.asarray(A)
|
399 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
400 |
+
raise ValueError('expected a square matrix')
|
401 |
+
|
402 |
+
X = scipy.linalg.expm(A)
|
403 |
+
K = expm_frechet_kronform(A, check_finite=False)
|
404 |
+
|
405 |
+
# The following norm choices are deliberate.
|
406 |
+
# The norms of A and X are Frobenius norms,
|
407 |
+
# and the norm of K is the induced 2-norm.
|
408 |
+
A_norm = scipy.linalg.norm(A, 'fro')
|
409 |
+
X_norm = scipy.linalg.norm(X, 'fro')
|
410 |
+
K_norm = scipy.linalg.norm(K, 2)
|
411 |
+
|
412 |
+
kappa = (K_norm * A_norm) / X_norm
|
413 |
+
return kappa
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_interpolative.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (457 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_interpolative_backend.py
ADDED
@@ -0,0 +1,1681 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#******************************************************************************
|
2 |
+
# Copyright (C) 2013 Kenneth L. Ho
|
3 |
+
#
|
4 |
+
# Redistribution and use in source and binary forms, with or without
|
5 |
+
# modification, are permitted provided that the following conditions are met:
|
6 |
+
#
|
7 |
+
# Redistributions of source code must retain the above copyright notice, this
|
8 |
+
# list of conditions and the following disclaimer. Redistributions in binary
|
9 |
+
# form must reproduce the above copyright notice, this list of conditions and
|
10 |
+
# the following disclaimer in the documentation and/or other materials
|
11 |
+
# provided with the distribution.
|
12 |
+
#
|
13 |
+
# None of the names of the copyright holders may be used to endorse or
|
14 |
+
# promote products derived from this software without specific prior written
|
15 |
+
# permission.
|
16 |
+
#
|
17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
18 |
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
19 |
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
20 |
+
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
21 |
+
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
22 |
+
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
23 |
+
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
24 |
+
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
25 |
+
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
26 |
+
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
+
#******************************************************************************
|
29 |
+
|
30 |
+
"""
|
31 |
+
Direct wrappers for Fortran `id_dist` backend.
|
32 |
+
"""
|
33 |
+
|
34 |
+
import scipy.linalg._interpolative as _id
|
35 |
+
import numpy as np
|
36 |
+
|
37 |
+
_RETCODE_ERROR = RuntimeError("nonzero return code")
|
38 |
+
|
39 |
+
|
40 |
+
def _asfortranarray_copy(A):
|
41 |
+
"""
|
42 |
+
Same as np.asfortranarray, but ensure a copy
|
43 |
+
"""
|
44 |
+
A = np.asarray(A)
|
45 |
+
if A.flags.f_contiguous:
|
46 |
+
A = A.copy(order="F")
|
47 |
+
else:
|
48 |
+
A = np.asfortranarray(A)
|
49 |
+
return A
|
50 |
+
|
51 |
+
|
52 |
+
#------------------------------------------------------------------------------
|
53 |
+
# id_rand.f
|
54 |
+
#------------------------------------------------------------------------------
|
55 |
+
|
56 |
+
def id_srand(n):
|
57 |
+
"""
|
58 |
+
Generate standard uniform pseudorandom numbers via a very efficient lagged
|
59 |
+
Fibonacci method.
|
60 |
+
|
61 |
+
:param n:
|
62 |
+
Number of pseudorandom numbers to generate.
|
63 |
+
:type n: int
|
64 |
+
|
65 |
+
:return:
|
66 |
+
Pseudorandom numbers.
|
67 |
+
:rtype: :class:`numpy.ndarray`
|
68 |
+
"""
|
69 |
+
return _id.id_srand(n)
|
70 |
+
|
71 |
+
|
72 |
+
def id_srandi(t):
|
73 |
+
"""
|
74 |
+
Initialize seed values for :func:`id_srand` (any appropriately random
|
75 |
+
numbers will do).
|
76 |
+
|
77 |
+
:param t:
|
78 |
+
Array of 55 seed values.
|
79 |
+
:type t: :class:`numpy.ndarray`
|
80 |
+
"""
|
81 |
+
t = np.asfortranarray(t)
|
82 |
+
_id.id_srandi(t)
|
83 |
+
|
84 |
+
|
85 |
+
def id_srando():
|
86 |
+
"""
|
87 |
+
Reset seed values to their original values.
|
88 |
+
"""
|
89 |
+
_id.id_srando()
|
90 |
+
|
91 |
+
|
92 |
+
#------------------------------------------------------------------------------
|
93 |
+
# idd_frm.f
|
94 |
+
#------------------------------------------------------------------------------
|
95 |
+
|
96 |
+
def idd_frm(n, w, x):
|
97 |
+
"""
|
98 |
+
Transform real vector via a composition of Rokhlin's random transform,
|
99 |
+
random subselection, and an FFT.
|
100 |
+
|
101 |
+
In contrast to :func:`idd_sfrm`, this routine works best when the length of
|
102 |
+
the transformed vector is the power-of-two integer output by
|
103 |
+
:func:`idd_frmi`, or when the length is not specified but instead
|
104 |
+
determined a posteriori from the output. The returned transformed vector is
|
105 |
+
randomly permuted.
|
106 |
+
|
107 |
+
:param n:
|
108 |
+
Greatest power-of-two integer satisfying `n <= x.size` as obtained from
|
109 |
+
:func:`idd_frmi`; `n` is also the length of the output vector.
|
110 |
+
:type n: int
|
111 |
+
:param w:
|
112 |
+
Initialization array constructed by :func:`idd_frmi`.
|
113 |
+
:type w: :class:`numpy.ndarray`
|
114 |
+
:param x:
|
115 |
+
Vector to be transformed.
|
116 |
+
:type x: :class:`numpy.ndarray`
|
117 |
+
|
118 |
+
:return:
|
119 |
+
Transformed vector.
|
120 |
+
:rtype: :class:`numpy.ndarray`
|
121 |
+
"""
|
122 |
+
return _id.idd_frm(n, w, x)
|
123 |
+
|
124 |
+
|
125 |
+
def idd_sfrm(l, n, w, x):
|
126 |
+
"""
|
127 |
+
Transform real vector via a composition of Rokhlin's random transform,
|
128 |
+
random subselection, and an FFT.
|
129 |
+
|
130 |
+
In contrast to :func:`idd_frm`, this routine works best when the length of
|
131 |
+
the transformed vector is known a priori.
|
132 |
+
|
133 |
+
:param l:
|
134 |
+
Length of transformed vector, satisfying `l <= n`.
|
135 |
+
:type l: int
|
136 |
+
:param n:
|
137 |
+
Greatest power-of-two integer satisfying `n <= x.size` as obtained from
|
138 |
+
:func:`idd_sfrmi`.
|
139 |
+
:type n: int
|
140 |
+
:param w:
|
141 |
+
Initialization array constructed by :func:`idd_sfrmi`.
|
142 |
+
:type w: :class:`numpy.ndarray`
|
143 |
+
:param x:
|
144 |
+
Vector to be transformed.
|
145 |
+
:type x: :class:`numpy.ndarray`
|
146 |
+
|
147 |
+
:return:
|
148 |
+
Transformed vector.
|
149 |
+
:rtype: :class:`numpy.ndarray`
|
150 |
+
"""
|
151 |
+
return _id.idd_sfrm(l, n, w, x)
|
152 |
+
|
153 |
+
|
154 |
+
def idd_frmi(m):
|
155 |
+
"""
|
156 |
+
Initialize data for :func:`idd_frm`.
|
157 |
+
|
158 |
+
:param m:
|
159 |
+
Length of vector to be transformed.
|
160 |
+
:type m: int
|
161 |
+
|
162 |
+
:return:
|
163 |
+
Greatest power-of-two integer `n` satisfying `n <= m`.
|
164 |
+
:rtype: int
|
165 |
+
:return:
|
166 |
+
Initialization array to be used by :func:`idd_frm`.
|
167 |
+
:rtype: :class:`numpy.ndarray`
|
168 |
+
"""
|
169 |
+
return _id.idd_frmi(m)
|
170 |
+
|
171 |
+
|
172 |
+
def idd_sfrmi(l, m):
|
173 |
+
"""
|
174 |
+
Initialize data for :func:`idd_sfrm`.
|
175 |
+
|
176 |
+
:param l:
|
177 |
+
Length of output transformed vector.
|
178 |
+
:type l: int
|
179 |
+
:param m:
|
180 |
+
Length of the vector to be transformed.
|
181 |
+
:type m: int
|
182 |
+
|
183 |
+
:return:
|
184 |
+
Greatest power-of-two integer `n` satisfying `n <= m`.
|
185 |
+
:rtype: int
|
186 |
+
:return:
|
187 |
+
Initialization array to be used by :func:`idd_sfrm`.
|
188 |
+
:rtype: :class:`numpy.ndarray`
|
189 |
+
"""
|
190 |
+
return _id.idd_sfrmi(l, m)
|
191 |
+
|
192 |
+
|
193 |
+
#------------------------------------------------------------------------------
|
194 |
+
# idd_id.f
|
195 |
+
#------------------------------------------------------------------------------
|
196 |
+
|
197 |
+
def iddp_id(eps, A):
|
198 |
+
"""
|
199 |
+
Compute ID of a real matrix to a specified relative precision.
|
200 |
+
|
201 |
+
:param eps:
|
202 |
+
Relative precision.
|
203 |
+
:type eps: float
|
204 |
+
:param A:
|
205 |
+
Matrix.
|
206 |
+
:type A: :class:`numpy.ndarray`
|
207 |
+
|
208 |
+
:return:
|
209 |
+
Rank of ID.
|
210 |
+
:rtype: int
|
211 |
+
:return:
|
212 |
+
Column index array.
|
213 |
+
:rtype: :class:`numpy.ndarray`
|
214 |
+
:return:
|
215 |
+
Interpolation coefficients.
|
216 |
+
:rtype: :class:`numpy.ndarray`
|
217 |
+
"""
|
218 |
+
A = _asfortranarray_copy(A)
|
219 |
+
k, idx, rnorms = _id.iddp_id(eps, A)
|
220 |
+
n = A.shape[1]
|
221 |
+
proj = A.T.ravel()[:k*(n-k)].reshape((k, n-k), order='F')
|
222 |
+
return k, idx, proj
|
223 |
+
|
224 |
+
|
225 |
+
def iddr_id(A, k):
|
226 |
+
"""
|
227 |
+
Compute ID of a real matrix to a specified rank.
|
228 |
+
|
229 |
+
:param A:
|
230 |
+
Matrix.
|
231 |
+
:type A: :class:`numpy.ndarray`
|
232 |
+
:param k:
|
233 |
+
Rank of ID.
|
234 |
+
:type k: int
|
235 |
+
|
236 |
+
:return:
|
237 |
+
Column index array.
|
238 |
+
:rtype: :class:`numpy.ndarray`
|
239 |
+
:return:
|
240 |
+
Interpolation coefficients.
|
241 |
+
:rtype: :class:`numpy.ndarray`
|
242 |
+
"""
|
243 |
+
A = _asfortranarray_copy(A)
|
244 |
+
idx, rnorms = _id.iddr_id(A, k)
|
245 |
+
n = A.shape[1]
|
246 |
+
proj = A.T.ravel()[:k*(n-k)].reshape((k, n-k), order='F')
|
247 |
+
return idx, proj
|
248 |
+
|
249 |
+
|
250 |
+
def idd_reconid(B, idx, proj):
|
251 |
+
"""
|
252 |
+
Reconstruct matrix from real ID.
|
253 |
+
|
254 |
+
:param B:
|
255 |
+
Skeleton matrix.
|
256 |
+
:type B: :class:`numpy.ndarray`
|
257 |
+
:param idx:
|
258 |
+
Column index array.
|
259 |
+
:type idx: :class:`numpy.ndarray`
|
260 |
+
:param proj:
|
261 |
+
Interpolation coefficients.
|
262 |
+
:type proj: :class:`numpy.ndarray`
|
263 |
+
|
264 |
+
:return:
|
265 |
+
Reconstructed matrix.
|
266 |
+
:rtype: :class:`numpy.ndarray`
|
267 |
+
"""
|
268 |
+
B = np.asfortranarray(B)
|
269 |
+
if proj.size > 0:
|
270 |
+
return _id.idd_reconid(B, idx, proj)
|
271 |
+
else:
|
272 |
+
return B[:, np.argsort(idx)]
|
273 |
+
|
274 |
+
|
275 |
+
def idd_reconint(idx, proj):
|
276 |
+
"""
|
277 |
+
Reconstruct interpolation matrix from real ID.
|
278 |
+
|
279 |
+
:param idx:
|
280 |
+
Column index array.
|
281 |
+
:type idx: :class:`numpy.ndarray`
|
282 |
+
:param proj:
|
283 |
+
Interpolation coefficients.
|
284 |
+
:type proj: :class:`numpy.ndarray`
|
285 |
+
|
286 |
+
:return:
|
287 |
+
Interpolation matrix.
|
288 |
+
:rtype: :class:`numpy.ndarray`
|
289 |
+
"""
|
290 |
+
return _id.idd_reconint(idx, proj)
|
291 |
+
|
292 |
+
|
293 |
+
def idd_copycols(A, k, idx):
|
294 |
+
"""
|
295 |
+
Reconstruct skeleton matrix from real ID.
|
296 |
+
|
297 |
+
:param A:
|
298 |
+
Original matrix.
|
299 |
+
:type A: :class:`numpy.ndarray`
|
300 |
+
:param k:
|
301 |
+
Rank of ID.
|
302 |
+
:type k: int
|
303 |
+
:param idx:
|
304 |
+
Column index array.
|
305 |
+
:type idx: :class:`numpy.ndarray`
|
306 |
+
|
307 |
+
:return:
|
308 |
+
Skeleton matrix.
|
309 |
+
:rtype: :class:`numpy.ndarray`
|
310 |
+
"""
|
311 |
+
A = np.asfortranarray(A)
|
312 |
+
return _id.idd_copycols(A, k, idx)
|
313 |
+
|
314 |
+
|
315 |
+
#------------------------------------------------------------------------------
|
316 |
+
# idd_id2svd.f
|
317 |
+
#------------------------------------------------------------------------------
|
318 |
+
|
319 |
+
def idd_id2svd(B, idx, proj):
|
320 |
+
"""
|
321 |
+
Convert real ID to SVD.
|
322 |
+
|
323 |
+
:param B:
|
324 |
+
Skeleton matrix.
|
325 |
+
:type B: :class:`numpy.ndarray`
|
326 |
+
:param idx:
|
327 |
+
Column index array.
|
328 |
+
:type idx: :class:`numpy.ndarray`
|
329 |
+
:param proj:
|
330 |
+
Interpolation coefficients.
|
331 |
+
:type proj: :class:`numpy.ndarray`
|
332 |
+
|
333 |
+
:return:
|
334 |
+
Left singular vectors.
|
335 |
+
:rtype: :class:`numpy.ndarray`
|
336 |
+
:return:
|
337 |
+
Right singular vectors.
|
338 |
+
:rtype: :class:`numpy.ndarray`
|
339 |
+
:return:
|
340 |
+
Singular values.
|
341 |
+
:rtype: :class:`numpy.ndarray`
|
342 |
+
"""
|
343 |
+
B = np.asfortranarray(B)
|
344 |
+
U, V, S, ier = _id.idd_id2svd(B, idx, proj)
|
345 |
+
if ier:
|
346 |
+
raise _RETCODE_ERROR
|
347 |
+
return U, V, S
|
348 |
+
|
349 |
+
|
350 |
+
#------------------------------------------------------------------------------
|
351 |
+
# idd_snorm.f
|
352 |
+
#------------------------------------------------------------------------------
|
353 |
+
|
354 |
+
def idd_snorm(m, n, matvect, matvec, its=20):
|
355 |
+
"""
|
356 |
+
Estimate spectral norm of a real matrix by the randomized power method.
|
357 |
+
|
358 |
+
:param m:
|
359 |
+
Matrix row dimension.
|
360 |
+
:type m: int
|
361 |
+
:param n:
|
362 |
+
Matrix column dimension.
|
363 |
+
:type n: int
|
364 |
+
:param matvect:
|
365 |
+
Function to apply the matrix transpose to a vector, with call signature
|
366 |
+
`y = matvect(x)`, where `x` and `y` are the input and output vectors,
|
367 |
+
respectively.
|
368 |
+
:type matvect: function
|
369 |
+
:param matvec:
|
370 |
+
Function to apply the matrix to a vector, with call signature
|
371 |
+
`y = matvec(x)`, where `x` and `y` are the input and output vectors,
|
372 |
+
respectively.
|
373 |
+
:type matvec: function
|
374 |
+
:param its:
|
375 |
+
Number of power method iterations.
|
376 |
+
:type its: int
|
377 |
+
|
378 |
+
:return:
|
379 |
+
Spectral norm estimate.
|
380 |
+
:rtype: float
|
381 |
+
"""
|
382 |
+
snorm, v = _id.idd_snorm(m, n, matvect, matvec, its)
|
383 |
+
return snorm
|
384 |
+
|
385 |
+
|
386 |
+
def idd_diffsnorm(m, n, matvect, matvect2, matvec, matvec2, its=20):
|
387 |
+
"""
|
388 |
+
Estimate spectral norm of the difference of two real matrices by the
|
389 |
+
randomized power method.
|
390 |
+
|
391 |
+
:param m:
|
392 |
+
Matrix row dimension.
|
393 |
+
:type m: int
|
394 |
+
:param n:
|
395 |
+
Matrix column dimension.
|
396 |
+
:type n: int
|
397 |
+
:param matvect:
|
398 |
+
Function to apply the transpose of the first matrix to a vector, with
|
399 |
+
call signature `y = matvect(x)`, where `x` and `y` are the input and
|
400 |
+
output vectors, respectively.
|
401 |
+
:type matvect: function
|
402 |
+
:param matvect2:
|
403 |
+
Function to apply the transpose of the second matrix to a vector, with
|
404 |
+
call signature `y = matvect2(x)`, where `x` and `y` are the input and
|
405 |
+
output vectors, respectively.
|
406 |
+
:type matvect2: function
|
407 |
+
:param matvec:
|
408 |
+
Function to apply the first matrix to a vector, with call signature
|
409 |
+
`y = matvec(x)`, where `x` and `y` are the input and output vectors,
|
410 |
+
respectively.
|
411 |
+
:type matvec: function
|
412 |
+
:param matvec2:
|
413 |
+
Function to apply the second matrix to a vector, with call signature
|
414 |
+
`y = matvec2(x)`, where `x` and `y` are the input and output vectors,
|
415 |
+
respectively.
|
416 |
+
:type matvec2: function
|
417 |
+
:param its:
|
418 |
+
Number of power method iterations.
|
419 |
+
:type its: int
|
420 |
+
|
421 |
+
:return:
|
422 |
+
Spectral norm estimate of matrix difference.
|
423 |
+
:rtype: float
|
424 |
+
"""
|
425 |
+
return _id.idd_diffsnorm(m, n, matvect, matvect2, matvec, matvec2, its)
|
426 |
+
|
427 |
+
|
428 |
+
#------------------------------------------------------------------------------
|
429 |
+
# idd_svd.f
|
430 |
+
#------------------------------------------------------------------------------
|
431 |
+
|
432 |
+
def iddr_svd(A, k):
|
433 |
+
"""
|
434 |
+
Compute SVD of a real matrix to a specified rank.
|
435 |
+
|
436 |
+
:param A:
|
437 |
+
Matrix.
|
438 |
+
:type A: :class:`numpy.ndarray`
|
439 |
+
:param k:
|
440 |
+
Rank of SVD.
|
441 |
+
:type k: int
|
442 |
+
|
443 |
+
:return:
|
444 |
+
Left singular vectors.
|
445 |
+
:rtype: :class:`numpy.ndarray`
|
446 |
+
:return:
|
447 |
+
Right singular vectors.
|
448 |
+
:rtype: :class:`numpy.ndarray`
|
449 |
+
:return:
|
450 |
+
Singular values.
|
451 |
+
:rtype: :class:`numpy.ndarray`
|
452 |
+
"""
|
453 |
+
A = np.asfortranarray(A)
|
454 |
+
U, V, S, ier = _id.iddr_svd(A, k)
|
455 |
+
if ier:
|
456 |
+
raise _RETCODE_ERROR
|
457 |
+
return U, V, S
|
458 |
+
|
459 |
+
|
460 |
+
def iddp_svd(eps, A):
|
461 |
+
"""
|
462 |
+
Compute SVD of a real matrix to a specified relative precision.
|
463 |
+
|
464 |
+
:param eps:
|
465 |
+
Relative precision.
|
466 |
+
:type eps: float
|
467 |
+
:param A:
|
468 |
+
Matrix.
|
469 |
+
:type A: :class:`numpy.ndarray`
|
470 |
+
|
471 |
+
:return:
|
472 |
+
Left singular vectors.
|
473 |
+
:rtype: :class:`numpy.ndarray`
|
474 |
+
:return:
|
475 |
+
Right singular vectors.
|
476 |
+
:rtype: :class:`numpy.ndarray`
|
477 |
+
:return:
|
478 |
+
Singular values.
|
479 |
+
:rtype: :class:`numpy.ndarray`
|
480 |
+
"""
|
481 |
+
A = np.asfortranarray(A)
|
482 |
+
m, n = A.shape
|
483 |
+
k, iU, iV, iS, w, ier = _id.iddp_svd(eps, A)
|
484 |
+
if ier:
|
485 |
+
raise _RETCODE_ERROR
|
486 |
+
U = w[iU-1:iU+m*k-1].reshape((m, k), order='F')
|
487 |
+
V = w[iV-1:iV+n*k-1].reshape((n, k), order='F')
|
488 |
+
S = w[iS-1:iS+k-1]
|
489 |
+
return U, V, S
|
490 |
+
|
491 |
+
|
492 |
+
#------------------------------------------------------------------------------
|
493 |
+
# iddp_aid.f
|
494 |
+
#------------------------------------------------------------------------------
|
495 |
+
|
496 |
+
def iddp_aid(eps, A):
|
497 |
+
"""
|
498 |
+
Compute ID of a real matrix to a specified relative precision using random
|
499 |
+
sampling.
|
500 |
+
|
501 |
+
:param eps:
|
502 |
+
Relative precision.
|
503 |
+
:type eps: float
|
504 |
+
:param A:
|
505 |
+
Matrix.
|
506 |
+
:type A: :class:`numpy.ndarray`
|
507 |
+
|
508 |
+
:return:
|
509 |
+
Rank of ID.
|
510 |
+
:rtype: int
|
511 |
+
:return:
|
512 |
+
Column index array.
|
513 |
+
:rtype: :class:`numpy.ndarray`
|
514 |
+
:return:
|
515 |
+
Interpolation coefficients.
|
516 |
+
:rtype: :class:`numpy.ndarray`
|
517 |
+
"""
|
518 |
+
A = np.asfortranarray(A)
|
519 |
+
m, n = A.shape
|
520 |
+
n2, w = idd_frmi(m)
|
521 |
+
proj = np.empty(n*(2*n2 + 1) + n2 + 1, order='F')
|
522 |
+
k, idx, proj = _id.iddp_aid(eps, A, w, proj)
|
523 |
+
proj = proj[:k*(n-k)].reshape((k, n-k), order='F')
|
524 |
+
return k, idx, proj
|
525 |
+
|
526 |
+
|
527 |
+
def idd_estrank(eps, A):
|
528 |
+
"""
|
529 |
+
Estimate rank of a real matrix to a specified relative precision using
|
530 |
+
random sampling.
|
531 |
+
|
532 |
+
The output rank is typically about 8 higher than the actual rank.
|
533 |
+
|
534 |
+
:param eps:
|
535 |
+
Relative precision.
|
536 |
+
:type eps: float
|
537 |
+
:param A:
|
538 |
+
Matrix.
|
539 |
+
:type A: :class:`numpy.ndarray`
|
540 |
+
|
541 |
+
:return:
|
542 |
+
Rank estimate.
|
543 |
+
:rtype: int
|
544 |
+
"""
|
545 |
+
A = np.asfortranarray(A)
|
546 |
+
m, n = A.shape
|
547 |
+
n2, w = idd_frmi(m)
|
548 |
+
ra = np.empty(n*n2 + (n + 1)*(n2 + 1), order='F')
|
549 |
+
k, ra = _id.idd_estrank(eps, A, w, ra)
|
550 |
+
return k
|
551 |
+
|
552 |
+
|
553 |
+
#------------------------------------------------------------------------------
|
554 |
+
# iddp_asvd.f
|
555 |
+
#------------------------------------------------------------------------------
|
556 |
+
|
557 |
+
def iddp_asvd(eps, A):
|
558 |
+
"""
|
559 |
+
Compute SVD of a real matrix to a specified relative precision using random
|
560 |
+
sampling.
|
561 |
+
|
562 |
+
:param eps:
|
563 |
+
Relative precision.
|
564 |
+
:type eps: float
|
565 |
+
:param A:
|
566 |
+
Matrix.
|
567 |
+
:type A: :class:`numpy.ndarray`
|
568 |
+
|
569 |
+
:return:
|
570 |
+
Left singular vectors.
|
571 |
+
:rtype: :class:`numpy.ndarray`
|
572 |
+
:return:
|
573 |
+
Right singular vectors.
|
574 |
+
:rtype: :class:`numpy.ndarray`
|
575 |
+
:return:
|
576 |
+
Singular values.
|
577 |
+
:rtype: :class:`numpy.ndarray`
|
578 |
+
"""
|
579 |
+
A = np.asfortranarray(A)
|
580 |
+
m, n = A.shape
|
581 |
+
n2, winit = _id.idd_frmi(m)
|
582 |
+
w = np.empty(
|
583 |
+
max((min(m, n) + 1)*(3*m + 5*n + 1) + 25*min(m, n)**2,
|
584 |
+
(2*n + 1)*(n2 + 1)),
|
585 |
+
order='F')
|
586 |
+
k, iU, iV, iS, w, ier = _id.iddp_asvd(eps, A, winit, w)
|
587 |
+
if ier:
|
588 |
+
raise _RETCODE_ERROR
|
589 |
+
U = w[iU-1:iU+m*k-1].reshape((m, k), order='F')
|
590 |
+
V = w[iV-1:iV+n*k-1].reshape((n, k), order='F')
|
591 |
+
S = w[iS-1:iS+k-1]
|
592 |
+
return U, V, S
|
593 |
+
|
594 |
+
|
595 |
+
#------------------------------------------------------------------------------
|
596 |
+
# iddp_rid.f
|
597 |
+
#------------------------------------------------------------------------------
|
598 |
+
|
599 |
+
def iddp_rid(eps, m, n, matvect):
|
600 |
+
"""
|
601 |
+
Compute ID of a real matrix to a specified relative precision using random
|
602 |
+
matrix-vector multiplication.
|
603 |
+
|
604 |
+
:param eps:
|
605 |
+
Relative precision.
|
606 |
+
:type eps: float
|
607 |
+
:param m:
|
608 |
+
Matrix row dimension.
|
609 |
+
:type m: int
|
610 |
+
:param n:
|
611 |
+
Matrix column dimension.
|
612 |
+
:type n: int
|
613 |
+
:param matvect:
|
614 |
+
Function to apply the matrix transpose to a vector, with call signature
|
615 |
+
`y = matvect(x)`, where `x` and `y` are the input and output vectors,
|
616 |
+
respectively.
|
617 |
+
:type matvect: function
|
618 |
+
|
619 |
+
:return:
|
620 |
+
Rank of ID.
|
621 |
+
:rtype: int
|
622 |
+
:return:
|
623 |
+
Column index array.
|
624 |
+
:rtype: :class:`numpy.ndarray`
|
625 |
+
:return:
|
626 |
+
Interpolation coefficients.
|
627 |
+
:rtype: :class:`numpy.ndarray`
|
628 |
+
"""
|
629 |
+
proj = np.empty(m + 1 + 2*n*(min(m, n) + 1), order='F')
|
630 |
+
k, idx, proj, ier = _id.iddp_rid(eps, m, n, matvect, proj)
|
631 |
+
if ier != 0:
|
632 |
+
raise _RETCODE_ERROR
|
633 |
+
proj = proj[:k*(n-k)].reshape((k, n-k), order='F')
|
634 |
+
return k, idx, proj
|
635 |
+
|
636 |
+
|
637 |
+
def idd_findrank(eps, m, n, matvect):
|
638 |
+
"""
|
639 |
+
Estimate rank of a real matrix to a specified relative precision using
|
640 |
+
random matrix-vector multiplication.
|
641 |
+
|
642 |
+
:param eps:
|
643 |
+
Relative precision.
|
644 |
+
:type eps: float
|
645 |
+
:param m:
|
646 |
+
Matrix row dimension.
|
647 |
+
:type m: int
|
648 |
+
:param n:
|
649 |
+
Matrix column dimension.
|
650 |
+
:type n: int
|
651 |
+
:param matvect:
|
652 |
+
Function to apply the matrix transpose to a vector, with call signature
|
653 |
+
`y = matvect(x)`, where `x` and `y` are the input and output vectors,
|
654 |
+
respectively.
|
655 |
+
:type matvect: function
|
656 |
+
|
657 |
+
:return:
|
658 |
+
Rank estimate.
|
659 |
+
:rtype: int
|
660 |
+
"""
|
661 |
+
k, ra, ier = _id.idd_findrank(eps, m, n, matvect)
|
662 |
+
if ier:
|
663 |
+
raise _RETCODE_ERROR
|
664 |
+
return k
|
665 |
+
|
666 |
+
|
667 |
+
#------------------------------------------------------------------------------
|
668 |
+
# iddp_rsvd.f
|
669 |
+
#------------------------------------------------------------------------------
|
670 |
+
|
671 |
+
def iddp_rsvd(eps, m, n, matvect, matvec):
|
672 |
+
"""
|
673 |
+
Compute SVD of a real matrix to a specified relative precision using random
|
674 |
+
matrix-vector multiplication.
|
675 |
+
|
676 |
+
:param eps:
|
677 |
+
Relative precision.
|
678 |
+
:type eps: float
|
679 |
+
:param m:
|
680 |
+
Matrix row dimension.
|
681 |
+
:type m: int
|
682 |
+
:param n:
|
683 |
+
Matrix column dimension.
|
684 |
+
:type n: int
|
685 |
+
:param matvect:
|
686 |
+
Function to apply the matrix transpose to a vector, with call signature
|
687 |
+
`y = matvect(x)`, where `x` and `y` are the input and output vectors,
|
688 |
+
respectively.
|
689 |
+
:type matvect: function
|
690 |
+
:param matvec:
|
691 |
+
Function to apply the matrix to a vector, with call signature
|
692 |
+
`y = matvec(x)`, where `x` and `y` are the input and output vectors,
|
693 |
+
respectively.
|
694 |
+
:type matvec: function
|
695 |
+
|
696 |
+
:return:
|
697 |
+
Left singular vectors.
|
698 |
+
:rtype: :class:`numpy.ndarray`
|
699 |
+
:return:
|
700 |
+
Right singular vectors.
|
701 |
+
:rtype: :class:`numpy.ndarray`
|
702 |
+
:return:
|
703 |
+
Singular values.
|
704 |
+
:rtype: :class:`numpy.ndarray`
|
705 |
+
"""
|
706 |
+
k, iU, iV, iS, w, ier = _id.iddp_rsvd(eps, m, n, matvect, matvec)
|
707 |
+
if ier:
|
708 |
+
raise _RETCODE_ERROR
|
709 |
+
U = w[iU-1:iU+m*k-1].reshape((m, k), order='F')
|
710 |
+
V = w[iV-1:iV+n*k-1].reshape((n, k), order='F')
|
711 |
+
S = w[iS-1:iS+k-1]
|
712 |
+
return U, V, S
|
713 |
+
|
714 |
+
|
715 |
+
#------------------------------------------------------------------------------
|
716 |
+
# iddr_aid.f
|
717 |
+
#------------------------------------------------------------------------------
|
718 |
+
|
719 |
+
def iddr_aid(A, k):
|
720 |
+
"""
|
721 |
+
Compute ID of a real matrix to a specified rank using random sampling.
|
722 |
+
|
723 |
+
:param A:
|
724 |
+
Matrix.
|
725 |
+
:type A: :class:`numpy.ndarray`
|
726 |
+
:param k:
|
727 |
+
Rank of ID.
|
728 |
+
:type k: int
|
729 |
+
|
730 |
+
:return:
|
731 |
+
Column index array.
|
732 |
+
:rtype: :class:`numpy.ndarray`
|
733 |
+
:return:
|
734 |
+
Interpolation coefficients.
|
735 |
+
:rtype: :class:`numpy.ndarray`
|
736 |
+
"""
|
737 |
+
A = np.asfortranarray(A)
|
738 |
+
m, n = A.shape
|
739 |
+
w = iddr_aidi(m, n, k)
|
740 |
+
idx, proj = _id.iddr_aid(A, k, w)
|
741 |
+
if k == n:
|
742 |
+
proj = np.empty((k, n-k), dtype='float64', order='F')
|
743 |
+
else:
|
744 |
+
proj = proj.reshape((k, n-k), order='F')
|
745 |
+
return idx, proj
|
746 |
+
|
747 |
+
|
748 |
+
def iddr_aidi(m, n, k):
|
749 |
+
"""
|
750 |
+
Initialize array for :func:`iddr_aid`.
|
751 |
+
|
752 |
+
:param m:
|
753 |
+
Matrix row dimension.
|
754 |
+
:type m: int
|
755 |
+
:param n:
|
756 |
+
Matrix column dimension.
|
757 |
+
:type n: int
|
758 |
+
:param k:
|
759 |
+
Rank of ID.
|
760 |
+
:type k: int
|
761 |
+
|
762 |
+
:return:
|
763 |
+
Initialization array to be used by :func:`iddr_aid`.
|
764 |
+
:rtype: :class:`numpy.ndarray`
|
765 |
+
"""
|
766 |
+
return _id.iddr_aidi(m, n, k)
|
767 |
+
|
768 |
+
|
769 |
+
#------------------------------------------------------------------------------
|
770 |
+
# iddr_asvd.f
|
771 |
+
#------------------------------------------------------------------------------
|
772 |
+
|
773 |
+
def iddr_asvd(A, k):
|
774 |
+
"""
|
775 |
+
Compute SVD of a real matrix to a specified rank using random sampling.
|
776 |
+
|
777 |
+
:param A:
|
778 |
+
Matrix.
|
779 |
+
:type A: :class:`numpy.ndarray`
|
780 |
+
:param k:
|
781 |
+
Rank of SVD.
|
782 |
+
:type k: int
|
783 |
+
|
784 |
+
:return:
|
785 |
+
Left singular vectors.
|
786 |
+
:rtype: :class:`numpy.ndarray`
|
787 |
+
:return:
|
788 |
+
Right singular vectors.
|
789 |
+
:rtype: :class:`numpy.ndarray`
|
790 |
+
:return:
|
791 |
+
Singular values.
|
792 |
+
:rtype: :class:`numpy.ndarray`
|
793 |
+
"""
|
794 |
+
A = np.asfortranarray(A)
|
795 |
+
m, n = A.shape
|
796 |
+
w = np.empty((2*k + 28)*m + (6*k + 21)*n + 25*k**2 + 100, order='F')
|
797 |
+
w_ = iddr_aidi(m, n, k)
|
798 |
+
w[:w_.size] = w_
|
799 |
+
U, V, S, ier = _id.iddr_asvd(A, k, w)
|
800 |
+
if ier != 0:
|
801 |
+
raise _RETCODE_ERROR
|
802 |
+
return U, V, S
|
803 |
+
|
804 |
+
|
805 |
+
#------------------------------------------------------------------------------
|
806 |
+
# iddr_rid.f
|
807 |
+
#------------------------------------------------------------------------------
|
808 |
+
|
809 |
+
def iddr_rid(m, n, matvect, k):
|
810 |
+
"""
|
811 |
+
Compute ID of a real matrix to a specified rank using random matrix-vector
|
812 |
+
multiplication.
|
813 |
+
|
814 |
+
:param m:
|
815 |
+
Matrix row dimension.
|
816 |
+
:type m: int
|
817 |
+
:param n:
|
818 |
+
Matrix column dimension.
|
819 |
+
:type n: int
|
820 |
+
:param matvect:
|
821 |
+
Function to apply the matrix transpose to a vector, with call signature
|
822 |
+
`y = matvect(x)`, where `x` and `y` are the input and output vectors,
|
823 |
+
respectively.
|
824 |
+
:type matvect: function
|
825 |
+
:param k:
|
826 |
+
Rank of ID.
|
827 |
+
:type k: int
|
828 |
+
|
829 |
+
:return:
|
830 |
+
Column index array.
|
831 |
+
:rtype: :class:`numpy.ndarray`
|
832 |
+
:return:
|
833 |
+
Interpolation coefficients.
|
834 |
+
:rtype: :class:`numpy.ndarray`
|
835 |
+
"""
|
836 |
+
idx, proj = _id.iddr_rid(m, n, matvect, k)
|
837 |
+
proj = proj[:k*(n-k)].reshape((k, n-k), order='F')
|
838 |
+
return idx, proj
|
839 |
+
|
840 |
+
|
841 |
+
#------------------------------------------------------------------------------
|
842 |
+
# iddr_rsvd.f
|
843 |
+
#------------------------------------------------------------------------------
|
844 |
+
|
845 |
+
def iddr_rsvd(m, n, matvect, matvec, k):
|
846 |
+
"""
|
847 |
+
Compute SVD of a real matrix to a specified rank using random matrix-vector
|
848 |
+
multiplication.
|
849 |
+
|
850 |
+
:param m:
|
851 |
+
Matrix row dimension.
|
852 |
+
:type m: int
|
853 |
+
:param n:
|
854 |
+
Matrix column dimension.
|
855 |
+
:type n: int
|
856 |
+
:param matvect:
|
857 |
+
Function to apply the matrix transpose to a vector, with call signature
|
858 |
+
`y = matvect(x)`, where `x` and `y` are the input and output vectors,
|
859 |
+
respectively.
|
860 |
+
:type matvect: function
|
861 |
+
:param matvec:
|
862 |
+
Function to apply the matrix to a vector, with call signature
|
863 |
+
`y = matvec(x)`, where `x` and `y` are the input and output vectors,
|
864 |
+
respectively.
|
865 |
+
:type matvec: function
|
866 |
+
:param k:
|
867 |
+
Rank of SVD.
|
868 |
+
:type k: int
|
869 |
+
|
870 |
+
:return:
|
871 |
+
Left singular vectors.
|
872 |
+
:rtype: :class:`numpy.ndarray`
|
873 |
+
:return:
|
874 |
+
Right singular vectors.
|
875 |
+
:rtype: :class:`numpy.ndarray`
|
876 |
+
:return:
|
877 |
+
Singular values.
|
878 |
+
:rtype: :class:`numpy.ndarray`
|
879 |
+
"""
|
880 |
+
U, V, S, ier = _id.iddr_rsvd(m, n, matvect, matvec, k)
|
881 |
+
if ier != 0:
|
882 |
+
raise _RETCODE_ERROR
|
883 |
+
return U, V, S
|
884 |
+
|
885 |
+
|
886 |
+
#------------------------------------------------------------------------------
|
887 |
+
# idz_frm.f
|
888 |
+
#------------------------------------------------------------------------------
|
889 |
+
|
890 |
+
def idz_frm(n, w, x):
|
891 |
+
"""
|
892 |
+
Transform complex vector via a composition of Rokhlin's random transform,
|
893 |
+
random subselection, and an FFT.
|
894 |
+
|
895 |
+
In contrast to :func:`idz_sfrm`, this routine works best when the length of
|
896 |
+
the transformed vector is the power-of-two integer output by
|
897 |
+
:func:`idz_frmi`, or when the length is not specified but instead
|
898 |
+
determined a posteriori from the output. The returned transformed vector is
|
899 |
+
randomly permuted.
|
900 |
+
|
901 |
+
:param n:
|
902 |
+
Greatest power-of-two integer satisfying `n <= x.size` as obtained from
|
903 |
+
:func:`idz_frmi`; `n` is also the length of the output vector.
|
904 |
+
:type n: int
|
905 |
+
:param w:
|
906 |
+
Initialization array constructed by :func:`idz_frmi`.
|
907 |
+
:type w: :class:`numpy.ndarray`
|
908 |
+
:param x:
|
909 |
+
Vector to be transformed.
|
910 |
+
:type x: :class:`numpy.ndarray`
|
911 |
+
|
912 |
+
:return:
|
913 |
+
Transformed vector.
|
914 |
+
:rtype: :class:`numpy.ndarray`
|
915 |
+
"""
|
916 |
+
return _id.idz_frm(n, w, x)
|
917 |
+
|
918 |
+
|
919 |
+
def idz_sfrm(l, n, w, x):
|
920 |
+
"""
|
921 |
+
Transform complex vector via a composition of Rokhlin's random transform,
|
922 |
+
random subselection, and an FFT.
|
923 |
+
|
924 |
+
In contrast to :func:`idz_frm`, this routine works best when the length of
|
925 |
+
the transformed vector is known a priori.
|
926 |
+
|
927 |
+
:param l:
|
928 |
+
Length of transformed vector, satisfying `l <= n`.
|
929 |
+
:type l: int
|
930 |
+
:param n:
|
931 |
+
Greatest power-of-two integer satisfying `n <= x.size` as obtained from
|
932 |
+
:func:`idz_sfrmi`.
|
933 |
+
:type n: int
|
934 |
+
:param w:
|
935 |
+
Initialization array constructed by :func:`idd_sfrmi`.
|
936 |
+
:type w: :class:`numpy.ndarray`
|
937 |
+
:param x:
|
938 |
+
Vector to be transformed.
|
939 |
+
:type x: :class:`numpy.ndarray`
|
940 |
+
|
941 |
+
:return:
|
942 |
+
Transformed vector.
|
943 |
+
:rtype: :class:`numpy.ndarray`
|
944 |
+
"""
|
945 |
+
return _id.idz_sfrm(l, n, w, x)
|
946 |
+
|
947 |
+
|
948 |
+
def idz_frmi(m):
|
949 |
+
"""
|
950 |
+
Initialize data for :func:`idz_frm`.
|
951 |
+
|
952 |
+
:param m:
|
953 |
+
Length of vector to be transformed.
|
954 |
+
:type m: int
|
955 |
+
|
956 |
+
:return:
|
957 |
+
Greatest power-of-two integer `n` satisfying `n <= m`.
|
958 |
+
:rtype: int
|
959 |
+
:return:
|
960 |
+
Initialization array to be used by :func:`idz_frm`.
|
961 |
+
:rtype: :class:`numpy.ndarray`
|
962 |
+
"""
|
963 |
+
return _id.idz_frmi(m)
|
964 |
+
|
965 |
+
|
966 |
+
def idz_sfrmi(l, m):
|
967 |
+
"""
|
968 |
+
Initialize data for :func:`idz_sfrm`.
|
969 |
+
|
970 |
+
:param l:
|
971 |
+
Length of output transformed vector.
|
972 |
+
:type l: int
|
973 |
+
:param m:
|
974 |
+
Length of the vector to be transformed.
|
975 |
+
:type m: int
|
976 |
+
|
977 |
+
:return:
|
978 |
+
Greatest power-of-two integer `n` satisfying `n <= m`.
|
979 |
+
:rtype: int
|
980 |
+
:return:
|
981 |
+
Initialization array to be used by :func:`idz_sfrm`.
|
982 |
+
:rtype: :class:`numpy.ndarray`
|
983 |
+
"""
|
984 |
+
return _id.idz_sfrmi(l, m)
|
985 |
+
|
986 |
+
|
987 |
+
#------------------------------------------------------------------------------
|
988 |
+
# idz_id.f
|
989 |
+
#------------------------------------------------------------------------------
|
990 |
+
|
991 |
+
def idzp_id(eps, A):
|
992 |
+
"""
|
993 |
+
Compute ID of a complex matrix to a specified relative precision.
|
994 |
+
|
995 |
+
:param eps:
|
996 |
+
Relative precision.
|
997 |
+
:type eps: float
|
998 |
+
:param A:
|
999 |
+
Matrix.
|
1000 |
+
:type A: :class:`numpy.ndarray`
|
1001 |
+
|
1002 |
+
:return:
|
1003 |
+
Rank of ID.
|
1004 |
+
:rtype: int
|
1005 |
+
:return:
|
1006 |
+
Column index array.
|
1007 |
+
:rtype: :class:`numpy.ndarray`
|
1008 |
+
:return:
|
1009 |
+
Interpolation coefficients.
|
1010 |
+
:rtype: :class:`numpy.ndarray`
|
1011 |
+
"""
|
1012 |
+
A = _asfortranarray_copy(A)
|
1013 |
+
k, idx, rnorms = _id.idzp_id(eps, A)
|
1014 |
+
n = A.shape[1]
|
1015 |
+
proj = A.T.ravel()[:k*(n-k)].reshape((k, n-k), order='F')
|
1016 |
+
return k, idx, proj
|
1017 |
+
|
1018 |
+
|
1019 |
+
def idzr_id(A, k):
|
1020 |
+
"""
|
1021 |
+
Compute ID of a complex matrix to a specified rank.
|
1022 |
+
|
1023 |
+
:param A:
|
1024 |
+
Matrix.
|
1025 |
+
:type A: :class:`numpy.ndarray`
|
1026 |
+
:param k:
|
1027 |
+
Rank of ID.
|
1028 |
+
:type k: int
|
1029 |
+
|
1030 |
+
:return:
|
1031 |
+
Column index array.
|
1032 |
+
:rtype: :class:`numpy.ndarray`
|
1033 |
+
:return:
|
1034 |
+
Interpolation coefficients.
|
1035 |
+
:rtype: :class:`numpy.ndarray`
|
1036 |
+
"""
|
1037 |
+
A = _asfortranarray_copy(A)
|
1038 |
+
idx, rnorms = _id.idzr_id(A, k)
|
1039 |
+
n = A.shape[1]
|
1040 |
+
proj = A.T.ravel()[:k*(n-k)].reshape((k, n-k), order='F')
|
1041 |
+
return idx, proj
|
1042 |
+
|
1043 |
+
|
1044 |
+
def idz_reconid(B, idx, proj):
|
1045 |
+
"""
|
1046 |
+
Reconstruct matrix from complex ID.
|
1047 |
+
|
1048 |
+
:param B:
|
1049 |
+
Skeleton matrix.
|
1050 |
+
:type B: :class:`numpy.ndarray`
|
1051 |
+
:param idx:
|
1052 |
+
Column index array.
|
1053 |
+
:type idx: :class:`numpy.ndarray`
|
1054 |
+
:param proj:
|
1055 |
+
Interpolation coefficients.
|
1056 |
+
:type proj: :class:`numpy.ndarray`
|
1057 |
+
|
1058 |
+
:return:
|
1059 |
+
Reconstructed matrix.
|
1060 |
+
:rtype: :class:`numpy.ndarray`
|
1061 |
+
"""
|
1062 |
+
B = np.asfortranarray(B)
|
1063 |
+
if proj.size > 0:
|
1064 |
+
return _id.idz_reconid(B, idx, proj)
|
1065 |
+
else:
|
1066 |
+
return B[:, np.argsort(idx)]
|
1067 |
+
|
1068 |
+
|
1069 |
+
def idz_reconint(idx, proj):
|
1070 |
+
"""
|
1071 |
+
Reconstruct interpolation matrix from complex ID.
|
1072 |
+
|
1073 |
+
:param idx:
|
1074 |
+
Column index array.
|
1075 |
+
:type idx: :class:`numpy.ndarray`
|
1076 |
+
:param proj:
|
1077 |
+
Interpolation coefficients.
|
1078 |
+
:type proj: :class:`numpy.ndarray`
|
1079 |
+
|
1080 |
+
:return:
|
1081 |
+
Interpolation matrix.
|
1082 |
+
:rtype: :class:`numpy.ndarray`
|
1083 |
+
"""
|
1084 |
+
return _id.idz_reconint(idx, proj)
|
1085 |
+
|
1086 |
+
|
1087 |
+
def idz_copycols(A, k, idx):
|
1088 |
+
"""
|
1089 |
+
Reconstruct skeleton matrix from complex ID.
|
1090 |
+
|
1091 |
+
:param A:
|
1092 |
+
Original matrix.
|
1093 |
+
:type A: :class:`numpy.ndarray`
|
1094 |
+
:param k:
|
1095 |
+
Rank of ID.
|
1096 |
+
:type k: int
|
1097 |
+
:param idx:
|
1098 |
+
Column index array.
|
1099 |
+
:type idx: :class:`numpy.ndarray`
|
1100 |
+
|
1101 |
+
:return:
|
1102 |
+
Skeleton matrix.
|
1103 |
+
:rtype: :class:`numpy.ndarray`
|
1104 |
+
"""
|
1105 |
+
A = np.asfortranarray(A)
|
1106 |
+
return _id.idz_copycols(A, k, idx)
|
1107 |
+
|
1108 |
+
|
1109 |
+
#------------------------------------------------------------------------------
|
1110 |
+
# idz_id2svd.f
|
1111 |
+
#------------------------------------------------------------------------------
|
1112 |
+
|
1113 |
+
def idz_id2svd(B, idx, proj):
|
1114 |
+
"""
|
1115 |
+
Convert complex ID to SVD.
|
1116 |
+
|
1117 |
+
:param B:
|
1118 |
+
Skeleton matrix.
|
1119 |
+
:type B: :class:`numpy.ndarray`
|
1120 |
+
:param idx:
|
1121 |
+
Column index array.
|
1122 |
+
:type idx: :class:`numpy.ndarray`
|
1123 |
+
:param proj:
|
1124 |
+
Interpolation coefficients.
|
1125 |
+
:type proj: :class:`numpy.ndarray`
|
1126 |
+
|
1127 |
+
:return:
|
1128 |
+
Left singular vectors.
|
1129 |
+
:rtype: :class:`numpy.ndarray`
|
1130 |
+
:return:
|
1131 |
+
Right singular vectors.
|
1132 |
+
:rtype: :class:`numpy.ndarray`
|
1133 |
+
:return:
|
1134 |
+
Singular values.
|
1135 |
+
:rtype: :class:`numpy.ndarray`
|
1136 |
+
"""
|
1137 |
+
B = np.asfortranarray(B)
|
1138 |
+
U, V, S, ier = _id.idz_id2svd(B, idx, proj)
|
1139 |
+
if ier:
|
1140 |
+
raise _RETCODE_ERROR
|
1141 |
+
return U, V, S
|
1142 |
+
|
1143 |
+
|
1144 |
+
#------------------------------------------------------------------------------
|
1145 |
+
# idz_snorm.f
|
1146 |
+
#------------------------------------------------------------------------------
|
1147 |
+
|
1148 |
+
def idz_snorm(m, n, matveca, matvec, its=20):
|
1149 |
+
"""
|
1150 |
+
Estimate spectral norm of a complex matrix by the randomized power method.
|
1151 |
+
|
1152 |
+
:param m:
|
1153 |
+
Matrix row dimension.
|
1154 |
+
:type m: int
|
1155 |
+
:param n:
|
1156 |
+
Matrix column dimension.
|
1157 |
+
:type n: int
|
1158 |
+
:param matveca:
|
1159 |
+
Function to apply the matrix adjoint to a vector, with call signature
|
1160 |
+
`y = matveca(x)`, where `x` and `y` are the input and output vectors,
|
1161 |
+
respectively.
|
1162 |
+
:type matveca: function
|
1163 |
+
:param matvec:
|
1164 |
+
Function to apply the matrix to a vector, with call signature
|
1165 |
+
`y = matvec(x)`, where `x` and `y` are the input and output vectors,
|
1166 |
+
respectively.
|
1167 |
+
:type matvec: function
|
1168 |
+
:param its:
|
1169 |
+
Number of power method iterations.
|
1170 |
+
:type its: int
|
1171 |
+
|
1172 |
+
:return:
|
1173 |
+
Spectral norm estimate.
|
1174 |
+
:rtype: float
|
1175 |
+
"""
|
1176 |
+
snorm, v = _id.idz_snorm(m, n, matveca, matvec, its)
|
1177 |
+
return snorm
|
1178 |
+
|
1179 |
+
|
1180 |
+
def idz_diffsnorm(m, n, matveca, matveca2, matvec, matvec2, its=20):
|
1181 |
+
"""
|
1182 |
+
Estimate spectral norm of the difference of two complex matrices by the
|
1183 |
+
randomized power method.
|
1184 |
+
|
1185 |
+
:param m:
|
1186 |
+
Matrix row dimension.
|
1187 |
+
:type m: int
|
1188 |
+
:param n:
|
1189 |
+
Matrix column dimension.
|
1190 |
+
:type n: int
|
1191 |
+
:param matveca:
|
1192 |
+
Function to apply the adjoint of the first matrix to a vector, with
|
1193 |
+
call signature `y = matveca(x)`, where `x` and `y` are the input and
|
1194 |
+
output vectors, respectively.
|
1195 |
+
:type matveca: function
|
1196 |
+
:param matveca2:
|
1197 |
+
Function to apply the adjoint of the second matrix to a vector, with
|
1198 |
+
call signature `y = matveca2(x)`, where `x` and `y` are the input and
|
1199 |
+
output vectors, respectively.
|
1200 |
+
:type matveca2: function
|
1201 |
+
:param matvec:
|
1202 |
+
Function to apply the first matrix to a vector, with call signature
|
1203 |
+
`y = matvec(x)`, where `x` and `y` are the input and output vectors,
|
1204 |
+
respectively.
|
1205 |
+
:type matvec: function
|
1206 |
+
:param matvec2:
|
1207 |
+
Function to apply the second matrix to a vector, with call signature
|
1208 |
+
`y = matvec2(x)`, where `x` and `y` are the input and output vectors,
|
1209 |
+
respectively.
|
1210 |
+
:type matvec2: function
|
1211 |
+
:param its:
|
1212 |
+
Number of power method iterations.
|
1213 |
+
:type its: int
|
1214 |
+
|
1215 |
+
:return:
|
1216 |
+
Spectral norm estimate of matrix difference.
|
1217 |
+
:rtype: float
|
1218 |
+
"""
|
1219 |
+
return _id.idz_diffsnorm(m, n, matveca, matveca2, matvec, matvec2, its)
|
1220 |
+
|
1221 |
+
|
1222 |
+
#------------------------------------------------------------------------------
|
1223 |
+
# idz_svd.f
|
1224 |
+
#------------------------------------------------------------------------------
|
1225 |
+
|
1226 |
+
def idzr_svd(A, k):
|
1227 |
+
"""
|
1228 |
+
Compute SVD of a complex matrix to a specified rank.
|
1229 |
+
|
1230 |
+
:param A:
|
1231 |
+
Matrix.
|
1232 |
+
:type A: :class:`numpy.ndarray`
|
1233 |
+
:param k:
|
1234 |
+
Rank of SVD.
|
1235 |
+
:type k: int
|
1236 |
+
|
1237 |
+
:return:
|
1238 |
+
Left singular vectors.
|
1239 |
+
:rtype: :class:`numpy.ndarray`
|
1240 |
+
:return:
|
1241 |
+
Right singular vectors.
|
1242 |
+
:rtype: :class:`numpy.ndarray`
|
1243 |
+
:return:
|
1244 |
+
Singular values.
|
1245 |
+
:rtype: :class:`numpy.ndarray`
|
1246 |
+
"""
|
1247 |
+
A = np.asfortranarray(A)
|
1248 |
+
U, V, S, ier = _id.idzr_svd(A, k)
|
1249 |
+
if ier:
|
1250 |
+
raise _RETCODE_ERROR
|
1251 |
+
return U, V, S
|
1252 |
+
|
1253 |
+
|
1254 |
+
def idzp_svd(eps, A):
|
1255 |
+
"""
|
1256 |
+
Compute SVD of a complex matrix to a specified relative precision.
|
1257 |
+
|
1258 |
+
:param eps:
|
1259 |
+
Relative precision.
|
1260 |
+
:type eps: float
|
1261 |
+
:param A:
|
1262 |
+
Matrix.
|
1263 |
+
:type A: :class:`numpy.ndarray`
|
1264 |
+
|
1265 |
+
:return:
|
1266 |
+
Left singular vectors.
|
1267 |
+
:rtype: :class:`numpy.ndarray`
|
1268 |
+
:return:
|
1269 |
+
Right singular vectors.
|
1270 |
+
:rtype: :class:`numpy.ndarray`
|
1271 |
+
:return:
|
1272 |
+
Singular values.
|
1273 |
+
:rtype: :class:`numpy.ndarray`
|
1274 |
+
"""
|
1275 |
+
A = np.asfortranarray(A)
|
1276 |
+
m, n = A.shape
|
1277 |
+
k, iU, iV, iS, w, ier = _id.idzp_svd(eps, A)
|
1278 |
+
if ier:
|
1279 |
+
raise _RETCODE_ERROR
|
1280 |
+
U = w[iU-1:iU+m*k-1].reshape((m, k), order='F')
|
1281 |
+
V = w[iV-1:iV+n*k-1].reshape((n, k), order='F')
|
1282 |
+
S = w[iS-1:iS+k-1]
|
1283 |
+
return U, V, S
|
1284 |
+
|
1285 |
+
|
1286 |
+
#------------------------------------------------------------------------------
|
1287 |
+
# idzp_aid.f
|
1288 |
+
#------------------------------------------------------------------------------
|
1289 |
+
|
1290 |
+
def idzp_aid(eps, A):
|
1291 |
+
"""
|
1292 |
+
Compute ID of a complex matrix to a specified relative precision using
|
1293 |
+
random sampling.
|
1294 |
+
|
1295 |
+
:param eps:
|
1296 |
+
Relative precision.
|
1297 |
+
:type eps: float
|
1298 |
+
:param A:
|
1299 |
+
Matrix.
|
1300 |
+
:type A: :class:`numpy.ndarray`
|
1301 |
+
|
1302 |
+
:return:
|
1303 |
+
Rank of ID.
|
1304 |
+
:rtype: int
|
1305 |
+
:return:
|
1306 |
+
Column index array.
|
1307 |
+
:rtype: :class:`numpy.ndarray`
|
1308 |
+
:return:
|
1309 |
+
Interpolation coefficients.
|
1310 |
+
:rtype: :class:`numpy.ndarray`
|
1311 |
+
"""
|
1312 |
+
A = np.asfortranarray(A)
|
1313 |
+
m, n = A.shape
|
1314 |
+
n2, w = idz_frmi(m)
|
1315 |
+
proj = np.empty(n*(2*n2 + 1) + n2 + 1, dtype='complex128', order='F')
|
1316 |
+
k, idx, proj = _id.idzp_aid(eps, A, w, proj)
|
1317 |
+
proj = proj[:k*(n-k)].reshape((k, n-k), order='F')
|
1318 |
+
return k, idx, proj
|
1319 |
+
|
1320 |
+
|
1321 |
+
def idz_estrank(eps, A):
|
1322 |
+
"""
|
1323 |
+
Estimate rank of a complex matrix to a specified relative precision using
|
1324 |
+
random sampling.
|
1325 |
+
|
1326 |
+
The output rank is typically about 8 higher than the actual rank.
|
1327 |
+
|
1328 |
+
:param eps:
|
1329 |
+
Relative precision.
|
1330 |
+
:type eps: float
|
1331 |
+
:param A:
|
1332 |
+
Matrix.
|
1333 |
+
:type A: :class:`numpy.ndarray`
|
1334 |
+
|
1335 |
+
:return:
|
1336 |
+
Rank estimate.
|
1337 |
+
:rtype: int
|
1338 |
+
"""
|
1339 |
+
A = np.asfortranarray(A)
|
1340 |
+
m, n = A.shape
|
1341 |
+
n2, w = idz_frmi(m)
|
1342 |
+
ra = np.empty(n*n2 + (n + 1)*(n2 + 1), dtype='complex128', order='F')
|
1343 |
+
k, ra = _id.idz_estrank(eps, A, w, ra)
|
1344 |
+
return k
|
1345 |
+
|
1346 |
+
|
1347 |
+
#------------------------------------------------------------------------------
|
1348 |
+
# idzp_asvd.f
|
1349 |
+
#------------------------------------------------------------------------------
|
1350 |
+
|
1351 |
+
def idzp_asvd(eps, A):
|
1352 |
+
"""
|
1353 |
+
Compute SVD of a complex matrix to a specified relative precision using
|
1354 |
+
random sampling.
|
1355 |
+
|
1356 |
+
:param eps:
|
1357 |
+
Relative precision.
|
1358 |
+
:type eps: float
|
1359 |
+
:param A:
|
1360 |
+
Matrix.
|
1361 |
+
:type A: :class:`numpy.ndarray`
|
1362 |
+
|
1363 |
+
:return:
|
1364 |
+
Left singular vectors.
|
1365 |
+
:rtype: :class:`numpy.ndarray`
|
1366 |
+
:return:
|
1367 |
+
Right singular vectors.
|
1368 |
+
:rtype: :class:`numpy.ndarray`
|
1369 |
+
:return:
|
1370 |
+
Singular values.
|
1371 |
+
:rtype: :class:`numpy.ndarray`
|
1372 |
+
"""
|
1373 |
+
A = np.asfortranarray(A)
|
1374 |
+
m, n = A.shape
|
1375 |
+
n2, winit = _id.idz_frmi(m)
|
1376 |
+
w = np.empty(
|
1377 |
+
max((min(m, n) + 1)*(3*m + 5*n + 11) + 8*min(m, n)**2,
|
1378 |
+
(2*n + 1)*(n2 + 1)),
|
1379 |
+
dtype=np.complex128, order='F')
|
1380 |
+
k, iU, iV, iS, w, ier = _id.idzp_asvd(eps, A, winit, w)
|
1381 |
+
if ier:
|
1382 |
+
raise _RETCODE_ERROR
|
1383 |
+
U = w[iU-1:iU+m*k-1].reshape((m, k), order='F')
|
1384 |
+
V = w[iV-1:iV+n*k-1].reshape((n, k), order='F')
|
1385 |
+
S = w[iS-1:iS+k-1]
|
1386 |
+
return U, V, S
|
1387 |
+
|
1388 |
+
|
1389 |
+
#------------------------------------------------------------------------------
|
1390 |
+
# idzp_rid.f
|
1391 |
+
#------------------------------------------------------------------------------
|
1392 |
+
|
1393 |
+
def idzp_rid(eps, m, n, matveca):
|
1394 |
+
"""
|
1395 |
+
Compute ID of a complex matrix to a specified relative precision using
|
1396 |
+
random matrix-vector multiplication.
|
1397 |
+
|
1398 |
+
:param eps:
|
1399 |
+
Relative precision.
|
1400 |
+
:type eps: float
|
1401 |
+
:param m:
|
1402 |
+
Matrix row dimension.
|
1403 |
+
:type m: int
|
1404 |
+
:param n:
|
1405 |
+
Matrix column dimension.
|
1406 |
+
:type n: int
|
1407 |
+
:param matveca:
|
1408 |
+
Function to apply the matrix adjoint to a vector, with call signature
|
1409 |
+
`y = matveca(x)`, where `x` and `y` are the input and output vectors,
|
1410 |
+
respectively.
|
1411 |
+
:type matveca: function
|
1412 |
+
|
1413 |
+
:return:
|
1414 |
+
Rank of ID.
|
1415 |
+
:rtype: int
|
1416 |
+
:return:
|
1417 |
+
Column index array.
|
1418 |
+
:rtype: :class:`numpy.ndarray`
|
1419 |
+
:return:
|
1420 |
+
Interpolation coefficients.
|
1421 |
+
:rtype: :class:`numpy.ndarray`
|
1422 |
+
"""
|
1423 |
+
proj = np.empty(
|
1424 |
+
m + 1 + 2*n*(min(m, n) + 1),
|
1425 |
+
dtype=np.complex128, order='F')
|
1426 |
+
k, idx, proj, ier = _id.idzp_rid(eps, m, n, matveca, proj)
|
1427 |
+
if ier:
|
1428 |
+
raise _RETCODE_ERROR
|
1429 |
+
proj = proj[:k*(n-k)].reshape((k, n-k), order='F')
|
1430 |
+
return k, idx, proj
|
1431 |
+
|
1432 |
+
|
1433 |
+
def idz_findrank(eps, m, n, matveca):
|
1434 |
+
"""
|
1435 |
+
Estimate rank of a complex matrix to a specified relative precision using
|
1436 |
+
random matrix-vector multiplication.
|
1437 |
+
|
1438 |
+
:param eps:
|
1439 |
+
Relative precision.
|
1440 |
+
:type eps: float
|
1441 |
+
:param m:
|
1442 |
+
Matrix row dimension.
|
1443 |
+
:type m: int
|
1444 |
+
:param n:
|
1445 |
+
Matrix column dimension.
|
1446 |
+
:type n: int
|
1447 |
+
:param matveca:
|
1448 |
+
Function to apply the matrix adjoint to a vector, with call signature
|
1449 |
+
`y = matveca(x)`, where `x` and `y` are the input and output vectors,
|
1450 |
+
respectively.
|
1451 |
+
:type matveca: function
|
1452 |
+
|
1453 |
+
:return:
|
1454 |
+
Rank estimate.
|
1455 |
+
:rtype: int
|
1456 |
+
"""
|
1457 |
+
k, ra, ier = _id.idz_findrank(eps, m, n, matveca)
|
1458 |
+
if ier:
|
1459 |
+
raise _RETCODE_ERROR
|
1460 |
+
return k
|
1461 |
+
|
1462 |
+
|
1463 |
+
#------------------------------------------------------------------------------
|
1464 |
+
# idzp_rsvd.f
|
1465 |
+
#------------------------------------------------------------------------------
|
1466 |
+
|
1467 |
+
def idzp_rsvd(eps, m, n, matveca, matvec):
|
1468 |
+
"""
|
1469 |
+
Compute SVD of a complex matrix to a specified relative precision using
|
1470 |
+
random matrix-vector multiplication.
|
1471 |
+
|
1472 |
+
:param eps:
|
1473 |
+
Relative precision.
|
1474 |
+
:type eps: float
|
1475 |
+
:param m:
|
1476 |
+
Matrix row dimension.
|
1477 |
+
:type m: int
|
1478 |
+
:param n:
|
1479 |
+
Matrix column dimension.
|
1480 |
+
:type n: int
|
1481 |
+
:param matveca:
|
1482 |
+
Function to apply the matrix adjoint to a vector, with call signature
|
1483 |
+
`y = matveca(x)`, where `x` and `y` are the input and output vectors,
|
1484 |
+
respectively.
|
1485 |
+
:type matveca: function
|
1486 |
+
:param matvec:
|
1487 |
+
Function to apply the matrix to a vector, with call signature
|
1488 |
+
`y = matvec(x)`, where `x` and `y` are the input and output vectors,
|
1489 |
+
respectively.
|
1490 |
+
:type matvec: function
|
1491 |
+
|
1492 |
+
:return:
|
1493 |
+
Left singular vectors.
|
1494 |
+
:rtype: :class:`numpy.ndarray`
|
1495 |
+
:return:
|
1496 |
+
Right singular vectors.
|
1497 |
+
:rtype: :class:`numpy.ndarray`
|
1498 |
+
:return:
|
1499 |
+
Singular values.
|
1500 |
+
:rtype: :class:`numpy.ndarray`
|
1501 |
+
"""
|
1502 |
+
k, iU, iV, iS, w, ier = _id.idzp_rsvd(eps, m, n, matveca, matvec)
|
1503 |
+
if ier:
|
1504 |
+
raise _RETCODE_ERROR
|
1505 |
+
U = w[iU-1:iU+m*k-1].reshape((m, k), order='F')
|
1506 |
+
V = w[iV-1:iV+n*k-1].reshape((n, k), order='F')
|
1507 |
+
S = w[iS-1:iS+k-1]
|
1508 |
+
return U, V, S
|
1509 |
+
|
1510 |
+
|
1511 |
+
#------------------------------------------------------------------------------
|
1512 |
+
# idzr_aid.f
|
1513 |
+
#------------------------------------------------------------------------------
|
1514 |
+
|
1515 |
+
def idzr_aid(A, k):
|
1516 |
+
"""
|
1517 |
+
Compute ID of a complex matrix to a specified rank using random sampling.
|
1518 |
+
|
1519 |
+
:param A:
|
1520 |
+
Matrix.
|
1521 |
+
:type A: :class:`numpy.ndarray`
|
1522 |
+
:param k:
|
1523 |
+
Rank of ID.
|
1524 |
+
:type k: int
|
1525 |
+
|
1526 |
+
:return:
|
1527 |
+
Column index array.
|
1528 |
+
:rtype: :class:`numpy.ndarray`
|
1529 |
+
:return:
|
1530 |
+
Interpolation coefficients.
|
1531 |
+
:rtype: :class:`numpy.ndarray`
|
1532 |
+
"""
|
1533 |
+
A = np.asfortranarray(A)
|
1534 |
+
m, n = A.shape
|
1535 |
+
w = idzr_aidi(m, n, k)
|
1536 |
+
idx, proj = _id.idzr_aid(A, k, w)
|
1537 |
+
if k == n:
|
1538 |
+
proj = np.empty((k, n-k), dtype='complex128', order='F')
|
1539 |
+
else:
|
1540 |
+
proj = proj.reshape((k, n-k), order='F')
|
1541 |
+
return idx, proj
|
1542 |
+
|
1543 |
+
|
1544 |
+
def idzr_aidi(m, n, k):
|
1545 |
+
"""
|
1546 |
+
Initialize array for :func:`idzr_aid`.
|
1547 |
+
|
1548 |
+
:param m:
|
1549 |
+
Matrix row dimension.
|
1550 |
+
:type m: int
|
1551 |
+
:param n:
|
1552 |
+
Matrix column dimension.
|
1553 |
+
:type n: int
|
1554 |
+
:param k:
|
1555 |
+
Rank of ID.
|
1556 |
+
:type k: int
|
1557 |
+
|
1558 |
+
:return:
|
1559 |
+
Initialization array to be used by :func:`idzr_aid`.
|
1560 |
+
:rtype: :class:`numpy.ndarray`
|
1561 |
+
"""
|
1562 |
+
return _id.idzr_aidi(m, n, k)
|
1563 |
+
|
1564 |
+
|
1565 |
+
#------------------------------------------------------------------------------
|
1566 |
+
# idzr_asvd.f
|
1567 |
+
#------------------------------------------------------------------------------
|
1568 |
+
|
1569 |
+
def idzr_asvd(A, k):
|
1570 |
+
"""
|
1571 |
+
Compute SVD of a complex matrix to a specified rank using random sampling.
|
1572 |
+
|
1573 |
+
:param A:
|
1574 |
+
Matrix.
|
1575 |
+
:type A: :class:`numpy.ndarray`
|
1576 |
+
:param k:
|
1577 |
+
Rank of SVD.
|
1578 |
+
:type k: int
|
1579 |
+
|
1580 |
+
:return:
|
1581 |
+
Left singular vectors.
|
1582 |
+
:rtype: :class:`numpy.ndarray`
|
1583 |
+
:return:
|
1584 |
+
Right singular vectors.
|
1585 |
+
:rtype: :class:`numpy.ndarray`
|
1586 |
+
:return:
|
1587 |
+
Singular values.
|
1588 |
+
:rtype: :class:`numpy.ndarray`
|
1589 |
+
"""
|
1590 |
+
A = np.asfortranarray(A)
|
1591 |
+
m, n = A.shape
|
1592 |
+
w = np.empty(
|
1593 |
+
(2*k + 22)*m + (6*k + 21)*n + 8*k**2 + 10*k + 90,
|
1594 |
+
dtype='complex128', order='F')
|
1595 |
+
w_ = idzr_aidi(m, n, k)
|
1596 |
+
w[:w_.size] = w_
|
1597 |
+
U, V, S, ier = _id.idzr_asvd(A, k, w)
|
1598 |
+
if ier:
|
1599 |
+
raise _RETCODE_ERROR
|
1600 |
+
return U, V, S
|
1601 |
+
|
1602 |
+
|
1603 |
+
#------------------------------------------------------------------------------
|
1604 |
+
# idzr_rid.f
|
1605 |
+
#------------------------------------------------------------------------------
|
1606 |
+
|
1607 |
+
def idzr_rid(m, n, matveca, k):
|
1608 |
+
"""
|
1609 |
+
Compute ID of a complex matrix to a specified rank using random
|
1610 |
+
matrix-vector multiplication.
|
1611 |
+
|
1612 |
+
:param m:
|
1613 |
+
Matrix row dimension.
|
1614 |
+
:type m: int
|
1615 |
+
:param n:
|
1616 |
+
Matrix column dimension.
|
1617 |
+
:type n: int
|
1618 |
+
:param matveca:
|
1619 |
+
Function to apply the matrix adjoint to a vector, with call signature
|
1620 |
+
`y = matveca(x)`, where `x` and `y` are the input and output vectors,
|
1621 |
+
respectively.
|
1622 |
+
:type matveca: function
|
1623 |
+
:param k:
|
1624 |
+
Rank of ID.
|
1625 |
+
:type k: int
|
1626 |
+
|
1627 |
+
:return:
|
1628 |
+
Column index array.
|
1629 |
+
:rtype: :class:`numpy.ndarray`
|
1630 |
+
:return:
|
1631 |
+
Interpolation coefficients.
|
1632 |
+
:rtype: :class:`numpy.ndarray`
|
1633 |
+
"""
|
1634 |
+
idx, proj = _id.idzr_rid(m, n, matveca, k)
|
1635 |
+
proj = proj[:k*(n-k)].reshape((k, n-k), order='F')
|
1636 |
+
return idx, proj
|
1637 |
+
|
1638 |
+
|
1639 |
+
#------------------------------------------------------------------------------
|
1640 |
+
# idzr_rsvd.f
|
1641 |
+
#------------------------------------------------------------------------------
|
1642 |
+
|
1643 |
+
def idzr_rsvd(m, n, matveca, matvec, k):
|
1644 |
+
"""
|
1645 |
+
Compute SVD of a complex matrix to a specified rank using random
|
1646 |
+
matrix-vector multiplication.
|
1647 |
+
|
1648 |
+
:param m:
|
1649 |
+
Matrix row dimension.
|
1650 |
+
:type m: int
|
1651 |
+
:param n:
|
1652 |
+
Matrix column dimension.
|
1653 |
+
:type n: int
|
1654 |
+
:param matveca:
|
1655 |
+
Function to apply the matrix adjoint to a vector, with call signature
|
1656 |
+
`y = matveca(x)`, where `x` and `y` are the input and output vectors,
|
1657 |
+
respectively.
|
1658 |
+
:type matveca: function
|
1659 |
+
:param matvec:
|
1660 |
+
Function to apply the matrix to a vector, with call signature
|
1661 |
+
`y = matvec(x)`, where `x` and `y` are the input and output vectors,
|
1662 |
+
respectively.
|
1663 |
+
:type matvec: function
|
1664 |
+
:param k:
|
1665 |
+
Rank of SVD.
|
1666 |
+
:type k: int
|
1667 |
+
|
1668 |
+
:return:
|
1669 |
+
Left singular vectors.
|
1670 |
+
:rtype: :class:`numpy.ndarray`
|
1671 |
+
:return:
|
1672 |
+
Right singular vectors.
|
1673 |
+
:rtype: :class:`numpy.ndarray`
|
1674 |
+
:return:
|
1675 |
+
Singular values.
|
1676 |
+
:rtype: :class:`numpy.ndarray`
|
1677 |
+
"""
|
1678 |
+
U, V, S, ier = _id.idzr_rsvd(m, n, matveca, matvec, k)
|
1679 |
+
if ier:
|
1680 |
+
raise _RETCODE_ERROR
|
1681 |
+
return U, V, S
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from numpy.typing import NDArray
|
2 |
+
from typing import Any
|
3 |
+
|
4 |
+
def pick_pade_structure(a: NDArray[Any]) -> tuple[int, int]: ...
|
5 |
+
|
6 |
+
def pade_UV_calc(Am: NDArray[Any], n: int, m: int) -> None: ...
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py
ADDED
@@ -0,0 +1,886 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Matrix functions that use Pade approximation with inverse scaling and squaring.
|
3 |
+
|
4 |
+
"""
|
5 |
+
import warnings
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from scipy.linalg._matfuncs_sqrtm import SqrtmError, _sqrtm_triu
|
10 |
+
from scipy.linalg._decomp_schur import schur, rsf2csf
|
11 |
+
from scipy.linalg._matfuncs import funm
|
12 |
+
from scipy.linalg import svdvals, solve_triangular
|
13 |
+
from scipy.sparse.linalg._interface import LinearOperator
|
14 |
+
from scipy.sparse.linalg import onenormest
|
15 |
+
import scipy.special
|
16 |
+
|
17 |
+
|
18 |
+
class LogmRankWarning(UserWarning):
|
19 |
+
pass
|
20 |
+
|
21 |
+
|
22 |
+
class LogmExactlySingularWarning(LogmRankWarning):
|
23 |
+
pass
|
24 |
+
|
25 |
+
|
26 |
+
class LogmNearlySingularWarning(LogmRankWarning):
|
27 |
+
pass
|
28 |
+
|
29 |
+
|
30 |
+
class LogmError(np.linalg.LinAlgError):
|
31 |
+
pass
|
32 |
+
|
33 |
+
|
34 |
+
class FractionalMatrixPowerError(np.linalg.LinAlgError):
|
35 |
+
pass
|
36 |
+
|
37 |
+
|
38 |
+
#TODO renovate or move this class when scipy operators are more mature
|
39 |
+
class _MatrixM1PowerOperator(LinearOperator):
|
40 |
+
"""
|
41 |
+
A representation of the linear operator (A - I)^p.
|
42 |
+
"""
|
43 |
+
|
44 |
+
def __init__(self, A, p):
|
45 |
+
if A.ndim != 2 or A.shape[0] != A.shape[1]:
|
46 |
+
raise ValueError('expected A to be like a square matrix')
|
47 |
+
if p < 0 or p != int(p):
|
48 |
+
raise ValueError('expected p to be a non-negative integer')
|
49 |
+
self._A = A
|
50 |
+
self._p = p
|
51 |
+
self.ndim = A.ndim
|
52 |
+
self.shape = A.shape
|
53 |
+
|
54 |
+
def _matvec(self, x):
|
55 |
+
for i in range(self._p):
|
56 |
+
x = self._A.dot(x) - x
|
57 |
+
return x
|
58 |
+
|
59 |
+
def _rmatvec(self, x):
|
60 |
+
for i in range(self._p):
|
61 |
+
x = x.dot(self._A) - x
|
62 |
+
return x
|
63 |
+
|
64 |
+
def _matmat(self, X):
|
65 |
+
for i in range(self._p):
|
66 |
+
X = self._A.dot(X) - X
|
67 |
+
return X
|
68 |
+
|
69 |
+
def _adjoint(self):
|
70 |
+
return _MatrixM1PowerOperator(self._A.T, self._p)
|
71 |
+
|
72 |
+
|
73 |
+
#TODO renovate or move this function when SciPy operators are more mature
|
74 |
+
def _onenormest_m1_power(A, p,
|
75 |
+
t=2, itmax=5, compute_v=False, compute_w=False):
|
76 |
+
"""
|
77 |
+
Efficiently estimate the 1-norm of (A - I)^p.
|
78 |
+
|
79 |
+
Parameters
|
80 |
+
----------
|
81 |
+
A : ndarray
|
82 |
+
Matrix whose 1-norm of a power is to be computed.
|
83 |
+
p : int
|
84 |
+
Non-negative integer power.
|
85 |
+
t : int, optional
|
86 |
+
A positive parameter controlling the tradeoff between
|
87 |
+
accuracy versus time and memory usage.
|
88 |
+
Larger values take longer and use more memory
|
89 |
+
but give more accurate output.
|
90 |
+
itmax : int, optional
|
91 |
+
Use at most this many iterations.
|
92 |
+
compute_v : bool, optional
|
93 |
+
Request a norm-maximizing linear operator input vector if True.
|
94 |
+
compute_w : bool, optional
|
95 |
+
Request a norm-maximizing linear operator output vector if True.
|
96 |
+
|
97 |
+
Returns
|
98 |
+
-------
|
99 |
+
est : float
|
100 |
+
An underestimate of the 1-norm of the sparse matrix.
|
101 |
+
v : ndarray, optional
|
102 |
+
The vector such that ||Av||_1 == est*||v||_1.
|
103 |
+
It can be thought of as an input to the linear operator
|
104 |
+
that gives an output with particularly large norm.
|
105 |
+
w : ndarray, optional
|
106 |
+
The vector Av which has relatively large 1-norm.
|
107 |
+
It can be thought of as an output of the linear operator
|
108 |
+
that is relatively large in norm compared to the input.
|
109 |
+
|
110 |
+
"""
|
111 |
+
return onenormest(_MatrixM1PowerOperator(A, p),
|
112 |
+
t=t, itmax=itmax, compute_v=compute_v, compute_w=compute_w)
|
113 |
+
|
114 |
+
|
115 |
+
def _unwindk(z):
|
116 |
+
"""
|
117 |
+
Compute the scalar unwinding number.
|
118 |
+
|
119 |
+
Uses Eq. (5.3) in [1]_, and should be equal to (z - log(exp(z)) / (2 pi i).
|
120 |
+
Note that this definition differs in sign from the original definition
|
121 |
+
in equations (5, 6) in [2]_. The sign convention is justified in [3]_.
|
122 |
+
|
123 |
+
Parameters
|
124 |
+
----------
|
125 |
+
z : complex
|
126 |
+
A complex number.
|
127 |
+
|
128 |
+
Returns
|
129 |
+
-------
|
130 |
+
unwinding_number : integer
|
131 |
+
The scalar unwinding number of z.
|
132 |
+
|
133 |
+
References
|
134 |
+
----------
|
135 |
+
.. [1] Nicholas J. Higham and Lijing lin (2011)
|
136 |
+
"A Schur-Pade Algorithm for Fractional Powers of a Matrix."
|
137 |
+
SIAM Journal on Matrix Analysis and Applications,
|
138 |
+
32 (3). pp. 1056-1078. ISSN 0895-4798
|
139 |
+
|
140 |
+
.. [2] Robert M. Corless and David J. Jeffrey,
|
141 |
+
"The unwinding number." Newsletter ACM SIGSAM Bulletin
|
142 |
+
Volume 30, Issue 2, June 1996, Pages 28-35.
|
143 |
+
|
144 |
+
.. [3] Russell Bradford and Robert M. Corless and James H. Davenport and
|
145 |
+
David J. Jeffrey and Stephen M. Watt,
|
146 |
+
"Reasoning about the elementary functions of complex analysis"
|
147 |
+
Annals of Mathematics and Artificial Intelligence,
|
148 |
+
36: 303-318, 2002.
|
149 |
+
|
150 |
+
"""
|
151 |
+
return int(np.ceil((z.imag - np.pi) / (2*np.pi)))
|
152 |
+
|
153 |
+
|
154 |
+
def _briggs_helper_function(a, k):
|
155 |
+
"""
|
156 |
+
Computes r = a^(1 / (2^k)) - 1.
|
157 |
+
|
158 |
+
This is algorithm (2) of [1]_.
|
159 |
+
The purpose is to avoid a danger of subtractive cancellation.
|
160 |
+
For more computational efficiency it should probably be cythonized.
|
161 |
+
|
162 |
+
Parameters
|
163 |
+
----------
|
164 |
+
a : complex
|
165 |
+
A complex number.
|
166 |
+
k : integer
|
167 |
+
A nonnegative integer.
|
168 |
+
|
169 |
+
Returns
|
170 |
+
-------
|
171 |
+
r : complex
|
172 |
+
The value r = a^(1 / (2^k)) - 1 computed with less cancellation.
|
173 |
+
|
174 |
+
Notes
|
175 |
+
-----
|
176 |
+
The algorithm as formulated in the reference does not handle k=0 or k=1
|
177 |
+
correctly, so these are special-cased in this implementation.
|
178 |
+
This function is intended to not allow `a` to belong to the closed
|
179 |
+
negative real axis, but this constraint is relaxed.
|
180 |
+
|
181 |
+
References
|
182 |
+
----------
|
183 |
+
.. [1] Awad H. Al-Mohy (2012)
|
184 |
+
"A more accurate Briggs method for the logarithm",
|
185 |
+
Numerical Algorithms, 59 : 393--402.
|
186 |
+
|
187 |
+
"""
|
188 |
+
if k < 0 or int(k) != k:
|
189 |
+
raise ValueError('expected a nonnegative integer k')
|
190 |
+
if k == 0:
|
191 |
+
return a - 1
|
192 |
+
elif k == 1:
|
193 |
+
return np.sqrt(a) - 1
|
194 |
+
else:
|
195 |
+
k_hat = k
|
196 |
+
if np.angle(a) >= np.pi / 2:
|
197 |
+
a = np.sqrt(a)
|
198 |
+
k_hat = k - 1
|
199 |
+
z0 = a - 1
|
200 |
+
a = np.sqrt(a)
|
201 |
+
r = 1 + a
|
202 |
+
for j in range(1, k_hat):
|
203 |
+
a = np.sqrt(a)
|
204 |
+
r = r * (1 + a)
|
205 |
+
r = z0 / r
|
206 |
+
return r
|
207 |
+
|
208 |
+
|
209 |
+
def _fractional_power_superdiag_entry(l1, l2, t12, p):
|
210 |
+
"""
|
211 |
+
Compute a superdiagonal entry of a fractional matrix power.
|
212 |
+
|
213 |
+
This is Eq. (5.6) in [1]_.
|
214 |
+
|
215 |
+
Parameters
|
216 |
+
----------
|
217 |
+
l1 : complex
|
218 |
+
A diagonal entry of the matrix.
|
219 |
+
l2 : complex
|
220 |
+
A diagonal entry of the matrix.
|
221 |
+
t12 : complex
|
222 |
+
A superdiagonal entry of the matrix.
|
223 |
+
p : float
|
224 |
+
A fractional power.
|
225 |
+
|
226 |
+
Returns
|
227 |
+
-------
|
228 |
+
f12 : complex
|
229 |
+
A superdiagonal entry of the fractional matrix power.
|
230 |
+
|
231 |
+
Notes
|
232 |
+
-----
|
233 |
+
Care has been taken to return a real number if possible when
|
234 |
+
all of the inputs are real numbers.
|
235 |
+
|
236 |
+
References
|
237 |
+
----------
|
238 |
+
.. [1] Nicholas J. Higham and Lijing lin (2011)
|
239 |
+
"A Schur-Pade Algorithm for Fractional Powers of a Matrix."
|
240 |
+
SIAM Journal on Matrix Analysis and Applications,
|
241 |
+
32 (3). pp. 1056-1078. ISSN 0895-4798
|
242 |
+
|
243 |
+
"""
|
244 |
+
if l1 == l2:
|
245 |
+
f12 = t12 * p * l1**(p-1)
|
246 |
+
elif abs(l2 - l1) > abs(l1 + l2) / 2:
|
247 |
+
f12 = t12 * ((l2**p) - (l1**p)) / (l2 - l1)
|
248 |
+
else:
|
249 |
+
# This is Eq. (5.5) in [1].
|
250 |
+
z = (l2 - l1) / (l2 + l1)
|
251 |
+
log_l1 = np.log(l1)
|
252 |
+
log_l2 = np.log(l2)
|
253 |
+
arctanh_z = np.arctanh(z)
|
254 |
+
tmp_a = t12 * np.exp((p/2)*(log_l2 + log_l1))
|
255 |
+
tmp_u = _unwindk(log_l2 - log_l1)
|
256 |
+
if tmp_u:
|
257 |
+
tmp_b = p * (arctanh_z + np.pi * 1j * tmp_u)
|
258 |
+
else:
|
259 |
+
tmp_b = p * arctanh_z
|
260 |
+
tmp_c = 2 * np.sinh(tmp_b) / (l2 - l1)
|
261 |
+
f12 = tmp_a * tmp_c
|
262 |
+
return f12
|
263 |
+
|
264 |
+
|
265 |
+
def _logm_superdiag_entry(l1, l2, t12):
|
266 |
+
"""
|
267 |
+
Compute a superdiagonal entry of a matrix logarithm.
|
268 |
+
|
269 |
+
This is like Eq. (11.28) in [1]_, except the determination of whether
|
270 |
+
l1 and l2 are sufficiently far apart has been modified.
|
271 |
+
|
272 |
+
Parameters
|
273 |
+
----------
|
274 |
+
l1 : complex
|
275 |
+
A diagonal entry of the matrix.
|
276 |
+
l2 : complex
|
277 |
+
A diagonal entry of the matrix.
|
278 |
+
t12 : complex
|
279 |
+
A superdiagonal entry of the matrix.
|
280 |
+
|
281 |
+
Returns
|
282 |
+
-------
|
283 |
+
f12 : complex
|
284 |
+
A superdiagonal entry of the matrix logarithm.
|
285 |
+
|
286 |
+
Notes
|
287 |
+
-----
|
288 |
+
Care has been taken to return a real number if possible when
|
289 |
+
all of the inputs are real numbers.
|
290 |
+
|
291 |
+
References
|
292 |
+
----------
|
293 |
+
.. [1] Nicholas J. Higham (2008)
|
294 |
+
"Functions of Matrices: Theory and Computation"
|
295 |
+
ISBN 978-0-898716-46-7
|
296 |
+
|
297 |
+
"""
|
298 |
+
if l1 == l2:
|
299 |
+
f12 = t12 / l1
|
300 |
+
elif abs(l2 - l1) > abs(l1 + l2) / 2:
|
301 |
+
f12 = t12 * (np.log(l2) - np.log(l1)) / (l2 - l1)
|
302 |
+
else:
|
303 |
+
z = (l2 - l1) / (l2 + l1)
|
304 |
+
u = _unwindk(np.log(l2) - np.log(l1))
|
305 |
+
if u:
|
306 |
+
f12 = t12 * 2 * (np.arctanh(z) + np.pi*1j*u) / (l2 - l1)
|
307 |
+
else:
|
308 |
+
f12 = t12 * 2 * np.arctanh(z) / (l2 - l1)
|
309 |
+
return f12
|
310 |
+
|
311 |
+
|
312 |
+
def _inverse_squaring_helper(T0, theta):
|
313 |
+
"""
|
314 |
+
A helper function for inverse scaling and squaring for Pade approximation.
|
315 |
+
|
316 |
+
Parameters
|
317 |
+
----------
|
318 |
+
T0 : (N, N) array_like upper triangular
|
319 |
+
Matrix involved in inverse scaling and squaring.
|
320 |
+
theta : indexable
|
321 |
+
The values theta[1] .. theta[7] must be available.
|
322 |
+
They represent bounds related to Pade approximation, and they depend
|
323 |
+
on the matrix function which is being computed.
|
324 |
+
For example, different values of theta are required for
|
325 |
+
matrix logarithm than for fractional matrix power.
|
326 |
+
|
327 |
+
Returns
|
328 |
+
-------
|
329 |
+
R : (N, N) array_like upper triangular
|
330 |
+
Composition of zero or more matrix square roots of T0, minus I.
|
331 |
+
s : non-negative integer
|
332 |
+
Number of square roots taken.
|
333 |
+
m : positive integer
|
334 |
+
The degree of the Pade approximation.
|
335 |
+
|
336 |
+
Notes
|
337 |
+
-----
|
338 |
+
This subroutine appears as a chunk of lines within
|
339 |
+
a couple of published algorithms; for example it appears
|
340 |
+
as lines 4--35 in algorithm (3.1) of [1]_, and
|
341 |
+
as lines 3--34 in algorithm (4.1) of [2]_.
|
342 |
+
The instances of 'goto line 38' in algorithm (3.1) of [1]_
|
343 |
+
probably mean 'goto line 36' and have been interpreted accordingly.
|
344 |
+
|
345 |
+
References
|
346 |
+
----------
|
347 |
+
.. [1] Nicholas J. Higham and Lijing Lin (2013)
|
348 |
+
"An Improved Schur-Pade Algorithm for Fractional Powers
|
349 |
+
of a Matrix and their Frechet Derivatives."
|
350 |
+
|
351 |
+
.. [2] Awad H. Al-Mohy and Nicholas J. Higham (2012)
|
352 |
+
"Improved Inverse Scaling and Squaring Algorithms
|
353 |
+
for the Matrix Logarithm."
|
354 |
+
SIAM Journal on Scientific Computing, 34 (4). C152-C169.
|
355 |
+
ISSN 1095-7197
|
356 |
+
|
357 |
+
"""
|
358 |
+
if len(T0.shape) != 2 or T0.shape[0] != T0.shape[1]:
|
359 |
+
raise ValueError('expected an upper triangular square matrix')
|
360 |
+
n, n = T0.shape
|
361 |
+
T = T0
|
362 |
+
|
363 |
+
# Find s0, the smallest s such that the spectral radius
|
364 |
+
# of a certain diagonal matrix is at most theta[7].
|
365 |
+
# Note that because theta[7] < 1,
|
366 |
+
# this search will not terminate if any diagonal entry of T is zero.
|
367 |
+
s0 = 0
|
368 |
+
tmp_diag = np.diag(T)
|
369 |
+
if np.count_nonzero(tmp_diag) != n:
|
370 |
+
raise Exception('Diagonal entries of T must be nonzero')
|
371 |
+
while np.max(np.absolute(tmp_diag - 1)) > theta[7]:
|
372 |
+
tmp_diag = np.sqrt(tmp_diag)
|
373 |
+
s0 += 1
|
374 |
+
|
375 |
+
# Take matrix square roots of T.
|
376 |
+
for i in range(s0):
|
377 |
+
T = _sqrtm_triu(T)
|
378 |
+
|
379 |
+
# Flow control in this section is a little odd.
|
380 |
+
# This is because I am translating algorithm descriptions
|
381 |
+
# which have GOTOs in the publication.
|
382 |
+
s = s0
|
383 |
+
k = 0
|
384 |
+
d2 = _onenormest_m1_power(T, 2) ** (1/2)
|
385 |
+
d3 = _onenormest_m1_power(T, 3) ** (1/3)
|
386 |
+
a2 = max(d2, d3)
|
387 |
+
m = None
|
388 |
+
for i in (1, 2):
|
389 |
+
if a2 <= theta[i]:
|
390 |
+
m = i
|
391 |
+
break
|
392 |
+
while m is None:
|
393 |
+
if s > s0:
|
394 |
+
d3 = _onenormest_m1_power(T, 3) ** (1/3)
|
395 |
+
d4 = _onenormest_m1_power(T, 4) ** (1/4)
|
396 |
+
a3 = max(d3, d4)
|
397 |
+
if a3 <= theta[7]:
|
398 |
+
j1 = min(i for i in (3, 4, 5, 6, 7) if a3 <= theta[i])
|
399 |
+
if j1 <= 6:
|
400 |
+
m = j1
|
401 |
+
break
|
402 |
+
elif a3 / 2 <= theta[5] and k < 2:
|
403 |
+
k += 1
|
404 |
+
T = _sqrtm_triu(T)
|
405 |
+
s += 1
|
406 |
+
continue
|
407 |
+
d5 = _onenormest_m1_power(T, 5) ** (1/5)
|
408 |
+
a4 = max(d4, d5)
|
409 |
+
eta = min(a3, a4)
|
410 |
+
for i in (6, 7):
|
411 |
+
if eta <= theta[i]:
|
412 |
+
m = i
|
413 |
+
break
|
414 |
+
if m is not None:
|
415 |
+
break
|
416 |
+
T = _sqrtm_triu(T)
|
417 |
+
s += 1
|
418 |
+
|
419 |
+
# The subtraction of the identity is redundant here,
|
420 |
+
# because the diagonal will be replaced for improved numerical accuracy,
|
421 |
+
# but this formulation should help clarify the meaning of R.
|
422 |
+
R = T - np.identity(n)
|
423 |
+
|
424 |
+
# Replace the diagonal and first superdiagonal of T0^(1/(2^s)) - I
|
425 |
+
# using formulas that have less subtractive cancellation.
|
426 |
+
# Skip this step if the principal branch
|
427 |
+
# does not exist at T0; this happens when a diagonal entry of T0
|
428 |
+
# is negative with imaginary part 0.
|
429 |
+
has_principal_branch = all(x.real > 0 or x.imag != 0 for x in np.diag(T0))
|
430 |
+
if has_principal_branch:
|
431 |
+
for j in range(n):
|
432 |
+
a = T0[j, j]
|
433 |
+
r = _briggs_helper_function(a, s)
|
434 |
+
R[j, j] = r
|
435 |
+
p = np.exp2(-s)
|
436 |
+
for j in range(n-1):
|
437 |
+
l1 = T0[j, j]
|
438 |
+
l2 = T0[j+1, j+1]
|
439 |
+
t12 = T0[j, j+1]
|
440 |
+
f12 = _fractional_power_superdiag_entry(l1, l2, t12, p)
|
441 |
+
R[j, j+1] = f12
|
442 |
+
|
443 |
+
# Return the T-I matrix, the number of square roots, and the Pade degree.
|
444 |
+
if not np.array_equal(R, np.triu(R)):
|
445 |
+
raise Exception('R is not upper triangular')
|
446 |
+
return R, s, m
|
447 |
+
|
448 |
+
|
449 |
+
def _fractional_power_pade_constant(i, t):
|
450 |
+
# A helper function for matrix fractional power.
|
451 |
+
if i < 1:
|
452 |
+
raise ValueError('expected a positive integer i')
|
453 |
+
if not (-1 < t < 1):
|
454 |
+
raise ValueError('expected -1 < t < 1')
|
455 |
+
if i == 1:
|
456 |
+
return -t
|
457 |
+
elif i % 2 == 0:
|
458 |
+
j = i // 2
|
459 |
+
return (-j + t) / (2 * (2*j - 1))
|
460 |
+
elif i % 2 == 1:
|
461 |
+
j = (i - 1) // 2
|
462 |
+
return (-j - t) / (2 * (2*j + 1))
|
463 |
+
else:
|
464 |
+
raise Exception(f'unnexpected value of i, i = {i}')
|
465 |
+
|
466 |
+
|
467 |
+
def _fractional_power_pade(R, t, m):
|
468 |
+
"""
|
469 |
+
Evaluate the Pade approximation of a fractional matrix power.
|
470 |
+
|
471 |
+
Evaluate the degree-m Pade approximation of R
|
472 |
+
to the fractional matrix power t using the continued fraction
|
473 |
+
in bottom-up fashion using algorithm (4.1) in [1]_.
|
474 |
+
|
475 |
+
Parameters
|
476 |
+
----------
|
477 |
+
R : (N, N) array_like
|
478 |
+
Upper triangular matrix whose fractional power to evaluate.
|
479 |
+
t : float
|
480 |
+
Fractional power between -1 and 1 exclusive.
|
481 |
+
m : positive integer
|
482 |
+
Degree of Pade approximation.
|
483 |
+
|
484 |
+
Returns
|
485 |
+
-------
|
486 |
+
U : (N, N) array_like
|
487 |
+
The degree-m Pade approximation of R to the fractional power t.
|
488 |
+
This matrix will be upper triangular.
|
489 |
+
|
490 |
+
References
|
491 |
+
----------
|
492 |
+
.. [1] Nicholas J. Higham and Lijing lin (2011)
|
493 |
+
"A Schur-Pade Algorithm for Fractional Powers of a Matrix."
|
494 |
+
SIAM Journal on Matrix Analysis and Applications,
|
495 |
+
32 (3). pp. 1056-1078. ISSN 0895-4798
|
496 |
+
|
497 |
+
"""
|
498 |
+
if m < 1 or int(m) != m:
|
499 |
+
raise ValueError('expected a positive integer m')
|
500 |
+
if not (-1 < t < 1):
|
501 |
+
raise ValueError('expected -1 < t < 1')
|
502 |
+
R = np.asarray(R)
|
503 |
+
if len(R.shape) != 2 or R.shape[0] != R.shape[1]:
|
504 |
+
raise ValueError('expected an upper triangular square matrix')
|
505 |
+
n, n = R.shape
|
506 |
+
ident = np.identity(n)
|
507 |
+
Y = R * _fractional_power_pade_constant(2*m, t)
|
508 |
+
for j in range(2*m - 1, 0, -1):
|
509 |
+
rhs = R * _fractional_power_pade_constant(j, t)
|
510 |
+
Y = solve_triangular(ident + Y, rhs)
|
511 |
+
U = ident + Y
|
512 |
+
if not np.array_equal(U, np.triu(U)):
|
513 |
+
raise Exception('U is not upper triangular')
|
514 |
+
return U
|
515 |
+
|
516 |
+
|
517 |
+
def _remainder_matrix_power_triu(T, t):
|
518 |
+
"""
|
519 |
+
Compute a fractional power of an upper triangular matrix.
|
520 |
+
|
521 |
+
The fractional power is restricted to fractions -1 < t < 1.
|
522 |
+
This uses algorithm (3.1) of [1]_.
|
523 |
+
The Pade approximation itself uses algorithm (4.1) of [2]_.
|
524 |
+
|
525 |
+
Parameters
|
526 |
+
----------
|
527 |
+
T : (N, N) array_like
|
528 |
+
Upper triangular matrix whose fractional power to evaluate.
|
529 |
+
t : float
|
530 |
+
Fractional power between -1 and 1 exclusive.
|
531 |
+
|
532 |
+
Returns
|
533 |
+
-------
|
534 |
+
X : (N, N) array_like
|
535 |
+
The fractional power of the matrix.
|
536 |
+
|
537 |
+
References
|
538 |
+
----------
|
539 |
+
.. [1] Nicholas J. Higham and Lijing Lin (2013)
|
540 |
+
"An Improved Schur-Pade Algorithm for Fractional Powers
|
541 |
+
of a Matrix and their Frechet Derivatives."
|
542 |
+
|
543 |
+
.. [2] Nicholas J. Higham and Lijing lin (2011)
|
544 |
+
"A Schur-Pade Algorithm for Fractional Powers of a Matrix."
|
545 |
+
SIAM Journal on Matrix Analysis and Applications,
|
546 |
+
32 (3). pp. 1056-1078. ISSN 0895-4798
|
547 |
+
|
548 |
+
"""
|
549 |
+
m_to_theta = {
|
550 |
+
1: 1.51e-5,
|
551 |
+
2: 2.24e-3,
|
552 |
+
3: 1.88e-2,
|
553 |
+
4: 6.04e-2,
|
554 |
+
5: 1.24e-1,
|
555 |
+
6: 2.00e-1,
|
556 |
+
7: 2.79e-1,
|
557 |
+
}
|
558 |
+
n, n = T.shape
|
559 |
+
T0 = T
|
560 |
+
T0_diag = np.diag(T0)
|
561 |
+
if np.array_equal(T0, np.diag(T0_diag)):
|
562 |
+
U = np.diag(T0_diag ** t)
|
563 |
+
else:
|
564 |
+
R, s, m = _inverse_squaring_helper(T0, m_to_theta)
|
565 |
+
|
566 |
+
# Evaluate the Pade approximation.
|
567 |
+
# Note that this function expects the negative of the matrix
|
568 |
+
# returned by the inverse squaring helper.
|
569 |
+
U = _fractional_power_pade(-R, t, m)
|
570 |
+
|
571 |
+
# Undo the inverse scaling and squaring.
|
572 |
+
# Be less clever about this
|
573 |
+
# if the principal branch does not exist at T0;
|
574 |
+
# this happens when a diagonal entry of T0
|
575 |
+
# is negative with imaginary part 0.
|
576 |
+
eivals = np.diag(T0)
|
577 |
+
has_principal_branch = all(x.real > 0 or x.imag != 0 for x in eivals)
|
578 |
+
for i in range(s, -1, -1):
|
579 |
+
if i < s:
|
580 |
+
U = U.dot(U)
|
581 |
+
else:
|
582 |
+
if has_principal_branch:
|
583 |
+
p = t * np.exp2(-i)
|
584 |
+
U[np.diag_indices(n)] = T0_diag ** p
|
585 |
+
for j in range(n-1):
|
586 |
+
l1 = T0[j, j]
|
587 |
+
l2 = T0[j+1, j+1]
|
588 |
+
t12 = T0[j, j+1]
|
589 |
+
f12 = _fractional_power_superdiag_entry(l1, l2, t12, p)
|
590 |
+
U[j, j+1] = f12
|
591 |
+
if not np.array_equal(U, np.triu(U)):
|
592 |
+
raise Exception('U is not upper triangular')
|
593 |
+
return U
|
594 |
+
|
595 |
+
|
596 |
+
def _remainder_matrix_power(A, t):
|
597 |
+
"""
|
598 |
+
Compute the fractional power of a matrix, for fractions -1 < t < 1.
|
599 |
+
|
600 |
+
This uses algorithm (3.1) of [1]_.
|
601 |
+
The Pade approximation itself uses algorithm (4.1) of [2]_.
|
602 |
+
|
603 |
+
Parameters
|
604 |
+
----------
|
605 |
+
A : (N, N) array_like
|
606 |
+
Matrix whose fractional power to evaluate.
|
607 |
+
t : float
|
608 |
+
Fractional power between -1 and 1 exclusive.
|
609 |
+
|
610 |
+
Returns
|
611 |
+
-------
|
612 |
+
X : (N, N) array_like
|
613 |
+
The fractional power of the matrix.
|
614 |
+
|
615 |
+
References
|
616 |
+
----------
|
617 |
+
.. [1] Nicholas J. Higham and Lijing Lin (2013)
|
618 |
+
"An Improved Schur-Pade Algorithm for Fractional Powers
|
619 |
+
of a Matrix and their Frechet Derivatives."
|
620 |
+
|
621 |
+
.. [2] Nicholas J. Higham and Lijing lin (2011)
|
622 |
+
"A Schur-Pade Algorithm for Fractional Powers of a Matrix."
|
623 |
+
SIAM Journal on Matrix Analysis and Applications,
|
624 |
+
32 (3). pp. 1056-1078. ISSN 0895-4798
|
625 |
+
|
626 |
+
"""
|
627 |
+
# This code block is copied from numpy.matrix_power().
|
628 |
+
A = np.asarray(A)
|
629 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
630 |
+
raise ValueError('input must be a square array')
|
631 |
+
|
632 |
+
# Get the number of rows and columns.
|
633 |
+
n, n = A.shape
|
634 |
+
|
635 |
+
# Triangularize the matrix if necessary,
|
636 |
+
# attempting to preserve dtype if possible.
|
637 |
+
if np.array_equal(A, np.triu(A)):
|
638 |
+
Z = None
|
639 |
+
T = A
|
640 |
+
else:
|
641 |
+
if np.isrealobj(A):
|
642 |
+
T, Z = schur(A)
|
643 |
+
if not np.array_equal(T, np.triu(T)):
|
644 |
+
T, Z = rsf2csf(T, Z)
|
645 |
+
else:
|
646 |
+
T, Z = schur(A, output='complex')
|
647 |
+
|
648 |
+
# Zeros on the diagonal of the triangular matrix are forbidden,
|
649 |
+
# because the inverse scaling and squaring cannot deal with it.
|
650 |
+
T_diag = np.diag(T)
|
651 |
+
if np.count_nonzero(T_diag) != n:
|
652 |
+
raise FractionalMatrixPowerError(
|
653 |
+
'cannot use inverse scaling and squaring to find '
|
654 |
+
'the fractional matrix power of a singular matrix')
|
655 |
+
|
656 |
+
# If the triangular matrix is real and has a negative
|
657 |
+
# entry on the diagonal, then force the matrix to be complex.
|
658 |
+
if np.isrealobj(T) and np.min(T_diag) < 0:
|
659 |
+
T = T.astype(complex)
|
660 |
+
|
661 |
+
# Get the fractional power of the triangular matrix,
|
662 |
+
# and de-triangularize it if necessary.
|
663 |
+
U = _remainder_matrix_power_triu(T, t)
|
664 |
+
if Z is not None:
|
665 |
+
ZH = np.conjugate(Z).T
|
666 |
+
return Z.dot(U).dot(ZH)
|
667 |
+
else:
|
668 |
+
return U
|
669 |
+
|
670 |
+
|
671 |
+
def _fractional_matrix_power(A, p):
|
672 |
+
"""
|
673 |
+
Compute the fractional power of a matrix.
|
674 |
+
|
675 |
+
See the fractional_matrix_power docstring in matfuncs.py for more info.
|
676 |
+
|
677 |
+
"""
|
678 |
+
A = np.asarray(A)
|
679 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
680 |
+
raise ValueError('expected a square matrix')
|
681 |
+
if p == int(p):
|
682 |
+
return np.linalg.matrix_power(A, int(p))
|
683 |
+
# Compute singular values.
|
684 |
+
s = svdvals(A)
|
685 |
+
# Inverse scaling and squaring cannot deal with a singular matrix,
|
686 |
+
# because the process of repeatedly taking square roots
|
687 |
+
# would not converge to the identity matrix.
|
688 |
+
if s[-1]:
|
689 |
+
# Compute the condition number relative to matrix inversion,
|
690 |
+
# and use this to decide between floor(p) and ceil(p).
|
691 |
+
k2 = s[0] / s[-1]
|
692 |
+
p1 = p - np.floor(p)
|
693 |
+
p2 = p - np.ceil(p)
|
694 |
+
if p1 * k2 ** (1 - p1) <= -p2 * k2:
|
695 |
+
a = int(np.floor(p))
|
696 |
+
b = p1
|
697 |
+
else:
|
698 |
+
a = int(np.ceil(p))
|
699 |
+
b = p2
|
700 |
+
try:
|
701 |
+
R = _remainder_matrix_power(A, b)
|
702 |
+
Q = np.linalg.matrix_power(A, a)
|
703 |
+
return Q.dot(R)
|
704 |
+
except np.linalg.LinAlgError:
|
705 |
+
pass
|
706 |
+
# If p is negative then we are going to give up.
|
707 |
+
# If p is non-negative then we can fall back to generic funm.
|
708 |
+
if p < 0:
|
709 |
+
X = np.empty_like(A)
|
710 |
+
X.fill(np.nan)
|
711 |
+
return X
|
712 |
+
else:
|
713 |
+
p1 = p - np.floor(p)
|
714 |
+
a = int(np.floor(p))
|
715 |
+
b = p1
|
716 |
+
R, info = funm(A, lambda x: pow(x, b), disp=False)
|
717 |
+
Q = np.linalg.matrix_power(A, a)
|
718 |
+
return Q.dot(R)
|
719 |
+
|
720 |
+
|
721 |
+
def _logm_triu(T):
|
722 |
+
"""
|
723 |
+
Compute matrix logarithm of an upper triangular matrix.
|
724 |
+
|
725 |
+
The matrix logarithm is the inverse of
|
726 |
+
expm: expm(logm(`T`)) == `T`
|
727 |
+
|
728 |
+
Parameters
|
729 |
+
----------
|
730 |
+
T : (N, N) array_like
|
731 |
+
Upper triangular matrix whose logarithm to evaluate
|
732 |
+
|
733 |
+
Returns
|
734 |
+
-------
|
735 |
+
logm : (N, N) ndarray
|
736 |
+
Matrix logarithm of `T`
|
737 |
+
|
738 |
+
References
|
739 |
+
----------
|
740 |
+
.. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012)
|
741 |
+
"Improved Inverse Scaling and Squaring Algorithms
|
742 |
+
for the Matrix Logarithm."
|
743 |
+
SIAM Journal on Scientific Computing, 34 (4). C152-C169.
|
744 |
+
ISSN 1095-7197
|
745 |
+
|
746 |
+
.. [2] Nicholas J. Higham (2008)
|
747 |
+
"Functions of Matrices: Theory and Computation"
|
748 |
+
ISBN 978-0-898716-46-7
|
749 |
+
|
750 |
+
.. [3] Nicholas J. Higham and Lijing lin (2011)
|
751 |
+
"A Schur-Pade Algorithm for Fractional Powers of a Matrix."
|
752 |
+
SIAM Journal on Matrix Analysis and Applications,
|
753 |
+
32 (3). pp. 1056-1078. ISSN 0895-4798
|
754 |
+
|
755 |
+
"""
|
756 |
+
T = np.asarray(T)
|
757 |
+
if len(T.shape) != 2 or T.shape[0] != T.shape[1]:
|
758 |
+
raise ValueError('expected an upper triangular square matrix')
|
759 |
+
n, n = T.shape
|
760 |
+
|
761 |
+
# Construct T0 with the appropriate type,
|
762 |
+
# depending on the dtype and the spectrum of T.
|
763 |
+
T_diag = np.diag(T)
|
764 |
+
keep_it_real = np.isrealobj(T) and np.min(T_diag) >= 0
|
765 |
+
if keep_it_real:
|
766 |
+
T0 = T
|
767 |
+
else:
|
768 |
+
T0 = T.astype(complex)
|
769 |
+
|
770 |
+
# Define bounds given in Table (2.1).
|
771 |
+
theta = (None,
|
772 |
+
1.59e-5, 2.31e-3, 1.94e-2, 6.21e-2,
|
773 |
+
1.28e-1, 2.06e-1, 2.88e-1, 3.67e-1,
|
774 |
+
4.39e-1, 5.03e-1, 5.60e-1, 6.09e-1,
|
775 |
+
6.52e-1, 6.89e-1, 7.21e-1, 7.49e-1)
|
776 |
+
|
777 |
+
R, s, m = _inverse_squaring_helper(T0, theta)
|
778 |
+
|
779 |
+
# Evaluate U = 2**s r_m(T - I) using the partial fraction expansion (1.1).
|
780 |
+
# This requires the nodes and weights
|
781 |
+
# corresponding to degree-m Gauss-Legendre quadrature.
|
782 |
+
# These quadrature arrays need to be transformed from the [-1, 1] interval
|
783 |
+
# to the [0, 1] interval.
|
784 |
+
nodes, weights = scipy.special.p_roots(m)
|
785 |
+
nodes = nodes.real
|
786 |
+
if nodes.shape != (m,) or weights.shape != (m,):
|
787 |
+
raise Exception('internal error')
|
788 |
+
nodes = 0.5 + 0.5 * nodes
|
789 |
+
weights = 0.5 * weights
|
790 |
+
ident = np.identity(n)
|
791 |
+
U = np.zeros_like(R)
|
792 |
+
for alpha, beta in zip(weights, nodes):
|
793 |
+
U += solve_triangular(ident + beta*R, alpha*R)
|
794 |
+
U *= np.exp2(s)
|
795 |
+
|
796 |
+
# Skip this step if the principal branch
|
797 |
+
# does not exist at T0; this happens when a diagonal entry of T0
|
798 |
+
# is negative with imaginary part 0.
|
799 |
+
has_principal_branch = all(x.real > 0 or x.imag != 0 for x in np.diag(T0))
|
800 |
+
if has_principal_branch:
|
801 |
+
|
802 |
+
# Recompute diagonal entries of U.
|
803 |
+
U[np.diag_indices(n)] = np.log(np.diag(T0))
|
804 |
+
|
805 |
+
# Recompute superdiagonal entries of U.
|
806 |
+
# This indexing of this code should be renovated
|
807 |
+
# when newer np.diagonal() becomes available.
|
808 |
+
for i in range(n-1):
|
809 |
+
l1 = T0[i, i]
|
810 |
+
l2 = T0[i+1, i+1]
|
811 |
+
t12 = T0[i, i+1]
|
812 |
+
U[i, i+1] = _logm_superdiag_entry(l1, l2, t12)
|
813 |
+
|
814 |
+
# Return the logm of the upper triangular matrix.
|
815 |
+
if not np.array_equal(U, np.triu(U)):
|
816 |
+
raise Exception('U is not upper triangular')
|
817 |
+
return U
|
818 |
+
|
819 |
+
|
820 |
+
def _logm_force_nonsingular_triangular_matrix(T, inplace=False):
|
821 |
+
# The input matrix should be upper triangular.
|
822 |
+
# The eps is ad hoc and is not meant to be machine precision.
|
823 |
+
tri_eps = 1e-20
|
824 |
+
abs_diag = np.absolute(np.diag(T))
|
825 |
+
if np.any(abs_diag == 0):
|
826 |
+
exact_singularity_msg = 'The logm input matrix is exactly singular.'
|
827 |
+
warnings.warn(exact_singularity_msg, LogmExactlySingularWarning, stacklevel=3)
|
828 |
+
if not inplace:
|
829 |
+
T = T.copy()
|
830 |
+
n = T.shape[0]
|
831 |
+
for i in range(n):
|
832 |
+
if not T[i, i]:
|
833 |
+
T[i, i] = tri_eps
|
834 |
+
elif np.any(abs_diag < tri_eps):
|
835 |
+
near_singularity_msg = 'The logm input matrix may be nearly singular.'
|
836 |
+
warnings.warn(near_singularity_msg, LogmNearlySingularWarning, stacklevel=3)
|
837 |
+
return T
|
838 |
+
|
839 |
+
|
840 |
+
def _logm(A):
|
841 |
+
"""
|
842 |
+
Compute the matrix logarithm.
|
843 |
+
|
844 |
+
See the logm docstring in matfuncs.py for more info.
|
845 |
+
|
846 |
+
Notes
|
847 |
+
-----
|
848 |
+
In this function we look at triangular matrices that are similar
|
849 |
+
to the input matrix. If any diagonal entry of such a triangular matrix
|
850 |
+
is exactly zero then the original matrix is singular.
|
851 |
+
The matrix logarithm does not exist for such matrices,
|
852 |
+
but in such cases we will pretend that the diagonal entries that are zero
|
853 |
+
are actually slightly positive by an ad-hoc amount, in the interest
|
854 |
+
of returning something more useful than NaN. This will cause a warning.
|
855 |
+
|
856 |
+
"""
|
857 |
+
A = np.asarray(A)
|
858 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
859 |
+
raise ValueError('expected a square matrix')
|
860 |
+
|
861 |
+
# If the input matrix dtype is integer then copy to a float dtype matrix.
|
862 |
+
if issubclass(A.dtype.type, np.integer):
|
863 |
+
A = np.asarray(A, dtype=float)
|
864 |
+
|
865 |
+
keep_it_real = np.isrealobj(A)
|
866 |
+
try:
|
867 |
+
if np.array_equal(A, np.triu(A)):
|
868 |
+
A = _logm_force_nonsingular_triangular_matrix(A)
|
869 |
+
if np.min(np.diag(A)) < 0:
|
870 |
+
A = A.astype(complex)
|
871 |
+
return _logm_triu(A)
|
872 |
+
else:
|
873 |
+
if keep_it_real:
|
874 |
+
T, Z = schur(A)
|
875 |
+
if not np.array_equal(T, np.triu(T)):
|
876 |
+
T, Z = rsf2csf(T, Z)
|
877 |
+
else:
|
878 |
+
T, Z = schur(A, output='complex')
|
879 |
+
T = _logm_force_nonsingular_triangular_matrix(T, inplace=True)
|
880 |
+
U = _logm_triu(T)
|
881 |
+
ZH = np.conjugate(Z).T
|
882 |
+
return Z.dot(U).dot(ZH)
|
883 |
+
except (SqrtmError, LogmError):
|
884 |
+
X = np.empty_like(A)
|
885 |
+
X.fill(np.nan)
|
886 |
+
return X
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (276 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_sketches.py
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" Sketching-based Matrix Computations """
|
2 |
+
|
3 |
+
# Author: Jordi Montes <[email protected]>
|
4 |
+
# August 28, 2017
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
from scipy._lib._util import check_random_state, rng_integers
|
9 |
+
from scipy.sparse import csc_matrix
|
10 |
+
|
11 |
+
__all__ = ['clarkson_woodruff_transform']
|
12 |
+
|
13 |
+
|
14 |
+
def cwt_matrix(n_rows, n_columns, seed=None):
|
15 |
+
r"""
|
16 |
+
Generate a matrix S which represents a Clarkson-Woodruff transform.
|
17 |
+
|
18 |
+
Given the desired size of matrix, the method returns a matrix S of size
|
19 |
+
(n_rows, n_columns) where each column has all the entries set to 0
|
20 |
+
except for one position which has been randomly set to +1 or -1 with
|
21 |
+
equal probability.
|
22 |
+
|
23 |
+
Parameters
|
24 |
+
----------
|
25 |
+
n_rows : int
|
26 |
+
Number of rows of S
|
27 |
+
n_columns : int
|
28 |
+
Number of columns of S
|
29 |
+
seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
|
30 |
+
If `seed` is None (or `np.random`), the `numpy.random.RandomState`
|
31 |
+
singleton is used.
|
32 |
+
If `seed` is an int, a new ``RandomState`` instance is used,
|
33 |
+
seeded with `seed`.
|
34 |
+
If `seed` is already a ``Generator`` or ``RandomState`` instance then
|
35 |
+
that instance is used.
|
36 |
+
|
37 |
+
Returns
|
38 |
+
-------
|
39 |
+
S : (n_rows, n_columns) csc_matrix
|
40 |
+
The returned matrix has ``n_columns`` nonzero entries.
|
41 |
+
|
42 |
+
Notes
|
43 |
+
-----
|
44 |
+
Given a matrix A, with probability at least 9/10,
|
45 |
+
.. math:: \|SA\| = (1 \pm \epsilon)\|A\|
|
46 |
+
Where the error epsilon is related to the size of S.
|
47 |
+
"""
|
48 |
+
rng = check_random_state(seed)
|
49 |
+
rows = rng_integers(rng, 0, n_rows, n_columns)
|
50 |
+
cols = np.arange(n_columns+1)
|
51 |
+
signs = rng.choice([1, -1], n_columns)
|
52 |
+
S = csc_matrix((signs, rows, cols),shape=(n_rows, n_columns))
|
53 |
+
return S
|
54 |
+
|
55 |
+
|
56 |
+
def clarkson_woodruff_transform(input_matrix, sketch_size, seed=None):
|
57 |
+
r"""
|
58 |
+
Applies a Clarkson-Woodruff Transform/sketch to the input matrix.
|
59 |
+
|
60 |
+
Given an input_matrix ``A`` of size ``(n, d)``, compute a matrix ``A'`` of
|
61 |
+
size (sketch_size, d) so that
|
62 |
+
|
63 |
+
.. math:: \|Ax\| \approx \|A'x\|
|
64 |
+
|
65 |
+
with high probability via the Clarkson-Woodruff Transform, otherwise
|
66 |
+
known as the CountSketch matrix.
|
67 |
+
|
68 |
+
Parameters
|
69 |
+
----------
|
70 |
+
input_matrix : array_like
|
71 |
+
Input matrix, of shape ``(n, d)``.
|
72 |
+
sketch_size : int
|
73 |
+
Number of rows for the sketch.
|
74 |
+
seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
|
75 |
+
If `seed` is None (or `np.random`), the `numpy.random.RandomState`
|
76 |
+
singleton is used.
|
77 |
+
If `seed` is an int, a new ``RandomState`` instance is used,
|
78 |
+
seeded with `seed`.
|
79 |
+
If `seed` is already a ``Generator`` or ``RandomState`` instance then
|
80 |
+
that instance is used.
|
81 |
+
|
82 |
+
Returns
|
83 |
+
-------
|
84 |
+
A' : array_like
|
85 |
+
Sketch of the input matrix ``A``, of size ``(sketch_size, d)``.
|
86 |
+
|
87 |
+
Notes
|
88 |
+
-----
|
89 |
+
To make the statement
|
90 |
+
|
91 |
+
.. math:: \|Ax\| \approx \|A'x\|
|
92 |
+
|
93 |
+
precise, observe the following result which is adapted from the
|
94 |
+
proof of Theorem 14 of [2]_ via Markov's Inequality. If we have
|
95 |
+
a sketch size ``sketch_size=k`` which is at least
|
96 |
+
|
97 |
+
.. math:: k \geq \frac{2}{\epsilon^2\delta}
|
98 |
+
|
99 |
+
Then for any fixed vector ``x``,
|
100 |
+
|
101 |
+
.. math:: \|Ax\| = (1\pm\epsilon)\|A'x\|
|
102 |
+
|
103 |
+
with probability at least one minus delta.
|
104 |
+
|
105 |
+
This implementation takes advantage of sparsity: computing
|
106 |
+
a sketch takes time proportional to ``A.nnz``. Data ``A`` which
|
107 |
+
is in ``scipy.sparse.csc_matrix`` format gives the quickest
|
108 |
+
computation time for sparse input.
|
109 |
+
|
110 |
+
>>> import numpy as np
|
111 |
+
>>> from scipy import linalg
|
112 |
+
>>> from scipy import sparse
|
113 |
+
>>> rng = np.random.default_rng()
|
114 |
+
>>> n_rows, n_columns, density, sketch_n_rows = 15000, 100, 0.01, 200
|
115 |
+
>>> A = sparse.rand(n_rows, n_columns, density=density, format='csc')
|
116 |
+
>>> B = sparse.rand(n_rows, n_columns, density=density, format='csr')
|
117 |
+
>>> C = sparse.rand(n_rows, n_columns, density=density, format='coo')
|
118 |
+
>>> D = rng.standard_normal((n_rows, n_columns))
|
119 |
+
>>> SA = linalg.clarkson_woodruff_transform(A, sketch_n_rows) # fastest
|
120 |
+
>>> SB = linalg.clarkson_woodruff_transform(B, sketch_n_rows) # fast
|
121 |
+
>>> SC = linalg.clarkson_woodruff_transform(C, sketch_n_rows) # slower
|
122 |
+
>>> SD = linalg.clarkson_woodruff_transform(D, sketch_n_rows) # slowest
|
123 |
+
|
124 |
+
That said, this method does perform well on dense inputs, just slower
|
125 |
+
on a relative scale.
|
126 |
+
|
127 |
+
References
|
128 |
+
----------
|
129 |
+
.. [1] Kenneth L. Clarkson and David P. Woodruff. Low rank approximation
|
130 |
+
and regression in input sparsity time. In STOC, 2013.
|
131 |
+
.. [2] David P. Woodruff. Sketching as a tool for numerical linear algebra.
|
132 |
+
In Foundations and Trends in Theoretical Computer Science, 2014.
|
133 |
+
|
134 |
+
Examples
|
135 |
+
--------
|
136 |
+
Create a big dense matrix ``A`` for the example:
|
137 |
+
|
138 |
+
>>> import numpy as np
|
139 |
+
>>> from scipy import linalg
|
140 |
+
>>> n_rows, n_columns = 15000, 100
|
141 |
+
>>> rng = np.random.default_rng()
|
142 |
+
>>> A = rng.standard_normal((n_rows, n_columns))
|
143 |
+
|
144 |
+
Apply the transform to create a new matrix with 200 rows:
|
145 |
+
|
146 |
+
>>> sketch_n_rows = 200
|
147 |
+
>>> sketch = linalg.clarkson_woodruff_transform(A, sketch_n_rows, seed=rng)
|
148 |
+
>>> sketch.shape
|
149 |
+
(200, 100)
|
150 |
+
|
151 |
+
Now with high probability, the true norm is close to the sketched norm
|
152 |
+
in absolute value.
|
153 |
+
|
154 |
+
>>> linalg.norm(A)
|
155 |
+
1224.2812927123198
|
156 |
+
>>> linalg.norm(sketch)
|
157 |
+
1226.518328407333
|
158 |
+
|
159 |
+
Similarly, applying our sketch preserves the solution to a linear
|
160 |
+
regression of :math:`\min \|Ax - b\|`.
|
161 |
+
|
162 |
+
>>> b = rng.standard_normal(n_rows)
|
163 |
+
>>> x = linalg.lstsq(A, b)[0]
|
164 |
+
>>> Ab = np.hstack((A, b.reshape(-1, 1)))
|
165 |
+
>>> SAb = linalg.clarkson_woodruff_transform(Ab, sketch_n_rows, seed=rng)
|
166 |
+
>>> SA, Sb = SAb[:, :-1], SAb[:, -1]
|
167 |
+
>>> x_sketched = linalg.lstsq(SA, Sb)[0]
|
168 |
+
|
169 |
+
As with the matrix norm example, ``linalg.norm(A @ x - b)`` is close
|
170 |
+
to ``linalg.norm(A @ x_sketched - b)`` with high probability.
|
171 |
+
|
172 |
+
>>> linalg.norm(A @ x - b)
|
173 |
+
122.83242365433877
|
174 |
+
>>> linalg.norm(A @ x_sketched - b)
|
175 |
+
166.58473879945151
|
176 |
+
|
177 |
+
"""
|
178 |
+
S = cwt_matrix(sketch_size, input_matrix.shape[0], seed)
|
179 |
+
return S.dot(input_matrix)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_solve_toeplitz.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (300 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_solvers.py
ADDED
@@ -0,0 +1,846 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Matrix equation solver routines"""
|
2 |
+
# Author: Jeffrey Armstrong <[email protected]>
|
3 |
+
# February 24, 2012
|
4 |
+
|
5 |
+
# Modified: Chad Fulton <[email protected]>
|
6 |
+
# June 19, 2014
|
7 |
+
|
8 |
+
# Modified: Ilhan Polat <[email protected]>
|
9 |
+
# September 13, 2016
|
10 |
+
|
11 |
+
import warnings
|
12 |
+
import numpy as np
|
13 |
+
from numpy.linalg import inv, LinAlgError, norm, cond, svd
|
14 |
+
|
15 |
+
from ._basic import solve, solve_triangular, matrix_balance
|
16 |
+
from .lapack import get_lapack_funcs
|
17 |
+
from ._decomp_schur import schur
|
18 |
+
from ._decomp_lu import lu
|
19 |
+
from ._decomp_qr import qr
|
20 |
+
from ._decomp_qz import ordqz
|
21 |
+
from ._decomp import _asarray_validated
|
22 |
+
from ._special_matrices import kron, block_diag
|
23 |
+
|
24 |
+
__all__ = ['solve_sylvester',
|
25 |
+
'solve_continuous_lyapunov', 'solve_discrete_lyapunov',
|
26 |
+
'solve_lyapunov',
|
27 |
+
'solve_continuous_are', 'solve_discrete_are']
|
28 |
+
|
29 |
+
|
30 |
+
def solve_sylvester(a, b, q):
|
31 |
+
"""
|
32 |
+
Computes a solution (X) to the Sylvester equation :math:`AX + XB = Q`.
|
33 |
+
|
34 |
+
Parameters
|
35 |
+
----------
|
36 |
+
a : (M, M) array_like
|
37 |
+
Leading matrix of the Sylvester equation
|
38 |
+
b : (N, N) array_like
|
39 |
+
Trailing matrix of the Sylvester equation
|
40 |
+
q : (M, N) array_like
|
41 |
+
Right-hand side
|
42 |
+
|
43 |
+
Returns
|
44 |
+
-------
|
45 |
+
x : (M, N) ndarray
|
46 |
+
The solution to the Sylvester equation.
|
47 |
+
|
48 |
+
Raises
|
49 |
+
------
|
50 |
+
LinAlgError
|
51 |
+
If solution was not found
|
52 |
+
|
53 |
+
Notes
|
54 |
+
-----
|
55 |
+
Computes a solution to the Sylvester matrix equation via the Bartels-
|
56 |
+
Stewart algorithm. The A and B matrices first undergo Schur
|
57 |
+
decompositions. The resulting matrices are used to construct an
|
58 |
+
alternative Sylvester equation (``RY + YS^T = F``) where the R and S
|
59 |
+
matrices are in quasi-triangular form (or, when R, S or F are complex,
|
60 |
+
triangular form). The simplified equation is then solved using
|
61 |
+
``*TRSYL`` from LAPACK directly.
|
62 |
+
|
63 |
+
.. versionadded:: 0.11.0
|
64 |
+
|
65 |
+
Examples
|
66 |
+
--------
|
67 |
+
Given `a`, `b`, and `q` solve for `x`:
|
68 |
+
|
69 |
+
>>> import numpy as np
|
70 |
+
>>> from scipy import linalg
|
71 |
+
>>> a = np.array([[-3, -2, 0], [-1, -1, 3], [3, -5, -1]])
|
72 |
+
>>> b = np.array([[1]])
|
73 |
+
>>> q = np.array([[1],[2],[3]])
|
74 |
+
>>> x = linalg.solve_sylvester(a, b, q)
|
75 |
+
>>> x
|
76 |
+
array([[ 0.0625],
|
77 |
+
[-0.5625],
|
78 |
+
[ 0.6875]])
|
79 |
+
>>> np.allclose(a.dot(x) + x.dot(b), q)
|
80 |
+
True
|
81 |
+
|
82 |
+
"""
|
83 |
+
|
84 |
+
# Compute the Schur decomposition form of a
|
85 |
+
r, u = schur(a, output='real')
|
86 |
+
|
87 |
+
# Compute the Schur decomposition of b
|
88 |
+
s, v = schur(b.conj().transpose(), output='real')
|
89 |
+
|
90 |
+
# Construct f = u'*q*v
|
91 |
+
f = np.dot(np.dot(u.conj().transpose(), q), v)
|
92 |
+
|
93 |
+
# Call the Sylvester equation solver
|
94 |
+
trsyl, = get_lapack_funcs(('trsyl',), (r, s, f))
|
95 |
+
if trsyl is None:
|
96 |
+
raise RuntimeError('LAPACK implementation does not contain a proper '
|
97 |
+
'Sylvester equation solver (TRSYL)')
|
98 |
+
y, scale, info = trsyl(r, s, f, tranb='C')
|
99 |
+
|
100 |
+
y = scale*y
|
101 |
+
|
102 |
+
if info < 0:
|
103 |
+
raise LinAlgError("Illegal value encountered in "
|
104 |
+
"the %d term" % (-info,))
|
105 |
+
|
106 |
+
return np.dot(np.dot(u, y), v.conj().transpose())
|
107 |
+
|
108 |
+
|
109 |
+
def solve_continuous_lyapunov(a, q):
|
110 |
+
"""
|
111 |
+
Solves the continuous Lyapunov equation :math:`AX + XA^H = Q`.
|
112 |
+
|
113 |
+
Uses the Bartels-Stewart algorithm to find :math:`X`.
|
114 |
+
|
115 |
+
Parameters
|
116 |
+
----------
|
117 |
+
a : array_like
|
118 |
+
A square matrix
|
119 |
+
|
120 |
+
q : array_like
|
121 |
+
Right-hand side square matrix
|
122 |
+
|
123 |
+
Returns
|
124 |
+
-------
|
125 |
+
x : ndarray
|
126 |
+
Solution to the continuous Lyapunov equation
|
127 |
+
|
128 |
+
See Also
|
129 |
+
--------
|
130 |
+
solve_discrete_lyapunov : computes the solution to the discrete-time
|
131 |
+
Lyapunov equation
|
132 |
+
solve_sylvester : computes the solution to the Sylvester equation
|
133 |
+
|
134 |
+
Notes
|
135 |
+
-----
|
136 |
+
The continuous Lyapunov equation is a special form of the Sylvester
|
137 |
+
equation, hence this solver relies on LAPACK routine ?TRSYL.
|
138 |
+
|
139 |
+
.. versionadded:: 0.11.0
|
140 |
+
|
141 |
+
Examples
|
142 |
+
--------
|
143 |
+
Given `a` and `q` solve for `x`:
|
144 |
+
|
145 |
+
>>> import numpy as np
|
146 |
+
>>> from scipy import linalg
|
147 |
+
>>> a = np.array([[-3, -2, 0], [-1, -1, 0], [0, -5, -1]])
|
148 |
+
>>> b = np.array([2, 4, -1])
|
149 |
+
>>> q = np.eye(3)
|
150 |
+
>>> x = linalg.solve_continuous_lyapunov(a, q)
|
151 |
+
>>> x
|
152 |
+
array([[ -0.75 , 0.875 , -3.75 ],
|
153 |
+
[ 0.875 , -1.375 , 5.3125],
|
154 |
+
[ -3.75 , 5.3125, -27.0625]])
|
155 |
+
>>> np.allclose(a.dot(x) + x.dot(a.T), q)
|
156 |
+
True
|
157 |
+
"""
|
158 |
+
|
159 |
+
a = np.atleast_2d(_asarray_validated(a, check_finite=True))
|
160 |
+
q = np.atleast_2d(_asarray_validated(q, check_finite=True))
|
161 |
+
|
162 |
+
r_or_c = float
|
163 |
+
|
164 |
+
for ind, _ in enumerate((a, q)):
|
165 |
+
if np.iscomplexobj(_):
|
166 |
+
r_or_c = complex
|
167 |
+
|
168 |
+
if not np.equal(*_.shape):
|
169 |
+
raise ValueError("Matrix {} should be square.".format("aq"[ind]))
|
170 |
+
|
171 |
+
# Shape consistency check
|
172 |
+
if a.shape != q.shape:
|
173 |
+
raise ValueError("Matrix a and q should have the same shape.")
|
174 |
+
|
175 |
+
# Compute the Schur decomposition form of a
|
176 |
+
r, u = schur(a, output='real')
|
177 |
+
|
178 |
+
# Construct f = u'*q*u
|
179 |
+
f = u.conj().T.dot(q.dot(u))
|
180 |
+
|
181 |
+
# Call the Sylvester equation solver
|
182 |
+
trsyl = get_lapack_funcs('trsyl', (r, f))
|
183 |
+
|
184 |
+
dtype_string = 'T' if r_or_c == float else 'C'
|
185 |
+
y, scale, info = trsyl(r, r, f, tranb=dtype_string)
|
186 |
+
|
187 |
+
if info < 0:
|
188 |
+
raise ValueError('?TRSYL exited with the internal error '
|
189 |
+
f'"illegal value in argument number {-info}.". See '
|
190 |
+
'LAPACK documentation for the ?TRSYL error codes.')
|
191 |
+
elif info == 1:
|
192 |
+
warnings.warn('Input "a" has an eigenvalue pair whose sum is '
|
193 |
+
'very close to or exactly zero. The solution is '
|
194 |
+
'obtained via perturbing the coefficients.',
|
195 |
+
RuntimeWarning, stacklevel=2)
|
196 |
+
y *= scale
|
197 |
+
|
198 |
+
return u.dot(y).dot(u.conj().T)
|
199 |
+
|
200 |
+
|
201 |
+
# For backwards compatibility, keep the old name
|
202 |
+
solve_lyapunov = solve_continuous_lyapunov
|
203 |
+
|
204 |
+
|
205 |
+
def _solve_discrete_lyapunov_direct(a, q):
|
206 |
+
"""
|
207 |
+
Solves the discrete Lyapunov equation directly.
|
208 |
+
|
209 |
+
This function is called by the `solve_discrete_lyapunov` function with
|
210 |
+
`method=direct`. It is not supposed to be called directly.
|
211 |
+
"""
|
212 |
+
|
213 |
+
lhs = kron(a, a.conj())
|
214 |
+
lhs = np.eye(lhs.shape[0]) - lhs
|
215 |
+
x = solve(lhs, q.flatten())
|
216 |
+
|
217 |
+
return np.reshape(x, q.shape)
|
218 |
+
|
219 |
+
|
220 |
+
def _solve_discrete_lyapunov_bilinear(a, q):
|
221 |
+
"""
|
222 |
+
Solves the discrete Lyapunov equation using a bilinear transformation.
|
223 |
+
|
224 |
+
This function is called by the `solve_discrete_lyapunov` function with
|
225 |
+
`method=bilinear`. It is not supposed to be called directly.
|
226 |
+
"""
|
227 |
+
eye = np.eye(a.shape[0])
|
228 |
+
aH = a.conj().transpose()
|
229 |
+
aHI_inv = inv(aH + eye)
|
230 |
+
b = np.dot(aH - eye, aHI_inv)
|
231 |
+
c = 2*np.dot(np.dot(inv(a + eye), q), aHI_inv)
|
232 |
+
return solve_lyapunov(b.conj().transpose(), -c)
|
233 |
+
|
234 |
+
|
235 |
+
def solve_discrete_lyapunov(a, q, method=None):
|
236 |
+
"""
|
237 |
+
Solves the discrete Lyapunov equation :math:`AXA^H - X + Q = 0`.
|
238 |
+
|
239 |
+
Parameters
|
240 |
+
----------
|
241 |
+
a, q : (M, M) array_like
|
242 |
+
Square matrices corresponding to A and Q in the equation
|
243 |
+
above respectively. Must have the same shape.
|
244 |
+
|
245 |
+
method : {'direct', 'bilinear'}, optional
|
246 |
+
Type of solver.
|
247 |
+
|
248 |
+
If not given, chosen to be ``direct`` if ``M`` is less than 10 and
|
249 |
+
``bilinear`` otherwise.
|
250 |
+
|
251 |
+
Returns
|
252 |
+
-------
|
253 |
+
x : ndarray
|
254 |
+
Solution to the discrete Lyapunov equation
|
255 |
+
|
256 |
+
See Also
|
257 |
+
--------
|
258 |
+
solve_continuous_lyapunov : computes the solution to the continuous-time
|
259 |
+
Lyapunov equation
|
260 |
+
|
261 |
+
Notes
|
262 |
+
-----
|
263 |
+
This section describes the available solvers that can be selected by the
|
264 |
+
'method' parameter. The default method is *direct* if ``M`` is less than 10
|
265 |
+
and ``bilinear`` otherwise.
|
266 |
+
|
267 |
+
Method *direct* uses a direct analytical solution to the discrete Lyapunov
|
268 |
+
equation. The algorithm is given in, for example, [1]_. However, it requires
|
269 |
+
the linear solution of a system with dimension :math:`M^2` so that
|
270 |
+
performance degrades rapidly for even moderately sized matrices.
|
271 |
+
|
272 |
+
Method *bilinear* uses a bilinear transformation to convert the discrete
|
273 |
+
Lyapunov equation to a continuous Lyapunov equation :math:`(BX+XB'=-C)`
|
274 |
+
where :math:`B=(A-I)(A+I)^{-1}` and
|
275 |
+
:math:`C=2(A' + I)^{-1} Q (A + I)^{-1}`. The continuous equation can be
|
276 |
+
efficiently solved since it is a special case of a Sylvester equation.
|
277 |
+
The transformation algorithm is from Popov (1964) as described in [2]_.
|
278 |
+
|
279 |
+
.. versionadded:: 0.11.0
|
280 |
+
|
281 |
+
References
|
282 |
+
----------
|
283 |
+
.. [1] Hamilton, James D. Time Series Analysis, Princeton: Princeton
|
284 |
+
University Press, 1994. 265. Print.
|
285 |
+
http://doc1.lbfl.li/aca/FLMF037168.pdf
|
286 |
+
.. [2] Gajic, Z., and M.T.J. Qureshi. 2008.
|
287 |
+
Lyapunov Matrix Equation in System Stability and Control.
|
288 |
+
Dover Books on Engineering Series. Dover Publications.
|
289 |
+
|
290 |
+
Examples
|
291 |
+
--------
|
292 |
+
Given `a` and `q` solve for `x`:
|
293 |
+
|
294 |
+
>>> import numpy as np
|
295 |
+
>>> from scipy import linalg
|
296 |
+
>>> a = np.array([[0.2, 0.5],[0.7, -0.9]])
|
297 |
+
>>> q = np.eye(2)
|
298 |
+
>>> x = linalg.solve_discrete_lyapunov(a, q)
|
299 |
+
>>> x
|
300 |
+
array([[ 0.70872893, 1.43518822],
|
301 |
+
[ 1.43518822, -2.4266315 ]])
|
302 |
+
>>> np.allclose(a.dot(x).dot(a.T)-x, -q)
|
303 |
+
True
|
304 |
+
|
305 |
+
"""
|
306 |
+
a = np.asarray(a)
|
307 |
+
q = np.asarray(q)
|
308 |
+
if method is None:
|
309 |
+
# Select automatically based on size of matrices
|
310 |
+
if a.shape[0] >= 10:
|
311 |
+
method = 'bilinear'
|
312 |
+
else:
|
313 |
+
method = 'direct'
|
314 |
+
|
315 |
+
meth = method.lower()
|
316 |
+
|
317 |
+
if meth == 'direct':
|
318 |
+
x = _solve_discrete_lyapunov_direct(a, q)
|
319 |
+
elif meth == 'bilinear':
|
320 |
+
x = _solve_discrete_lyapunov_bilinear(a, q)
|
321 |
+
else:
|
322 |
+
raise ValueError('Unknown solver %s' % method)
|
323 |
+
|
324 |
+
return x
|
325 |
+
|
326 |
+
|
327 |
+
def solve_continuous_are(a, b, q, r, e=None, s=None, balanced=True):
|
328 |
+
r"""
|
329 |
+
Solves the continuous-time algebraic Riccati equation (CARE).
|
330 |
+
|
331 |
+
The CARE is defined as
|
332 |
+
|
333 |
+
.. math::
|
334 |
+
|
335 |
+
X A + A^H X - X B R^{-1} B^H X + Q = 0
|
336 |
+
|
337 |
+
The limitations for a solution to exist are :
|
338 |
+
|
339 |
+
* All eigenvalues of :math:`A` on the right half plane, should be
|
340 |
+
controllable.
|
341 |
+
|
342 |
+
* The associated hamiltonian pencil (See Notes), should have
|
343 |
+
eigenvalues sufficiently away from the imaginary axis.
|
344 |
+
|
345 |
+
Moreover, if ``e`` or ``s`` is not precisely ``None``, then the
|
346 |
+
generalized version of CARE
|
347 |
+
|
348 |
+
.. math::
|
349 |
+
|
350 |
+
E^HXA + A^HXE - (E^HXB + S) R^{-1} (B^HXE + S^H) + Q = 0
|
351 |
+
|
352 |
+
is solved. When omitted, ``e`` is assumed to be the identity and ``s``
|
353 |
+
is assumed to be the zero matrix with sizes compatible with ``a`` and
|
354 |
+
``b``, respectively.
|
355 |
+
|
356 |
+
Parameters
|
357 |
+
----------
|
358 |
+
a : (M, M) array_like
|
359 |
+
Square matrix
|
360 |
+
b : (M, N) array_like
|
361 |
+
Input
|
362 |
+
q : (M, M) array_like
|
363 |
+
Input
|
364 |
+
r : (N, N) array_like
|
365 |
+
Nonsingular square matrix
|
366 |
+
e : (M, M) array_like, optional
|
367 |
+
Nonsingular square matrix
|
368 |
+
s : (M, N) array_like, optional
|
369 |
+
Input
|
370 |
+
balanced : bool, optional
|
371 |
+
The boolean that indicates whether a balancing step is performed
|
372 |
+
on the data. The default is set to True.
|
373 |
+
|
374 |
+
Returns
|
375 |
+
-------
|
376 |
+
x : (M, M) ndarray
|
377 |
+
Solution to the continuous-time algebraic Riccati equation.
|
378 |
+
|
379 |
+
Raises
|
380 |
+
------
|
381 |
+
LinAlgError
|
382 |
+
For cases where the stable subspace of the pencil could not be
|
383 |
+
isolated. See Notes section and the references for details.
|
384 |
+
|
385 |
+
See Also
|
386 |
+
--------
|
387 |
+
solve_discrete_are : Solves the discrete-time algebraic Riccati equation
|
388 |
+
|
389 |
+
Notes
|
390 |
+
-----
|
391 |
+
The equation is solved by forming the extended hamiltonian matrix pencil,
|
392 |
+
as described in [1]_, :math:`H - \lambda J` given by the block matrices ::
|
393 |
+
|
394 |
+
[ A 0 B ] [ E 0 0 ]
|
395 |
+
[-Q -A^H -S ] - \lambda * [ 0 E^H 0 ]
|
396 |
+
[ S^H B^H R ] [ 0 0 0 ]
|
397 |
+
|
398 |
+
and using a QZ decomposition method.
|
399 |
+
|
400 |
+
In this algorithm, the fail conditions are linked to the symmetry
|
401 |
+
of the product :math:`U_2 U_1^{-1}` and condition number of
|
402 |
+
:math:`U_1`. Here, :math:`U` is the 2m-by-m matrix that holds the
|
403 |
+
eigenvectors spanning the stable subspace with 2-m rows and partitioned
|
404 |
+
into two m-row matrices. See [1]_ and [2]_ for more details.
|
405 |
+
|
406 |
+
In order to improve the QZ decomposition accuracy, the pencil goes
|
407 |
+
through a balancing step where the sum of absolute values of
|
408 |
+
:math:`H` and :math:`J` entries (after removing the diagonal entries of
|
409 |
+
the sum) is balanced following the recipe given in [3]_.
|
410 |
+
|
411 |
+
.. versionadded:: 0.11.0
|
412 |
+
|
413 |
+
References
|
414 |
+
----------
|
415 |
+
.. [1] P. van Dooren , "A Generalized Eigenvalue Approach For Solving
|
416 |
+
Riccati Equations.", SIAM Journal on Scientific and Statistical
|
417 |
+
Computing, Vol.2(2), :doi:`10.1137/0902010`
|
418 |
+
|
419 |
+
.. [2] A.J. Laub, "A Schur Method for Solving Algebraic Riccati
|
420 |
+
Equations.", Massachusetts Institute of Technology. Laboratory for
|
421 |
+
Information and Decision Systems. LIDS-R ; 859. Available online :
|
422 |
+
http://hdl.handle.net/1721.1/1301
|
423 |
+
|
424 |
+
.. [3] P. Benner, "Symplectic Balancing of Hamiltonian Matrices", 2001,
|
425 |
+
SIAM J. Sci. Comput., 2001, Vol.22(5), :doi:`10.1137/S1064827500367993`
|
426 |
+
|
427 |
+
Examples
|
428 |
+
--------
|
429 |
+
Given `a`, `b`, `q`, and `r` solve for `x`:
|
430 |
+
|
431 |
+
>>> import numpy as np
|
432 |
+
>>> from scipy import linalg
|
433 |
+
>>> a = np.array([[4, 3], [-4.5, -3.5]])
|
434 |
+
>>> b = np.array([[1], [-1]])
|
435 |
+
>>> q = np.array([[9, 6], [6, 4.]])
|
436 |
+
>>> r = 1
|
437 |
+
>>> x = linalg.solve_continuous_are(a, b, q, r)
|
438 |
+
>>> x
|
439 |
+
array([[ 21.72792206, 14.48528137],
|
440 |
+
[ 14.48528137, 9.65685425]])
|
441 |
+
>>> np.allclose(a.T.dot(x) + x.dot(a)-x.dot(b).dot(b.T).dot(x), -q)
|
442 |
+
True
|
443 |
+
|
444 |
+
"""
|
445 |
+
|
446 |
+
# Validate input arguments
|
447 |
+
a, b, q, r, e, s, m, n, r_or_c, gen_are = _are_validate_args(
|
448 |
+
a, b, q, r, e, s, 'care')
|
449 |
+
|
450 |
+
H = np.empty((2*m+n, 2*m+n), dtype=r_or_c)
|
451 |
+
H[:m, :m] = a
|
452 |
+
H[:m, m:2*m] = 0.
|
453 |
+
H[:m, 2*m:] = b
|
454 |
+
H[m:2*m, :m] = -q
|
455 |
+
H[m:2*m, m:2*m] = -a.conj().T
|
456 |
+
H[m:2*m, 2*m:] = 0. if s is None else -s
|
457 |
+
H[2*m:, :m] = 0. if s is None else s.conj().T
|
458 |
+
H[2*m:, m:2*m] = b.conj().T
|
459 |
+
H[2*m:, 2*m:] = r
|
460 |
+
|
461 |
+
if gen_are and e is not None:
|
462 |
+
J = block_diag(e, e.conj().T, np.zeros_like(r, dtype=r_or_c))
|
463 |
+
else:
|
464 |
+
J = block_diag(np.eye(2*m), np.zeros_like(r, dtype=r_or_c))
|
465 |
+
|
466 |
+
if balanced:
|
467 |
+
# xGEBAL does not remove the diagonals before scaling. Also
|
468 |
+
# to avoid destroying the Symplectic structure, we follow Ref.3
|
469 |
+
M = np.abs(H) + np.abs(J)
|
470 |
+
np.fill_diagonal(M, 0.)
|
471 |
+
_, (sca, _) = matrix_balance(M, separate=1, permute=0)
|
472 |
+
# do we need to bother?
|
473 |
+
if not np.allclose(sca, np.ones_like(sca)):
|
474 |
+
# Now impose diag(D,inv(D)) from Benner where D is
|
475 |
+
# square root of s_i/s_(n+i) for i=0,....
|
476 |
+
sca = np.log2(sca)
|
477 |
+
# NOTE: Py3 uses "Bankers Rounding: round to the nearest even" !!
|
478 |
+
s = np.round((sca[m:2*m] - sca[:m])/2)
|
479 |
+
sca = 2 ** np.r_[s, -s, sca[2*m:]]
|
480 |
+
# Elementwise multiplication via broadcasting.
|
481 |
+
elwisescale = sca[:, None] * np.reciprocal(sca)
|
482 |
+
H *= elwisescale
|
483 |
+
J *= elwisescale
|
484 |
+
|
485 |
+
# Deflate the pencil to 2m x 2m ala Ref.1, eq.(55)
|
486 |
+
q, r = qr(H[:, -n:])
|
487 |
+
H = q[:, n:].conj().T.dot(H[:, :2*m])
|
488 |
+
J = q[:2*m, n:].conj().T.dot(J[:2*m, :2*m])
|
489 |
+
|
490 |
+
# Decide on which output type is needed for QZ
|
491 |
+
out_str = 'real' if r_or_c == float else 'complex'
|
492 |
+
|
493 |
+
_, _, _, _, _, u = ordqz(H, J, sort='lhp', overwrite_a=True,
|
494 |
+
overwrite_b=True, check_finite=False,
|
495 |
+
output=out_str)
|
496 |
+
|
497 |
+
# Get the relevant parts of the stable subspace basis
|
498 |
+
if e is not None:
|
499 |
+
u, _ = qr(np.vstack((e.dot(u[:m, :m]), u[m:, :m])))
|
500 |
+
u00 = u[:m, :m]
|
501 |
+
u10 = u[m:, :m]
|
502 |
+
|
503 |
+
# Solve via back-substituion after checking the condition of u00
|
504 |
+
up, ul, uu = lu(u00)
|
505 |
+
if 1/cond(uu) < np.spacing(1.):
|
506 |
+
raise LinAlgError('Failed to find a finite solution.')
|
507 |
+
|
508 |
+
# Exploit the triangular structure
|
509 |
+
x = solve_triangular(ul.conj().T,
|
510 |
+
solve_triangular(uu.conj().T,
|
511 |
+
u10.conj().T,
|
512 |
+
lower=True),
|
513 |
+
unit_diagonal=True,
|
514 |
+
).conj().T.dot(up.conj().T)
|
515 |
+
if balanced:
|
516 |
+
x *= sca[:m, None] * sca[:m]
|
517 |
+
|
518 |
+
# Check the deviation from symmetry for lack of success
|
519 |
+
# See proof of Thm.5 item 3 in [2]
|
520 |
+
u_sym = u00.conj().T.dot(u10)
|
521 |
+
n_u_sym = norm(u_sym, 1)
|
522 |
+
u_sym = u_sym - u_sym.conj().T
|
523 |
+
sym_threshold = np.max([np.spacing(1000.), 0.1*n_u_sym])
|
524 |
+
|
525 |
+
if norm(u_sym, 1) > sym_threshold:
|
526 |
+
raise LinAlgError('The associated Hamiltonian pencil has eigenvalues '
|
527 |
+
'too close to the imaginary axis')
|
528 |
+
|
529 |
+
return (x + x.conj().T)/2
|
530 |
+
|
531 |
+
|
532 |
+
def solve_discrete_are(a, b, q, r, e=None, s=None, balanced=True):
|
533 |
+
r"""
|
534 |
+
Solves the discrete-time algebraic Riccati equation (DARE).
|
535 |
+
|
536 |
+
The DARE is defined as
|
537 |
+
|
538 |
+
.. math::
|
539 |
+
|
540 |
+
A^HXA - X - (A^HXB) (R + B^HXB)^{-1} (B^HXA) + Q = 0
|
541 |
+
|
542 |
+
The limitations for a solution to exist are :
|
543 |
+
|
544 |
+
* All eigenvalues of :math:`A` outside the unit disc, should be
|
545 |
+
controllable.
|
546 |
+
|
547 |
+
* The associated symplectic pencil (See Notes), should have
|
548 |
+
eigenvalues sufficiently away from the unit circle.
|
549 |
+
|
550 |
+
Moreover, if ``e`` and ``s`` are not both precisely ``None``, then the
|
551 |
+
generalized version of DARE
|
552 |
+
|
553 |
+
.. math::
|
554 |
+
|
555 |
+
A^HXA - E^HXE - (A^HXB+S) (R+B^HXB)^{-1} (B^HXA+S^H) + Q = 0
|
556 |
+
|
557 |
+
is solved. When omitted, ``e`` is assumed to be the identity and ``s``
|
558 |
+
is assumed to be the zero matrix.
|
559 |
+
|
560 |
+
Parameters
|
561 |
+
----------
|
562 |
+
a : (M, M) array_like
|
563 |
+
Square matrix
|
564 |
+
b : (M, N) array_like
|
565 |
+
Input
|
566 |
+
q : (M, M) array_like
|
567 |
+
Input
|
568 |
+
r : (N, N) array_like
|
569 |
+
Square matrix
|
570 |
+
e : (M, M) array_like, optional
|
571 |
+
Nonsingular square matrix
|
572 |
+
s : (M, N) array_like, optional
|
573 |
+
Input
|
574 |
+
balanced : bool
|
575 |
+
The boolean that indicates whether a balancing step is performed
|
576 |
+
on the data. The default is set to True.
|
577 |
+
|
578 |
+
Returns
|
579 |
+
-------
|
580 |
+
x : (M, M) ndarray
|
581 |
+
Solution to the discrete algebraic Riccati equation.
|
582 |
+
|
583 |
+
Raises
|
584 |
+
------
|
585 |
+
LinAlgError
|
586 |
+
For cases where the stable subspace of the pencil could not be
|
587 |
+
isolated. See Notes section and the references for details.
|
588 |
+
|
589 |
+
See Also
|
590 |
+
--------
|
591 |
+
solve_continuous_are : Solves the continuous algebraic Riccati equation
|
592 |
+
|
593 |
+
Notes
|
594 |
+
-----
|
595 |
+
The equation is solved by forming the extended symplectic matrix pencil,
|
596 |
+
as described in [1]_, :math:`H - \lambda J` given by the block matrices ::
|
597 |
+
|
598 |
+
[ A 0 B ] [ E 0 B ]
|
599 |
+
[ -Q E^H -S ] - \lambda * [ 0 A^H 0 ]
|
600 |
+
[ S^H 0 R ] [ 0 -B^H 0 ]
|
601 |
+
|
602 |
+
and using a QZ decomposition method.
|
603 |
+
|
604 |
+
In this algorithm, the fail conditions are linked to the symmetry
|
605 |
+
of the product :math:`U_2 U_1^{-1}` and condition number of
|
606 |
+
:math:`U_1`. Here, :math:`U` is the 2m-by-m matrix that holds the
|
607 |
+
eigenvectors spanning the stable subspace with 2-m rows and partitioned
|
608 |
+
into two m-row matrices. See [1]_ and [2]_ for more details.
|
609 |
+
|
610 |
+
In order to improve the QZ decomposition accuracy, the pencil goes
|
611 |
+
through a balancing step where the sum of absolute values of
|
612 |
+
:math:`H` and :math:`J` rows/cols (after removing the diagonal entries)
|
613 |
+
is balanced following the recipe given in [3]_. If the data has small
|
614 |
+
numerical noise, balancing may amplify their effects and some clean up
|
615 |
+
is required.
|
616 |
+
|
617 |
+
.. versionadded:: 0.11.0
|
618 |
+
|
619 |
+
References
|
620 |
+
----------
|
621 |
+
.. [1] P. van Dooren , "A Generalized Eigenvalue Approach For Solving
|
622 |
+
Riccati Equations.", SIAM Journal on Scientific and Statistical
|
623 |
+
Computing, Vol.2(2), :doi:`10.1137/0902010`
|
624 |
+
|
625 |
+
.. [2] A.J. Laub, "A Schur Method for Solving Algebraic Riccati
|
626 |
+
Equations.", Massachusetts Institute of Technology. Laboratory for
|
627 |
+
Information and Decision Systems. LIDS-R ; 859. Available online :
|
628 |
+
http://hdl.handle.net/1721.1/1301
|
629 |
+
|
630 |
+
.. [3] P. Benner, "Symplectic Balancing of Hamiltonian Matrices", 2001,
|
631 |
+
SIAM J. Sci. Comput., 2001, Vol.22(5), :doi:`10.1137/S1064827500367993`
|
632 |
+
|
633 |
+
Examples
|
634 |
+
--------
|
635 |
+
Given `a`, `b`, `q`, and `r` solve for `x`:
|
636 |
+
|
637 |
+
>>> import numpy as np
|
638 |
+
>>> from scipy import linalg as la
|
639 |
+
>>> a = np.array([[0, 1], [0, -1]])
|
640 |
+
>>> b = np.array([[1, 0], [2, 1]])
|
641 |
+
>>> q = np.array([[-4, -4], [-4, 7]])
|
642 |
+
>>> r = np.array([[9, 3], [3, 1]])
|
643 |
+
>>> x = la.solve_discrete_are(a, b, q, r)
|
644 |
+
>>> x
|
645 |
+
array([[-4., -4.],
|
646 |
+
[-4., 7.]])
|
647 |
+
>>> R = la.solve(r + b.T.dot(x).dot(b), b.T.dot(x).dot(a))
|
648 |
+
>>> np.allclose(a.T.dot(x).dot(a) - x - a.T.dot(x).dot(b).dot(R), -q)
|
649 |
+
True
|
650 |
+
|
651 |
+
"""
|
652 |
+
|
653 |
+
# Validate input arguments
|
654 |
+
a, b, q, r, e, s, m, n, r_or_c, gen_are = _are_validate_args(
|
655 |
+
a, b, q, r, e, s, 'dare')
|
656 |
+
|
657 |
+
# Form the matrix pencil
|
658 |
+
H = np.zeros((2*m+n, 2*m+n), dtype=r_or_c)
|
659 |
+
H[:m, :m] = a
|
660 |
+
H[:m, 2*m:] = b
|
661 |
+
H[m:2*m, :m] = -q
|
662 |
+
H[m:2*m, m:2*m] = np.eye(m) if e is None else e.conj().T
|
663 |
+
H[m:2*m, 2*m:] = 0. if s is None else -s
|
664 |
+
H[2*m:, :m] = 0. if s is None else s.conj().T
|
665 |
+
H[2*m:, 2*m:] = r
|
666 |
+
|
667 |
+
J = np.zeros_like(H, dtype=r_or_c)
|
668 |
+
J[:m, :m] = np.eye(m) if e is None else e
|
669 |
+
J[m:2*m, m:2*m] = a.conj().T
|
670 |
+
J[2*m:, m:2*m] = -b.conj().T
|
671 |
+
|
672 |
+
if balanced:
|
673 |
+
# xGEBAL does not remove the diagonals before scaling. Also
|
674 |
+
# to avoid destroying the Symplectic structure, we follow Ref.3
|
675 |
+
M = np.abs(H) + np.abs(J)
|
676 |
+
np.fill_diagonal(M, 0.)
|
677 |
+
_, (sca, _) = matrix_balance(M, separate=1, permute=0)
|
678 |
+
# do we need to bother?
|
679 |
+
if not np.allclose(sca, np.ones_like(sca)):
|
680 |
+
# Now impose diag(D,inv(D)) from Benner where D is
|
681 |
+
# square root of s_i/s_(n+i) for i=0,....
|
682 |
+
sca = np.log2(sca)
|
683 |
+
# NOTE: Py3 uses "Bankers Rounding: round to the nearest even" !!
|
684 |
+
s = np.round((sca[m:2*m] - sca[:m])/2)
|
685 |
+
sca = 2 ** np.r_[s, -s, sca[2*m:]]
|
686 |
+
# Elementwise multiplication via broadcasting.
|
687 |
+
elwisescale = sca[:, None] * np.reciprocal(sca)
|
688 |
+
H *= elwisescale
|
689 |
+
J *= elwisescale
|
690 |
+
|
691 |
+
# Deflate the pencil by the R column ala Ref.1
|
692 |
+
q_of_qr, _ = qr(H[:, -n:])
|
693 |
+
H = q_of_qr[:, n:].conj().T.dot(H[:, :2*m])
|
694 |
+
J = q_of_qr[:, n:].conj().T.dot(J[:, :2*m])
|
695 |
+
|
696 |
+
# Decide on which output type is needed for QZ
|
697 |
+
out_str = 'real' if r_or_c == float else 'complex'
|
698 |
+
|
699 |
+
_, _, _, _, _, u = ordqz(H, J, sort='iuc',
|
700 |
+
overwrite_a=True,
|
701 |
+
overwrite_b=True,
|
702 |
+
check_finite=False,
|
703 |
+
output=out_str)
|
704 |
+
|
705 |
+
# Get the relevant parts of the stable subspace basis
|
706 |
+
if e is not None:
|
707 |
+
u, _ = qr(np.vstack((e.dot(u[:m, :m]), u[m:, :m])))
|
708 |
+
u00 = u[:m, :m]
|
709 |
+
u10 = u[m:, :m]
|
710 |
+
|
711 |
+
# Solve via back-substituion after checking the condition of u00
|
712 |
+
up, ul, uu = lu(u00)
|
713 |
+
|
714 |
+
if 1/cond(uu) < np.spacing(1.):
|
715 |
+
raise LinAlgError('Failed to find a finite solution.')
|
716 |
+
|
717 |
+
# Exploit the triangular structure
|
718 |
+
x = solve_triangular(ul.conj().T,
|
719 |
+
solve_triangular(uu.conj().T,
|
720 |
+
u10.conj().T,
|
721 |
+
lower=True),
|
722 |
+
unit_diagonal=True,
|
723 |
+
).conj().T.dot(up.conj().T)
|
724 |
+
if balanced:
|
725 |
+
x *= sca[:m, None] * sca[:m]
|
726 |
+
|
727 |
+
# Check the deviation from symmetry for lack of success
|
728 |
+
# See proof of Thm.5 item 3 in [2]
|
729 |
+
u_sym = u00.conj().T.dot(u10)
|
730 |
+
n_u_sym = norm(u_sym, 1)
|
731 |
+
u_sym = u_sym - u_sym.conj().T
|
732 |
+
sym_threshold = np.max([np.spacing(1000.), 0.1*n_u_sym])
|
733 |
+
|
734 |
+
if norm(u_sym, 1) > sym_threshold:
|
735 |
+
raise LinAlgError('The associated symplectic pencil has eigenvalues '
|
736 |
+
'too close to the unit circle')
|
737 |
+
|
738 |
+
return (x + x.conj().T)/2
|
739 |
+
|
740 |
+
|
741 |
+
def _are_validate_args(a, b, q, r, e, s, eq_type='care'):
|
742 |
+
"""
|
743 |
+
A helper function to validate the arguments supplied to the
|
744 |
+
Riccati equation solvers. Any discrepancy found in the input
|
745 |
+
matrices leads to a ``ValueError`` exception.
|
746 |
+
|
747 |
+
Essentially, it performs:
|
748 |
+
|
749 |
+
- a check whether the input is free of NaN and Infs
|
750 |
+
- a pass for the data through ``numpy.atleast_2d()``
|
751 |
+
- squareness check of the relevant arrays
|
752 |
+
- shape consistency check of the arrays
|
753 |
+
- singularity check of the relevant arrays
|
754 |
+
- symmetricity check of the relevant matrices
|
755 |
+
- a check whether the regular or the generalized version is asked.
|
756 |
+
|
757 |
+
This function is used by ``solve_continuous_are`` and
|
758 |
+
``solve_discrete_are``.
|
759 |
+
|
760 |
+
Parameters
|
761 |
+
----------
|
762 |
+
a, b, q, r, e, s : array_like
|
763 |
+
Input data
|
764 |
+
eq_type : str
|
765 |
+
Accepted arguments are 'care' and 'dare'.
|
766 |
+
|
767 |
+
Returns
|
768 |
+
-------
|
769 |
+
a, b, q, r, e, s : ndarray
|
770 |
+
Regularized input data
|
771 |
+
m, n : int
|
772 |
+
shape of the problem
|
773 |
+
r_or_c : type
|
774 |
+
Data type of the problem, returns float or complex
|
775 |
+
gen_or_not : bool
|
776 |
+
Type of the equation, True for generalized and False for regular ARE.
|
777 |
+
|
778 |
+
"""
|
779 |
+
|
780 |
+
if eq_type.lower() not in ("dare", "care"):
|
781 |
+
raise ValueError("Equation type unknown. "
|
782 |
+
"Only 'care' and 'dare' is understood")
|
783 |
+
|
784 |
+
a = np.atleast_2d(_asarray_validated(a, check_finite=True))
|
785 |
+
b = np.atleast_2d(_asarray_validated(b, check_finite=True))
|
786 |
+
q = np.atleast_2d(_asarray_validated(q, check_finite=True))
|
787 |
+
r = np.atleast_2d(_asarray_validated(r, check_finite=True))
|
788 |
+
|
789 |
+
# Get the correct data types otherwise NumPy complains
|
790 |
+
# about pushing complex numbers into real arrays.
|
791 |
+
r_or_c = complex if np.iscomplexobj(b) else float
|
792 |
+
|
793 |
+
for ind, mat in enumerate((a, q, r)):
|
794 |
+
if np.iscomplexobj(mat):
|
795 |
+
r_or_c = complex
|
796 |
+
|
797 |
+
if not np.equal(*mat.shape):
|
798 |
+
raise ValueError("Matrix {} should be square.".format("aqr"[ind]))
|
799 |
+
|
800 |
+
# Shape consistency checks
|
801 |
+
m, n = b.shape
|
802 |
+
if m != a.shape[0]:
|
803 |
+
raise ValueError("Matrix a and b should have the same number of rows.")
|
804 |
+
if m != q.shape[0]:
|
805 |
+
raise ValueError("Matrix a and q should have the same shape.")
|
806 |
+
if n != r.shape[0]:
|
807 |
+
raise ValueError("Matrix b and r should have the same number of cols.")
|
808 |
+
|
809 |
+
# Check if the data matrices q, r are (sufficiently) hermitian
|
810 |
+
for ind, mat in enumerate((q, r)):
|
811 |
+
if norm(mat - mat.conj().T, 1) > np.spacing(norm(mat, 1))*100:
|
812 |
+
raise ValueError("Matrix {} should be symmetric/hermitian."
|
813 |
+
"".format("qr"[ind]))
|
814 |
+
|
815 |
+
# Continuous time ARE should have a nonsingular r matrix.
|
816 |
+
if eq_type == 'care':
|
817 |
+
min_sv = svd(r, compute_uv=False)[-1]
|
818 |
+
if min_sv == 0. or min_sv < np.spacing(1.)*norm(r, 1):
|
819 |
+
raise ValueError('Matrix r is numerically singular.')
|
820 |
+
|
821 |
+
# Check if the generalized case is required with omitted arguments
|
822 |
+
# perform late shape checking etc.
|
823 |
+
generalized_case = e is not None or s is not None
|
824 |
+
|
825 |
+
if generalized_case:
|
826 |
+
if e is not None:
|
827 |
+
e = np.atleast_2d(_asarray_validated(e, check_finite=True))
|
828 |
+
if not np.equal(*e.shape):
|
829 |
+
raise ValueError("Matrix e should be square.")
|
830 |
+
if m != e.shape[0]:
|
831 |
+
raise ValueError("Matrix a and e should have the same shape.")
|
832 |
+
# numpy.linalg.cond doesn't check for exact zeros and
|
833 |
+
# emits a runtime warning. Hence the following manual check.
|
834 |
+
min_sv = svd(e, compute_uv=False)[-1]
|
835 |
+
if min_sv == 0. or min_sv < np.spacing(1.) * norm(e, 1):
|
836 |
+
raise ValueError('Matrix e is numerically singular.')
|
837 |
+
if np.iscomplexobj(e):
|
838 |
+
r_or_c = complex
|
839 |
+
if s is not None:
|
840 |
+
s = np.atleast_2d(_asarray_validated(s, check_finite=True))
|
841 |
+
if s.shape != b.shape:
|
842 |
+
raise ValueError("Matrix b and s should have the same shape.")
|
843 |
+
if np.iscomplexobj(s):
|
844 |
+
r_or_c = complex
|
845 |
+
|
846 |
+
return a, b, q, r, e, s, m, n, r_or_c, generalized_case
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_testutils.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
|
4 |
+
class _FakeMatrix:
|
5 |
+
def __init__(self, data):
|
6 |
+
self._data = data
|
7 |
+
self.__array_interface__ = data.__array_interface__
|
8 |
+
|
9 |
+
|
10 |
+
class _FakeMatrix2:
|
11 |
+
def __init__(self, data):
|
12 |
+
self._data = data
|
13 |
+
|
14 |
+
def __array__(self, dtype=None, copy=None):
|
15 |
+
return self._data
|
16 |
+
|
17 |
+
|
18 |
+
def _get_array(shape, dtype):
|
19 |
+
"""
|
20 |
+
Get a test array of given shape and data type.
|
21 |
+
Returned NxN matrices are posdef, and 2xN are banded-posdef.
|
22 |
+
|
23 |
+
"""
|
24 |
+
if len(shape) == 2 and shape[0] == 2:
|
25 |
+
# yield a banded positive definite one
|
26 |
+
x = np.zeros(shape, dtype=dtype)
|
27 |
+
x[0, 1:] = -1
|
28 |
+
x[1] = 2
|
29 |
+
return x
|
30 |
+
elif len(shape) == 2 and shape[0] == shape[1]:
|
31 |
+
# always yield a positive definite matrix
|
32 |
+
x = np.zeros(shape, dtype=dtype)
|
33 |
+
j = np.arange(shape[0])
|
34 |
+
x[j, j] = 2
|
35 |
+
x[j[:-1], j[:-1]+1] = -1
|
36 |
+
x[j[:-1]+1, j[:-1]] = -1
|
37 |
+
return x
|
38 |
+
else:
|
39 |
+
np.random.seed(1234)
|
40 |
+
return np.random.randn(*shape).astype(dtype)
|
41 |
+
|
42 |
+
|
43 |
+
def _id(x):
|
44 |
+
return x
|
45 |
+
|
46 |
+
|
47 |
+
def assert_no_overwrite(call, shapes, dtypes=None):
|
48 |
+
"""
|
49 |
+
Test that a call does not overwrite its input arguments
|
50 |
+
"""
|
51 |
+
|
52 |
+
if dtypes is None:
|
53 |
+
dtypes = [np.float32, np.float64, np.complex64, np.complex128]
|
54 |
+
|
55 |
+
for dtype in dtypes:
|
56 |
+
for order in ["C", "F"]:
|
57 |
+
for faker in [_id, _FakeMatrix, _FakeMatrix2]:
|
58 |
+
orig_inputs = [_get_array(s, dtype) for s in shapes]
|
59 |
+
inputs = [faker(x.copy(order)) for x in orig_inputs]
|
60 |
+
call(*inputs)
|
61 |
+
msg = f"call modified inputs [{dtype!r}, {faker!r}]"
|
62 |
+
for a, b in zip(inputs, orig_inputs):
|
63 |
+
np.testing.assert_equal(a, b, err_msg=msg)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This file was generated by _generate_pyx.py.
|
3 |
+
Do not edit this file directly.
|
4 |
+
"""
|
5 |
+
|
6 |
+
# Within scipy, these wrappers can be used via relative or absolute cimport.
|
7 |
+
# Examples:
|
8 |
+
# from ..linalg cimport cython_blas
|
9 |
+
# from scipy.linalg cimport cython_blas
|
10 |
+
# cimport scipy.linalg.cython_blas as cython_blas
|
11 |
+
# cimport ..linalg.cython_blas as cython_blas
|
12 |
+
|
13 |
+
# Within SciPy, if BLAS functions are needed in C/C++/Fortran,
|
14 |
+
# these wrappers should not be used.
|
15 |
+
# The original libraries should be linked directly.
|
16 |
+
|
17 |
+
ctypedef float s
|
18 |
+
ctypedef double d
|
19 |
+
ctypedef float complex c
|
20 |
+
ctypedef double complex z
|
21 |
+
|
22 |
+
cdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogil
|
23 |
+
cdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
|
24 |
+
cdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
|
25 |
+
cdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
|
26 |
+
cdef void cgbmv(char *trans, int *m, int *n, int *kl, int *ku, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
|
27 |
+
cdef void cgemm(char *transa, char *transb, int *m, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
|
28 |
+
cdef void cgemv(char *trans, int *m, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
|
29 |
+
cdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
|
30 |
+
cdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
|
31 |
+
cdef void chbmv(char *uplo, int *n, int *k, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
|
32 |
+
cdef void chemm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
|
33 |
+
cdef void chemv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
|
34 |
+
cdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil
|
35 |
+
cdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
|
36 |
+
cdef void cher2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, s *beta, c *c, int *ldc) noexcept nogil
|
37 |
+
cdef void cherk(char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c, int *ldc) noexcept nogil
|
38 |
+
cdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
|
39 |
+
cdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogil
|
40 |
+
cdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogil
|
41 |
+
cdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogil
|
42 |
+
cdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogil
|
43 |
+
cdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogil
|
44 |
+
cdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogil
|
45 |
+
cdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
|
46 |
+
cdef void csymm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
|
47 |
+
cdef void csyr2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
|
48 |
+
cdef void csyrk(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *beta, c *c, int *ldc) noexcept nogil
|
49 |
+
cdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil
|
50 |
+
cdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil
|
51 |
+
cdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil
|
52 |
+
cdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil
|
53 |
+
cdef void ctrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil
|
54 |
+
cdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil
|
55 |
+
cdef void ctrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil
|
56 |
+
cdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil
|
57 |
+
cdef d dasum(int *n, d *dx, int *incx) noexcept nogil
|
58 |
+
cdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogil
|
59 |
+
cdef d dcabs1(z *z) noexcept nogil
|
60 |
+
cdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
|
61 |
+
cdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
|
62 |
+
cdef void dgbmv(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
|
63 |
+
cdef void dgemm(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
|
64 |
+
cdef void dgemv(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
|
65 |
+
cdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil
|
66 |
+
cdef d dnrm2(int *n, d *x, int *incx) noexcept nogil
|
67 |
+
cdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogil
|
68 |
+
cdef void drotg(d *da, d *db, d *c, d *s) noexcept nogil
|
69 |
+
cdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogil
|
70 |
+
cdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogil
|
71 |
+
cdef void dsbmv(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
|
72 |
+
cdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogil
|
73 |
+
cdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
|
74 |
+
cdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
|
75 |
+
cdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogil
|
76 |
+
cdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogil
|
77 |
+
cdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
|
78 |
+
cdef void dsymm(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
|
79 |
+
cdef void dsymv(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
|
80 |
+
cdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogil
|
81 |
+
cdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil
|
82 |
+
cdef void dsyr2k(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
|
83 |
+
cdef void dsyrk(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) noexcept nogil
|
84 |
+
cdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil
|
85 |
+
cdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil
|
86 |
+
cdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil
|
87 |
+
cdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil
|
88 |
+
cdef void dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil
|
89 |
+
cdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil
|
90 |
+
cdef void dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil
|
91 |
+
cdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil
|
92 |
+
cdef d dzasum(int *n, z *zx, int *incx) noexcept nogil
|
93 |
+
cdef d dznrm2(int *n, z *x, int *incx) noexcept nogil
|
94 |
+
cdef int icamax(int *n, c *cx, int *incx) noexcept nogil
|
95 |
+
cdef int idamax(int *n, d *dx, int *incx) noexcept nogil
|
96 |
+
cdef int isamax(int *n, s *sx, int *incx) noexcept nogil
|
97 |
+
cdef int izamax(int *n, z *zx, int *incx) noexcept nogil
|
98 |
+
cdef bint lsame(char *ca, char *cb) noexcept nogil
|
99 |
+
cdef s sasum(int *n, s *sx, int *incx) noexcept nogil
|
100 |
+
cdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogil
|
101 |
+
cdef s scasum(int *n, c *cx, int *incx) noexcept nogil
|
102 |
+
cdef s scnrm2(int *n, c *x, int *incx) noexcept nogil
|
103 |
+
cdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
|
104 |
+
cdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
|
105 |
+
cdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogil
|
106 |
+
cdef void sgbmv(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
|
107 |
+
cdef void sgemm(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
|
108 |
+
cdef void sgemv(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
|
109 |
+
cdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil
|
110 |
+
cdef s snrm2(int *n, s *x, int *incx) noexcept nogil
|
111 |
+
cdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogil
|
112 |
+
cdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogil
|
113 |
+
cdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogil
|
114 |
+
cdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogil
|
115 |
+
cdef void ssbmv(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
|
116 |
+
cdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogil
|
117 |
+
cdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
|
118 |
+
cdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogil
|
119 |
+
cdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogil
|
120 |
+
cdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
|
121 |
+
cdef void ssymm(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
|
122 |
+
cdef void ssymv(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
|
123 |
+
cdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogil
|
124 |
+
cdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil
|
125 |
+
cdef void ssyr2k(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
|
126 |
+
cdef void ssyrk(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) noexcept nogil
|
127 |
+
cdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil
|
128 |
+
cdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil
|
129 |
+
cdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil
|
130 |
+
cdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil
|
131 |
+
cdef void strmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil
|
132 |
+
cdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil
|
133 |
+
cdef void strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil
|
134 |
+
cdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil
|
135 |
+
cdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogil
|
136 |
+
cdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
|
137 |
+
cdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
|
138 |
+
cdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
|
139 |
+
cdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogil
|
140 |
+
cdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogil
|
141 |
+
cdef void zgbmv(char *trans, int *m, int *n, int *kl, int *ku, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
|
142 |
+
cdef void zgemm(char *transa, char *transb, int *m, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
|
143 |
+
cdef void zgemv(char *trans, int *m, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
|
144 |
+
cdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
|
145 |
+
cdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
|
146 |
+
cdef void zhbmv(char *uplo, int *n, int *k, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
|
147 |
+
cdef void zhemm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
|
148 |
+
cdef void zhemv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
|
149 |
+
cdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil
|
150 |
+
cdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
|
151 |
+
cdef void zher2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, d *beta, z *c, int *ldc) noexcept nogil
|
152 |
+
cdef void zherk(char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c, int *ldc) noexcept nogil
|
153 |
+
cdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
|
154 |
+
cdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogil
|
155 |
+
cdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogil
|
156 |
+
cdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogil
|
157 |
+
cdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogil
|
158 |
+
cdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
|
159 |
+
cdef void zsymm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
|
160 |
+
cdef void zsyr2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
|
161 |
+
cdef void zsyrk(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *beta, z *c, int *ldc) noexcept nogil
|
162 |
+
cdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil
|
163 |
+
cdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil
|
164 |
+
cdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil
|
165 |
+
cdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil
|
166 |
+
cdef void ztrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil
|
167 |
+
cdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil
|
168 |
+
cdef void ztrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil
|
169 |
+
cdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx
ADDED
@@ -0,0 +1,1422 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file was generated by _generate_pyx.py.
|
2 |
+
# Do not edit this file directly.
|
3 |
+
# cython: boundscheck = False
|
4 |
+
# cython: wraparound = False
|
5 |
+
# cython: cdivision = True
|
6 |
+
|
7 |
+
"""
|
8 |
+
BLAS Functions for Cython
|
9 |
+
=========================
|
10 |
+
|
11 |
+
Usable from Cython via::
|
12 |
+
|
13 |
+
cimport scipy.linalg.cython_blas
|
14 |
+
|
15 |
+
These wrappers do not check for alignment of arrays.
|
16 |
+
Alignment should be checked before these wrappers are used.
|
17 |
+
|
18 |
+
Raw function pointers (Fortran-style pointer arguments):
|
19 |
+
|
20 |
+
- caxpy
|
21 |
+
- ccopy
|
22 |
+
- cdotc
|
23 |
+
- cdotu
|
24 |
+
- cgbmv
|
25 |
+
- cgemm
|
26 |
+
- cgemv
|
27 |
+
- cgerc
|
28 |
+
- cgeru
|
29 |
+
- chbmv
|
30 |
+
- chemm
|
31 |
+
- chemv
|
32 |
+
- cher
|
33 |
+
- cher2
|
34 |
+
- cher2k
|
35 |
+
- cherk
|
36 |
+
- chpmv
|
37 |
+
- chpr
|
38 |
+
- chpr2
|
39 |
+
- crotg
|
40 |
+
- cscal
|
41 |
+
- csrot
|
42 |
+
- csscal
|
43 |
+
- cswap
|
44 |
+
- csymm
|
45 |
+
- csyr2k
|
46 |
+
- csyrk
|
47 |
+
- ctbmv
|
48 |
+
- ctbsv
|
49 |
+
- ctpmv
|
50 |
+
- ctpsv
|
51 |
+
- ctrmm
|
52 |
+
- ctrmv
|
53 |
+
- ctrsm
|
54 |
+
- ctrsv
|
55 |
+
- dasum
|
56 |
+
- daxpy
|
57 |
+
- dcabs1
|
58 |
+
- dcopy
|
59 |
+
- ddot
|
60 |
+
- dgbmv
|
61 |
+
- dgemm
|
62 |
+
- dgemv
|
63 |
+
- dger
|
64 |
+
- dnrm2
|
65 |
+
- drot
|
66 |
+
- drotg
|
67 |
+
- drotm
|
68 |
+
- drotmg
|
69 |
+
- dsbmv
|
70 |
+
- dscal
|
71 |
+
- dsdot
|
72 |
+
- dspmv
|
73 |
+
- dspr
|
74 |
+
- dspr2
|
75 |
+
- dswap
|
76 |
+
- dsymm
|
77 |
+
- dsymv
|
78 |
+
- dsyr
|
79 |
+
- dsyr2
|
80 |
+
- dsyr2k
|
81 |
+
- dsyrk
|
82 |
+
- dtbmv
|
83 |
+
- dtbsv
|
84 |
+
- dtpmv
|
85 |
+
- dtpsv
|
86 |
+
- dtrmm
|
87 |
+
- dtrmv
|
88 |
+
- dtrsm
|
89 |
+
- dtrsv
|
90 |
+
- dzasum
|
91 |
+
- dznrm2
|
92 |
+
- icamax
|
93 |
+
- idamax
|
94 |
+
- isamax
|
95 |
+
- izamax
|
96 |
+
- lsame
|
97 |
+
- sasum
|
98 |
+
- saxpy
|
99 |
+
- scasum
|
100 |
+
- scnrm2
|
101 |
+
- scopy
|
102 |
+
- sdot
|
103 |
+
- sdsdot
|
104 |
+
- sgbmv
|
105 |
+
- sgemm
|
106 |
+
- sgemv
|
107 |
+
- sger
|
108 |
+
- snrm2
|
109 |
+
- srot
|
110 |
+
- srotg
|
111 |
+
- srotm
|
112 |
+
- srotmg
|
113 |
+
- ssbmv
|
114 |
+
- sscal
|
115 |
+
- sspmv
|
116 |
+
- sspr
|
117 |
+
- sspr2
|
118 |
+
- sswap
|
119 |
+
- ssymm
|
120 |
+
- ssymv
|
121 |
+
- ssyr
|
122 |
+
- ssyr2
|
123 |
+
- ssyr2k
|
124 |
+
- ssyrk
|
125 |
+
- stbmv
|
126 |
+
- stbsv
|
127 |
+
- stpmv
|
128 |
+
- stpsv
|
129 |
+
- strmm
|
130 |
+
- strmv
|
131 |
+
- strsm
|
132 |
+
- strsv
|
133 |
+
- zaxpy
|
134 |
+
- zcopy
|
135 |
+
- zdotc
|
136 |
+
- zdotu
|
137 |
+
- zdrot
|
138 |
+
- zdscal
|
139 |
+
- zgbmv
|
140 |
+
- zgemm
|
141 |
+
- zgemv
|
142 |
+
- zgerc
|
143 |
+
- zgeru
|
144 |
+
- zhbmv
|
145 |
+
- zhemm
|
146 |
+
- zhemv
|
147 |
+
- zher
|
148 |
+
- zher2
|
149 |
+
- zher2k
|
150 |
+
- zherk
|
151 |
+
- zhpmv
|
152 |
+
- zhpr
|
153 |
+
- zhpr2
|
154 |
+
- zrotg
|
155 |
+
- zscal
|
156 |
+
- zswap
|
157 |
+
- zsymm
|
158 |
+
- zsyr2k
|
159 |
+
- zsyrk
|
160 |
+
- ztbmv
|
161 |
+
- ztbsv
|
162 |
+
- ztpmv
|
163 |
+
- ztpsv
|
164 |
+
- ztrmm
|
165 |
+
- ztrmv
|
166 |
+
- ztrsm
|
167 |
+
- ztrsv
|
168 |
+
|
169 |
+
|
170 |
+
"""
|
171 |
+
|
172 |
+
# Within SciPy, these wrappers can be used via relative or absolute cimport.
|
173 |
+
# Examples:
|
174 |
+
# from ..linalg cimport cython_blas
|
175 |
+
# from scipy.linalg cimport cython_blas
|
176 |
+
# cimport scipy.linalg.cython_blas as cython_blas
|
177 |
+
# cimport ..linalg.cython_blas as cython_blas
|
178 |
+
|
179 |
+
# Within SciPy, if BLAS functions are needed in C/C++/Fortran,
|
180 |
+
# these wrappers should not be used.
|
181 |
+
# The original libraries should be linked directly.
|
182 |
+
|
183 |
+
cdef extern from "fortran_defs.h":
|
184 |
+
pass
|
185 |
+
|
186 |
+
from numpy cimport npy_complex64, npy_complex128
|
187 |
+
|
188 |
+
|
189 |
+
cdef extern from "_blas_subroutines.h":
|
190 |
+
void _fortran_caxpy "BLAS_FUNC(caxpy)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
|
191 |
+
cdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
|
192 |
+
|
193 |
+
_fortran_caxpy(n, <npy_complex64*>ca, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy)
|
194 |
+
|
195 |
+
|
196 |
+
cdef extern from "_blas_subroutines.h":
|
197 |
+
void _fortran_ccopy "BLAS_FUNC(ccopy)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
|
198 |
+
cdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
|
199 |
+
|
200 |
+
_fortran_ccopy(n, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy)
|
201 |
+
|
202 |
+
|
203 |
+
cdef extern from "_blas_subroutines.h":
|
204 |
+
void _fortran_cdotc "(cdotcwrp_)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
|
205 |
+
cdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
|
206 |
+
cdef c out
|
207 |
+
_fortran_cdotc(<npy_complex64*>&out, n, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy)
|
208 |
+
return out
|
209 |
+
|
210 |
+
cdef extern from "_blas_subroutines.h":
|
211 |
+
void _fortran_cdotu "(cdotuwrp_)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
|
212 |
+
cdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
|
213 |
+
cdef c out
|
214 |
+
_fortran_cdotu(<npy_complex64*>&out, n, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy)
|
215 |
+
return out
|
216 |
+
|
217 |
+
cdef extern from "_blas_subroutines.h":
|
218 |
+
void _fortran_cgbmv "BLAS_FUNC(cgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
|
219 |
+
cdef void cgbmv(char *trans, int *m, int *n, int *kl, int *ku, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
|
220 |
+
|
221 |
+
_fortran_cgbmv(trans, m, n, kl, ku, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>x, incx, <npy_complex64*>beta, <npy_complex64*>y, incy)
|
222 |
+
|
223 |
+
|
224 |
+
cdef extern from "_blas_subroutines.h":
|
225 |
+
void _fortran_cgemm "BLAS_FUNC(cgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
|
226 |
+
cdef void cgemm(char *transa, char *transb, int *m, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
|
227 |
+
|
228 |
+
_fortran_cgemm(transa, transb, m, n, k, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb, <npy_complex64*>beta, <npy_complex64*>c, ldc)
|
229 |
+
|
230 |
+
|
231 |
+
cdef extern from "_blas_subroutines.h":
|
232 |
+
void _fortran_cgemv "BLAS_FUNC(cgemv)"(char *trans, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
|
233 |
+
cdef void cgemv(char *trans, int *m, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
|
234 |
+
|
235 |
+
_fortran_cgemv(trans, m, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>x, incx, <npy_complex64*>beta, <npy_complex64*>y, incy)
|
236 |
+
|
237 |
+
|
238 |
+
cdef extern from "_blas_subroutines.h":
|
239 |
+
void _fortran_cgerc "BLAS_FUNC(cgerc)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
|
240 |
+
cdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
|
241 |
+
|
242 |
+
_fortran_cgerc(m, n, <npy_complex64*>alpha, <npy_complex64*>x, incx, <npy_complex64*>y, incy, <npy_complex64*>a, lda)
|
243 |
+
|
244 |
+
|
245 |
+
cdef extern from "_blas_subroutines.h":
|
246 |
+
void _fortran_cgeru "BLAS_FUNC(cgeru)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
|
247 |
+
cdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
|
248 |
+
|
249 |
+
_fortran_cgeru(m, n, <npy_complex64*>alpha, <npy_complex64*>x, incx, <npy_complex64*>y, incy, <npy_complex64*>a, lda)
|
250 |
+
|
251 |
+
|
252 |
+
cdef extern from "_blas_subroutines.h":
|
253 |
+
void _fortran_chbmv "BLAS_FUNC(chbmv)"(char *uplo, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
|
254 |
+
cdef void chbmv(char *uplo, int *n, int *k, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
|
255 |
+
|
256 |
+
_fortran_chbmv(uplo, n, k, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>x, incx, <npy_complex64*>beta, <npy_complex64*>y, incy)
|
257 |
+
|
258 |
+
|
259 |
+
cdef extern from "_blas_subroutines.h":
|
260 |
+
void _fortran_chemm "BLAS_FUNC(chemm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
|
261 |
+
cdef void chemm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
|
262 |
+
|
263 |
+
_fortran_chemm(side, uplo, m, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb, <npy_complex64*>beta, <npy_complex64*>c, ldc)
|
264 |
+
|
265 |
+
|
266 |
+
cdef extern from "_blas_subroutines.h":
|
267 |
+
void _fortran_chemv "BLAS_FUNC(chemv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
|
268 |
+
cdef void chemv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
|
269 |
+
|
270 |
+
_fortran_chemv(uplo, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>x, incx, <npy_complex64*>beta, <npy_complex64*>y, incy)
|
271 |
+
|
272 |
+
|
273 |
+
cdef extern from "_blas_subroutines.h":
|
274 |
+
void _fortran_cher "BLAS_FUNC(cher)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda) nogil
|
275 |
+
cdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil:
|
276 |
+
|
277 |
+
_fortran_cher(uplo, n, alpha, <npy_complex64*>x, incx, <npy_complex64*>a, lda)
|
278 |
+
|
279 |
+
|
280 |
+
cdef extern from "_blas_subroutines.h":
|
281 |
+
void _fortran_cher2 "BLAS_FUNC(cher2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
|
282 |
+
cdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
|
283 |
+
|
284 |
+
_fortran_cher2(uplo, n, <npy_complex64*>alpha, <npy_complex64*>x, incx, <npy_complex64*>y, incy, <npy_complex64*>a, lda)
|
285 |
+
|
286 |
+
|
287 |
+
cdef extern from "_blas_subroutines.h":
|
288 |
+
void _fortran_cher2k "BLAS_FUNC(cher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *beta, npy_complex64 *c, int *ldc) nogil
|
289 |
+
cdef void cher2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, s *beta, c *c, int *ldc) noexcept nogil:
|
290 |
+
|
291 |
+
_fortran_cher2k(uplo, trans, n, k, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb, beta, <npy_complex64*>c, ldc)
|
292 |
+
|
293 |
+
|
294 |
+
cdef extern from "_blas_subroutines.h":
|
295 |
+
void _fortran_cherk "BLAS_FUNC(cherk)"(char *uplo, char *trans, int *n, int *k, s *alpha, npy_complex64 *a, int *lda, s *beta, npy_complex64 *c, int *ldc) nogil
|
296 |
+
cdef void cherk(char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c, int *ldc) noexcept nogil:
|
297 |
+
|
298 |
+
_fortran_cherk(uplo, trans, n, k, alpha, <npy_complex64*>a, lda, beta, <npy_complex64*>c, ldc)
|
299 |
+
|
300 |
+
|
301 |
+
cdef extern from "_blas_subroutines.h":
|
302 |
+
void _fortran_chpmv "BLAS_FUNC(chpmv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
|
303 |
+
cdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
|
304 |
+
|
305 |
+
_fortran_chpmv(uplo, n, <npy_complex64*>alpha, <npy_complex64*>ap, <npy_complex64*>x, incx, <npy_complex64*>beta, <npy_complex64*>y, incy)
|
306 |
+
|
307 |
+
|
308 |
+
cdef extern from "_blas_subroutines.h":
|
309 |
+
void _fortran_chpr "BLAS_FUNC(chpr)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap) nogil
|
310 |
+
cdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogil:
|
311 |
+
|
312 |
+
_fortran_chpr(uplo, n, alpha, <npy_complex64*>x, incx, <npy_complex64*>ap)
|
313 |
+
|
314 |
+
|
315 |
+
cdef extern from "_blas_subroutines.h":
|
316 |
+
void _fortran_chpr2 "BLAS_FUNC(chpr2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *ap) nogil
|
317 |
+
cdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogil:
|
318 |
+
|
319 |
+
_fortran_chpr2(uplo, n, <npy_complex64*>alpha, <npy_complex64*>x, incx, <npy_complex64*>y, incy, <npy_complex64*>ap)
|
320 |
+
|
321 |
+
|
322 |
+
cdef extern from "_blas_subroutines.h":
|
323 |
+
void _fortran_crotg "BLAS_FUNC(crotg)"(npy_complex64 *ca, npy_complex64 *cb, s *c, npy_complex64 *s) nogil
|
324 |
+
cdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogil:
|
325 |
+
|
326 |
+
_fortran_crotg(<npy_complex64*>ca, <npy_complex64*>cb, c, <npy_complex64*>s)
|
327 |
+
|
328 |
+
|
329 |
+
cdef extern from "_blas_subroutines.h":
|
330 |
+
void _fortran_cscal "BLAS_FUNC(cscal)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx) nogil
|
331 |
+
cdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogil:
|
332 |
+
|
333 |
+
_fortran_cscal(n, <npy_complex64*>ca, <npy_complex64*>cx, incx)
|
334 |
+
|
335 |
+
|
336 |
+
cdef extern from "_blas_subroutines.h":
|
337 |
+
void _fortran_csrot "BLAS_FUNC(csrot)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, s *c, s *s) nogil
|
338 |
+
cdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogil:
|
339 |
+
|
340 |
+
_fortran_csrot(n, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy, c, s)
|
341 |
+
|
342 |
+
|
343 |
+
cdef extern from "_blas_subroutines.h":
|
344 |
+
void _fortran_csscal "BLAS_FUNC(csscal)"(int *n, s *sa, npy_complex64 *cx, int *incx) nogil
|
345 |
+
cdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogil:
|
346 |
+
|
347 |
+
_fortran_csscal(n, sa, <npy_complex64*>cx, incx)
|
348 |
+
|
349 |
+
|
350 |
+
cdef extern from "_blas_subroutines.h":
|
351 |
+
void _fortran_cswap "BLAS_FUNC(cswap)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
|
352 |
+
cdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
|
353 |
+
|
354 |
+
_fortran_cswap(n, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy)
|
355 |
+
|
356 |
+
|
357 |
+
cdef extern from "_blas_subroutines.h":
|
358 |
+
void _fortran_csymm "BLAS_FUNC(csymm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
|
359 |
+
cdef void csymm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
|
360 |
+
|
361 |
+
_fortran_csymm(side, uplo, m, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb, <npy_complex64*>beta, <npy_complex64*>c, ldc)
|
362 |
+
|
363 |
+
|
364 |
+
cdef extern from "_blas_subroutines.h":
|
365 |
+
void _fortran_csyr2k "BLAS_FUNC(csyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
|
366 |
+
cdef void csyr2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
|
367 |
+
|
368 |
+
_fortran_csyr2k(uplo, trans, n, k, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb, <npy_complex64*>beta, <npy_complex64*>c, ldc)
|
369 |
+
|
370 |
+
|
371 |
+
cdef extern from "_blas_subroutines.h":
|
372 |
+
void _fortran_csyrk "BLAS_FUNC(csyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
|
373 |
+
cdef void csyrk(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *beta, c *c, int *ldc) noexcept nogil:
|
374 |
+
|
375 |
+
_fortran_csyrk(uplo, trans, n, k, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>beta, <npy_complex64*>c, ldc)
|
376 |
+
|
377 |
+
|
378 |
+
cdef extern from "_blas_subroutines.h":
|
379 |
+
void _fortran_ctbmv "BLAS_FUNC(ctbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
|
380 |
+
cdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil:
|
381 |
+
|
382 |
+
_fortran_ctbmv(uplo, trans, diag, n, k, <npy_complex64*>a, lda, <npy_complex64*>x, incx)
|
383 |
+
|
384 |
+
|
385 |
+
cdef extern from "_blas_subroutines.h":
|
386 |
+
void _fortran_ctbsv "BLAS_FUNC(ctbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
|
387 |
+
cdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil:
|
388 |
+
|
389 |
+
_fortran_ctbsv(uplo, trans, diag, n, k, <npy_complex64*>a, lda, <npy_complex64*>x, incx)
|
390 |
+
|
391 |
+
|
392 |
+
cdef extern from "_blas_subroutines.h":
|
393 |
+
void _fortran_ctpmv "BLAS_FUNC(ctpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogil
|
394 |
+
cdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil:
|
395 |
+
|
396 |
+
_fortran_ctpmv(uplo, trans, diag, n, <npy_complex64*>ap, <npy_complex64*>x, incx)
|
397 |
+
|
398 |
+
|
399 |
+
cdef extern from "_blas_subroutines.h":
|
400 |
+
void _fortran_ctpsv "BLAS_FUNC(ctpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogil
|
401 |
+
cdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil:
|
402 |
+
|
403 |
+
_fortran_ctpsv(uplo, trans, diag, n, <npy_complex64*>ap, <npy_complex64*>x, incx)
|
404 |
+
|
405 |
+
|
406 |
+
cdef extern from "_blas_subroutines.h":
|
407 |
+
void _fortran_ctrmm "BLAS_FUNC(ctrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil
|
408 |
+
cdef void ctrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil:
|
409 |
+
|
410 |
+
_fortran_ctrmm(side, uplo, transa, diag, m, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb)
|
411 |
+
|
412 |
+
|
413 |
+
cdef extern from "_blas_subroutines.h":
|
414 |
+
void _fortran_ctrmv "BLAS_FUNC(ctrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
|
415 |
+
cdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil:
|
416 |
+
|
417 |
+
_fortran_ctrmv(uplo, trans, diag, n, <npy_complex64*>a, lda, <npy_complex64*>x, incx)
|
418 |
+
|
419 |
+
|
420 |
+
cdef extern from "_blas_subroutines.h":
|
421 |
+
void _fortran_ctrsm "BLAS_FUNC(ctrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil
|
422 |
+
cdef void ctrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil:
|
423 |
+
|
424 |
+
_fortran_ctrsm(side, uplo, transa, diag, m, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb)
|
425 |
+
|
426 |
+
|
427 |
+
cdef extern from "_blas_subroutines.h":
|
428 |
+
void _fortran_ctrsv "BLAS_FUNC(ctrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
|
429 |
+
cdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil:
|
430 |
+
|
431 |
+
_fortran_ctrsv(uplo, trans, diag, n, <npy_complex64*>a, lda, <npy_complex64*>x, incx)
|
432 |
+
|
433 |
+
|
434 |
+
cdef extern from "_blas_subroutines.h":
|
435 |
+
d _fortran_dasum "BLAS_FUNC(dasum)"(int *n, d *dx, int *incx) nogil
|
436 |
+
cdef d dasum(int *n, d *dx, int *incx) noexcept nogil:
|
437 |
+
|
438 |
+
return _fortran_dasum(n, dx, incx)
|
439 |
+
|
440 |
+
|
441 |
+
cdef extern from "_blas_subroutines.h":
|
442 |
+
void _fortran_daxpy "BLAS_FUNC(daxpy)"(int *n, d *da, d *dx, int *incx, d *dy, int *incy) nogil
|
443 |
+
cdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
|
444 |
+
|
445 |
+
_fortran_daxpy(n, da, dx, incx, dy, incy)
|
446 |
+
|
447 |
+
|
448 |
+
cdef extern from "_blas_subroutines.h":
|
449 |
+
d _fortran_dcabs1 "BLAS_FUNC(dcabs1)"(npy_complex128 *z) nogil
|
450 |
+
cdef d dcabs1(z *z) noexcept nogil:
|
451 |
+
|
452 |
+
return _fortran_dcabs1(<npy_complex128*>z)
|
453 |
+
|
454 |
+
|
455 |
+
cdef extern from "_blas_subroutines.h":
|
456 |
+
void _fortran_dcopy "BLAS_FUNC(dcopy)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
|
457 |
+
cdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
|
458 |
+
|
459 |
+
_fortran_dcopy(n, dx, incx, dy, incy)
|
460 |
+
|
461 |
+
|
462 |
+
cdef extern from "_blas_subroutines.h":
|
463 |
+
d _fortran_ddot "BLAS_FUNC(ddot)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
|
464 |
+
cdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
|
465 |
+
|
466 |
+
return _fortran_ddot(n, dx, incx, dy, incy)
|
467 |
+
|
468 |
+
|
469 |
+
cdef extern from "_blas_subroutines.h":
|
470 |
+
void _fortran_dgbmv "BLAS_FUNC(dgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
|
471 |
+
cdef void dgbmv(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
|
472 |
+
|
473 |
+
_fortran_dgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
|
474 |
+
|
475 |
+
|
476 |
+
cdef extern from "_blas_subroutines.h":
|
477 |
+
void _fortran_dgemm "BLAS_FUNC(dgemm)"(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil
|
478 |
+
cdef void dgemm(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil:
|
479 |
+
|
480 |
+
_fortran_dgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
|
481 |
+
|
482 |
+
|
483 |
+
cdef extern from "_blas_subroutines.h":
|
484 |
+
void _fortran_dgemv "BLAS_FUNC(dgemv)"(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
|
485 |
+
cdef void dgemv(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
|
486 |
+
|
487 |
+
_fortran_dgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
|
488 |
+
|
489 |
+
|
490 |
+
cdef extern from "_blas_subroutines.h":
|
491 |
+
void _fortran_dger "BLAS_FUNC(dger)"(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogil
|
492 |
+
cdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil:
|
493 |
+
|
494 |
+
_fortran_dger(m, n, alpha, x, incx, y, incy, a, lda)
|
495 |
+
|
496 |
+
|
497 |
+
cdef extern from "_blas_subroutines.h":
|
498 |
+
d _fortran_dnrm2 "BLAS_FUNC(dnrm2)"(int *n, d *x, int *incx) nogil
|
499 |
+
cdef d dnrm2(int *n, d *x, int *incx) noexcept nogil:
|
500 |
+
|
501 |
+
return _fortran_dnrm2(n, x, incx)
|
502 |
+
|
503 |
+
|
504 |
+
cdef extern from "_blas_subroutines.h":
|
505 |
+
void _fortran_drot "BLAS_FUNC(drot)"(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) nogil
|
506 |
+
cdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogil:
|
507 |
+
|
508 |
+
_fortran_drot(n, dx, incx, dy, incy, c, s)
|
509 |
+
|
510 |
+
|
511 |
+
cdef extern from "_blas_subroutines.h":
|
512 |
+
void _fortran_drotg "BLAS_FUNC(drotg)"(d *da, d *db, d *c, d *s) nogil
|
513 |
+
cdef void drotg(d *da, d *db, d *c, d *s) noexcept nogil:
|
514 |
+
|
515 |
+
_fortran_drotg(da, db, c, s)
|
516 |
+
|
517 |
+
|
518 |
+
cdef extern from "_blas_subroutines.h":
|
519 |
+
void _fortran_drotm "BLAS_FUNC(drotm)"(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) nogil
|
520 |
+
cdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogil:
|
521 |
+
|
522 |
+
_fortran_drotm(n, dx, incx, dy, incy, dparam)
|
523 |
+
|
524 |
+
|
525 |
+
cdef extern from "_blas_subroutines.h":
|
526 |
+
void _fortran_drotmg "BLAS_FUNC(drotmg)"(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) nogil
|
527 |
+
cdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogil:
|
528 |
+
|
529 |
+
_fortran_drotmg(dd1, dd2, dx1, dy1, dparam)
|
530 |
+
|
531 |
+
|
532 |
+
cdef extern from "_blas_subroutines.h":
|
533 |
+
void _fortran_dsbmv "BLAS_FUNC(dsbmv)"(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
|
534 |
+
cdef void dsbmv(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
|
535 |
+
|
536 |
+
_fortran_dsbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
|
537 |
+
|
538 |
+
|
539 |
+
cdef extern from "_blas_subroutines.h":
|
540 |
+
void _fortran_dscal "BLAS_FUNC(dscal)"(int *n, d *da, d *dx, int *incx) nogil
|
541 |
+
cdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogil:
|
542 |
+
|
543 |
+
_fortran_dscal(n, da, dx, incx)
|
544 |
+
|
545 |
+
|
546 |
+
cdef extern from "_blas_subroutines.h":
|
547 |
+
d _fortran_dsdot "BLAS_FUNC(dsdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
|
548 |
+
cdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
|
549 |
+
|
550 |
+
return _fortran_dsdot(n, sx, incx, sy, incy)
|
551 |
+
|
552 |
+
|
553 |
+
cdef extern from "_blas_subroutines.h":
|
554 |
+
void _fortran_dspmv "BLAS_FUNC(dspmv)"(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) nogil
|
555 |
+
cdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
|
556 |
+
|
557 |
+
_fortran_dspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
|
558 |
+
|
559 |
+
|
560 |
+
cdef extern from "_blas_subroutines.h":
|
561 |
+
void _fortran_dspr "BLAS_FUNC(dspr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) nogil
|
562 |
+
cdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogil:
|
563 |
+
|
564 |
+
_fortran_dspr(uplo, n, alpha, x, incx, ap)
|
565 |
+
|
566 |
+
|
567 |
+
cdef extern from "_blas_subroutines.h":
|
568 |
+
void _fortran_dspr2 "BLAS_FUNC(dspr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) nogil
|
569 |
+
cdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogil:
|
570 |
+
|
571 |
+
_fortran_dspr2(uplo, n, alpha, x, incx, y, incy, ap)
|
572 |
+
|
573 |
+
|
574 |
+
cdef extern from "_blas_subroutines.h":
|
575 |
+
void _fortran_dswap "BLAS_FUNC(dswap)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
|
576 |
+
cdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
|
577 |
+
|
578 |
+
_fortran_dswap(n, dx, incx, dy, incy)
|
579 |
+
|
580 |
+
|
581 |
+
cdef extern from "_blas_subroutines.h":
|
582 |
+
void _fortran_dsymm "BLAS_FUNC(dsymm)"(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil
|
583 |
+
cdef void dsymm(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil:
|
584 |
+
|
585 |
+
_fortran_dsymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
|
586 |
+
|
587 |
+
|
588 |
+
cdef extern from "_blas_subroutines.h":
|
589 |
+
void _fortran_dsymv "BLAS_FUNC(dsymv)"(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
|
590 |
+
cdef void dsymv(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
|
591 |
+
|
592 |
+
_fortran_dsymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
|
593 |
+
|
594 |
+
|
595 |
+
cdef extern from "_blas_subroutines.h":
|
596 |
+
void _fortran_dsyr "BLAS_FUNC(dsyr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) nogil
|
597 |
+
cdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogil:
|
598 |
+
|
599 |
+
_fortran_dsyr(uplo, n, alpha, x, incx, a, lda)
|
600 |
+
|
601 |
+
|
602 |
+
cdef extern from "_blas_subroutines.h":
|
603 |
+
void _fortran_dsyr2 "BLAS_FUNC(dsyr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogil
|
604 |
+
cdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil:
|
605 |
+
|
606 |
+
_fortran_dsyr2(uplo, n, alpha, x, incx, y, incy, a, lda)
|
607 |
+
|
608 |
+
|
609 |
+
cdef extern from "_blas_subroutines.h":
|
610 |
+
void _fortran_dsyr2k "BLAS_FUNC(dsyr2k)"(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil
|
611 |
+
cdef void dsyr2k(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil:
|
612 |
+
|
613 |
+
_fortran_dsyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
|
614 |
+
|
615 |
+
|
616 |
+
cdef extern from "_blas_subroutines.h":
|
617 |
+
void _fortran_dsyrk "BLAS_FUNC(dsyrk)"(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) nogil
|
618 |
+
cdef void dsyrk(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) noexcept nogil:
|
619 |
+
|
620 |
+
_fortran_dsyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
|
621 |
+
|
622 |
+
|
623 |
+
cdef extern from "_blas_subroutines.h":
|
624 |
+
void _fortran_dtbmv "BLAS_FUNC(dtbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogil
|
625 |
+
cdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil:
|
626 |
+
|
627 |
+
_fortran_dtbmv(uplo, trans, diag, n, k, a, lda, x, incx)
|
628 |
+
|
629 |
+
|
630 |
+
cdef extern from "_blas_subroutines.h":
|
631 |
+
void _fortran_dtbsv "BLAS_FUNC(dtbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogil
|
632 |
+
cdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil:
|
633 |
+
|
634 |
+
_fortran_dtbsv(uplo, trans, diag, n, k, a, lda, x, incx)
|
635 |
+
|
636 |
+
|
637 |
+
cdef extern from "_blas_subroutines.h":
|
638 |
+
void _fortran_dtpmv "BLAS_FUNC(dtpmv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogil
|
639 |
+
cdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil:
|
640 |
+
|
641 |
+
_fortran_dtpmv(uplo, trans, diag, n, ap, x, incx)
|
642 |
+
|
643 |
+
|
644 |
+
cdef extern from "_blas_subroutines.h":
|
645 |
+
void _fortran_dtpsv "BLAS_FUNC(dtpsv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogil
|
646 |
+
cdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil:
|
647 |
+
|
648 |
+
_fortran_dtpsv(uplo, trans, diag, n, ap, x, incx)
|
649 |
+
|
650 |
+
|
651 |
+
cdef extern from "_blas_subroutines.h":
|
652 |
+
void _fortran_dtrmm "BLAS_FUNC(dtrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) nogil
|
653 |
+
cdef void dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil:
|
654 |
+
|
655 |
+
_fortran_dtrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
|
656 |
+
|
657 |
+
|
658 |
+
cdef extern from "_blas_subroutines.h":
|
659 |
+
void _fortran_dtrmv "BLAS_FUNC(dtrmv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogil
|
660 |
+
cdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil:
|
661 |
+
|
662 |
+
_fortran_dtrmv(uplo, trans, diag, n, a, lda, x, incx)
|
663 |
+
|
664 |
+
|
665 |
+
cdef extern from "_blas_subroutines.h":
|
666 |
+
void _fortran_dtrsm "BLAS_FUNC(dtrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) nogil
|
667 |
+
cdef void dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil:
|
668 |
+
|
669 |
+
_fortran_dtrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
|
670 |
+
|
671 |
+
|
672 |
+
cdef extern from "_blas_subroutines.h":
|
673 |
+
void _fortran_dtrsv "BLAS_FUNC(dtrsv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogil
|
674 |
+
cdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil:
|
675 |
+
|
676 |
+
_fortran_dtrsv(uplo, trans, diag, n, a, lda, x, incx)
|
677 |
+
|
678 |
+
|
679 |
+
cdef extern from "_blas_subroutines.h":
|
680 |
+
d _fortran_dzasum "BLAS_FUNC(dzasum)"(int *n, npy_complex128 *zx, int *incx) nogil
|
681 |
+
cdef d dzasum(int *n, z *zx, int *incx) noexcept nogil:
|
682 |
+
|
683 |
+
return _fortran_dzasum(n, <npy_complex128*>zx, incx)
|
684 |
+
|
685 |
+
|
686 |
+
cdef extern from "_blas_subroutines.h":
|
687 |
+
d _fortran_dznrm2 "BLAS_FUNC(dznrm2)"(int *n, npy_complex128 *x, int *incx) nogil
|
688 |
+
cdef d dznrm2(int *n, z *x, int *incx) noexcept nogil:
|
689 |
+
|
690 |
+
return _fortran_dznrm2(n, <npy_complex128*>x, incx)
|
691 |
+
|
692 |
+
|
693 |
+
cdef extern from "_blas_subroutines.h":
|
694 |
+
int _fortran_icamax "BLAS_FUNC(icamax)"(int *n, npy_complex64 *cx, int *incx) nogil
|
695 |
+
cdef int icamax(int *n, c *cx, int *incx) noexcept nogil:
|
696 |
+
|
697 |
+
return _fortran_icamax(n, <npy_complex64*>cx, incx)
|
698 |
+
|
699 |
+
|
700 |
+
cdef extern from "_blas_subroutines.h":
|
701 |
+
int _fortran_idamax "BLAS_FUNC(idamax)"(int *n, d *dx, int *incx) nogil
|
702 |
+
cdef int idamax(int *n, d *dx, int *incx) noexcept nogil:
|
703 |
+
|
704 |
+
return _fortran_idamax(n, dx, incx)
|
705 |
+
|
706 |
+
|
707 |
+
cdef extern from "_blas_subroutines.h":
|
708 |
+
int _fortran_isamax "BLAS_FUNC(isamax)"(int *n, s *sx, int *incx) nogil
|
709 |
+
cdef int isamax(int *n, s *sx, int *incx) noexcept nogil:
|
710 |
+
|
711 |
+
return _fortran_isamax(n, sx, incx)
|
712 |
+
|
713 |
+
|
714 |
+
cdef extern from "_blas_subroutines.h":
|
715 |
+
int _fortran_izamax "BLAS_FUNC(izamax)"(int *n, npy_complex128 *zx, int *incx) nogil
|
716 |
+
cdef int izamax(int *n, z *zx, int *incx) noexcept nogil:
|
717 |
+
|
718 |
+
return _fortran_izamax(n, <npy_complex128*>zx, incx)
|
719 |
+
|
720 |
+
|
721 |
+
cdef extern from "_blas_subroutines.h":
|
722 |
+
bint _fortran_lsame "BLAS_FUNC(lsame)"(char *ca, char *cb) nogil
|
723 |
+
cdef bint lsame(char *ca, char *cb) noexcept nogil:
|
724 |
+
|
725 |
+
return _fortran_lsame(ca, cb)
|
726 |
+
|
727 |
+
|
728 |
+
cdef extern from "_blas_subroutines.h":
|
729 |
+
s _fortran_sasum "BLAS_FUNC(sasum)"(int *n, s *sx, int *incx) nogil
|
730 |
+
cdef s sasum(int *n, s *sx, int *incx) noexcept nogil:
|
731 |
+
|
732 |
+
return _fortran_sasum(n, sx, incx)
|
733 |
+
|
734 |
+
|
735 |
+
cdef extern from "_blas_subroutines.h":
|
736 |
+
void _fortran_saxpy "BLAS_FUNC(saxpy)"(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) nogil
|
737 |
+
cdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
|
738 |
+
|
739 |
+
_fortran_saxpy(n, sa, sx, incx, sy, incy)
|
740 |
+
|
741 |
+
|
742 |
+
cdef extern from "_blas_subroutines.h":
|
743 |
+
s _fortran_scasum "BLAS_FUNC(scasum)"(int *n, npy_complex64 *cx, int *incx) nogil
|
744 |
+
cdef s scasum(int *n, c *cx, int *incx) noexcept nogil:
|
745 |
+
|
746 |
+
return _fortran_scasum(n, <npy_complex64*>cx, incx)
|
747 |
+
|
748 |
+
|
749 |
+
cdef extern from "_blas_subroutines.h":
|
750 |
+
s _fortran_scnrm2 "BLAS_FUNC(scnrm2)"(int *n, npy_complex64 *x, int *incx) nogil
|
751 |
+
cdef s scnrm2(int *n, c *x, int *incx) noexcept nogil:
|
752 |
+
|
753 |
+
return _fortran_scnrm2(n, <npy_complex64*>x, incx)
|
754 |
+
|
755 |
+
|
756 |
+
cdef extern from "_blas_subroutines.h":
|
757 |
+
void _fortran_scopy "BLAS_FUNC(scopy)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
|
758 |
+
cdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
|
759 |
+
|
760 |
+
_fortran_scopy(n, sx, incx, sy, incy)
|
761 |
+
|
762 |
+
|
763 |
+
cdef extern from "_blas_subroutines.h":
|
764 |
+
s _fortran_sdot "BLAS_FUNC(sdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
|
765 |
+
cdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
|
766 |
+
|
767 |
+
return _fortran_sdot(n, sx, incx, sy, incy)
|
768 |
+
|
769 |
+
|
770 |
+
cdef extern from "_blas_subroutines.h":
|
771 |
+
s _fortran_sdsdot "BLAS_FUNC(sdsdot)"(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) nogil
|
772 |
+
cdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
|
773 |
+
|
774 |
+
return _fortran_sdsdot(n, sb, sx, incx, sy, incy)
|
775 |
+
|
776 |
+
|
777 |
+
cdef extern from "_blas_subroutines.h":
|
778 |
+
void _fortran_sgbmv "BLAS_FUNC(sgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
|
779 |
+
cdef void sgbmv(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
|
780 |
+
|
781 |
+
_fortran_sgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
|
782 |
+
|
783 |
+
|
784 |
+
cdef extern from "_blas_subroutines.h":
|
785 |
+
void _fortran_sgemm "BLAS_FUNC(sgemm)"(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil
|
786 |
+
cdef void sgemm(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil:
|
787 |
+
|
788 |
+
_fortran_sgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
|
789 |
+
|
790 |
+
|
791 |
+
cdef extern from "_blas_subroutines.h":
|
792 |
+
void _fortran_sgemv "BLAS_FUNC(sgemv)"(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
|
793 |
+
cdef void sgemv(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
|
794 |
+
|
795 |
+
_fortran_sgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
|
796 |
+
|
797 |
+
|
798 |
+
cdef extern from "_blas_subroutines.h":
|
799 |
+
void _fortran_sger "BLAS_FUNC(sger)"(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogil
|
800 |
+
cdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil:
|
801 |
+
|
802 |
+
_fortran_sger(m, n, alpha, x, incx, y, incy, a, lda)
|
803 |
+
|
804 |
+
|
805 |
+
cdef extern from "_blas_subroutines.h":
|
806 |
+
s _fortran_snrm2 "BLAS_FUNC(snrm2)"(int *n, s *x, int *incx) nogil
|
807 |
+
cdef s snrm2(int *n, s *x, int *incx) noexcept nogil:
|
808 |
+
|
809 |
+
return _fortran_snrm2(n, x, incx)
|
810 |
+
|
811 |
+
|
812 |
+
cdef extern from "_blas_subroutines.h":
|
813 |
+
void _fortran_srot "BLAS_FUNC(srot)"(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) nogil
|
814 |
+
cdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogil:
|
815 |
+
|
816 |
+
_fortran_srot(n, sx, incx, sy, incy, c, s)
|
817 |
+
|
818 |
+
|
819 |
+
cdef extern from "_blas_subroutines.h":
|
820 |
+
void _fortran_srotg "BLAS_FUNC(srotg)"(s *sa, s *sb, s *c, s *s) nogil
|
821 |
+
cdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogil:
|
822 |
+
|
823 |
+
_fortran_srotg(sa, sb, c, s)
|
824 |
+
|
825 |
+
|
826 |
+
cdef extern from "_blas_subroutines.h":
|
827 |
+
void _fortran_srotm "BLAS_FUNC(srotm)"(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) nogil
|
828 |
+
cdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogil:
|
829 |
+
|
830 |
+
_fortran_srotm(n, sx, incx, sy, incy, sparam)
|
831 |
+
|
832 |
+
|
833 |
+
cdef extern from "_blas_subroutines.h":
|
834 |
+
void _fortran_srotmg "BLAS_FUNC(srotmg)"(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) nogil
|
835 |
+
cdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogil:
|
836 |
+
|
837 |
+
_fortran_srotmg(sd1, sd2, sx1, sy1, sparam)
|
838 |
+
|
839 |
+
|
840 |
+
cdef extern from "_blas_subroutines.h":
|
841 |
+
void _fortran_ssbmv "BLAS_FUNC(ssbmv)"(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
|
842 |
+
cdef void ssbmv(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
|
843 |
+
|
844 |
+
_fortran_ssbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
|
845 |
+
|
846 |
+
|
847 |
+
cdef extern from "_blas_subroutines.h":
|
848 |
+
void _fortran_sscal "BLAS_FUNC(sscal)"(int *n, s *sa, s *sx, int *incx) nogil
|
849 |
+
cdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogil:
|
850 |
+
|
851 |
+
_fortran_sscal(n, sa, sx, incx)
|
852 |
+
|
853 |
+
|
854 |
+
cdef extern from "_blas_subroutines.h":
|
855 |
+
void _fortran_sspmv "BLAS_FUNC(sspmv)"(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) nogil
|
856 |
+
cdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
|
857 |
+
|
858 |
+
_fortran_sspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
|
859 |
+
|
860 |
+
|
861 |
+
cdef extern from "_blas_subroutines.h":
|
862 |
+
void _fortran_sspr "BLAS_FUNC(sspr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) nogil
|
863 |
+
cdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogil:
|
864 |
+
|
865 |
+
_fortran_sspr(uplo, n, alpha, x, incx, ap)
|
866 |
+
|
867 |
+
|
868 |
+
cdef extern from "_blas_subroutines.h":
|
869 |
+
void _fortran_sspr2 "BLAS_FUNC(sspr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) nogil
|
870 |
+
cdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogil:
|
871 |
+
|
872 |
+
_fortran_sspr2(uplo, n, alpha, x, incx, y, incy, ap)
|
873 |
+
|
874 |
+
|
875 |
+
cdef extern from "_blas_subroutines.h":
|
876 |
+
void _fortran_sswap "BLAS_FUNC(sswap)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
|
877 |
+
cdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
|
878 |
+
|
879 |
+
_fortran_sswap(n, sx, incx, sy, incy)
|
880 |
+
|
881 |
+
|
882 |
+
cdef extern from "_blas_subroutines.h":
|
883 |
+
void _fortran_ssymm "BLAS_FUNC(ssymm)"(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil
|
884 |
+
cdef void ssymm(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil:
|
885 |
+
|
886 |
+
_fortran_ssymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
|
887 |
+
|
888 |
+
|
889 |
+
cdef extern from "_blas_subroutines.h":
|
890 |
+
void _fortran_ssymv "BLAS_FUNC(ssymv)"(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
|
891 |
+
cdef void ssymv(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
|
892 |
+
|
893 |
+
_fortran_ssymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
|
894 |
+
|
895 |
+
|
896 |
+
cdef extern from "_blas_subroutines.h":
|
897 |
+
void _fortran_ssyr "BLAS_FUNC(ssyr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) nogil
|
898 |
+
cdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogil:
|
899 |
+
|
900 |
+
_fortran_ssyr(uplo, n, alpha, x, incx, a, lda)
|
901 |
+
|
902 |
+
|
903 |
+
cdef extern from "_blas_subroutines.h":
|
904 |
+
void _fortran_ssyr2 "BLAS_FUNC(ssyr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogil
|
905 |
+
cdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil:
|
906 |
+
|
907 |
+
_fortran_ssyr2(uplo, n, alpha, x, incx, y, incy, a, lda)
|
908 |
+
|
909 |
+
|
910 |
+
cdef extern from "_blas_subroutines.h":
|
911 |
+
void _fortran_ssyr2k "BLAS_FUNC(ssyr2k)"(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil
|
912 |
+
cdef void ssyr2k(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil:
|
913 |
+
|
914 |
+
_fortran_ssyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
|
915 |
+
|
916 |
+
|
917 |
+
cdef extern from "_blas_subroutines.h":
|
918 |
+
void _fortran_ssyrk "BLAS_FUNC(ssyrk)"(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) nogil
|
919 |
+
cdef void ssyrk(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) noexcept nogil:
|
920 |
+
|
921 |
+
_fortran_ssyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
|
922 |
+
|
923 |
+
|
924 |
+
cdef extern from "_blas_subroutines.h":
|
925 |
+
void _fortran_stbmv "BLAS_FUNC(stbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogil
|
926 |
+
cdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil:
|
927 |
+
|
928 |
+
_fortran_stbmv(uplo, trans, diag, n, k, a, lda, x, incx)
|
929 |
+
|
930 |
+
|
931 |
+
cdef extern from "_blas_subroutines.h":
|
932 |
+
void _fortran_stbsv "BLAS_FUNC(stbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogil
|
933 |
+
cdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil:
|
934 |
+
|
935 |
+
_fortran_stbsv(uplo, trans, diag, n, k, a, lda, x, incx)
|
936 |
+
|
937 |
+
|
938 |
+
cdef extern from "_blas_subroutines.h":
|
939 |
+
void _fortran_stpmv "BLAS_FUNC(stpmv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogil
|
940 |
+
cdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil:
|
941 |
+
|
942 |
+
_fortran_stpmv(uplo, trans, diag, n, ap, x, incx)
|
943 |
+
|
944 |
+
|
945 |
+
cdef extern from "_blas_subroutines.h":
|
946 |
+
void _fortran_stpsv "BLAS_FUNC(stpsv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogil
|
947 |
+
cdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil:
|
948 |
+
|
949 |
+
_fortran_stpsv(uplo, trans, diag, n, ap, x, incx)
|
950 |
+
|
951 |
+
|
952 |
+
cdef extern from "_blas_subroutines.h":
|
953 |
+
void _fortran_strmm "BLAS_FUNC(strmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) nogil
|
954 |
+
cdef void strmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil:
|
955 |
+
|
956 |
+
_fortran_strmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
|
957 |
+
|
958 |
+
|
959 |
+
cdef extern from "_blas_subroutines.h":
|
960 |
+
void _fortran_strmv "BLAS_FUNC(strmv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogil
|
961 |
+
cdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil:
|
962 |
+
|
963 |
+
_fortran_strmv(uplo, trans, diag, n, a, lda, x, incx)
|
964 |
+
|
965 |
+
|
966 |
+
cdef extern from "_blas_subroutines.h":
|
967 |
+
void _fortran_strsm "BLAS_FUNC(strsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) nogil
|
968 |
+
cdef void strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil:
|
969 |
+
|
970 |
+
_fortran_strsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
|
971 |
+
|
972 |
+
|
973 |
+
cdef extern from "_blas_subroutines.h":
|
974 |
+
void _fortran_strsv "BLAS_FUNC(strsv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogil
|
975 |
+
cdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil:
|
976 |
+
|
977 |
+
_fortran_strsv(uplo, trans, diag, n, a, lda, x, incx)
|
978 |
+
|
979 |
+
|
980 |
+
cdef extern from "_blas_subroutines.h":
|
981 |
+
void _fortran_zaxpy "BLAS_FUNC(zaxpy)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
|
982 |
+
cdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
|
983 |
+
|
984 |
+
_fortran_zaxpy(n, <npy_complex128*>za, <npy_complex128*>zx, incx, <npy_complex128*>zy, incy)
|
985 |
+
|
986 |
+
|
987 |
+
cdef extern from "_blas_subroutines.h":
|
988 |
+
void _fortran_zcopy "BLAS_FUNC(zcopy)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
|
989 |
+
cdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
|
990 |
+
|
991 |
+
_fortran_zcopy(n, <npy_complex128*>zx, incx, <npy_complex128*>zy, incy)
|
992 |
+
|
993 |
+
|
994 |
+
cdef extern from "_blas_subroutines.h":
|
995 |
+
void _fortran_zdotc "(zdotcwrp_)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
|
996 |
+
cdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
|
997 |
+
cdef z out
|
998 |
+
_fortran_zdotc(<npy_complex128*>&out, n, <npy_complex128*>zx, incx, <npy_complex128*>zy, incy)
|
999 |
+
return out
|
1000 |
+
|
1001 |
+
cdef extern from "_blas_subroutines.h":
|
1002 |
+
void _fortran_zdotu "(zdotuwrp_)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
|
1003 |
+
cdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
|
1004 |
+
cdef z out
|
1005 |
+
_fortran_zdotu(<npy_complex128*>&out, n, <npy_complex128*>zx, incx, <npy_complex128*>zy, incy)
|
1006 |
+
return out
|
1007 |
+
|
1008 |
+
cdef extern from "_blas_subroutines.h":
|
1009 |
+
void _fortran_zdrot "BLAS_FUNC(zdrot)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, d *c, d *s) nogil
|
1010 |
+
cdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogil:
|
1011 |
+
|
1012 |
+
_fortran_zdrot(n, <npy_complex128*>cx, incx, <npy_complex128*>cy, incy, c, s)
|
1013 |
+
|
1014 |
+
|
1015 |
+
cdef extern from "_blas_subroutines.h":
|
1016 |
+
void _fortran_zdscal "BLAS_FUNC(zdscal)"(int *n, d *da, npy_complex128 *zx, int *incx) nogil
|
1017 |
+
cdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogil:
|
1018 |
+
|
1019 |
+
_fortran_zdscal(n, da, <npy_complex128*>zx, incx)
|
1020 |
+
|
1021 |
+
|
1022 |
+
cdef extern from "_blas_subroutines.h":
|
1023 |
+
void _fortran_zgbmv "BLAS_FUNC(zgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
|
1024 |
+
cdef void zgbmv(char *trans, int *m, int *n, int *kl, int *ku, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
|
1025 |
+
|
1026 |
+
_fortran_zgbmv(trans, m, n, kl, ku, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>x, incx, <npy_complex128*>beta, <npy_complex128*>y, incy)
|
1027 |
+
|
1028 |
+
|
1029 |
+
cdef extern from "_blas_subroutines.h":
|
1030 |
+
void _fortran_zgemm "BLAS_FUNC(zgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
|
1031 |
+
cdef void zgemm(char *transa, char *transb, int *m, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
|
1032 |
+
|
1033 |
+
_fortran_zgemm(transa, transb, m, n, k, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb, <npy_complex128*>beta, <npy_complex128*>c, ldc)
|
1034 |
+
|
1035 |
+
|
1036 |
+
cdef extern from "_blas_subroutines.h":
|
1037 |
+
void _fortran_zgemv "BLAS_FUNC(zgemv)"(char *trans, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
|
1038 |
+
cdef void zgemv(char *trans, int *m, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
|
1039 |
+
|
1040 |
+
_fortran_zgemv(trans, m, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>x, incx, <npy_complex128*>beta, <npy_complex128*>y, incy)
|
1041 |
+
|
1042 |
+
|
1043 |
+
cdef extern from "_blas_subroutines.h":
|
1044 |
+
void _fortran_zgerc "BLAS_FUNC(zgerc)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
|
1045 |
+
cdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
|
1046 |
+
|
1047 |
+
_fortran_zgerc(m, n, <npy_complex128*>alpha, <npy_complex128*>x, incx, <npy_complex128*>y, incy, <npy_complex128*>a, lda)
|
1048 |
+
|
1049 |
+
|
1050 |
+
cdef extern from "_blas_subroutines.h":
|
1051 |
+
void _fortran_zgeru "BLAS_FUNC(zgeru)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
|
1052 |
+
cdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
|
1053 |
+
|
1054 |
+
_fortran_zgeru(m, n, <npy_complex128*>alpha, <npy_complex128*>x, incx, <npy_complex128*>y, incy, <npy_complex128*>a, lda)
|
1055 |
+
|
1056 |
+
|
1057 |
+
cdef extern from "_blas_subroutines.h":
|
1058 |
+
void _fortran_zhbmv "BLAS_FUNC(zhbmv)"(char *uplo, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
|
1059 |
+
cdef void zhbmv(char *uplo, int *n, int *k, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
|
1060 |
+
|
1061 |
+
_fortran_zhbmv(uplo, n, k, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>x, incx, <npy_complex128*>beta, <npy_complex128*>y, incy)
|
1062 |
+
|
1063 |
+
|
1064 |
+
cdef extern from "_blas_subroutines.h":
|
1065 |
+
void _fortran_zhemm "BLAS_FUNC(zhemm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
|
1066 |
+
cdef void zhemm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
|
1067 |
+
|
1068 |
+
_fortran_zhemm(side, uplo, m, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb, <npy_complex128*>beta, <npy_complex128*>c, ldc)
|
1069 |
+
|
1070 |
+
|
1071 |
+
cdef extern from "_blas_subroutines.h":
|
1072 |
+
void _fortran_zhemv "BLAS_FUNC(zhemv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
|
1073 |
+
cdef void zhemv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
|
1074 |
+
|
1075 |
+
_fortran_zhemv(uplo, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>x, incx, <npy_complex128*>beta, <npy_complex128*>y, incy)
|
1076 |
+
|
1077 |
+
|
1078 |
+
cdef extern from "_blas_subroutines.h":
|
1079 |
+
void _fortran_zher "BLAS_FUNC(zher)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda) nogil
|
1080 |
+
cdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil:
|
1081 |
+
|
1082 |
+
_fortran_zher(uplo, n, alpha, <npy_complex128*>x, incx, <npy_complex128*>a, lda)
|
1083 |
+
|
1084 |
+
|
1085 |
+
cdef extern from "_blas_subroutines.h":
|
1086 |
+
void _fortran_zher2 "BLAS_FUNC(zher2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
|
1087 |
+
cdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
|
1088 |
+
|
1089 |
+
_fortran_zher2(uplo, n, <npy_complex128*>alpha, <npy_complex128*>x, incx, <npy_complex128*>y, incy, <npy_complex128*>a, lda)
|
1090 |
+
|
1091 |
+
|
1092 |
+
cdef extern from "_blas_subroutines.h":
|
1093 |
+
void _fortran_zher2k "BLAS_FUNC(zher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *beta, npy_complex128 *c, int *ldc) nogil
|
1094 |
+
cdef void zher2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, d *beta, z *c, int *ldc) noexcept nogil:
|
1095 |
+
|
1096 |
+
_fortran_zher2k(uplo, trans, n, k, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb, beta, <npy_complex128*>c, ldc)
|
1097 |
+
|
1098 |
+
|
1099 |
+
cdef extern from "_blas_subroutines.h":
|
1100 |
+
void _fortran_zherk "BLAS_FUNC(zherk)"(char *uplo, char *trans, int *n, int *k, d *alpha, npy_complex128 *a, int *lda, d *beta, npy_complex128 *c, int *ldc) nogil
|
1101 |
+
cdef void zherk(char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c, int *ldc) noexcept nogil:
|
1102 |
+
|
1103 |
+
_fortran_zherk(uplo, trans, n, k, alpha, <npy_complex128*>a, lda, beta, <npy_complex128*>c, ldc)
|
1104 |
+
|
1105 |
+
|
1106 |
+
cdef extern from "_blas_subroutines.h":
|
1107 |
+
void _fortran_zhpmv "BLAS_FUNC(zhpmv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
|
1108 |
+
cdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
|
1109 |
+
|
1110 |
+
_fortran_zhpmv(uplo, n, <npy_complex128*>alpha, <npy_complex128*>ap, <npy_complex128*>x, incx, <npy_complex128*>beta, <npy_complex128*>y, incy)
|
1111 |
+
|
1112 |
+
|
1113 |
+
cdef extern from "_blas_subroutines.h":
|
1114 |
+
void _fortran_zhpr "BLAS_FUNC(zhpr)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap) nogil
|
1115 |
+
cdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogil:
|
1116 |
+
|
1117 |
+
_fortran_zhpr(uplo, n, alpha, <npy_complex128*>x, incx, <npy_complex128*>ap)
|
1118 |
+
|
1119 |
+
|
1120 |
+
cdef extern from "_blas_subroutines.h":
|
1121 |
+
void _fortran_zhpr2 "BLAS_FUNC(zhpr2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *ap) nogil
|
1122 |
+
cdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogil:
|
1123 |
+
|
1124 |
+
_fortran_zhpr2(uplo, n, <npy_complex128*>alpha, <npy_complex128*>x, incx, <npy_complex128*>y, incy, <npy_complex128*>ap)
|
1125 |
+
|
1126 |
+
|
1127 |
+
cdef extern from "_blas_subroutines.h":
|
1128 |
+
void _fortran_zrotg "BLAS_FUNC(zrotg)"(npy_complex128 *ca, npy_complex128 *cb, d *c, npy_complex128 *s) nogil
|
1129 |
+
cdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogil:
|
1130 |
+
|
1131 |
+
_fortran_zrotg(<npy_complex128*>ca, <npy_complex128*>cb, c, <npy_complex128*>s)
|
1132 |
+
|
1133 |
+
|
1134 |
+
cdef extern from "_blas_subroutines.h":
|
1135 |
+
void _fortran_zscal "BLAS_FUNC(zscal)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx) nogil
|
1136 |
+
cdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogil:
|
1137 |
+
|
1138 |
+
_fortran_zscal(n, <npy_complex128*>za, <npy_complex128*>zx, incx)
|
1139 |
+
|
1140 |
+
|
1141 |
+
cdef extern from "_blas_subroutines.h":
|
1142 |
+
void _fortran_zswap "BLAS_FUNC(zswap)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
|
1143 |
+
cdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
|
1144 |
+
|
1145 |
+
_fortran_zswap(n, <npy_complex128*>zx, incx, <npy_complex128*>zy, incy)
|
1146 |
+
|
1147 |
+
|
1148 |
+
cdef extern from "_blas_subroutines.h":
|
1149 |
+
void _fortran_zsymm "BLAS_FUNC(zsymm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
|
1150 |
+
cdef void zsymm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
|
1151 |
+
|
1152 |
+
_fortran_zsymm(side, uplo, m, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb, <npy_complex128*>beta, <npy_complex128*>c, ldc)
|
1153 |
+
|
1154 |
+
|
1155 |
+
cdef extern from "_blas_subroutines.h":
|
1156 |
+
void _fortran_zsyr2k "BLAS_FUNC(zsyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
|
1157 |
+
cdef void zsyr2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
|
1158 |
+
|
1159 |
+
_fortran_zsyr2k(uplo, trans, n, k, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb, <npy_complex128*>beta, <npy_complex128*>c, ldc)
|
1160 |
+
|
1161 |
+
|
1162 |
+
cdef extern from "_blas_subroutines.h":
|
1163 |
+
void _fortran_zsyrk "BLAS_FUNC(zsyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
|
1164 |
+
cdef void zsyrk(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *beta, z *c, int *ldc) noexcept nogil:
|
1165 |
+
|
1166 |
+
_fortran_zsyrk(uplo, trans, n, k, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>beta, <npy_complex128*>c, ldc)
|
1167 |
+
|
1168 |
+
|
1169 |
+
cdef extern from "_blas_subroutines.h":
|
1170 |
+
void _fortran_ztbmv "BLAS_FUNC(ztbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
|
1171 |
+
cdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil:
|
1172 |
+
|
1173 |
+
_fortran_ztbmv(uplo, trans, diag, n, k, <npy_complex128*>a, lda, <npy_complex128*>x, incx)
|
1174 |
+
|
1175 |
+
|
1176 |
+
cdef extern from "_blas_subroutines.h":
|
1177 |
+
void _fortran_ztbsv "BLAS_FUNC(ztbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
|
1178 |
+
cdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil:
|
1179 |
+
|
1180 |
+
_fortran_ztbsv(uplo, trans, diag, n, k, <npy_complex128*>a, lda, <npy_complex128*>x, incx)
|
1181 |
+
|
1182 |
+
|
1183 |
+
cdef extern from "_blas_subroutines.h":
|
1184 |
+
void _fortran_ztpmv "BLAS_FUNC(ztpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogil
|
1185 |
+
cdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil:
|
1186 |
+
|
1187 |
+
_fortran_ztpmv(uplo, trans, diag, n, <npy_complex128*>ap, <npy_complex128*>x, incx)
|
1188 |
+
|
1189 |
+
|
1190 |
+
cdef extern from "_blas_subroutines.h":
|
1191 |
+
void _fortran_ztpsv "BLAS_FUNC(ztpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogil
|
1192 |
+
cdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil:
|
1193 |
+
|
1194 |
+
_fortran_ztpsv(uplo, trans, diag, n, <npy_complex128*>ap, <npy_complex128*>x, incx)
|
1195 |
+
|
1196 |
+
|
1197 |
+
cdef extern from "_blas_subroutines.h":
|
1198 |
+
void _fortran_ztrmm "BLAS_FUNC(ztrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil
|
1199 |
+
cdef void ztrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil:
|
1200 |
+
|
1201 |
+
_fortran_ztrmm(side, uplo, transa, diag, m, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb)
|
1202 |
+
|
1203 |
+
|
1204 |
+
cdef extern from "_blas_subroutines.h":
|
1205 |
+
void _fortran_ztrmv "BLAS_FUNC(ztrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
|
1206 |
+
cdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil:
|
1207 |
+
|
1208 |
+
_fortran_ztrmv(uplo, trans, diag, n, <npy_complex128*>a, lda, <npy_complex128*>x, incx)
|
1209 |
+
|
1210 |
+
|
1211 |
+
cdef extern from "_blas_subroutines.h":
|
1212 |
+
void _fortran_ztrsm "BLAS_FUNC(ztrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil
|
1213 |
+
cdef void ztrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil:
|
1214 |
+
|
1215 |
+
_fortran_ztrsm(side, uplo, transa, diag, m, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb)
|
1216 |
+
|
1217 |
+
|
1218 |
+
cdef extern from "_blas_subroutines.h":
|
1219 |
+
void _fortran_ztrsv "BLAS_FUNC(ztrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
|
1220 |
+
cdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil:
|
1221 |
+
|
1222 |
+
_fortran_ztrsv(uplo, trans, diag, n, <npy_complex128*>a, lda, <npy_complex128*>x, incx)
|
1223 |
+
|
1224 |
+
|
1225 |
+
|
1226 |
+
# Python-accessible wrappers for testing:
|
1227 |
+
|
1228 |
+
cdef inline bint _is_contiguous(double[:,:] a, int axis) noexcept nogil:
|
1229 |
+
return (a.strides[axis] == sizeof(a[0,0]) or a.shape[axis] == 1)
|
1230 |
+
|
1231 |
+
cpdef float complex _test_cdotc(float complex[:] cx, float complex[:] cy) noexcept nogil:
|
1232 |
+
cdef:
|
1233 |
+
int n = cx.shape[0]
|
1234 |
+
int incx = cx.strides[0] // sizeof(cx[0])
|
1235 |
+
int incy = cy.strides[0] // sizeof(cy[0])
|
1236 |
+
return cdotc(&n, &cx[0], &incx, &cy[0], &incy)
|
1237 |
+
|
1238 |
+
cpdef float complex _test_cdotu(float complex[:] cx, float complex[:] cy) noexcept nogil:
|
1239 |
+
cdef:
|
1240 |
+
int n = cx.shape[0]
|
1241 |
+
int incx = cx.strides[0] // sizeof(cx[0])
|
1242 |
+
int incy = cy.strides[0] // sizeof(cy[0])
|
1243 |
+
return cdotu(&n, &cx[0], &incx, &cy[0], &incy)
|
1244 |
+
|
1245 |
+
cpdef double _test_dasum(double[:] dx) noexcept nogil:
|
1246 |
+
cdef:
|
1247 |
+
int n = dx.shape[0]
|
1248 |
+
int incx = dx.strides[0] // sizeof(dx[0])
|
1249 |
+
return dasum(&n, &dx[0], &incx)
|
1250 |
+
|
1251 |
+
cpdef double _test_ddot(double[:] dx, double[:] dy) noexcept nogil:
|
1252 |
+
cdef:
|
1253 |
+
int n = dx.shape[0]
|
1254 |
+
int incx = dx.strides[0] // sizeof(dx[0])
|
1255 |
+
int incy = dy.strides[0] // sizeof(dy[0])
|
1256 |
+
return ddot(&n, &dx[0], &incx, &dy[0], &incy)
|
1257 |
+
|
1258 |
+
cpdef int _test_dgemm(double alpha, double[:,:] a, double[:,:] b, double beta,
|
1259 |
+
double[:,:] c) except -1 nogil:
|
1260 |
+
cdef:
|
1261 |
+
char *transa
|
1262 |
+
char *transb
|
1263 |
+
int m, n, k, lda, ldb, ldc
|
1264 |
+
double *a0=&a[0,0]
|
1265 |
+
double *b0=&b[0,0]
|
1266 |
+
double *c0=&c[0,0]
|
1267 |
+
# In the case that c is C contiguous, swap a and b and
|
1268 |
+
# swap whether or not each of them is transposed.
|
1269 |
+
# This can be done because a.dot(b) = b.T.dot(a.T).T.
|
1270 |
+
if _is_contiguous(c, 1):
|
1271 |
+
if _is_contiguous(a, 1):
|
1272 |
+
transb = 'n'
|
1273 |
+
ldb = (&a[1,0]) - a0 if a.shape[0] > 1 else 1
|
1274 |
+
elif _is_contiguous(a, 0):
|
1275 |
+
transb = 't'
|
1276 |
+
ldb = (&a[0,1]) - a0 if a.shape[1] > 1 else 1
|
1277 |
+
else:
|
1278 |
+
with gil:
|
1279 |
+
raise ValueError("Input 'a' is neither C nor Fortran contiguous.")
|
1280 |
+
if _is_contiguous(b, 1):
|
1281 |
+
transa = 'n'
|
1282 |
+
lda = (&b[1,0]) - b0 if b.shape[0] > 1 else 1
|
1283 |
+
elif _is_contiguous(b, 0):
|
1284 |
+
transa = 't'
|
1285 |
+
lda = (&b[0,1]) - b0 if b.shape[1] > 1 else 1
|
1286 |
+
else:
|
1287 |
+
with gil:
|
1288 |
+
raise ValueError("Input 'b' is neither C nor Fortran contiguous.")
|
1289 |
+
k = b.shape[0]
|
1290 |
+
if k != a.shape[1]:
|
1291 |
+
with gil:
|
1292 |
+
raise ValueError("Shape mismatch in input arrays.")
|
1293 |
+
m = b.shape[1]
|
1294 |
+
n = a.shape[0]
|
1295 |
+
if n != c.shape[0] or m != c.shape[1]:
|
1296 |
+
with gil:
|
1297 |
+
raise ValueError("Output array does not have the correct shape.")
|
1298 |
+
ldc = (&c[1,0]) - c0 if c.shape[0] > 1 else 1
|
1299 |
+
dgemm(transa, transb, &m, &n, &k, &alpha, b0, &lda, a0,
|
1300 |
+
&ldb, &beta, c0, &ldc)
|
1301 |
+
elif _is_contiguous(c, 0):
|
1302 |
+
if _is_contiguous(a, 1):
|
1303 |
+
transa = 't'
|
1304 |
+
lda = (&a[1,0]) - a0 if a.shape[0] > 1 else 1
|
1305 |
+
elif _is_contiguous(a, 0):
|
1306 |
+
transa = 'n'
|
1307 |
+
lda = (&a[0,1]) - a0 if a.shape[1] > 1 else 1
|
1308 |
+
else:
|
1309 |
+
with gil:
|
1310 |
+
raise ValueError("Input 'a' is neither C nor Fortran contiguous.")
|
1311 |
+
if _is_contiguous(b, 1):
|
1312 |
+
transb = 't'
|
1313 |
+
ldb = (&b[1,0]) - b0 if b.shape[0] > 1 else 1
|
1314 |
+
elif _is_contiguous(b, 0):
|
1315 |
+
transb = 'n'
|
1316 |
+
ldb = (&b[0,1]) - b0 if b.shape[1] > 1 else 1
|
1317 |
+
else:
|
1318 |
+
with gil:
|
1319 |
+
raise ValueError("Input 'b' is neither C nor Fortran contiguous.")
|
1320 |
+
m = a.shape[0]
|
1321 |
+
k = a.shape[1]
|
1322 |
+
if k != b.shape[0]:
|
1323 |
+
with gil:
|
1324 |
+
raise ValueError("Shape mismatch in input arrays.")
|
1325 |
+
n = b.shape[1]
|
1326 |
+
if m != c.shape[0] or n != c.shape[1]:
|
1327 |
+
with gil:
|
1328 |
+
raise ValueError("Output array does not have the correct shape.")
|
1329 |
+
ldc = (&c[0,1]) - c0 if c.shape[1] > 1 else 1
|
1330 |
+
dgemm(transa, transb, &m, &n, &k, &alpha, a0, &lda, b0,
|
1331 |
+
&ldb, &beta, c0, &ldc)
|
1332 |
+
else:
|
1333 |
+
with gil:
|
1334 |
+
raise ValueError("Input 'c' is neither C nor Fortran contiguous.")
|
1335 |
+
return 0
|
1336 |
+
|
1337 |
+
cpdef double _test_dnrm2(double[:] x) noexcept nogil:
|
1338 |
+
cdef:
|
1339 |
+
int n = x.shape[0]
|
1340 |
+
int incx = x.strides[0] // sizeof(x[0])
|
1341 |
+
return dnrm2(&n, &x[0], &incx)
|
1342 |
+
|
1343 |
+
cpdef double _test_dzasum(double complex[:] zx) noexcept nogil:
|
1344 |
+
cdef:
|
1345 |
+
int n = zx.shape[0]
|
1346 |
+
int incx = zx.strides[0] // sizeof(zx[0])
|
1347 |
+
return dzasum(&n, &zx[0], &incx)
|
1348 |
+
|
1349 |
+
cpdef double _test_dznrm2(double complex[:] x) noexcept nogil:
|
1350 |
+
cdef:
|
1351 |
+
int n = x.shape[0]
|
1352 |
+
int incx = x.strides[0] // sizeof(x[0])
|
1353 |
+
return dznrm2(&n, &x[0], &incx)
|
1354 |
+
|
1355 |
+
cpdef int _test_icamax(float complex[:] cx) noexcept nogil:
|
1356 |
+
cdef:
|
1357 |
+
int n = cx.shape[0]
|
1358 |
+
int incx = cx.strides[0] // sizeof(cx[0])
|
1359 |
+
return icamax(&n, &cx[0], &incx)
|
1360 |
+
|
1361 |
+
cpdef int _test_idamax(double[:] dx) noexcept nogil:
|
1362 |
+
cdef:
|
1363 |
+
int n = dx.shape[0]
|
1364 |
+
int incx = dx.strides[0] // sizeof(dx[0])
|
1365 |
+
return idamax(&n, &dx[0], &incx)
|
1366 |
+
|
1367 |
+
cpdef int _test_isamax(float[:] sx) noexcept nogil:
|
1368 |
+
cdef:
|
1369 |
+
int n = sx.shape[0]
|
1370 |
+
int incx = sx.strides[0] // sizeof(sx[0])
|
1371 |
+
return isamax(&n, &sx[0], &incx)
|
1372 |
+
|
1373 |
+
cpdef int _test_izamax(double complex[:] zx) noexcept nogil:
|
1374 |
+
cdef:
|
1375 |
+
int n = zx.shape[0]
|
1376 |
+
int incx = zx.strides[0] // sizeof(zx[0])
|
1377 |
+
return izamax(&n, &zx[0], &incx)
|
1378 |
+
|
1379 |
+
cpdef float _test_sasum(float[:] sx) noexcept nogil:
|
1380 |
+
cdef:
|
1381 |
+
int n = sx.shape[0]
|
1382 |
+
int incx = sx.strides[0] // sizeof(sx[0])
|
1383 |
+
return sasum(&n, &sx[0], &incx)
|
1384 |
+
|
1385 |
+
cpdef float _test_scasum(float complex[:] cx) noexcept nogil:
|
1386 |
+
cdef:
|
1387 |
+
int n = cx.shape[0]
|
1388 |
+
int incx = cx.strides[0] // sizeof(cx[0])
|
1389 |
+
return scasum(&n, &cx[0], &incx)
|
1390 |
+
|
1391 |
+
cpdef float _test_scnrm2(float complex[:] x) noexcept nogil:
|
1392 |
+
cdef:
|
1393 |
+
int n = x.shape[0]
|
1394 |
+
int incx = x.strides[0] // sizeof(x[0])
|
1395 |
+
return scnrm2(&n, &x[0], &incx)
|
1396 |
+
|
1397 |
+
cpdef float _test_sdot(float[:] sx, float[:] sy) noexcept nogil:
|
1398 |
+
cdef:
|
1399 |
+
int n = sx.shape[0]
|
1400 |
+
int incx = sx.strides[0] // sizeof(sx[0])
|
1401 |
+
int incy = sy.strides[0] // sizeof(sy[0])
|
1402 |
+
return sdot(&n, &sx[0], &incx, &sy[0], &incy)
|
1403 |
+
|
1404 |
+
cpdef float _test_snrm2(float[:] x) noexcept nogil:
|
1405 |
+
cdef:
|
1406 |
+
int n = x.shape[0]
|
1407 |
+
int incx = x.strides[0] // sizeof(x[0])
|
1408 |
+
return snrm2(&n, &x[0], &incx)
|
1409 |
+
|
1410 |
+
cpdef double complex _test_zdotc(double complex[:] zx, double complex[:] zy) noexcept nogil:
|
1411 |
+
cdef:
|
1412 |
+
int n = zx.shape[0]
|
1413 |
+
int incx = zx.strides[0] // sizeof(zx[0])
|
1414 |
+
int incy = zy.strides[0] // sizeof(zy[0])
|
1415 |
+
return zdotc(&n, &zx[0], &incx, &zy[0], &incy)
|
1416 |
+
|
1417 |
+
cpdef double complex _test_zdotu(double complex[:] zx, double complex[:] zy) noexcept nogil:
|
1418 |
+
cdef:
|
1419 |
+
int n = zx.shape[0]
|
1420 |
+
int incx = zx.strides[0] // sizeof(zx[0])
|
1421 |
+
int incy = zy.strides[0] // sizeof(zy[0])
|
1422 |
+
return zdotu(&n, &zx[0], &incx, &zy[0], &incy)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp.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.linalg` 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 |
+
'eig', 'eigvals', 'eigh', 'eigvalsh',
|
10 |
+
'eig_banded', 'eigvals_banded',
|
11 |
+
'eigh_tridiagonal', 'eigvalsh_tridiagonal', 'hessenberg', 'cdf2rdf',
|
12 |
+
'array', 'isfinite', 'inexact', 'nonzero', 'iscomplexobj',
|
13 |
+
'flatnonzero', 'argsort', 'iscomplex', 'einsum', 'eye', 'inf',
|
14 |
+
'LinAlgError', 'norm', 'get_lapack_funcs'
|
15 |
+
]
|
16 |
+
|
17 |
+
|
18 |
+
def __dir__():
|
19 |
+
return __all__
|
20 |
+
|
21 |
+
|
22 |
+
def __getattr__(name):
|
23 |
+
return _sub_module_deprecation(sub_package="linalg", module="decomp",
|
24 |
+
private_modules=["_decomp"], all=__all__,
|
25 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.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.linalg` 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 |
+
'cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded',
|
10 |
+
'cho_solve_banded', 'asarray_chkfinite', 'atleast_2d',
|
11 |
+
'LinAlgError', 'get_lapack_funcs'
|
12 |
+
]
|
13 |
+
|
14 |
+
|
15 |
+
def __dir__():
|
16 |
+
return __all__
|
17 |
+
|
18 |
+
|
19 |
+
def __getattr__(name):
|
20 |
+
return _sub_module_deprecation(sub_package="linalg", module="decomp_cholesky",
|
21 |
+
private_modules=["_decomp_cholesky"], all=__all__,
|
22 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
2 |
+
# Use the `scipy.linalg` 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 |
+
'qr', 'qr_multiply', 'rq', 'get_lapack_funcs', 'safecall'
|
10 |
+
]
|
11 |
+
|
12 |
+
|
13 |
+
def __dir__():
|
14 |
+
return __all__
|
15 |
+
|
16 |
+
|
17 |
+
def __getattr__(name):
|
18 |
+
return _sub_module_deprecation(sub_package="linalg", module="decomp_qr",
|
19 |
+
private_modules=["_decomp_qr"], all=__all__,
|
20 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp_schur.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.linalg` 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 |
+
'schur', 'rsf2csf', 'asarray_chkfinite', 'single', 'array', 'norm',
|
10 |
+
'LinAlgError', 'get_lapack_funcs', 'eigvals', 'eps', 'feps'
|
11 |
+
]
|
12 |
+
|
13 |
+
|
14 |
+
def __dir__():
|
15 |
+
return __all__
|
16 |
+
|
17 |
+
|
18 |
+
def __getattr__(name):
|
19 |
+
return _sub_module_deprecation(sub_package="linalg", module="decomp_schur",
|
20 |
+
private_modules=["_decomp_schur"], all=__all__,
|
21 |
+
attribute=name)
|
22 |
+
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/interpolative.py
ADDED
@@ -0,0 +1,1015 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#******************************************************************************
|
2 |
+
# Copyright (C) 2013 Kenneth L. Ho
|
3 |
+
#
|
4 |
+
# Redistribution and use in source and binary forms, with or without
|
5 |
+
# modification, are permitted provided that the following conditions are met:
|
6 |
+
#
|
7 |
+
# Redistributions of source code must retain the above copyright notice, this
|
8 |
+
# list of conditions and the following disclaimer. Redistributions in binary
|
9 |
+
# form must reproduce the above copyright notice, this list of conditions and
|
10 |
+
# the following disclaimer in the documentation and/or other materials
|
11 |
+
# provided with the distribution.
|
12 |
+
#
|
13 |
+
# None of the names of the copyright holders may be used to endorse or
|
14 |
+
# promote products derived from this software without specific prior written
|
15 |
+
# permission.
|
16 |
+
#
|
17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
18 |
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
19 |
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
20 |
+
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
21 |
+
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
22 |
+
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
23 |
+
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
24 |
+
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
25 |
+
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
26 |
+
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
+
#******************************************************************************
|
29 |
+
|
30 |
+
# Python module for interfacing with `id_dist`.
|
31 |
+
|
32 |
+
r"""
|
33 |
+
======================================================================
|
34 |
+
Interpolative matrix decomposition (:mod:`scipy.linalg.interpolative`)
|
35 |
+
======================================================================
|
36 |
+
|
37 |
+
.. moduleauthor:: Kenneth L. Ho <[email protected]>
|
38 |
+
|
39 |
+
.. versionadded:: 0.13
|
40 |
+
|
41 |
+
.. currentmodule:: scipy.linalg.interpolative
|
42 |
+
|
43 |
+
An interpolative decomposition (ID) of a matrix :math:`A \in
|
44 |
+
\mathbb{C}^{m \times n}` of rank :math:`k \leq \min \{ m, n \}` is a
|
45 |
+
factorization
|
46 |
+
|
47 |
+
.. math::
|
48 |
+
A \Pi =
|
49 |
+
\begin{bmatrix}
|
50 |
+
A \Pi_{1} & A \Pi_{2}
|
51 |
+
\end{bmatrix} =
|
52 |
+
A \Pi_{1}
|
53 |
+
\begin{bmatrix}
|
54 |
+
I & T
|
55 |
+
\end{bmatrix},
|
56 |
+
|
57 |
+
where :math:`\Pi = [\Pi_{1}, \Pi_{2}]` is a permutation matrix with
|
58 |
+
:math:`\Pi_{1} \in \{ 0, 1 \}^{n \times k}`, i.e., :math:`A \Pi_{2} =
|
59 |
+
A \Pi_{1} T`. This can equivalently be written as :math:`A = BP`,
|
60 |
+
where :math:`B = A \Pi_{1}` and :math:`P = [I, T] \Pi^{\mathsf{T}}`
|
61 |
+
are the *skeleton* and *interpolation matrices*, respectively.
|
62 |
+
|
63 |
+
If :math:`A` does not have exact rank :math:`k`, then there exists an
|
64 |
+
approximation in the form of an ID such that :math:`A = BP + E`, where
|
65 |
+
:math:`\| E \| \sim \sigma_{k + 1}` is on the order of the :math:`(k +
|
66 |
+
1)`-th largest singular value of :math:`A`. Note that :math:`\sigma_{k
|
67 |
+
+ 1}` is the best possible error for a rank-:math:`k` approximation
|
68 |
+
and, in fact, is achieved by the singular value decomposition (SVD)
|
69 |
+
:math:`A \approx U S V^{*}`, where :math:`U \in \mathbb{C}^{m \times
|
70 |
+
k}` and :math:`V \in \mathbb{C}^{n \times k}` have orthonormal columns
|
71 |
+
and :math:`S = \mathop{\mathrm{diag}} (\sigma_{i}) \in \mathbb{C}^{k
|
72 |
+
\times k}` is diagonal with nonnegative entries. The principal
|
73 |
+
advantages of using an ID over an SVD are that:
|
74 |
+
|
75 |
+
- it is cheaper to construct;
|
76 |
+
- it preserves the structure of :math:`A`; and
|
77 |
+
- it is more efficient to compute with in light of the identity submatrix of :math:`P`.
|
78 |
+
|
79 |
+
Routines
|
80 |
+
========
|
81 |
+
|
82 |
+
Main functionality:
|
83 |
+
|
84 |
+
.. autosummary::
|
85 |
+
:toctree: generated/
|
86 |
+
|
87 |
+
interp_decomp
|
88 |
+
reconstruct_matrix_from_id
|
89 |
+
reconstruct_interp_matrix
|
90 |
+
reconstruct_skel_matrix
|
91 |
+
id_to_svd
|
92 |
+
svd
|
93 |
+
estimate_spectral_norm
|
94 |
+
estimate_spectral_norm_diff
|
95 |
+
estimate_rank
|
96 |
+
|
97 |
+
Support functions:
|
98 |
+
|
99 |
+
.. autosummary::
|
100 |
+
:toctree: generated/
|
101 |
+
|
102 |
+
seed
|
103 |
+
rand
|
104 |
+
|
105 |
+
|
106 |
+
References
|
107 |
+
==========
|
108 |
+
|
109 |
+
This module uses the ID software package [1]_ by Martinsson, Rokhlin,
|
110 |
+
Shkolnisky, and Tygert, which is a Fortran library for computing IDs
|
111 |
+
using various algorithms, including the rank-revealing QR approach of
|
112 |
+
[2]_ and the more recent randomized methods described in [3]_, [4]_,
|
113 |
+
and [5]_. This module exposes its functionality in a way convenient
|
114 |
+
for Python users. Note that this module does not add any functionality
|
115 |
+
beyond that of organizing a simpler and more consistent interface.
|
116 |
+
|
117 |
+
We advise the user to consult also the `documentation for the ID package
|
118 |
+
<http://tygert.com/id_doc.4.pdf>`_.
|
119 |
+
|
120 |
+
.. [1] P.G. Martinsson, V. Rokhlin, Y. Shkolnisky, M. Tygert. "ID: a
|
121 |
+
software package for low-rank approximation of matrices via interpolative
|
122 |
+
decompositions, version 0.2." http://tygert.com/id_doc.4.pdf.
|
123 |
+
|
124 |
+
.. [2] H. Cheng, Z. Gimbutas, P.G. Martinsson, V. Rokhlin. "On the
|
125 |
+
compression of low rank matrices." *SIAM J. Sci. Comput.* 26 (4): 1389--1404,
|
126 |
+
2005. :doi:`10.1137/030602678`.
|
127 |
+
|
128 |
+
.. [3] E. Liberty, F. Woolfe, P.G. Martinsson, V. Rokhlin, M.
|
129 |
+
Tygert. "Randomized algorithms for the low-rank approximation of matrices."
|
130 |
+
*Proc. Natl. Acad. Sci. U.S.A.* 104 (51): 20167--20172, 2007.
|
131 |
+
:doi:`10.1073/pnas.0709640104`.
|
132 |
+
|
133 |
+
.. [4] P.G. Martinsson, V. Rokhlin, M. Tygert. "A randomized
|
134 |
+
algorithm for the decomposition of matrices." *Appl. Comput. Harmon. Anal.* 30
|
135 |
+
(1): 47--68, 2011. :doi:`10.1016/j.acha.2010.02.003`.
|
136 |
+
|
137 |
+
.. [5] F. Woolfe, E. Liberty, V. Rokhlin, M. Tygert. "A fast
|
138 |
+
randomized algorithm for the approximation of matrices." *Appl. Comput.
|
139 |
+
Harmon. Anal.* 25 (3): 335--366, 2008. :doi:`10.1016/j.acha.2007.12.002`.
|
140 |
+
|
141 |
+
|
142 |
+
Tutorial
|
143 |
+
========
|
144 |
+
|
145 |
+
Initializing
|
146 |
+
------------
|
147 |
+
|
148 |
+
The first step is to import :mod:`scipy.linalg.interpolative` by issuing the
|
149 |
+
command:
|
150 |
+
|
151 |
+
>>> import scipy.linalg.interpolative as sli
|
152 |
+
|
153 |
+
Now let's build a matrix. For this, we consider a Hilbert matrix, which is well
|
154 |
+
know to have low rank:
|
155 |
+
|
156 |
+
>>> from scipy.linalg import hilbert
|
157 |
+
>>> n = 1000
|
158 |
+
>>> A = hilbert(n)
|
159 |
+
|
160 |
+
We can also do this explicitly via:
|
161 |
+
|
162 |
+
>>> import numpy as np
|
163 |
+
>>> n = 1000
|
164 |
+
>>> A = np.empty((n, n), order='F')
|
165 |
+
>>> for j in range(n):
|
166 |
+
... for i in range(n):
|
167 |
+
... A[i,j] = 1. / (i + j + 1)
|
168 |
+
|
169 |
+
Note the use of the flag ``order='F'`` in :func:`numpy.empty`. This
|
170 |
+
instantiates the matrix in Fortran-contiguous order and is important for
|
171 |
+
avoiding data copying when passing to the backend.
|
172 |
+
|
173 |
+
We then define multiplication routines for the matrix by regarding it as a
|
174 |
+
:class:`scipy.sparse.linalg.LinearOperator`:
|
175 |
+
|
176 |
+
>>> from scipy.sparse.linalg import aslinearoperator
|
177 |
+
>>> L = aslinearoperator(A)
|
178 |
+
|
179 |
+
This automatically sets up methods describing the action of the matrix and its
|
180 |
+
adjoint on a vector.
|
181 |
+
|
182 |
+
Computing an ID
|
183 |
+
---------------
|
184 |
+
|
185 |
+
We have several choices of algorithm to compute an ID. These fall largely
|
186 |
+
according to two dichotomies:
|
187 |
+
|
188 |
+
1. how the matrix is represented, i.e., via its entries or via its action on a
|
189 |
+
vector; and
|
190 |
+
2. whether to approximate it to a fixed relative precision or to a fixed rank.
|
191 |
+
|
192 |
+
We step through each choice in turn below.
|
193 |
+
|
194 |
+
In all cases, the ID is represented by three parameters:
|
195 |
+
|
196 |
+
1. a rank ``k``;
|
197 |
+
2. an index array ``idx``; and
|
198 |
+
3. interpolation coefficients ``proj``.
|
199 |
+
|
200 |
+
The ID is specified by the relation
|
201 |
+
``np.dot(A[:,idx[:k]], proj) == A[:,idx[k:]]``.
|
202 |
+
|
203 |
+
From matrix entries
|
204 |
+
...................
|
205 |
+
|
206 |
+
We first consider a matrix given in terms of its entries.
|
207 |
+
|
208 |
+
To compute an ID to a fixed precision, type:
|
209 |
+
|
210 |
+
>>> eps = 1e-3
|
211 |
+
>>> k, idx, proj = sli.interp_decomp(A, eps)
|
212 |
+
|
213 |
+
where ``eps < 1`` is the desired precision.
|
214 |
+
|
215 |
+
To compute an ID to a fixed rank, use:
|
216 |
+
|
217 |
+
>>> idx, proj = sli.interp_decomp(A, k)
|
218 |
+
|
219 |
+
where ``k >= 1`` is the desired rank.
|
220 |
+
|
221 |
+
Both algorithms use random sampling and are usually faster than the
|
222 |
+
corresponding older, deterministic algorithms, which can be accessed via the
|
223 |
+
commands:
|
224 |
+
|
225 |
+
>>> k, idx, proj = sli.interp_decomp(A, eps, rand=False)
|
226 |
+
|
227 |
+
and:
|
228 |
+
|
229 |
+
>>> idx, proj = sli.interp_decomp(A, k, rand=False)
|
230 |
+
|
231 |
+
respectively.
|
232 |
+
|
233 |
+
From matrix action
|
234 |
+
..................
|
235 |
+
|
236 |
+
Now consider a matrix given in terms of its action on a vector as a
|
237 |
+
:class:`scipy.sparse.linalg.LinearOperator`.
|
238 |
+
|
239 |
+
To compute an ID to a fixed precision, type:
|
240 |
+
|
241 |
+
>>> k, idx, proj = sli.interp_decomp(L, eps)
|
242 |
+
|
243 |
+
To compute an ID to a fixed rank, use:
|
244 |
+
|
245 |
+
>>> idx, proj = sli.interp_decomp(L, k)
|
246 |
+
|
247 |
+
These algorithms are randomized.
|
248 |
+
|
249 |
+
Reconstructing an ID
|
250 |
+
--------------------
|
251 |
+
|
252 |
+
The ID routines above do not output the skeleton and interpolation matrices
|
253 |
+
explicitly but instead return the relevant information in a more compact (and
|
254 |
+
sometimes more useful) form. To build these matrices, write:
|
255 |
+
|
256 |
+
>>> B = sli.reconstruct_skel_matrix(A, k, idx)
|
257 |
+
|
258 |
+
for the skeleton matrix and:
|
259 |
+
|
260 |
+
>>> P = sli.reconstruct_interp_matrix(idx, proj)
|
261 |
+
|
262 |
+
for the interpolation matrix. The ID approximation can then be computed as:
|
263 |
+
|
264 |
+
>>> C = np.dot(B, P)
|
265 |
+
|
266 |
+
This can also be constructed directly using:
|
267 |
+
|
268 |
+
>>> C = sli.reconstruct_matrix_from_id(B, idx, proj)
|
269 |
+
|
270 |
+
without having to first compute ``P``.
|
271 |
+
|
272 |
+
Alternatively, this can be done explicitly as well using:
|
273 |
+
|
274 |
+
>>> B = A[:,idx[:k]]
|
275 |
+
>>> P = np.hstack([np.eye(k), proj])[:,np.argsort(idx)]
|
276 |
+
>>> C = np.dot(B, P)
|
277 |
+
|
278 |
+
Computing an SVD
|
279 |
+
----------------
|
280 |
+
|
281 |
+
An ID can be converted to an SVD via the command:
|
282 |
+
|
283 |
+
>>> U, S, V = sli.id_to_svd(B, idx, proj)
|
284 |
+
|
285 |
+
The SVD approximation is then:
|
286 |
+
|
287 |
+
>>> approx = U @ np.diag(S) @ V.conj().T
|
288 |
+
|
289 |
+
The SVD can also be computed "fresh" by combining both the ID and conversion
|
290 |
+
steps into one command. Following the various ID algorithms above, there are
|
291 |
+
correspondingly various SVD algorithms that one can employ.
|
292 |
+
|
293 |
+
From matrix entries
|
294 |
+
...................
|
295 |
+
|
296 |
+
We consider first SVD algorithms for a matrix given in terms of its entries.
|
297 |
+
|
298 |
+
To compute an SVD to a fixed precision, type:
|
299 |
+
|
300 |
+
>>> U, S, V = sli.svd(A, eps)
|
301 |
+
|
302 |
+
To compute an SVD to a fixed rank, use:
|
303 |
+
|
304 |
+
>>> U, S, V = sli.svd(A, k)
|
305 |
+
|
306 |
+
Both algorithms use random sampling; for the deterministic versions, issue the
|
307 |
+
keyword ``rand=False`` as above.
|
308 |
+
|
309 |
+
From matrix action
|
310 |
+
..................
|
311 |
+
|
312 |
+
Now consider a matrix given in terms of its action on a vector.
|
313 |
+
|
314 |
+
To compute an SVD to a fixed precision, type:
|
315 |
+
|
316 |
+
>>> U, S, V = sli.svd(L, eps)
|
317 |
+
|
318 |
+
To compute an SVD to a fixed rank, use:
|
319 |
+
|
320 |
+
>>> U, S, V = sli.svd(L, k)
|
321 |
+
|
322 |
+
Utility routines
|
323 |
+
----------------
|
324 |
+
|
325 |
+
Several utility routines are also available.
|
326 |
+
|
327 |
+
To estimate the spectral norm of a matrix, use:
|
328 |
+
|
329 |
+
>>> snorm = sli.estimate_spectral_norm(A)
|
330 |
+
|
331 |
+
This algorithm is based on the randomized power method and thus requires only
|
332 |
+
matrix-vector products. The number of iterations to take can be set using the
|
333 |
+
keyword ``its`` (default: ``its=20``). The matrix is interpreted as a
|
334 |
+
:class:`scipy.sparse.linalg.LinearOperator`, but it is also valid to supply it
|
335 |
+
as a :class:`numpy.ndarray`, in which case it is trivially converted using
|
336 |
+
:func:`scipy.sparse.linalg.aslinearoperator`.
|
337 |
+
|
338 |
+
The same algorithm can also estimate the spectral norm of the difference of two
|
339 |
+
matrices ``A1`` and ``A2`` as follows:
|
340 |
+
|
341 |
+
>>> A1, A2 = A**2, A
|
342 |
+
>>> diff = sli.estimate_spectral_norm_diff(A1, A2)
|
343 |
+
|
344 |
+
This is often useful for checking the accuracy of a matrix approximation.
|
345 |
+
|
346 |
+
Some routines in :mod:`scipy.linalg.interpolative` require estimating the rank
|
347 |
+
of a matrix as well. This can be done with either:
|
348 |
+
|
349 |
+
>>> k = sli.estimate_rank(A, eps)
|
350 |
+
|
351 |
+
or:
|
352 |
+
|
353 |
+
>>> k = sli.estimate_rank(L, eps)
|
354 |
+
|
355 |
+
depending on the representation. The parameter ``eps`` controls the definition
|
356 |
+
of the numerical rank.
|
357 |
+
|
358 |
+
Finally, the random number generation required for all randomized routines can
|
359 |
+
be controlled via :func:`scipy.linalg.interpolative.seed`. To reset the seed
|
360 |
+
values to their original values, use:
|
361 |
+
|
362 |
+
>>> sli.seed('default')
|
363 |
+
|
364 |
+
To specify the seed values, use:
|
365 |
+
|
366 |
+
>>> s = 42
|
367 |
+
>>> sli.seed(s)
|
368 |
+
|
369 |
+
where ``s`` must be an integer or array of 55 floats. If an integer, the array
|
370 |
+
of floats is obtained by using ``numpy.random.rand`` with the given integer
|
371 |
+
seed.
|
372 |
+
|
373 |
+
To simply generate some random numbers, type:
|
374 |
+
|
375 |
+
>>> arr = sli.rand(n)
|
376 |
+
|
377 |
+
where ``n`` is the number of random numbers to generate.
|
378 |
+
|
379 |
+
Remarks
|
380 |
+
-------
|
381 |
+
|
382 |
+
The above functions all automatically detect the appropriate interface and work
|
383 |
+
with both real and complex data types, passing input arguments to the proper
|
384 |
+
backend routine.
|
385 |
+
|
386 |
+
"""
|
387 |
+
|
388 |
+
import scipy.linalg._interpolative_backend as _backend
|
389 |
+
import numpy as np
|
390 |
+
import sys
|
391 |
+
|
392 |
+
__all__ = [
|
393 |
+
'estimate_rank',
|
394 |
+
'estimate_spectral_norm',
|
395 |
+
'estimate_spectral_norm_diff',
|
396 |
+
'id_to_svd',
|
397 |
+
'interp_decomp',
|
398 |
+
'rand',
|
399 |
+
'reconstruct_interp_matrix',
|
400 |
+
'reconstruct_matrix_from_id',
|
401 |
+
'reconstruct_skel_matrix',
|
402 |
+
'seed',
|
403 |
+
'svd',
|
404 |
+
]
|
405 |
+
|
406 |
+
_DTYPE_ERROR = ValueError("invalid input dtype (input must be float64 or complex128)")
|
407 |
+
_TYPE_ERROR = TypeError("invalid input type (must be array or LinearOperator)")
|
408 |
+
_32BIT_ERROR = ValueError("interpolative decomposition on 32-bit systems "
|
409 |
+
"with complex128 is buggy")
|
410 |
+
_IS_32BIT = (sys.maxsize < 2**32)
|
411 |
+
|
412 |
+
|
413 |
+
def _is_real(A):
|
414 |
+
try:
|
415 |
+
if A.dtype == np.complex128:
|
416 |
+
return False
|
417 |
+
elif A.dtype == np.float64:
|
418 |
+
return True
|
419 |
+
else:
|
420 |
+
raise _DTYPE_ERROR
|
421 |
+
except AttributeError as e:
|
422 |
+
raise _TYPE_ERROR from e
|
423 |
+
|
424 |
+
|
425 |
+
def seed(seed=None):
|
426 |
+
"""
|
427 |
+
Seed the internal random number generator used in this ID package.
|
428 |
+
|
429 |
+
The generator is a lagged Fibonacci method with 55-element internal state.
|
430 |
+
|
431 |
+
Parameters
|
432 |
+
----------
|
433 |
+
seed : int, sequence, 'default', optional
|
434 |
+
If 'default', the random seed is reset to a default value.
|
435 |
+
|
436 |
+
If `seed` is a sequence containing 55 floating-point numbers
|
437 |
+
in range [0,1], these are used to set the internal state of
|
438 |
+
the generator.
|
439 |
+
|
440 |
+
If the value is an integer, the internal state is obtained
|
441 |
+
from `numpy.random.RandomState` (MT19937) with the integer
|
442 |
+
used as the initial seed.
|
443 |
+
|
444 |
+
If `seed` is omitted (None), ``numpy.random.rand`` is used to
|
445 |
+
initialize the generator.
|
446 |
+
|
447 |
+
"""
|
448 |
+
# For details, see :func:`_backend.id_srand`, :func:`_backend.id_srandi`,
|
449 |
+
# and :func:`_backend.id_srando`.
|
450 |
+
|
451 |
+
if isinstance(seed, str) and seed == 'default':
|
452 |
+
_backend.id_srando()
|
453 |
+
elif hasattr(seed, '__len__'):
|
454 |
+
state = np.asfortranarray(seed, dtype=float)
|
455 |
+
if state.shape != (55,):
|
456 |
+
raise ValueError("invalid input size")
|
457 |
+
elif state.min() < 0 or state.max() > 1:
|
458 |
+
raise ValueError("values not in range [0,1]")
|
459 |
+
_backend.id_srandi(state)
|
460 |
+
elif seed is None:
|
461 |
+
_backend.id_srandi(np.random.rand(55))
|
462 |
+
else:
|
463 |
+
rnd = np.random.RandomState(seed)
|
464 |
+
_backend.id_srandi(rnd.rand(55))
|
465 |
+
|
466 |
+
|
467 |
+
def rand(*shape):
|
468 |
+
"""
|
469 |
+
Generate standard uniform pseudorandom numbers via a very efficient lagged
|
470 |
+
Fibonacci method.
|
471 |
+
|
472 |
+
This routine is used for all random number generation in this package and
|
473 |
+
can affect ID and SVD results.
|
474 |
+
|
475 |
+
Parameters
|
476 |
+
----------
|
477 |
+
*shape
|
478 |
+
Shape of output array
|
479 |
+
|
480 |
+
"""
|
481 |
+
# For details, see :func:`_backend.id_srand`, and :func:`_backend.id_srando`.
|
482 |
+
return _backend.id_srand(np.prod(shape)).reshape(shape)
|
483 |
+
|
484 |
+
|
485 |
+
def interp_decomp(A, eps_or_k, rand=True):
|
486 |
+
"""
|
487 |
+
Compute ID of a matrix.
|
488 |
+
|
489 |
+
An ID of a matrix `A` is a factorization defined by a rank `k`, a column
|
490 |
+
index array `idx`, and interpolation coefficients `proj` such that::
|
491 |
+
|
492 |
+
numpy.dot(A[:,idx[:k]], proj) = A[:,idx[k:]]
|
493 |
+
|
494 |
+
The original matrix can then be reconstructed as::
|
495 |
+
|
496 |
+
numpy.hstack([A[:,idx[:k]],
|
497 |
+
numpy.dot(A[:,idx[:k]], proj)]
|
498 |
+
)[:,numpy.argsort(idx)]
|
499 |
+
|
500 |
+
or via the routine :func:`reconstruct_matrix_from_id`. This can
|
501 |
+
equivalently be written as::
|
502 |
+
|
503 |
+
numpy.dot(A[:,idx[:k]],
|
504 |
+
numpy.hstack([numpy.eye(k), proj])
|
505 |
+
)[:,np.argsort(idx)]
|
506 |
+
|
507 |
+
in terms of the skeleton and interpolation matrices::
|
508 |
+
|
509 |
+
B = A[:,idx[:k]]
|
510 |
+
|
511 |
+
and::
|
512 |
+
|
513 |
+
P = numpy.hstack([numpy.eye(k), proj])[:,np.argsort(idx)]
|
514 |
+
|
515 |
+
respectively. See also :func:`reconstruct_interp_matrix` and
|
516 |
+
:func:`reconstruct_skel_matrix`.
|
517 |
+
|
518 |
+
The ID can be computed to any relative precision or rank (depending on the
|
519 |
+
value of `eps_or_k`). If a precision is specified (`eps_or_k < 1`), then
|
520 |
+
this function has the output signature::
|
521 |
+
|
522 |
+
k, idx, proj = interp_decomp(A, eps_or_k)
|
523 |
+
|
524 |
+
Otherwise, if a rank is specified (`eps_or_k >= 1`), then the output
|
525 |
+
signature is::
|
526 |
+
|
527 |
+
idx, proj = interp_decomp(A, eps_or_k)
|
528 |
+
|
529 |
+
.. This function automatically detects the form of the input parameters
|
530 |
+
and passes them to the appropriate backend. For details, see
|
531 |
+
:func:`_backend.iddp_id`, :func:`_backend.iddp_aid`,
|
532 |
+
:func:`_backend.iddp_rid`, :func:`_backend.iddr_id`,
|
533 |
+
:func:`_backend.iddr_aid`, :func:`_backend.iddr_rid`,
|
534 |
+
:func:`_backend.idzp_id`, :func:`_backend.idzp_aid`,
|
535 |
+
:func:`_backend.idzp_rid`, :func:`_backend.idzr_id`,
|
536 |
+
:func:`_backend.idzr_aid`, and :func:`_backend.idzr_rid`.
|
537 |
+
|
538 |
+
Parameters
|
539 |
+
----------
|
540 |
+
A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator` with `rmatvec`
|
541 |
+
Matrix to be factored
|
542 |
+
eps_or_k : float or int
|
543 |
+
Relative error (if `eps_or_k < 1`) or rank (if `eps_or_k >= 1`) of
|
544 |
+
approximation.
|
545 |
+
rand : bool, optional
|
546 |
+
Whether to use random sampling if `A` is of type :class:`numpy.ndarray`
|
547 |
+
(randomized algorithms are always used if `A` is of type
|
548 |
+
:class:`scipy.sparse.linalg.LinearOperator`).
|
549 |
+
|
550 |
+
Returns
|
551 |
+
-------
|
552 |
+
k : int
|
553 |
+
Rank required to achieve specified relative precision if
|
554 |
+
`eps_or_k < 1`.
|
555 |
+
idx : :class:`numpy.ndarray`
|
556 |
+
Column index array.
|
557 |
+
proj : :class:`numpy.ndarray`
|
558 |
+
Interpolation coefficients.
|
559 |
+
""" # numpy/numpydoc#87 # noqa: E501
|
560 |
+
from scipy.sparse.linalg import LinearOperator
|
561 |
+
|
562 |
+
real = _is_real(A)
|
563 |
+
|
564 |
+
if isinstance(A, np.ndarray):
|
565 |
+
if eps_or_k < 1:
|
566 |
+
eps = eps_or_k
|
567 |
+
if rand:
|
568 |
+
if real:
|
569 |
+
k, idx, proj = _backend.iddp_aid(eps, A)
|
570 |
+
else:
|
571 |
+
if _IS_32BIT:
|
572 |
+
raise _32BIT_ERROR
|
573 |
+
k, idx, proj = _backend.idzp_aid(eps, A)
|
574 |
+
else:
|
575 |
+
if real:
|
576 |
+
k, idx, proj = _backend.iddp_id(eps, A)
|
577 |
+
else:
|
578 |
+
k, idx, proj = _backend.idzp_id(eps, A)
|
579 |
+
return k, idx - 1, proj
|
580 |
+
else:
|
581 |
+
k = int(eps_or_k)
|
582 |
+
if rand:
|
583 |
+
if real:
|
584 |
+
idx, proj = _backend.iddr_aid(A, k)
|
585 |
+
else:
|
586 |
+
if _IS_32BIT:
|
587 |
+
raise _32BIT_ERROR
|
588 |
+
idx, proj = _backend.idzr_aid(A, k)
|
589 |
+
else:
|
590 |
+
if real:
|
591 |
+
idx, proj = _backend.iddr_id(A, k)
|
592 |
+
else:
|
593 |
+
idx, proj = _backend.idzr_id(A, k)
|
594 |
+
return idx - 1, proj
|
595 |
+
elif isinstance(A, LinearOperator):
|
596 |
+
m, n = A.shape
|
597 |
+
matveca = A.rmatvec
|
598 |
+
if eps_or_k < 1:
|
599 |
+
eps = eps_or_k
|
600 |
+
if real:
|
601 |
+
k, idx, proj = _backend.iddp_rid(eps, m, n, matveca)
|
602 |
+
else:
|
603 |
+
if _IS_32BIT:
|
604 |
+
raise _32BIT_ERROR
|
605 |
+
k, idx, proj = _backend.idzp_rid(eps, m, n, matveca)
|
606 |
+
return k, idx - 1, proj
|
607 |
+
else:
|
608 |
+
k = int(eps_or_k)
|
609 |
+
if real:
|
610 |
+
idx, proj = _backend.iddr_rid(m, n, matveca, k)
|
611 |
+
else:
|
612 |
+
if _IS_32BIT:
|
613 |
+
raise _32BIT_ERROR
|
614 |
+
idx, proj = _backend.idzr_rid(m, n, matveca, k)
|
615 |
+
return idx - 1, proj
|
616 |
+
else:
|
617 |
+
raise _TYPE_ERROR
|
618 |
+
|
619 |
+
|
620 |
+
def reconstruct_matrix_from_id(B, idx, proj):
|
621 |
+
"""
|
622 |
+
Reconstruct matrix from its ID.
|
623 |
+
|
624 |
+
A matrix `A` with skeleton matrix `B` and ID indices and coefficients `idx`
|
625 |
+
and `proj`, respectively, can be reconstructed as::
|
626 |
+
|
627 |
+
numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)]
|
628 |
+
|
629 |
+
See also :func:`reconstruct_interp_matrix` and
|
630 |
+
:func:`reconstruct_skel_matrix`.
|
631 |
+
|
632 |
+
.. This function automatically detects the matrix data type and calls the
|
633 |
+
appropriate backend. For details, see :func:`_backend.idd_reconid` and
|
634 |
+
:func:`_backend.idz_reconid`.
|
635 |
+
|
636 |
+
Parameters
|
637 |
+
----------
|
638 |
+
B : :class:`numpy.ndarray`
|
639 |
+
Skeleton matrix.
|
640 |
+
idx : :class:`numpy.ndarray`
|
641 |
+
Column index array.
|
642 |
+
proj : :class:`numpy.ndarray`
|
643 |
+
Interpolation coefficients.
|
644 |
+
|
645 |
+
Returns
|
646 |
+
-------
|
647 |
+
:class:`numpy.ndarray`
|
648 |
+
Reconstructed matrix.
|
649 |
+
"""
|
650 |
+
if _is_real(B):
|
651 |
+
return _backend.idd_reconid(B, idx + 1, proj)
|
652 |
+
else:
|
653 |
+
return _backend.idz_reconid(B, idx + 1, proj)
|
654 |
+
|
655 |
+
|
656 |
+
def reconstruct_interp_matrix(idx, proj):
|
657 |
+
"""
|
658 |
+
Reconstruct interpolation matrix from ID.
|
659 |
+
|
660 |
+
The interpolation matrix can be reconstructed from the ID indices and
|
661 |
+
coefficients `idx` and `proj`, respectively, as::
|
662 |
+
|
663 |
+
P = numpy.hstack([numpy.eye(proj.shape[0]), proj])[:,numpy.argsort(idx)]
|
664 |
+
|
665 |
+
The original matrix can then be reconstructed from its skeleton matrix `B`
|
666 |
+
via::
|
667 |
+
|
668 |
+
numpy.dot(B, P)
|
669 |
+
|
670 |
+
See also :func:`reconstruct_matrix_from_id` and
|
671 |
+
:func:`reconstruct_skel_matrix`.
|
672 |
+
|
673 |
+
.. This function automatically detects the matrix data type and calls the
|
674 |
+
appropriate backend. For details, see :func:`_backend.idd_reconint` and
|
675 |
+
:func:`_backend.idz_reconint`.
|
676 |
+
|
677 |
+
Parameters
|
678 |
+
----------
|
679 |
+
idx : :class:`numpy.ndarray`
|
680 |
+
Column index array.
|
681 |
+
proj : :class:`numpy.ndarray`
|
682 |
+
Interpolation coefficients.
|
683 |
+
|
684 |
+
Returns
|
685 |
+
-------
|
686 |
+
:class:`numpy.ndarray`
|
687 |
+
Interpolation matrix.
|
688 |
+
"""
|
689 |
+
if _is_real(proj):
|
690 |
+
return _backend.idd_reconint(idx + 1, proj)
|
691 |
+
else:
|
692 |
+
return _backend.idz_reconint(idx + 1, proj)
|
693 |
+
|
694 |
+
|
695 |
+
def reconstruct_skel_matrix(A, k, idx):
|
696 |
+
"""
|
697 |
+
Reconstruct skeleton matrix from ID.
|
698 |
+
|
699 |
+
The skeleton matrix can be reconstructed from the original matrix `A` and its
|
700 |
+
ID rank and indices `k` and `idx`, respectively, as::
|
701 |
+
|
702 |
+
B = A[:,idx[:k]]
|
703 |
+
|
704 |
+
The original matrix can then be reconstructed via::
|
705 |
+
|
706 |
+
numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)]
|
707 |
+
|
708 |
+
See also :func:`reconstruct_matrix_from_id` and
|
709 |
+
:func:`reconstruct_interp_matrix`.
|
710 |
+
|
711 |
+
.. This function automatically detects the matrix data type and calls the
|
712 |
+
appropriate backend. For details, see :func:`_backend.idd_copycols` and
|
713 |
+
:func:`_backend.idz_copycols`.
|
714 |
+
|
715 |
+
Parameters
|
716 |
+
----------
|
717 |
+
A : :class:`numpy.ndarray`
|
718 |
+
Original matrix.
|
719 |
+
k : int
|
720 |
+
Rank of ID.
|
721 |
+
idx : :class:`numpy.ndarray`
|
722 |
+
Column index array.
|
723 |
+
|
724 |
+
Returns
|
725 |
+
-------
|
726 |
+
:class:`numpy.ndarray`
|
727 |
+
Skeleton matrix.
|
728 |
+
"""
|
729 |
+
if _is_real(A):
|
730 |
+
return _backend.idd_copycols(A, k, idx + 1)
|
731 |
+
else:
|
732 |
+
return _backend.idz_copycols(A, k, idx + 1)
|
733 |
+
|
734 |
+
|
735 |
+
def id_to_svd(B, idx, proj):
|
736 |
+
"""
|
737 |
+
Convert ID to SVD.
|
738 |
+
|
739 |
+
The SVD reconstruction of a matrix with skeleton matrix `B` and ID indices and
|
740 |
+
coefficients `idx` and `proj`, respectively, is::
|
741 |
+
|
742 |
+
U, S, V = id_to_svd(B, idx, proj)
|
743 |
+
A = numpy.dot(U, numpy.dot(numpy.diag(S), V.conj().T))
|
744 |
+
|
745 |
+
See also :func:`svd`.
|
746 |
+
|
747 |
+
.. This function automatically detects the matrix data type and calls the
|
748 |
+
appropriate backend. For details, see :func:`_backend.idd_id2svd` and
|
749 |
+
:func:`_backend.idz_id2svd`.
|
750 |
+
|
751 |
+
Parameters
|
752 |
+
----------
|
753 |
+
B : :class:`numpy.ndarray`
|
754 |
+
Skeleton matrix.
|
755 |
+
idx : :class:`numpy.ndarray`
|
756 |
+
Column index array.
|
757 |
+
proj : :class:`numpy.ndarray`
|
758 |
+
Interpolation coefficients.
|
759 |
+
|
760 |
+
Returns
|
761 |
+
-------
|
762 |
+
U : :class:`numpy.ndarray`
|
763 |
+
Left singular vectors.
|
764 |
+
S : :class:`numpy.ndarray`
|
765 |
+
Singular values.
|
766 |
+
V : :class:`numpy.ndarray`
|
767 |
+
Right singular vectors.
|
768 |
+
"""
|
769 |
+
if _is_real(B):
|
770 |
+
U, V, S = _backend.idd_id2svd(B, idx + 1, proj)
|
771 |
+
else:
|
772 |
+
U, V, S = _backend.idz_id2svd(B, idx + 1, proj)
|
773 |
+
return U, S, V
|
774 |
+
|
775 |
+
|
776 |
+
def estimate_spectral_norm(A, its=20):
|
777 |
+
"""
|
778 |
+
Estimate spectral norm of a matrix by the randomized power method.
|
779 |
+
|
780 |
+
.. This function automatically detects the matrix data type and calls the
|
781 |
+
appropriate backend. For details, see :func:`_backend.idd_snorm` and
|
782 |
+
:func:`_backend.idz_snorm`.
|
783 |
+
|
784 |
+
Parameters
|
785 |
+
----------
|
786 |
+
A : :class:`scipy.sparse.linalg.LinearOperator`
|
787 |
+
Matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the
|
788 |
+
`matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
|
789 |
+
its : int, optional
|
790 |
+
Number of power method iterations.
|
791 |
+
|
792 |
+
Returns
|
793 |
+
-------
|
794 |
+
float
|
795 |
+
Spectral norm estimate.
|
796 |
+
"""
|
797 |
+
from scipy.sparse.linalg import aslinearoperator
|
798 |
+
A = aslinearoperator(A)
|
799 |
+
m, n = A.shape
|
800 |
+
def matvec(x):
|
801 |
+
return A.matvec(x)
|
802 |
+
def matveca(x):
|
803 |
+
return A.rmatvec(x)
|
804 |
+
if _is_real(A):
|
805 |
+
return _backend.idd_snorm(m, n, matveca, matvec, its=its)
|
806 |
+
else:
|
807 |
+
return _backend.idz_snorm(m, n, matveca, matvec, its=its)
|
808 |
+
|
809 |
+
|
810 |
+
def estimate_spectral_norm_diff(A, B, its=20):
|
811 |
+
"""
|
812 |
+
Estimate spectral norm of the difference of two matrices by the randomized
|
813 |
+
power method.
|
814 |
+
|
815 |
+
.. This function automatically detects the matrix data type and calls the
|
816 |
+
appropriate backend. For details, see :func:`_backend.idd_diffsnorm` and
|
817 |
+
:func:`_backend.idz_diffsnorm`.
|
818 |
+
|
819 |
+
Parameters
|
820 |
+
----------
|
821 |
+
A : :class:`scipy.sparse.linalg.LinearOperator`
|
822 |
+
First matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the
|
823 |
+
`matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
|
824 |
+
B : :class:`scipy.sparse.linalg.LinearOperator`
|
825 |
+
Second matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with
|
826 |
+
the `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
|
827 |
+
its : int, optional
|
828 |
+
Number of power method iterations.
|
829 |
+
|
830 |
+
Returns
|
831 |
+
-------
|
832 |
+
float
|
833 |
+
Spectral norm estimate of matrix difference.
|
834 |
+
"""
|
835 |
+
from scipy.sparse.linalg import aslinearoperator
|
836 |
+
A = aslinearoperator(A)
|
837 |
+
B = aslinearoperator(B)
|
838 |
+
m, n = A.shape
|
839 |
+
def matvec1(x):
|
840 |
+
return A.matvec(x)
|
841 |
+
def matveca1(x):
|
842 |
+
return A.rmatvec(x)
|
843 |
+
def matvec2(x):
|
844 |
+
return B.matvec(x)
|
845 |
+
def matveca2(x):
|
846 |
+
return B.rmatvec(x)
|
847 |
+
if _is_real(A):
|
848 |
+
return _backend.idd_diffsnorm(
|
849 |
+
m, n, matveca1, matveca2, matvec1, matvec2, its=its)
|
850 |
+
else:
|
851 |
+
return _backend.idz_diffsnorm(
|
852 |
+
m, n, matveca1, matveca2, matvec1, matvec2, its=its)
|
853 |
+
|
854 |
+
|
855 |
+
def svd(A, eps_or_k, rand=True):
|
856 |
+
"""
|
857 |
+
Compute SVD of a matrix via an ID.
|
858 |
+
|
859 |
+
An SVD of a matrix `A` is a factorization::
|
860 |
+
|
861 |
+
A = numpy.dot(U, numpy.dot(numpy.diag(S), V.conj().T))
|
862 |
+
|
863 |
+
where `U` and `V` have orthonormal columns and `S` is nonnegative.
|
864 |
+
|
865 |
+
The SVD can be computed to any relative precision or rank (depending on the
|
866 |
+
value of `eps_or_k`).
|
867 |
+
|
868 |
+
See also :func:`interp_decomp` and :func:`id_to_svd`.
|
869 |
+
|
870 |
+
.. This function automatically detects the form of the input parameters and
|
871 |
+
passes them to the appropriate backend. For details, see
|
872 |
+
:func:`_backend.iddp_svd`, :func:`_backend.iddp_asvd`,
|
873 |
+
:func:`_backend.iddp_rsvd`, :func:`_backend.iddr_svd`,
|
874 |
+
:func:`_backend.iddr_asvd`, :func:`_backend.iddr_rsvd`,
|
875 |
+
:func:`_backend.idzp_svd`, :func:`_backend.idzp_asvd`,
|
876 |
+
:func:`_backend.idzp_rsvd`, :func:`_backend.idzr_svd`,
|
877 |
+
:func:`_backend.idzr_asvd`, and :func:`_backend.idzr_rsvd`.
|
878 |
+
|
879 |
+
Parameters
|
880 |
+
----------
|
881 |
+
A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator`
|
882 |
+
Matrix to be factored, given as either a :class:`numpy.ndarray` or a
|
883 |
+
:class:`scipy.sparse.linalg.LinearOperator` with the `matvec` and
|
884 |
+
`rmatvec` methods (to apply the matrix and its adjoint).
|
885 |
+
eps_or_k : float or int
|
886 |
+
Relative error (if `eps_or_k < 1`) or rank (if `eps_or_k >= 1`) of
|
887 |
+
approximation.
|
888 |
+
rand : bool, optional
|
889 |
+
Whether to use random sampling if `A` is of type :class:`numpy.ndarray`
|
890 |
+
(randomized algorithms are always used if `A` is of type
|
891 |
+
:class:`scipy.sparse.linalg.LinearOperator`).
|
892 |
+
|
893 |
+
Returns
|
894 |
+
-------
|
895 |
+
U : :class:`numpy.ndarray`
|
896 |
+
Left singular vectors.
|
897 |
+
S : :class:`numpy.ndarray`
|
898 |
+
Singular values.
|
899 |
+
V : :class:`numpy.ndarray`
|
900 |
+
Right singular vectors.
|
901 |
+
"""
|
902 |
+
from scipy.sparse.linalg import LinearOperator
|
903 |
+
|
904 |
+
real = _is_real(A)
|
905 |
+
|
906 |
+
if isinstance(A, np.ndarray):
|
907 |
+
if eps_or_k < 1:
|
908 |
+
eps = eps_or_k
|
909 |
+
if rand:
|
910 |
+
if real:
|
911 |
+
U, V, S = _backend.iddp_asvd(eps, A)
|
912 |
+
else:
|
913 |
+
if _IS_32BIT:
|
914 |
+
raise _32BIT_ERROR
|
915 |
+
U, V, S = _backend.idzp_asvd(eps, A)
|
916 |
+
else:
|
917 |
+
if real:
|
918 |
+
U, V, S = _backend.iddp_svd(eps, A)
|
919 |
+
else:
|
920 |
+
U, V, S = _backend.idzp_svd(eps, A)
|
921 |
+
else:
|
922 |
+
k = int(eps_or_k)
|
923 |
+
if k > min(A.shape):
|
924 |
+
raise ValueError(f"Approximation rank {k} exceeds min(A.shape) = "
|
925 |
+
f" {min(A.shape)} ")
|
926 |
+
if rand:
|
927 |
+
if real:
|
928 |
+
U, V, S = _backend.iddr_asvd(A, k)
|
929 |
+
else:
|
930 |
+
if _IS_32BIT:
|
931 |
+
raise _32BIT_ERROR
|
932 |
+
U, V, S = _backend.idzr_asvd(A, k)
|
933 |
+
else:
|
934 |
+
if real:
|
935 |
+
U, V, S = _backend.iddr_svd(A, k)
|
936 |
+
else:
|
937 |
+
U, V, S = _backend.idzr_svd(A, k)
|
938 |
+
elif isinstance(A, LinearOperator):
|
939 |
+
m, n = A.shape
|
940 |
+
def matvec(x):
|
941 |
+
return A.matvec(x)
|
942 |
+
def matveca(x):
|
943 |
+
return A.rmatvec(x)
|
944 |
+
if eps_or_k < 1:
|
945 |
+
eps = eps_or_k
|
946 |
+
if real:
|
947 |
+
U, V, S = _backend.iddp_rsvd(eps, m, n, matveca, matvec)
|
948 |
+
else:
|
949 |
+
if _IS_32BIT:
|
950 |
+
raise _32BIT_ERROR
|
951 |
+
U, V, S = _backend.idzp_rsvd(eps, m, n, matveca, matvec)
|
952 |
+
else:
|
953 |
+
k = int(eps_or_k)
|
954 |
+
if real:
|
955 |
+
U, V, S = _backend.iddr_rsvd(m, n, matveca, matvec, k)
|
956 |
+
else:
|
957 |
+
if _IS_32BIT:
|
958 |
+
raise _32BIT_ERROR
|
959 |
+
U, V, S = _backend.idzr_rsvd(m, n, matveca, matvec, k)
|
960 |
+
else:
|
961 |
+
raise _TYPE_ERROR
|
962 |
+
return U, S, V
|
963 |
+
|
964 |
+
|
965 |
+
def estimate_rank(A, eps):
|
966 |
+
"""
|
967 |
+
Estimate matrix rank to a specified relative precision using randomized
|
968 |
+
methods.
|
969 |
+
|
970 |
+
The matrix `A` can be given as either a :class:`numpy.ndarray` or a
|
971 |
+
:class:`scipy.sparse.linalg.LinearOperator`, with different algorithms used
|
972 |
+
for each case. If `A` is of type :class:`numpy.ndarray`, then the output
|
973 |
+
rank is typically about 8 higher than the actual numerical rank.
|
974 |
+
|
975 |
+
.. This function automatically detects the form of the input parameters and
|
976 |
+
passes them to the appropriate backend. For details,
|
977 |
+
see :func:`_backend.idd_estrank`, :func:`_backend.idd_findrank`,
|
978 |
+
:func:`_backend.idz_estrank`, and :func:`_backend.idz_findrank`.
|
979 |
+
|
980 |
+
Parameters
|
981 |
+
----------
|
982 |
+
A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator`
|
983 |
+
Matrix whose rank is to be estimated, given as either a
|
984 |
+
:class:`numpy.ndarray` or a :class:`scipy.sparse.linalg.LinearOperator`
|
985 |
+
with the `rmatvec` method (to apply the matrix adjoint).
|
986 |
+
eps : float
|
987 |
+
Relative error for numerical rank definition.
|
988 |
+
|
989 |
+
Returns
|
990 |
+
-------
|
991 |
+
int
|
992 |
+
Estimated matrix rank.
|
993 |
+
"""
|
994 |
+
from scipy.sparse.linalg import LinearOperator
|
995 |
+
|
996 |
+
real = _is_real(A)
|
997 |
+
|
998 |
+
if isinstance(A, np.ndarray):
|
999 |
+
if real:
|
1000 |
+
rank = _backend.idd_estrank(eps, A)
|
1001 |
+
else:
|
1002 |
+
rank = _backend.idz_estrank(eps, A)
|
1003 |
+
if rank == 0:
|
1004 |
+
# special return value for nearly full rank
|
1005 |
+
rank = min(A.shape)
|
1006 |
+
return rank
|
1007 |
+
elif isinstance(A, LinearOperator):
|
1008 |
+
m, n = A.shape
|
1009 |
+
matveca = A.rmatvec
|
1010 |
+
if real:
|
1011 |
+
return _backend.idd_findrank(eps, m, n, matveca)
|
1012 |
+
else:
|
1013 |
+
return _backend.idz_findrank(eps, m, n, matveca)
|
1014 |
+
else:
|
1015 |
+
raise _TYPE_ERROR
|