jasonfan commited on
Commit
f723ecc
·
verified ·
1 Parent(s): 2d00d09

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat +0 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat +0 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat +0 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat +0 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat +0 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat +0 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat +0 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat +0 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat +0 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/invalid_pointer.sav +0 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/null_pointer.sav +0 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte.sav +0 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte_descr.sav +0 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav +0 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex64.sav +0 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float32.sav +0 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float64.sav +0 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav +0 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int16.sav +0 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int32.sav +0 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav +0 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_string.sav +0 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint16.sav +0 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav +0 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav +0 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays.sav +0 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav +0 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav +0 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav +0 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_inherit.sav +0 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav +0 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav +0 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav +0 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers.sav +0 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav +0 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav +0 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars.sav +0 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav +0 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav +0 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/various_compressed.sav +0 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/__init__.pxd +1 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/__init__.py +236 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_basic.py +2119 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h +164 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd +40 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi +16 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp.py +1632 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py +398 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py +221 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py +353 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat ADDED
Binary file (48 Bytes). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat ADDED
Binary file (64 Bytes). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat ADDED
Binary file (128 Bytes). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat ADDED
Binary file (448 Bytes). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat ADDED
Binary file (13.2 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat ADDED
Binary file (12 Bytes). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat ADDED
Binary file (28 Bytes). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat ADDED
Binary file (36 Bytes). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat ADDED
Binary file (68 Bytes). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/invalid_pointer.sav ADDED
Binary file (1.28 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/null_pointer.sav ADDED
Binary file (2.18 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte.sav ADDED
Binary file (2.08 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte_descr.sav ADDED
Binary file (2.12 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav ADDED
Binary file (2.08 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex64.sav ADDED
Binary file (2.08 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float32.sav ADDED
Binary file (2.07 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float64.sav ADDED
Binary file (2.08 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav ADDED
Binary file (2.2 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int16.sav ADDED
Binary file (2.07 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int32.sav ADDED
Binary file (2.07 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav ADDED
Binary file (2.08 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_string.sav ADDED
Binary file (2.12 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint16.sav ADDED
Binary file (2.07 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav ADDED
Binary file (2.07 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav ADDED
Binary file (2.08 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays.sav ADDED
Binary file (2.58 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav ADDED
Binary file (1.39 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav ADDED
Binary file (2.94 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav ADDED
Binary file (4.61 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_inherit.sav ADDED
Binary file (2.4 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav ADDED
Binary file (2.41 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav ADDED
Binary file (2.49 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav ADDED
Binary file (2.87 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers.sav ADDED
Binary file (2.27 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav ADDED
Binary file (2.3 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav ADDED
Binary file (2.46 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars.sav ADDED
Binary file (2.32 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav ADDED
Binary file (2.48 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav ADDED
Binary file (3.24 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/various_compressed.sav ADDED
Binary file (1.02 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/__init__.pxd ADDED
@@ -0,0 +1 @@
 
 
1
+ from scipy.linalg cimport cython_blas, cython_lapack
miniconda3/envs/ladir/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
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_basic.py ADDED
@@ -0,0 +1,2119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Author: Pearu Peterson, March 2002
3
+ #
4
+ # w/ additions by Travis Oliphant, March 2002
5
+ # and Jake Vanderplas, August 2012
6
+
7
+ import warnings
8
+ from warnings import warn
9
+ from itertools import product
10
+ import numpy as np
11
+ from numpy import atleast_1d, atleast_2d
12
+ from .lapack import get_lapack_funcs, _compute_lwork
13
+ from ._misc import LinAlgError, _datacopied, LinAlgWarning
14
+ from ._decomp import _asarray_validated
15
+ from . import _decomp, _decomp_svd
16
+ from ._solve_toeplitz import levinson
17
+ from ._cythonized_array_utils import (find_det_from_lu, bandwidth, issymmetric,
18
+ ishermitian)
19
+
20
+ __all__ = ['solve', 'solve_triangular', 'solveh_banded', 'solve_banded',
21
+ 'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq',
22
+ 'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz']
23
+
24
+
25
+ # The numpy facilities for type-casting checks are too slow for small sized
26
+ # arrays and eat away the time budget for the checkups. Here we set a
27
+ # precomputed dict container of the numpy.can_cast() table.
28
+
29
+ # It can be used to determine quickly what a dtype can be cast to LAPACK
30
+ # compatible types, i.e., 'float32, float64, complex64, complex128'.
31
+ # Then it can be checked via "casting_dict[arr.dtype.char]"
32
+ lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)])
33
+ for x in np.typecodes['All']}
34
+
35
+
36
+ # Linear equations
37
+ def _solve_check(n, info, lamch=None, rcond=None):
38
+ """ Check arguments during the different steps of the solution phase """
39
+ if info < 0:
40
+ raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument.')
41
+ elif 0 < info:
42
+ raise LinAlgError('Matrix is singular.')
43
+
44
+ if lamch is None:
45
+ return
46
+ E = lamch('E')
47
+ if rcond < E:
48
+ warn(f'Ill-conditioned matrix (rcond={rcond:.6g}): '
49
+ 'result may not be accurate.',
50
+ LinAlgWarning, stacklevel=3)
51
+
52
+
53
+ def _find_matrix_structure(a):
54
+ n = a.shape[0]
55
+ n_below, n_above = bandwidth(a)
56
+
57
+ if n_below == n_above == 0:
58
+ kind = 'diagonal'
59
+ elif n_above == 0:
60
+ kind = 'lower triangular'
61
+ elif n_below == 0:
62
+ kind = 'upper triangular'
63
+ elif n_above <= 1 and n_below <= 1 and n > 3:
64
+ kind = 'tridiagonal'
65
+ elif np.issubdtype(a.dtype, np.complexfloating) and ishermitian(a):
66
+ kind = 'hermitian'
67
+ elif issymmetric(a):
68
+ kind = 'symmetric'
69
+ else:
70
+ kind = 'general'
71
+
72
+ return kind, n_below, n_above
73
+
74
+
75
+ def solve(a, b, lower=False, overwrite_a=False,
76
+ overwrite_b=False, check_finite=True, assume_a=None,
77
+ transposed=False):
78
+ """
79
+ Solves the linear equation set ``a @ x == b`` for the unknown ``x``
80
+ for square `a` matrix.
81
+
82
+ If the data matrix is known to be a particular type then supplying the
83
+ corresponding string to ``assume_a`` key chooses the dedicated solver.
84
+ The available options are
85
+
86
+ =================== ================================
87
+ diagonal 'diagonal'
88
+ tridiagonal 'tridiagonal'
89
+ banded 'banded'
90
+ upper triangular 'upper triangular'
91
+ lower triangular 'lower triangular'
92
+ symmetric 'symmetric' (or 'sym')
93
+ hermitian 'hermitian' (or 'her')
94
+ positive definite 'positive definite' (or 'pos')
95
+ general 'general' (or 'gen')
96
+ =================== ================================
97
+
98
+ Parameters
99
+ ----------
100
+ a : (N, N) array_like
101
+ Square input data
102
+ b : (N, NRHS) array_like
103
+ Input data for the right hand side.
104
+ lower : bool, default: False
105
+ Ignored unless ``assume_a`` is one of ``'sym'``, ``'her'``, or ``'pos'``.
106
+ If True, the calculation uses only the data in the lower triangle of `a`;
107
+ entries above the diagonal are ignored. If False (default), the
108
+ calculation uses only the data in the upper triangle of `a`; entries
109
+ below the diagonal are ignored.
110
+ overwrite_a : bool, default: False
111
+ Allow overwriting data in `a` (may enhance performance).
112
+ overwrite_b : bool, default: False
113
+ Allow overwriting data in `b` (may enhance performance).
114
+ check_finite : bool, default: True
115
+ Whether to check that the input matrices contain only finite numbers.
116
+ Disabling may give a performance gain, but may result in problems
117
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
118
+ assume_a : str, optional
119
+ Valid entries are described above.
120
+ If omitted or ``None``, checks are performed to identify structure so the
121
+ appropriate solver can be called.
122
+ transposed : bool, default: False
123
+ If True, solve ``a.T @ x == b``. Raises `NotImplementedError`
124
+ for complex `a`.
125
+
126
+ Returns
127
+ -------
128
+ x : (N, NRHS) ndarray
129
+ The solution array.
130
+
131
+ Raises
132
+ ------
133
+ ValueError
134
+ If size mismatches detected or input a is not square.
135
+ LinAlgError
136
+ If the matrix is singular.
137
+ LinAlgWarning
138
+ If an ill-conditioned input a is detected.
139
+ NotImplementedError
140
+ If transposed is True and input a is a complex matrix.
141
+
142
+ Notes
143
+ -----
144
+ If the input b matrix is a 1-D array with N elements, when supplied
145
+ together with an NxN input a, it is assumed as a valid column vector
146
+ despite the apparent size mismatch. This is compatible with the
147
+ numpy.dot() behavior and the returned result is still 1-D array.
148
+
149
+ The general, symmetric, Hermitian and positive definite solutions are
150
+ obtained via calling ?GESV, ?SYSV, ?HESV, and ?POSV routines of
151
+ LAPACK respectively.
152
+
153
+ The datatype of the arrays define which solver is called regardless
154
+ of the values. In other words, even when the complex array entries have
155
+ precisely zero imaginary parts, the complex solver will be called based
156
+ on the data type of the array.
157
+
158
+ Examples
159
+ --------
160
+ Given `a` and `b`, solve for `x`:
161
+
162
+ >>> import numpy as np
163
+ >>> a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
164
+ >>> b = np.array([2, 4, -1])
165
+ >>> from scipy import linalg
166
+ >>> x = linalg.solve(a, b)
167
+ >>> x
168
+ array([ 2., -2., 9.])
169
+ >>> np.dot(a, x) == b
170
+ array([ True, True, True], dtype=bool)
171
+
172
+ """
173
+ # Flags for 1-D or N-D right-hand side
174
+ b_is_1D = False
175
+
176
+ # check finite after determining structure
177
+ a1 = atleast_2d(_asarray_validated(a, check_finite=False))
178
+ b1 = atleast_1d(_asarray_validated(b, check_finite=False))
179
+ a1, b1 = _ensure_dtype_cdsz(a1, b1)
180
+ n = a1.shape[0]
181
+
182
+ overwrite_a = overwrite_a or _datacopied(a1, a)
183
+ overwrite_b = overwrite_b or _datacopied(b1, b)
184
+
185
+ if a1.shape[0] != a1.shape[1]:
186
+ raise ValueError('Input a needs to be a square matrix.')
187
+
188
+ if n != b1.shape[0]:
189
+ # Last chance to catch 1x1 scalar a and 1-D b arrays
190
+ if not (n == 1 and b1.size != 0):
191
+ raise ValueError('Input b has to have same number of rows as '
192
+ 'input a')
193
+
194
+ # accommodate empty arrays
195
+ if b1.size == 0:
196
+ dt = solve(np.eye(2, dtype=a1.dtype), np.ones(2, dtype=b1.dtype)).dtype
197
+ return np.empty_like(b1, dtype=dt)
198
+
199
+ # regularize 1-D b arrays to 2D
200
+ if b1.ndim == 1:
201
+ if n == 1:
202
+ b1 = b1[None, :]
203
+ else:
204
+ b1 = b1[:, None]
205
+ b_is_1D = True
206
+
207
+ if assume_a not in {None, 'diagonal', 'tridiagonal', 'banded', 'lower triangular',
208
+ 'upper triangular', 'symmetric', 'hermitian',
209
+ 'positive definite', 'general', 'sym', 'her', 'pos', 'gen'}:
210
+ raise ValueError(f'{assume_a} is not a recognized matrix structure')
211
+
212
+ # for a real matrix, describe it as "symmetric", not "hermitian"
213
+ # (lapack doesn't know what to do with real hermitian matrices)
214
+ if assume_a in {'hermitian', 'her'} and not np.iscomplexobj(a1):
215
+ assume_a = 'symmetric'
216
+
217
+ n_below, n_above = None, None
218
+ if assume_a is None:
219
+ assume_a, n_below, n_above = _find_matrix_structure(a1)
220
+
221
+ # Get the correct lamch function.
222
+ # The LAMCH functions only exists for S and D
223
+ # So for complex values we have to convert to real/double.
224
+ if a1.dtype.char in 'fF': # single precision
225
+ lamch = get_lapack_funcs('lamch', dtype='f')
226
+ else:
227
+ lamch = get_lapack_funcs('lamch', dtype='d')
228
+
229
+ # Currently we do not have the other forms of the norm calculators
230
+ # lansy, lanpo, lanhe.
231
+ # However, in any case they only reduce computations slightly...
232
+ if assume_a == 'diagonal':
233
+ _matrix_norm = _matrix_norm_diagonal
234
+ elif assume_a == 'tridiagonal':
235
+ _matrix_norm = _matrix_norm_tridiagonal
236
+ elif assume_a in {'lower triangular', 'upper triangular'}:
237
+ _matrix_norm = _matrix_norm_triangular(assume_a)
238
+ else:
239
+ _matrix_norm = _matrix_norm_general
240
+
241
+ # Since the I-norm and 1-norm are the same for symmetric matrices
242
+ # we can collect them all in this one call
243
+ # Note however, that when issuing 'gen' and form!='none', then
244
+ # the I-norm should be used
245
+ if transposed:
246
+ trans = 1
247
+ norm = 'I'
248
+ if np.iscomplexobj(a1):
249
+ raise NotImplementedError('scipy.linalg.solve can currently '
250
+ 'not solve a^T x = b or a^H x = b '
251
+ 'for complex matrices.')
252
+ else:
253
+ trans = 0
254
+ norm = '1'
255
+
256
+ anorm = _matrix_norm(norm, a1, check_finite)
257
+
258
+ info, rcond = 0, np.inf
259
+
260
+ # Generalized case 'gesv'
261
+ if assume_a in {'general', 'gen'}:
262
+ gecon, getrf, getrs = get_lapack_funcs(('gecon', 'getrf', 'getrs'),
263
+ (a1, b1))
264
+ lu, ipvt, info = getrf(a1, overwrite_a=overwrite_a)
265
+ _solve_check(n, info)
266
+ x, info = getrs(lu, ipvt, b1,
267
+ trans=trans, overwrite_b=overwrite_b)
268
+ _solve_check(n, info)
269
+ rcond, info = gecon(lu, anorm, norm=norm)
270
+ # Hermitian case 'hesv'
271
+ elif assume_a in {'hermitian', 'her'}:
272
+ hecon, hesv, hesv_lw = get_lapack_funcs(('hecon', 'hesv',
273
+ 'hesv_lwork'), (a1, b1))
274
+ lwork = _compute_lwork(hesv_lw, n, lower)
275
+ lu, ipvt, x, info = hesv(a1, b1, lwork=lwork,
276
+ lower=lower,
277
+ overwrite_a=overwrite_a,
278
+ overwrite_b=overwrite_b)
279
+ _solve_check(n, info)
280
+ rcond, info = hecon(lu, ipvt, anorm)
281
+ # Symmetric case 'sysv'
282
+ elif assume_a in {'symmetric', 'sym'}:
283
+ sycon, sysv, sysv_lw = get_lapack_funcs(('sycon', 'sysv',
284
+ 'sysv_lwork'), (a1, b1))
285
+ lwork = _compute_lwork(sysv_lw, n, lower)
286
+ lu, ipvt, x, info = sysv(a1, b1, lwork=lwork,
287
+ lower=lower,
288
+ overwrite_a=overwrite_a,
289
+ overwrite_b=overwrite_b)
290
+ _solve_check(n, info)
291
+ rcond, info = sycon(lu, ipvt, anorm)
292
+ # Diagonal case
293
+ elif assume_a == 'diagonal':
294
+ diag_a = np.diag(a1)
295
+ x = (b1.T / diag_a).T
296
+ abs_diag_a = np.abs(diag_a)
297
+ rcond = abs_diag_a.min() / abs_diag_a.max()
298
+ # Tri-diagonal case
299
+ elif assume_a == 'tridiagonal':
300
+ a1 = a1.T if transposed else a1
301
+ dl, d, du = np.diag(a1, -1), np.diag(a1, 0), np.diag(a1, 1)
302
+ _gttrf, _gttrs, _gtcon = get_lapack_funcs(('gttrf', 'gttrs', 'gtcon'), (a1, b1))
303
+ dl, d, du, du2, ipiv, info = _gttrf(dl, d, du)
304
+ _solve_check(n, info)
305
+ x, info = _gttrs(dl, d, du, du2, ipiv, b1, overwrite_b=overwrite_b)
306
+ _solve_check(n, info)
307
+ rcond, info = _gtcon(dl, d, du, du2, ipiv, anorm)
308
+ # Banded case
309
+ elif assume_a == 'banded':
310
+ a1, n_below, n_above = ((a1.T, n_above, n_below) if transposed
311
+ else (a1, n_below, n_above))
312
+ n_below, n_above = bandwidth(a1) if n_below is None else (n_below, n_above)
313
+ ab = _to_banded(n_below, n_above, a1)
314
+ gbsv, = get_lapack_funcs(('gbsv',), (a1, b1))
315
+ # Next two lines copied from `solve_banded`
316
+ a2 = np.zeros((2*n_below + n_above + 1, ab.shape[1]), dtype=gbsv.dtype)
317
+ a2[n_below:, :] = ab
318
+ _, _, x, info = gbsv(n_below, n_above, a2, b1,
319
+ overwrite_ab=True, overwrite_b=overwrite_b)
320
+ _solve_check(n, info)
321
+ # TODO: wrap gbcon and use to get rcond
322
+ # Triangular case
323
+ elif assume_a in {'lower triangular', 'upper triangular'}:
324
+ lower = assume_a == 'lower triangular'
325
+ x, info = _solve_triangular(a1, b1, lower=lower, overwrite_b=overwrite_b,
326
+ trans=transposed)
327
+ _solve_check(n, info)
328
+ _trcon = get_lapack_funcs(('trcon'), (a1, b1))
329
+ rcond, info = _trcon(a1, uplo='L' if lower else 'U')
330
+ # Positive definite case 'posv'
331
+ else:
332
+ pocon, posv = get_lapack_funcs(('pocon', 'posv'),
333
+ (a1, b1))
334
+ lu, x, info = posv(a1, b1, lower=lower,
335
+ overwrite_a=overwrite_a,
336
+ overwrite_b=overwrite_b)
337
+ _solve_check(n, info)
338
+ rcond, info = pocon(lu, anorm)
339
+
340
+ _solve_check(n, info, lamch, rcond)
341
+
342
+ if b_is_1D:
343
+ x = x.ravel()
344
+
345
+ return x
346
+
347
+
348
+ def _matrix_norm_diagonal(_, a, check_finite):
349
+ # Equivalent of dlange for diagonal matrix, assuming
350
+ # norm is either 'I' or '1' (really just not the Frobenius norm)
351
+ d = np.diag(a)
352
+ d = np.asarray_chkfinite(d) if check_finite else d
353
+ return np.abs(d).max()
354
+
355
+
356
+ def _matrix_norm_tridiagonal(norm, a, check_finite):
357
+ # Equivalent of dlange for tridiagonal matrix, assuming
358
+ # norm is either 'I' or '1'
359
+ if norm == 'I':
360
+ a = a.T
361
+ # Context to avoid warning before error in cases like -inf + inf
362
+ with np.errstate(invalid='ignore'):
363
+ d = np.abs(np.diag(a))
364
+ d[1:] += np.abs(np.diag(a, 1))
365
+ d[:-1] += np.abs(np.diag(a, -1))
366
+ d = np.asarray_chkfinite(d) if check_finite else d
367
+ return d.max()
368
+
369
+
370
+ def _matrix_norm_triangular(structure):
371
+ def fun(norm, a, check_finite):
372
+ a = np.asarray_chkfinite(a) if check_finite else a
373
+ lantr = get_lapack_funcs('lantr', (a,))
374
+ return lantr(norm, a, 'L' if structure == 'lower triangular' else 'U' )
375
+ return fun
376
+
377
+
378
+ def _matrix_norm_general(norm, a, check_finite):
379
+ a = np.asarray_chkfinite(a) if check_finite else a
380
+ lange = get_lapack_funcs('lange', (a,))
381
+ return lange(norm, a)
382
+
383
+
384
+ def _to_banded(n_below, n_above, a):
385
+ n = a.shape[0]
386
+ rows = n_above + n_below + 1
387
+ ab = np.zeros((rows, n), dtype=a.dtype)
388
+ ab[n_above] = np.diag(a)
389
+ for i in range(1, n_above + 1):
390
+ ab[n_above - i, i:] = np.diag(a, i)
391
+ for i in range(1, n_below + 1):
392
+ ab[n_above + i, :-i] = np.diag(a, -i)
393
+ return ab
394
+
395
+
396
+ def _ensure_dtype_cdsz(*arrays):
397
+ # Ensure that the dtype of arrays is one of the standard types
398
+ # compatible with LAPACK functions (single or double precision
399
+ # real or complex).
400
+ dtype = np.result_type(*arrays)
401
+ if not np.issubdtype(dtype, np.inexact):
402
+ return (array.astype(np.float64) for array in arrays)
403
+ complex = np.issubdtype(dtype, np.complexfloating)
404
+ if np.finfo(dtype).bits <= 32:
405
+ dtype = np.complex64 if complex else np.float32
406
+ elif np.finfo(dtype).bits >= 64:
407
+ dtype = np.complex128 if complex else np.float64
408
+ return (array.astype(dtype, copy=False) for array in arrays)
409
+
410
+
411
+ def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False,
412
+ overwrite_b=False, check_finite=True):
413
+ """
414
+ Solve the equation ``a x = b`` for `x`, assuming a is a triangular matrix.
415
+
416
+ Parameters
417
+ ----------
418
+ a : (M, M) array_like
419
+ A triangular matrix
420
+ b : (M,) or (M, N) array_like
421
+ Right-hand side matrix in ``a x = b``
422
+ lower : bool, optional
423
+ Use only data contained in the lower triangle of `a`.
424
+ Default is to use upper triangle.
425
+ trans : {0, 1, 2, 'N', 'T', 'C'}, optional
426
+ Type of system to solve:
427
+
428
+ ======== =========
429
+ trans system
430
+ ======== =========
431
+ 0 or 'N' a x = b
432
+ 1 or 'T' a^T x = b
433
+ 2 or 'C' a^H x = b
434
+ ======== =========
435
+ unit_diagonal : bool, optional
436
+ If True, diagonal elements of `a` are assumed to be 1 and
437
+ will not be referenced.
438
+ overwrite_b : bool, optional
439
+ Allow overwriting data in `b` (may enhance performance)
440
+ check_finite : bool, optional
441
+ Whether to check that the input matrices contain only finite numbers.
442
+ Disabling may give a performance gain, but may result in problems
443
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
444
+
445
+ Returns
446
+ -------
447
+ x : (M,) or (M, N) ndarray
448
+ Solution to the system ``a x = b``. Shape of return matches `b`.
449
+
450
+ Raises
451
+ ------
452
+ LinAlgError
453
+ If `a` is singular
454
+
455
+ Notes
456
+ -----
457
+ .. versionadded:: 0.9.0
458
+
459
+ Examples
460
+ --------
461
+ Solve the lower triangular system a x = b, where::
462
+
463
+ [3 0 0 0] [4]
464
+ a = [2 1 0 0] b = [2]
465
+ [1 0 1 0] [4]
466
+ [1 1 1 1] [2]
467
+
468
+ >>> import numpy as np
469
+ >>> from scipy.linalg import solve_triangular
470
+ >>> a = np.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]])
471
+ >>> b = np.array([4, 2, 4, 2])
472
+ >>> x = solve_triangular(a, b, lower=True)
473
+ >>> x
474
+ array([ 1.33333333, -0.66666667, 2.66666667, -1.33333333])
475
+ >>> a.dot(x) # Check the result
476
+ array([ 4., 2., 4., 2.])
477
+
478
+ """
479
+
480
+ a1 = _asarray_validated(a, check_finite=check_finite)
481
+ b1 = _asarray_validated(b, check_finite=check_finite)
482
+
483
+ if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
484
+ raise ValueError('expected square matrix')
485
+
486
+ if a1.shape[0] != b1.shape[0]:
487
+ raise ValueError(f'shapes of a {a1.shape} and b {b1.shape} are incompatible')
488
+
489
+ # accommodate empty arrays
490
+ if b1.size == 0:
491
+ dt_nonempty = solve_triangular(
492
+ np.eye(2, dtype=a1.dtype), np.ones(2, dtype=b1.dtype)
493
+ ).dtype
494
+ return np.empty_like(b1, dtype=dt_nonempty)
495
+
496
+ overwrite_b = overwrite_b or _datacopied(b1, b)
497
+
498
+ x, _ = _solve_triangular(a1, b1, trans, lower, unit_diagonal, overwrite_b)
499
+ return x
500
+
501
+
502
+ # solve_triangular without the input validation
503
+ def _solve_triangular(a1, b1, trans=0, lower=False, unit_diagonal=False,
504
+ overwrite_b=False):
505
+
506
+ trans = {'N': 0, 'T': 1, 'C': 2}.get(trans, trans)
507
+ trtrs, = get_lapack_funcs(('trtrs',), (a1, b1))
508
+ if a1.flags.f_contiguous or trans == 2:
509
+ x, info = trtrs(a1, b1, overwrite_b=overwrite_b, lower=lower,
510
+ trans=trans, unitdiag=unit_diagonal)
511
+ else:
512
+ # transposed system is solved since trtrs expects Fortran ordering
513
+ x, info = trtrs(a1.T, b1, overwrite_b=overwrite_b, lower=not lower,
514
+ trans=not trans, unitdiag=unit_diagonal)
515
+
516
+ if info == 0:
517
+ return x, info
518
+ if info > 0:
519
+ raise LinAlgError("singular matrix: resolution failed at diagonal %d" %
520
+ (info-1))
521
+ raise ValueError('illegal value in %dth argument of internal trtrs' %
522
+ (-info))
523
+
524
+
525
+ def solve_banded(l_and_u, ab, b, overwrite_ab=False, overwrite_b=False,
526
+ check_finite=True):
527
+ """
528
+ Solve the equation a x = b for x, assuming a is banded matrix.
529
+
530
+ The matrix a is stored in `ab` using the matrix diagonal ordered form::
531
+
532
+ ab[u + i - j, j] == a[i,j]
533
+
534
+ Example of `ab` (shape of a is (6,6), `u` =1, `l` =2)::
535
+
536
+ * a01 a12 a23 a34 a45
537
+ a00 a11 a22 a33 a44 a55
538
+ a10 a21 a32 a43 a54 *
539
+ a20 a31 a42 a53 * *
540
+
541
+ Parameters
542
+ ----------
543
+ (l, u) : (integer, integer)
544
+ Number of non-zero lower and upper diagonals
545
+ ab : (`l` + `u` + 1, M) array_like
546
+ Banded matrix
547
+ b : (M,) or (M, K) array_like
548
+ Right-hand side
549
+ overwrite_ab : bool, optional
550
+ Discard data in `ab` (may enhance performance)
551
+ overwrite_b : bool, optional
552
+ Discard data in `b` (may enhance performance)
553
+ check_finite : bool, optional
554
+ Whether to check that the input matrices contain only finite numbers.
555
+ Disabling may give a performance gain, but may result in problems
556
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
557
+
558
+ Returns
559
+ -------
560
+ x : (M,) or (M, K) ndarray
561
+ The solution to the system a x = b. Returned shape depends on the
562
+ shape of `b`.
563
+
564
+ Examples
565
+ --------
566
+ Solve the banded system a x = b, where::
567
+
568
+ [5 2 -1 0 0] [0]
569
+ [1 4 2 -1 0] [1]
570
+ a = [0 1 3 2 -1] b = [2]
571
+ [0 0 1 2 2] [2]
572
+ [0 0 0 1 1] [3]
573
+
574
+ There is one nonzero diagonal below the main diagonal (l = 1), and
575
+ two above (u = 2). The diagonal banded form of the matrix is::
576
+
577
+ [* * -1 -1 -1]
578
+ ab = [* 2 2 2 2]
579
+ [5 4 3 2 1]
580
+ [1 1 1 1 *]
581
+
582
+ >>> import numpy as np
583
+ >>> from scipy.linalg import solve_banded
584
+ >>> ab = np.array([[0, 0, -1, -1, -1],
585
+ ... [0, 2, 2, 2, 2],
586
+ ... [5, 4, 3, 2, 1],
587
+ ... [1, 1, 1, 1, 0]])
588
+ >>> b = np.array([0, 1, 2, 2, 3])
589
+ >>> x = solve_banded((1, 2), ab, b)
590
+ >>> x
591
+ array([-2.37288136, 3.93220339, -4. , 4.3559322 , -1.3559322 ])
592
+
593
+ """
594
+
595
+ a1 = _asarray_validated(ab, check_finite=check_finite, as_inexact=True)
596
+ b1 = _asarray_validated(b, check_finite=check_finite, as_inexact=True)
597
+
598
+ # Validate shapes.
599
+ if a1.shape[-1] != b1.shape[0]:
600
+ raise ValueError("shapes of ab and b are not compatible.")
601
+
602
+ (nlower, nupper) = l_and_u
603
+ if nlower + nupper + 1 != a1.shape[0]:
604
+ raise ValueError("invalid values for the number of lower and upper "
605
+ "diagonals: l+u+1 (%d) does not equal ab.shape[0] "
606
+ "(%d)" % (nlower + nupper + 1, ab.shape[0]))
607
+
608
+ # accommodate empty arrays
609
+ if b1.size == 0:
610
+ dt = solve(np.eye(1, dtype=a1.dtype), np.ones(1, dtype=b1.dtype)).dtype
611
+ return np.empty_like(b1, dtype=dt)
612
+
613
+ overwrite_b = overwrite_b or _datacopied(b1, b)
614
+ if a1.shape[-1] == 1:
615
+ b2 = np.array(b1, copy=(not overwrite_b))
616
+ # a1.shape[-1] == 1 -> original matrix is 1x1. Typically, the user
617
+ # will pass u = l = 0 and `a1` will be 1x1. However, the rest of the
618
+ # function works with unnecessary rows in `a1` as long as
619
+ # `a1[u + i - j, j] == a[i,j]`. In the 1x1 case, we want i = j = 0,
620
+ # so the diagonal is in row `u` of `a1`. See gh-8906.
621
+ b2 /= a1[nupper, 0]
622
+ return b2
623
+ if nlower == nupper == 1:
624
+ overwrite_ab = overwrite_ab or _datacopied(a1, ab)
625
+ gtsv, = get_lapack_funcs(('gtsv',), (a1, b1))
626
+ du = a1[0, 1:]
627
+ d = a1[1, :]
628
+ dl = a1[2, :-1]
629
+ du2, d, du, x, info = gtsv(dl, d, du, b1, overwrite_ab, overwrite_ab,
630
+ overwrite_ab, overwrite_b)
631
+ else:
632
+ gbsv, = get_lapack_funcs(('gbsv',), (a1, b1))
633
+ a2 = np.zeros((2*nlower + nupper + 1, a1.shape[1]), dtype=gbsv.dtype)
634
+ a2[nlower:, :] = a1
635
+ lu, piv, x, info = gbsv(nlower, nupper, a2, b1, overwrite_ab=True,
636
+ overwrite_b=overwrite_b)
637
+ if info == 0:
638
+ return x
639
+ if info > 0:
640
+ raise LinAlgError("singular matrix")
641
+ raise ValueError('illegal value in %d-th argument of internal '
642
+ 'gbsv/gtsv' % -info)
643
+
644
+
645
+ def solveh_banded(ab, b, overwrite_ab=False, overwrite_b=False, lower=False,
646
+ check_finite=True):
647
+ """
648
+ Solve equation a x = b. a is Hermitian positive-definite banded matrix.
649
+
650
+ Uses Thomas' Algorithm, which is more efficient than standard LU
651
+ factorization, but should only be used for Hermitian positive-definite
652
+ matrices.
653
+
654
+ The matrix ``a`` is stored in `ab` either in lower diagonal or upper
655
+ diagonal ordered form:
656
+
657
+ ab[u + i - j, j] == a[i,j] (if upper form; i <= j)
658
+ ab[ i - j, j] == a[i,j] (if lower form; i >= j)
659
+
660
+ Example of `ab` (shape of ``a`` is (6, 6), number of upper diagonals,
661
+ ``u`` =2)::
662
+
663
+ upper form:
664
+ * * a02 a13 a24 a35
665
+ * a01 a12 a23 a34 a45
666
+ a00 a11 a22 a33 a44 a55
667
+
668
+ lower form:
669
+ a00 a11 a22 a33 a44 a55
670
+ a10 a21 a32 a43 a54 *
671
+ a20 a31 a42 a53 * *
672
+
673
+ Cells marked with * are not used.
674
+
675
+ Parameters
676
+ ----------
677
+ ab : (``u`` + 1, M) array_like
678
+ Banded matrix
679
+ b : (M,) or (M, K) array_like
680
+ Right-hand side
681
+ overwrite_ab : bool, optional
682
+ Discard data in `ab` (may enhance performance)
683
+ overwrite_b : bool, optional
684
+ Discard data in `b` (may enhance performance)
685
+ lower : bool, optional
686
+ Is the matrix in the lower form. (Default is upper form)
687
+ check_finite : bool, optional
688
+ Whether to check that the input matrices contain only finite numbers.
689
+ Disabling may give a performance gain, but may result in problems
690
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
691
+
692
+ Returns
693
+ -------
694
+ x : (M,) or (M, K) ndarray
695
+ The solution to the system ``a x = b``. Shape of return matches shape
696
+ of `b`.
697
+
698
+ Notes
699
+ -----
700
+ In the case of a non-positive definite matrix ``a``, the solver
701
+ `solve_banded` may be used.
702
+
703
+ Examples
704
+ --------
705
+ Solve the banded system ``A x = b``, where::
706
+
707
+ [ 4 2 -1 0 0 0] [1]
708
+ [ 2 5 2 -1 0 0] [2]
709
+ A = [-1 2 6 2 -1 0] b = [2]
710
+ [ 0 -1 2 7 2 -1] [3]
711
+ [ 0 0 -1 2 8 2] [3]
712
+ [ 0 0 0 -1 2 9] [3]
713
+
714
+ >>> import numpy as np
715
+ >>> from scipy.linalg import solveh_banded
716
+
717
+ ``ab`` contains the main diagonal and the nonzero diagonals below the
718
+ main diagonal. That is, we use the lower form:
719
+
720
+ >>> ab = np.array([[ 4, 5, 6, 7, 8, 9],
721
+ ... [ 2, 2, 2, 2, 2, 0],
722
+ ... [-1, -1, -1, -1, 0, 0]])
723
+ >>> b = np.array([1, 2, 2, 3, 3, 3])
724
+ >>> x = solveh_banded(ab, b, lower=True)
725
+ >>> x
726
+ array([ 0.03431373, 0.45938375, 0.05602241, 0.47759104, 0.17577031,
727
+ 0.34733894])
728
+
729
+
730
+ Solve the Hermitian banded system ``H x = b``, where::
731
+
732
+ [ 8 2-1j 0 0 ] [ 1 ]
733
+ H = [2+1j 5 1j 0 ] b = [1+1j]
734
+ [ 0 -1j 9 -2-1j] [1-2j]
735
+ [ 0 0 -2+1j 6 ] [ 0 ]
736
+
737
+ In this example, we put the upper diagonals in the array ``hb``:
738
+
739
+ >>> hb = np.array([[0, 2-1j, 1j, -2-1j],
740
+ ... [8, 5, 9, 6 ]])
741
+ >>> b = np.array([1, 1+1j, 1-2j, 0])
742
+ >>> x = solveh_banded(hb, b)
743
+ >>> x
744
+ array([ 0.07318536-0.02939412j, 0.11877624+0.17696461j,
745
+ 0.10077984-0.23035393j, -0.00479904-0.09358128j])
746
+
747
+ """
748
+ a1 = _asarray_validated(ab, check_finite=check_finite)
749
+ b1 = _asarray_validated(b, check_finite=check_finite)
750
+
751
+ # Validate shapes.
752
+ if a1.shape[-1] != b1.shape[0]:
753
+ raise ValueError("shapes of ab and b are not compatible.")
754
+
755
+ # accommodate empty arrays
756
+ if b1.size == 0:
757
+ dt = solve(np.eye(1, dtype=a1.dtype), np.ones(1, dtype=b1.dtype)).dtype
758
+ return np.empty_like(b1, dtype=dt)
759
+
760
+ overwrite_b = overwrite_b or _datacopied(b1, b)
761
+ overwrite_ab = overwrite_ab or _datacopied(a1, ab)
762
+
763
+ if a1.shape[0] == 2:
764
+ ptsv, = get_lapack_funcs(('ptsv',), (a1, b1))
765
+ if lower:
766
+ d = a1[0, :].real
767
+ e = a1[1, :-1]
768
+ else:
769
+ d = a1[1, :].real
770
+ e = a1[0, 1:].conj()
771
+ d, du, x, info = ptsv(d, e, b1, overwrite_ab, overwrite_ab,
772
+ overwrite_b)
773
+ else:
774
+ pbsv, = get_lapack_funcs(('pbsv',), (a1, b1))
775
+ c, x, info = pbsv(a1, b1, lower=lower, overwrite_ab=overwrite_ab,
776
+ overwrite_b=overwrite_b)
777
+ if info > 0:
778
+ raise LinAlgError("%dth leading minor not positive definite" % info)
779
+ if info < 0:
780
+ raise ValueError('illegal value in %dth argument of internal '
781
+ 'pbsv' % -info)
782
+ return x
783
+
784
+
785
+ def solve_toeplitz(c_or_cr, b, check_finite=True):
786
+ r"""Solve a Toeplitz system using Levinson Recursion
787
+
788
+ The Toeplitz matrix has constant diagonals, with c as its first column
789
+ and r as its first row. If r is not given, ``r == conjugate(c)`` is
790
+ assumed.
791
+
792
+ .. warning::
793
+
794
+ Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
795
+ not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
796
+ before passing them to `solve_toeplitz`.
797
+
798
+ Parameters
799
+ ----------
800
+ c_or_cr : array_like or tuple of (array_like, array_like)
801
+ The vector ``c``, or a tuple of arrays (``c``, ``r``). If not
802
+ supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
803
+ real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
804
+ of the Toeplitz matrix is ``[c[0], r[1:]]``.
805
+ b : (M,) or (M, K) array_like
806
+ Right-hand side in ``T x = b``.
807
+ check_finite : bool, optional
808
+ Whether to check that the input matrices contain only finite numbers.
809
+ Disabling may give a performance gain, but may result in problems
810
+ (result entirely NaNs) if the inputs do contain infinities or NaNs.
811
+
812
+ Returns
813
+ -------
814
+ x : (M,) or (M, K) ndarray
815
+ The solution to the system ``T x = b``. Shape of return matches shape
816
+ of `b`.
817
+
818
+ See Also
819
+ --------
820
+ toeplitz : Toeplitz matrix
821
+
822
+ Notes
823
+ -----
824
+ The solution is computed using Levinson-Durbin recursion, which is faster
825
+ than generic least-squares methods, but can be less numerically stable.
826
+
827
+ Examples
828
+ --------
829
+ Solve the Toeplitz system T x = b, where::
830
+
831
+ [ 1 -1 -2 -3] [1]
832
+ T = [ 3 1 -1 -2] b = [2]
833
+ [ 6 3 1 -1] [2]
834
+ [10 6 3 1] [5]
835
+
836
+ To specify the Toeplitz matrix, only the first column and the first
837
+ row are needed.
838
+
839
+ >>> import numpy as np
840
+ >>> c = np.array([1, 3, 6, 10]) # First column of T
841
+ >>> r = np.array([1, -1, -2, -3]) # First row of T
842
+ >>> b = np.array([1, 2, 2, 5])
843
+
844
+ >>> from scipy.linalg import solve_toeplitz, toeplitz
845
+ >>> x = solve_toeplitz((c, r), b)
846
+ >>> x
847
+ array([ 1.66666667, -1. , -2.66666667, 2.33333333])
848
+
849
+ Check the result by creating the full Toeplitz matrix and
850
+ multiplying it by `x`. We should get `b`.
851
+
852
+ >>> T = toeplitz(c, r)
853
+ >>> T.dot(x)
854
+ array([ 1., 2., 2., 5.])
855
+
856
+ """
857
+ # If numerical stability of this algorithm is a problem, a future
858
+ # developer might consider implementing other O(N^2) Toeplitz solvers,
859
+ # such as GKO (https://www.jstor.org/stable/2153371) or Bareiss.
860
+
861
+ r, c, b, dtype, b_shape = _validate_args_for_toeplitz_ops(
862
+ c_or_cr, b, check_finite, keep_b_shape=True)
863
+
864
+ # accommodate empty arrays
865
+ if b.size == 0:
866
+ return np.empty_like(b)
867
+
868
+ # Form a 1-D array of values to be used in the matrix, containing a
869
+ # reversed copy of r[1:], followed by c.
870
+ vals = np.concatenate((r[-1:0:-1], c))
871
+ if b is None:
872
+ raise ValueError('illegal value, `b` is a required argument')
873
+
874
+ if b.ndim == 1:
875
+ x, _ = levinson(vals, np.ascontiguousarray(b))
876
+ else:
877
+ x = np.column_stack([levinson(vals, np.ascontiguousarray(b[:, i]))[0]
878
+ for i in range(b.shape[1])])
879
+ x = x.reshape(*b_shape)
880
+
881
+ return x
882
+
883
+
884
+ def _get_axis_len(aname, a, axis):
885
+ ax = axis
886
+ if ax < 0:
887
+ ax += a.ndim
888
+ if 0 <= ax < a.ndim:
889
+ return a.shape[ax]
890
+ raise ValueError(f"'{aname}axis' entry is out of bounds")
891
+
892
+
893
+ def solve_circulant(c, b, singular='raise', tol=None,
894
+ caxis=-1, baxis=0, outaxis=0):
895
+ """Solve C x = b for x, where C is a circulant matrix.
896
+
897
+ `C` is the circulant matrix associated with the vector `c`.
898
+
899
+ The system is solved by doing division in Fourier space. The
900
+ calculation is::
901
+
902
+ x = ifft(fft(b) / fft(c))
903
+
904
+ where `fft` and `ifft` are the fast Fourier transform and its inverse,
905
+ respectively. For a large vector `c`, this is *much* faster than
906
+ solving the system with the full circulant matrix.
907
+
908
+ Parameters
909
+ ----------
910
+ c : array_like
911
+ The coefficients of the circulant matrix.
912
+ b : array_like
913
+ Right-hand side matrix in ``a x = b``.
914
+ singular : str, optional
915
+ This argument controls how a near singular circulant matrix is
916
+ handled. If `singular` is "raise" and the circulant matrix is
917
+ near singular, a `LinAlgError` is raised. If `singular` is
918
+ "lstsq", the least squares solution is returned. Default is "raise".
919
+ tol : float, optional
920
+ If any eigenvalue of the circulant matrix has an absolute value
921
+ that is less than or equal to `tol`, the matrix is considered to be
922
+ near singular. If not given, `tol` is set to::
923
+
924
+ tol = abs_eigs.max() * abs_eigs.size * np.finfo(np.float64).eps
925
+
926
+ where `abs_eigs` is the array of absolute values of the eigenvalues
927
+ of the circulant matrix.
928
+ caxis : int
929
+ When `c` has dimension greater than 1, it is viewed as a collection
930
+ of circulant vectors. In this case, `caxis` is the axis of `c` that
931
+ holds the vectors of circulant coefficients.
932
+ baxis : int
933
+ When `b` has dimension greater than 1, it is viewed as a collection
934
+ of vectors. In this case, `baxis` is the axis of `b` that holds the
935
+ right-hand side vectors.
936
+ outaxis : int
937
+ When `c` or `b` are multidimensional, the value returned by
938
+ `solve_circulant` is multidimensional. In this case, `outaxis` is
939
+ the axis of the result that holds the solution vectors.
940
+
941
+ Returns
942
+ -------
943
+ x : ndarray
944
+ Solution to the system ``C x = b``.
945
+
946
+ Raises
947
+ ------
948
+ LinAlgError
949
+ If the circulant matrix associated with `c` is near singular.
950
+
951
+ See Also
952
+ --------
953
+ circulant : circulant matrix
954
+
955
+ Notes
956
+ -----
957
+ For a 1-D vector `c` with length `m`, and an array `b`
958
+ with shape ``(m, ...)``,
959
+
960
+ solve_circulant(c, b)
961
+
962
+ returns the same result as
963
+
964
+ solve(circulant(c), b)
965
+
966
+ where `solve` and `circulant` are from `scipy.linalg`.
967
+
968
+ .. versionadded:: 0.16.0
969
+
970
+ Examples
971
+ --------
972
+ >>> import numpy as np
973
+ >>> from scipy.linalg import solve_circulant, solve, circulant, lstsq
974
+
975
+ >>> c = np.array([2, 2, 4])
976
+ >>> b = np.array([1, 2, 3])
977
+ >>> solve_circulant(c, b)
978
+ array([ 0.75, -0.25, 0.25])
979
+
980
+ Compare that result to solving the system with `scipy.linalg.solve`:
981
+
982
+ >>> solve(circulant(c), b)
983
+ array([ 0.75, -0.25, 0.25])
984
+
985
+ A singular example:
986
+
987
+ >>> c = np.array([1, 1, 0, 0])
988
+ >>> b = np.array([1, 2, 3, 4])
989
+
990
+ Calling ``solve_circulant(c, b)`` will raise a `LinAlgError`. For the
991
+ least square solution, use the option ``singular='lstsq'``:
992
+
993
+ >>> solve_circulant(c, b, singular='lstsq')
994
+ array([ 0.25, 1.25, 2.25, 1.25])
995
+
996
+ Compare to `scipy.linalg.lstsq`:
997
+
998
+ >>> x, resid, rnk, s = lstsq(circulant(c), b)
999
+ >>> x
1000
+ array([ 0.25, 1.25, 2.25, 1.25])
1001
+
1002
+ A broadcasting example:
1003
+
1004
+ Suppose we have the vectors of two circulant matrices stored in an array
1005
+ with shape (2, 5), and three `b` vectors stored in an array with shape
1006
+ (3, 5). For example,
1007
+
1008
+ >>> c = np.array([[1.5, 2, 3, 0, 0], [1, 1, 4, 3, 2]])
1009
+ >>> b = np.arange(15).reshape(-1, 5)
1010
+
1011
+ We want to solve all combinations of circulant matrices and `b` vectors,
1012
+ with the result stored in an array with shape (2, 3, 5). When we
1013
+ disregard the axes of `c` and `b` that hold the vectors of coefficients,
1014
+ the shapes of the collections are (2,) and (3,), respectively, which are
1015
+ not compatible for broadcasting. To have a broadcast result with shape
1016
+ (2, 3), we add a trivial dimension to `c`: ``c[:, np.newaxis, :]`` has
1017
+ shape (2, 1, 5). The last dimension holds the coefficients of the
1018
+ circulant matrices, so when we call `solve_circulant`, we can use the
1019
+ default ``caxis=-1``. The coefficients of the `b` vectors are in the last
1020
+ dimension of the array `b`, so we use ``baxis=-1``. If we use the
1021
+ default `outaxis`, the result will have shape (5, 2, 3), so we'll use
1022
+ ``outaxis=-1`` to put the solution vectors in the last dimension.
1023
+
1024
+ >>> x = solve_circulant(c[:, np.newaxis, :], b, baxis=-1, outaxis=-1)
1025
+ >>> x.shape
1026
+ (2, 3, 5)
1027
+ >>> np.set_printoptions(precision=3) # For compact output of numbers.
1028
+ >>> x
1029
+ array([[[-0.118, 0.22 , 1.277, -0.142, 0.302],
1030
+ [ 0.651, 0.989, 2.046, 0.627, 1.072],
1031
+ [ 1.42 , 1.758, 2.816, 1.396, 1.841]],
1032
+ [[ 0.401, 0.304, 0.694, -0.867, 0.377],
1033
+ [ 0.856, 0.758, 1.149, -0.412, 0.831],
1034
+ [ 1.31 , 1.213, 1.603, 0.042, 1.286]]])
1035
+
1036
+ Check by solving one pair of `c` and `b` vectors (cf. ``x[1, 1, :]``):
1037
+
1038
+ >>> solve_circulant(c[1], b[1, :])
1039
+ array([ 0.856, 0.758, 1.149, -0.412, 0.831])
1040
+
1041
+ """
1042
+ c = np.atleast_1d(c)
1043
+ nc = _get_axis_len("c", c, caxis)
1044
+ b = np.atleast_1d(b)
1045
+ nb = _get_axis_len("b", b, baxis)
1046
+ if nc != nb:
1047
+ raise ValueError(f'Shapes of c {c.shape} and b {b.shape} are incompatible')
1048
+
1049
+ # accommodate empty arrays
1050
+ if b.size == 0:
1051
+ dt = solve_circulant(np.arange(3, dtype=c.dtype),
1052
+ np.ones(3, dtype=b.dtype)).dtype
1053
+ return np.empty_like(b, dtype=dt)
1054
+
1055
+ fc = np.fft.fft(np.moveaxis(c, caxis, -1), axis=-1)
1056
+ abs_fc = np.abs(fc)
1057
+ if tol is None:
1058
+ # This is the same tolerance as used in np.linalg.matrix_rank.
1059
+ tol = abs_fc.max(axis=-1) * nc * np.finfo(np.float64).eps
1060
+ if tol.shape != ():
1061
+ tol.shape = tol.shape + (1,)
1062
+ else:
1063
+ tol = np.atleast_1d(tol)
1064
+
1065
+ near_zeros = abs_fc <= tol
1066
+ is_near_singular = np.any(near_zeros)
1067
+ if is_near_singular:
1068
+ if singular == 'raise':
1069
+ raise LinAlgError("near singular circulant matrix.")
1070
+ else:
1071
+ # Replace the small values with 1 to avoid errors in the
1072
+ # division fb/fc below.
1073
+ fc[near_zeros] = 1
1074
+
1075
+ fb = np.fft.fft(np.moveaxis(b, baxis, -1), axis=-1)
1076
+
1077
+ q = fb / fc
1078
+
1079
+ if is_near_singular:
1080
+ # `near_zeros` is a boolean array, same shape as `c`, that is
1081
+ # True where `fc` is (near) zero. `q` is the broadcasted result
1082
+ # of fb / fc, so to set the values of `q` to 0 where `fc` is near
1083
+ # zero, we use a mask that is the broadcast result of an array
1084
+ # of True values shaped like `b` with `near_zeros`.
1085
+ mask = np.ones_like(b, dtype=bool) & near_zeros
1086
+ q[mask] = 0
1087
+
1088
+ x = np.fft.ifft(q, axis=-1)
1089
+ if not (np.iscomplexobj(c) or np.iscomplexobj(b)):
1090
+ x = x.real
1091
+ if outaxis != -1:
1092
+ x = np.moveaxis(x, -1, outaxis)
1093
+ return x
1094
+
1095
+
1096
+ # matrix inversion
1097
+ def inv(a, overwrite_a=False, check_finite=True):
1098
+ """
1099
+ Compute the inverse of a matrix.
1100
+
1101
+ Parameters
1102
+ ----------
1103
+ a : array_like
1104
+ Square matrix to be inverted.
1105
+ overwrite_a : bool, optional
1106
+ Discard data in `a` (may improve performance). Default is False.
1107
+ check_finite : bool, optional
1108
+ Whether to check that the input matrix contains only finite numbers.
1109
+ Disabling may give a performance gain, but may result in problems
1110
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
1111
+
1112
+ Returns
1113
+ -------
1114
+ ainv : ndarray
1115
+ Inverse of the matrix `a`.
1116
+
1117
+ Raises
1118
+ ------
1119
+ LinAlgError
1120
+ If `a` is singular.
1121
+ ValueError
1122
+ If `a` is not square, or not 2D.
1123
+
1124
+ Examples
1125
+ --------
1126
+ >>> import numpy as np
1127
+ >>> from scipy import linalg
1128
+ >>> a = np.array([[1., 2.], [3., 4.]])
1129
+ >>> linalg.inv(a)
1130
+ array([[-2. , 1. ],
1131
+ [ 1.5, -0.5]])
1132
+ >>> np.dot(a, linalg.inv(a))
1133
+ array([[ 1., 0.],
1134
+ [ 0., 1.]])
1135
+
1136
+ """
1137
+ a1 = _asarray_validated(a, check_finite=check_finite)
1138
+ if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
1139
+ raise ValueError('expected square matrix')
1140
+
1141
+ # accommodate empty square matrices
1142
+ if a1.size == 0:
1143
+ dt = inv(np.eye(2, dtype=a1.dtype)).dtype
1144
+ return np.empty_like(a1, dtype=dt)
1145
+
1146
+ overwrite_a = overwrite_a or _datacopied(a1, a)
1147
+ getrf, getri, getri_lwork = get_lapack_funcs(('getrf', 'getri',
1148
+ 'getri_lwork'),
1149
+ (a1,))
1150
+ lu, piv, info = getrf(a1, overwrite_a=overwrite_a)
1151
+ if info == 0:
1152
+ lwork = _compute_lwork(getri_lwork, a1.shape[0])
1153
+
1154
+ # XXX: the following line fixes curious SEGFAULT when
1155
+ # benchmarking 500x500 matrix inverse. This seems to
1156
+ # be a bug in LAPACK ?getri routine because if lwork is
1157
+ # minimal (when using lwork[0] instead of lwork[1]) then
1158
+ # all tests pass. Further investigation is required if
1159
+ # more such SEGFAULTs occur.
1160
+ lwork = int(1.01 * lwork)
1161
+ inv_a, info = getri(lu, piv, lwork=lwork, overwrite_lu=1)
1162
+ if info > 0:
1163
+ raise LinAlgError("singular matrix")
1164
+ if info < 0:
1165
+ raise ValueError('illegal value in %d-th argument of internal '
1166
+ 'getrf|getri' % -info)
1167
+ return inv_a
1168
+
1169
+
1170
+ # Determinant
1171
+
1172
+ def det(a, overwrite_a=False, check_finite=True):
1173
+ """
1174
+ Compute the determinant of a matrix
1175
+
1176
+ The determinant is a scalar that is a function of the associated square
1177
+ matrix coefficients. The determinant value is zero for singular matrices.
1178
+
1179
+ Parameters
1180
+ ----------
1181
+ a : (..., M, M) array_like
1182
+ Input array to compute determinants for.
1183
+ overwrite_a : bool, optional
1184
+ Allow overwriting data in a (may enhance performance).
1185
+ check_finite : bool, optional
1186
+ Whether to check that the input matrix contains only finite numbers.
1187
+ Disabling may give a performance gain, but may result in problems
1188
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
1189
+
1190
+ Returns
1191
+ -------
1192
+ det : (...) float or complex
1193
+ Determinant of `a`. For stacked arrays, a scalar is returned for each
1194
+ (m, m) slice in the last two dimensions of the input. For example, an
1195
+ input of shape (p, q, m, m) will produce a result of shape (p, q). If
1196
+ all dimensions are 1 a scalar is returned regardless of ndim.
1197
+
1198
+ Notes
1199
+ -----
1200
+ The determinant is computed by performing an LU factorization of the
1201
+ input with LAPACK routine 'getrf', and then calculating the product of
1202
+ diagonal entries of the U factor.
1203
+
1204
+ Even if the input array is single precision (float32 or complex64), the
1205
+ result will be returned in double precision (float64 or complex128) to
1206
+ prevent overflows.
1207
+
1208
+ Examples
1209
+ --------
1210
+ >>> import numpy as np
1211
+ >>> from scipy import linalg
1212
+ >>> a = np.array([[1,2,3], [4,5,6], [7,8,9]]) # A singular matrix
1213
+ >>> linalg.det(a)
1214
+ 0.0
1215
+ >>> b = np.array([[0,2,3], [4,5,6], [7,8,9]])
1216
+ >>> linalg.det(b)
1217
+ 3.0
1218
+ >>> # An array with the shape (3, 2, 2, 2)
1219
+ >>> c = np.array([[[[1., 2.], [3., 4.]],
1220
+ ... [[5., 6.], [7., 8.]]],
1221
+ ... [[[9., 10.], [11., 12.]],
1222
+ ... [[13., 14.], [15., 16.]]],
1223
+ ... [[[17., 18.], [19., 20.]],
1224
+ ... [[21., 22.], [23., 24.]]]])
1225
+ >>> linalg.det(c) # The resulting shape is (3, 2)
1226
+ array([[-2., -2.],
1227
+ [-2., -2.],
1228
+ [-2., -2.]])
1229
+ >>> linalg.det(c[0, 0]) # Confirm the (0, 0) slice, [[1, 2], [3, 4]]
1230
+ -2.0
1231
+ """
1232
+ # The goal is to end up with a writable contiguous array to pass to Cython
1233
+
1234
+ # First we check and make arrays.
1235
+ a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a)
1236
+ if a1.ndim < 2:
1237
+ raise ValueError('The input array must be at least two-dimensional.')
1238
+ if a1.shape[-1] != a1.shape[-2]:
1239
+ raise ValueError('Last 2 dimensions of the array must be square'
1240
+ f' but received shape {a1.shape}.')
1241
+
1242
+ # Also check if dtype is LAPACK compatible
1243
+ if a1.dtype.char not in 'fdFD':
1244
+ dtype_char = lapack_cast_dict[a1.dtype.char]
1245
+ if not dtype_char: # No casting possible
1246
+ raise TypeError(f'The dtype "{a1.dtype.name}" cannot be cast '
1247
+ 'to float(32, 64) or complex(64, 128).')
1248
+
1249
+ a1 = a1.astype(dtype_char[0]) # makes a copy, free to scratch
1250
+ overwrite_a = True
1251
+
1252
+ # Empty array has determinant 1 because math.
1253
+ if min(*a1.shape) == 0:
1254
+ dtyp = np.float64 if a1.dtype.char not in 'FD' else np.complex128
1255
+ if a1.ndim == 2:
1256
+ return dtyp(1.0)
1257
+ else:
1258
+ return np.ones(shape=a1.shape[:-2], dtype=dtyp)
1259
+
1260
+ # Scalar case
1261
+ if a1.shape[-2:] == (1, 1):
1262
+ a1 = a1[..., 0, 0]
1263
+ if a1.ndim == 0:
1264
+ a1 = a1[()]
1265
+ # Convert float32 to float64, and complex64 to complex128.
1266
+ if a1.dtype.char in 'dD':
1267
+ return a1
1268
+ return a1.astype('d') if a1.dtype.char == 'f' else a1.astype('D')
1269
+
1270
+ # Then check overwrite permission
1271
+ if not _datacopied(a1, a): # "a" still alive through "a1"
1272
+ if not overwrite_a:
1273
+ # Data belongs to "a" so make a copy
1274
+ a1 = a1.copy(order='C')
1275
+ # else: Do nothing we'll use "a" if possible
1276
+ # else: a1 has its own data thus free to scratch
1277
+
1278
+ # Then layout checks, might happen that overwrite is allowed but original
1279
+ # array was read-only or non-C-contiguous.
1280
+ if not (a1.flags['C_CONTIGUOUS'] and a1.flags['WRITEABLE']):
1281
+ a1 = a1.copy(order='C')
1282
+
1283
+ if a1.ndim == 2:
1284
+ det = find_det_from_lu(a1)
1285
+ # Convert float, complex to NumPy scalars
1286
+ return (np.float64(det) if np.isrealobj(det) else np.complex128(det))
1287
+
1288
+ # loop over the stacked array, and avoid overflows for single precision
1289
+ # Cf. np.linalg.det(np.diag([1e+38, 1e+38]).astype(np.float32))
1290
+ dtype_char = a1.dtype.char
1291
+ if dtype_char in 'fF':
1292
+ dtype_char = 'd' if dtype_char.islower() else 'D'
1293
+
1294
+ det = np.empty(a1.shape[:-2], dtype=dtype_char)
1295
+ for ind in product(*[range(x) for x in a1.shape[:-2]]):
1296
+ det[ind] = find_det_from_lu(a1[ind])
1297
+ return det
1298
+
1299
+
1300
+ # Linear Least Squares
1301
+ def lstsq(a, b, cond=None, overwrite_a=False, overwrite_b=False,
1302
+ check_finite=True, lapack_driver=None):
1303
+ """
1304
+ Compute least-squares solution to equation Ax = b.
1305
+
1306
+ Compute a vector x such that the 2-norm ``|b - A x|`` is minimized.
1307
+
1308
+ Parameters
1309
+ ----------
1310
+ a : (M, N) array_like
1311
+ Left-hand side array
1312
+ b : (M,) or (M, K) array_like
1313
+ Right hand side array
1314
+ cond : float, optional
1315
+ Cutoff for 'small' singular values; used to determine effective
1316
+ rank of a. Singular values smaller than
1317
+ ``cond * largest_singular_value`` are considered zero.
1318
+ overwrite_a : bool, optional
1319
+ Discard data in `a` (may enhance performance). Default is False.
1320
+ overwrite_b : bool, optional
1321
+ Discard data in `b` (may enhance performance). Default is False.
1322
+ check_finite : bool, optional
1323
+ Whether to check that the input matrices contain only finite numbers.
1324
+ Disabling may give a performance gain, but may result in problems
1325
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
1326
+ lapack_driver : str, optional
1327
+ Which LAPACK driver is used to solve the least-squares problem.
1328
+ Options are ``'gelsd'``, ``'gelsy'``, ``'gelss'``. Default
1329
+ (``'gelsd'``) is a good choice. However, ``'gelsy'`` can be slightly
1330
+ faster on many problems. ``'gelss'`` was used historically. It is
1331
+ generally slow but uses less memory.
1332
+
1333
+ .. versionadded:: 0.17.0
1334
+
1335
+ Returns
1336
+ -------
1337
+ x : (N,) or (N, K) ndarray
1338
+ Least-squares solution.
1339
+ residues : (K,) ndarray or float
1340
+ Square of the 2-norm for each column in ``b - a x``, if ``M > N`` and
1341
+ ``rank(A) == n`` (returns a scalar if ``b`` is 1-D). Otherwise a
1342
+ (0,)-shaped array is returned.
1343
+ rank : int
1344
+ Effective rank of `a`.
1345
+ s : (min(M, N),) ndarray or None
1346
+ Singular values of `a`. The condition number of ``a`` is
1347
+ ``s[0] / s[-1]``.
1348
+
1349
+ Raises
1350
+ ------
1351
+ LinAlgError
1352
+ If computation does not converge.
1353
+
1354
+ ValueError
1355
+ When parameters are not compatible.
1356
+
1357
+ See Also
1358
+ --------
1359
+ scipy.optimize.nnls : linear least squares with non-negativity constraint
1360
+
1361
+ Notes
1362
+ -----
1363
+ When ``'gelsy'`` is used as a driver, `residues` is set to a (0,)-shaped
1364
+ array and `s` is always ``None``.
1365
+
1366
+ Examples
1367
+ --------
1368
+ >>> import numpy as np
1369
+ >>> from scipy.linalg import lstsq
1370
+ >>> import matplotlib.pyplot as plt
1371
+
1372
+ Suppose we have the following data:
1373
+
1374
+ >>> x = np.array([1, 2.5, 3.5, 4, 5, 7, 8.5])
1375
+ >>> y = np.array([0.3, 1.1, 1.5, 2.0, 3.2, 6.6, 8.6])
1376
+
1377
+ We want to fit a quadratic polynomial of the form ``y = a + b*x**2``
1378
+ to this data. We first form the "design matrix" M, with a constant
1379
+ column of 1s and a column containing ``x**2``:
1380
+
1381
+ >>> M = x[:, np.newaxis]**[0, 2]
1382
+ >>> M
1383
+ array([[ 1. , 1. ],
1384
+ [ 1. , 6.25],
1385
+ [ 1. , 12.25],
1386
+ [ 1. , 16. ],
1387
+ [ 1. , 25. ],
1388
+ [ 1. , 49. ],
1389
+ [ 1. , 72.25]])
1390
+
1391
+ We want to find the least-squares solution to ``M.dot(p) = y``,
1392
+ where ``p`` is a vector with length 2 that holds the parameters
1393
+ ``a`` and ``b``.
1394
+
1395
+ >>> p, res, rnk, s = lstsq(M, y)
1396
+ >>> p
1397
+ array([ 0.20925829, 0.12013861])
1398
+
1399
+ Plot the data and the fitted curve.
1400
+
1401
+ >>> plt.plot(x, y, 'o', label='data')
1402
+ >>> xx = np.linspace(0, 9, 101)
1403
+ >>> yy = p[0] + p[1]*xx**2
1404
+ >>> plt.plot(xx, yy, label='least squares fit, $y = a + bx^2$')
1405
+ >>> plt.xlabel('x')
1406
+ >>> plt.ylabel('y')
1407
+ >>> plt.legend(framealpha=1, shadow=True)
1408
+ >>> plt.grid(alpha=0.25)
1409
+ >>> plt.show()
1410
+
1411
+ """
1412
+ a1 = _asarray_validated(a, check_finite=check_finite)
1413
+ b1 = _asarray_validated(b, check_finite=check_finite)
1414
+ if len(a1.shape) != 2:
1415
+ raise ValueError('Input array a should be 2D')
1416
+ m, n = a1.shape
1417
+ if len(b1.shape) == 2:
1418
+ nrhs = b1.shape[1]
1419
+ else:
1420
+ nrhs = 1
1421
+ if m != b1.shape[0]:
1422
+ raise ValueError('Shape mismatch: a and b should have the same number'
1423
+ f' of rows ({m} != {b1.shape[0]}).')
1424
+ if m == 0 or n == 0: # Zero-sized problem, confuses LAPACK
1425
+ x = np.zeros((n,) + b1.shape[1:], dtype=np.common_type(a1, b1))
1426
+ if n == 0:
1427
+ residues = np.linalg.norm(b1, axis=0)**2
1428
+ else:
1429
+ residues = np.empty((0,))
1430
+ return x, residues, 0, np.empty((0,))
1431
+
1432
+ driver = lapack_driver
1433
+ if driver is None:
1434
+ driver = lstsq.default_lapack_driver
1435
+ if driver not in ('gelsd', 'gelsy', 'gelss'):
1436
+ raise ValueError(f'LAPACK driver "{driver}" is not found')
1437
+
1438
+ lapack_func, lapack_lwork = get_lapack_funcs((driver,
1439
+ f'{driver}_lwork'),
1440
+ (a1, b1))
1441
+ real_data = True if (lapack_func.dtype.kind == 'f') else False
1442
+
1443
+ if m < n:
1444
+ # need to extend b matrix as it will be filled with
1445
+ # a larger solution matrix
1446
+ if len(b1.shape) == 2:
1447
+ b2 = np.zeros((n, nrhs), dtype=lapack_func.dtype)
1448
+ b2[:m, :] = b1
1449
+ else:
1450
+ b2 = np.zeros(n, dtype=lapack_func.dtype)
1451
+ b2[:m] = b1
1452
+ b1 = b2
1453
+
1454
+ overwrite_a = overwrite_a or _datacopied(a1, a)
1455
+ overwrite_b = overwrite_b or _datacopied(b1, b)
1456
+
1457
+ if cond is None:
1458
+ cond = np.finfo(lapack_func.dtype).eps
1459
+
1460
+ if driver in ('gelss', 'gelsd'):
1461
+ if driver == 'gelss':
1462
+ lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
1463
+ v, x, s, rank, work, info = lapack_func(a1, b1, cond, lwork,
1464
+ overwrite_a=overwrite_a,
1465
+ overwrite_b=overwrite_b)
1466
+
1467
+ elif driver == 'gelsd':
1468
+ if real_data:
1469
+ lwork, iwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
1470
+ x, s, rank, info = lapack_func(a1, b1, lwork,
1471
+ iwork, cond, False, False)
1472
+ else: # complex data
1473
+ lwork, rwork, iwork = _compute_lwork(lapack_lwork, m, n,
1474
+ nrhs, cond)
1475
+ x, s, rank, info = lapack_func(a1, b1, lwork, rwork, iwork,
1476
+ cond, False, False)
1477
+ if info > 0:
1478
+ raise LinAlgError("SVD did not converge in Linear Least Squares")
1479
+ if info < 0:
1480
+ raise ValueError('illegal value in %d-th argument of internal %s'
1481
+ % (-info, lapack_driver))
1482
+ resids = np.asarray([], dtype=x.dtype)
1483
+ if m > n:
1484
+ x1 = x[:n]
1485
+ if rank == n:
1486
+ resids = np.sum(np.abs(x[n:])**2, axis=0)
1487
+ x = x1
1488
+ return x, resids, rank, s
1489
+
1490
+ elif driver == 'gelsy':
1491
+ lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
1492
+ jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
1493
+ v, x, j, rank, info = lapack_func(a1, b1, jptv, cond,
1494
+ lwork, False, False)
1495
+ if info < 0:
1496
+ raise ValueError("illegal value in %d-th argument of internal "
1497
+ "gelsy" % -info)
1498
+ if m > n:
1499
+ x1 = x[:n]
1500
+ x = x1
1501
+ return x, np.array([], x.dtype), rank, None
1502
+
1503
+
1504
+ lstsq.default_lapack_driver = 'gelsd'
1505
+
1506
+
1507
+ def pinv(a, *, atol=None, rtol=None, return_rank=False, check_finite=True):
1508
+ """
1509
+ Compute the (Moore-Penrose) pseudo-inverse of a matrix.
1510
+
1511
+ Calculate a generalized inverse of a matrix using its
1512
+ singular-value decomposition ``U @ S @ V`` in the economy mode and picking
1513
+ up only the columns/rows that are associated with significant singular
1514
+ values.
1515
+
1516
+ If ``s`` is the maximum singular value of ``a``, then the
1517
+ significance cut-off value is determined by ``atol + rtol * s``. Any
1518
+ singular value below this value is assumed insignificant.
1519
+
1520
+ Parameters
1521
+ ----------
1522
+ a : (M, N) array_like
1523
+ Matrix to be pseudo-inverted.
1524
+ atol : float, optional
1525
+ Absolute threshold term, default value is 0.
1526
+
1527
+ .. versionadded:: 1.7.0
1528
+
1529
+ rtol : float, optional
1530
+ Relative threshold term, default value is ``max(M, N) * eps`` where
1531
+ ``eps`` is the machine precision value of the datatype of ``a``.
1532
+
1533
+ .. versionadded:: 1.7.0
1534
+
1535
+ return_rank : bool, optional
1536
+ If True, return the effective rank of the matrix.
1537
+ check_finite : bool, optional
1538
+ Whether to check that the input matrix contains only finite numbers.
1539
+ Disabling may give a performance gain, but may result in problems
1540
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
1541
+
1542
+ Returns
1543
+ -------
1544
+ B : (N, M) ndarray
1545
+ The pseudo-inverse of matrix `a`.
1546
+ rank : int
1547
+ The effective rank of the matrix. Returned if `return_rank` is True.
1548
+
1549
+ Raises
1550
+ ------
1551
+ LinAlgError
1552
+ If SVD computation does not converge.
1553
+
1554
+ See Also
1555
+ --------
1556
+ pinvh : Moore-Penrose pseudoinverse of a hermitian matrix.
1557
+
1558
+ Notes
1559
+ -----
1560
+ If ``A`` is invertible then the Moore-Penrose pseudoinverse is exactly
1561
+ the inverse of ``A`` [1]_. If ``A`` is not invertible then the
1562
+ Moore-Penrose pseudoinverse computes the ``x`` solution to ``Ax = b`` such
1563
+ that ``||Ax - b||`` is minimized [1]_.
1564
+
1565
+ References
1566
+ ----------
1567
+ .. [1] Penrose, R. (1956). On best approximate solutions of linear matrix
1568
+ equations. Mathematical Proceedings of the Cambridge Philosophical
1569
+ Society, 52(1), 17-19. doi:10.1017/S0305004100030929
1570
+
1571
+ Examples
1572
+ --------
1573
+
1574
+ Given an ``m x n`` matrix ``A`` and an ``n x m`` matrix ``B`` the four
1575
+ Moore-Penrose conditions are:
1576
+
1577
+ 1. ``ABA = A`` (``B`` is a generalized inverse of ``A``),
1578
+ 2. ``BAB = B`` (``A`` is a generalized inverse of ``B``),
1579
+ 3. ``(AB)* = AB`` (``AB`` is hermitian),
1580
+ 4. ``(BA)* = BA`` (``BA`` is hermitian) [1]_.
1581
+
1582
+ Here, ``A*`` denotes the conjugate transpose. The Moore-Penrose
1583
+ pseudoinverse is a unique ``B`` that satisfies all four of these
1584
+ conditions and exists for any ``A``. Note that, unlike the standard
1585
+ matrix inverse, ``A`` does not have to be a square matrix or have
1586
+ linearly independent columns/rows.
1587
+
1588
+ As an example, we can calculate the Moore-Penrose pseudoinverse of a
1589
+ random non-square matrix and verify it satisfies the four conditions.
1590
+
1591
+ >>> import numpy as np
1592
+ >>> from scipy import linalg
1593
+ >>> rng = np.random.default_rng()
1594
+ >>> A = rng.standard_normal((9, 6))
1595
+ >>> B = linalg.pinv(A)
1596
+ >>> np.allclose(A @ B @ A, A) # Condition 1
1597
+ True
1598
+ >>> np.allclose(B @ A @ B, B) # Condition 2
1599
+ True
1600
+ >>> np.allclose((A @ B).conj().T, A @ B) # Condition 3
1601
+ True
1602
+ >>> np.allclose((B @ A).conj().T, B @ A) # Condition 4
1603
+ True
1604
+
1605
+ """
1606
+ a = _asarray_validated(a, check_finite=check_finite)
1607
+ u, s, vh = _decomp_svd.svd(a, full_matrices=False, check_finite=False)
1608
+ t = u.dtype.char.lower()
1609
+ maxS = np.max(s, initial=0.)
1610
+
1611
+ atol = 0. if atol is None else atol
1612
+ rtol = max(a.shape) * np.finfo(t).eps if (rtol is None) else rtol
1613
+
1614
+ if (atol < 0.) or (rtol < 0.):
1615
+ raise ValueError("atol and rtol values must be positive.")
1616
+
1617
+ val = atol + maxS * rtol
1618
+ rank = np.sum(s > val)
1619
+
1620
+ u = u[:, :rank]
1621
+ u /= s[:rank]
1622
+ B = (u @ vh[:rank]).conj().T
1623
+
1624
+ if return_rank:
1625
+ return B, rank
1626
+ else:
1627
+ return B
1628
+
1629
+
1630
+ def pinvh(a, atol=None, rtol=None, lower=True, return_rank=False,
1631
+ check_finite=True):
1632
+ """
1633
+ Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix.
1634
+
1635
+ Calculate a generalized inverse of a complex Hermitian/real symmetric
1636
+ matrix using its eigenvalue decomposition and including all eigenvalues
1637
+ with 'large' absolute value.
1638
+
1639
+ Parameters
1640
+ ----------
1641
+ a : (N, N) array_like
1642
+ Real symmetric or complex hermetian matrix to be pseudo-inverted
1643
+
1644
+ atol : float, optional
1645
+ Absolute threshold term, default value is 0.
1646
+
1647
+ .. versionadded:: 1.7.0
1648
+
1649
+ rtol : float, optional
1650
+ Relative threshold term, default value is ``N * eps`` where
1651
+ ``eps`` is the machine precision value of the datatype of ``a``.
1652
+
1653
+ .. versionadded:: 1.7.0
1654
+
1655
+ lower : bool, optional
1656
+ Whether the pertinent array data is taken from the lower or upper
1657
+ triangle of `a`. (Default: lower)
1658
+ return_rank : bool, optional
1659
+ If True, return the effective rank of the matrix.
1660
+ check_finite : bool, optional
1661
+ Whether to check that the input matrix contains only finite numbers.
1662
+ Disabling may give a performance gain, but may result in problems
1663
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
1664
+
1665
+ Returns
1666
+ -------
1667
+ B : (N, N) ndarray
1668
+ The pseudo-inverse of matrix `a`.
1669
+ rank : int
1670
+ The effective rank of the matrix. Returned if `return_rank` is True.
1671
+
1672
+ Raises
1673
+ ------
1674
+ LinAlgError
1675
+ If eigenvalue algorithm does not converge.
1676
+
1677
+ See Also
1678
+ --------
1679
+ pinv : Moore-Penrose pseudoinverse of a matrix.
1680
+
1681
+ Examples
1682
+ --------
1683
+
1684
+ For a more detailed example see `pinv`.
1685
+
1686
+ >>> import numpy as np
1687
+ >>> from scipy.linalg import pinvh
1688
+ >>> rng = np.random.default_rng()
1689
+ >>> a = rng.standard_normal((9, 6))
1690
+ >>> a = np.dot(a, a.T)
1691
+ >>> B = pinvh(a)
1692
+ >>> np.allclose(a, a @ B @ a)
1693
+ True
1694
+ >>> np.allclose(B, B @ a @ B)
1695
+ True
1696
+
1697
+ """
1698
+ a = _asarray_validated(a, check_finite=check_finite)
1699
+ s, u = _decomp.eigh(a, lower=lower, check_finite=False, driver='ev')
1700
+ t = u.dtype.char.lower()
1701
+ maxS = np.max(np.abs(s), initial=0.)
1702
+
1703
+ atol = 0. if atol is None else atol
1704
+ rtol = max(a.shape) * np.finfo(t).eps if (rtol is None) else rtol
1705
+
1706
+ if (atol < 0.) or (rtol < 0.):
1707
+ raise ValueError("atol and rtol values must be positive.")
1708
+
1709
+ val = atol + maxS * rtol
1710
+ above_cutoff = (abs(s) > val)
1711
+
1712
+ psigma_diag = 1.0 / s[above_cutoff]
1713
+ u = u[:, above_cutoff]
1714
+
1715
+ B = (u * psigma_diag) @ u.conj().T
1716
+
1717
+ if return_rank:
1718
+ return B, len(psigma_diag)
1719
+ else:
1720
+ return B
1721
+
1722
+
1723
+ def matrix_balance(A, permute=True, scale=True, separate=False,
1724
+ overwrite_a=False):
1725
+ """
1726
+ Compute a diagonal similarity transformation for row/column balancing.
1727
+
1728
+ The balancing tries to equalize the row and column 1-norms by applying
1729
+ a similarity transformation such that the magnitude variation of the
1730
+ matrix entries is reflected to the scaling matrices.
1731
+
1732
+ Moreover, if enabled, the matrix is first permuted to isolate the upper
1733
+ triangular parts of the matrix and, again if scaling is also enabled,
1734
+ only the remaining subblocks are subjected to scaling.
1735
+
1736
+ The balanced matrix satisfies the following equality
1737
+
1738
+ .. math::
1739
+
1740
+ B = T^{-1} A T
1741
+
1742
+ The scaling coefficients are approximated to the nearest power of 2
1743
+ to avoid round-off errors.
1744
+
1745
+ Parameters
1746
+ ----------
1747
+ A : (n, n) array_like
1748
+ Square data matrix for the balancing.
1749
+ permute : bool, optional
1750
+ The selector to define whether permutation of A is also performed
1751
+ prior to scaling.
1752
+ scale : bool, optional
1753
+ The selector to turn on and off the scaling. If False, the matrix
1754
+ will not be scaled.
1755
+ separate : bool, optional
1756
+ This switches from returning a full matrix of the transformation
1757
+ to a tuple of two separate 1-D permutation and scaling arrays.
1758
+ overwrite_a : bool, optional
1759
+ This is passed to xGEBAL directly. Essentially, overwrites the result
1760
+ to the data. It might increase the space efficiency. See LAPACK manual
1761
+ for details. This is False by default.
1762
+
1763
+ Returns
1764
+ -------
1765
+ B : (n, n) ndarray
1766
+ Balanced matrix
1767
+ T : (n, n) ndarray
1768
+ A possibly permuted diagonal matrix whose nonzero entries are
1769
+ integer powers of 2 to avoid numerical truncation errors.
1770
+ scale, perm : (n,) ndarray
1771
+ If ``separate`` keyword is set to True then instead of the array
1772
+ ``T`` above, the scaling and the permutation vectors are given
1773
+ separately as a tuple without allocating the full array ``T``.
1774
+
1775
+ Notes
1776
+ -----
1777
+ This algorithm is particularly useful for eigenvalue and matrix
1778
+ decompositions and in many cases it is already called by various
1779
+ LAPACK routines.
1780
+
1781
+ The algorithm is based on the well-known technique of [1]_ and has
1782
+ been modified to account for special cases. See [2]_ for details
1783
+ which have been implemented since LAPACK v3.5.0. Before this version
1784
+ there are corner cases where balancing can actually worsen the
1785
+ conditioning. See [3]_ for such examples.
1786
+
1787
+ The code is a wrapper around LAPACK's xGEBAL routine family for matrix
1788
+ balancing.
1789
+
1790
+ .. versionadded:: 0.19.0
1791
+
1792
+ References
1793
+ ----------
1794
+ .. [1] B.N. Parlett and C. Reinsch, "Balancing a Matrix for
1795
+ Calculation of Eigenvalues and Eigenvectors", Numerische Mathematik,
1796
+ Vol.13(4), 1969, :doi:`10.1007/BF02165404`
1797
+ .. [2] R. James, J. Langou, B.R. Lowery, "On matrix balancing and
1798
+ eigenvector computation", 2014, :arxiv:`1401.5766`
1799
+ .. [3] D.S. Watkins. A case where balancing is harmful.
1800
+ Electron. Trans. Numer. Anal, Vol.23, 2006.
1801
+
1802
+ Examples
1803
+ --------
1804
+ >>> import numpy as np
1805
+ >>> from scipy import linalg
1806
+ >>> x = np.array([[1,2,0], [9,1,0.01], [1,2,10*np.pi]])
1807
+
1808
+ >>> y, permscale = linalg.matrix_balance(x)
1809
+ >>> np.abs(x).sum(axis=0) / np.abs(x).sum(axis=1)
1810
+ array([ 3.66666667, 0.4995005 , 0.91312162])
1811
+
1812
+ >>> np.abs(y).sum(axis=0) / np.abs(y).sum(axis=1)
1813
+ array([ 1.2 , 1.27041742, 0.92658316]) # may vary
1814
+
1815
+ >>> permscale # only powers of 2 (0.5 == 2^(-1))
1816
+ array([[ 0.5, 0. , 0. ], # may vary
1817
+ [ 0. , 1. , 0. ],
1818
+ [ 0. , 0. , 1. ]])
1819
+
1820
+ """
1821
+
1822
+ A = np.atleast_2d(_asarray_validated(A, check_finite=True))
1823
+
1824
+ if not np.equal(*A.shape):
1825
+ raise ValueError('The data matrix for balancing should be square.')
1826
+
1827
+ # accommodate empty arrays
1828
+ if A.size == 0:
1829
+ b_n, t_n = matrix_balance(np.eye(2, dtype=A.dtype))
1830
+ B = np.empty_like(A, dtype=b_n.dtype)
1831
+ if separate:
1832
+ scaling = np.ones_like(A, shape=len(A))
1833
+ perm = np.arange(len(A))
1834
+ return B, (scaling, perm)
1835
+ return B, np.empty_like(A, dtype=t_n.dtype)
1836
+
1837
+ gebal = get_lapack_funcs(('gebal'), (A,))
1838
+ B, lo, hi, ps, info = gebal(A, scale=scale, permute=permute,
1839
+ overwrite_a=overwrite_a)
1840
+
1841
+ if info < 0:
1842
+ raise ValueError('xGEBAL exited with the internal error '
1843
+ f'"illegal value in argument number {-info}.". See '
1844
+ 'LAPACK documentation for the xGEBAL error codes.')
1845
+
1846
+ # Separate the permutations from the scalings and then convert to int
1847
+ scaling = np.ones_like(ps, dtype=float)
1848
+ scaling[lo:hi+1] = ps[lo:hi+1]
1849
+
1850
+ # gebal uses 1-indexing
1851
+ ps = ps.astype(int, copy=False) - 1
1852
+ n = A.shape[0]
1853
+ perm = np.arange(n)
1854
+
1855
+ # LAPACK permutes with the ordering n --> hi, then 0--> lo
1856
+ if hi < n:
1857
+ for ind, x in enumerate(ps[hi+1:][::-1], 1):
1858
+ if n-ind == x:
1859
+ continue
1860
+ perm[[x, n-ind]] = perm[[n-ind, x]]
1861
+
1862
+ if lo > 0:
1863
+ for ind, x in enumerate(ps[:lo]):
1864
+ if ind == x:
1865
+ continue
1866
+ perm[[x, ind]] = perm[[ind, x]]
1867
+
1868
+ if separate:
1869
+ return B, (scaling, perm)
1870
+
1871
+ # get the inverse permutation
1872
+ iperm = np.empty_like(perm)
1873
+ iperm[perm] = np.arange(n)
1874
+
1875
+ return B, np.diag(scaling)[iperm, :]
1876
+
1877
+
1878
+ def _validate_args_for_toeplitz_ops(c_or_cr, b, check_finite, keep_b_shape,
1879
+ enforce_square=True):
1880
+ """Validate arguments and format inputs for toeplitz functions
1881
+
1882
+ Parameters
1883
+ ----------
1884
+ c_or_cr : array_like or tuple of (array_like, array_like)
1885
+ The vector ``c``, or a tuple of arrays (``c``, ``r``). Whatever the
1886
+ actual shape of ``c``, it will be converted to a 1-D array. If not
1887
+ supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
1888
+ real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
1889
+ of the Toeplitz matrix is ``[c[0], r[1:]]``. Whatever the actual shape
1890
+ of ``r``, it will be converted to a 1-D array.
1891
+ b : (M,) or (M, K) array_like
1892
+ Right-hand side in ``T x = b``.
1893
+ check_finite : bool
1894
+ Whether to check that the input matrices contain only finite numbers.
1895
+ Disabling may give a performance gain, but may result in problems
1896
+ (result entirely NaNs) if the inputs do contain infinities or NaNs.
1897
+ keep_b_shape : bool
1898
+ Whether to convert a (M,) dimensional b into a (M, 1) dimensional
1899
+ matrix.
1900
+ enforce_square : bool, optional
1901
+ If True (default), this verifies that the Toeplitz matrix is square.
1902
+
1903
+ Returns
1904
+ -------
1905
+ r : array
1906
+ 1d array corresponding to the first row of the Toeplitz matrix.
1907
+ c: array
1908
+ 1d array corresponding to the first column of the Toeplitz matrix.
1909
+ b: array
1910
+ (M,), (M, 1) or (M, K) dimensional array, post validation,
1911
+ corresponding to ``b``.
1912
+ dtype: numpy datatype
1913
+ ``dtype`` stores the datatype of ``r``, ``c`` and ``b``. If any of
1914
+ ``r``, ``c`` or ``b`` are complex, ``dtype`` is ``np.complex128``,
1915
+ otherwise, it is ``np.float``.
1916
+ b_shape: tuple
1917
+ Shape of ``b`` after passing it through ``_asarray_validated``.
1918
+
1919
+ """
1920
+
1921
+ if isinstance(c_or_cr, tuple):
1922
+ c, r = c_or_cr
1923
+ c = _asarray_validated(c, check_finite=check_finite)
1924
+ r = _asarray_validated(r, check_finite=check_finite)
1925
+ else:
1926
+ c = _asarray_validated(c_or_cr, check_finite=check_finite)
1927
+ r = c.conjugate()
1928
+
1929
+ if c.ndim > 1 or r.ndim > 1:
1930
+ msg = ("Beginning in SciPy 1.17, multidimensional input will be treated as a "
1931
+ "batch, not `ravel`ed. To preserve the existing behavior and silence "
1932
+ "this warning, `ravel` arguments before passing them to "
1933
+ "`toeplitz`, `matmul_toeplitz`, and `solve_toeplitz`.")
1934
+ warnings.warn(msg, FutureWarning, stacklevel=2)
1935
+ c = c.ravel()
1936
+ r = r.ravel()
1937
+
1938
+ if b is None:
1939
+ raise ValueError('`b` must be an array, not None.')
1940
+
1941
+ b = _asarray_validated(b, check_finite=check_finite)
1942
+ b_shape = b.shape
1943
+
1944
+ is_not_square = r.shape[0] != c.shape[0]
1945
+ if (enforce_square and is_not_square) or b.shape[0] != r.shape[0]:
1946
+ raise ValueError('Incompatible dimensions.')
1947
+
1948
+ is_cmplx = np.iscomplexobj(r) or np.iscomplexobj(c) or np.iscomplexobj(b)
1949
+ dtype = np.complex128 if is_cmplx else np.float64
1950
+ r, c, b = (np.asarray(i, dtype=dtype) for i in (r, c, b))
1951
+
1952
+ if b.ndim == 1 and not keep_b_shape:
1953
+ b = b.reshape(-1, 1)
1954
+ elif b.ndim != 1:
1955
+ b = b.reshape(b.shape[0], -1 if b.size > 0 else 0)
1956
+
1957
+ return r, c, b, dtype, b_shape
1958
+
1959
+
1960
+ def matmul_toeplitz(c_or_cr, x, check_finite=False, workers=None):
1961
+ r"""Efficient Toeplitz Matrix-Matrix Multiplication using FFT
1962
+
1963
+ This function returns the matrix multiplication between a Toeplitz
1964
+ matrix and a dense matrix.
1965
+
1966
+ The Toeplitz matrix has constant diagonals, with c as its first column
1967
+ and r as its first row. If r is not given, ``r == conjugate(c)`` is
1968
+ assumed.
1969
+
1970
+ .. warning::
1971
+
1972
+ Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
1973
+ not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
1974
+ before passing them to `matmul_toeplitz`.
1975
+
1976
+ Parameters
1977
+ ----------
1978
+ c_or_cr : array_like or tuple of (array_like, array_like)
1979
+ The vector ``c``, or a tuple of arrays (``c``, ``r``). If not
1980
+ supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
1981
+ real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
1982
+ of the Toeplitz matrix is ``[c[0], r[1:]]``.
1983
+ x : (M,) or (M, K) array_like
1984
+ Matrix with which to multiply.
1985
+ check_finite : bool, optional
1986
+ Whether to check that the input matrices contain only finite numbers.
1987
+ Disabling may give a performance gain, but may result in problems
1988
+ (result entirely NaNs) if the inputs do contain infinities or NaNs.
1989
+ workers : int, optional
1990
+ To pass to scipy.fft.fft and ifft. Maximum number of workers to use
1991
+ for parallel computation. If negative, the value wraps around from
1992
+ ``os.cpu_count()``. See scipy.fft.fft for more details.
1993
+
1994
+ Returns
1995
+ -------
1996
+ T @ x : (M,) or (M, K) ndarray
1997
+ The result of the matrix multiplication ``T @ x``. Shape of return
1998
+ matches shape of `x`.
1999
+
2000
+ See Also
2001
+ --------
2002
+ toeplitz : Toeplitz matrix
2003
+ solve_toeplitz : Solve a Toeplitz system using Levinson Recursion
2004
+
2005
+ Notes
2006
+ -----
2007
+ The Toeplitz matrix is embedded in a circulant matrix and the FFT is used
2008
+ to efficiently calculate the matrix-matrix product.
2009
+
2010
+ Because the computation is based on the FFT, integer inputs will
2011
+ result in floating point outputs. This is unlike NumPy's `matmul`,
2012
+ which preserves the data type of the input.
2013
+
2014
+ This is partly based on the implementation that can be found in [1]_,
2015
+ licensed under the MIT license. More information about the method can be
2016
+ found in reference [2]_. References [3]_ and [4]_ have more reference
2017
+ implementations in Python.
2018
+
2019
+ .. versionadded:: 1.6.0
2020
+
2021
+ References
2022
+ ----------
2023
+ .. [1] Jacob R Gardner, Geoff Pleiss, David Bindel, Kilian
2024
+ Q Weinberger, Andrew Gordon Wilson, "GPyTorch: Blackbox Matrix-Matrix
2025
+ Gaussian Process Inference with GPU Acceleration" with contributions
2026
+ from Max Balandat and Ruihan Wu. Available online:
2027
+ https://github.com/cornellius-gp/gpytorch
2028
+
2029
+ .. [2] J. Demmel, P. Koev, and X. Li, "A Brief Survey of Direct Linear
2030
+ Solvers". In Z. Bai, J. Demmel, J. Dongarra, A. Ruhe, and H. van der
2031
+ Vorst, editors. Templates for the Solution of Algebraic Eigenvalue
2032
+ Problems: A Practical Guide. SIAM, Philadelphia, 2000. Available at:
2033
+ http://www.netlib.org/utk/people/JackDongarra/etemplates/node384.html
2034
+
2035
+ .. [3] R. Scheibler, E. Bezzam, I. Dokmanic, Pyroomacoustics: A Python
2036
+ package for audio room simulations and array processing algorithms,
2037
+ Proc. IEEE ICASSP, Calgary, CA, 2018.
2038
+ https://github.com/LCAV/pyroomacoustics/blob/pypi-release/
2039
+ pyroomacoustics/adaptive/util.py
2040
+
2041
+ .. [4] Marano S, Edwards B, Ferrari G and Fah D (2017), "Fitting
2042
+ Earthquake Spectra: Colored Noise and Incomplete Data", Bulletin of
2043
+ the Seismological Society of America., January, 2017. Vol. 107(1),
2044
+ pp. 276-291.
2045
+
2046
+ Examples
2047
+ --------
2048
+ Multiply the Toeplitz matrix T with matrix x::
2049
+
2050
+ [ 1 -1 -2 -3] [1 10]
2051
+ T = [ 3 1 -1 -2] x = [2 11]
2052
+ [ 6 3 1 -1] [2 11]
2053
+ [10 6 3 1] [5 19]
2054
+
2055
+ To specify the Toeplitz matrix, only the first column and the first
2056
+ row are needed.
2057
+
2058
+ >>> import numpy as np
2059
+ >>> c = np.array([1, 3, 6, 10]) # First column of T
2060
+ >>> r = np.array([1, -1, -2, -3]) # First row of T
2061
+ >>> x = np.array([[1, 10], [2, 11], [2, 11], [5, 19]])
2062
+
2063
+ >>> from scipy.linalg import toeplitz, matmul_toeplitz
2064
+ >>> matmul_toeplitz((c, r), x)
2065
+ array([[-20., -80.],
2066
+ [ -7., -8.],
2067
+ [ 9., 85.],
2068
+ [ 33., 218.]])
2069
+
2070
+ Check the result by creating the full Toeplitz matrix and
2071
+ multiplying it by ``x``.
2072
+
2073
+ >>> toeplitz(c, r) @ x
2074
+ array([[-20, -80],
2075
+ [ -7, -8],
2076
+ [ 9, 85],
2077
+ [ 33, 218]])
2078
+
2079
+ The full matrix is never formed explicitly, so this routine
2080
+ is suitable for very large Toeplitz matrices.
2081
+
2082
+ >>> n = 1000000
2083
+ >>> matmul_toeplitz([1] + [0]*(n-1), np.ones(n))
2084
+ array([1., 1., 1., ..., 1., 1., 1.], shape=(1000000,))
2085
+
2086
+ """
2087
+
2088
+ from ..fft import fft, ifft, rfft, irfft
2089
+
2090
+ r, c, x, dtype, x_shape = _validate_args_for_toeplitz_ops(
2091
+ c_or_cr, x, check_finite, keep_b_shape=False, enforce_square=False)
2092
+ n, m = x.shape
2093
+
2094
+ T_nrows = len(c)
2095
+ T_ncols = len(r)
2096
+ p = T_nrows + T_ncols - 1 # equivalent to len(embedded_col)
2097
+ return_shape = (T_nrows,) if len(x_shape) == 1 else (T_nrows, m)
2098
+
2099
+ # accommodate empty arrays
2100
+ if x.size == 0:
2101
+ return np.empty_like(x, shape=return_shape)
2102
+
2103
+ embedded_col = np.concatenate((c, r[-1:0:-1]))
2104
+
2105
+ if np.iscomplexobj(embedded_col) or np.iscomplexobj(x):
2106
+ fft_mat = fft(embedded_col, axis=0, workers=workers).reshape(-1, 1)
2107
+ fft_x = fft(x, n=p, axis=0, workers=workers)
2108
+
2109
+ mat_times_x = ifft(fft_mat*fft_x, axis=0,
2110
+ workers=workers)[:T_nrows, :]
2111
+ else:
2112
+ # Real inputs; using rfft is faster
2113
+ fft_mat = rfft(embedded_col, axis=0, workers=workers).reshape(-1, 1)
2114
+ fft_x = rfft(x, n=p, axis=0, workers=workers)
2115
+
2116
+ mat_times_x = irfft(fft_mat*fft_x, axis=0,
2117
+ workers=workers, n=p)[:T_nrows, :]
2118
+
2119
+ return mat_times_x.reshape(*return_shape)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ This file was generated by _generate_pyx.py.
3
+ Do not edit this file directly.
4
+ */
5
+
6
+ #include "npy_cblas.h"
7
+ #include "fortran_defs.h"
8
+
9
+ #ifdef __cplusplus
10
+ extern "C" {
11
+ #endif
12
+
13
+ void BLAS_FUNC(caxpy)(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
14
+ void BLAS_FUNC(ccopy)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
15
+ void F_FUNC(cdotcwrp,CDOTCWRP)(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
16
+ void F_FUNC(cdotuwrp,CDOTUWRP)(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
17
+ void 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);
18
+ void 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);
19
+ void 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);
20
+ void 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);
21
+ void 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);
22
+ void 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);
23
+ void 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);
24
+ void 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);
25
+ void BLAS_FUNC(cher)(char *uplo, int *n, float *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda);
26
+ void 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);
27
+ void BLAS_FUNC(cher2k)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *beta, npy_complex64 *c, int *ldc);
28
+ void BLAS_FUNC(cherk)(char *uplo, char *trans, int *n, int *k, float *alpha, npy_complex64 *a, int *lda, float *beta, npy_complex64 *c, int *ldc);
29
+ void 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);
30
+ void BLAS_FUNC(chpr)(char *uplo, int *n, float *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap);
31
+ void BLAS_FUNC(chpr2)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *ap);
32
+ void BLAS_FUNC(crotg)(npy_complex64 *ca, npy_complex64 *cb, float *c, npy_complex64 *s);
33
+ void BLAS_FUNC(cscal)(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx);
34
+ void BLAS_FUNC(csrot)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, float *c, float *s);
35
+ void BLAS_FUNC(csscal)(int *n, float *sa, npy_complex64 *cx, int *incx);
36
+ void BLAS_FUNC(cswap)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
37
+ void 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);
38
+ void 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);
39
+ void 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);
40
+ void BLAS_FUNC(ctbmv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
41
+ void BLAS_FUNC(ctbsv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
42
+ void BLAS_FUNC(ctpmv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx);
43
+ void BLAS_FUNC(ctpsv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx);
44
+ void 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);
45
+ void BLAS_FUNC(ctrmv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
46
+ void 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);
47
+ void BLAS_FUNC(ctrsv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
48
+ double BLAS_FUNC(dasum)(int *n, double *dx, int *incx);
49
+ void BLAS_FUNC(daxpy)(int *n, double *da, double *dx, int *incx, double *dy, int *incy);
50
+ double BLAS_FUNC(dcabs1)(npy_complex128 *z);
51
+ void BLAS_FUNC(dcopy)(int *n, double *dx, int *incx, double *dy, int *incy);
52
+ double BLAS_FUNC(ddot)(int *n, double *dx, int *incx, double *dy, int *incy);
53
+ void BLAS_FUNC(dgbmv)(char *trans, int *m, int *n, int *kl, int *ku, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
54
+ void BLAS_FUNC(dgemm)(char *transa, char *transb, int *m, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
55
+ void BLAS_FUNC(dgemv)(char *trans, int *m, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
56
+ void BLAS_FUNC(dger)(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *a, int *lda);
57
+ double BLAS_FUNC(dnrm2)(int *n, double *x, int *incx);
58
+ void BLAS_FUNC(drot)(int *n, double *dx, int *incx, double *dy, int *incy, double *c, double *s);
59
+ void BLAS_FUNC(drotg)(double *da, double *db, double *c, double *s);
60
+ void BLAS_FUNC(drotm)(int *n, double *dx, int *incx, double *dy, int *incy, double *dparam);
61
+ void BLAS_FUNC(drotmg)(double *dd1, double *dd2, double *dx1, double *dy1, double *dparam);
62
+ void BLAS_FUNC(dsbmv)(char *uplo, int *n, int *k, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
63
+ void BLAS_FUNC(dscal)(int *n, double *da, double *dx, int *incx);
64
+ double BLAS_FUNC(dsdot)(int *n, float *sx, int *incx, float *sy, int *incy);
65
+ void BLAS_FUNC(dspmv)(char *uplo, int *n, double *alpha, double *ap, double *x, int *incx, double *beta, double *y, int *incy);
66
+ void BLAS_FUNC(dspr)(char *uplo, int *n, double *alpha, double *x, int *incx, double *ap);
67
+ void BLAS_FUNC(dspr2)(char *uplo, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *ap);
68
+ void BLAS_FUNC(dswap)(int *n, double *dx, int *incx, double *dy, int *incy);
69
+ void BLAS_FUNC(dsymm)(char *side, char *uplo, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
70
+ void BLAS_FUNC(dsymv)(char *uplo, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
71
+ void BLAS_FUNC(dsyr)(char *uplo, int *n, double *alpha, double *x, int *incx, double *a, int *lda);
72
+ void BLAS_FUNC(dsyr2)(char *uplo, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *a, int *lda);
73
+ void BLAS_FUNC(dsyr2k)(char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
74
+ void BLAS_FUNC(dsyrk)(char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *beta, double *c, int *ldc);
75
+ void BLAS_FUNC(dtbmv)(char *uplo, char *trans, char *diag, int *n, int *k, double *a, int *lda, double *x, int *incx);
76
+ void BLAS_FUNC(dtbsv)(char *uplo, char *trans, char *diag, int *n, int *k, double *a, int *lda, double *x, int *incx);
77
+ void BLAS_FUNC(dtpmv)(char *uplo, char *trans, char *diag, int *n, double *ap, double *x, int *incx);
78
+ void BLAS_FUNC(dtpsv)(char *uplo, char *trans, char *diag, int *n, double *ap, double *x, int *incx);
79
+ void BLAS_FUNC(dtrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb);
80
+ void BLAS_FUNC(dtrmv)(char *uplo, char *trans, char *diag, int *n, double *a, int *lda, double *x, int *incx);
81
+ void BLAS_FUNC(dtrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb);
82
+ void BLAS_FUNC(dtrsv)(char *uplo, char *trans, char *diag, int *n, double *a, int *lda, double *x, int *incx);
83
+ double BLAS_FUNC(dzasum)(int *n, npy_complex128 *zx, int *incx);
84
+ double BLAS_FUNC(dznrm2)(int *n, npy_complex128 *x, int *incx);
85
+ int BLAS_FUNC(icamax)(int *n, npy_complex64 *cx, int *incx);
86
+ int BLAS_FUNC(idamax)(int *n, double *dx, int *incx);
87
+ int BLAS_FUNC(isamax)(int *n, float *sx, int *incx);
88
+ int BLAS_FUNC(izamax)(int *n, npy_complex128 *zx, int *incx);
89
+ int BLAS_FUNC(lsame)(char *ca, char *cb);
90
+ float BLAS_FUNC(sasum)(int *n, float *sx, int *incx);
91
+ void BLAS_FUNC(saxpy)(int *n, float *sa, float *sx, int *incx, float *sy, int *incy);
92
+ float BLAS_FUNC(scasum)(int *n, npy_complex64 *cx, int *incx);
93
+ float BLAS_FUNC(scnrm2)(int *n, npy_complex64 *x, int *incx);
94
+ void BLAS_FUNC(scopy)(int *n, float *sx, int *incx, float *sy, int *incy);
95
+ float BLAS_FUNC(sdot)(int *n, float *sx, int *incx, float *sy, int *incy);
96
+ float BLAS_FUNC(sdsdot)(int *n, float *sb, float *sx, int *incx, float *sy, int *incy);
97
+ void BLAS_FUNC(sgbmv)(char *trans, int *m, int *n, int *kl, int *ku, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
98
+ void BLAS_FUNC(sgemm)(char *transa, char *transb, int *m, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
99
+ void BLAS_FUNC(sgemv)(char *trans, int *m, int *n, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
100
+ void BLAS_FUNC(sger)(int *m, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *a, int *lda);
101
+ float BLAS_FUNC(snrm2)(int *n, float *x, int *incx);
102
+ void BLAS_FUNC(srot)(int *n, float *sx, int *incx, float *sy, int *incy, float *c, float *s);
103
+ void BLAS_FUNC(srotg)(float *sa, float *sb, float *c, float *s);
104
+ void BLAS_FUNC(srotm)(int *n, float *sx, int *incx, float *sy, int *incy, float *sparam);
105
+ void BLAS_FUNC(srotmg)(float *sd1, float *sd2, float *sx1, float *sy1, float *sparam);
106
+ void BLAS_FUNC(ssbmv)(char *uplo, int *n, int *k, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
107
+ void BLAS_FUNC(sscal)(int *n, float *sa, float *sx, int *incx);
108
+ void BLAS_FUNC(sspmv)(char *uplo, int *n, float *alpha, float *ap, float *x, int *incx, float *beta, float *y, int *incy);
109
+ void BLAS_FUNC(sspr)(char *uplo, int *n, float *alpha, float *x, int *incx, float *ap);
110
+ void BLAS_FUNC(sspr2)(char *uplo, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *ap);
111
+ void BLAS_FUNC(sswap)(int *n, float *sx, int *incx, float *sy, int *incy);
112
+ void BLAS_FUNC(ssymm)(char *side, char *uplo, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
113
+ void BLAS_FUNC(ssymv)(char *uplo, int *n, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
114
+ void BLAS_FUNC(ssyr)(char *uplo, int *n, float *alpha, float *x, int *incx, float *a, int *lda);
115
+ void BLAS_FUNC(ssyr2)(char *uplo, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *a, int *lda);
116
+ void BLAS_FUNC(ssyr2k)(char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
117
+ void BLAS_FUNC(ssyrk)(char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *beta, float *c, int *ldc);
118
+ void BLAS_FUNC(stbmv)(char *uplo, char *trans, char *diag, int *n, int *k, float *a, int *lda, float *x, int *incx);
119
+ void BLAS_FUNC(stbsv)(char *uplo, char *trans, char *diag, int *n, int *k, float *a, int *lda, float *x, int *incx);
120
+ void BLAS_FUNC(stpmv)(char *uplo, char *trans, char *diag, int *n, float *ap, float *x, int *incx);
121
+ void BLAS_FUNC(stpsv)(char *uplo, char *trans, char *diag, int *n, float *ap, float *x, int *incx);
122
+ void BLAS_FUNC(strmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb);
123
+ void BLAS_FUNC(strmv)(char *uplo, char *trans, char *diag, int *n, float *a, int *lda, float *x, int *incx);
124
+ void BLAS_FUNC(strsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb);
125
+ void BLAS_FUNC(strsv)(char *uplo, char *trans, char *diag, int *n, float *a, int *lda, float *x, int *incx);
126
+ void BLAS_FUNC(zaxpy)(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
127
+ void BLAS_FUNC(zcopy)(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
128
+ void F_FUNC(zdotcwrp,ZDOTCWRP)(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
129
+ void F_FUNC(zdotuwrp,ZDOTUWRP)(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
130
+ void BLAS_FUNC(zdrot)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, double *c, double *s);
131
+ void BLAS_FUNC(zdscal)(int *n, double *da, npy_complex128 *zx, int *incx);
132
+ void 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);
133
+ void 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);
134
+ void 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);
135
+ void 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);
136
+ void 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);
137
+ void 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);
138
+ void 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);
139
+ void 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);
140
+ void BLAS_FUNC(zher)(char *uplo, int *n, double *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda);
141
+ void 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);
142
+ void BLAS_FUNC(zher2k)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *beta, npy_complex128 *c, int *ldc);
143
+ void BLAS_FUNC(zherk)(char *uplo, char *trans, int *n, int *k, double *alpha, npy_complex128 *a, int *lda, double *beta, npy_complex128 *c, int *ldc);
144
+ void 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);
145
+ void BLAS_FUNC(zhpr)(char *uplo, int *n, double *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap);
146
+ void BLAS_FUNC(zhpr2)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *ap);
147
+ void BLAS_FUNC(zrotg)(npy_complex128 *ca, npy_complex128 *cb, double *c, npy_complex128 *s);
148
+ void BLAS_FUNC(zscal)(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx);
149
+ void BLAS_FUNC(zswap)(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
150
+ void 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);
151
+ void 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);
152
+ void 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);
153
+ void BLAS_FUNC(ztbmv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
154
+ void BLAS_FUNC(ztbsv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
155
+ void BLAS_FUNC(ztpmv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx);
156
+ void BLAS_FUNC(ztpsv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx);
157
+ void 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);
158
+ void BLAS_FUNC(ztrmv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
159
+ void 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);
160
+ void BLAS_FUNC(ztrsv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
161
+
162
+ #ifdef __cplusplus
163
+ }
164
+ #endif
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport numpy as cnp
2
+
3
+ ctypedef fused lapack_t:
4
+ float
5
+ double
6
+ (float complex)
7
+ (double complex)
8
+
9
+ ctypedef fused lapack_cz_t:
10
+ (float complex)
11
+ (double complex)
12
+
13
+ ctypedef fused lapack_sd_t:
14
+ float
15
+ double
16
+
17
+ ctypedef fused np_numeric_t:
18
+ cnp.int8_t
19
+ cnp.int16_t
20
+ cnp.int32_t
21
+ cnp.int64_t
22
+ cnp.uint8_t
23
+ cnp.uint16_t
24
+ cnp.uint32_t
25
+ cnp.uint64_t
26
+ cnp.float32_t
27
+ cnp.float64_t
28
+ cnp.longdouble_t
29
+ cnp.complex64_t
30
+ cnp.complex128_t
31
+
32
+ ctypedef fused np_complex_numeric_t:
33
+ cnp.complex64_t
34
+ cnp.complex128_t
35
+
36
+
37
+ cdef void swap_c_and_f_layout(lapack_t *a, lapack_t *b, int r, int c) noexcept nogil
38
+ cdef (int, int) band_check_internal_c(np_numeric_t[:, ::1]A) noexcept nogil
39
+ cdef bint is_sym_her_real_c_internal(np_numeric_t[:, ::1]A) noexcept nogil
40
+ cdef bint is_sym_her_complex_c_internal(np_complex_numeric_t[:, ::1]A) noexcept nogil
miniconda3/envs/ladir/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
+ a: NDArray[Any],
14
+ atol: None | float = ...,
15
+ rtol: None | float = ...,
16
+ ) -> bool: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp.py ADDED
@@ -0,0 +1,1632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Author: Pearu Peterson, March 2002
3
+ #
4
+ # additions by Travis Oliphant, March 2002
5
+ # additions by Eric Jones, June 2002
6
+ # additions by Johannes Loehnert, June 2006
7
+ # additions by Bart Vandereycken, June 2006
8
+ # additions by Andrew D Straw, May 2007
9
+ # additions by Tiziano Zito, November 2008
10
+ #
11
+ # April 2010: Functions for LU, QR, SVD, Schur, and Cholesky decompositions
12
+ # were moved to their own files. Still in this file are functions for
13
+ # eigenstuff and for the Hessenberg form.
14
+
15
+ __all__ = ['eig', 'eigvals', 'eigh', 'eigvalsh',
16
+ 'eig_banded', 'eigvals_banded',
17
+ 'eigh_tridiagonal', 'eigvalsh_tridiagonal', 'hessenberg', 'cdf2rdf']
18
+
19
+ import numpy as np
20
+ from numpy import (array, isfinite, inexact, nonzero, iscomplexobj,
21
+ flatnonzero, conj, asarray, argsort, empty,
22
+ iscomplex, zeros, einsum, eye, inf)
23
+ # Local imports
24
+ from scipy._lib._util import _asarray_validated
25
+ from ._misc import LinAlgError, _datacopied, norm
26
+ from .lapack import get_lapack_funcs, _compute_lwork
27
+
28
+
29
+ _I = np.array(1j, dtype='F')
30
+
31
+
32
+ def _make_complex_eigvecs(w, vin, dtype):
33
+ """
34
+ Produce complex-valued eigenvectors from LAPACK DGGEV real-valued output
35
+ """
36
+ # - see LAPACK man page DGGEV at ALPHAI
37
+ v = np.array(vin, dtype=dtype)
38
+ m = (w.imag > 0)
39
+ m[:-1] |= (w.imag[1:] < 0) # workaround for LAPACK bug, cf. ticket #709
40
+ for i in flatnonzero(m):
41
+ v.imag[:, i] = vin[:, i+1]
42
+ conj(v[:, i], v[:, i+1])
43
+ return v
44
+
45
+
46
+ def _make_eigvals(alpha, beta, homogeneous_eigvals):
47
+ if homogeneous_eigvals:
48
+ if beta is None:
49
+ return np.vstack((alpha, np.ones_like(alpha)))
50
+ else:
51
+ return np.vstack((alpha, beta))
52
+ else:
53
+ if beta is None:
54
+ return alpha
55
+ else:
56
+ w = np.empty_like(alpha)
57
+ alpha_zero = (alpha == 0)
58
+ beta_zero = (beta == 0)
59
+ beta_nonzero = ~beta_zero
60
+ w[beta_nonzero] = alpha[beta_nonzero]/beta[beta_nonzero]
61
+ # Use np.inf for complex values too since
62
+ # 1/np.inf = 0, i.e., it correctly behaves as projective
63
+ # infinity.
64
+ w[~alpha_zero & beta_zero] = np.inf
65
+ if np.all(alpha.imag == 0):
66
+ w[alpha_zero & beta_zero] = np.nan
67
+ else:
68
+ w[alpha_zero & beta_zero] = complex(np.nan, np.nan)
69
+ return w
70
+
71
+
72
+ def _geneig(a1, b1, left, right, overwrite_a, overwrite_b,
73
+ homogeneous_eigvals):
74
+ ggev, = get_lapack_funcs(('ggev',), (a1, b1))
75
+ cvl, cvr = left, right
76
+ res = ggev(a1, b1, lwork=-1)
77
+ lwork = res[-2][0].real.astype(np.int_)
78
+ if ggev.typecode in 'cz':
79
+ alpha, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr, lwork,
80
+ overwrite_a, overwrite_b)
81
+ w = _make_eigvals(alpha, beta, homogeneous_eigvals)
82
+ else:
83
+ alphar, alphai, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr,
84
+ lwork, overwrite_a,
85
+ overwrite_b)
86
+ alpha = alphar + _I * alphai
87
+ w = _make_eigvals(alpha, beta, homogeneous_eigvals)
88
+ _check_info(info, 'generalized eig algorithm (ggev)')
89
+
90
+ only_real = np.all(w.imag == 0.0)
91
+ if not (ggev.typecode in 'cz' or only_real):
92
+ t = w.dtype.char
93
+ if left:
94
+ vl = _make_complex_eigvecs(w, vl, t)
95
+ if right:
96
+ vr = _make_complex_eigvecs(w, vr, t)
97
+
98
+ # the eigenvectors returned by the lapack function are NOT normalized
99
+ for i in range(vr.shape[0]):
100
+ if right:
101
+ vr[:, i] /= norm(vr[:, i])
102
+ if left:
103
+ vl[:, i] /= norm(vl[:, i])
104
+
105
+ if not (left or right):
106
+ return w
107
+ if left:
108
+ if right:
109
+ return w, vl, vr
110
+ return w, vl
111
+ return w, vr
112
+
113
+
114
+ def eig(a, b=None, left=False, right=True, overwrite_a=False,
115
+ overwrite_b=False, check_finite=True, homogeneous_eigvals=False):
116
+ """
117
+ Solve an ordinary or generalized eigenvalue problem of a square matrix.
118
+
119
+ Find eigenvalues w and right or left eigenvectors of a general matrix::
120
+
121
+ a vr[:,i] = w[i] b vr[:,i]
122
+ a.H vl[:,i] = w[i].conj() b.H vl[:,i]
123
+
124
+ where ``.H`` is the Hermitian conjugation.
125
+
126
+ Parameters
127
+ ----------
128
+ a : (M, M) array_like
129
+ A complex or real matrix whose eigenvalues and eigenvectors
130
+ will be computed.
131
+ b : (M, M) array_like, optional
132
+ Right-hand side matrix in a generalized eigenvalue problem.
133
+ Default is None, identity matrix is assumed.
134
+ left : bool, optional
135
+ Whether to calculate and return left eigenvectors. Default is False.
136
+ right : bool, optional
137
+ Whether to calculate and return right eigenvectors. Default is True.
138
+ overwrite_a : bool, optional
139
+ Whether to overwrite `a`; may improve performance. Default is False.
140
+ overwrite_b : bool, optional
141
+ Whether to overwrite `b`; may improve performance. Default is False.
142
+ check_finite : bool, optional
143
+ Whether to check that the input matrices contain only finite numbers.
144
+ Disabling may give a performance gain, but may result in problems
145
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
146
+ homogeneous_eigvals : bool, optional
147
+ If True, return the eigenvalues in homogeneous coordinates.
148
+ In this case ``w`` is a (2, M) array so that::
149
+
150
+ w[1,i] a vr[:,i] = w[0,i] b vr[:,i]
151
+
152
+ Default is False.
153
+
154
+ Returns
155
+ -------
156
+ w : (M,) or (2, M) double or complex ndarray
157
+ The eigenvalues, each repeated according to its
158
+ multiplicity. The shape is (M,) unless
159
+ ``homogeneous_eigvals=True``.
160
+ vl : (M, M) double or complex ndarray
161
+ The left eigenvector corresponding to the eigenvalue
162
+ ``w[i]`` is the column ``vl[:,i]``. Only returned if ``left=True``.
163
+ The left eigenvector is not normalized.
164
+ vr : (M, M) double or complex ndarray
165
+ The normalized right eigenvector corresponding to the eigenvalue
166
+ ``w[i]`` is the column ``vr[:,i]``. Only returned if ``right=True``.
167
+
168
+ Raises
169
+ ------
170
+ LinAlgError
171
+ If eigenvalue computation does not converge.
172
+
173
+ See Also
174
+ --------
175
+ eigvals : eigenvalues of general arrays
176
+ eigh : Eigenvalues and right eigenvectors for symmetric/Hermitian arrays.
177
+ eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
178
+ band matrices
179
+ eigh_tridiagonal : eigenvalues and right eiegenvectors for
180
+ symmetric/Hermitian tridiagonal matrices
181
+
182
+ Examples
183
+ --------
184
+ >>> import numpy as np
185
+ >>> from scipy import linalg
186
+ >>> a = np.array([[0., -1.], [1., 0.]])
187
+ >>> linalg.eigvals(a)
188
+ array([0.+1.j, 0.-1.j])
189
+
190
+ >>> b = np.array([[0., 1.], [1., 1.]])
191
+ >>> linalg.eigvals(a, b)
192
+ array([ 1.+0.j, -1.+0.j])
193
+
194
+ >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]])
195
+ >>> linalg.eigvals(a, homogeneous_eigvals=True)
196
+ array([[3.+0.j, 8.+0.j, 7.+0.j],
197
+ [1.+0.j, 1.+0.j, 1.+0.j]])
198
+
199
+ >>> a = np.array([[0., -1.], [1., 0.]])
200
+ >>> linalg.eigvals(a) == linalg.eig(a)[0]
201
+ array([ True, True])
202
+ >>> linalg.eig(a, left=True, right=False)[1] # normalized left eigenvector
203
+ array([[-0.70710678+0.j , -0.70710678-0.j ],
204
+ [-0. +0.70710678j, -0. -0.70710678j]])
205
+ >>> linalg.eig(a, left=False, right=True)[1] # normalized right eigenvector
206
+ array([[0.70710678+0.j , 0.70710678-0.j ],
207
+ [0. -0.70710678j, 0. +0.70710678j]])
208
+
209
+
210
+
211
+ """
212
+ a1 = _asarray_validated(a, check_finite=check_finite)
213
+ if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
214
+ raise ValueError('expected square matrix')
215
+
216
+ # accommodate square empty matrices
217
+ if a1.size == 0:
218
+ w_n, vr_n = eig(np.eye(2, dtype=a1.dtype))
219
+ w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
220
+ w = _make_eigvals(w, None, homogeneous_eigvals)
221
+ vl = np.empty_like(a1, shape=(0, 0), dtype=vr_n.dtype)
222
+ vr = np.empty_like(a1, shape=(0, 0), dtype=vr_n.dtype)
223
+ if not (left or right):
224
+ return w
225
+ if left:
226
+ if right:
227
+ return w, vl, vr
228
+ return w, vl
229
+ return w, vr
230
+
231
+ overwrite_a = overwrite_a or (_datacopied(a1, a))
232
+ if b is not None:
233
+ b1 = _asarray_validated(b, check_finite=check_finite)
234
+ overwrite_b = overwrite_b or _datacopied(b1, b)
235
+ if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:
236
+ raise ValueError('expected square matrix')
237
+ if b1.shape != a1.shape:
238
+ raise ValueError('a and b must have the same shape')
239
+ return _geneig(a1, b1, left, right, overwrite_a, overwrite_b,
240
+ homogeneous_eigvals)
241
+
242
+ geev, geev_lwork = get_lapack_funcs(('geev', 'geev_lwork'), (a1,))
243
+ compute_vl, compute_vr = left, right
244
+
245
+ lwork = _compute_lwork(geev_lwork, a1.shape[0],
246
+ compute_vl=compute_vl,
247
+ compute_vr=compute_vr)
248
+
249
+ if geev.typecode in 'cz':
250
+ w, vl, vr, info = geev(a1, lwork=lwork,
251
+ compute_vl=compute_vl,
252
+ compute_vr=compute_vr,
253
+ overwrite_a=overwrite_a)
254
+ w = _make_eigvals(w, None, homogeneous_eigvals)
255
+ else:
256
+ wr, wi, vl, vr, info = geev(a1, lwork=lwork,
257
+ compute_vl=compute_vl,
258
+ compute_vr=compute_vr,
259
+ overwrite_a=overwrite_a)
260
+ w = wr + _I * wi
261
+ w = _make_eigvals(w, None, homogeneous_eigvals)
262
+
263
+ _check_info(info, 'eig algorithm (geev)',
264
+ positive='did not converge (only eigenvalues '
265
+ 'with order >= %d have converged)')
266
+
267
+ only_real = np.all(w.imag == 0.0)
268
+ if not (geev.typecode in 'cz' or only_real):
269
+ t = w.dtype.char
270
+ if left:
271
+ vl = _make_complex_eigvecs(w, vl, t)
272
+ if right:
273
+ vr = _make_complex_eigvecs(w, vr, t)
274
+ if not (left or right):
275
+ return w
276
+ if left:
277
+ if right:
278
+ return w, vl, vr
279
+ return w, vl
280
+ return w, vr
281
+
282
+
283
+ def eigh(a, b=None, *, lower=True, eigvals_only=False, overwrite_a=False,
284
+ overwrite_b=False, type=1, check_finite=True, subset_by_index=None,
285
+ subset_by_value=None, driver=None):
286
+ """
287
+ Solve a standard or generalized eigenvalue problem for a complex
288
+ Hermitian or real symmetric matrix.
289
+
290
+ Find eigenvalues array ``w`` and optionally eigenvectors array ``v`` of
291
+ array ``a``, where ``b`` is positive definite such that for every
292
+ eigenvalue λ (i-th entry of w) and its eigenvector ``vi`` (i-th column of
293
+ ``v``) satisfies::
294
+
295
+ a @ vi = λ * b @ vi
296
+ vi.conj().T @ a @ vi = λ
297
+ vi.conj().T @ b @ vi = 1
298
+
299
+ In the standard problem, ``b`` is assumed to be the identity matrix.
300
+
301
+ Parameters
302
+ ----------
303
+ a : (M, M) array_like
304
+ A complex Hermitian or real symmetric matrix whose eigenvalues and
305
+ eigenvectors will be computed.
306
+ b : (M, M) array_like, optional
307
+ A complex Hermitian or real symmetric definite positive matrix in.
308
+ If omitted, identity matrix is assumed.
309
+ lower : bool, optional
310
+ Whether the pertinent array data is taken from the lower or upper
311
+ triangle of ``a`` and, if applicable, ``b``. (Default: lower)
312
+ eigvals_only : bool, optional
313
+ Whether to calculate only eigenvalues and no eigenvectors.
314
+ (Default: both are calculated)
315
+ subset_by_index : iterable, optional
316
+ If provided, this two-element iterable defines the start and the end
317
+ indices of the desired eigenvalues (ascending order and 0-indexed).
318
+ To return only the second smallest to fifth smallest eigenvalues,
319
+ ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only
320
+ available with "evr", "evx", and "gvx" drivers. The entries are
321
+ directly converted to integers via ``int()``.
322
+ subset_by_value : iterable, optional
323
+ If provided, this two-element iterable defines the half-open interval
324
+ ``(a, b]`` that, if any, only the eigenvalues between these values
325
+ are returned. Only available with "evr", "evx", and "gvx" drivers. Use
326
+ ``np.inf`` for the unconstrained ends.
327
+ driver : str, optional
328
+ Defines which LAPACK driver should be used. Valid options are "ev",
329
+ "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for
330
+ generalized (where b is not None) problems. See the Notes section.
331
+ The default for standard problems is "evr". For generalized problems,
332
+ "gvd" is used for full set, and "gvx" for subset requested cases.
333
+ type : int, optional
334
+ For the generalized problems, this keyword specifies the problem type
335
+ to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible
336
+ inputs)::
337
+
338
+ 1 => a @ v = w @ b @ v
339
+ 2 => a @ b @ v = w @ v
340
+ 3 => b @ a @ v = w @ v
341
+
342
+ This keyword is ignored for standard problems.
343
+ overwrite_a : bool, optional
344
+ Whether to overwrite data in ``a`` (may improve performance). Default
345
+ is False.
346
+ overwrite_b : bool, optional
347
+ Whether to overwrite data in ``b`` (may improve performance). Default
348
+ is False.
349
+ check_finite : bool, optional
350
+ Whether to check that the input matrices contain only finite numbers.
351
+ Disabling may give a performance gain, but may result in problems
352
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
353
+
354
+ Returns
355
+ -------
356
+ w : (N,) ndarray
357
+ The N (N<=M) selected eigenvalues, in ascending order, each
358
+ repeated according to its multiplicity.
359
+ v : (M, N) ndarray
360
+ The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
361
+ the column ``v[:,i]``. Only returned if ``eigvals_only=False``.
362
+
363
+ Raises
364
+ ------
365
+ LinAlgError
366
+ If eigenvalue computation does not converge, an error occurred, or
367
+ b matrix is not definite positive. Note that if input matrices are
368
+ not symmetric or Hermitian, no error will be reported but results will
369
+ be wrong.
370
+
371
+ See Also
372
+ --------
373
+ eigvalsh : eigenvalues of symmetric or Hermitian arrays
374
+ eig : eigenvalues and right eigenvectors for non-symmetric arrays
375
+ eigh_tridiagonal : eigenvalues and right eiegenvectors for
376
+ symmetric/Hermitian tridiagonal matrices
377
+
378
+ Notes
379
+ -----
380
+ This function does not check the input array for being Hermitian/symmetric
381
+ in order to allow for representing arrays with only their upper/lower
382
+ triangular parts. Also, note that even though not taken into account,
383
+ finiteness check applies to the whole array and unaffected by "lower"
384
+ keyword.
385
+
386
+ This function uses LAPACK drivers for computations in all possible keyword
387
+ combinations, prefixed with ``sy`` if arrays are real and ``he`` if
388
+ complex, e.g., a float array with "evr" driver is solved via
389
+ "syevr", complex arrays with "gvx" driver problem is solved via "hegvx"
390
+ etc.
391
+
392
+ As a brief summary, the slowest and the most robust driver is the
393
+ classical ``<sy/he>ev`` which uses symmetric QR. ``<sy/he>evr`` is seen as
394
+ the optimal choice for the most general cases. However, there are certain
395
+ occasions that ``<sy/he>evd`` computes faster at the expense of more
396
+ memory usage. ``<sy/he>evx``, while still being faster than ``<sy/he>ev``,
397
+ often performs worse than the rest except when very few eigenvalues are
398
+ requested for large arrays though there is still no performance guarantee.
399
+
400
+ Note that the underlying LAPACK algorithms are different depending on whether
401
+ `eigvals_only` is True or False --- thus the eigenvalues may differ
402
+ depending on whether eigenvectors are requested or not. The difference is
403
+ generally of the order of machine epsilon times the largest eigenvalue,
404
+ so is likely only visible for zero or nearly zero eigenvalues.
405
+
406
+ For the generalized problem, normalization with respect to the given
407
+ type argument::
408
+
409
+ type 1 and 3 : v.conj().T @ a @ v = w
410
+ type 2 : inv(v).conj().T @ a @ inv(v) = w
411
+
412
+ type 1 or 2 : v.conj().T @ b @ v = I
413
+ type 3 : v.conj().T @ inv(b) @ v = I
414
+
415
+
416
+ Examples
417
+ --------
418
+ >>> import numpy as np
419
+ >>> from scipy.linalg import eigh
420
+ >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]])
421
+ >>> w, v = eigh(A)
422
+ >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
423
+ True
424
+
425
+ Request only the eigenvalues
426
+
427
+ >>> w = eigh(A, eigvals_only=True)
428
+
429
+ Request eigenvalues that are less than 10.
430
+
431
+ >>> A = np.array([[34, -4, -10, -7, 2],
432
+ ... [-4, 7, 2, 12, 0],
433
+ ... [-10, 2, 44, 2, -19],
434
+ ... [-7, 12, 2, 79, -34],
435
+ ... [2, 0, -19, -34, 29]])
436
+ >>> eigh(A, eigvals_only=True, subset_by_value=[-np.inf, 10])
437
+ array([6.69199443e-07, 9.11938152e+00])
438
+
439
+ Request the second smallest eigenvalue and its eigenvector
440
+
441
+ >>> w, v = eigh(A, subset_by_index=[1, 1])
442
+ >>> w
443
+ array([9.11938152])
444
+ >>> v.shape # only a single column is returned
445
+ (5, 1)
446
+
447
+ """
448
+ # set lower
449
+ uplo = 'L' if lower else 'U'
450
+ # Set job for Fortran routines
451
+ _job = 'N' if eigvals_only else 'V'
452
+
453
+ drv_str = [None, "ev", "evd", "evr", "evx", "gv", "gvd", "gvx"]
454
+ if driver not in drv_str:
455
+ raise ValueError('"{}" is unknown. Possible values are "None", "{}".'
456
+ ''.format(driver, '", "'.join(drv_str[1:])))
457
+
458
+ a1 = _asarray_validated(a, check_finite=check_finite)
459
+ if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
460
+ raise ValueError('expected square "a" matrix')
461
+
462
+ # accommodate square empty matrices
463
+ if a1.size == 0:
464
+ w_n, v_n = eigh(np.eye(2, dtype=a1.dtype))
465
+
466
+ w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
467
+ v = np.empty_like(a1, shape=(0, 0), dtype=v_n.dtype)
468
+ if eigvals_only:
469
+ return w
470
+ else:
471
+ return w, v
472
+
473
+ overwrite_a = overwrite_a or (_datacopied(a1, a))
474
+ cplx = True if iscomplexobj(a1) else False
475
+ n = a1.shape[0]
476
+ drv_args = {'overwrite_a': overwrite_a}
477
+
478
+ if b is not None:
479
+ b1 = _asarray_validated(b, check_finite=check_finite)
480
+ overwrite_b = overwrite_b or _datacopied(b1, b)
481
+ if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:
482
+ raise ValueError('expected square "b" matrix')
483
+
484
+ if b1.shape != a1.shape:
485
+ raise ValueError(f"wrong b dimensions {b1.shape}, should be {a1.shape}")
486
+
487
+ if type not in [1, 2, 3]:
488
+ raise ValueError('"type" keyword only accepts 1, 2, and 3.')
489
+
490
+ cplx = True if iscomplexobj(b1) else (cplx or False)
491
+ drv_args.update({'overwrite_b': overwrite_b, 'itype': type})
492
+
493
+ subset = (subset_by_index is not None) or (subset_by_value is not None)
494
+
495
+ # Both subsets can't be given
496
+ if subset_by_index and subset_by_value:
497
+ raise ValueError('Either index or value subset can be requested.')
498
+
499
+ # Check indices if given
500
+ if subset_by_index:
501
+ lo, hi = (int(x) for x in subset_by_index)
502
+ if not (0 <= lo <= hi < n):
503
+ raise ValueError('Requested eigenvalue indices are not valid. '
504
+ f'Valid range is [0, {n-1}] and start <= end, but '
505
+ f'start={lo}, end={hi} is given')
506
+ # fortran is 1-indexed
507
+ drv_args.update({'range': 'I', 'il': lo + 1, 'iu': hi + 1})
508
+
509
+ if subset_by_value:
510
+ lo, hi = subset_by_value
511
+ if not (-inf <= lo < hi <= inf):
512
+ raise ValueError('Requested eigenvalue bounds are not valid. '
513
+ 'Valid range is (-inf, inf) and low < high, but '
514
+ f'low={lo}, high={hi} is given')
515
+
516
+ drv_args.update({'range': 'V', 'vl': lo, 'vu': hi})
517
+
518
+ # fix prefix for lapack routines
519
+ pfx = 'he' if cplx else 'sy'
520
+
521
+ # decide on the driver if not given
522
+ # first early exit on incompatible choice
523
+ if driver:
524
+ if b is None and (driver in ["gv", "gvd", "gvx"]):
525
+ raise ValueError(f'{driver} requires input b array to be supplied '
526
+ 'for generalized eigenvalue problems.')
527
+ if (b is not None) and (driver in ['ev', 'evd', 'evr', 'evx']):
528
+ raise ValueError(f'"{driver}" does not accept input b array '
529
+ 'for standard eigenvalue problems.')
530
+ if subset and (driver in ["ev", "evd", "gv", "gvd"]):
531
+ raise ValueError(f'"{driver}" cannot compute subsets of eigenvalues')
532
+
533
+ # Default driver is evr and gvd
534
+ else:
535
+ driver = "evr" if b is None else ("gvx" if subset else "gvd")
536
+
537
+ lwork_spec = {
538
+ 'syevd': ['lwork', 'liwork'],
539
+ 'syevr': ['lwork', 'liwork'],
540
+ 'heevd': ['lwork', 'liwork', 'lrwork'],
541
+ 'heevr': ['lwork', 'lrwork', 'liwork'],
542
+ }
543
+
544
+ if b is None: # Standard problem
545
+ drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'),
546
+ [a1])
547
+ clw_args = {'n': n, 'lower': lower}
548
+ if driver == 'evd':
549
+ clw_args.update({'compute_v': 0 if _job == "N" else 1})
550
+
551
+ lw = _compute_lwork(drvlw, **clw_args)
552
+ # Multiple lwork vars
553
+ if isinstance(lw, tuple):
554
+ lwork_args = dict(zip(lwork_spec[pfx+driver], lw))
555
+ else:
556
+ lwork_args = {'lwork': lw}
557
+
558
+ drv_args.update({'lower': lower, 'compute_v': 0 if _job == "N" else 1})
559
+ w, v, *other_args, info = drv(a=a1, **drv_args, **lwork_args)
560
+
561
+ else: # Generalized problem
562
+ # 'gvd' doesn't have lwork query
563
+ if driver == "gvd":
564
+ drv = get_lapack_funcs(pfx + "gvd", [a1, b1])
565
+ lwork_args = {}
566
+ else:
567
+ drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'),
568
+ [a1, b1])
569
+ # generalized drivers use uplo instead of lower
570
+ lw = _compute_lwork(drvlw, n, uplo=uplo)
571
+ lwork_args = {'lwork': lw}
572
+
573
+ drv_args.update({'uplo': uplo, 'jobz': _job})
574
+
575
+ w, v, *other_args, info = drv(a=a1, b=b1, **drv_args, **lwork_args)
576
+
577
+ # m is always the first extra argument
578
+ w = w[:other_args[0]] if subset else w
579
+ v = v[:, :other_args[0]] if (subset and not eigvals_only) else v
580
+
581
+ # Check if we had a successful exit
582
+ if info == 0:
583
+ if eigvals_only:
584
+ return w
585
+ else:
586
+ return w, v
587
+ else:
588
+ if info < -1:
589
+ raise LinAlgError(f'Illegal value in argument {-info} of internal '
590
+ f'{drv.typecode + pfx + driver}')
591
+ elif info > n:
592
+ raise LinAlgError(f'The leading minor of order {info-n} of B is not '
593
+ 'positive definite. The factorization of B '
594
+ 'could not be completed and no eigenvalues '
595
+ 'or eigenvectors were computed.')
596
+ else:
597
+ drv_err = {'ev': 'The algorithm failed to converge; {} '
598
+ 'off-diagonal elements of an intermediate '
599
+ 'tridiagonal form did not converge to zero.',
600
+ 'evx': '{} eigenvectors failed to converge.',
601
+ 'evd': 'The algorithm failed to compute an eigenvalue '
602
+ 'while working on the submatrix lying in rows '
603
+ 'and columns {0}/{1} through mod({0},{1}).',
604
+ 'evr': 'Internal Error.'
605
+ }
606
+ if driver in ['ev', 'gv']:
607
+ msg = drv_err['ev'].format(info)
608
+ elif driver in ['evx', 'gvx']:
609
+ msg = drv_err['evx'].format(info)
610
+ elif driver in ['evd', 'gvd']:
611
+ if eigvals_only:
612
+ msg = drv_err['ev'].format(info)
613
+ else:
614
+ msg = drv_err['evd'].format(info, n+1)
615
+ else:
616
+ msg = drv_err['evr']
617
+
618
+ raise LinAlgError(msg)
619
+
620
+
621
+ _conv_dict = {0: 0, 1: 1, 2: 2,
622
+ 'all': 0, 'value': 1, 'index': 2,
623
+ 'a': 0, 'v': 1, 'i': 2}
624
+
625
+
626
+ def _check_select(select, select_range, max_ev, max_len):
627
+ """Check that select is valid, convert to Fortran style."""
628
+ if isinstance(select, str):
629
+ select = select.lower()
630
+ try:
631
+ select = _conv_dict[select]
632
+ except KeyError as e:
633
+ raise ValueError('invalid argument for select') from e
634
+ vl, vu = 0., 1.
635
+ il = iu = 1
636
+ if select != 0: # (non-all)
637
+ sr = asarray(select_range)
638
+ if sr.ndim != 1 or sr.size != 2 or sr[1] < sr[0]:
639
+ raise ValueError('select_range must be a 2-element array-like '
640
+ 'in nondecreasing order')
641
+ if select == 1: # (value)
642
+ vl, vu = sr
643
+ if max_ev == 0:
644
+ max_ev = max_len
645
+ else: # 2 (index)
646
+ if sr.dtype.char.lower() not in 'hilqp':
647
+ raise ValueError(
648
+ f'when using select="i", select_range must '
649
+ f'contain integers, got dtype {sr.dtype} ({sr.dtype.char})'
650
+ )
651
+ # translate Python (0 ... N-1) into Fortran (1 ... N) with + 1
652
+ il, iu = sr + 1
653
+ if min(il, iu) < 1 or max(il, iu) > max_len:
654
+ raise ValueError('select_range out of bounds')
655
+ max_ev = iu - il + 1
656
+ return select, vl, vu, il, iu, max_ev
657
+
658
+
659
+ def eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False,
660
+ select='a', select_range=None, max_ev=0, check_finite=True):
661
+ """
662
+ Solve real symmetric or complex Hermitian band matrix eigenvalue problem.
663
+
664
+ Find eigenvalues w and optionally right eigenvectors v of a::
665
+
666
+ a v[:,i] = w[i] v[:,i]
667
+ v.H v = identity
668
+
669
+ The matrix a is stored in a_band either in lower diagonal or upper
670
+ diagonal ordered form:
671
+
672
+ a_band[u + i - j, j] == a[i,j] (if upper form; i <= j)
673
+ a_band[ i - j, j] == a[i,j] (if lower form; i >= j)
674
+
675
+ where u is the number of bands above the diagonal.
676
+
677
+ Example of a_band (shape of a is (6,6), u=2)::
678
+
679
+ upper form:
680
+ * * a02 a13 a24 a35
681
+ * a01 a12 a23 a34 a45
682
+ a00 a11 a22 a33 a44 a55
683
+
684
+ lower form:
685
+ a00 a11 a22 a33 a44 a55
686
+ a10 a21 a32 a43 a54 *
687
+ a20 a31 a42 a53 * *
688
+
689
+ Cells marked with * are not used.
690
+
691
+ Parameters
692
+ ----------
693
+ a_band : (u+1, M) array_like
694
+ The bands of the M by M matrix a.
695
+ lower : bool, optional
696
+ Is the matrix in the lower form. (Default is upper form)
697
+ eigvals_only : bool, optional
698
+ Compute only the eigenvalues and no eigenvectors.
699
+ (Default: calculate also eigenvectors)
700
+ overwrite_a_band : bool, optional
701
+ Discard data in a_band (may enhance performance)
702
+ select : {'a', 'v', 'i'}, optional
703
+ Which eigenvalues to calculate
704
+
705
+ ====== ========================================
706
+ select calculated
707
+ ====== ========================================
708
+ 'a' All eigenvalues
709
+ 'v' Eigenvalues in the interval (min, max]
710
+ 'i' Eigenvalues with indices min <= i <= max
711
+ ====== ========================================
712
+ select_range : (min, max), optional
713
+ Range of selected eigenvalues
714
+ max_ev : int, optional
715
+ For select=='v', maximum number of eigenvalues expected.
716
+ For other values of select, has no meaning.
717
+
718
+ In doubt, leave this parameter untouched.
719
+
720
+ check_finite : bool, optional
721
+ Whether to check that the input matrix contains only finite numbers.
722
+ Disabling may give a performance gain, but may result in problems
723
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
724
+
725
+ Returns
726
+ -------
727
+ w : (M,) ndarray
728
+ The eigenvalues, in ascending order, each repeated according to its
729
+ multiplicity.
730
+ v : (M, M) float or complex ndarray
731
+ The normalized eigenvector corresponding to the eigenvalue w[i] is
732
+ the column v[:,i]. Only returned if ``eigvals_only=False``.
733
+
734
+ Raises
735
+ ------
736
+ LinAlgError
737
+ If eigenvalue computation does not converge.
738
+
739
+ See Also
740
+ --------
741
+ eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
742
+ eig : eigenvalues and right eigenvectors of general arrays.
743
+ eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
744
+ eigh_tridiagonal : eigenvalues and right eigenvectors for
745
+ symmetric/Hermitian tridiagonal matrices
746
+
747
+ Examples
748
+ --------
749
+ >>> import numpy as np
750
+ >>> from scipy.linalg import eig_banded
751
+ >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]])
752
+ >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]])
753
+ >>> w, v = eig_banded(Ab, lower=True)
754
+ >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
755
+ True
756
+ >>> w = eig_banded(Ab, lower=True, eigvals_only=True)
757
+ >>> w
758
+ array([-4.26200532, -2.22987175, 3.95222349, 12.53965359])
759
+
760
+ Request only the eigenvalues between ``[-3, 4]``
761
+
762
+ >>> w, v = eig_banded(Ab, lower=True, select='v', select_range=[-3, 4])
763
+ >>> w
764
+ array([-2.22987175, 3.95222349])
765
+
766
+ """
767
+ if eigvals_only or overwrite_a_band:
768
+ a1 = _asarray_validated(a_band, check_finite=check_finite)
769
+ overwrite_a_band = overwrite_a_band or (_datacopied(a1, a_band))
770
+ else:
771
+ a1 = array(a_band)
772
+ if issubclass(a1.dtype.type, inexact) and not isfinite(a1).all():
773
+ raise ValueError("array must not contain infs or NaNs")
774
+ overwrite_a_band = 1
775
+
776
+ if len(a1.shape) != 2:
777
+ raise ValueError('expected a 2-D array')
778
+
779
+ # accommodate square empty matrices
780
+ if a1.size == 0:
781
+ w_n, v_n = eig_banded(np.array([[0, 0], [1, 1]], dtype=a1.dtype))
782
+
783
+ w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
784
+ v = np.empty_like(a1, shape=(0, 0), dtype=v_n.dtype)
785
+ if eigvals_only:
786
+ return w
787
+ else:
788
+ return w, v
789
+
790
+ select, vl, vu, il, iu, max_ev = _check_select(
791
+ select, select_range, max_ev, a1.shape[1])
792
+
793
+ del select_range
794
+ if select == 0:
795
+ if a1.dtype.char in 'GFD':
796
+ # FIXME: implement this somewhen, for now go with builtin values
797
+ # FIXME: calc optimal lwork by calling ?hbevd(lwork=-1)
798
+ # or by using calc_lwork.f ???
799
+ # lwork = calc_lwork.hbevd(bevd.typecode, a1.shape[0], lower)
800
+ internal_name = 'hbevd'
801
+ else: # a1.dtype.char in 'fd':
802
+ # FIXME: implement this somewhen, for now go with builtin values
803
+ # see above
804
+ # lwork = calc_lwork.sbevd(bevd.typecode, a1.shape[0], lower)
805
+ internal_name = 'sbevd'
806
+ bevd, = get_lapack_funcs((internal_name,), (a1,))
807
+ w, v, info = bevd(a1, compute_v=not eigvals_only,
808
+ lower=lower, overwrite_ab=overwrite_a_band)
809
+ else: # select in [1, 2]
810
+ if eigvals_only:
811
+ max_ev = 1
812
+ # calculate optimal abstol for dsbevx (see manpage)
813
+ if a1.dtype.char in 'fF': # single precision
814
+ lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='f'),))
815
+ else:
816
+ lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='d'),))
817
+ abstol = 2 * lamch('s')
818
+ if a1.dtype.char in 'GFD':
819
+ internal_name = 'hbevx'
820
+ else: # a1.dtype.char in 'gfd'
821
+ internal_name = 'sbevx'
822
+ bevx, = get_lapack_funcs((internal_name,), (a1,))
823
+ w, v, m, ifail, info = bevx(
824
+ a1, vl, vu, il, iu, compute_v=not eigvals_only, mmax=max_ev,
825
+ range=select, lower=lower, overwrite_ab=overwrite_a_band,
826
+ abstol=abstol)
827
+ # crop off w and v
828
+ w = w[:m]
829
+ if not eigvals_only:
830
+ v = v[:, :m]
831
+ _check_info(info, internal_name)
832
+
833
+ if eigvals_only:
834
+ return w
835
+ return w, v
836
+
837
+
838
+ def eigvals(a, b=None, overwrite_a=False, check_finite=True,
839
+ homogeneous_eigvals=False):
840
+ """
841
+ Compute eigenvalues from an ordinary or generalized eigenvalue problem.
842
+
843
+ Find eigenvalues of a general matrix::
844
+
845
+ a vr[:,i] = w[i] b vr[:,i]
846
+
847
+ Parameters
848
+ ----------
849
+ a : (M, M) array_like
850
+ A complex or real matrix whose eigenvalues and eigenvectors
851
+ will be computed.
852
+ b : (M, M) array_like, optional
853
+ Right-hand side matrix in a generalized eigenvalue problem.
854
+ If omitted, identity matrix is assumed.
855
+ overwrite_a : bool, optional
856
+ Whether to overwrite data in a (may improve performance)
857
+ check_finite : bool, optional
858
+ Whether to check that the input matrices contain only finite numbers.
859
+ Disabling may give a performance gain, but may result in problems
860
+ (crashes, non-termination) if the inputs do contain infinities
861
+ or NaNs.
862
+ homogeneous_eigvals : bool, optional
863
+ If True, return the eigenvalues in homogeneous coordinates.
864
+ In this case ``w`` is a (2, M) array so that::
865
+
866
+ w[1,i] a vr[:,i] = w[0,i] b vr[:,i]
867
+
868
+ Default is False.
869
+
870
+ Returns
871
+ -------
872
+ w : (M,) or (2, M) double or complex ndarray
873
+ The eigenvalues, each repeated according to its multiplicity
874
+ but not in any specific order. The shape is (M,) unless
875
+ ``homogeneous_eigvals=True``.
876
+
877
+ Raises
878
+ ------
879
+ LinAlgError
880
+ If eigenvalue computation does not converge
881
+
882
+ See Also
883
+ --------
884
+ eig : eigenvalues and right eigenvectors of general arrays.
885
+ eigvalsh : eigenvalues of symmetric or Hermitian arrays
886
+ eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
887
+ eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
888
+ matrices
889
+
890
+ Examples
891
+ --------
892
+ >>> import numpy as np
893
+ >>> from scipy import linalg
894
+ >>> a = np.array([[0., -1.], [1., 0.]])
895
+ >>> linalg.eigvals(a)
896
+ array([0.+1.j, 0.-1.j])
897
+
898
+ >>> b = np.array([[0., 1.], [1., 1.]])
899
+ >>> linalg.eigvals(a, b)
900
+ array([ 1.+0.j, -1.+0.j])
901
+
902
+ >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]])
903
+ >>> linalg.eigvals(a, homogeneous_eigvals=True)
904
+ array([[3.+0.j, 8.+0.j, 7.+0.j],
905
+ [1.+0.j, 1.+0.j, 1.+0.j]])
906
+
907
+ """
908
+ return eig(a, b=b, left=0, right=0, overwrite_a=overwrite_a,
909
+ check_finite=check_finite,
910
+ homogeneous_eigvals=homogeneous_eigvals)
911
+
912
+
913
+ def eigvalsh(a, b=None, *, lower=True, overwrite_a=False,
914
+ overwrite_b=False, type=1, check_finite=True, subset_by_index=None,
915
+ subset_by_value=None, driver=None):
916
+ """
917
+ Solves a standard or generalized eigenvalue problem for a complex
918
+ Hermitian or real symmetric matrix.
919
+
920
+ Find eigenvalues array ``w`` of array ``a``, where ``b`` is positive
921
+ definite such that for every eigenvalue λ (i-th entry of w) and its
922
+ eigenvector vi (i-th column of v) satisfies::
923
+
924
+ a @ vi = λ * b @ vi
925
+ vi.conj().T @ a @ vi = λ
926
+ vi.conj().T @ b @ vi = 1
927
+
928
+ In the standard problem, b is assumed to be the identity matrix.
929
+
930
+ Parameters
931
+ ----------
932
+ a : (M, M) array_like
933
+ A complex Hermitian or real symmetric matrix whose eigenvalues will
934
+ be computed.
935
+ b : (M, M) array_like, optional
936
+ A complex Hermitian or real symmetric definite positive matrix in.
937
+ If omitted, identity matrix is assumed.
938
+ lower : bool, optional
939
+ Whether the pertinent array data is taken from the lower or upper
940
+ triangle of ``a`` and, if applicable, ``b``. (Default: lower)
941
+ overwrite_a : bool, optional
942
+ Whether to overwrite data in ``a`` (may improve performance). Default
943
+ is False.
944
+ overwrite_b : bool, optional
945
+ Whether to overwrite data in ``b`` (may improve performance). Default
946
+ is False.
947
+ type : int, optional
948
+ For the generalized problems, this keyword specifies the problem type
949
+ to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible
950
+ inputs)::
951
+
952
+ 1 => a @ v = w @ b @ v
953
+ 2 => a @ b @ v = w @ v
954
+ 3 => b @ a @ v = w @ v
955
+
956
+ This keyword is ignored for standard problems.
957
+ check_finite : bool, optional
958
+ Whether to check that the input matrices contain only finite numbers.
959
+ Disabling may give a performance gain, but may result in problems
960
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
961
+ subset_by_index : iterable, optional
962
+ If provided, this two-element iterable defines the start and the end
963
+ indices of the desired eigenvalues (ascending order and 0-indexed).
964
+ To return only the second smallest to fifth smallest eigenvalues,
965
+ ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only
966
+ available with "evr", "evx", and "gvx" drivers. The entries are
967
+ directly converted to integers via ``int()``.
968
+ subset_by_value : iterable, optional
969
+ If provided, this two-element iterable defines the half-open interval
970
+ ``(a, b]`` that, if any, only the eigenvalues between these values
971
+ are returned. Only available with "evr", "evx", and "gvx" drivers. Use
972
+ ``np.inf`` for the unconstrained ends.
973
+ driver : str, optional
974
+ Defines which LAPACK driver should be used. Valid options are "ev",
975
+ "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for
976
+ generalized (where b is not None) problems. See the Notes section of
977
+ `scipy.linalg.eigh`.
978
+
979
+ Returns
980
+ -------
981
+ w : (N,) ndarray
982
+ The N (N<=M) selected eigenvalues, in ascending order, each
983
+ repeated according to its multiplicity.
984
+
985
+ Raises
986
+ ------
987
+ LinAlgError
988
+ If eigenvalue computation does not converge, an error occurred, or
989
+ b matrix is not definite positive. Note that if input matrices are
990
+ not symmetric or Hermitian, no error will be reported but results will
991
+ be wrong.
992
+
993
+ See Also
994
+ --------
995
+ eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
996
+ eigvals : eigenvalues of general arrays
997
+ eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
998
+ eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
999
+ matrices
1000
+
1001
+ Notes
1002
+ -----
1003
+ This function does not check the input array for being Hermitian/symmetric
1004
+ in order to allow for representing arrays with only their upper/lower
1005
+ triangular parts.
1006
+
1007
+ This function serves as a one-liner shorthand for `scipy.linalg.eigh` with
1008
+ the option ``eigvals_only=True`` to get the eigenvalues and not the
1009
+ eigenvectors. Here it is kept as a legacy convenience. It might be
1010
+ beneficial to use the main function to have full control and to be a bit
1011
+ more pythonic.
1012
+
1013
+ Examples
1014
+ --------
1015
+ For more examples see `scipy.linalg.eigh`.
1016
+
1017
+ >>> import numpy as np
1018
+ >>> from scipy.linalg import eigvalsh
1019
+ >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]])
1020
+ >>> w = eigvalsh(A)
1021
+ >>> w
1022
+ array([-3.74637491, -0.76263923, 6.08502336, 12.42399079])
1023
+
1024
+ """
1025
+ return eigh(a, b=b, lower=lower, eigvals_only=True, overwrite_a=overwrite_a,
1026
+ overwrite_b=overwrite_b, type=type, check_finite=check_finite,
1027
+ subset_by_index=subset_by_index, subset_by_value=subset_by_value,
1028
+ driver=driver)
1029
+
1030
+
1031
+ def eigvals_banded(a_band, lower=False, overwrite_a_band=False,
1032
+ select='a', select_range=None, check_finite=True):
1033
+ """
1034
+ Solve real symmetric or complex Hermitian band matrix eigenvalue problem.
1035
+
1036
+ Find eigenvalues w of a::
1037
+
1038
+ a v[:,i] = w[i] v[:,i]
1039
+ v.H v = identity
1040
+
1041
+ The matrix a is stored in a_band either in lower diagonal or upper
1042
+ diagonal ordered form:
1043
+
1044
+ a_band[u + i - j, j] == a[i,j] (if upper form; i <= j)
1045
+ a_band[ i - j, j] == a[i,j] (if lower form; i >= j)
1046
+
1047
+ where u is the number of bands above the diagonal.
1048
+
1049
+ Example of a_band (shape of a is (6,6), u=2)::
1050
+
1051
+ upper form:
1052
+ * * a02 a13 a24 a35
1053
+ * a01 a12 a23 a34 a45
1054
+ a00 a11 a22 a33 a44 a55
1055
+
1056
+ lower form:
1057
+ a00 a11 a22 a33 a44 a55
1058
+ a10 a21 a32 a43 a54 *
1059
+ a20 a31 a42 a53 * *
1060
+
1061
+ Cells marked with * are not used.
1062
+
1063
+ Parameters
1064
+ ----------
1065
+ a_band : (u+1, M) array_like
1066
+ The bands of the M by M matrix a.
1067
+ lower : bool, optional
1068
+ Is the matrix in the lower form. (Default is upper form)
1069
+ overwrite_a_band : bool, optional
1070
+ Discard data in a_band (may enhance performance)
1071
+ select : {'a', 'v', 'i'}, optional
1072
+ Which eigenvalues to calculate
1073
+
1074
+ ====== ========================================
1075
+ select calculated
1076
+ ====== ========================================
1077
+ 'a' All eigenvalues
1078
+ 'v' Eigenvalues in the interval (min, max]
1079
+ 'i' Eigenvalues with indices min <= i <= max
1080
+ ====== ========================================
1081
+ select_range : (min, max), optional
1082
+ Range of selected eigenvalues
1083
+ check_finite : bool, optional
1084
+ Whether to check that the input matrix contains only finite numbers.
1085
+ Disabling may give a performance gain, but may result in problems
1086
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
1087
+
1088
+ Returns
1089
+ -------
1090
+ w : (M,) ndarray
1091
+ The eigenvalues, in ascending order, each repeated according to its
1092
+ multiplicity.
1093
+
1094
+ Raises
1095
+ ------
1096
+ LinAlgError
1097
+ If eigenvalue computation does not converge.
1098
+
1099
+ See Also
1100
+ --------
1101
+ eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
1102
+ band matrices
1103
+ eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
1104
+ matrices
1105
+ eigvals : eigenvalues of general arrays
1106
+ eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
1107
+ eig : eigenvalues and right eigenvectors for non-symmetric arrays
1108
+
1109
+ Examples
1110
+ --------
1111
+ >>> import numpy as np
1112
+ >>> from scipy.linalg import eigvals_banded
1113
+ >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]])
1114
+ >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]])
1115
+ >>> w = eigvals_banded(Ab, lower=True)
1116
+ >>> w
1117
+ array([-4.26200532, -2.22987175, 3.95222349, 12.53965359])
1118
+ """
1119
+ return eig_banded(a_band, lower=lower, eigvals_only=1,
1120
+ overwrite_a_band=overwrite_a_band, select=select,
1121
+ select_range=select_range, check_finite=check_finite)
1122
+
1123
+
1124
+ def eigvalsh_tridiagonal(d, e, select='a', select_range=None,
1125
+ check_finite=True, tol=0., lapack_driver='auto'):
1126
+ """
1127
+ Solve eigenvalue problem for a real symmetric tridiagonal matrix.
1128
+
1129
+ Find eigenvalues `w` of ``a``::
1130
+
1131
+ a v[:,i] = w[i] v[:,i]
1132
+ v.H v = identity
1133
+
1134
+ For a real symmetric matrix ``a`` with diagonal elements `d` and
1135
+ off-diagonal elements `e`.
1136
+
1137
+ Parameters
1138
+ ----------
1139
+ d : ndarray, shape (ndim,)
1140
+ The diagonal elements of the array.
1141
+ e : ndarray, shape (ndim-1,)
1142
+ The off-diagonal elements of the array.
1143
+ select : {'a', 'v', 'i'}, optional
1144
+ Which eigenvalues to calculate
1145
+
1146
+ ====== ========================================
1147
+ select calculated
1148
+ ====== ========================================
1149
+ 'a' All eigenvalues
1150
+ 'v' Eigenvalues in the interval (min, max]
1151
+ 'i' Eigenvalues with indices min <= i <= max
1152
+ ====== ========================================
1153
+ select_range : (min, max), optional
1154
+ Range of selected eigenvalues
1155
+ check_finite : bool, optional
1156
+ Whether to check that the input matrix contains only finite numbers.
1157
+ Disabling may give a performance gain, but may result in problems
1158
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
1159
+ tol : float
1160
+ The absolute tolerance to which each eigenvalue is required
1161
+ (only used when ``lapack_driver='stebz'``).
1162
+ An eigenvalue (or cluster) is considered to have converged if it
1163
+ lies in an interval of this width. If <= 0. (default),
1164
+ the value ``eps*|a|`` is used where eps is the machine precision,
1165
+ and ``|a|`` is the 1-norm of the matrix ``a``.
1166
+ lapack_driver : str
1167
+ LAPACK function to use, can be 'auto', 'stemr', 'stebz', 'sterf',
1168
+ or 'stev'. When 'auto' (default), it will use 'stemr' if ``select='a'``
1169
+ and 'stebz' otherwise. 'sterf' and 'stev' can only be used when
1170
+ ``select='a'``.
1171
+
1172
+ Returns
1173
+ -------
1174
+ w : (M,) ndarray
1175
+ The eigenvalues, in ascending order, each repeated according to its
1176
+ multiplicity.
1177
+
1178
+ Raises
1179
+ ------
1180
+ LinAlgError
1181
+ If eigenvalue computation does not converge.
1182
+
1183
+ See Also
1184
+ --------
1185
+ eigh_tridiagonal : eigenvalues and right eiegenvectors for
1186
+ symmetric/Hermitian tridiagonal matrices
1187
+
1188
+ Examples
1189
+ --------
1190
+ >>> import numpy as np
1191
+ >>> from scipy.linalg import eigvalsh_tridiagonal, eigvalsh
1192
+ >>> d = 3*np.ones(4)
1193
+ >>> e = -1*np.ones(3)
1194
+ >>> w = eigvalsh_tridiagonal(d, e)
1195
+ >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1)
1196
+ >>> w2 = eigvalsh(A) # Verify with other eigenvalue routines
1197
+ >>> np.allclose(w - w2, np.zeros(4))
1198
+ True
1199
+ """
1200
+ return eigh_tridiagonal(
1201
+ d, e, eigvals_only=True, select=select, select_range=select_range,
1202
+ check_finite=check_finite, tol=tol, lapack_driver=lapack_driver)
1203
+
1204
+
1205
+ def eigh_tridiagonal(d, e, eigvals_only=False, select='a', select_range=None,
1206
+ check_finite=True, tol=0., lapack_driver='auto'):
1207
+ """
1208
+ Solve eigenvalue problem for a real symmetric tridiagonal matrix.
1209
+
1210
+ Find eigenvalues `w` and optionally right eigenvectors `v` of ``a``::
1211
+
1212
+ a v[:,i] = w[i] v[:,i]
1213
+ v.H v = identity
1214
+
1215
+ For a real symmetric matrix ``a`` with diagonal elements `d` and
1216
+ off-diagonal elements `e`.
1217
+
1218
+ Parameters
1219
+ ----------
1220
+ d : ndarray, shape (ndim,)
1221
+ The diagonal elements of the array.
1222
+ e : ndarray, shape (ndim-1,)
1223
+ The off-diagonal elements of the array.
1224
+ eigvals_only : bool, optional
1225
+ Compute only the eigenvalues and no eigenvectors.
1226
+ (Default: calculate also eigenvectors)
1227
+ select : {'a', 'v', 'i'}, optional
1228
+ Which eigenvalues to calculate
1229
+
1230
+ ====== ========================================
1231
+ select calculated
1232
+ ====== ========================================
1233
+ 'a' All eigenvalues
1234
+ 'v' Eigenvalues in the interval (min, max]
1235
+ 'i' Eigenvalues with indices min <= i <= max
1236
+ ====== ========================================
1237
+ select_range : (min, max), optional
1238
+ Range of selected eigenvalues
1239
+ check_finite : bool, optional
1240
+ Whether to check that the input matrix contains only finite numbers.
1241
+ Disabling may give a performance gain, but may result in problems
1242
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
1243
+ tol : float
1244
+ The absolute tolerance to which each eigenvalue is required
1245
+ (only used when 'stebz' is the `lapack_driver`).
1246
+ An eigenvalue (or cluster) is considered to have converged if it
1247
+ lies in an interval of this width. If <= 0. (default),
1248
+ the value ``eps*|a|`` is used where eps is the machine precision,
1249
+ and ``|a|`` is the 1-norm of the matrix ``a``.
1250
+ lapack_driver : str
1251
+ LAPACK function to use, can be 'auto', 'stemr', 'stebz', 'sterf',
1252
+ or 'stev'. When 'auto' (default), it will use 'stemr' if ``select='a'``
1253
+ and 'stebz' otherwise. When 'stebz' is used to find the eigenvalues and
1254
+ ``eigvals_only=False``, then a second LAPACK call (to ``?STEIN``) is
1255
+ used to find the corresponding eigenvectors. 'sterf' can only be
1256
+ used when ``eigvals_only=True`` and ``select='a'``. 'stev' can only
1257
+ be used when ``select='a'``.
1258
+
1259
+ Returns
1260
+ -------
1261
+ w : (M,) ndarray
1262
+ The eigenvalues, in ascending order, each repeated according to its
1263
+ multiplicity.
1264
+ v : (M, M) ndarray
1265
+ The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
1266
+ the column ``v[:,i]``. Only returned if ``eigvals_only=False``.
1267
+
1268
+ Raises
1269
+ ------
1270
+ LinAlgError
1271
+ If eigenvalue computation does not converge.
1272
+
1273
+ See Also
1274
+ --------
1275
+ eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
1276
+ matrices
1277
+ eig : eigenvalues and right eigenvectors for non-symmetric arrays
1278
+ eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
1279
+ eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
1280
+ band matrices
1281
+
1282
+ Notes
1283
+ -----
1284
+ This function makes use of LAPACK ``S/DSTEMR`` routines.
1285
+
1286
+ Examples
1287
+ --------
1288
+ >>> import numpy as np
1289
+ >>> from scipy.linalg import eigh_tridiagonal
1290
+ >>> d = 3*np.ones(4)
1291
+ >>> e = -1*np.ones(3)
1292
+ >>> w, v = eigh_tridiagonal(d, e)
1293
+ >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1)
1294
+ >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
1295
+ True
1296
+ """
1297
+ d = _asarray_validated(d, check_finite=check_finite)
1298
+ e = _asarray_validated(e, check_finite=check_finite)
1299
+ for check in (d, e):
1300
+ if check.ndim != 1:
1301
+ raise ValueError('expected a 1-D array')
1302
+ if check.dtype.char in 'GFD': # complex
1303
+ raise TypeError('Only real arrays currently supported')
1304
+ if d.size != e.size + 1:
1305
+ raise ValueError(f'd ({d.size}) must have one more element than e ({e.size})')
1306
+ select, vl, vu, il, iu, _ = _check_select(
1307
+ select, select_range, 0, d.size)
1308
+ if not isinstance(lapack_driver, str):
1309
+ raise TypeError('lapack_driver must be str')
1310
+ drivers = ('auto', 'stemr', 'sterf', 'stebz', 'stev')
1311
+ if lapack_driver not in drivers:
1312
+ raise ValueError(f'lapack_driver must be one of {drivers}, '
1313
+ f'got {lapack_driver}')
1314
+ if lapack_driver == 'auto':
1315
+ lapack_driver = 'stemr' if select == 0 else 'stebz'
1316
+
1317
+ # Quick exit for 1x1 case
1318
+ if len(d) == 1:
1319
+ if select == 1 and (not (vl < d[0] <= vu)): # request by value
1320
+ w = array([])
1321
+ v = empty([1, 0], dtype=d.dtype)
1322
+ else: # all and request by index
1323
+ w = array([d[0]], dtype=d.dtype)
1324
+ v = array([[1.]], dtype=d.dtype)
1325
+
1326
+ if eigvals_only:
1327
+ return w
1328
+ else:
1329
+ return w, v
1330
+
1331
+ func, = get_lapack_funcs((lapack_driver,), (d, e))
1332
+ compute_v = not eigvals_only
1333
+ if lapack_driver == 'sterf':
1334
+ if select != 0:
1335
+ raise ValueError('sterf can only be used when select == "a"')
1336
+ if not eigvals_only:
1337
+ raise ValueError('sterf can only be used when eigvals_only is '
1338
+ 'True')
1339
+ w, info = func(d, e)
1340
+ m = len(w)
1341
+ elif lapack_driver == 'stev':
1342
+ if select != 0:
1343
+ raise ValueError('stev can only be used when select == "a"')
1344
+ w, v, info = func(d, e, compute_v=compute_v)
1345
+ m = len(w)
1346
+ elif lapack_driver == 'stebz':
1347
+ tol = float(tol)
1348
+ internal_name = 'stebz'
1349
+ stebz, = get_lapack_funcs((internal_name,), (d, e))
1350
+ # If getting eigenvectors, needs to be block-ordered (B) instead of
1351
+ # matrix-ordered (E), and we will reorder later
1352
+ order = 'E' if eigvals_only else 'B'
1353
+ m, w, iblock, isplit, info = stebz(d, e, select, vl, vu, il, iu, tol,
1354
+ order)
1355
+ else: # 'stemr'
1356
+ # ?STEMR annoyingly requires size N instead of N-1
1357
+ e_ = empty(e.size+1, e.dtype)
1358
+ e_[:-1] = e
1359
+ stemr_lwork, = get_lapack_funcs(('stemr_lwork',), (d, e))
1360
+ lwork, liwork, info = stemr_lwork(d, e_, select, vl, vu, il, iu,
1361
+ compute_v=compute_v)
1362
+ _check_info(info, 'stemr_lwork')
1363
+ m, w, v, info = func(d, e_, select, vl, vu, il, iu,
1364
+ compute_v=compute_v, lwork=lwork, liwork=liwork)
1365
+ _check_info(info, lapack_driver + ' (eigh_tridiagonal)')
1366
+ w = w[:m]
1367
+ if eigvals_only:
1368
+ return w
1369
+ else:
1370
+ # Do we still need to compute the eigenvalues?
1371
+ if lapack_driver == 'stebz':
1372
+ func, = get_lapack_funcs(('stein',), (d, e))
1373
+ v, info = func(d, e, w, iblock, isplit)
1374
+ _check_info(info, 'stein (eigh_tridiagonal)',
1375
+ positive='%d eigenvectors failed to converge')
1376
+ # Convert block-order to matrix-order
1377
+ order = argsort(w)
1378
+ w, v = w[order], v[:, order]
1379
+ else:
1380
+ v = v[:, :m]
1381
+ return w, v
1382
+
1383
+
1384
+ def _check_info(info, driver, positive='did not converge (LAPACK info=%d)'):
1385
+ """Check info return value."""
1386
+ if info < 0:
1387
+ raise ValueError('illegal value in argument %d of internal %s'
1388
+ % (-info, driver))
1389
+ if info > 0 and positive:
1390
+ raise LinAlgError(("%s " + positive) % (driver, info,))
1391
+
1392
+
1393
+ def hessenberg(a, calc_q=False, overwrite_a=False, check_finite=True):
1394
+ """
1395
+ Compute Hessenberg form of a matrix.
1396
+
1397
+ The Hessenberg decomposition is::
1398
+
1399
+ A = Q H Q^H
1400
+
1401
+ where `Q` is unitary/orthogonal and `H` has only zero elements below
1402
+ the first sub-diagonal.
1403
+
1404
+ Parameters
1405
+ ----------
1406
+ a : (M, M) array_like
1407
+ Matrix to bring into Hessenberg form.
1408
+ calc_q : bool, optional
1409
+ Whether to compute the transformation matrix. Default is False.
1410
+ overwrite_a : bool, optional
1411
+ Whether to overwrite `a`; may improve performance.
1412
+ Default is False.
1413
+ check_finite : bool, optional
1414
+ Whether to check that the input matrix contains only finite numbers.
1415
+ Disabling may give a performance gain, but may result in problems
1416
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
1417
+
1418
+ Returns
1419
+ -------
1420
+ H : (M, M) ndarray
1421
+ Hessenberg form of `a`.
1422
+ Q : (M, M) ndarray
1423
+ Unitary/orthogonal similarity transformation matrix ``A = Q H Q^H``.
1424
+ Only returned if ``calc_q=True``.
1425
+
1426
+ Examples
1427
+ --------
1428
+ >>> import numpy as np
1429
+ >>> from scipy.linalg import hessenberg
1430
+ >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
1431
+ >>> H, Q = hessenberg(A, calc_q=True)
1432
+ >>> H
1433
+ array([[ 2. , -11.65843866, 1.42005301, 0.25349066],
1434
+ [ -9.94987437, 14.53535354, -5.31022304, 2.43081618],
1435
+ [ 0. , -1.83299243, 0.38969961, -0.51527034],
1436
+ [ 0. , 0. , -3.83189513, 1.07494686]])
1437
+ >>> np.allclose(Q @ H @ Q.conj().T - A, np.zeros((4, 4)))
1438
+ True
1439
+ """
1440
+ a1 = _asarray_validated(a, check_finite=check_finite)
1441
+ if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
1442
+ raise ValueError('expected square matrix')
1443
+ overwrite_a = overwrite_a or (_datacopied(a1, a))
1444
+
1445
+ if a1.size == 0:
1446
+ h3 = hessenberg(np.eye(3, dtype=a1.dtype))
1447
+ h = np.empty(a1.shape, dtype=h3.dtype)
1448
+ if not calc_q:
1449
+ return h
1450
+ else:
1451
+ h3, q3 = hessenberg(np.eye(3, dtype=a1.dtype), calc_q=True)
1452
+ q = np.empty(a1.shape, dtype=q3.dtype)
1453
+ h = np.empty(a1.shape, dtype=h3.dtype)
1454
+ return h, q
1455
+
1456
+ # if 2x2 or smaller: already in Hessenberg
1457
+ if a1.shape[0] <= 2:
1458
+ if calc_q:
1459
+ return a1, eye(a1.shape[0])
1460
+ return a1
1461
+
1462
+ gehrd, gebal, gehrd_lwork = get_lapack_funcs(('gehrd', 'gebal',
1463
+ 'gehrd_lwork'), (a1,))
1464
+ ba, lo, hi, pivscale, info = gebal(a1, permute=0, overwrite_a=overwrite_a)
1465
+ _check_info(info, 'gebal (hessenberg)', positive=False)
1466
+ n = len(a1)
1467
+
1468
+ lwork = _compute_lwork(gehrd_lwork, ba.shape[0], lo=lo, hi=hi)
1469
+
1470
+ hq, tau, info = gehrd(ba, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)
1471
+ _check_info(info, 'gehrd (hessenberg)', positive=False)
1472
+ h = np.triu(hq, -1)
1473
+ if not calc_q:
1474
+ return h
1475
+
1476
+ # use orghr/unghr to compute q
1477
+ orghr, orghr_lwork = get_lapack_funcs(('orghr', 'orghr_lwork'), (a1,))
1478
+ lwork = _compute_lwork(orghr_lwork, n, lo=lo, hi=hi)
1479
+
1480
+ q, info = orghr(a=hq, tau=tau, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)
1481
+ _check_info(info, 'orghr (hessenberg)', positive=False)
1482
+ return h, q
1483
+
1484
+
1485
+ def cdf2rdf(w, v):
1486
+ """
1487
+ Converts complex eigenvalues ``w`` and eigenvectors ``v`` to real
1488
+ eigenvalues in a block diagonal form ``wr`` and the associated real
1489
+ eigenvectors ``vr``, such that::
1490
+
1491
+ vr @ wr = X @ vr
1492
+
1493
+ continues to hold, where ``X`` is the original array for which ``w`` and
1494
+ ``v`` are the eigenvalues and eigenvectors.
1495
+
1496
+ .. versionadded:: 1.1.0
1497
+
1498
+ Parameters
1499
+ ----------
1500
+ w : (..., M) array_like
1501
+ Complex or real eigenvalues, an array or stack of arrays
1502
+
1503
+ Conjugate pairs must not be interleaved, else the wrong result
1504
+ will be produced. So ``[1+1j, 1, 1-1j]`` will give a correct result,
1505
+ but ``[1+1j, 2+1j, 1-1j, 2-1j]`` will not.
1506
+
1507
+ v : (..., M, M) array_like
1508
+ Complex or real eigenvectors, a square array or stack of square arrays.
1509
+
1510
+ Returns
1511
+ -------
1512
+ wr : (..., M, M) ndarray
1513
+ Real diagonal block form of eigenvalues
1514
+ vr : (..., M, M) ndarray
1515
+ Real eigenvectors associated with ``wr``
1516
+
1517
+ See Also
1518
+ --------
1519
+ eig : Eigenvalues and right eigenvectors for non-symmetric arrays
1520
+ rsf2csf : Convert real Schur form to complex Schur form
1521
+
1522
+ Notes
1523
+ -----
1524
+ ``w``, ``v`` must be the eigenstructure for some *real* matrix ``X``.
1525
+ For example, obtained by ``w, v = scipy.linalg.eig(X)`` or
1526
+ ``w, v = numpy.linalg.eig(X)`` in which case ``X`` can also represent
1527
+ stacked arrays.
1528
+
1529
+ .. versionadded:: 1.1.0
1530
+
1531
+ Examples
1532
+ --------
1533
+ >>> import numpy as np
1534
+ >>> X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]])
1535
+ >>> X
1536
+ array([[ 1, 2, 3],
1537
+ [ 0, 4, 5],
1538
+ [ 0, -5, 4]])
1539
+
1540
+ >>> from scipy import linalg
1541
+ >>> w, v = linalg.eig(X)
1542
+ >>> w
1543
+ array([ 1.+0.j, 4.+5.j, 4.-5.j])
1544
+ >>> v
1545
+ array([[ 1.00000+0.j , -0.01906-0.40016j, -0.01906+0.40016j],
1546
+ [ 0.00000+0.j , 0.00000-0.64788j, 0.00000+0.64788j],
1547
+ [ 0.00000+0.j , 0.64788+0.j , 0.64788-0.j ]])
1548
+
1549
+ >>> wr, vr = linalg.cdf2rdf(w, v)
1550
+ >>> wr
1551
+ array([[ 1., 0., 0.],
1552
+ [ 0., 4., 5.],
1553
+ [ 0., -5., 4.]])
1554
+ >>> vr
1555
+ array([[ 1. , 0.40016, -0.01906],
1556
+ [ 0. , 0.64788, 0. ],
1557
+ [ 0. , 0. , 0.64788]])
1558
+
1559
+ >>> vr @ wr
1560
+ array([[ 1. , 1.69593, 1.9246 ],
1561
+ [ 0. , 2.59153, 3.23942],
1562
+ [ 0. , -3.23942, 2.59153]])
1563
+ >>> X @ vr
1564
+ array([[ 1. , 1.69593, 1.9246 ],
1565
+ [ 0. , 2.59153, 3.23942],
1566
+ [ 0. , -3.23942, 2.59153]])
1567
+ """
1568
+ w, v = _asarray_validated(w), _asarray_validated(v)
1569
+
1570
+ # check dimensions
1571
+ if w.ndim < 1:
1572
+ raise ValueError('expected w to be at least 1D')
1573
+ if v.ndim < 2:
1574
+ raise ValueError('expected v to be at least 2D')
1575
+ if v.ndim != w.ndim + 1:
1576
+ raise ValueError('expected eigenvectors array to have exactly one '
1577
+ 'dimension more than eigenvalues array')
1578
+
1579
+ # check shapes
1580
+ n = w.shape[-1]
1581
+ M = w.shape[:-1]
1582
+ if v.shape[-2] != v.shape[-1]:
1583
+ raise ValueError('expected v to be a square matrix or stacked square '
1584
+ 'matrices: v.shape[-2] = v.shape[-1]')
1585
+ if v.shape[-1] != n:
1586
+ raise ValueError('expected the same number of eigenvalues as '
1587
+ 'eigenvectors')
1588
+
1589
+ # get indices for each first pair of complex eigenvalues
1590
+ complex_mask = iscomplex(w)
1591
+ n_complex = complex_mask.sum(axis=-1)
1592
+
1593
+ # check if all complex eigenvalues have conjugate pairs
1594
+ if not (n_complex % 2 == 0).all():
1595
+ raise ValueError('expected complex-conjugate pairs of eigenvalues')
1596
+
1597
+ # find complex indices
1598
+ idx = nonzero(complex_mask)
1599
+ idx_stack = idx[:-1]
1600
+ idx_elem = idx[-1]
1601
+
1602
+ # filter them to conjugate indices, assuming pairs are not interleaved
1603
+ j = idx_elem[0::2]
1604
+ k = idx_elem[1::2]
1605
+ stack_ind = ()
1606
+ for i in idx_stack:
1607
+ # should never happen, assuming nonzero orders by the last axis
1608
+ assert (i[0::2] == i[1::2]).all(), \
1609
+ "Conjugate pair spanned different arrays!"
1610
+ stack_ind += (i[0::2],)
1611
+
1612
+ # all eigenvalues to diagonal form
1613
+ wr = zeros(M + (n, n), dtype=w.real.dtype)
1614
+ di = range(n)
1615
+ wr[..., di, di] = w.real
1616
+
1617
+ # complex eigenvalues to real block diagonal form
1618
+ wr[stack_ind + (j, k)] = w[stack_ind + (j,)].imag
1619
+ wr[stack_ind + (k, j)] = w[stack_ind + (k,)].imag
1620
+
1621
+ # compute real eigenvectors associated with real block diagonal eigenvalues
1622
+ u = zeros(M + (n, n), dtype=np.cdouble)
1623
+ u[..., di, di] = 1.0
1624
+ u[stack_ind + (j, j)] = 0.5j
1625
+ u[stack_ind + (j, k)] = 0.5
1626
+ u[stack_ind + (k, j)] = -0.5j
1627
+ u[stack_ind + (k, k)] = 0.5
1628
+
1629
+ # multiply matrices v and u (equivalent to v @ u)
1630
+ vr = einsum('...ij,...jk->...ik', v, u).real
1631
+
1632
+ return wr, vr
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cholesky decomposition functions."""
2
+
3
+ import numpy as np
4
+ from numpy import asarray_chkfinite, asarray, atleast_2d, empty_like
5
+
6
+ # Local imports
7
+ from ._misc import LinAlgError, _datacopied
8
+ from .lapack import get_lapack_funcs
9
+
10
+ __all__ = ['cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded',
11
+ 'cho_solve_banded']
12
+
13
+
14
+ def _cholesky(a, lower=False, overwrite_a=False, clean=True,
15
+ check_finite=True):
16
+ """Common code for cholesky() and cho_factor()."""
17
+
18
+ a1 = asarray_chkfinite(a) if check_finite else asarray(a)
19
+ a1 = atleast_2d(a1)
20
+
21
+ # Dimension check
22
+ if a1.ndim != 2:
23
+ raise ValueError(f'Input array needs to be 2D but received a {a1.ndim}d-array.')
24
+ # Squareness check
25
+ if a1.shape[0] != a1.shape[1]:
26
+ raise ValueError('Input array is expected to be square but has '
27
+ f'the shape: {a1.shape}.')
28
+
29
+ # Quick return for square empty array
30
+ if a1.size == 0:
31
+ dt = cholesky(np.eye(1, dtype=a1.dtype)).dtype
32
+ return empty_like(a1, dtype=dt), lower
33
+
34
+ overwrite_a = overwrite_a or _datacopied(a1, a)
35
+ potrf, = get_lapack_funcs(('potrf',), (a1,))
36
+ c, info = potrf(a1, lower=lower, overwrite_a=overwrite_a, clean=clean)
37
+ if info > 0:
38
+ raise LinAlgError("%d-th leading minor of the array is not positive "
39
+ "definite" % info)
40
+ if info < 0:
41
+ raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument'
42
+ 'on entry to "POTRF".')
43
+ return c, lower
44
+
45
+
46
+ def cholesky(a, lower=False, overwrite_a=False, check_finite=True):
47
+ """
48
+ Compute the Cholesky decomposition of a matrix.
49
+
50
+ Returns the Cholesky decomposition, :math:`A = L L^*` or
51
+ :math:`A = U^* U` of a Hermitian positive-definite matrix A.
52
+
53
+ Parameters
54
+ ----------
55
+ a : (M, M) array_like
56
+ Matrix to be decomposed
57
+ lower : bool, optional
58
+ Whether to compute the upper- or lower-triangular Cholesky
59
+ factorization. During decomposition, only the selected half of the
60
+ matrix is referenced. Default is upper-triangular.
61
+ overwrite_a : bool, optional
62
+ Whether to overwrite data in `a` (may improve performance).
63
+ check_finite : bool, optional
64
+ Whether to check that the entire input matrix contains only finite numbers.
65
+ Disabling may give a performance gain, but may result in problems
66
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
67
+
68
+ Returns
69
+ -------
70
+ c : (M, M) ndarray
71
+ Upper- or lower-triangular Cholesky factor of `a`.
72
+
73
+ Raises
74
+ ------
75
+ LinAlgError : if decomposition fails.
76
+
77
+ Notes
78
+ -----
79
+ During the finiteness check (if selected), the entire matrix `a` is
80
+ checked. During decomposition, `a` is assumed to be symmetric or Hermitian
81
+ (as applicable), and only the half selected by option `lower` is referenced.
82
+ Consequently, if `a` is asymmetric/non-Hermitian, `cholesky` may still
83
+ succeed if the symmetric/Hermitian matrix represented by the selected half
84
+ is positive definite, yet it may fail if an element in the other half is
85
+ non-finite.
86
+
87
+ Examples
88
+ --------
89
+ >>> import numpy as np
90
+ >>> from scipy.linalg import cholesky
91
+ >>> a = np.array([[1,-2j],[2j,5]])
92
+ >>> L = cholesky(a, lower=True)
93
+ >>> L
94
+ array([[ 1.+0.j, 0.+0.j],
95
+ [ 0.+2.j, 1.+0.j]])
96
+ >>> L @ L.T.conj()
97
+ array([[ 1.+0.j, 0.-2.j],
98
+ [ 0.+2.j, 5.+0.j]])
99
+
100
+ """
101
+ c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=True,
102
+ check_finite=check_finite)
103
+ return c
104
+
105
+
106
+ def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):
107
+ """
108
+ Compute the Cholesky decomposition of a matrix, to use in cho_solve
109
+
110
+ Returns a matrix containing the Cholesky decomposition,
111
+ ``A = L L*`` or ``A = U* U`` of a Hermitian positive-definite matrix `a`.
112
+ The return value can be directly used as the first parameter to cho_solve.
113
+
114
+ .. warning::
115
+ The returned matrix also contains random data in the entries not
116
+ used by the Cholesky decomposition. If you need to zero these
117
+ entries, use the function `cholesky` instead.
118
+
119
+ Parameters
120
+ ----------
121
+ a : (M, M) array_like
122
+ Matrix to be decomposed
123
+ lower : bool, optional
124
+ Whether to compute the upper or lower triangular Cholesky factorization.
125
+ During decomposition, only the selected half of the matrix is referenced.
126
+ (Default: upper-triangular)
127
+ overwrite_a : bool, optional
128
+ Whether to overwrite data in a (may improve performance)
129
+ check_finite : bool, optional
130
+ Whether to check that the entire input matrix contains only finite numbers.
131
+ Disabling may give a performance gain, but may result in problems
132
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
133
+
134
+ Returns
135
+ -------
136
+ c : (M, M) ndarray
137
+ Matrix whose upper or lower triangle contains the Cholesky factor
138
+ of `a`. Other parts of the matrix contain random data.
139
+ lower : bool
140
+ Flag indicating whether the factor is in the lower or upper triangle
141
+
142
+ Raises
143
+ ------
144
+ LinAlgError
145
+ Raised if decomposition fails.
146
+
147
+ See Also
148
+ --------
149
+ cho_solve : Solve a linear set equations using the Cholesky factorization
150
+ of a matrix.
151
+
152
+ Notes
153
+ -----
154
+ During the finiteness check (if selected), the entire matrix `a` is
155
+ checked. During decomposition, `a` is assumed to be symmetric or Hermitian
156
+ (as applicable), and only the half selected by option `lower` is referenced.
157
+ Consequently, if `a` is asymmetric/non-Hermitian, `cholesky` may still
158
+ succeed if the symmetric/Hermitian matrix represented by the selected half
159
+ is positive definite, yet it may fail if an element in the other half is
160
+ non-finite.
161
+
162
+ Examples
163
+ --------
164
+ >>> import numpy as np
165
+ >>> from scipy.linalg import cho_factor
166
+ >>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]])
167
+ >>> c, low = cho_factor(A)
168
+ >>> c
169
+ array([[3. , 1. , 0.33333333, 1.66666667],
170
+ [3. , 2.44948974, 1.90515869, -0.27216553],
171
+ [1. , 5. , 2.29330749, 0.8559528 ],
172
+ [5. , 1. , 2. , 1.55418563]])
173
+ >>> np.allclose(np.triu(c).T @ np. triu(c) - A, np.zeros((4, 4)))
174
+ True
175
+
176
+ """
177
+ c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False,
178
+ check_finite=check_finite)
179
+ return c, lower
180
+
181
+
182
+ def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):
183
+ """Solve the linear equations A x = b, given the Cholesky factorization of A.
184
+
185
+ Parameters
186
+ ----------
187
+ (c, lower) : tuple, (array, bool)
188
+ Cholesky factorization of a, as given by cho_factor
189
+ b : array
190
+ Right-hand side
191
+ overwrite_b : bool, optional
192
+ Whether to overwrite data in b (may improve performance)
193
+ check_finite : bool, optional
194
+ Whether to check that the input matrices contain only finite numbers.
195
+ Disabling may give a performance gain, but may result in problems
196
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
197
+
198
+ Returns
199
+ -------
200
+ x : array
201
+ The solution to the system A x = b
202
+
203
+ See Also
204
+ --------
205
+ cho_factor : Cholesky factorization of a matrix
206
+
207
+ Examples
208
+ --------
209
+ >>> import numpy as np
210
+ >>> from scipy.linalg import cho_factor, cho_solve
211
+ >>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]])
212
+ >>> c, low = cho_factor(A)
213
+ >>> x = cho_solve((c, low), [1, 1, 1, 1])
214
+ >>> np.allclose(A @ x - [1, 1, 1, 1], np.zeros(4))
215
+ True
216
+
217
+ """
218
+ (c, lower) = c_and_lower
219
+ if check_finite:
220
+ b1 = asarray_chkfinite(b)
221
+ c = asarray_chkfinite(c)
222
+ else:
223
+ b1 = asarray(b)
224
+ c = asarray(c)
225
+
226
+ if c.ndim != 2 or c.shape[0] != c.shape[1]:
227
+ raise ValueError("The factored matrix c is not square.")
228
+ if c.shape[1] != b1.shape[0]:
229
+ raise ValueError(f"incompatible dimensions ({c.shape} and {b1.shape})")
230
+
231
+ # accommodate empty arrays
232
+ if b1.size == 0:
233
+ dt = cho_solve((np.eye(2, dtype=b1.dtype), True),
234
+ np.ones(2, dtype=c.dtype)).dtype
235
+ return empty_like(b1, dtype=dt)
236
+
237
+ overwrite_b = overwrite_b or _datacopied(b1, b)
238
+
239
+ potrs, = get_lapack_funcs(('potrs',), (c, b1))
240
+ x, info = potrs(c, b1, lower=lower, overwrite_b=overwrite_b)
241
+ if info != 0:
242
+ raise ValueError('illegal value in %dth argument of internal potrs'
243
+ % -info)
244
+ return x
245
+
246
+
247
+ def cholesky_banded(ab, overwrite_ab=False, lower=False, check_finite=True):
248
+ """
249
+ Cholesky decompose a banded Hermitian positive-definite matrix
250
+
251
+ The matrix a is stored in ab either in lower-diagonal or upper-
252
+ diagonal ordered form::
253
+
254
+ ab[u + i - j, j] == a[i,j] (if upper form; i <= j)
255
+ ab[ i - j, j] == a[i,j] (if lower form; i >= j)
256
+
257
+ Example of ab (shape of a is (6,6), u=2)::
258
+
259
+ upper form:
260
+ * * a02 a13 a24 a35
261
+ * a01 a12 a23 a34 a45
262
+ a00 a11 a22 a33 a44 a55
263
+
264
+ lower form:
265
+ a00 a11 a22 a33 a44 a55
266
+ a10 a21 a32 a43 a54 *
267
+ a20 a31 a42 a53 * *
268
+
269
+ Parameters
270
+ ----------
271
+ ab : (u + 1, M) array_like
272
+ Banded matrix
273
+ overwrite_ab : bool, optional
274
+ Discard data in ab (may enhance performance)
275
+ lower : bool, optional
276
+ Is the matrix in the lower form. (Default is upper form)
277
+ check_finite : bool, optional
278
+ Whether to check that the input matrix contains only finite numbers.
279
+ Disabling may give a performance gain, but may result in problems
280
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
281
+
282
+ Returns
283
+ -------
284
+ c : (u + 1, M) ndarray
285
+ Cholesky factorization of a, in the same banded format as ab
286
+
287
+ See Also
288
+ --------
289
+ cho_solve_banded :
290
+ Solve a linear set equations, given the Cholesky factorization
291
+ of a banded Hermitian.
292
+
293
+ Examples
294
+ --------
295
+ >>> import numpy as np
296
+ >>> from scipy.linalg import cholesky_banded
297
+ >>> from numpy import allclose, zeros, diag
298
+ >>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]])
299
+ >>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1)
300
+ >>> A = A + A.conj().T + np.diag(Ab[2, :])
301
+ >>> c = cholesky_banded(Ab)
302
+ >>> C = np.diag(c[0, 2:], k=2) + np.diag(c[1, 1:], k=1) + np.diag(c[2, :])
303
+ >>> np.allclose(C.conj().T @ C - A, np.zeros((5, 5)))
304
+ True
305
+
306
+ """
307
+ if check_finite:
308
+ ab = asarray_chkfinite(ab)
309
+ else:
310
+ ab = asarray(ab)
311
+
312
+ # accommodate square empty matrices
313
+ if ab.size == 0:
314
+ dt = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=ab.dtype)).dtype
315
+ return empty_like(ab, dtype=dt)
316
+
317
+ pbtrf, = get_lapack_funcs(('pbtrf',), (ab,))
318
+ c, info = pbtrf(ab, lower=lower, overwrite_ab=overwrite_ab)
319
+ if info > 0:
320
+ raise LinAlgError("%d-th leading minor not positive definite" % info)
321
+ if info < 0:
322
+ raise ValueError('illegal value in %d-th argument of internal pbtrf'
323
+ % -info)
324
+ return c
325
+
326
+
327
+ def cho_solve_banded(cb_and_lower, b, overwrite_b=False, check_finite=True):
328
+ """
329
+ Solve the linear equations ``A x = b``, given the Cholesky factorization of
330
+ the banded Hermitian ``A``.
331
+
332
+ Parameters
333
+ ----------
334
+ (cb, lower) : tuple, (ndarray, bool)
335
+ `cb` is the Cholesky factorization of A, as given by cholesky_banded.
336
+ `lower` must be the same value that was given to cholesky_banded.
337
+ b : array_like
338
+ Right-hand side
339
+ overwrite_b : bool, optional
340
+ If True, the function will overwrite the values in `b`.
341
+ check_finite : bool, optional
342
+ Whether to check that the input matrices contain only finite numbers.
343
+ Disabling may give a performance gain, but may result in problems
344
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
345
+
346
+ Returns
347
+ -------
348
+ x : array
349
+ The solution to the system A x = b
350
+
351
+ See Also
352
+ --------
353
+ cholesky_banded : Cholesky factorization of a banded matrix
354
+
355
+ Notes
356
+ -----
357
+
358
+ .. versionadded:: 0.8.0
359
+
360
+ Examples
361
+ --------
362
+ >>> import numpy as np
363
+ >>> from scipy.linalg import cholesky_banded, cho_solve_banded
364
+ >>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]])
365
+ >>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1)
366
+ >>> A = A + A.conj().T + np.diag(Ab[2, :])
367
+ >>> c = cholesky_banded(Ab)
368
+ >>> x = cho_solve_banded((c, False), np.ones(5))
369
+ >>> np.allclose(A @ x - np.ones(5), np.zeros(5))
370
+ True
371
+
372
+ """
373
+ (cb, lower) = cb_and_lower
374
+ if check_finite:
375
+ cb = asarray_chkfinite(cb)
376
+ b = asarray_chkfinite(b)
377
+ else:
378
+ cb = asarray(cb)
379
+ b = asarray(b)
380
+
381
+ # Validate shapes.
382
+ if cb.shape[-1] != b.shape[0]:
383
+ raise ValueError("shapes of cb and b are not compatible.")
384
+
385
+ # accommodate empty arrays
386
+ if b.size == 0:
387
+ m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=cb.dtype))
388
+ dt = cho_solve_banded((m, True), np.ones(2, dtype=b.dtype)).dtype
389
+ return empty_like(b, dtype=dt)
390
+
391
+ pbtrs, = get_lapack_funcs(('pbtrs',), (cb, b))
392
+ x, info = pbtrs(cb, b, lower=lower, overwrite_b=overwrite_b)
393
+ if info > 0:
394
+ raise LinAlgError("%dth leading minor not positive definite" % info)
395
+ if info < 0:
396
+ raise ValueError('illegal value in %dth argument of internal pbtrs'
397
+ % -info)
398
+ return x
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
+ f" {p + mmp}x{q + mmq} array). This might be "
152
+ "due to missing p, q arguments.")
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, n11 + r + n21 + n22:2 * r + n11 + 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
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ import numpy as np
4
+ from numpy import (atleast_2d, arange, zeros_like, imag, diag,
5
+ iscomplexobj, tril, triu, argsort, empty_like)
6
+ from scipy._lib._util import ComplexWarning
7
+ from ._decomp import _asarray_validated
8
+ from .lapack import get_lapack_funcs, _compute_lwork
9
+
10
+ __all__ = ['ldl']
11
+
12
+
13
+ def ldl(A, lower=True, hermitian=True, overwrite_a=False, check_finite=True):
14
+ """ Computes the LDLt or Bunch-Kaufman factorization of a symmetric/
15
+ hermitian matrix.
16
+
17
+ This function returns a block diagonal matrix D consisting blocks of size
18
+ at most 2x2 and also a possibly permuted unit lower triangular matrix
19
+ ``L`` such that the factorization ``A = L D L^H`` or ``A = L D L^T``
20
+ holds. If `lower` is False then (again possibly permuted) upper
21
+ triangular matrices are returned as outer factors.
22
+
23
+ The permutation array can be used to triangularize the outer factors
24
+ simply by a row shuffle, i.e., ``lu[perm, :]`` is an upper/lower
25
+ triangular matrix. This is also equivalent to multiplication with a
26
+ permutation matrix ``P.dot(lu)``, where ``P`` is a column-permuted
27
+ identity matrix ``I[:, perm]``.
28
+
29
+ Depending on the value of the boolean `lower`, only upper or lower
30
+ triangular part of the input array is referenced. Hence, a triangular
31
+ matrix on entry would give the same result as if the full matrix is
32
+ supplied.
33
+
34
+ Parameters
35
+ ----------
36
+ A : array_like
37
+ Square input array
38
+ lower : bool, optional
39
+ This switches between the lower and upper triangular outer factors of
40
+ the factorization. Lower triangular (``lower=True``) is the default.
41
+ hermitian : bool, optional
42
+ For complex-valued arrays, this defines whether ``A = A.conj().T`` or
43
+ ``A = A.T`` is assumed. For real-valued arrays, this switch has no
44
+ effect.
45
+ overwrite_a : bool, optional
46
+ Allow overwriting data in `A` (may enhance performance). The default
47
+ is False.
48
+ check_finite : bool, optional
49
+ Whether to check that the input matrices contain only finite numbers.
50
+ Disabling may give a performance gain, but may result in problems
51
+ (crashes, non-termination) if the inputs do contain infinities or NaNs.
52
+
53
+ Returns
54
+ -------
55
+ lu : ndarray
56
+ The (possibly) permuted upper/lower triangular outer factor of the
57
+ factorization.
58
+ d : ndarray
59
+ The block diagonal multiplier of the factorization.
60
+ perm : ndarray
61
+ The row-permutation index array that brings lu into triangular form.
62
+
63
+ Raises
64
+ ------
65
+ ValueError
66
+ If input array is not square.
67
+ ComplexWarning
68
+ If a complex-valued array with nonzero imaginary parts on the
69
+ diagonal is given and hermitian is set to True.
70
+
71
+ See Also
72
+ --------
73
+ cholesky, lu
74
+
75
+ Notes
76
+ -----
77
+ This function uses ``?SYTRF`` routines for symmetric matrices and
78
+ ``?HETRF`` routines for Hermitian matrices from LAPACK. See [1]_ for
79
+ the algorithm details.
80
+
81
+ Depending on the `lower` keyword value, only lower or upper triangular
82
+ part of the input array is referenced. Moreover, this keyword also defines
83
+ the structure of the outer factors of the factorization.
84
+
85
+ .. versionadded:: 1.1.0
86
+
87
+ References
88
+ ----------
89
+ .. [1] J.R. Bunch, L. Kaufman, Some stable methods for calculating
90
+ inertia and solving symmetric linear systems, Math. Comput. Vol.31,
91
+ 1977. :doi:`10.2307/2005787`
92
+
93
+ Examples
94
+ --------
95
+ Given an upper triangular array ``a`` that represents the full symmetric
96
+ array with its entries, obtain ``l``, 'd' and the permutation vector `perm`:
97
+
98
+ >>> import numpy as np
99
+ >>> from scipy.linalg import ldl
100
+ >>> a = np.array([[2, -1, 3], [0, 2, 0], [0, 0, 1]])
101
+ >>> lu, d, perm = ldl(a, lower=0) # Use the upper part
102
+ >>> lu
103
+ array([[ 0. , 0. , 1. ],
104
+ [ 0. , 1. , -0.5],
105
+ [ 1. , 1. , 1.5]])
106
+ >>> d
107
+ array([[-5. , 0. , 0. ],
108
+ [ 0. , 1.5, 0. ],
109
+ [ 0. , 0. , 2. ]])
110
+ >>> perm
111
+ array([2, 1, 0])
112
+ >>> lu[perm, :]
113
+ array([[ 1. , 1. , 1.5],
114
+ [ 0. , 1. , -0.5],
115
+ [ 0. , 0. , 1. ]])
116
+ >>> lu.dot(d).dot(lu.T)
117
+ array([[ 2., -1., 3.],
118
+ [-1., 2., 0.],
119
+ [ 3., 0., 1.]])
120
+
121
+ """
122
+ a = atleast_2d(_asarray_validated(A, check_finite=check_finite))
123
+ if a.shape[0] != a.shape[1]:
124
+ raise ValueError('The input array "a" should be square.')
125
+ # Return empty arrays for empty square input
126
+ if a.size == 0:
127
+ return empty_like(a), empty_like(a), np.array([], dtype=int)
128
+
129
+ n = a.shape[0]
130
+ r_or_c = complex if iscomplexobj(a) else float
131
+
132
+ # Get the LAPACK routine
133
+ if r_or_c is complex and hermitian:
134
+ s, sl = 'hetrf', 'hetrf_lwork'
135
+ if np.any(imag(diag(a))):
136
+ warn('scipy.linalg.ldl():\nThe imaginary parts of the diagonal'
137
+ 'are ignored. Use "hermitian=False" for factorization of'
138
+ 'complex symmetric arrays.', ComplexWarning, stacklevel=2)
139
+ else:
140
+ s, sl = 'sytrf', 'sytrf_lwork'
141
+
142
+ solver, solver_lwork = get_lapack_funcs((s, sl), (a,))
143
+ lwork = _compute_lwork(solver_lwork, n, lower=lower)
144
+ ldu, piv, info = solver(a, lwork=lwork, lower=lower,
145
+ overwrite_a=overwrite_a)
146
+ if info < 0:
147
+ raise ValueError(f'{s.upper()} exited with the internal error "illegal value '
148
+ f'in argument number {-info}". See LAPACK documentation '
149
+ 'for the error codes.')
150
+
151
+ swap_arr, pivot_arr = _ldl_sanitize_ipiv(piv, lower=lower)
152
+ d, lu = _ldl_get_d_and_l(ldu, pivot_arr, lower=lower, hermitian=hermitian)
153
+ lu, perm = _ldl_construct_tri_factor(lu, swap_arr, pivot_arr, lower=lower)
154
+
155
+ return lu, d, perm
156
+
157
+
158
+ def _ldl_sanitize_ipiv(a, lower=True):
159
+ """
160
+ This helper function takes the rather strangely encoded permutation array
161
+ returned by the LAPACK routines ?(HE/SY)TRF and converts it into
162
+ regularized permutation and diagonal pivot size format.
163
+
164
+ Since FORTRAN uses 1-indexing and LAPACK uses different start points for
165
+ upper and lower formats there are certain offsets in the indices used
166
+ below.
167
+
168
+ Let's assume a result where the matrix is 6x6 and there are two 2x2
169
+ and two 1x1 blocks reported by the routine. To ease the coding efforts,
170
+ we still populate a 6-sized array and fill zeros as the following ::
171
+
172
+ pivots = [2, 0, 2, 0, 1, 1]
173
+
174
+ This denotes a diagonal matrix of the form ::
175
+
176
+ [x x ]
177
+ [x x ]
178
+ [ x x ]
179
+ [ x x ]
180
+ [ x ]
181
+ [ x]
182
+
183
+ In other words, we write 2 when the 2x2 block is first encountered and
184
+ automatically write 0 to the next entry and skip the next spin of the
185
+ loop. Thus, a separate counter or array appends to keep track of block
186
+ sizes are avoided. If needed, zeros can be filtered out later without
187
+ losing the block structure.
188
+
189
+ Parameters
190
+ ----------
191
+ a : ndarray
192
+ The permutation array ipiv returned by LAPACK
193
+ lower : bool, optional
194
+ The switch to select whether upper or lower triangle is chosen in
195
+ the LAPACK call.
196
+
197
+ Returns
198
+ -------
199
+ swap_ : ndarray
200
+ The array that defines the row/column swap operations. For example,
201
+ if row two is swapped with row four, the result is [0, 3, 2, 3].
202
+ pivots : ndarray
203
+ The array that defines the block diagonal structure as given above.
204
+
205
+ """
206
+ n = a.size
207
+ swap_ = arange(n)
208
+ pivots = zeros_like(swap_, dtype=int)
209
+ skip_2x2 = False
210
+
211
+ # Some upper/lower dependent offset values
212
+ # range (s)tart, r(e)nd, r(i)ncrement
213
+ x, y, rs, re, ri = (1, 0, 0, n, 1) if lower else (-1, -1, n-1, -1, -1)
214
+
215
+ for ind in range(rs, re, ri):
216
+ # If previous spin belonged already to a 2x2 block
217
+ if skip_2x2:
218
+ skip_2x2 = False
219
+ continue
220
+
221
+ cur_val = a[ind]
222
+ # do we have a 1x1 block or not?
223
+ if cur_val > 0:
224
+ if cur_val != ind+1:
225
+ # Index value != array value --> permutation required
226
+ swap_[ind] = swap_[cur_val-1]
227
+ pivots[ind] = 1
228
+ # Not.
229
+ elif cur_val < 0 and cur_val == a[ind+x]:
230
+ # first neg entry of 2x2 block identifier
231
+ if -cur_val != ind+2:
232
+ # Index value != array value --> permutation required
233
+ swap_[ind+x] = swap_[-cur_val-1]
234
+ pivots[ind+y] = 2
235
+ skip_2x2 = True
236
+ else: # Doesn't make sense, give up
237
+ raise ValueError('While parsing the permutation array '
238
+ 'in "scipy.linalg.ldl", invalid entries '
239
+ 'found. The array syntax is invalid.')
240
+ return swap_, pivots
241
+
242
+
243
+ def _ldl_get_d_and_l(ldu, pivs, lower=True, hermitian=True):
244
+ """
245
+ Helper function to extract the diagonal and triangular matrices for
246
+ LDL.T factorization.
247
+
248
+ Parameters
249
+ ----------
250
+ ldu : ndarray
251
+ The compact output returned by the LAPACK routing
252
+ pivs : ndarray
253
+ The sanitized array of {0, 1, 2} denoting the sizes of the pivots. For
254
+ every 2 there is a succeeding 0.
255
+ lower : bool, optional
256
+ If set to False, upper triangular part is considered.
257
+ hermitian : bool, optional
258
+ If set to False a symmetric complex array is assumed.
259
+
260
+ Returns
261
+ -------
262
+ d : ndarray
263
+ The block diagonal matrix.
264
+ lu : ndarray
265
+ The upper/lower triangular matrix
266
+ """
267
+ is_c = iscomplexobj(ldu)
268
+ d = diag(diag(ldu))
269
+ n = d.shape[0]
270
+ blk_i = 0 # block index
271
+
272
+ # row/column offsets for selecting sub-, super-diagonal
273
+ x, y = (1, 0) if lower else (0, 1)
274
+
275
+ lu = tril(ldu, -1) if lower else triu(ldu, 1)
276
+ diag_inds = arange(n)
277
+ lu[diag_inds, diag_inds] = 1
278
+
279
+ for blk in pivs[pivs != 0]:
280
+ # increment the block index and check for 2s
281
+ # if 2 then copy the off diagonals depending on uplo
282
+ inc = blk_i + blk
283
+
284
+ if blk == 2:
285
+ d[blk_i+x, blk_i+y] = ldu[blk_i+x, blk_i+y]
286
+ # If Hermitian matrix is factorized, the cross-offdiagonal element
287
+ # should be conjugated.
288
+ if is_c and hermitian:
289
+ d[blk_i+y, blk_i+x] = ldu[blk_i+x, blk_i+y].conj()
290
+ else:
291
+ d[blk_i+y, blk_i+x] = ldu[blk_i+x, blk_i+y]
292
+
293
+ lu[blk_i+x, blk_i+y] = 0.
294
+ blk_i = inc
295
+
296
+ return d, lu
297
+
298
+
299
+ def _ldl_construct_tri_factor(lu, swap_vec, pivs, lower=True):
300
+ """
301
+ Helper function to construct explicit outer factors of LDL factorization.
302
+
303
+ If lower is True the permuted factors are multiplied as L(1)*L(2)*...*L(k).
304
+ Otherwise, the permuted factors are multiplied as L(k)*...*L(2)*L(1). See
305
+ LAPACK documentation for more details.
306
+
307
+ Parameters
308
+ ----------
309
+ lu : ndarray
310
+ The triangular array that is extracted from LAPACK routine call with
311
+ ones on the diagonals.
312
+ swap_vec : ndarray
313
+ The array that defines the row swapping indices. If the kth entry is m
314
+ then rows k,m are swapped. Notice that the mth entry is not necessarily
315
+ k to avoid undoing the swapping.
316
+ pivs : ndarray
317
+ The array that defines the block diagonal structure returned by
318
+ _ldl_sanitize_ipiv().
319
+ lower : bool, optional
320
+ The boolean to switch between lower and upper triangular structure.
321
+
322
+ Returns
323
+ -------
324
+ lu : ndarray
325
+ The square outer factor which satisfies the L * D * L.T = A
326
+ perm : ndarray
327
+ The permutation vector that brings the lu to the triangular form
328
+
329
+ Notes
330
+ -----
331
+ Note that the original argument "lu" is overwritten.
332
+
333
+ """
334
+ n = lu.shape[0]
335
+ perm = arange(n)
336
+ # Setup the reading order of the permutation matrix for upper/lower
337
+ rs, re, ri = (n-1, -1, -1) if lower else (0, n, 1)
338
+
339
+ for ind in range(rs, re, ri):
340
+ s_ind = swap_vec[ind]
341
+ if s_ind != ind:
342
+ # Column start and end positions
343
+ col_s = ind if lower else 0
344
+ col_e = n if lower else ind+1
345
+
346
+ # If we stumble upon a 2x2 block include both cols in the perm.
347
+ if pivs[ind] == (0 if lower else 2):
348
+ col_s += -1 if lower else 0
349
+ col_e += 0 if lower else 1
350
+ lu[[s_ind, ind], col_s:col_e] = lu[[ind, s_ind], col_s:col_e]
351
+ perm[[s_ind, ind]] = perm[[ind, s_ind]]
352
+
353
+ return lu, argsort(perm)