Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_inv_ssq.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h +164 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd +40 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp.py +1621 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py +356 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py +353 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py +449 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py +300 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_update.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_fblas.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_flapack.cpython-310-x86_64-linux-gnu.so +3 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py +861 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py +214 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_misc.py +191 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_procrustes.py +90 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py +1257 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/basic.py +24 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/blas.py +484 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_blas.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_lapack.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py +21 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py +21 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py +1114 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py +118 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py +22 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py +121 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py +219 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py +157 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py +90 -0
- env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py +1700 -0
.gitattributes
CHANGED
@@ -158,3 +158,5 @@ env-llmeval/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_host.so
|
|
158 |
env-llmeval/lib/python3.10/site-packages/tokenizers/tokenizers.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
159 |
llmeval-env/lib/python3.10/site-packages/torch/lib/libtorch_cuda.so filter=lfs diff=lfs merge=lfs -text
|
160 |
env-llmeval/lib/python3.10/site-packages/scipy/sparse/_sparsetools.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
158 |
env-llmeval/lib/python3.10/site-packages/tokenizers/tokenizers.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
159 |
llmeval-env/lib/python3.10/site-packages/torch/lib/libtorch_cuda.so filter=lfs diff=lfs merge=lfs -text
|
160 |
env-llmeval/lib/python3.10/site-packages/scipy/sparse/_sparsetools.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
161 |
+
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_flapack.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
162 |
+
env-llmeval/lib/python3.10/site-packages/scipy/misc/face.dat filter=lfs diff=lfs merge=lfs -text
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc
ADDED
Binary file (57.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp.cpython-310.pyc
ADDED
Binary file (50.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc
ADDED
Binary file (11.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-310.pyc
ADDED
Binary file (11.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc
ADDED
Binary file (22.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_inv_ssq.cpython-310.pyc
ADDED
Binary file (23.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc
ADDED
Binary file (5.54 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-310.pyc
ADDED
Binary file (2.86 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc
ADDED
Binary file (816 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc
ADDED
Binary file (9.63 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp.cpython-310.pyc
ADDED
Binary file (845 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-310.pyc
ADDED
Binary file (746 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc
ADDED
Binary file (690 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc
ADDED
Binary file (872 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-310.pyc
ADDED
Binary file (809 Bytes). View file
|
|
env-llmeval/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 "fortran_defs.h"
|
7 |
+
#include "npy_cblas.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 (cdotcwrp_)(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
|
16 |
+
void (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 (zdotcwrp_)(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
|
129 |
+
void (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
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (633 kB). View file
|
|
env-llmeval/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
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp.py
ADDED
@@ -0,0 +1,1621 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 warnings
|
20 |
+
|
21 |
+
import numpy
|
22 |
+
from numpy import (array, isfinite, inexact, nonzero, iscomplexobj,
|
23 |
+
flatnonzero, conj, asarray, argsort, empty,
|
24 |
+
iscomplex, zeros, einsum, eye, inf)
|
25 |
+
# Local imports
|
26 |
+
from scipy._lib._util import _asarray_validated
|
27 |
+
from ._misc import LinAlgError, _datacopied, norm
|
28 |
+
from .lapack import get_lapack_funcs, _compute_lwork
|
29 |
+
from scipy._lib.deprecation import _NoValue, _deprecate_positional_args
|
30 |
+
|
31 |
+
|
32 |
+
_I = numpy.array(1j, dtype='F')
|
33 |
+
|
34 |
+
|
35 |
+
def _make_complex_eigvecs(w, vin, dtype):
|
36 |
+
"""
|
37 |
+
Produce complex-valued eigenvectors from LAPACK DGGEV real-valued output
|
38 |
+
"""
|
39 |
+
# - see LAPACK man page DGGEV at ALPHAI
|
40 |
+
v = numpy.array(vin, dtype=dtype)
|
41 |
+
m = (w.imag > 0)
|
42 |
+
m[:-1] |= (w.imag[1:] < 0) # workaround for LAPACK bug, cf. ticket #709
|
43 |
+
for i in flatnonzero(m):
|
44 |
+
v.imag[:, i] = vin[:, i+1]
|
45 |
+
conj(v[:, i], v[:, i+1])
|
46 |
+
return v
|
47 |
+
|
48 |
+
|
49 |
+
def _make_eigvals(alpha, beta, homogeneous_eigvals):
|
50 |
+
if homogeneous_eigvals:
|
51 |
+
if beta is None:
|
52 |
+
return numpy.vstack((alpha, numpy.ones_like(alpha)))
|
53 |
+
else:
|
54 |
+
return numpy.vstack((alpha, beta))
|
55 |
+
else:
|
56 |
+
if beta is None:
|
57 |
+
return alpha
|
58 |
+
else:
|
59 |
+
w = numpy.empty_like(alpha)
|
60 |
+
alpha_zero = (alpha == 0)
|
61 |
+
beta_zero = (beta == 0)
|
62 |
+
beta_nonzero = ~beta_zero
|
63 |
+
w[beta_nonzero] = alpha[beta_nonzero]/beta[beta_nonzero]
|
64 |
+
# Use numpy.inf for complex values too since
|
65 |
+
# 1/numpy.inf = 0, i.e., it correctly behaves as projective
|
66 |
+
# infinity.
|
67 |
+
w[~alpha_zero & beta_zero] = numpy.inf
|
68 |
+
if numpy.all(alpha.imag == 0):
|
69 |
+
w[alpha_zero & beta_zero] = numpy.nan
|
70 |
+
else:
|
71 |
+
w[alpha_zero & beta_zero] = complex(numpy.nan, numpy.nan)
|
72 |
+
return w
|
73 |
+
|
74 |
+
|
75 |
+
def _geneig(a1, b1, left, right, overwrite_a, overwrite_b,
|
76 |
+
homogeneous_eigvals):
|
77 |
+
ggev, = get_lapack_funcs(('ggev',), (a1, b1))
|
78 |
+
cvl, cvr = left, right
|
79 |
+
res = ggev(a1, b1, lwork=-1)
|
80 |
+
lwork = res[-2][0].real.astype(numpy.int_)
|
81 |
+
if ggev.typecode in 'cz':
|
82 |
+
alpha, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr, lwork,
|
83 |
+
overwrite_a, overwrite_b)
|
84 |
+
w = _make_eigvals(alpha, beta, homogeneous_eigvals)
|
85 |
+
else:
|
86 |
+
alphar, alphai, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr,
|
87 |
+
lwork, overwrite_a,
|
88 |
+
overwrite_b)
|
89 |
+
alpha = alphar + _I * alphai
|
90 |
+
w = _make_eigvals(alpha, beta, homogeneous_eigvals)
|
91 |
+
_check_info(info, 'generalized eig algorithm (ggev)')
|
92 |
+
|
93 |
+
only_real = numpy.all(w.imag == 0.0)
|
94 |
+
if not (ggev.typecode in 'cz' or only_real):
|
95 |
+
t = w.dtype.char
|
96 |
+
if left:
|
97 |
+
vl = _make_complex_eigvecs(w, vl, t)
|
98 |
+
if right:
|
99 |
+
vr = _make_complex_eigvecs(w, vr, t)
|
100 |
+
|
101 |
+
# the eigenvectors returned by the lapack function are NOT normalized
|
102 |
+
for i in range(vr.shape[0]):
|
103 |
+
if right:
|
104 |
+
vr[:, i] /= norm(vr[:, i])
|
105 |
+
if left:
|
106 |
+
vl[:, i] /= norm(vl[:, i])
|
107 |
+
|
108 |
+
if not (left or right):
|
109 |
+
return w
|
110 |
+
if left:
|
111 |
+
if right:
|
112 |
+
return w, vl, vr
|
113 |
+
return w, vl
|
114 |
+
return w, vr
|
115 |
+
|
116 |
+
|
117 |
+
def eig(a, b=None, left=False, right=True, overwrite_a=False,
|
118 |
+
overwrite_b=False, check_finite=True, homogeneous_eigvals=False):
|
119 |
+
"""
|
120 |
+
Solve an ordinary or generalized eigenvalue problem of a square matrix.
|
121 |
+
|
122 |
+
Find eigenvalues w and right or left eigenvectors of a general matrix::
|
123 |
+
|
124 |
+
a vr[:,i] = w[i] b vr[:,i]
|
125 |
+
a.H vl[:,i] = w[i].conj() b.H vl[:,i]
|
126 |
+
|
127 |
+
where ``.H`` is the Hermitian conjugation.
|
128 |
+
|
129 |
+
Parameters
|
130 |
+
----------
|
131 |
+
a : (M, M) array_like
|
132 |
+
A complex or real matrix whose eigenvalues and eigenvectors
|
133 |
+
will be computed.
|
134 |
+
b : (M, M) array_like, optional
|
135 |
+
Right-hand side matrix in a generalized eigenvalue problem.
|
136 |
+
Default is None, identity matrix is assumed.
|
137 |
+
left : bool, optional
|
138 |
+
Whether to calculate and return left eigenvectors. Default is False.
|
139 |
+
right : bool, optional
|
140 |
+
Whether to calculate and return right eigenvectors. Default is True.
|
141 |
+
overwrite_a : bool, optional
|
142 |
+
Whether to overwrite `a`; may improve performance. Default is False.
|
143 |
+
overwrite_b : bool, optional
|
144 |
+
Whether to overwrite `b`; may improve performance. Default is False.
|
145 |
+
check_finite : bool, optional
|
146 |
+
Whether to check that the input matrices contain only finite numbers.
|
147 |
+
Disabling may give a performance gain, but may result in problems
|
148 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
149 |
+
homogeneous_eigvals : bool, optional
|
150 |
+
If True, return the eigenvalues in homogeneous coordinates.
|
151 |
+
In this case ``w`` is a (2, M) array so that::
|
152 |
+
|
153 |
+
w[1,i] a vr[:,i] = w[0,i] b vr[:,i]
|
154 |
+
|
155 |
+
Default is False.
|
156 |
+
|
157 |
+
Returns
|
158 |
+
-------
|
159 |
+
w : (M,) or (2, M) double or complex ndarray
|
160 |
+
The eigenvalues, each repeated according to its
|
161 |
+
multiplicity. The shape is (M,) unless
|
162 |
+
``homogeneous_eigvals=True``.
|
163 |
+
vl : (M, M) double or complex ndarray
|
164 |
+
The left eigenvector corresponding to the eigenvalue
|
165 |
+
``w[i]`` is the column ``vl[:,i]``. Only returned if ``left=True``.
|
166 |
+
The left eigenvector is not normalized.
|
167 |
+
vr : (M, M) double or complex ndarray
|
168 |
+
The normalized right eigenvector corresponding to the eigenvalue
|
169 |
+
``w[i]`` is the column ``vr[:,i]``. Only returned if ``right=True``.
|
170 |
+
|
171 |
+
Raises
|
172 |
+
------
|
173 |
+
LinAlgError
|
174 |
+
If eigenvalue computation does not converge.
|
175 |
+
|
176 |
+
See Also
|
177 |
+
--------
|
178 |
+
eigvals : eigenvalues of general arrays
|
179 |
+
eigh : Eigenvalues and right eigenvectors for symmetric/Hermitian arrays.
|
180 |
+
eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
|
181 |
+
band matrices
|
182 |
+
eigh_tridiagonal : eigenvalues and right eiegenvectors for
|
183 |
+
symmetric/Hermitian tridiagonal matrices
|
184 |
+
|
185 |
+
Examples
|
186 |
+
--------
|
187 |
+
>>> import numpy as np
|
188 |
+
>>> from scipy import linalg
|
189 |
+
>>> a = np.array([[0., -1.], [1., 0.]])
|
190 |
+
>>> linalg.eigvals(a)
|
191 |
+
array([0.+1.j, 0.-1.j])
|
192 |
+
|
193 |
+
>>> b = np.array([[0., 1.], [1., 1.]])
|
194 |
+
>>> linalg.eigvals(a, b)
|
195 |
+
array([ 1.+0.j, -1.+0.j])
|
196 |
+
|
197 |
+
>>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]])
|
198 |
+
>>> linalg.eigvals(a, homogeneous_eigvals=True)
|
199 |
+
array([[3.+0.j, 8.+0.j, 7.+0.j],
|
200 |
+
[1.+0.j, 1.+0.j, 1.+0.j]])
|
201 |
+
|
202 |
+
>>> a = np.array([[0., -1.], [1., 0.]])
|
203 |
+
>>> linalg.eigvals(a) == linalg.eig(a)[0]
|
204 |
+
array([ True, True])
|
205 |
+
>>> linalg.eig(a, left=True, right=False)[1] # normalized left eigenvector
|
206 |
+
array([[-0.70710678+0.j , -0.70710678-0.j ],
|
207 |
+
[-0. +0.70710678j, -0. -0.70710678j]])
|
208 |
+
>>> linalg.eig(a, left=False, right=True)[1] # normalized right eigenvector
|
209 |
+
array([[0.70710678+0.j , 0.70710678-0.j ],
|
210 |
+
[0. -0.70710678j, 0. +0.70710678j]])
|
211 |
+
|
212 |
+
|
213 |
+
|
214 |
+
"""
|
215 |
+
a1 = _asarray_validated(a, check_finite=check_finite)
|
216 |
+
if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
|
217 |
+
raise ValueError('expected square matrix')
|
218 |
+
overwrite_a = overwrite_a or (_datacopied(a1, a))
|
219 |
+
if b is not None:
|
220 |
+
b1 = _asarray_validated(b, check_finite=check_finite)
|
221 |
+
overwrite_b = overwrite_b or _datacopied(b1, b)
|
222 |
+
if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:
|
223 |
+
raise ValueError('expected square matrix')
|
224 |
+
if b1.shape != a1.shape:
|
225 |
+
raise ValueError('a and b must have the same shape')
|
226 |
+
return _geneig(a1, b1, left, right, overwrite_a, overwrite_b,
|
227 |
+
homogeneous_eigvals)
|
228 |
+
|
229 |
+
geev, geev_lwork = get_lapack_funcs(('geev', 'geev_lwork'), (a1,))
|
230 |
+
compute_vl, compute_vr = left, right
|
231 |
+
|
232 |
+
lwork = _compute_lwork(geev_lwork, a1.shape[0],
|
233 |
+
compute_vl=compute_vl,
|
234 |
+
compute_vr=compute_vr)
|
235 |
+
|
236 |
+
if geev.typecode in 'cz':
|
237 |
+
w, vl, vr, info = geev(a1, lwork=lwork,
|
238 |
+
compute_vl=compute_vl,
|
239 |
+
compute_vr=compute_vr,
|
240 |
+
overwrite_a=overwrite_a)
|
241 |
+
w = _make_eigvals(w, None, homogeneous_eigvals)
|
242 |
+
else:
|
243 |
+
wr, wi, vl, vr, info = geev(a1, lwork=lwork,
|
244 |
+
compute_vl=compute_vl,
|
245 |
+
compute_vr=compute_vr,
|
246 |
+
overwrite_a=overwrite_a)
|
247 |
+
t = {'f': 'F', 'd': 'D'}[wr.dtype.char]
|
248 |
+
w = wr + _I * wi
|
249 |
+
w = _make_eigvals(w, None, homogeneous_eigvals)
|
250 |
+
|
251 |
+
_check_info(info, 'eig algorithm (geev)',
|
252 |
+
positive='did not converge (only eigenvalues '
|
253 |
+
'with order >= %d have converged)')
|
254 |
+
|
255 |
+
only_real = numpy.all(w.imag == 0.0)
|
256 |
+
if not (geev.typecode in 'cz' or only_real):
|
257 |
+
t = w.dtype.char
|
258 |
+
if left:
|
259 |
+
vl = _make_complex_eigvecs(w, vl, t)
|
260 |
+
if right:
|
261 |
+
vr = _make_complex_eigvecs(w, vr, t)
|
262 |
+
if not (left or right):
|
263 |
+
return w
|
264 |
+
if left:
|
265 |
+
if right:
|
266 |
+
return w, vl, vr
|
267 |
+
return w, vl
|
268 |
+
return w, vr
|
269 |
+
|
270 |
+
|
271 |
+
@_deprecate_positional_args(version="1.14.0")
|
272 |
+
def eigh(a, b=None, *, lower=True, eigvals_only=False, overwrite_a=False,
|
273 |
+
overwrite_b=False, turbo=_NoValue, eigvals=_NoValue, type=1,
|
274 |
+
check_finite=True, subset_by_index=None, subset_by_value=None,
|
275 |
+
driver=None):
|
276 |
+
"""
|
277 |
+
Solve a standard or generalized eigenvalue problem for a complex
|
278 |
+
Hermitian or real symmetric matrix.
|
279 |
+
|
280 |
+
Find eigenvalues array ``w`` and optionally eigenvectors array ``v`` of
|
281 |
+
array ``a``, where ``b`` is positive definite such that for every
|
282 |
+
eigenvalue λ (i-th entry of w) and its eigenvector ``vi`` (i-th column of
|
283 |
+
``v``) satisfies::
|
284 |
+
|
285 |
+
a @ vi = λ * b @ vi
|
286 |
+
vi.conj().T @ a @ vi = λ
|
287 |
+
vi.conj().T @ b @ vi = 1
|
288 |
+
|
289 |
+
In the standard problem, ``b`` is assumed to be the identity matrix.
|
290 |
+
|
291 |
+
Parameters
|
292 |
+
----------
|
293 |
+
a : (M, M) array_like
|
294 |
+
A complex Hermitian or real symmetric matrix whose eigenvalues and
|
295 |
+
eigenvectors will be computed.
|
296 |
+
b : (M, M) array_like, optional
|
297 |
+
A complex Hermitian or real symmetric definite positive matrix in.
|
298 |
+
If omitted, identity matrix is assumed.
|
299 |
+
lower : bool, optional
|
300 |
+
Whether the pertinent array data is taken from the lower or upper
|
301 |
+
triangle of ``a`` and, if applicable, ``b``. (Default: lower)
|
302 |
+
eigvals_only : bool, optional
|
303 |
+
Whether to calculate only eigenvalues and no eigenvectors.
|
304 |
+
(Default: both are calculated)
|
305 |
+
subset_by_index : iterable, optional
|
306 |
+
If provided, this two-element iterable defines the start and the end
|
307 |
+
indices of the desired eigenvalues (ascending order and 0-indexed).
|
308 |
+
To return only the second smallest to fifth smallest eigenvalues,
|
309 |
+
``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only
|
310 |
+
available with "evr", "evx", and "gvx" drivers. The entries are
|
311 |
+
directly converted to integers via ``int()``.
|
312 |
+
subset_by_value : iterable, optional
|
313 |
+
If provided, this two-element iterable defines the half-open interval
|
314 |
+
``(a, b]`` that, if any, only the eigenvalues between these values
|
315 |
+
are returned. Only available with "evr", "evx", and "gvx" drivers. Use
|
316 |
+
``np.inf`` for the unconstrained ends.
|
317 |
+
driver : str, optional
|
318 |
+
Defines which LAPACK driver should be used. Valid options are "ev",
|
319 |
+
"evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for
|
320 |
+
generalized (where b is not None) problems. See the Notes section.
|
321 |
+
The default for standard problems is "evr". For generalized problems,
|
322 |
+
"gvd" is used for full set, and "gvx" for subset requested cases.
|
323 |
+
type : int, optional
|
324 |
+
For the generalized problems, this keyword specifies the problem type
|
325 |
+
to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible
|
326 |
+
inputs)::
|
327 |
+
|
328 |
+
1 => a @ v = w @ b @ v
|
329 |
+
2 => a @ b @ v = w @ v
|
330 |
+
3 => b @ a @ v = w @ v
|
331 |
+
|
332 |
+
This keyword is ignored for standard problems.
|
333 |
+
overwrite_a : bool, optional
|
334 |
+
Whether to overwrite data in ``a`` (may improve performance). Default
|
335 |
+
is False.
|
336 |
+
overwrite_b : bool, optional
|
337 |
+
Whether to overwrite data in ``b`` (may improve performance). Default
|
338 |
+
is False.
|
339 |
+
check_finite : bool, optional
|
340 |
+
Whether to check that the input matrices contain only finite numbers.
|
341 |
+
Disabling may give a performance gain, but may result in problems
|
342 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
343 |
+
turbo : bool, optional, deprecated
|
344 |
+
.. deprecated:: 1.5.0
|
345 |
+
`eigh` keyword argument `turbo` is deprecated in favour of
|
346 |
+
``driver=gvd`` keyword instead and will be removed in SciPy
|
347 |
+
1.14.0.
|
348 |
+
eigvals : tuple (lo, hi), optional, deprecated
|
349 |
+
.. deprecated:: 1.5.0
|
350 |
+
`eigh` keyword argument `eigvals` is deprecated in favour of
|
351 |
+
`subset_by_index` keyword instead and will be removed in SciPy
|
352 |
+
1.14.0.
|
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 |
+
|
401 |
+
For the generalized problem, normalization with respect to the given
|
402 |
+
type argument::
|
403 |
+
|
404 |
+
type 1 and 3 : v.conj().T @ a @ v = w
|
405 |
+
type 2 : inv(v).conj().T @ a @ inv(v) = w
|
406 |
+
|
407 |
+
type 1 or 2 : v.conj().T @ b @ v = I
|
408 |
+
type 3 : v.conj().T @ inv(b) @ v = I
|
409 |
+
|
410 |
+
|
411 |
+
Examples
|
412 |
+
--------
|
413 |
+
>>> import numpy as np
|
414 |
+
>>> from scipy.linalg import eigh
|
415 |
+
>>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]])
|
416 |
+
>>> w, v = eigh(A)
|
417 |
+
>>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
|
418 |
+
True
|
419 |
+
|
420 |
+
Request only the eigenvalues
|
421 |
+
|
422 |
+
>>> w = eigh(A, eigvals_only=True)
|
423 |
+
|
424 |
+
Request eigenvalues that are less than 10.
|
425 |
+
|
426 |
+
>>> A = np.array([[34, -4, -10, -7, 2],
|
427 |
+
... [-4, 7, 2, 12, 0],
|
428 |
+
... [-10, 2, 44, 2, -19],
|
429 |
+
... [-7, 12, 2, 79, -34],
|
430 |
+
... [2, 0, -19, -34, 29]])
|
431 |
+
>>> eigh(A, eigvals_only=True, subset_by_value=[-np.inf, 10])
|
432 |
+
array([6.69199443e-07, 9.11938152e+00])
|
433 |
+
|
434 |
+
Request the second smallest eigenvalue and its eigenvector
|
435 |
+
|
436 |
+
>>> w, v = eigh(A, subset_by_index=[1, 1])
|
437 |
+
>>> w
|
438 |
+
array([9.11938152])
|
439 |
+
>>> v.shape # only a single column is returned
|
440 |
+
(5, 1)
|
441 |
+
|
442 |
+
"""
|
443 |
+
if turbo is not _NoValue:
|
444 |
+
warnings.warn("Keyword argument 'turbo' is deprecated in favour of '"
|
445 |
+
"driver=gvd' keyword instead and will be removed in "
|
446 |
+
"SciPy 1.14.0.",
|
447 |
+
DeprecationWarning, stacklevel=2)
|
448 |
+
if eigvals is not _NoValue:
|
449 |
+
warnings.warn("Keyword argument 'eigvals' is deprecated in favour of "
|
450 |
+
"'subset_by_index' keyword instead and will be removed "
|
451 |
+
"in SciPy 1.14.0.",
|
452 |
+
DeprecationWarning, stacklevel=2)
|
453 |
+
|
454 |
+
# set lower
|
455 |
+
uplo = 'L' if lower else 'U'
|
456 |
+
# Set job for Fortran routines
|
457 |
+
_job = 'N' if eigvals_only else 'V'
|
458 |
+
|
459 |
+
drv_str = [None, "ev", "evd", "evr", "evx", "gv", "gvd", "gvx"]
|
460 |
+
if driver not in drv_str:
|
461 |
+
raise ValueError('"{}" is unknown. Possible values are "None", "{}".'
|
462 |
+
''.format(driver, '", "'.join(drv_str[1:])))
|
463 |
+
|
464 |
+
a1 = _asarray_validated(a, check_finite=check_finite)
|
465 |
+
if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
|
466 |
+
raise ValueError('expected square "a" matrix')
|
467 |
+
overwrite_a = overwrite_a or (_datacopied(a1, a))
|
468 |
+
cplx = True if iscomplexobj(a1) else False
|
469 |
+
n = a1.shape[0]
|
470 |
+
drv_args = {'overwrite_a': overwrite_a}
|
471 |
+
|
472 |
+
if b is not None:
|
473 |
+
b1 = _asarray_validated(b, check_finite=check_finite)
|
474 |
+
overwrite_b = overwrite_b or _datacopied(b1, b)
|
475 |
+
if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:
|
476 |
+
raise ValueError('expected square "b" matrix')
|
477 |
+
|
478 |
+
if b1.shape != a1.shape:
|
479 |
+
raise ValueError(f"wrong b dimensions {b1.shape}, should be {a1.shape}")
|
480 |
+
|
481 |
+
if type not in [1, 2, 3]:
|
482 |
+
raise ValueError('"type" keyword only accepts 1, 2, and 3.')
|
483 |
+
|
484 |
+
cplx = True if iscomplexobj(b1) else (cplx or False)
|
485 |
+
drv_args.update({'overwrite_b': overwrite_b, 'itype': type})
|
486 |
+
|
487 |
+
# backwards-compatibility handling
|
488 |
+
subset_by_index = subset_by_index if (eigvals in (None, _NoValue)) else eigvals
|
489 |
+
|
490 |
+
subset = (subset_by_index is not None) or (subset_by_value is not None)
|
491 |
+
|
492 |
+
# Both subsets can't be given
|
493 |
+
if subset_by_index and subset_by_value:
|
494 |
+
raise ValueError('Either index or value subset can be requested.')
|
495 |
+
|
496 |
+
# Take turbo into account if all conditions are met otherwise ignore
|
497 |
+
if turbo not in (None, _NoValue) and b is not None:
|
498 |
+
driver = 'gvx' if subset else 'gvd'
|
499 |
+
|
500 |
+
# Check indices if given
|
501 |
+
if subset_by_index:
|
502 |
+
lo, hi = (int(x) for x in subset_by_index)
|
503 |
+
if not (0 <= lo <= hi < n):
|
504 |
+
raise ValueError('Requested eigenvalue indices are not valid. '
|
505 |
+
f'Valid range is [0, {n-1}] and start <= end, but '
|
506 |
+
f'start={lo}, end={hi} is given')
|
507 |
+
# fortran is 1-indexed
|
508 |
+
drv_args.update({'range': 'I', 'il': lo + 1, 'iu': hi + 1})
|
509 |
+
|
510 |
+
if subset_by_value:
|
511 |
+
lo, hi = subset_by_value
|
512 |
+
if not (-inf <= lo < hi <= inf):
|
513 |
+
raise ValueError('Requested eigenvalue bounds are not valid. '
|
514 |
+
'Valid range is (-inf, inf) and low < high, but '
|
515 |
+
f'low={lo}, high={hi} is given')
|
516 |
+
|
517 |
+
drv_args.update({'range': 'V', 'vl': lo, 'vu': hi})
|
518 |
+
|
519 |
+
# fix prefix for lapack routines
|
520 |
+
pfx = 'he' if cplx else 'sy'
|
521 |
+
|
522 |
+
# decide on the driver if not given
|
523 |
+
# first early exit on incompatible choice
|
524 |
+
if driver:
|
525 |
+
if b is None and (driver in ["gv", "gvd", "gvx"]):
|
526 |
+
raise ValueError(f'{driver} requires input b array to be supplied '
|
527 |
+
'for generalized eigenvalue problems.')
|
528 |
+
if (b is not None) and (driver in ['ev', 'evd', 'evr', 'evx']):
|
529 |
+
raise ValueError(f'"{driver}" does not accept input b array '
|
530 |
+
'for standard eigenvalue problems.')
|
531 |
+
if subset and (driver in ["ev", "evd", "gv", "gvd"]):
|
532 |
+
raise ValueError(f'"{driver}" cannot compute subsets of eigenvalues')
|
533 |
+
|
534 |
+
# Default driver is evr and gvd
|
535 |
+
else:
|
536 |
+
driver = "evr" if b is None else ("gvx" if subset else "gvd")
|
537 |
+
|
538 |
+
lwork_spec = {
|
539 |
+
'syevd': ['lwork', 'liwork'],
|
540 |
+
'syevr': ['lwork', 'liwork'],
|
541 |
+
'heevd': ['lwork', 'liwork', 'lrwork'],
|
542 |
+
'heevr': ['lwork', 'lrwork', 'liwork'],
|
543 |
+
}
|
544 |
+
|
545 |
+
if b is None: # Standard problem
|
546 |
+
drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'),
|
547 |
+
[a1])
|
548 |
+
clw_args = {'n': n, 'lower': lower}
|
549 |
+
if driver == 'evd':
|
550 |
+
clw_args.update({'compute_v': 0 if _job == "N" else 1})
|
551 |
+
|
552 |
+
lw = _compute_lwork(drvlw, **clw_args)
|
553 |
+
# Multiple lwork vars
|
554 |
+
if isinstance(lw, tuple):
|
555 |
+
lwork_args = dict(zip(lwork_spec[pfx+driver], lw))
|
556 |
+
else:
|
557 |
+
lwork_args = {'lwork': lw}
|
558 |
+
|
559 |
+
drv_args.update({'lower': lower, 'compute_v': 0 if _job == "N" else 1})
|
560 |
+
w, v, *other_args, info = drv(a=a1, **drv_args, **lwork_args)
|
561 |
+
|
562 |
+
else: # Generalized problem
|
563 |
+
# 'gvd' doesn't have lwork query
|
564 |
+
if driver == "gvd":
|
565 |
+
drv = get_lapack_funcs(pfx + "gvd", [a1, b1])
|
566 |
+
lwork_args = {}
|
567 |
+
else:
|
568 |
+
drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'),
|
569 |
+
[a1, b1])
|
570 |
+
# generalized drivers use uplo instead of lower
|
571 |
+
lw = _compute_lwork(drvlw, n, uplo=uplo)
|
572 |
+
lwork_args = {'lwork': lw}
|
573 |
+
|
574 |
+
drv_args.update({'uplo': uplo, 'jobz': _job})
|
575 |
+
|
576 |
+
w, v, *other_args, info = drv(a=a1, b=b1, **drv_args, **lwork_args)
|
577 |
+
|
578 |
+
# m is always the first extra argument
|
579 |
+
w = w[:other_args[0]] if subset else w
|
580 |
+
v = v[:, :other_args[0]] if (subset and not eigvals_only) else v
|
581 |
+
|
582 |
+
# Check if we had a successful exit
|
583 |
+
if info == 0:
|
584 |
+
if eigvals_only:
|
585 |
+
return w
|
586 |
+
else:
|
587 |
+
return w, v
|
588 |
+
else:
|
589 |
+
if info < -1:
|
590 |
+
raise LinAlgError('Illegal value in argument {} of internal {}'
|
591 |
+
''.format(-info, drv.typecode + pfx + driver))
|
592 |
+
elif info > n:
|
593 |
+
raise LinAlgError(f'The leading minor of order {info-n} of B is not '
|
594 |
+
'positive definite. The factorization of B '
|
595 |
+
'could not be completed and no eigenvalues '
|
596 |
+
'or eigenvectors were computed.')
|
597 |
+
else:
|
598 |
+
drv_err = {'ev': 'The algorithm failed to converge; {} '
|
599 |
+
'off-diagonal elements of an intermediate '
|
600 |
+
'tridiagonal form did not converge to zero.',
|
601 |
+
'evx': '{} eigenvectors failed to converge.',
|
602 |
+
'evd': 'The algorithm failed to compute an eigenvalue '
|
603 |
+
'while working on the submatrix lying in rows '
|
604 |
+
'and columns {0}/{1} through mod({0},{1}).',
|
605 |
+
'evr': 'Internal Error.'
|
606 |
+
}
|
607 |
+
if driver in ['ev', 'gv']:
|
608 |
+
msg = drv_err['ev'].format(info)
|
609 |
+
elif driver in ['evx', 'gvx']:
|
610 |
+
msg = drv_err['evx'].format(info)
|
611 |
+
elif driver in ['evd', 'gvd']:
|
612 |
+
if eigvals_only:
|
613 |
+
msg = drv_err['ev'].format(info)
|
614 |
+
else:
|
615 |
+
msg = drv_err['evd'].format(info, n+1)
|
616 |
+
else:
|
617 |
+
msg = drv_err['evr']
|
618 |
+
|
619 |
+
raise LinAlgError(msg)
|
620 |
+
|
621 |
+
|
622 |
+
_conv_dict = {0: 0, 1: 1, 2: 2,
|
623 |
+
'all': 0, 'value': 1, 'index': 2,
|
624 |
+
'a': 0, 'v': 1, 'i': 2}
|
625 |
+
|
626 |
+
|
627 |
+
def _check_select(select, select_range, max_ev, max_len):
|
628 |
+
"""Check that select is valid, convert to Fortran style."""
|
629 |
+
if isinstance(select, str):
|
630 |
+
select = select.lower()
|
631 |
+
try:
|
632 |
+
select = _conv_dict[select]
|
633 |
+
except KeyError as e:
|
634 |
+
raise ValueError('invalid argument for select') from e
|
635 |
+
vl, vu = 0., 1.
|
636 |
+
il = iu = 1
|
637 |
+
if select != 0: # (non-all)
|
638 |
+
sr = asarray(select_range)
|
639 |
+
if sr.ndim != 1 or sr.size != 2 or sr[1] < sr[0]:
|
640 |
+
raise ValueError('select_range must be a 2-element array-like '
|
641 |
+
'in nondecreasing order')
|
642 |
+
if select == 1: # (value)
|
643 |
+
vl, vu = sr
|
644 |
+
if max_ev == 0:
|
645 |
+
max_ev = max_len
|
646 |
+
else: # 2 (index)
|
647 |
+
if sr.dtype.char.lower() not in 'hilqp':
|
648 |
+
raise ValueError(
|
649 |
+
f'when using select="i", select_range must '
|
650 |
+
f'contain integers, got dtype {sr.dtype} ({sr.dtype.char})'
|
651 |
+
)
|
652 |
+
# translate Python (0 ... N-1) into Fortran (1 ... N) with + 1
|
653 |
+
il, iu = sr + 1
|
654 |
+
if min(il, iu) < 1 or max(il, iu) > max_len:
|
655 |
+
raise ValueError('select_range out of bounds')
|
656 |
+
max_ev = iu - il + 1
|
657 |
+
return select, vl, vu, il, iu, max_ev
|
658 |
+
|
659 |
+
|
660 |
+
def eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False,
|
661 |
+
select='a', select_range=None, max_ev=0, check_finite=True):
|
662 |
+
"""
|
663 |
+
Solve real symmetric or complex Hermitian band matrix eigenvalue problem.
|
664 |
+
|
665 |
+
Find eigenvalues w and optionally right eigenvectors v of a::
|
666 |
+
|
667 |
+
a v[:,i] = w[i] v[:,i]
|
668 |
+
v.H v = identity
|
669 |
+
|
670 |
+
The matrix a is stored in a_band either in lower diagonal or upper
|
671 |
+
diagonal ordered form:
|
672 |
+
|
673 |
+
a_band[u + i - j, j] == a[i,j] (if upper form; i <= j)
|
674 |
+
a_band[ i - j, j] == a[i,j] (if lower form; i >= j)
|
675 |
+
|
676 |
+
where u is the number of bands above the diagonal.
|
677 |
+
|
678 |
+
Example of a_band (shape of a is (6,6), u=2)::
|
679 |
+
|
680 |
+
upper form:
|
681 |
+
* * a02 a13 a24 a35
|
682 |
+
* a01 a12 a23 a34 a45
|
683 |
+
a00 a11 a22 a33 a44 a55
|
684 |
+
|
685 |
+
lower form:
|
686 |
+
a00 a11 a22 a33 a44 a55
|
687 |
+
a10 a21 a32 a43 a54 *
|
688 |
+
a20 a31 a42 a53 * *
|
689 |
+
|
690 |
+
Cells marked with * are not used.
|
691 |
+
|
692 |
+
Parameters
|
693 |
+
----------
|
694 |
+
a_band : (u+1, M) array_like
|
695 |
+
The bands of the M by M matrix a.
|
696 |
+
lower : bool, optional
|
697 |
+
Is the matrix in the lower form. (Default is upper form)
|
698 |
+
eigvals_only : bool, optional
|
699 |
+
Compute only the eigenvalues and no eigenvectors.
|
700 |
+
(Default: calculate also eigenvectors)
|
701 |
+
overwrite_a_band : bool, optional
|
702 |
+
Discard data in a_band (may enhance performance)
|
703 |
+
select : {'a', 'v', 'i'}, optional
|
704 |
+
Which eigenvalues to calculate
|
705 |
+
|
706 |
+
====== ========================================
|
707 |
+
select calculated
|
708 |
+
====== ========================================
|
709 |
+
'a' All eigenvalues
|
710 |
+
'v' Eigenvalues in the interval (min, max]
|
711 |
+
'i' Eigenvalues with indices min <= i <= max
|
712 |
+
====== ========================================
|
713 |
+
select_range : (min, max), optional
|
714 |
+
Range of selected eigenvalues
|
715 |
+
max_ev : int, optional
|
716 |
+
For select=='v', maximum number of eigenvalues expected.
|
717 |
+
For other values of select, has no meaning.
|
718 |
+
|
719 |
+
In doubt, leave this parameter untouched.
|
720 |
+
|
721 |
+
check_finite : bool, optional
|
722 |
+
Whether to check that the input matrix contains only finite numbers.
|
723 |
+
Disabling may give a performance gain, but may result in problems
|
724 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
725 |
+
|
726 |
+
Returns
|
727 |
+
-------
|
728 |
+
w : (M,) ndarray
|
729 |
+
The eigenvalues, in ascending order, each repeated according to its
|
730 |
+
multiplicity.
|
731 |
+
v : (M, M) float or complex ndarray
|
732 |
+
The normalized eigenvector corresponding to the eigenvalue w[i] is
|
733 |
+
the column v[:,i]. Only returned if ``eigvals_only=False``.
|
734 |
+
|
735 |
+
Raises
|
736 |
+
------
|
737 |
+
LinAlgError
|
738 |
+
If eigenvalue computation does not converge.
|
739 |
+
|
740 |
+
See Also
|
741 |
+
--------
|
742 |
+
eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
|
743 |
+
eig : eigenvalues and right eigenvectors of general arrays.
|
744 |
+
eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
|
745 |
+
eigh_tridiagonal : eigenvalues and right eigenvectors for
|
746 |
+
symmetric/Hermitian tridiagonal matrices
|
747 |
+
|
748 |
+
Examples
|
749 |
+
--------
|
750 |
+
>>> import numpy as np
|
751 |
+
>>> from scipy.linalg import eig_banded
|
752 |
+
>>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]])
|
753 |
+
>>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]])
|
754 |
+
>>> w, v = eig_banded(Ab, lower=True)
|
755 |
+
>>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
|
756 |
+
True
|
757 |
+
>>> w = eig_banded(Ab, lower=True, eigvals_only=True)
|
758 |
+
>>> w
|
759 |
+
array([-4.26200532, -2.22987175, 3.95222349, 12.53965359])
|
760 |
+
|
761 |
+
Request only the eigenvalues between ``[-3, 4]``
|
762 |
+
|
763 |
+
>>> w, v = eig_banded(Ab, lower=True, select='v', select_range=[-3, 4])
|
764 |
+
>>> w
|
765 |
+
array([-2.22987175, 3.95222349])
|
766 |
+
|
767 |
+
"""
|
768 |
+
if eigvals_only or overwrite_a_band:
|
769 |
+
a1 = _asarray_validated(a_band, check_finite=check_finite)
|
770 |
+
overwrite_a_band = overwrite_a_band or (_datacopied(a1, a_band))
|
771 |
+
else:
|
772 |
+
a1 = array(a_band)
|
773 |
+
if issubclass(a1.dtype.type, inexact) and not isfinite(a1).all():
|
774 |
+
raise ValueError("array must not contain infs or NaNs")
|
775 |
+
overwrite_a_band = 1
|
776 |
+
|
777 |
+
if len(a1.shape) != 2:
|
778 |
+
raise ValueError('expected a 2-D array')
|
779 |
+
select, vl, vu, il, iu, max_ev = _check_select(
|
780 |
+
select, select_range, max_ev, a1.shape[1])
|
781 |
+
del select_range
|
782 |
+
if select == 0:
|
783 |
+
if a1.dtype.char in 'GFD':
|
784 |
+
# FIXME: implement this somewhen, for now go with builtin values
|
785 |
+
# FIXME: calc optimal lwork by calling ?hbevd(lwork=-1)
|
786 |
+
# or by using calc_lwork.f ???
|
787 |
+
# lwork = calc_lwork.hbevd(bevd.typecode, a1.shape[0], lower)
|
788 |
+
internal_name = 'hbevd'
|
789 |
+
else: # a1.dtype.char in 'fd':
|
790 |
+
# FIXME: implement this somewhen, for now go with builtin values
|
791 |
+
# see above
|
792 |
+
# lwork = calc_lwork.sbevd(bevd.typecode, a1.shape[0], lower)
|
793 |
+
internal_name = 'sbevd'
|
794 |
+
bevd, = get_lapack_funcs((internal_name,), (a1,))
|
795 |
+
w, v, info = bevd(a1, compute_v=not eigvals_only,
|
796 |
+
lower=lower, overwrite_ab=overwrite_a_band)
|
797 |
+
else: # select in [1, 2]
|
798 |
+
if eigvals_only:
|
799 |
+
max_ev = 1
|
800 |
+
# calculate optimal abstol for dsbevx (see manpage)
|
801 |
+
if a1.dtype.char in 'fF': # single precision
|
802 |
+
lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='f'),))
|
803 |
+
else:
|
804 |
+
lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='d'),))
|
805 |
+
abstol = 2 * lamch('s')
|
806 |
+
if a1.dtype.char in 'GFD':
|
807 |
+
internal_name = 'hbevx'
|
808 |
+
else: # a1.dtype.char in 'gfd'
|
809 |
+
internal_name = 'sbevx'
|
810 |
+
bevx, = get_lapack_funcs((internal_name,), (a1,))
|
811 |
+
w, v, m, ifail, info = bevx(
|
812 |
+
a1, vl, vu, il, iu, compute_v=not eigvals_only, mmax=max_ev,
|
813 |
+
range=select, lower=lower, overwrite_ab=overwrite_a_band,
|
814 |
+
abstol=abstol)
|
815 |
+
# crop off w and v
|
816 |
+
w = w[:m]
|
817 |
+
if not eigvals_only:
|
818 |
+
v = v[:, :m]
|
819 |
+
_check_info(info, internal_name)
|
820 |
+
|
821 |
+
if eigvals_only:
|
822 |
+
return w
|
823 |
+
return w, v
|
824 |
+
|
825 |
+
|
826 |
+
def eigvals(a, b=None, overwrite_a=False, check_finite=True,
|
827 |
+
homogeneous_eigvals=False):
|
828 |
+
"""
|
829 |
+
Compute eigenvalues from an ordinary or generalized eigenvalue problem.
|
830 |
+
|
831 |
+
Find eigenvalues of a general matrix::
|
832 |
+
|
833 |
+
a vr[:,i] = w[i] b vr[:,i]
|
834 |
+
|
835 |
+
Parameters
|
836 |
+
----------
|
837 |
+
a : (M, M) array_like
|
838 |
+
A complex or real matrix whose eigenvalues and eigenvectors
|
839 |
+
will be computed.
|
840 |
+
b : (M, M) array_like, optional
|
841 |
+
Right-hand side matrix in a generalized eigenvalue problem.
|
842 |
+
If omitted, identity matrix is assumed.
|
843 |
+
overwrite_a : bool, optional
|
844 |
+
Whether to overwrite data in a (may improve performance)
|
845 |
+
check_finite : bool, optional
|
846 |
+
Whether to check that the input matrices contain only finite numbers.
|
847 |
+
Disabling may give a performance gain, but may result in problems
|
848 |
+
(crashes, non-termination) if the inputs do contain infinities
|
849 |
+
or NaNs.
|
850 |
+
homogeneous_eigvals : bool, optional
|
851 |
+
If True, return the eigenvalues in homogeneous coordinates.
|
852 |
+
In this case ``w`` is a (2, M) array so that::
|
853 |
+
|
854 |
+
w[1,i] a vr[:,i] = w[0,i] b vr[:,i]
|
855 |
+
|
856 |
+
Default is False.
|
857 |
+
|
858 |
+
Returns
|
859 |
+
-------
|
860 |
+
w : (M,) or (2, M) double or complex ndarray
|
861 |
+
The eigenvalues, each repeated according to its multiplicity
|
862 |
+
but not in any specific order. The shape is (M,) unless
|
863 |
+
``homogeneous_eigvals=True``.
|
864 |
+
|
865 |
+
Raises
|
866 |
+
------
|
867 |
+
LinAlgError
|
868 |
+
If eigenvalue computation does not converge
|
869 |
+
|
870 |
+
See Also
|
871 |
+
--------
|
872 |
+
eig : eigenvalues and right eigenvectors of general arrays.
|
873 |
+
eigvalsh : eigenvalues of symmetric or Hermitian arrays
|
874 |
+
eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
|
875 |
+
eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
|
876 |
+
matrices
|
877 |
+
|
878 |
+
Examples
|
879 |
+
--------
|
880 |
+
>>> import numpy as np
|
881 |
+
>>> from scipy import linalg
|
882 |
+
>>> a = np.array([[0., -1.], [1., 0.]])
|
883 |
+
>>> linalg.eigvals(a)
|
884 |
+
array([0.+1.j, 0.-1.j])
|
885 |
+
|
886 |
+
>>> b = np.array([[0., 1.], [1., 1.]])
|
887 |
+
>>> linalg.eigvals(a, b)
|
888 |
+
array([ 1.+0.j, -1.+0.j])
|
889 |
+
|
890 |
+
>>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]])
|
891 |
+
>>> linalg.eigvals(a, homogeneous_eigvals=True)
|
892 |
+
array([[3.+0.j, 8.+0.j, 7.+0.j],
|
893 |
+
[1.+0.j, 1.+0.j, 1.+0.j]])
|
894 |
+
|
895 |
+
"""
|
896 |
+
return eig(a, b=b, left=0, right=0, overwrite_a=overwrite_a,
|
897 |
+
check_finite=check_finite,
|
898 |
+
homogeneous_eigvals=homogeneous_eigvals)
|
899 |
+
|
900 |
+
|
901 |
+
@_deprecate_positional_args(version="1.14.0")
|
902 |
+
def eigvalsh(a, b=None, *, lower=True, overwrite_a=False,
|
903 |
+
overwrite_b=False, turbo=_NoValue, eigvals=_NoValue, type=1,
|
904 |
+
check_finite=True, subset_by_index=None, subset_by_value=None,
|
905 |
+
driver=None):
|
906 |
+
"""
|
907 |
+
Solves a standard or generalized eigenvalue problem for a complex
|
908 |
+
Hermitian or real symmetric matrix.
|
909 |
+
|
910 |
+
Find eigenvalues array ``w`` of array ``a``, where ``b`` is positive
|
911 |
+
definite such that for every eigenvalue λ (i-th entry of w) and its
|
912 |
+
eigenvector vi (i-th column of v) satisfies::
|
913 |
+
|
914 |
+
a @ vi = λ * b @ vi
|
915 |
+
vi.conj().T @ a @ vi = λ
|
916 |
+
vi.conj().T @ b @ vi = 1
|
917 |
+
|
918 |
+
In the standard problem, b is assumed to be the identity matrix.
|
919 |
+
|
920 |
+
Parameters
|
921 |
+
----------
|
922 |
+
a : (M, M) array_like
|
923 |
+
A complex Hermitian or real symmetric matrix whose eigenvalues will
|
924 |
+
be computed.
|
925 |
+
b : (M, M) array_like, optional
|
926 |
+
A complex Hermitian or real symmetric definite positive matrix in.
|
927 |
+
If omitted, identity matrix is assumed.
|
928 |
+
lower : bool, optional
|
929 |
+
Whether the pertinent array data is taken from the lower or upper
|
930 |
+
triangle of ``a`` and, if applicable, ``b``. (Default: lower)
|
931 |
+
overwrite_a : bool, optional
|
932 |
+
Whether to overwrite data in ``a`` (may improve performance). Default
|
933 |
+
is False.
|
934 |
+
overwrite_b : bool, optional
|
935 |
+
Whether to overwrite data in ``b`` (may improve performance). Default
|
936 |
+
is False.
|
937 |
+
type : int, optional
|
938 |
+
For the generalized problems, this keyword specifies the problem type
|
939 |
+
to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible
|
940 |
+
inputs)::
|
941 |
+
|
942 |
+
1 => a @ v = w @ b @ v
|
943 |
+
2 => a @ b @ v = w @ v
|
944 |
+
3 => b @ a @ v = w @ v
|
945 |
+
|
946 |
+
This keyword is ignored for standard problems.
|
947 |
+
check_finite : bool, optional
|
948 |
+
Whether to check that the input matrices contain only finite numbers.
|
949 |
+
Disabling may give a performance gain, but may result in problems
|
950 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
951 |
+
subset_by_index : iterable, optional
|
952 |
+
If provided, this two-element iterable defines the start and the end
|
953 |
+
indices of the desired eigenvalues (ascending order and 0-indexed).
|
954 |
+
To return only the second smallest to fifth smallest eigenvalues,
|
955 |
+
``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only
|
956 |
+
available with "evr", "evx", and "gvx" drivers. The entries are
|
957 |
+
directly converted to integers via ``int()``.
|
958 |
+
subset_by_value : iterable, optional
|
959 |
+
If provided, this two-element iterable defines the half-open interval
|
960 |
+
``(a, b]`` that, if any, only the eigenvalues between these values
|
961 |
+
are returned. Only available with "evr", "evx", and "gvx" drivers. Use
|
962 |
+
``np.inf`` for the unconstrained ends.
|
963 |
+
driver : str, optional
|
964 |
+
Defines which LAPACK driver should be used. Valid options are "ev",
|
965 |
+
"evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for
|
966 |
+
generalized (where b is not None) problems. See the Notes section of
|
967 |
+
`scipy.linalg.eigh`.
|
968 |
+
turbo : bool, optional, deprecated
|
969 |
+
.. deprecated:: 1.5.0
|
970 |
+
'eigvalsh' keyword argument `turbo` is deprecated in favor of
|
971 |
+
``driver=gvd`` option and will be removed in SciPy 1.14.0.
|
972 |
+
|
973 |
+
eigvals : tuple (lo, hi), optional
|
974 |
+
.. deprecated:: 1.5.0
|
975 |
+
'eigvalsh' keyword argument `eigvals` is deprecated in favor of
|
976 |
+
`subset_by_index` option and will be removed in SciPy 1.14.0.
|
977 |
+
|
978 |
+
Returns
|
979 |
+
-------
|
980 |
+
w : (N,) ndarray
|
981 |
+
The N (N<=M) selected eigenvalues, in ascending order, each
|
982 |
+
repeated according to its multiplicity.
|
983 |
+
|
984 |
+
Raises
|
985 |
+
------
|
986 |
+
LinAlgError
|
987 |
+
If eigenvalue computation does not converge, an error occurred, or
|
988 |
+
b matrix is not definite positive. Note that if input matrices are
|
989 |
+
not symmetric or Hermitian, no error will be reported but results will
|
990 |
+
be wrong.
|
991 |
+
|
992 |
+
See Also
|
993 |
+
--------
|
994 |
+
eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
|
995 |
+
eigvals : eigenvalues of general arrays
|
996 |
+
eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
|
997 |
+
eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
|
998 |
+
matrices
|
999 |
+
|
1000 |
+
Notes
|
1001 |
+
-----
|
1002 |
+
This function does not check the input array for being Hermitian/symmetric
|
1003 |
+
in order to allow for representing arrays with only their upper/lower
|
1004 |
+
triangular parts.
|
1005 |
+
|
1006 |
+
This function serves as a one-liner shorthand for `scipy.linalg.eigh` with
|
1007 |
+
the option ``eigvals_only=True`` to get the eigenvalues and not the
|
1008 |
+
eigenvectors. Here it is kept as a legacy convenience. It might be
|
1009 |
+
beneficial to use the main function to have full control and to be a bit
|
1010 |
+
more pythonic.
|
1011 |
+
|
1012 |
+
Examples
|
1013 |
+
--------
|
1014 |
+
For more examples see `scipy.linalg.eigh`.
|
1015 |
+
|
1016 |
+
>>> import numpy as np
|
1017 |
+
>>> from scipy.linalg import eigvalsh
|
1018 |
+
>>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]])
|
1019 |
+
>>> w = eigvalsh(A)
|
1020 |
+
>>> w
|
1021 |
+
array([-3.74637491, -0.76263923, 6.08502336, 12.42399079])
|
1022 |
+
|
1023 |
+
"""
|
1024 |
+
return eigh(a, b=b, lower=lower, eigvals_only=True,
|
1025 |
+
overwrite_a=overwrite_a, overwrite_b=overwrite_b,
|
1026 |
+
turbo=turbo, eigvals=eigvals, type=type,
|
1027 |
+
check_finite=check_finite, subset_by_index=subset_by_index,
|
1028 |
+
subset_by_value=subset_by_value, 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 2x2 or smaller: already in Hessenberg
|
1446 |
+
if a1.shape[0] <= 2:
|
1447 |
+
if calc_q:
|
1448 |
+
return a1, eye(a1.shape[0])
|
1449 |
+
return a1
|
1450 |
+
|
1451 |
+
gehrd, gebal, gehrd_lwork = get_lapack_funcs(('gehrd', 'gebal',
|
1452 |
+
'gehrd_lwork'), (a1,))
|
1453 |
+
ba, lo, hi, pivscale, info = gebal(a1, permute=0, overwrite_a=overwrite_a)
|
1454 |
+
_check_info(info, 'gebal (hessenberg)', positive=False)
|
1455 |
+
n = len(a1)
|
1456 |
+
|
1457 |
+
lwork = _compute_lwork(gehrd_lwork, ba.shape[0], lo=lo, hi=hi)
|
1458 |
+
|
1459 |
+
hq, tau, info = gehrd(ba, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)
|
1460 |
+
_check_info(info, 'gehrd (hessenberg)', positive=False)
|
1461 |
+
h = numpy.triu(hq, -1)
|
1462 |
+
if not calc_q:
|
1463 |
+
return h
|
1464 |
+
|
1465 |
+
# use orghr/unghr to compute q
|
1466 |
+
orghr, orghr_lwork = get_lapack_funcs(('orghr', 'orghr_lwork'), (a1,))
|
1467 |
+
lwork = _compute_lwork(orghr_lwork, n, lo=lo, hi=hi)
|
1468 |
+
|
1469 |
+
q, info = orghr(a=hq, tau=tau, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)
|
1470 |
+
_check_info(info, 'orghr (hessenberg)', positive=False)
|
1471 |
+
return h, q
|
1472 |
+
|
1473 |
+
|
1474 |
+
def cdf2rdf(w, v):
|
1475 |
+
"""
|
1476 |
+
Converts complex eigenvalues ``w`` and eigenvectors ``v`` to real
|
1477 |
+
eigenvalues in a block diagonal form ``wr`` and the associated real
|
1478 |
+
eigenvectors ``vr``, such that::
|
1479 |
+
|
1480 |
+
vr @ wr = X @ vr
|
1481 |
+
|
1482 |
+
continues to hold, where ``X`` is the original array for which ``w`` and
|
1483 |
+
``v`` are the eigenvalues and eigenvectors.
|
1484 |
+
|
1485 |
+
.. versionadded:: 1.1.0
|
1486 |
+
|
1487 |
+
Parameters
|
1488 |
+
----------
|
1489 |
+
w : (..., M) array_like
|
1490 |
+
Complex or real eigenvalues, an array or stack of arrays
|
1491 |
+
|
1492 |
+
Conjugate pairs must not be interleaved, else the wrong result
|
1493 |
+
will be produced. So ``[1+1j, 1, 1-1j]`` will give a correct result,
|
1494 |
+
but ``[1+1j, 2+1j, 1-1j, 2-1j]`` will not.
|
1495 |
+
|
1496 |
+
v : (..., M, M) array_like
|
1497 |
+
Complex or real eigenvectors, a square array or stack of square arrays.
|
1498 |
+
|
1499 |
+
Returns
|
1500 |
+
-------
|
1501 |
+
wr : (..., M, M) ndarray
|
1502 |
+
Real diagonal block form of eigenvalues
|
1503 |
+
vr : (..., M, M) ndarray
|
1504 |
+
Real eigenvectors associated with ``wr``
|
1505 |
+
|
1506 |
+
See Also
|
1507 |
+
--------
|
1508 |
+
eig : Eigenvalues and right eigenvectors for non-symmetric arrays
|
1509 |
+
rsf2csf : Convert real Schur form to complex Schur form
|
1510 |
+
|
1511 |
+
Notes
|
1512 |
+
-----
|
1513 |
+
``w``, ``v`` must be the eigenstructure for some *real* matrix ``X``.
|
1514 |
+
For example, obtained by ``w, v = scipy.linalg.eig(X)`` or
|
1515 |
+
``w, v = numpy.linalg.eig(X)`` in which case ``X`` can also represent
|
1516 |
+
stacked arrays.
|
1517 |
+
|
1518 |
+
.. versionadded:: 1.1.0
|
1519 |
+
|
1520 |
+
Examples
|
1521 |
+
--------
|
1522 |
+
>>> import numpy as np
|
1523 |
+
>>> X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]])
|
1524 |
+
>>> X
|
1525 |
+
array([[ 1, 2, 3],
|
1526 |
+
[ 0, 4, 5],
|
1527 |
+
[ 0, -5, 4]])
|
1528 |
+
|
1529 |
+
>>> from scipy import linalg
|
1530 |
+
>>> w, v = linalg.eig(X)
|
1531 |
+
>>> w
|
1532 |
+
array([ 1.+0.j, 4.+5.j, 4.-5.j])
|
1533 |
+
>>> v
|
1534 |
+
array([[ 1.00000+0.j , -0.01906-0.40016j, -0.01906+0.40016j],
|
1535 |
+
[ 0.00000+0.j , 0.00000-0.64788j, 0.00000+0.64788j],
|
1536 |
+
[ 0.00000+0.j , 0.64788+0.j , 0.64788-0.j ]])
|
1537 |
+
|
1538 |
+
>>> wr, vr = linalg.cdf2rdf(w, v)
|
1539 |
+
>>> wr
|
1540 |
+
array([[ 1., 0., 0.],
|
1541 |
+
[ 0., 4., 5.],
|
1542 |
+
[ 0., -5., 4.]])
|
1543 |
+
>>> vr
|
1544 |
+
array([[ 1. , 0.40016, -0.01906],
|
1545 |
+
[ 0. , 0.64788, 0. ],
|
1546 |
+
[ 0. , 0. , 0.64788]])
|
1547 |
+
|
1548 |
+
>>> vr @ wr
|
1549 |
+
array([[ 1. , 1.69593, 1.9246 ],
|
1550 |
+
[ 0. , 2.59153, 3.23942],
|
1551 |
+
[ 0. , -3.23942, 2.59153]])
|
1552 |
+
>>> X @ vr
|
1553 |
+
array([[ 1. , 1.69593, 1.9246 ],
|
1554 |
+
[ 0. , 2.59153, 3.23942],
|
1555 |
+
[ 0. , -3.23942, 2.59153]])
|
1556 |
+
"""
|
1557 |
+
w, v = _asarray_validated(w), _asarray_validated(v)
|
1558 |
+
|
1559 |
+
# check dimensions
|
1560 |
+
if w.ndim < 1:
|
1561 |
+
raise ValueError('expected w to be at least 1D')
|
1562 |
+
if v.ndim < 2:
|
1563 |
+
raise ValueError('expected v to be at least 2D')
|
1564 |
+
if v.ndim != w.ndim + 1:
|
1565 |
+
raise ValueError('expected eigenvectors array to have exactly one '
|
1566 |
+
'dimension more than eigenvalues array')
|
1567 |
+
|
1568 |
+
# check shapes
|
1569 |
+
n = w.shape[-1]
|
1570 |
+
M = w.shape[:-1]
|
1571 |
+
if v.shape[-2] != v.shape[-1]:
|
1572 |
+
raise ValueError('expected v to be a square matrix or stacked square '
|
1573 |
+
'matrices: v.shape[-2] = v.shape[-1]')
|
1574 |
+
if v.shape[-1] != n:
|
1575 |
+
raise ValueError('expected the same number of eigenvalues as '
|
1576 |
+
'eigenvectors')
|
1577 |
+
|
1578 |
+
# get indices for each first pair of complex eigenvalues
|
1579 |
+
complex_mask = iscomplex(w)
|
1580 |
+
n_complex = complex_mask.sum(axis=-1)
|
1581 |
+
|
1582 |
+
# check if all complex eigenvalues have conjugate pairs
|
1583 |
+
if not (n_complex % 2 == 0).all():
|
1584 |
+
raise ValueError('expected complex-conjugate pairs of eigenvalues')
|
1585 |
+
|
1586 |
+
# find complex indices
|
1587 |
+
idx = nonzero(complex_mask)
|
1588 |
+
idx_stack = idx[:-1]
|
1589 |
+
idx_elem = idx[-1]
|
1590 |
+
|
1591 |
+
# filter them to conjugate indices, assuming pairs are not interleaved
|
1592 |
+
j = idx_elem[0::2]
|
1593 |
+
k = idx_elem[1::2]
|
1594 |
+
stack_ind = ()
|
1595 |
+
for i in idx_stack:
|
1596 |
+
# should never happen, assuming nonzero orders by the last axis
|
1597 |
+
assert (i[0::2] == i[1::2]).all(), \
|
1598 |
+
"Conjugate pair spanned different arrays!"
|
1599 |
+
stack_ind += (i[0::2],)
|
1600 |
+
|
1601 |
+
# all eigenvalues to diagonal form
|
1602 |
+
wr = zeros(M + (n, n), dtype=w.real.dtype)
|
1603 |
+
di = range(n)
|
1604 |
+
wr[..., di, di] = w.real
|
1605 |
+
|
1606 |
+
# complex eigenvalues to real block diagonal form
|
1607 |
+
wr[stack_ind + (j, k)] = w[stack_ind + (j,)].imag
|
1608 |
+
wr[stack_ind + (k, j)] = w[stack_ind + (k,)].imag
|
1609 |
+
|
1610 |
+
# compute real eigenvectors associated with real block diagonal eigenvalues
|
1611 |
+
u = zeros(M + (n, n), dtype=numpy.cdouble)
|
1612 |
+
u[..., di, di] = 1.0
|
1613 |
+
u[stack_ind + (j, j)] = 0.5j
|
1614 |
+
u[stack_ind + (j, k)] = 0.5
|
1615 |
+
u[stack_ind + (k, j)] = -0.5j
|
1616 |
+
u[stack_ind + (k, k)] = 0.5
|
1617 |
+
|
1618 |
+
# multiply matrices v and u (equivalent to v @ u)
|
1619 |
+
vr = einsum('...ij,...jk->...ik', v, u).real
|
1620 |
+
|
1621 |
+
return wr, vr
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py
ADDED
@@ -0,0 +1,356 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Cholesky decomposition functions."""
|
2 |
+
|
3 |
+
from numpy import asarray_chkfinite, asarray, atleast_2d
|
4 |
+
|
5 |
+
# Local imports
|
6 |
+
from ._misc import LinAlgError, _datacopied
|
7 |
+
from .lapack import get_lapack_funcs
|
8 |
+
|
9 |
+
__all__ = ['cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded',
|
10 |
+
'cho_solve_banded']
|
11 |
+
|
12 |
+
|
13 |
+
def _cholesky(a, lower=False, overwrite_a=False, clean=True,
|
14 |
+
check_finite=True):
|
15 |
+
"""Common code for cholesky() and cho_factor()."""
|
16 |
+
|
17 |
+
a1 = asarray_chkfinite(a) if check_finite else asarray(a)
|
18 |
+
a1 = atleast_2d(a1)
|
19 |
+
|
20 |
+
# Dimension check
|
21 |
+
if a1.ndim != 2:
|
22 |
+
raise ValueError(f'Input array needs to be 2D but received a {a1.ndim}d-array.')
|
23 |
+
# Squareness check
|
24 |
+
if a1.shape[0] != a1.shape[1]:
|
25 |
+
raise ValueError('Input array is expected to be square but has '
|
26 |
+
f'the shape: {a1.shape}.')
|
27 |
+
|
28 |
+
# Quick return for square empty array
|
29 |
+
if a1.size == 0:
|
30 |
+
return a1.copy(), lower
|
31 |
+
|
32 |
+
overwrite_a = overwrite_a or _datacopied(a1, a)
|
33 |
+
potrf, = get_lapack_funcs(('potrf',), (a1,))
|
34 |
+
c, info = potrf(a1, lower=lower, overwrite_a=overwrite_a, clean=clean)
|
35 |
+
if info > 0:
|
36 |
+
raise LinAlgError("%d-th leading minor of the array is not positive "
|
37 |
+
"definite" % info)
|
38 |
+
if info < 0:
|
39 |
+
raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument'
|
40 |
+
'on entry to "POTRF".')
|
41 |
+
return c, lower
|
42 |
+
|
43 |
+
|
44 |
+
def cholesky(a, lower=False, overwrite_a=False, check_finite=True):
|
45 |
+
"""
|
46 |
+
Compute the Cholesky decomposition of a matrix.
|
47 |
+
|
48 |
+
Returns the Cholesky decomposition, :math:`A = L L^*` or
|
49 |
+
:math:`A = U^* U` of a Hermitian positive-definite matrix A.
|
50 |
+
|
51 |
+
Parameters
|
52 |
+
----------
|
53 |
+
a : (M, M) array_like
|
54 |
+
Matrix to be decomposed
|
55 |
+
lower : bool, optional
|
56 |
+
Whether to compute the upper- or lower-triangular Cholesky
|
57 |
+
factorization. Default is upper-triangular.
|
58 |
+
overwrite_a : bool, optional
|
59 |
+
Whether to overwrite data in `a` (may improve performance).
|
60 |
+
check_finite : bool, optional
|
61 |
+
Whether to check that the input matrix contains only finite numbers.
|
62 |
+
Disabling may give a performance gain, but may result in problems
|
63 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
64 |
+
|
65 |
+
Returns
|
66 |
+
-------
|
67 |
+
c : (M, M) ndarray
|
68 |
+
Upper- or lower-triangular Cholesky factor of `a`.
|
69 |
+
|
70 |
+
Raises
|
71 |
+
------
|
72 |
+
LinAlgError : if decomposition fails.
|
73 |
+
|
74 |
+
Examples
|
75 |
+
--------
|
76 |
+
>>> import numpy as np
|
77 |
+
>>> from scipy.linalg import cholesky
|
78 |
+
>>> a = np.array([[1,-2j],[2j,5]])
|
79 |
+
>>> L = cholesky(a, lower=True)
|
80 |
+
>>> L
|
81 |
+
array([[ 1.+0.j, 0.+0.j],
|
82 |
+
[ 0.+2.j, 1.+0.j]])
|
83 |
+
>>> L @ L.T.conj()
|
84 |
+
array([[ 1.+0.j, 0.-2.j],
|
85 |
+
[ 0.+2.j, 5.+0.j]])
|
86 |
+
|
87 |
+
"""
|
88 |
+
c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=True,
|
89 |
+
check_finite=check_finite)
|
90 |
+
return c
|
91 |
+
|
92 |
+
|
93 |
+
def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):
|
94 |
+
"""
|
95 |
+
Compute the Cholesky decomposition of a matrix, to use in cho_solve
|
96 |
+
|
97 |
+
Returns a matrix containing the Cholesky decomposition,
|
98 |
+
``A = L L*`` or ``A = U* U`` of a Hermitian positive-definite matrix `a`.
|
99 |
+
The return value can be directly used as the first parameter to cho_solve.
|
100 |
+
|
101 |
+
.. warning::
|
102 |
+
The returned matrix also contains random data in the entries not
|
103 |
+
used by the Cholesky decomposition. If you need to zero these
|
104 |
+
entries, use the function `cholesky` instead.
|
105 |
+
|
106 |
+
Parameters
|
107 |
+
----------
|
108 |
+
a : (M, M) array_like
|
109 |
+
Matrix to be decomposed
|
110 |
+
lower : bool, optional
|
111 |
+
Whether to compute the upper or lower triangular Cholesky factorization
|
112 |
+
(Default: upper-triangular)
|
113 |
+
overwrite_a : bool, optional
|
114 |
+
Whether to overwrite data in a (may improve performance)
|
115 |
+
check_finite : bool, optional
|
116 |
+
Whether to check that the input matrix contains only finite numbers.
|
117 |
+
Disabling may give a performance gain, but may result in problems
|
118 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
119 |
+
|
120 |
+
Returns
|
121 |
+
-------
|
122 |
+
c : (M, M) ndarray
|
123 |
+
Matrix whose upper or lower triangle contains the Cholesky factor
|
124 |
+
of `a`. Other parts of the matrix contain random data.
|
125 |
+
lower : bool
|
126 |
+
Flag indicating whether the factor is in the lower or upper triangle
|
127 |
+
|
128 |
+
Raises
|
129 |
+
------
|
130 |
+
LinAlgError
|
131 |
+
Raised if decomposition fails.
|
132 |
+
|
133 |
+
See Also
|
134 |
+
--------
|
135 |
+
cho_solve : Solve a linear set equations using the Cholesky factorization
|
136 |
+
of a matrix.
|
137 |
+
|
138 |
+
Examples
|
139 |
+
--------
|
140 |
+
>>> import numpy as np
|
141 |
+
>>> from scipy.linalg import cho_factor
|
142 |
+
>>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]])
|
143 |
+
>>> c, low = cho_factor(A)
|
144 |
+
>>> c
|
145 |
+
array([[3. , 1. , 0.33333333, 1.66666667],
|
146 |
+
[3. , 2.44948974, 1.90515869, -0.27216553],
|
147 |
+
[1. , 5. , 2.29330749, 0.8559528 ],
|
148 |
+
[5. , 1. , 2. , 1.55418563]])
|
149 |
+
>>> np.allclose(np.triu(c).T @ np. triu(c) - A, np.zeros((4, 4)))
|
150 |
+
True
|
151 |
+
|
152 |
+
"""
|
153 |
+
c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False,
|
154 |
+
check_finite=check_finite)
|
155 |
+
return c, lower
|
156 |
+
|
157 |
+
|
158 |
+
def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):
|
159 |
+
"""Solve the linear equations A x = b, given the Cholesky factorization of A.
|
160 |
+
|
161 |
+
Parameters
|
162 |
+
----------
|
163 |
+
(c, lower) : tuple, (array, bool)
|
164 |
+
Cholesky factorization of a, as given by cho_factor
|
165 |
+
b : array
|
166 |
+
Right-hand side
|
167 |
+
overwrite_b : bool, optional
|
168 |
+
Whether to overwrite data in b (may improve performance)
|
169 |
+
check_finite : bool, optional
|
170 |
+
Whether to check that the input matrices contain only finite numbers.
|
171 |
+
Disabling may give a performance gain, but may result in problems
|
172 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
173 |
+
|
174 |
+
Returns
|
175 |
+
-------
|
176 |
+
x : array
|
177 |
+
The solution to the system A x = b
|
178 |
+
|
179 |
+
See Also
|
180 |
+
--------
|
181 |
+
cho_factor : Cholesky factorization of a matrix
|
182 |
+
|
183 |
+
Examples
|
184 |
+
--------
|
185 |
+
>>> import numpy as np
|
186 |
+
>>> from scipy.linalg import cho_factor, cho_solve
|
187 |
+
>>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]])
|
188 |
+
>>> c, low = cho_factor(A)
|
189 |
+
>>> x = cho_solve((c, low), [1, 1, 1, 1])
|
190 |
+
>>> np.allclose(A @ x - [1, 1, 1, 1], np.zeros(4))
|
191 |
+
True
|
192 |
+
|
193 |
+
"""
|
194 |
+
(c, lower) = c_and_lower
|
195 |
+
if check_finite:
|
196 |
+
b1 = asarray_chkfinite(b)
|
197 |
+
c = asarray_chkfinite(c)
|
198 |
+
else:
|
199 |
+
b1 = asarray(b)
|
200 |
+
c = asarray(c)
|
201 |
+
if c.ndim != 2 or c.shape[0] != c.shape[1]:
|
202 |
+
raise ValueError("The factored matrix c is not square.")
|
203 |
+
if c.shape[1] != b1.shape[0]:
|
204 |
+
raise ValueError(f"incompatible dimensions ({c.shape} and {b1.shape})")
|
205 |
+
|
206 |
+
overwrite_b = overwrite_b or _datacopied(b1, b)
|
207 |
+
|
208 |
+
potrs, = get_lapack_funcs(('potrs',), (c, b1))
|
209 |
+
x, info = potrs(c, b1, lower=lower, overwrite_b=overwrite_b)
|
210 |
+
if info != 0:
|
211 |
+
raise ValueError('illegal value in %dth argument of internal potrs'
|
212 |
+
% -info)
|
213 |
+
return x
|
214 |
+
|
215 |
+
|
216 |
+
def cholesky_banded(ab, overwrite_ab=False, lower=False, check_finite=True):
|
217 |
+
"""
|
218 |
+
Cholesky decompose a banded Hermitian positive-definite matrix
|
219 |
+
|
220 |
+
The matrix a is stored in ab either in lower-diagonal or upper-
|
221 |
+
diagonal ordered form::
|
222 |
+
|
223 |
+
ab[u + i - j, j] == a[i,j] (if upper form; i <= j)
|
224 |
+
ab[ i - j, j] == a[i,j] (if lower form; i >= j)
|
225 |
+
|
226 |
+
Example of ab (shape of a is (6,6), u=2)::
|
227 |
+
|
228 |
+
upper form:
|
229 |
+
* * a02 a13 a24 a35
|
230 |
+
* a01 a12 a23 a34 a45
|
231 |
+
a00 a11 a22 a33 a44 a55
|
232 |
+
|
233 |
+
lower form:
|
234 |
+
a00 a11 a22 a33 a44 a55
|
235 |
+
a10 a21 a32 a43 a54 *
|
236 |
+
a20 a31 a42 a53 * *
|
237 |
+
|
238 |
+
Parameters
|
239 |
+
----------
|
240 |
+
ab : (u + 1, M) array_like
|
241 |
+
Banded matrix
|
242 |
+
overwrite_ab : bool, optional
|
243 |
+
Discard data in ab (may enhance performance)
|
244 |
+
lower : bool, optional
|
245 |
+
Is the matrix in the lower form. (Default is upper form)
|
246 |
+
check_finite : bool, optional
|
247 |
+
Whether to check that the input matrix contains only finite numbers.
|
248 |
+
Disabling may give a performance gain, but may result in problems
|
249 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
250 |
+
|
251 |
+
Returns
|
252 |
+
-------
|
253 |
+
c : (u + 1, M) ndarray
|
254 |
+
Cholesky factorization of a, in the same banded format as ab
|
255 |
+
|
256 |
+
See Also
|
257 |
+
--------
|
258 |
+
cho_solve_banded :
|
259 |
+
Solve a linear set equations, given the Cholesky factorization
|
260 |
+
of a banded Hermitian.
|
261 |
+
|
262 |
+
Examples
|
263 |
+
--------
|
264 |
+
>>> import numpy as np
|
265 |
+
>>> from scipy.linalg import cholesky_banded
|
266 |
+
>>> from numpy import allclose, zeros, diag
|
267 |
+
>>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]])
|
268 |
+
>>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1)
|
269 |
+
>>> A = A + A.conj().T + np.diag(Ab[2, :])
|
270 |
+
>>> c = cholesky_banded(Ab)
|
271 |
+
>>> C = np.diag(c[0, 2:], k=2) + np.diag(c[1, 1:], k=1) + np.diag(c[2, :])
|
272 |
+
>>> np.allclose(C.conj().T @ C - A, np.zeros((5, 5)))
|
273 |
+
True
|
274 |
+
|
275 |
+
"""
|
276 |
+
if check_finite:
|
277 |
+
ab = asarray_chkfinite(ab)
|
278 |
+
else:
|
279 |
+
ab = asarray(ab)
|
280 |
+
|
281 |
+
pbtrf, = get_lapack_funcs(('pbtrf',), (ab,))
|
282 |
+
c, info = pbtrf(ab, lower=lower, overwrite_ab=overwrite_ab)
|
283 |
+
if info > 0:
|
284 |
+
raise LinAlgError("%d-th leading minor not positive definite" % info)
|
285 |
+
if info < 0:
|
286 |
+
raise ValueError('illegal value in %d-th argument of internal pbtrf'
|
287 |
+
% -info)
|
288 |
+
return c
|
289 |
+
|
290 |
+
|
291 |
+
def cho_solve_banded(cb_and_lower, b, overwrite_b=False, check_finite=True):
|
292 |
+
"""
|
293 |
+
Solve the linear equations ``A x = b``, given the Cholesky factorization of
|
294 |
+
the banded Hermitian ``A``.
|
295 |
+
|
296 |
+
Parameters
|
297 |
+
----------
|
298 |
+
(cb, lower) : tuple, (ndarray, bool)
|
299 |
+
`cb` is the Cholesky factorization of A, as given by cholesky_banded.
|
300 |
+
`lower` must be the same value that was given to cholesky_banded.
|
301 |
+
b : array_like
|
302 |
+
Right-hand side
|
303 |
+
overwrite_b : bool, optional
|
304 |
+
If True, the function will overwrite the values in `b`.
|
305 |
+
check_finite : bool, optional
|
306 |
+
Whether to check that the input matrices contain only finite numbers.
|
307 |
+
Disabling may give a performance gain, but may result in problems
|
308 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
309 |
+
|
310 |
+
Returns
|
311 |
+
-------
|
312 |
+
x : array
|
313 |
+
The solution to the system A x = b
|
314 |
+
|
315 |
+
See Also
|
316 |
+
--------
|
317 |
+
cholesky_banded : Cholesky factorization of a banded matrix
|
318 |
+
|
319 |
+
Notes
|
320 |
+
-----
|
321 |
+
|
322 |
+
.. versionadded:: 0.8.0
|
323 |
+
|
324 |
+
Examples
|
325 |
+
--------
|
326 |
+
>>> import numpy as np
|
327 |
+
>>> from scipy.linalg import cholesky_banded, cho_solve_banded
|
328 |
+
>>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]])
|
329 |
+
>>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1)
|
330 |
+
>>> A = A + A.conj().T + np.diag(Ab[2, :])
|
331 |
+
>>> c = cholesky_banded(Ab)
|
332 |
+
>>> x = cho_solve_banded((c, False), np.ones(5))
|
333 |
+
>>> np.allclose(A @ x - np.ones(5), np.zeros(5))
|
334 |
+
True
|
335 |
+
|
336 |
+
"""
|
337 |
+
(cb, lower) = cb_and_lower
|
338 |
+
if check_finite:
|
339 |
+
cb = asarray_chkfinite(cb)
|
340 |
+
b = asarray_chkfinite(b)
|
341 |
+
else:
|
342 |
+
cb = asarray(cb)
|
343 |
+
b = asarray(b)
|
344 |
+
|
345 |
+
# Validate shapes.
|
346 |
+
if cb.shape[-1] != b.shape[0]:
|
347 |
+
raise ValueError("shapes of cb and b are not compatible.")
|
348 |
+
|
349 |
+
pbtrs, = get_lapack_funcs(('pbtrs',), (cb, b))
|
350 |
+
x, info = pbtrs(cb, b, lower=lower, overwrite_b=overwrite_b)
|
351 |
+
if info > 0:
|
352 |
+
raise LinAlgError("%dth leading minor not positive definite" % info)
|
353 |
+
if info < 0:
|
354 |
+
raise ValueError('illegal value in %dth argument of internal pbtrs'
|
355 |
+
% -info)
|
356 |
+
return x
|
env-llmeval/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)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py
ADDED
@@ -0,0 +1,449 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import warnings
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
from numpy import asarray_chkfinite
|
5 |
+
from ._misc import LinAlgError, _datacopied, LinAlgWarning
|
6 |
+
from .lapack import get_lapack_funcs
|
7 |
+
|
8 |
+
|
9 |
+
__all__ = ['qz', 'ordqz']
|
10 |
+
|
11 |
+
_double_precision = ['i', 'l', 'd']
|
12 |
+
|
13 |
+
|
14 |
+
def _select_function(sort):
|
15 |
+
if callable(sort):
|
16 |
+
# assume the user knows what they're doing
|
17 |
+
sfunction = sort
|
18 |
+
elif sort == 'lhp':
|
19 |
+
sfunction = _lhp
|
20 |
+
elif sort == 'rhp':
|
21 |
+
sfunction = _rhp
|
22 |
+
elif sort == 'iuc':
|
23 |
+
sfunction = _iuc
|
24 |
+
elif sort == 'ouc':
|
25 |
+
sfunction = _ouc
|
26 |
+
else:
|
27 |
+
raise ValueError("sort parameter must be None, a callable, or "
|
28 |
+
"one of ('lhp','rhp','iuc','ouc')")
|
29 |
+
|
30 |
+
return sfunction
|
31 |
+
|
32 |
+
|
33 |
+
def _lhp(x, y):
|
34 |
+
out = np.empty_like(x, dtype=bool)
|
35 |
+
nonzero = (y != 0)
|
36 |
+
# handles (x, y) = (0, 0) too
|
37 |
+
out[~nonzero] = False
|
38 |
+
out[nonzero] = (np.real(x[nonzero]/y[nonzero]) < 0.0)
|
39 |
+
return out
|
40 |
+
|
41 |
+
|
42 |
+
def _rhp(x, y):
|
43 |
+
out = np.empty_like(x, dtype=bool)
|
44 |
+
nonzero = (y != 0)
|
45 |
+
# handles (x, y) = (0, 0) too
|
46 |
+
out[~nonzero] = False
|
47 |
+
out[nonzero] = (np.real(x[nonzero]/y[nonzero]) > 0.0)
|
48 |
+
return out
|
49 |
+
|
50 |
+
|
51 |
+
def _iuc(x, y):
|
52 |
+
out = np.empty_like(x, dtype=bool)
|
53 |
+
nonzero = (y != 0)
|
54 |
+
# handles (x, y) = (0, 0) too
|
55 |
+
out[~nonzero] = False
|
56 |
+
out[nonzero] = (abs(x[nonzero]/y[nonzero]) < 1.0)
|
57 |
+
return out
|
58 |
+
|
59 |
+
|
60 |
+
def _ouc(x, y):
|
61 |
+
out = np.empty_like(x, dtype=bool)
|
62 |
+
xzero = (x == 0)
|
63 |
+
yzero = (y == 0)
|
64 |
+
out[xzero & yzero] = False
|
65 |
+
out[~xzero & yzero] = True
|
66 |
+
out[~yzero] = (abs(x[~yzero]/y[~yzero]) > 1.0)
|
67 |
+
return out
|
68 |
+
|
69 |
+
|
70 |
+
def _qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False,
|
71 |
+
overwrite_b=False, check_finite=True):
|
72 |
+
if sort is not None:
|
73 |
+
# Disabled due to segfaults on win32, see ticket 1717.
|
74 |
+
raise ValueError("The 'sort' input of qz() has to be None and will be "
|
75 |
+
"removed in a future release. Use ordqz instead.")
|
76 |
+
|
77 |
+
if output not in ['real', 'complex', 'r', 'c']:
|
78 |
+
raise ValueError("argument must be 'real', or 'complex'")
|
79 |
+
|
80 |
+
if check_finite:
|
81 |
+
a1 = asarray_chkfinite(A)
|
82 |
+
b1 = asarray_chkfinite(B)
|
83 |
+
else:
|
84 |
+
a1 = np.asarray(A)
|
85 |
+
b1 = np.asarray(B)
|
86 |
+
|
87 |
+
a_m, a_n = a1.shape
|
88 |
+
b_m, b_n = b1.shape
|
89 |
+
if not (a_m == a_n == b_m == b_n):
|
90 |
+
raise ValueError("Array dimensions must be square and agree")
|
91 |
+
|
92 |
+
typa = a1.dtype.char
|
93 |
+
if output in ['complex', 'c'] and typa not in ['F', 'D']:
|
94 |
+
if typa in _double_precision:
|
95 |
+
a1 = a1.astype('D')
|
96 |
+
typa = 'D'
|
97 |
+
else:
|
98 |
+
a1 = a1.astype('F')
|
99 |
+
typa = 'F'
|
100 |
+
typb = b1.dtype.char
|
101 |
+
if output in ['complex', 'c'] and typb not in ['F', 'D']:
|
102 |
+
if typb in _double_precision:
|
103 |
+
b1 = b1.astype('D')
|
104 |
+
typb = 'D'
|
105 |
+
else:
|
106 |
+
b1 = b1.astype('F')
|
107 |
+
typb = 'F'
|
108 |
+
|
109 |
+
overwrite_a = overwrite_a or (_datacopied(a1, A))
|
110 |
+
overwrite_b = overwrite_b or (_datacopied(b1, B))
|
111 |
+
|
112 |
+
gges, = get_lapack_funcs(('gges',), (a1, b1))
|
113 |
+
|
114 |
+
if lwork is None or lwork == -1:
|
115 |
+
# get optimal work array size
|
116 |
+
result = gges(lambda x: None, a1, b1, lwork=-1)
|
117 |
+
lwork = result[-2][0].real.astype(int)
|
118 |
+
|
119 |
+
def sfunction(x):
|
120 |
+
return None
|
121 |
+
result = gges(sfunction, a1, b1, lwork=lwork, overwrite_a=overwrite_a,
|
122 |
+
overwrite_b=overwrite_b, sort_t=0)
|
123 |
+
|
124 |
+
info = result[-1]
|
125 |
+
if info < 0:
|
126 |
+
raise ValueError(f"Illegal value in argument {-info} of gges")
|
127 |
+
elif info > 0 and info <= a_n:
|
128 |
+
warnings.warn("The QZ iteration failed. (a,b) are not in Schur "
|
129 |
+
"form, but ALPHAR(j), ALPHAI(j), and BETA(j) should be "
|
130 |
+
f"correct for J={info-1},...,N", LinAlgWarning,
|
131 |
+
stacklevel=3)
|
132 |
+
elif info == a_n+1:
|
133 |
+
raise LinAlgError("Something other than QZ iteration failed")
|
134 |
+
elif info == a_n+2:
|
135 |
+
raise LinAlgError("After reordering, roundoff changed values of some "
|
136 |
+
"complex eigenvalues so that leading eigenvalues "
|
137 |
+
"in the Generalized Schur form no longer satisfy "
|
138 |
+
"sort=True. This could also be due to scaling.")
|
139 |
+
elif info == a_n+3:
|
140 |
+
raise LinAlgError("Reordering failed in <s,d,c,z>tgsen")
|
141 |
+
|
142 |
+
return result, gges.typecode
|
143 |
+
|
144 |
+
|
145 |
+
def qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False,
|
146 |
+
overwrite_b=False, check_finite=True):
|
147 |
+
"""
|
148 |
+
QZ decomposition for generalized eigenvalues of a pair of matrices.
|
149 |
+
|
150 |
+
The QZ, or generalized Schur, decomposition for a pair of n-by-n
|
151 |
+
matrices (A,B) is::
|
152 |
+
|
153 |
+
(A,B) = (Q @ AA @ Z*, Q @ BB @ Z*)
|
154 |
+
|
155 |
+
where AA, BB is in generalized Schur form if BB is upper-triangular
|
156 |
+
with non-negative diagonal and AA is upper-triangular, or for real QZ
|
157 |
+
decomposition (``output='real'``) block upper triangular with 1x1
|
158 |
+
and 2x2 blocks. In this case, the 1x1 blocks correspond to real
|
159 |
+
generalized eigenvalues and 2x2 blocks are 'standardized' by making
|
160 |
+
the corresponding elements of BB have the form::
|
161 |
+
|
162 |
+
[ a 0 ]
|
163 |
+
[ 0 b ]
|
164 |
+
|
165 |
+
and the pair of corresponding 2x2 blocks in AA and BB will have a complex
|
166 |
+
conjugate pair of generalized eigenvalues. If (``output='complex'``) or
|
167 |
+
A and B are complex matrices, Z' denotes the conjugate-transpose of Z.
|
168 |
+
Q and Z are unitary matrices.
|
169 |
+
|
170 |
+
Parameters
|
171 |
+
----------
|
172 |
+
A : (N, N) array_like
|
173 |
+
2-D array to decompose
|
174 |
+
B : (N, N) array_like
|
175 |
+
2-D array to decompose
|
176 |
+
output : {'real', 'complex'}, optional
|
177 |
+
Construct the real or complex QZ decomposition for real matrices.
|
178 |
+
Default is 'real'.
|
179 |
+
lwork : int, optional
|
180 |
+
Work array size. If None or -1, it is automatically computed.
|
181 |
+
sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
|
182 |
+
NOTE: THIS INPUT IS DISABLED FOR NOW. Use ordqz instead.
|
183 |
+
|
184 |
+
Specifies whether the upper eigenvalues should be sorted. A callable
|
185 |
+
may be passed that, given a eigenvalue, returns a boolean denoting
|
186 |
+
whether the eigenvalue should be sorted to the top-left (True). For
|
187 |
+
real matrix pairs, the sort function takes three real arguments
|
188 |
+
(alphar, alphai, beta). The eigenvalue
|
189 |
+
``x = (alphar + alphai*1j)/beta``. For complex matrix pairs or
|
190 |
+
output='complex', the sort function takes two complex arguments
|
191 |
+
(alpha, beta). The eigenvalue ``x = (alpha/beta)``. Alternatively,
|
192 |
+
string parameters may be used:
|
193 |
+
|
194 |
+
- 'lhp' Left-hand plane (x.real < 0.0)
|
195 |
+
- 'rhp' Right-hand plane (x.real > 0.0)
|
196 |
+
- 'iuc' Inside the unit circle (x*x.conjugate() < 1.0)
|
197 |
+
- 'ouc' Outside the unit circle (x*x.conjugate() > 1.0)
|
198 |
+
|
199 |
+
Defaults to None (no sorting).
|
200 |
+
overwrite_a : bool, optional
|
201 |
+
Whether to overwrite data in a (may improve performance)
|
202 |
+
overwrite_b : bool, optional
|
203 |
+
Whether to overwrite data in b (may improve performance)
|
204 |
+
check_finite : bool, optional
|
205 |
+
If true checks the elements of `A` and `B` are finite numbers. If
|
206 |
+
false does no checking and passes matrix through to
|
207 |
+
underlying algorithm.
|
208 |
+
|
209 |
+
Returns
|
210 |
+
-------
|
211 |
+
AA : (N, N) ndarray
|
212 |
+
Generalized Schur form of A.
|
213 |
+
BB : (N, N) ndarray
|
214 |
+
Generalized Schur form of B.
|
215 |
+
Q : (N, N) ndarray
|
216 |
+
The left Schur vectors.
|
217 |
+
Z : (N, N) ndarray
|
218 |
+
The right Schur vectors.
|
219 |
+
|
220 |
+
See Also
|
221 |
+
--------
|
222 |
+
ordqz
|
223 |
+
|
224 |
+
Notes
|
225 |
+
-----
|
226 |
+
Q is transposed versus the equivalent function in Matlab.
|
227 |
+
|
228 |
+
.. versionadded:: 0.11.0
|
229 |
+
|
230 |
+
Examples
|
231 |
+
--------
|
232 |
+
>>> import numpy as np
|
233 |
+
>>> from scipy.linalg import qz
|
234 |
+
|
235 |
+
>>> A = np.array([[1, 2, -1], [5, 5, 5], [2, 4, -8]])
|
236 |
+
>>> B = np.array([[1, 1, -3], [3, 1, -1], [5, 6, -2]])
|
237 |
+
|
238 |
+
Compute the decomposition. The QZ decomposition is not unique, so
|
239 |
+
depending on the underlying library that is used, there may be
|
240 |
+
differences in the signs of coefficients in the following output.
|
241 |
+
|
242 |
+
>>> AA, BB, Q, Z = qz(A, B)
|
243 |
+
>>> AA
|
244 |
+
array([[-1.36949157, -4.05459025, 7.44389431],
|
245 |
+
[ 0. , 7.65653432, 5.13476017],
|
246 |
+
[ 0. , -0.65978437, 2.4186015 ]]) # may vary
|
247 |
+
>>> BB
|
248 |
+
array([[ 1.71890633, -1.64723705, -0.72696385],
|
249 |
+
[ 0. , 8.6965692 , -0. ],
|
250 |
+
[ 0. , 0. , 2.27446233]]) # may vary
|
251 |
+
>>> Q
|
252 |
+
array([[-0.37048362, 0.1903278 , 0.90912992],
|
253 |
+
[-0.90073232, 0.16534124, -0.40167593],
|
254 |
+
[ 0.22676676, 0.96769706, -0.11017818]]) # may vary
|
255 |
+
>>> Z
|
256 |
+
array([[-0.67660785, 0.63528924, -0.37230283],
|
257 |
+
[ 0.70243299, 0.70853819, -0.06753907],
|
258 |
+
[ 0.22088393, -0.30721526, -0.92565062]]) # may vary
|
259 |
+
|
260 |
+
Verify the QZ decomposition. With real output, we only need the
|
261 |
+
transpose of ``Z`` in the following expressions.
|
262 |
+
|
263 |
+
>>> Q @ AA @ Z.T # Should be A
|
264 |
+
array([[ 1., 2., -1.],
|
265 |
+
[ 5., 5., 5.],
|
266 |
+
[ 2., 4., -8.]])
|
267 |
+
>>> Q @ BB @ Z.T # Should be B
|
268 |
+
array([[ 1., 1., -3.],
|
269 |
+
[ 3., 1., -1.],
|
270 |
+
[ 5., 6., -2.]])
|
271 |
+
|
272 |
+
Repeat the decomposition, but with ``output='complex'``.
|
273 |
+
|
274 |
+
>>> AA, BB, Q, Z = qz(A, B, output='complex')
|
275 |
+
|
276 |
+
For conciseness in the output, we use ``np.set_printoptions()`` to set
|
277 |
+
the output precision of NumPy arrays to 3 and display tiny values as 0.
|
278 |
+
|
279 |
+
>>> np.set_printoptions(precision=3, suppress=True)
|
280 |
+
>>> AA
|
281 |
+
array([[-1.369+0.j , 2.248+4.237j, 4.861-5.022j],
|
282 |
+
[ 0. +0.j , 7.037+2.922j, 0.794+4.932j],
|
283 |
+
[ 0. +0.j , 0. +0.j , 2.655-1.103j]]) # may vary
|
284 |
+
>>> BB
|
285 |
+
array([[ 1.719+0.j , -1.115+1.j , -0.763-0.646j],
|
286 |
+
[ 0. +0.j , 7.24 +0.j , -3.144+3.322j],
|
287 |
+
[ 0. +0.j , 0. +0.j , 2.732+0.j ]]) # may vary
|
288 |
+
>>> Q
|
289 |
+
array([[ 0.326+0.175j, -0.273-0.029j, -0.886-0.052j],
|
290 |
+
[ 0.794+0.426j, -0.093+0.134j, 0.402-0.02j ],
|
291 |
+
[-0.2 -0.107j, -0.816+0.482j, 0.151-0.167j]]) # may vary
|
292 |
+
>>> Z
|
293 |
+
array([[ 0.596+0.32j , -0.31 +0.414j, 0.393-0.347j],
|
294 |
+
[-0.619-0.332j, -0.479+0.314j, 0.154-0.393j],
|
295 |
+
[-0.195-0.104j, 0.576+0.27j , 0.715+0.187j]]) # may vary
|
296 |
+
|
297 |
+
With complex arrays, we must use ``Z.conj().T`` in the following
|
298 |
+
expressions to verify the decomposition.
|
299 |
+
|
300 |
+
>>> Q @ AA @ Z.conj().T # Should be A
|
301 |
+
array([[ 1.-0.j, 2.-0.j, -1.-0.j],
|
302 |
+
[ 5.+0.j, 5.+0.j, 5.-0.j],
|
303 |
+
[ 2.+0.j, 4.+0.j, -8.+0.j]])
|
304 |
+
>>> Q @ BB @ Z.conj().T # Should be B
|
305 |
+
array([[ 1.+0.j, 1.+0.j, -3.+0.j],
|
306 |
+
[ 3.-0.j, 1.-0.j, -1.+0.j],
|
307 |
+
[ 5.+0.j, 6.+0.j, -2.+0.j]])
|
308 |
+
|
309 |
+
"""
|
310 |
+
# output for real
|
311 |
+
# AA, BB, sdim, alphar, alphai, beta, vsl, vsr, work, info
|
312 |
+
# output for complex
|
313 |
+
# AA, BB, sdim, alpha, beta, vsl, vsr, work, info
|
314 |
+
result, _ = _qz(A, B, output=output, lwork=lwork, sort=sort,
|
315 |
+
overwrite_a=overwrite_a, overwrite_b=overwrite_b,
|
316 |
+
check_finite=check_finite)
|
317 |
+
return result[0], result[1], result[-4], result[-3]
|
318 |
+
|
319 |
+
|
320 |
+
def ordqz(A, B, sort='lhp', output='real', overwrite_a=False,
|
321 |
+
overwrite_b=False, check_finite=True):
|
322 |
+
"""QZ decomposition for a pair of matrices with reordering.
|
323 |
+
|
324 |
+
Parameters
|
325 |
+
----------
|
326 |
+
A : (N, N) array_like
|
327 |
+
2-D array to decompose
|
328 |
+
B : (N, N) array_like
|
329 |
+
2-D array to decompose
|
330 |
+
sort : {callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
|
331 |
+
Specifies whether the upper eigenvalues should be sorted. A
|
332 |
+
callable may be passed that, given an ordered pair ``(alpha,
|
333 |
+
beta)`` representing the eigenvalue ``x = (alpha/beta)``,
|
334 |
+
returns a boolean denoting whether the eigenvalue should be
|
335 |
+
sorted to the top-left (True). For the real matrix pairs
|
336 |
+
``beta`` is real while ``alpha`` can be complex, and for
|
337 |
+
complex matrix pairs both ``alpha`` and ``beta`` can be
|
338 |
+
complex. The callable must be able to accept a NumPy
|
339 |
+
array. Alternatively, string parameters may be used:
|
340 |
+
|
341 |
+
- 'lhp' Left-hand plane (x.real < 0.0)
|
342 |
+
- 'rhp' Right-hand plane (x.real > 0.0)
|
343 |
+
- 'iuc' Inside the unit circle (x*x.conjugate() < 1.0)
|
344 |
+
- 'ouc' Outside the unit circle (x*x.conjugate() > 1.0)
|
345 |
+
|
346 |
+
With the predefined sorting functions, an infinite eigenvalue
|
347 |
+
(i.e., ``alpha != 0`` and ``beta = 0``) is considered to lie in
|
348 |
+
neither the left-hand nor the right-hand plane, but it is
|
349 |
+
considered to lie outside the unit circle. For the eigenvalue
|
350 |
+
``(alpha, beta) = (0, 0)``, the predefined sorting functions
|
351 |
+
all return `False`.
|
352 |
+
output : str {'real','complex'}, optional
|
353 |
+
Construct the real or complex QZ decomposition for real matrices.
|
354 |
+
Default is 'real'.
|
355 |
+
overwrite_a : bool, optional
|
356 |
+
If True, the contents of A are overwritten.
|
357 |
+
overwrite_b : bool, optional
|
358 |
+
If True, the contents of B are overwritten.
|
359 |
+
check_finite : bool, optional
|
360 |
+
If true checks the elements of `A` and `B` are finite numbers. If
|
361 |
+
false does no checking and passes matrix through to
|
362 |
+
underlying algorithm.
|
363 |
+
|
364 |
+
Returns
|
365 |
+
-------
|
366 |
+
AA : (N, N) ndarray
|
367 |
+
Generalized Schur form of A.
|
368 |
+
BB : (N, N) ndarray
|
369 |
+
Generalized Schur form of B.
|
370 |
+
alpha : (N,) ndarray
|
371 |
+
alpha = alphar + alphai * 1j. See notes.
|
372 |
+
beta : (N,) ndarray
|
373 |
+
See notes.
|
374 |
+
Q : (N, N) ndarray
|
375 |
+
The left Schur vectors.
|
376 |
+
Z : (N, N) ndarray
|
377 |
+
The right Schur vectors.
|
378 |
+
|
379 |
+
See Also
|
380 |
+
--------
|
381 |
+
qz
|
382 |
+
|
383 |
+
Notes
|
384 |
+
-----
|
385 |
+
On exit, ``(ALPHAR(j) + ALPHAI(j)*i)/BETA(j), j=1,...,N``, will be the
|
386 |
+
generalized eigenvalues. ``ALPHAR(j) + ALPHAI(j)*i`` and
|
387 |
+
``BETA(j),j=1,...,N`` are the diagonals of the complex Schur form (S,T)
|
388 |
+
that would result if the 2-by-2 diagonal blocks of the real generalized
|
389 |
+
Schur form of (A,B) were further reduced to triangular form using complex
|
390 |
+
unitary transformations. If ALPHAI(j) is zero, then the jth eigenvalue is
|
391 |
+
real; if positive, then the ``j``\\ th and ``(j+1)``\\ st eigenvalues are a
|
392 |
+
complex conjugate pair, with ``ALPHAI(j+1)`` negative.
|
393 |
+
|
394 |
+
.. versionadded:: 0.17.0
|
395 |
+
|
396 |
+
Examples
|
397 |
+
--------
|
398 |
+
>>> import numpy as np
|
399 |
+
>>> from scipy.linalg import ordqz
|
400 |
+
>>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
|
401 |
+
>>> B = np.array([[0, 6, 0, 0], [5, 0, 2, 1], [5, 2, 6, 6], [4, 7, 7, 7]])
|
402 |
+
>>> AA, BB, alpha, beta, Q, Z = ordqz(A, B, sort='lhp')
|
403 |
+
|
404 |
+
Since we have sorted for left half plane eigenvalues, negatives come first
|
405 |
+
|
406 |
+
>>> (alpha/beta).real < 0
|
407 |
+
array([ True, True, False, False], dtype=bool)
|
408 |
+
|
409 |
+
"""
|
410 |
+
(AA, BB, _, *ab, Q, Z, _, _), typ = _qz(A, B, output=output, sort=None,
|
411 |
+
overwrite_a=overwrite_a,
|
412 |
+
overwrite_b=overwrite_b,
|
413 |
+
check_finite=check_finite)
|
414 |
+
|
415 |
+
if typ == 's':
|
416 |
+
alpha, beta = ab[0] + ab[1]*np.complex64(1j), ab[2]
|
417 |
+
elif typ == 'd':
|
418 |
+
alpha, beta = ab[0] + ab[1]*1.j, ab[2]
|
419 |
+
else:
|
420 |
+
alpha, beta = ab
|
421 |
+
|
422 |
+
sfunction = _select_function(sort)
|
423 |
+
select = sfunction(alpha, beta)
|
424 |
+
|
425 |
+
tgsen = get_lapack_funcs('tgsen', (AA, BB))
|
426 |
+
# the real case needs 4n + 16 lwork
|
427 |
+
lwork = 4*AA.shape[0] + 16 if typ in 'sd' else 1
|
428 |
+
AAA, BBB, *ab, QQ, ZZ, _, _, _, _, info = tgsen(select, AA, BB, Q, Z,
|
429 |
+
ijob=0,
|
430 |
+
lwork=lwork, liwork=1)
|
431 |
+
|
432 |
+
# Once more for tgsen output
|
433 |
+
if typ == 's':
|
434 |
+
alpha, beta = ab[0] + ab[1]*np.complex64(1j), ab[2]
|
435 |
+
elif typ == 'd':
|
436 |
+
alpha, beta = ab[0] + ab[1]*1.j, ab[2]
|
437 |
+
else:
|
438 |
+
alpha, beta = ab
|
439 |
+
|
440 |
+
if info < 0:
|
441 |
+
raise ValueError(f"Illegal value in argument {-info} of tgsen")
|
442 |
+
elif info == 1:
|
443 |
+
raise ValueError("Reordering of (A, B) failed because the transformed"
|
444 |
+
" matrix pair (A, B) would be too far from "
|
445 |
+
"generalized Schur form; the problem is very "
|
446 |
+
"ill-conditioned. (A, B) may have been partially "
|
447 |
+
"reordered.")
|
448 |
+
|
449 |
+
return AAA, BBB, alpha, beta, QQ, ZZ
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py
ADDED
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Schur decomposition functions."""
|
2 |
+
import numpy
|
3 |
+
from numpy import asarray_chkfinite, single, asarray, array
|
4 |
+
from numpy.linalg import norm
|
5 |
+
|
6 |
+
|
7 |
+
# Local imports.
|
8 |
+
from ._misc import LinAlgError, _datacopied
|
9 |
+
from .lapack import get_lapack_funcs
|
10 |
+
from ._decomp import eigvals
|
11 |
+
|
12 |
+
__all__ = ['schur', 'rsf2csf']
|
13 |
+
|
14 |
+
_double_precision = ['i', 'l', 'd']
|
15 |
+
|
16 |
+
|
17 |
+
def schur(a, output='real', lwork=None, overwrite_a=False, sort=None,
|
18 |
+
check_finite=True):
|
19 |
+
"""
|
20 |
+
Compute Schur decomposition of a matrix.
|
21 |
+
|
22 |
+
The Schur decomposition is::
|
23 |
+
|
24 |
+
A = Z T Z^H
|
25 |
+
|
26 |
+
where Z is unitary and T is either upper-triangular, or for real
|
27 |
+
Schur decomposition (output='real'), quasi-upper triangular. In
|
28 |
+
the quasi-triangular form, 2x2 blocks describing complex-valued
|
29 |
+
eigenvalue pairs may extrude from the diagonal.
|
30 |
+
|
31 |
+
Parameters
|
32 |
+
----------
|
33 |
+
a : (M, M) array_like
|
34 |
+
Matrix to decompose
|
35 |
+
output : {'real', 'complex'}, optional
|
36 |
+
Construct the real or complex Schur decomposition (for real matrices).
|
37 |
+
lwork : int, optional
|
38 |
+
Work array size. If None or -1, it is automatically computed.
|
39 |
+
overwrite_a : bool, optional
|
40 |
+
Whether to overwrite data in a (may improve performance).
|
41 |
+
sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
|
42 |
+
Specifies whether the upper eigenvalues should be sorted. A callable
|
43 |
+
may be passed that, given a eigenvalue, returns a boolean denoting
|
44 |
+
whether the eigenvalue should be sorted to the top-left (True).
|
45 |
+
Alternatively, string parameters may be used::
|
46 |
+
|
47 |
+
'lhp' Left-hand plane (x.real < 0.0)
|
48 |
+
'rhp' Right-hand plane (x.real > 0.0)
|
49 |
+
'iuc' Inside the unit circle (x*x.conjugate() <= 1.0)
|
50 |
+
'ouc' Outside the unit circle (x*x.conjugate() > 1.0)
|
51 |
+
|
52 |
+
Defaults to None (no sorting).
|
53 |
+
check_finite : bool, optional
|
54 |
+
Whether to check that the input matrix contains only finite numbers.
|
55 |
+
Disabling may give a performance gain, but may result in problems
|
56 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
57 |
+
|
58 |
+
Returns
|
59 |
+
-------
|
60 |
+
T : (M, M) ndarray
|
61 |
+
Schur form of A. It is real-valued for the real Schur decomposition.
|
62 |
+
Z : (M, M) ndarray
|
63 |
+
An unitary Schur transformation matrix for A.
|
64 |
+
It is real-valued for the real Schur decomposition.
|
65 |
+
sdim : int
|
66 |
+
If and only if sorting was requested, a third return value will
|
67 |
+
contain the number of eigenvalues satisfying the sort condition.
|
68 |
+
|
69 |
+
Raises
|
70 |
+
------
|
71 |
+
LinAlgError
|
72 |
+
Error raised under three conditions:
|
73 |
+
|
74 |
+
1. The algorithm failed due to a failure of the QR algorithm to
|
75 |
+
compute all eigenvalues.
|
76 |
+
2. If eigenvalue sorting was requested, the eigenvalues could not be
|
77 |
+
reordered due to a failure to separate eigenvalues, usually because
|
78 |
+
of poor conditioning.
|
79 |
+
3. If eigenvalue sorting was requested, roundoff errors caused the
|
80 |
+
leading eigenvalues to no longer satisfy the sorting condition.
|
81 |
+
|
82 |
+
See Also
|
83 |
+
--------
|
84 |
+
rsf2csf : Convert real Schur form to complex Schur form
|
85 |
+
|
86 |
+
Examples
|
87 |
+
--------
|
88 |
+
>>> import numpy as np
|
89 |
+
>>> from scipy.linalg import schur, eigvals
|
90 |
+
>>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]])
|
91 |
+
>>> T, Z = schur(A)
|
92 |
+
>>> T
|
93 |
+
array([[ 2.65896708, 1.42440458, -1.92933439],
|
94 |
+
[ 0. , -0.32948354, -0.49063704],
|
95 |
+
[ 0. , 1.31178921, -0.32948354]])
|
96 |
+
>>> Z
|
97 |
+
array([[0.72711591, -0.60156188, 0.33079564],
|
98 |
+
[0.52839428, 0.79801892, 0.28976765],
|
99 |
+
[0.43829436, 0.03590414, -0.89811411]])
|
100 |
+
|
101 |
+
>>> T2, Z2 = schur(A, output='complex')
|
102 |
+
>>> T2
|
103 |
+
array([[ 2.65896708, -1.22839825+1.32378589j, 0.42590089+1.51937378j], # may vary
|
104 |
+
[ 0. , -0.32948354+0.80225456j, -0.59877807+0.56192146j],
|
105 |
+
[ 0. , 0. , -0.32948354-0.80225456j]])
|
106 |
+
>>> eigvals(T2)
|
107 |
+
array([2.65896708, -0.32948354+0.80225456j, -0.32948354-0.80225456j])
|
108 |
+
|
109 |
+
An arbitrary custom eig-sorting condition, having positive imaginary part,
|
110 |
+
which is satisfied by only one eigenvalue
|
111 |
+
|
112 |
+
>>> T3, Z3, sdim = schur(A, output='complex', sort=lambda x: x.imag > 0)
|
113 |
+
>>> sdim
|
114 |
+
1
|
115 |
+
|
116 |
+
"""
|
117 |
+
if output not in ['real', 'complex', 'r', 'c']:
|
118 |
+
raise ValueError("argument must be 'real', or 'complex'")
|
119 |
+
if check_finite:
|
120 |
+
a1 = asarray_chkfinite(a)
|
121 |
+
else:
|
122 |
+
a1 = asarray(a)
|
123 |
+
if numpy.issubdtype(a1.dtype, numpy.integer):
|
124 |
+
a1 = asarray(a, dtype=numpy.dtype("long"))
|
125 |
+
if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
|
126 |
+
raise ValueError('expected square matrix')
|
127 |
+
typ = a1.dtype.char
|
128 |
+
if output in ['complex', 'c'] and typ not in ['F', 'D']:
|
129 |
+
if typ in _double_precision:
|
130 |
+
a1 = a1.astype('D')
|
131 |
+
typ = 'D'
|
132 |
+
else:
|
133 |
+
a1 = a1.astype('F')
|
134 |
+
typ = 'F'
|
135 |
+
overwrite_a = overwrite_a or (_datacopied(a1, a))
|
136 |
+
gees, = get_lapack_funcs(('gees',), (a1,))
|
137 |
+
if lwork is None or lwork == -1:
|
138 |
+
# get optimal work array
|
139 |
+
result = gees(lambda x: None, a1, lwork=-1)
|
140 |
+
lwork = result[-2][0].real.astype(numpy.int_)
|
141 |
+
|
142 |
+
if sort is None:
|
143 |
+
sort_t = 0
|
144 |
+
def sfunction(x):
|
145 |
+
return None
|
146 |
+
else:
|
147 |
+
sort_t = 1
|
148 |
+
if callable(sort):
|
149 |
+
sfunction = sort
|
150 |
+
elif sort == 'lhp':
|
151 |
+
def sfunction(x):
|
152 |
+
return x.real < 0.0
|
153 |
+
elif sort == 'rhp':
|
154 |
+
def sfunction(x):
|
155 |
+
return x.real >= 0.0
|
156 |
+
elif sort == 'iuc':
|
157 |
+
def sfunction(x):
|
158 |
+
return abs(x) <= 1.0
|
159 |
+
elif sort == 'ouc':
|
160 |
+
def sfunction(x):
|
161 |
+
return abs(x) > 1.0
|
162 |
+
else:
|
163 |
+
raise ValueError("'sort' parameter must either be 'None', or a "
|
164 |
+
"callable, or one of ('lhp','rhp','iuc','ouc')")
|
165 |
+
|
166 |
+
result = gees(sfunction, a1, lwork=lwork, overwrite_a=overwrite_a,
|
167 |
+
sort_t=sort_t)
|
168 |
+
|
169 |
+
info = result[-1]
|
170 |
+
if info < 0:
|
171 |
+
raise ValueError(f'illegal value in {-info}-th argument of internal gees')
|
172 |
+
elif info == a1.shape[0] + 1:
|
173 |
+
raise LinAlgError('Eigenvalues could not be separated for reordering.')
|
174 |
+
elif info == a1.shape[0] + 2:
|
175 |
+
raise LinAlgError('Leading eigenvalues do not satisfy sort condition.')
|
176 |
+
elif info > 0:
|
177 |
+
raise LinAlgError("Schur form not found. Possibly ill-conditioned.")
|
178 |
+
|
179 |
+
if sort_t == 0:
|
180 |
+
return result[0], result[-3]
|
181 |
+
else:
|
182 |
+
return result[0], result[-3], result[1]
|
183 |
+
|
184 |
+
|
185 |
+
eps = numpy.finfo(float).eps
|
186 |
+
feps = numpy.finfo(single).eps
|
187 |
+
|
188 |
+
_array_kind = {'b': 0, 'h': 0, 'B': 0, 'i': 0, 'l': 0,
|
189 |
+
'f': 0, 'd': 0, 'F': 1, 'D': 1}
|
190 |
+
_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1}
|
191 |
+
_array_type = [['f', 'd'], ['F', 'D']]
|
192 |
+
|
193 |
+
|
194 |
+
def _commonType(*arrays):
|
195 |
+
kind = 0
|
196 |
+
precision = 0
|
197 |
+
for a in arrays:
|
198 |
+
t = a.dtype.char
|
199 |
+
kind = max(kind, _array_kind[t])
|
200 |
+
precision = max(precision, _array_precision[t])
|
201 |
+
return _array_type[kind][precision]
|
202 |
+
|
203 |
+
|
204 |
+
def _castCopy(type, *arrays):
|
205 |
+
cast_arrays = ()
|
206 |
+
for a in arrays:
|
207 |
+
if a.dtype.char == type:
|
208 |
+
cast_arrays = cast_arrays + (a.copy(),)
|
209 |
+
else:
|
210 |
+
cast_arrays = cast_arrays + (a.astype(type),)
|
211 |
+
if len(cast_arrays) == 1:
|
212 |
+
return cast_arrays[0]
|
213 |
+
else:
|
214 |
+
return cast_arrays
|
215 |
+
|
216 |
+
|
217 |
+
def rsf2csf(T, Z, check_finite=True):
|
218 |
+
"""
|
219 |
+
Convert real Schur form to complex Schur form.
|
220 |
+
|
221 |
+
Convert a quasi-diagonal real-valued Schur form to the upper-triangular
|
222 |
+
complex-valued Schur form.
|
223 |
+
|
224 |
+
Parameters
|
225 |
+
----------
|
226 |
+
T : (M, M) array_like
|
227 |
+
Real Schur form of the original array
|
228 |
+
Z : (M, M) array_like
|
229 |
+
Schur transformation matrix
|
230 |
+
check_finite : bool, optional
|
231 |
+
Whether to check that the input arrays contain only finite numbers.
|
232 |
+
Disabling may give a performance gain, but may result in problems
|
233 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
234 |
+
|
235 |
+
Returns
|
236 |
+
-------
|
237 |
+
T : (M, M) ndarray
|
238 |
+
Complex Schur form of the original array
|
239 |
+
Z : (M, M) ndarray
|
240 |
+
Schur transformation matrix corresponding to the complex form
|
241 |
+
|
242 |
+
See Also
|
243 |
+
--------
|
244 |
+
schur : Schur decomposition of an array
|
245 |
+
|
246 |
+
Examples
|
247 |
+
--------
|
248 |
+
>>> import numpy as np
|
249 |
+
>>> from scipy.linalg import schur, rsf2csf
|
250 |
+
>>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]])
|
251 |
+
>>> T, Z = schur(A)
|
252 |
+
>>> T
|
253 |
+
array([[ 2.65896708, 1.42440458, -1.92933439],
|
254 |
+
[ 0. , -0.32948354, -0.49063704],
|
255 |
+
[ 0. , 1.31178921, -0.32948354]])
|
256 |
+
>>> Z
|
257 |
+
array([[0.72711591, -0.60156188, 0.33079564],
|
258 |
+
[0.52839428, 0.79801892, 0.28976765],
|
259 |
+
[0.43829436, 0.03590414, -0.89811411]])
|
260 |
+
>>> T2 , Z2 = rsf2csf(T, Z)
|
261 |
+
>>> T2
|
262 |
+
array([[2.65896708+0.j, -1.64592781+0.743164187j, -1.21516887+1.00660462j],
|
263 |
+
[0.+0.j , -0.32948354+8.02254558e-01j, -0.82115218-2.77555756e-17j],
|
264 |
+
[0.+0.j , 0.+0.j, -0.32948354-0.802254558j]])
|
265 |
+
>>> Z2
|
266 |
+
array([[0.72711591+0.j, 0.28220393-0.31385693j, 0.51319638-0.17258824j],
|
267 |
+
[0.52839428+0.j, 0.24720268+0.41635578j, -0.68079517-0.15118243j],
|
268 |
+
[0.43829436+0.j, -0.76618703+0.01873251j, -0.03063006+0.46857912j]])
|
269 |
+
|
270 |
+
"""
|
271 |
+
if check_finite:
|
272 |
+
Z, T = map(asarray_chkfinite, (Z, T))
|
273 |
+
else:
|
274 |
+
Z, T = map(asarray, (Z, T))
|
275 |
+
|
276 |
+
for ind, X in enumerate([Z, T]):
|
277 |
+
if X.ndim != 2 or X.shape[0] != X.shape[1]:
|
278 |
+
raise ValueError("Input '{}' must be square.".format('ZT'[ind]))
|
279 |
+
|
280 |
+
if T.shape[0] != Z.shape[0]:
|
281 |
+
message = f"Input array shapes must match: Z: {Z.shape} vs. T: {T.shape}"
|
282 |
+
raise ValueError(message)
|
283 |
+
N = T.shape[0]
|
284 |
+
t = _commonType(Z, T, array([3.0], 'F'))
|
285 |
+
Z, T = _castCopy(t, Z, T)
|
286 |
+
|
287 |
+
for m in range(N-1, 0, -1):
|
288 |
+
if abs(T[m, m-1]) > eps*(abs(T[m-1, m-1]) + abs(T[m, m])):
|
289 |
+
mu = eigvals(T[m-1:m+1, m-1:m+1]) - T[m, m]
|
290 |
+
r = norm([mu[0], T[m, m-1]])
|
291 |
+
c = mu[0] / r
|
292 |
+
s = T[m, m-1] / r
|
293 |
+
G = array([[c.conj(), s], [-s, c]], dtype=t)
|
294 |
+
|
295 |
+
T[m-1:m+1, m-1:] = G.dot(T[m-1:m+1, m-1:])
|
296 |
+
T[:m+1, m-1:m+1] = T[:m+1, m-1:m+1].dot(G.conj().T)
|
297 |
+
Z[:, m-1:m+1] = Z[:, m-1:m+1].dot(G.conj().T)
|
298 |
+
|
299 |
+
T[m, m-1] = 0.0
|
300 |
+
return T, Z
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_decomp_update.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (373 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_fblas.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (642 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_flapack.cpython-310-x86_64-linux-gnu.so
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4565fa0d0dc440d074193a89770c505a2a17463dcfd6346e83da0858f22f1b1e
|
3 |
+
size 2066281
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py
ADDED
@@ -0,0 +1,861 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# Author: Travis Oliphant, March 2002
|
3 |
+
#
|
4 |
+
from itertools import product
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
from numpy import (dot, diag, prod, logical_not, ravel, transpose,
|
8 |
+
conjugate, absolute, amax, sign, isfinite, triu)
|
9 |
+
|
10 |
+
# Local imports
|
11 |
+
from scipy.linalg import LinAlgError, bandwidth
|
12 |
+
from ._misc import norm
|
13 |
+
from ._basic import solve, inv
|
14 |
+
from ._decomp_svd import svd
|
15 |
+
from ._decomp_schur import schur, rsf2csf
|
16 |
+
from ._expm_frechet import expm_frechet, expm_cond
|
17 |
+
from ._matfuncs_sqrtm import sqrtm
|
18 |
+
from ._matfuncs_expm import pick_pade_structure, pade_UV_calc
|
19 |
+
|
20 |
+
# deprecated imports to be removed in SciPy 1.13.0
|
21 |
+
from numpy import single # noqa: F401
|
22 |
+
|
23 |
+
__all__ = ['expm', 'cosm', 'sinm', 'tanm', 'coshm', 'sinhm', 'tanhm', 'logm',
|
24 |
+
'funm', 'signm', 'sqrtm', 'fractional_matrix_power', 'expm_frechet',
|
25 |
+
'expm_cond', 'khatri_rao']
|
26 |
+
|
27 |
+
eps = np.finfo('d').eps
|
28 |
+
feps = np.finfo('f').eps
|
29 |
+
|
30 |
+
_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1}
|
31 |
+
|
32 |
+
|
33 |
+
###############################################################################
|
34 |
+
# Utility functions.
|
35 |
+
|
36 |
+
|
37 |
+
def _asarray_square(A):
|
38 |
+
"""
|
39 |
+
Wraps asarray with the extra requirement that the input be a square matrix.
|
40 |
+
|
41 |
+
The motivation is that the matfuncs module has real functions that have
|
42 |
+
been lifted to square matrix functions.
|
43 |
+
|
44 |
+
Parameters
|
45 |
+
----------
|
46 |
+
A : array_like
|
47 |
+
A square matrix.
|
48 |
+
|
49 |
+
Returns
|
50 |
+
-------
|
51 |
+
out : ndarray
|
52 |
+
An ndarray copy or view or other representation of A.
|
53 |
+
|
54 |
+
"""
|
55 |
+
A = np.asarray(A)
|
56 |
+
if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
|
57 |
+
raise ValueError('expected square array_like input')
|
58 |
+
return A
|
59 |
+
|
60 |
+
|
61 |
+
def _maybe_real(A, B, tol=None):
|
62 |
+
"""
|
63 |
+
Return either B or the real part of B, depending on properties of A and B.
|
64 |
+
|
65 |
+
The motivation is that B has been computed as a complicated function of A,
|
66 |
+
and B may be perturbed by negligible imaginary components.
|
67 |
+
If A is real and B is complex with small imaginary components,
|
68 |
+
then return a real copy of B. The assumption in that case would be that
|
69 |
+
the imaginary components of B are numerical artifacts.
|
70 |
+
|
71 |
+
Parameters
|
72 |
+
----------
|
73 |
+
A : ndarray
|
74 |
+
Input array whose type is to be checked as real vs. complex.
|
75 |
+
B : ndarray
|
76 |
+
Array to be returned, possibly without its imaginary part.
|
77 |
+
tol : float
|
78 |
+
Absolute tolerance.
|
79 |
+
|
80 |
+
Returns
|
81 |
+
-------
|
82 |
+
out : real or complex array
|
83 |
+
Either the input array B or only the real part of the input array B.
|
84 |
+
|
85 |
+
"""
|
86 |
+
# Note that booleans and integers compare as real.
|
87 |
+
if np.isrealobj(A) and np.iscomplexobj(B):
|
88 |
+
if tol is None:
|
89 |
+
tol = {0: feps*1e3, 1: eps*1e6}[_array_precision[B.dtype.char]]
|
90 |
+
if np.allclose(B.imag, 0.0, atol=tol):
|
91 |
+
B = B.real
|
92 |
+
return B
|
93 |
+
|
94 |
+
|
95 |
+
###############################################################################
|
96 |
+
# Matrix functions.
|
97 |
+
|
98 |
+
|
99 |
+
def fractional_matrix_power(A, t):
|
100 |
+
"""
|
101 |
+
Compute the fractional power of a matrix.
|
102 |
+
|
103 |
+
Proceeds according to the discussion in section (6) of [1]_.
|
104 |
+
|
105 |
+
Parameters
|
106 |
+
----------
|
107 |
+
A : (N, N) array_like
|
108 |
+
Matrix whose fractional power to evaluate.
|
109 |
+
t : float
|
110 |
+
Fractional power.
|
111 |
+
|
112 |
+
Returns
|
113 |
+
-------
|
114 |
+
X : (N, N) array_like
|
115 |
+
The fractional power of the matrix.
|
116 |
+
|
117 |
+
References
|
118 |
+
----------
|
119 |
+
.. [1] Nicholas J. Higham and Lijing lin (2011)
|
120 |
+
"A Schur-Pade Algorithm for Fractional Powers of a Matrix."
|
121 |
+
SIAM Journal on Matrix Analysis and Applications,
|
122 |
+
32 (3). pp. 1056-1078. ISSN 0895-4798
|
123 |
+
|
124 |
+
Examples
|
125 |
+
--------
|
126 |
+
>>> import numpy as np
|
127 |
+
>>> from scipy.linalg import fractional_matrix_power
|
128 |
+
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
|
129 |
+
>>> b = fractional_matrix_power(a, 0.5)
|
130 |
+
>>> b
|
131 |
+
array([[ 0.75592895, 1.13389342],
|
132 |
+
[ 0.37796447, 1.88982237]])
|
133 |
+
>>> np.dot(b, b) # Verify square root
|
134 |
+
array([[ 1., 3.],
|
135 |
+
[ 1., 4.]])
|
136 |
+
|
137 |
+
"""
|
138 |
+
# This fixes some issue with imports;
|
139 |
+
# this function calls onenormest which is in scipy.sparse.
|
140 |
+
A = _asarray_square(A)
|
141 |
+
import scipy.linalg._matfuncs_inv_ssq
|
142 |
+
return scipy.linalg._matfuncs_inv_ssq._fractional_matrix_power(A, t)
|
143 |
+
|
144 |
+
|
145 |
+
def logm(A, disp=True):
|
146 |
+
"""
|
147 |
+
Compute matrix logarithm.
|
148 |
+
|
149 |
+
The matrix logarithm is the inverse of
|
150 |
+
expm: expm(logm(`A`)) == `A`
|
151 |
+
|
152 |
+
Parameters
|
153 |
+
----------
|
154 |
+
A : (N, N) array_like
|
155 |
+
Matrix whose logarithm to evaluate
|
156 |
+
disp : bool, optional
|
157 |
+
Print warning if error in the result is estimated large
|
158 |
+
instead of returning estimated error. (Default: True)
|
159 |
+
|
160 |
+
Returns
|
161 |
+
-------
|
162 |
+
logm : (N, N) ndarray
|
163 |
+
Matrix logarithm of `A`
|
164 |
+
errest : float
|
165 |
+
(if disp == False)
|
166 |
+
|
167 |
+
1-norm of the estimated error, ||err||_1 / ||A||_1
|
168 |
+
|
169 |
+
References
|
170 |
+
----------
|
171 |
+
.. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012)
|
172 |
+
"Improved Inverse Scaling and Squaring Algorithms
|
173 |
+
for the Matrix Logarithm."
|
174 |
+
SIAM Journal on Scientific Computing, 34 (4). C152-C169.
|
175 |
+
ISSN 1095-7197
|
176 |
+
|
177 |
+
.. [2] Nicholas J. Higham (2008)
|
178 |
+
"Functions of Matrices: Theory and Computation"
|
179 |
+
ISBN 978-0-898716-46-7
|
180 |
+
|
181 |
+
.. [3] Nicholas J. Higham and Lijing lin (2011)
|
182 |
+
"A Schur-Pade Algorithm for Fractional Powers of a Matrix."
|
183 |
+
SIAM Journal on Matrix Analysis and Applications,
|
184 |
+
32 (3). pp. 1056-1078. ISSN 0895-4798
|
185 |
+
|
186 |
+
Examples
|
187 |
+
--------
|
188 |
+
>>> import numpy as np
|
189 |
+
>>> from scipy.linalg import logm, expm
|
190 |
+
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
|
191 |
+
>>> b = logm(a)
|
192 |
+
>>> b
|
193 |
+
array([[-1.02571087, 2.05142174],
|
194 |
+
[ 0.68380725, 1.02571087]])
|
195 |
+
>>> expm(b) # Verify expm(logm(a)) returns a
|
196 |
+
array([[ 1., 3.],
|
197 |
+
[ 1., 4.]])
|
198 |
+
|
199 |
+
"""
|
200 |
+
A = _asarray_square(A)
|
201 |
+
# Avoid circular import ... this is OK, right?
|
202 |
+
import scipy.linalg._matfuncs_inv_ssq
|
203 |
+
F = scipy.linalg._matfuncs_inv_ssq._logm(A)
|
204 |
+
F = _maybe_real(A, F)
|
205 |
+
errtol = 1000*eps
|
206 |
+
# TODO use a better error approximation
|
207 |
+
errest = norm(expm(F)-A, 1) / norm(A, 1)
|
208 |
+
if disp:
|
209 |
+
if not isfinite(errest) or errest >= errtol:
|
210 |
+
print("logm result may be inaccurate, approximate err =", errest)
|
211 |
+
return F
|
212 |
+
else:
|
213 |
+
return F, errest
|
214 |
+
|
215 |
+
|
216 |
+
def expm(A):
|
217 |
+
"""Compute the matrix exponential of an array.
|
218 |
+
|
219 |
+
Parameters
|
220 |
+
----------
|
221 |
+
A : ndarray
|
222 |
+
Input with last two dimensions are square ``(..., n, n)``.
|
223 |
+
|
224 |
+
Returns
|
225 |
+
-------
|
226 |
+
eA : ndarray
|
227 |
+
The resulting matrix exponential with the same shape of ``A``
|
228 |
+
|
229 |
+
Notes
|
230 |
+
-----
|
231 |
+
Implements the algorithm given in [1], which is essentially a Pade
|
232 |
+
approximation with a variable order that is decided based on the array
|
233 |
+
data.
|
234 |
+
|
235 |
+
For input with size ``n``, the memory usage is in the worst case in the
|
236 |
+
order of ``8*(n**2)``. If the input data is not of single and double
|
237 |
+
precision of real and complex dtypes, it is copied to a new array.
|
238 |
+
|
239 |
+
For cases ``n >= 400``, the exact 1-norm computation cost, breaks even with
|
240 |
+
1-norm estimation and from that point on the estimation scheme given in
|
241 |
+
[2] is used to decide on the approximation order.
|
242 |
+
|
243 |
+
References
|
244 |
+
----------
|
245 |
+
.. [1] Awad H. Al-Mohy and Nicholas J. Higham, (2009), "A New Scaling
|
246 |
+
and Squaring Algorithm for the Matrix Exponential", SIAM J. Matrix
|
247 |
+
Anal. Appl. 31(3):970-989, :doi:`10.1137/09074721X`
|
248 |
+
|
249 |
+
.. [2] Nicholas J. Higham and Francoise Tisseur (2000), "A Block Algorithm
|
250 |
+
for Matrix 1-Norm Estimation, with an Application to 1-Norm
|
251 |
+
Pseudospectra." SIAM J. Matrix Anal. Appl. 21(4):1185-1201,
|
252 |
+
:doi:`10.1137/S0895479899356080`
|
253 |
+
|
254 |
+
Examples
|
255 |
+
--------
|
256 |
+
>>> import numpy as np
|
257 |
+
>>> from scipy.linalg import expm, sinm, cosm
|
258 |
+
|
259 |
+
Matrix version of the formula exp(0) = 1:
|
260 |
+
|
261 |
+
>>> expm(np.zeros((3, 2, 2)))
|
262 |
+
array([[[1., 0.],
|
263 |
+
[0., 1.]],
|
264 |
+
<BLANKLINE>
|
265 |
+
[[1., 0.],
|
266 |
+
[0., 1.]],
|
267 |
+
<BLANKLINE>
|
268 |
+
[[1., 0.],
|
269 |
+
[0., 1.]]])
|
270 |
+
|
271 |
+
Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
|
272 |
+
applied to a matrix:
|
273 |
+
|
274 |
+
>>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
|
275 |
+
>>> expm(1j*a)
|
276 |
+
array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
|
277 |
+
[ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
|
278 |
+
>>> cosm(a) + 1j*sinm(a)
|
279 |
+
array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
|
280 |
+
[ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
|
281 |
+
|
282 |
+
"""
|
283 |
+
a = np.asarray(A)
|
284 |
+
if a.size == 1 and a.ndim < 2:
|
285 |
+
return np.array([[np.exp(a.item())]])
|
286 |
+
|
287 |
+
if a.ndim < 2:
|
288 |
+
raise LinAlgError('The input array must be at least two-dimensional')
|
289 |
+
if a.shape[-1] != a.shape[-2]:
|
290 |
+
raise LinAlgError('Last 2 dimensions of the array must be square')
|
291 |
+
n = a.shape[-1]
|
292 |
+
# Empty array
|
293 |
+
if min(*a.shape) == 0:
|
294 |
+
return np.empty_like(a)
|
295 |
+
|
296 |
+
# Scalar case
|
297 |
+
if a.shape[-2:] == (1, 1):
|
298 |
+
return np.exp(a)
|
299 |
+
|
300 |
+
if not np.issubdtype(a.dtype, np.inexact):
|
301 |
+
a = a.astype(np.float64)
|
302 |
+
elif a.dtype == np.float16:
|
303 |
+
a = a.astype(np.float32)
|
304 |
+
|
305 |
+
# An explicit formula for 2x2 case exists (formula (2.2) in [1]). However, without
|
306 |
+
# Kahan's method, numerical instabilities can occur (See gh-19584). Hence removed
|
307 |
+
# here until we have a more stable implementation.
|
308 |
+
|
309 |
+
n = a.shape[-1]
|
310 |
+
eA = np.empty(a.shape, dtype=a.dtype)
|
311 |
+
# working memory to hold intermediate arrays
|
312 |
+
Am = np.empty((5, n, n), dtype=a.dtype)
|
313 |
+
|
314 |
+
# Main loop to go through the slices of an ndarray and passing to expm
|
315 |
+
for ind in product(*[range(x) for x in a.shape[:-2]]):
|
316 |
+
aw = a[ind]
|
317 |
+
|
318 |
+
lu = bandwidth(aw)
|
319 |
+
if not any(lu): # a is diagonal?
|
320 |
+
eA[ind] = np.diag(np.exp(np.diag(aw)))
|
321 |
+
continue
|
322 |
+
|
323 |
+
# Generic/triangular case; copy the slice into scratch and send.
|
324 |
+
# Am will be mutated by pick_pade_structure
|
325 |
+
Am[0, :, :] = aw
|
326 |
+
m, s = pick_pade_structure(Am)
|
327 |
+
|
328 |
+
if s != 0: # scaling needed
|
329 |
+
Am[:4] *= [[[2**(-s)]], [[4**(-s)]], [[16**(-s)]], [[64**(-s)]]]
|
330 |
+
|
331 |
+
pade_UV_calc(Am, n, m)
|
332 |
+
eAw = Am[0]
|
333 |
+
|
334 |
+
if s != 0: # squaring needed
|
335 |
+
|
336 |
+
if (lu[1] == 0) or (lu[0] == 0): # lower/upper triangular
|
337 |
+
# This branch implements Code Fragment 2.1 of [1]
|
338 |
+
|
339 |
+
diag_aw = np.diag(aw)
|
340 |
+
# einsum returns a writable view
|
341 |
+
np.einsum('ii->i', eAw)[:] = np.exp(diag_aw * 2**(-s))
|
342 |
+
# super/sub diagonal
|
343 |
+
sd = np.diag(aw, k=-1 if lu[1] == 0 else 1)
|
344 |
+
|
345 |
+
for i in range(s-1, -1, -1):
|
346 |
+
eAw = eAw @ eAw
|
347 |
+
|
348 |
+
# diagonal
|
349 |
+
np.einsum('ii->i', eAw)[:] = np.exp(diag_aw * 2.**(-i))
|
350 |
+
exp_sd = _exp_sinch(diag_aw * (2.**(-i))) * (sd * 2**(-i))
|
351 |
+
if lu[1] == 0: # lower
|
352 |
+
np.einsum('ii->i', eAw[1:, :-1])[:] = exp_sd
|
353 |
+
else: # upper
|
354 |
+
np.einsum('ii->i', eAw[:-1, 1:])[:] = exp_sd
|
355 |
+
|
356 |
+
else: # generic
|
357 |
+
for _ in range(s):
|
358 |
+
eAw = eAw @ eAw
|
359 |
+
|
360 |
+
# Zero out the entries from np.empty in case of triangular input
|
361 |
+
if (lu[0] == 0) or (lu[1] == 0):
|
362 |
+
eA[ind] = np.triu(eAw) if lu[0] == 0 else np.tril(eAw)
|
363 |
+
else:
|
364 |
+
eA[ind] = eAw
|
365 |
+
|
366 |
+
return eA
|
367 |
+
|
368 |
+
|
369 |
+
def _exp_sinch(x):
|
370 |
+
# Higham's formula (10.42), might overflow, see GH-11839
|
371 |
+
lexp_diff = np.diff(np.exp(x))
|
372 |
+
l_diff = np.diff(x)
|
373 |
+
mask_z = l_diff == 0.
|
374 |
+
lexp_diff[~mask_z] /= l_diff[~mask_z]
|
375 |
+
lexp_diff[mask_z] = np.exp(x[:-1][mask_z])
|
376 |
+
return lexp_diff
|
377 |
+
|
378 |
+
|
379 |
+
def cosm(A):
|
380 |
+
"""
|
381 |
+
Compute the matrix cosine.
|
382 |
+
|
383 |
+
This routine uses expm to compute the matrix exponentials.
|
384 |
+
|
385 |
+
Parameters
|
386 |
+
----------
|
387 |
+
A : (N, N) array_like
|
388 |
+
Input array
|
389 |
+
|
390 |
+
Returns
|
391 |
+
-------
|
392 |
+
cosm : (N, N) ndarray
|
393 |
+
Matrix cosine of A
|
394 |
+
|
395 |
+
Examples
|
396 |
+
--------
|
397 |
+
>>> import numpy as np
|
398 |
+
>>> from scipy.linalg import expm, sinm, cosm
|
399 |
+
|
400 |
+
Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
|
401 |
+
applied to a matrix:
|
402 |
+
|
403 |
+
>>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
|
404 |
+
>>> expm(1j*a)
|
405 |
+
array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
|
406 |
+
[ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
|
407 |
+
>>> cosm(a) + 1j*sinm(a)
|
408 |
+
array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
|
409 |
+
[ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
|
410 |
+
|
411 |
+
"""
|
412 |
+
A = _asarray_square(A)
|
413 |
+
if np.iscomplexobj(A):
|
414 |
+
return 0.5*(expm(1j*A) + expm(-1j*A))
|
415 |
+
else:
|
416 |
+
return expm(1j*A).real
|
417 |
+
|
418 |
+
|
419 |
+
def sinm(A):
|
420 |
+
"""
|
421 |
+
Compute the matrix sine.
|
422 |
+
|
423 |
+
This routine uses expm to compute the matrix exponentials.
|
424 |
+
|
425 |
+
Parameters
|
426 |
+
----------
|
427 |
+
A : (N, N) array_like
|
428 |
+
Input array.
|
429 |
+
|
430 |
+
Returns
|
431 |
+
-------
|
432 |
+
sinm : (N, N) ndarray
|
433 |
+
Matrix sine of `A`
|
434 |
+
|
435 |
+
Examples
|
436 |
+
--------
|
437 |
+
>>> import numpy as np
|
438 |
+
>>> from scipy.linalg import expm, sinm, cosm
|
439 |
+
|
440 |
+
Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
|
441 |
+
applied to a matrix:
|
442 |
+
|
443 |
+
>>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
|
444 |
+
>>> expm(1j*a)
|
445 |
+
array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
|
446 |
+
[ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
|
447 |
+
>>> cosm(a) + 1j*sinm(a)
|
448 |
+
array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
|
449 |
+
[ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
|
450 |
+
|
451 |
+
"""
|
452 |
+
A = _asarray_square(A)
|
453 |
+
if np.iscomplexobj(A):
|
454 |
+
return -0.5j*(expm(1j*A) - expm(-1j*A))
|
455 |
+
else:
|
456 |
+
return expm(1j*A).imag
|
457 |
+
|
458 |
+
|
459 |
+
def tanm(A):
|
460 |
+
"""
|
461 |
+
Compute the matrix tangent.
|
462 |
+
|
463 |
+
This routine uses expm to compute the matrix exponentials.
|
464 |
+
|
465 |
+
Parameters
|
466 |
+
----------
|
467 |
+
A : (N, N) array_like
|
468 |
+
Input array.
|
469 |
+
|
470 |
+
Returns
|
471 |
+
-------
|
472 |
+
tanm : (N, N) ndarray
|
473 |
+
Matrix tangent of `A`
|
474 |
+
|
475 |
+
Examples
|
476 |
+
--------
|
477 |
+
>>> import numpy as np
|
478 |
+
>>> from scipy.linalg import tanm, sinm, cosm
|
479 |
+
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
|
480 |
+
>>> t = tanm(a)
|
481 |
+
>>> t
|
482 |
+
array([[ -2.00876993, -8.41880636],
|
483 |
+
[ -2.80626879, -10.42757629]])
|
484 |
+
|
485 |
+
Verify tanm(a) = sinm(a).dot(inv(cosm(a)))
|
486 |
+
|
487 |
+
>>> s = sinm(a)
|
488 |
+
>>> c = cosm(a)
|
489 |
+
>>> s.dot(np.linalg.inv(c))
|
490 |
+
array([[ -2.00876993, -8.41880636],
|
491 |
+
[ -2.80626879, -10.42757629]])
|
492 |
+
|
493 |
+
"""
|
494 |
+
A = _asarray_square(A)
|
495 |
+
return _maybe_real(A, solve(cosm(A), sinm(A)))
|
496 |
+
|
497 |
+
|
498 |
+
def coshm(A):
|
499 |
+
"""
|
500 |
+
Compute the hyperbolic matrix cosine.
|
501 |
+
|
502 |
+
This routine uses expm to compute the matrix exponentials.
|
503 |
+
|
504 |
+
Parameters
|
505 |
+
----------
|
506 |
+
A : (N, N) array_like
|
507 |
+
Input array.
|
508 |
+
|
509 |
+
Returns
|
510 |
+
-------
|
511 |
+
coshm : (N, N) ndarray
|
512 |
+
Hyperbolic matrix cosine of `A`
|
513 |
+
|
514 |
+
Examples
|
515 |
+
--------
|
516 |
+
>>> import numpy as np
|
517 |
+
>>> from scipy.linalg import tanhm, sinhm, coshm
|
518 |
+
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
|
519 |
+
>>> c = coshm(a)
|
520 |
+
>>> c
|
521 |
+
array([[ 11.24592233, 38.76236492],
|
522 |
+
[ 12.92078831, 50.00828725]])
|
523 |
+
|
524 |
+
Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
|
525 |
+
|
526 |
+
>>> t = tanhm(a)
|
527 |
+
>>> s = sinhm(a)
|
528 |
+
>>> t - s.dot(np.linalg.inv(c))
|
529 |
+
array([[ 2.72004641e-15, 4.55191440e-15],
|
530 |
+
[ 0.00000000e+00, -5.55111512e-16]])
|
531 |
+
|
532 |
+
"""
|
533 |
+
A = _asarray_square(A)
|
534 |
+
return _maybe_real(A, 0.5 * (expm(A) + expm(-A)))
|
535 |
+
|
536 |
+
|
537 |
+
def sinhm(A):
|
538 |
+
"""
|
539 |
+
Compute the hyperbolic matrix sine.
|
540 |
+
|
541 |
+
This routine uses expm to compute the matrix exponentials.
|
542 |
+
|
543 |
+
Parameters
|
544 |
+
----------
|
545 |
+
A : (N, N) array_like
|
546 |
+
Input array.
|
547 |
+
|
548 |
+
Returns
|
549 |
+
-------
|
550 |
+
sinhm : (N, N) ndarray
|
551 |
+
Hyperbolic matrix sine of `A`
|
552 |
+
|
553 |
+
Examples
|
554 |
+
--------
|
555 |
+
>>> import numpy as np
|
556 |
+
>>> from scipy.linalg import tanhm, sinhm, coshm
|
557 |
+
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
|
558 |
+
>>> s = sinhm(a)
|
559 |
+
>>> s
|
560 |
+
array([[ 10.57300653, 39.28826594],
|
561 |
+
[ 13.09608865, 49.86127247]])
|
562 |
+
|
563 |
+
Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
|
564 |
+
|
565 |
+
>>> t = tanhm(a)
|
566 |
+
>>> c = coshm(a)
|
567 |
+
>>> t - s.dot(np.linalg.inv(c))
|
568 |
+
array([[ 2.72004641e-15, 4.55191440e-15],
|
569 |
+
[ 0.00000000e+00, -5.55111512e-16]])
|
570 |
+
|
571 |
+
"""
|
572 |
+
A = _asarray_square(A)
|
573 |
+
return _maybe_real(A, 0.5 * (expm(A) - expm(-A)))
|
574 |
+
|
575 |
+
|
576 |
+
def tanhm(A):
|
577 |
+
"""
|
578 |
+
Compute the hyperbolic matrix tangent.
|
579 |
+
|
580 |
+
This routine uses expm to compute the matrix exponentials.
|
581 |
+
|
582 |
+
Parameters
|
583 |
+
----------
|
584 |
+
A : (N, N) array_like
|
585 |
+
Input array
|
586 |
+
|
587 |
+
Returns
|
588 |
+
-------
|
589 |
+
tanhm : (N, N) ndarray
|
590 |
+
Hyperbolic matrix tangent of `A`
|
591 |
+
|
592 |
+
Examples
|
593 |
+
--------
|
594 |
+
>>> import numpy as np
|
595 |
+
>>> from scipy.linalg import tanhm, sinhm, coshm
|
596 |
+
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
|
597 |
+
>>> t = tanhm(a)
|
598 |
+
>>> t
|
599 |
+
array([[ 0.3428582 , 0.51987926],
|
600 |
+
[ 0.17329309, 0.86273746]])
|
601 |
+
|
602 |
+
Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
|
603 |
+
|
604 |
+
>>> s = sinhm(a)
|
605 |
+
>>> c = coshm(a)
|
606 |
+
>>> t - s.dot(np.linalg.inv(c))
|
607 |
+
array([[ 2.72004641e-15, 4.55191440e-15],
|
608 |
+
[ 0.00000000e+00, -5.55111512e-16]])
|
609 |
+
|
610 |
+
"""
|
611 |
+
A = _asarray_square(A)
|
612 |
+
return _maybe_real(A, solve(coshm(A), sinhm(A)))
|
613 |
+
|
614 |
+
|
615 |
+
def funm(A, func, disp=True):
|
616 |
+
"""
|
617 |
+
Evaluate a matrix function specified by a callable.
|
618 |
+
|
619 |
+
Returns the value of matrix-valued function ``f`` at `A`. The
|
620 |
+
function ``f`` is an extension of the scalar-valued function `func`
|
621 |
+
to matrices.
|
622 |
+
|
623 |
+
Parameters
|
624 |
+
----------
|
625 |
+
A : (N, N) array_like
|
626 |
+
Matrix at which to evaluate the function
|
627 |
+
func : callable
|
628 |
+
Callable object that evaluates a scalar function f.
|
629 |
+
Must be vectorized (eg. using vectorize).
|
630 |
+
disp : bool, optional
|
631 |
+
Print warning if error in the result is estimated large
|
632 |
+
instead of returning estimated error. (Default: True)
|
633 |
+
|
634 |
+
Returns
|
635 |
+
-------
|
636 |
+
funm : (N, N) ndarray
|
637 |
+
Value of the matrix function specified by func evaluated at `A`
|
638 |
+
errest : float
|
639 |
+
(if disp == False)
|
640 |
+
|
641 |
+
1-norm of the estimated error, ||err||_1 / ||A||_1
|
642 |
+
|
643 |
+
Notes
|
644 |
+
-----
|
645 |
+
This function implements the general algorithm based on Schur decomposition
|
646 |
+
(Algorithm 9.1.1. in [1]_).
|
647 |
+
|
648 |
+
If the input matrix is known to be diagonalizable, then relying on the
|
649 |
+
eigendecomposition is likely to be faster. For example, if your matrix is
|
650 |
+
Hermitian, you can do
|
651 |
+
|
652 |
+
>>> from scipy.linalg import eigh
|
653 |
+
>>> def funm_herm(a, func, check_finite=False):
|
654 |
+
... w, v = eigh(a, check_finite=check_finite)
|
655 |
+
... ## if you further know that your matrix is positive semidefinite,
|
656 |
+
... ## you can optionally guard against precision errors by doing
|
657 |
+
... # w = np.maximum(w, 0)
|
658 |
+
... w = func(w)
|
659 |
+
... return (v * w).dot(v.conj().T)
|
660 |
+
|
661 |
+
References
|
662 |
+
----------
|
663 |
+
.. [1] Gene H. Golub, Charles F. van Loan, Matrix Computations 4th ed.
|
664 |
+
|
665 |
+
Examples
|
666 |
+
--------
|
667 |
+
>>> import numpy as np
|
668 |
+
>>> from scipy.linalg import funm
|
669 |
+
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
|
670 |
+
>>> funm(a, lambda x: x*x)
|
671 |
+
array([[ 4., 15.],
|
672 |
+
[ 5., 19.]])
|
673 |
+
>>> a.dot(a)
|
674 |
+
array([[ 4., 15.],
|
675 |
+
[ 5., 19.]])
|
676 |
+
|
677 |
+
"""
|
678 |
+
A = _asarray_square(A)
|
679 |
+
# Perform Shur decomposition (lapack ?gees)
|
680 |
+
T, Z = schur(A)
|
681 |
+
T, Z = rsf2csf(T, Z)
|
682 |
+
n, n = T.shape
|
683 |
+
F = diag(func(diag(T))) # apply function to diagonal elements
|
684 |
+
F = F.astype(T.dtype.char) # e.g., when F is real but T is complex
|
685 |
+
|
686 |
+
minden = abs(T[0, 0])
|
687 |
+
|
688 |
+
# implement Algorithm 11.1.1 from Golub and Van Loan
|
689 |
+
# "matrix Computations."
|
690 |
+
for p in range(1, n):
|
691 |
+
for i in range(1, n-p+1):
|
692 |
+
j = i + p
|
693 |
+
s = T[i-1, j-1] * (F[j-1, j-1] - F[i-1, i-1])
|
694 |
+
ksl = slice(i, j-1)
|
695 |
+
val = dot(T[i-1, ksl], F[ksl, j-1]) - dot(F[i-1, ksl], T[ksl, j-1])
|
696 |
+
s = s + val
|
697 |
+
den = T[j-1, j-1] - T[i-1, i-1]
|
698 |
+
if den != 0.0:
|
699 |
+
s = s / den
|
700 |
+
F[i-1, j-1] = s
|
701 |
+
minden = min(minden, abs(den))
|
702 |
+
|
703 |
+
F = dot(dot(Z, F), transpose(conjugate(Z)))
|
704 |
+
F = _maybe_real(A, F)
|
705 |
+
|
706 |
+
tol = {0: feps, 1: eps}[_array_precision[F.dtype.char]]
|
707 |
+
if minden == 0.0:
|
708 |
+
minden = tol
|
709 |
+
err = min(1, max(tol, (tol/minden)*norm(triu(T, 1), 1)))
|
710 |
+
if prod(ravel(logical_not(isfinite(F))), axis=0):
|
711 |
+
err = np.inf
|
712 |
+
if disp:
|
713 |
+
if err > 1000*tol:
|
714 |
+
print("funm result may be inaccurate, approximate err =", err)
|
715 |
+
return F
|
716 |
+
else:
|
717 |
+
return F, err
|
718 |
+
|
719 |
+
|
720 |
+
def signm(A, disp=True):
|
721 |
+
"""
|
722 |
+
Matrix sign function.
|
723 |
+
|
724 |
+
Extension of the scalar sign(x) to matrices.
|
725 |
+
|
726 |
+
Parameters
|
727 |
+
----------
|
728 |
+
A : (N, N) array_like
|
729 |
+
Matrix at which to evaluate the sign function
|
730 |
+
disp : bool, optional
|
731 |
+
Print warning if error in the result is estimated large
|
732 |
+
instead of returning estimated error. (Default: True)
|
733 |
+
|
734 |
+
Returns
|
735 |
+
-------
|
736 |
+
signm : (N, N) ndarray
|
737 |
+
Value of the sign function at `A`
|
738 |
+
errest : float
|
739 |
+
(if disp == False)
|
740 |
+
|
741 |
+
1-norm of the estimated error, ||err||_1 / ||A||_1
|
742 |
+
|
743 |
+
Examples
|
744 |
+
--------
|
745 |
+
>>> from scipy.linalg import signm, eigvals
|
746 |
+
>>> a = [[1,2,3], [1,2,1], [1,1,1]]
|
747 |
+
>>> eigvals(a)
|
748 |
+
array([ 4.12488542+0.j, -0.76155718+0.j, 0.63667176+0.j])
|
749 |
+
>>> eigvals(signm(a))
|
750 |
+
array([-1.+0.j, 1.+0.j, 1.+0.j])
|
751 |
+
|
752 |
+
"""
|
753 |
+
A = _asarray_square(A)
|
754 |
+
|
755 |
+
def rounded_sign(x):
|
756 |
+
rx = np.real(x)
|
757 |
+
if rx.dtype.char == 'f':
|
758 |
+
c = 1e3*feps*amax(x)
|
759 |
+
else:
|
760 |
+
c = 1e3*eps*amax(x)
|
761 |
+
return sign((absolute(rx) > c) * rx)
|
762 |
+
result, errest = funm(A, rounded_sign, disp=0)
|
763 |
+
errtol = {0: 1e3*feps, 1: 1e3*eps}[_array_precision[result.dtype.char]]
|
764 |
+
if errest < errtol:
|
765 |
+
return result
|
766 |
+
|
767 |
+
# Handle signm of defective matrices:
|
768 |
+
|
769 |
+
# See "E.D.Denman and J.Leyva-Ramos, Appl.Math.Comp.,
|
770 |
+
# 8:237-250,1981" for how to improve the following (currently a
|
771 |
+
# rather naive) iteration process:
|
772 |
+
|
773 |
+
# a = result # sometimes iteration converges faster but where??
|
774 |
+
|
775 |
+
# Shifting to avoid zero eigenvalues. How to ensure that shifting does
|
776 |
+
# not change the spectrum too much?
|
777 |
+
vals = svd(A, compute_uv=False)
|
778 |
+
max_sv = np.amax(vals)
|
779 |
+
# min_nonzero_sv = vals[(vals>max_sv*errtol).tolist().count(1)-1]
|
780 |
+
# c = 0.5/min_nonzero_sv
|
781 |
+
c = 0.5/max_sv
|
782 |
+
S0 = A + c*np.identity(A.shape[0])
|
783 |
+
prev_errest = errest
|
784 |
+
for i in range(100):
|
785 |
+
iS0 = inv(S0)
|
786 |
+
S0 = 0.5*(S0 + iS0)
|
787 |
+
Pp = 0.5*(dot(S0, S0)+S0)
|
788 |
+
errest = norm(dot(Pp, Pp)-Pp, 1)
|
789 |
+
if errest < errtol or prev_errest == errest:
|
790 |
+
break
|
791 |
+
prev_errest = errest
|
792 |
+
if disp:
|
793 |
+
if not isfinite(errest) or errest >= errtol:
|
794 |
+
print("signm result may be inaccurate, approximate err =", errest)
|
795 |
+
return S0
|
796 |
+
else:
|
797 |
+
return S0, errest
|
798 |
+
|
799 |
+
|
800 |
+
def khatri_rao(a, b):
|
801 |
+
r"""
|
802 |
+
Khatri-rao product
|
803 |
+
|
804 |
+
A column-wise Kronecker product of two matrices
|
805 |
+
|
806 |
+
Parameters
|
807 |
+
----------
|
808 |
+
a : (n, k) array_like
|
809 |
+
Input array
|
810 |
+
b : (m, k) array_like
|
811 |
+
Input array
|
812 |
+
|
813 |
+
Returns
|
814 |
+
-------
|
815 |
+
c: (n*m, k) ndarray
|
816 |
+
Khatri-rao product of `a` and `b`.
|
817 |
+
|
818 |
+
See Also
|
819 |
+
--------
|
820 |
+
kron : Kronecker product
|
821 |
+
|
822 |
+
Notes
|
823 |
+
-----
|
824 |
+
The mathematical definition of the Khatri-Rao product is:
|
825 |
+
|
826 |
+
.. math::
|
827 |
+
|
828 |
+
(A_{ij} \bigotimes B_{ij})_{ij}
|
829 |
+
|
830 |
+
which is the Kronecker product of every column of A and B, e.g.::
|
831 |
+
|
832 |
+
c = np.vstack([np.kron(a[:, k], b[:, k]) for k in range(b.shape[1])]).T
|
833 |
+
|
834 |
+
Examples
|
835 |
+
--------
|
836 |
+
>>> import numpy as np
|
837 |
+
>>> from scipy import linalg
|
838 |
+
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
|
839 |
+
>>> b = np.array([[3, 4, 5], [6, 7, 8], [2, 3, 9]])
|
840 |
+
>>> linalg.khatri_rao(a, b)
|
841 |
+
array([[ 3, 8, 15],
|
842 |
+
[ 6, 14, 24],
|
843 |
+
[ 2, 6, 27],
|
844 |
+
[12, 20, 30],
|
845 |
+
[24, 35, 48],
|
846 |
+
[ 8, 15, 54]])
|
847 |
+
|
848 |
+
"""
|
849 |
+
a = np.asarray(a)
|
850 |
+
b = np.asarray(b)
|
851 |
+
|
852 |
+
if not (a.ndim == 2 and b.ndim == 2):
|
853 |
+
raise ValueError("The both arrays should be 2-dimensional.")
|
854 |
+
|
855 |
+
if not a.shape[1] == b.shape[1]:
|
856 |
+
raise ValueError("The number of columns for both arrays "
|
857 |
+
"should be equal.")
|
858 |
+
|
859 |
+
# c = np.vstack([np.kron(a[:, k], b[:, k]) for k in range(b.shape[1])]).T
|
860 |
+
c = a[..., :, np.newaxis, :] * b[..., np.newaxis, :, :]
|
861 |
+
return c.reshape((-1,) + c.shape[2:])
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (526 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py
ADDED
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Matrix square root for general matrices and for upper triangular matrices.
|
3 |
+
|
4 |
+
This module exists to avoid cyclic imports.
|
5 |
+
|
6 |
+
"""
|
7 |
+
__all__ = ['sqrtm']
|
8 |
+
|
9 |
+
import numpy as np
|
10 |
+
|
11 |
+
from scipy._lib._util import _asarray_validated
|
12 |
+
|
13 |
+
# Local imports
|
14 |
+
from ._misc import norm
|
15 |
+
from .lapack import ztrsyl, dtrsyl
|
16 |
+
from ._decomp_schur import schur, rsf2csf
|
17 |
+
|
18 |
+
|
19 |
+
|
20 |
+
class SqrtmError(np.linalg.LinAlgError):
|
21 |
+
pass
|
22 |
+
|
23 |
+
|
24 |
+
from ._matfuncs_sqrtm_triu import within_block_loop # noqa: E402
|
25 |
+
|
26 |
+
|
27 |
+
def _sqrtm_triu(T, blocksize=64):
|
28 |
+
"""
|
29 |
+
Matrix square root of an upper triangular matrix.
|
30 |
+
|
31 |
+
This is a helper function for `sqrtm` and `logm`.
|
32 |
+
|
33 |
+
Parameters
|
34 |
+
----------
|
35 |
+
T : (N, N) array_like upper triangular
|
36 |
+
Matrix whose square root to evaluate
|
37 |
+
blocksize : int, optional
|
38 |
+
If the blocksize is not degenerate with respect to the
|
39 |
+
size of the input array, then use a blocked algorithm. (Default: 64)
|
40 |
+
|
41 |
+
Returns
|
42 |
+
-------
|
43 |
+
sqrtm : (N, N) ndarray
|
44 |
+
Value of the sqrt function at `T`
|
45 |
+
|
46 |
+
References
|
47 |
+
----------
|
48 |
+
.. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
|
49 |
+
"Blocked Schur Algorithms for Computing the Matrix Square Root,
|
50 |
+
Lecture Notes in Computer Science, 7782. pp. 171-182.
|
51 |
+
|
52 |
+
"""
|
53 |
+
T_diag = np.diag(T)
|
54 |
+
keep_it_real = np.isrealobj(T) and np.min(T_diag) >= 0
|
55 |
+
|
56 |
+
# Cast to complex as necessary + ensure double precision
|
57 |
+
if not keep_it_real:
|
58 |
+
T = np.asarray(T, dtype=np.complex128, order="C")
|
59 |
+
T_diag = np.asarray(T_diag, dtype=np.complex128)
|
60 |
+
else:
|
61 |
+
T = np.asarray(T, dtype=np.float64, order="C")
|
62 |
+
T_diag = np.asarray(T_diag, dtype=np.float64)
|
63 |
+
|
64 |
+
R = np.diag(np.sqrt(T_diag))
|
65 |
+
|
66 |
+
# Compute the number of blocks to use; use at least one block.
|
67 |
+
n, n = T.shape
|
68 |
+
nblocks = max(n // blocksize, 1)
|
69 |
+
|
70 |
+
# Compute the smaller of the two sizes of blocks that
|
71 |
+
# we will actually use, and compute the number of large blocks.
|
72 |
+
bsmall, nlarge = divmod(n, nblocks)
|
73 |
+
blarge = bsmall + 1
|
74 |
+
nsmall = nblocks - nlarge
|
75 |
+
if nsmall * bsmall + nlarge * blarge != n:
|
76 |
+
raise Exception('internal inconsistency')
|
77 |
+
|
78 |
+
# Define the index range covered by each block.
|
79 |
+
start_stop_pairs = []
|
80 |
+
start = 0
|
81 |
+
for count, size in ((nsmall, bsmall), (nlarge, blarge)):
|
82 |
+
for i in range(count):
|
83 |
+
start_stop_pairs.append((start, start + size))
|
84 |
+
start += size
|
85 |
+
|
86 |
+
# Within-block interactions (Cythonized)
|
87 |
+
try:
|
88 |
+
within_block_loop(R, T, start_stop_pairs, nblocks)
|
89 |
+
except RuntimeError as e:
|
90 |
+
raise SqrtmError(*e.args) from e
|
91 |
+
|
92 |
+
# Between-block interactions (Cython would give no significant speedup)
|
93 |
+
for j in range(nblocks):
|
94 |
+
jstart, jstop = start_stop_pairs[j]
|
95 |
+
for i in range(j-1, -1, -1):
|
96 |
+
istart, istop = start_stop_pairs[i]
|
97 |
+
S = T[istart:istop, jstart:jstop]
|
98 |
+
if j - i > 1:
|
99 |
+
S = S - R[istart:istop, istop:jstart].dot(R[istop:jstart,
|
100 |
+
jstart:jstop])
|
101 |
+
|
102 |
+
# Invoke LAPACK.
|
103 |
+
# For more details, see the solve_sylvester implementation
|
104 |
+
# and the fortran dtrsyl and ztrsyl docs.
|
105 |
+
Rii = R[istart:istop, istart:istop]
|
106 |
+
Rjj = R[jstart:jstop, jstart:jstop]
|
107 |
+
if keep_it_real:
|
108 |
+
x, scale, info = dtrsyl(Rii, Rjj, S)
|
109 |
+
else:
|
110 |
+
x, scale, info = ztrsyl(Rii, Rjj, S)
|
111 |
+
R[istart:istop, jstart:jstop] = x * scale
|
112 |
+
|
113 |
+
# Return the matrix square root.
|
114 |
+
return R
|
115 |
+
|
116 |
+
|
117 |
+
def sqrtm(A, disp=True, blocksize=64):
|
118 |
+
"""
|
119 |
+
Matrix square root.
|
120 |
+
|
121 |
+
Parameters
|
122 |
+
----------
|
123 |
+
A : (N, N) array_like
|
124 |
+
Matrix whose square root to evaluate
|
125 |
+
disp : bool, optional
|
126 |
+
Print warning if error in the result is estimated large
|
127 |
+
instead of returning estimated error. (Default: True)
|
128 |
+
blocksize : integer, optional
|
129 |
+
If the blocksize is not degenerate with respect to the
|
130 |
+
size of the input array, then use a blocked algorithm. (Default: 64)
|
131 |
+
|
132 |
+
Returns
|
133 |
+
-------
|
134 |
+
sqrtm : (N, N) ndarray
|
135 |
+
Value of the sqrt function at `A`. The dtype is float or complex.
|
136 |
+
The precision (data size) is determined based on the precision of
|
137 |
+
input `A`. When the dtype is float, the precision is the same as `A`.
|
138 |
+
When the dtype is complex, the precision is double that of `A`. The
|
139 |
+
precision might be clipped by each dtype precision range.
|
140 |
+
|
141 |
+
errest : float
|
142 |
+
(if disp == False)
|
143 |
+
|
144 |
+
Frobenius norm of the estimated error, ||err||_F / ||A||_F
|
145 |
+
|
146 |
+
References
|
147 |
+
----------
|
148 |
+
.. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
|
149 |
+
"Blocked Schur Algorithms for Computing the Matrix Square Root,
|
150 |
+
Lecture Notes in Computer Science, 7782. pp. 171-182.
|
151 |
+
|
152 |
+
Examples
|
153 |
+
--------
|
154 |
+
>>> import numpy as np
|
155 |
+
>>> from scipy.linalg import sqrtm
|
156 |
+
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
|
157 |
+
>>> r = sqrtm(a)
|
158 |
+
>>> r
|
159 |
+
array([[ 0.75592895, 1.13389342],
|
160 |
+
[ 0.37796447, 1.88982237]])
|
161 |
+
>>> r.dot(r)
|
162 |
+
array([[ 1., 3.],
|
163 |
+
[ 1., 4.]])
|
164 |
+
|
165 |
+
"""
|
166 |
+
byte_size = np.asarray(A).dtype.itemsize
|
167 |
+
A = _asarray_validated(A, check_finite=True, as_inexact=True)
|
168 |
+
if len(A.shape) != 2:
|
169 |
+
raise ValueError("Non-matrix input to matrix function.")
|
170 |
+
if blocksize < 1:
|
171 |
+
raise ValueError("The blocksize should be at least 1.")
|
172 |
+
keep_it_real = np.isrealobj(A)
|
173 |
+
if keep_it_real:
|
174 |
+
T, Z = schur(A)
|
175 |
+
d0 = np.diagonal(T)
|
176 |
+
d1 = np.diagonal(T, -1)
|
177 |
+
eps = np.finfo(T.dtype).eps
|
178 |
+
needs_conversion = abs(d1) > eps * (abs(d0[1:]) + abs(d0[:-1]))
|
179 |
+
if needs_conversion.any():
|
180 |
+
T, Z = rsf2csf(T, Z)
|
181 |
+
else:
|
182 |
+
T, Z = schur(A, output='complex')
|
183 |
+
failflag = False
|
184 |
+
try:
|
185 |
+
R = _sqrtm_triu(T, blocksize=blocksize)
|
186 |
+
ZH = np.conjugate(Z).T
|
187 |
+
X = Z.dot(R).dot(ZH)
|
188 |
+
if not np.iscomplexobj(X):
|
189 |
+
# float byte size range: f2 ~ f16
|
190 |
+
X = X.astype(f"f{np.clip(byte_size, 2, 16)}", copy=False)
|
191 |
+
else:
|
192 |
+
# complex byte size range: c8 ~ c32.
|
193 |
+
# c32(complex256) might not be supported in some environments.
|
194 |
+
if hasattr(np, 'complex256'):
|
195 |
+
X = X.astype(f"c{np.clip(byte_size*2, 8, 32)}", copy=False)
|
196 |
+
else:
|
197 |
+
X = X.astype(f"c{np.clip(byte_size*2, 8, 16)}", copy=False)
|
198 |
+
except SqrtmError:
|
199 |
+
failflag = True
|
200 |
+
X = np.empty_like(A)
|
201 |
+
X.fill(np.nan)
|
202 |
+
|
203 |
+
if disp:
|
204 |
+
if failflag:
|
205 |
+
print("Failed to find a square root.")
|
206 |
+
return X
|
207 |
+
else:
|
208 |
+
try:
|
209 |
+
arg2 = norm(X.dot(X) - A, 'fro')**2 / norm(A, 'fro')
|
210 |
+
except ValueError:
|
211 |
+
# NaNs in matrix
|
212 |
+
arg2 = np.inf
|
213 |
+
|
214 |
+
return X, arg2
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_misc.py
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from numpy.linalg import LinAlgError
|
3 |
+
from .blas import get_blas_funcs
|
4 |
+
from .lapack import get_lapack_funcs
|
5 |
+
|
6 |
+
__all__ = ['LinAlgError', 'LinAlgWarning', 'norm']
|
7 |
+
|
8 |
+
|
9 |
+
class LinAlgWarning(RuntimeWarning):
|
10 |
+
"""
|
11 |
+
The warning emitted when a linear algebra related operation is close
|
12 |
+
to fail conditions of the algorithm or loss of accuracy is expected.
|
13 |
+
"""
|
14 |
+
pass
|
15 |
+
|
16 |
+
|
17 |
+
def norm(a, ord=None, axis=None, keepdims=False, check_finite=True):
|
18 |
+
"""
|
19 |
+
Matrix or vector norm.
|
20 |
+
|
21 |
+
This function is able to return one of eight different matrix norms,
|
22 |
+
or one of an infinite number of vector norms (described below), depending
|
23 |
+
on the value of the ``ord`` parameter. For tensors with rank different from
|
24 |
+
1 or 2, only `ord=None` is supported.
|
25 |
+
|
26 |
+
Parameters
|
27 |
+
----------
|
28 |
+
a : array_like
|
29 |
+
Input array. If `axis` is None, `a` must be 1-D or 2-D, unless `ord`
|
30 |
+
is None. If both `axis` and `ord` are None, the 2-norm of
|
31 |
+
``a.ravel`` will be returned.
|
32 |
+
ord : {int, inf, -inf, 'fro', 'nuc', None}, optional
|
33 |
+
Order of the norm (see table under ``Notes``). inf means NumPy's
|
34 |
+
`inf` object.
|
35 |
+
axis : {int, 2-tuple of ints, None}, optional
|
36 |
+
If `axis` is an integer, it specifies the axis of `a` along which to
|
37 |
+
compute the vector norms. If `axis` is a 2-tuple, it specifies the
|
38 |
+
axes that hold 2-D matrices, and the matrix norms of these matrices
|
39 |
+
are computed. If `axis` is None then either a vector norm (when `a`
|
40 |
+
is 1-D) or a matrix norm (when `a` is 2-D) is returned.
|
41 |
+
keepdims : bool, optional
|
42 |
+
If this is set to True, the axes which are normed over are left in the
|
43 |
+
result as dimensions with size one. With this option the result will
|
44 |
+
broadcast correctly against the original `a`.
|
45 |
+
check_finite : bool, optional
|
46 |
+
Whether to check that the input matrix contains only finite numbers.
|
47 |
+
Disabling may give a performance gain, but may result in problems
|
48 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
49 |
+
|
50 |
+
Returns
|
51 |
+
-------
|
52 |
+
n : float or ndarray
|
53 |
+
Norm of the matrix or vector(s).
|
54 |
+
|
55 |
+
Notes
|
56 |
+
-----
|
57 |
+
For values of ``ord <= 0``, the result is, strictly speaking, not a
|
58 |
+
mathematical 'norm', but it may still be useful for various numerical
|
59 |
+
purposes.
|
60 |
+
|
61 |
+
The following norms can be calculated:
|
62 |
+
|
63 |
+
===== ============================ ==========================
|
64 |
+
ord norm for matrices norm for vectors
|
65 |
+
===== ============================ ==========================
|
66 |
+
None Frobenius norm 2-norm
|
67 |
+
'fro' Frobenius norm --
|
68 |
+
'nuc' nuclear norm --
|
69 |
+
inf max(sum(abs(a), axis=1)) max(abs(a))
|
70 |
+
-inf min(sum(abs(a), axis=1)) min(abs(a))
|
71 |
+
0 -- sum(a != 0)
|
72 |
+
1 max(sum(abs(a), axis=0)) as below
|
73 |
+
-1 min(sum(abs(a), axis=0)) as below
|
74 |
+
2 2-norm (largest sing. value) as below
|
75 |
+
-2 smallest singular value as below
|
76 |
+
other -- sum(abs(a)**ord)**(1./ord)
|
77 |
+
===== ============================ ==========================
|
78 |
+
|
79 |
+
The Frobenius norm is given by [1]_:
|
80 |
+
|
81 |
+
:math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
|
82 |
+
|
83 |
+
The nuclear norm is the sum of the singular values.
|
84 |
+
|
85 |
+
Both the Frobenius and nuclear norm orders are only defined for
|
86 |
+
matrices.
|
87 |
+
|
88 |
+
References
|
89 |
+
----------
|
90 |
+
.. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
|
91 |
+
Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
|
92 |
+
|
93 |
+
Examples
|
94 |
+
--------
|
95 |
+
>>> import numpy as np
|
96 |
+
>>> from scipy.linalg import norm
|
97 |
+
>>> a = np.arange(9) - 4.0
|
98 |
+
>>> a
|
99 |
+
array([-4., -3., -2., -1., 0., 1., 2., 3., 4.])
|
100 |
+
>>> b = a.reshape((3, 3))
|
101 |
+
>>> b
|
102 |
+
array([[-4., -3., -2.],
|
103 |
+
[-1., 0., 1.],
|
104 |
+
[ 2., 3., 4.]])
|
105 |
+
|
106 |
+
>>> norm(a)
|
107 |
+
7.745966692414834
|
108 |
+
>>> norm(b)
|
109 |
+
7.745966692414834
|
110 |
+
>>> norm(b, 'fro')
|
111 |
+
7.745966692414834
|
112 |
+
>>> norm(a, np.inf)
|
113 |
+
4
|
114 |
+
>>> norm(b, np.inf)
|
115 |
+
9
|
116 |
+
>>> norm(a, -np.inf)
|
117 |
+
0
|
118 |
+
>>> norm(b, -np.inf)
|
119 |
+
2
|
120 |
+
|
121 |
+
>>> norm(a, 1)
|
122 |
+
20
|
123 |
+
>>> norm(b, 1)
|
124 |
+
7
|
125 |
+
>>> norm(a, -1)
|
126 |
+
-4.6566128774142013e-010
|
127 |
+
>>> norm(b, -1)
|
128 |
+
6
|
129 |
+
>>> norm(a, 2)
|
130 |
+
7.745966692414834
|
131 |
+
>>> norm(b, 2)
|
132 |
+
7.3484692283495345
|
133 |
+
|
134 |
+
>>> norm(a, -2)
|
135 |
+
0
|
136 |
+
>>> norm(b, -2)
|
137 |
+
1.8570331885190563e-016
|
138 |
+
>>> norm(a, 3)
|
139 |
+
5.8480354764257312
|
140 |
+
>>> norm(a, -3)
|
141 |
+
0
|
142 |
+
|
143 |
+
"""
|
144 |
+
# Differs from numpy only in non-finite handling and the use of blas.
|
145 |
+
if check_finite:
|
146 |
+
a = np.asarray_chkfinite(a)
|
147 |
+
else:
|
148 |
+
a = np.asarray(a)
|
149 |
+
|
150 |
+
if a.size and a.dtype.char in 'fdFD' and axis is None and not keepdims:
|
151 |
+
|
152 |
+
if ord in (None, 2) and (a.ndim == 1):
|
153 |
+
# use blas for fast and stable euclidean norm
|
154 |
+
nrm2 = get_blas_funcs('nrm2', dtype=a.dtype, ilp64='preferred')
|
155 |
+
return nrm2(a)
|
156 |
+
|
157 |
+
if a.ndim == 2:
|
158 |
+
# Use lapack for a couple fast matrix norms.
|
159 |
+
# For some reason the *lange frobenius norm is slow.
|
160 |
+
lange_args = None
|
161 |
+
# Make sure this works if the user uses the axis keywords
|
162 |
+
# to apply the norm to the transpose.
|
163 |
+
if ord == 1:
|
164 |
+
if np.isfortran(a):
|
165 |
+
lange_args = '1', a
|
166 |
+
elif np.isfortran(a.T):
|
167 |
+
lange_args = 'i', a.T
|
168 |
+
elif ord == np.inf:
|
169 |
+
if np.isfortran(a):
|
170 |
+
lange_args = 'i', a
|
171 |
+
elif np.isfortran(a.T):
|
172 |
+
lange_args = '1', a.T
|
173 |
+
if lange_args:
|
174 |
+
lange = get_lapack_funcs('lange', dtype=a.dtype, ilp64='preferred')
|
175 |
+
return lange(*lange_args)
|
176 |
+
|
177 |
+
# fall back to numpy in every other case
|
178 |
+
return np.linalg.norm(a, ord=ord, axis=axis, keepdims=keepdims)
|
179 |
+
|
180 |
+
|
181 |
+
def _datacopied(arr, original):
|
182 |
+
"""
|
183 |
+
Strict check for `arr` not sharing any data with `original`,
|
184 |
+
under the assumption that arr = asarray(original)
|
185 |
+
|
186 |
+
"""
|
187 |
+
if arr is original:
|
188 |
+
return False
|
189 |
+
if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
|
190 |
+
return False
|
191 |
+
return arr.base is None
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_procrustes.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Solve the orthogonal Procrustes problem.
|
3 |
+
|
4 |
+
"""
|
5 |
+
import numpy as np
|
6 |
+
from ._decomp_svd import svd
|
7 |
+
|
8 |
+
|
9 |
+
__all__ = ['orthogonal_procrustes']
|
10 |
+
|
11 |
+
|
12 |
+
def orthogonal_procrustes(A, B, check_finite=True):
|
13 |
+
"""
|
14 |
+
Compute the matrix solution of the orthogonal Procrustes problem.
|
15 |
+
|
16 |
+
Given matrices A and B of equal shape, find an orthogonal matrix R
|
17 |
+
that most closely maps A to B using the algorithm given in [1]_.
|
18 |
+
|
19 |
+
Parameters
|
20 |
+
----------
|
21 |
+
A : (M, N) array_like
|
22 |
+
Matrix to be mapped.
|
23 |
+
B : (M, N) array_like
|
24 |
+
Target matrix.
|
25 |
+
check_finite : bool, optional
|
26 |
+
Whether to check that the input matrices contain only finite numbers.
|
27 |
+
Disabling may give a performance gain, but may result in problems
|
28 |
+
(crashes, non-termination) if the inputs do contain infinities or NaNs.
|
29 |
+
|
30 |
+
Returns
|
31 |
+
-------
|
32 |
+
R : (N, N) ndarray
|
33 |
+
The matrix solution of the orthogonal Procrustes problem.
|
34 |
+
Minimizes the Frobenius norm of ``(A @ R) - B``, subject to
|
35 |
+
``R.T @ R = I``.
|
36 |
+
scale : float
|
37 |
+
Sum of the singular values of ``A.T @ B``.
|
38 |
+
|
39 |
+
Raises
|
40 |
+
------
|
41 |
+
ValueError
|
42 |
+
If the input array shapes don't match or if check_finite is True and
|
43 |
+
the arrays contain Inf or NaN.
|
44 |
+
|
45 |
+
Notes
|
46 |
+
-----
|
47 |
+
Note that unlike higher level Procrustes analyses of spatial data, this
|
48 |
+
function only uses orthogonal transformations like rotations and
|
49 |
+
reflections, and it does not use scaling or translation.
|
50 |
+
|
51 |
+
.. versionadded:: 0.15.0
|
52 |
+
|
53 |
+
References
|
54 |
+
----------
|
55 |
+
.. [1] Peter H. Schonemann, "A generalized solution of the orthogonal
|
56 |
+
Procrustes problem", Psychometrica -- Vol. 31, No. 1, March, 1966.
|
57 |
+
:doi:`10.1007/BF02289451`
|
58 |
+
|
59 |
+
Examples
|
60 |
+
--------
|
61 |
+
>>> import numpy as np
|
62 |
+
>>> from scipy.linalg import orthogonal_procrustes
|
63 |
+
>>> A = np.array([[ 2, 0, 1], [-2, 0, 0]])
|
64 |
+
|
65 |
+
Flip the order of columns and check for the anti-diagonal mapping
|
66 |
+
|
67 |
+
>>> R, sca = orthogonal_procrustes(A, np.fliplr(A))
|
68 |
+
>>> R
|
69 |
+
array([[-5.34384992e-17, 0.00000000e+00, 1.00000000e+00],
|
70 |
+
[ 0.00000000e+00, 1.00000000e+00, 0.00000000e+00],
|
71 |
+
[ 1.00000000e+00, 0.00000000e+00, -7.85941422e-17]])
|
72 |
+
>>> sca
|
73 |
+
9.0
|
74 |
+
|
75 |
+
"""
|
76 |
+
if check_finite:
|
77 |
+
A = np.asarray_chkfinite(A)
|
78 |
+
B = np.asarray_chkfinite(B)
|
79 |
+
else:
|
80 |
+
A = np.asanyarray(A)
|
81 |
+
B = np.asanyarray(B)
|
82 |
+
if A.ndim != 2:
|
83 |
+
raise ValueError('expected ndim to be 2, but observed %s' % A.ndim)
|
84 |
+
if A.shape != B.shape:
|
85 |
+
raise ValueError(f'the shapes of A and B differ ({A.shape} vs {B.shape})')
|
86 |
+
# Be clever with transposes, with the intention to save memory.
|
87 |
+
u, w, vt = svd(B.T.dot(A).T)
|
88 |
+
R = u.dot(vt)
|
89 |
+
scale = w.sum()
|
90 |
+
return R, scale
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py
ADDED
@@ -0,0 +1,1257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
from numpy.lib.stride_tricks import as_strided
|
5 |
+
|
6 |
+
__all__ = ['toeplitz', 'circulant', 'hankel',
|
7 |
+
'hadamard', 'leslie', 'kron', 'block_diag', 'companion',
|
8 |
+
'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft',
|
9 |
+
'fiedler', 'fiedler_companion', 'convolution_matrix']
|
10 |
+
|
11 |
+
|
12 |
+
# -----------------------------------------------------------------------------
|
13 |
+
# matrix construction functions
|
14 |
+
# -----------------------------------------------------------------------------
|
15 |
+
|
16 |
+
|
17 |
+
def toeplitz(c, r=None):
|
18 |
+
"""
|
19 |
+
Construct a Toeplitz matrix.
|
20 |
+
|
21 |
+
The Toeplitz matrix has constant diagonals, with c as its first column
|
22 |
+
and r as its first row. If r is not given, ``r == conjugate(c)`` is
|
23 |
+
assumed.
|
24 |
+
|
25 |
+
Parameters
|
26 |
+
----------
|
27 |
+
c : array_like
|
28 |
+
First column of the matrix. Whatever the actual shape of `c`, it
|
29 |
+
will be converted to a 1-D array.
|
30 |
+
r : array_like, optional
|
31 |
+
First row of the matrix. If None, ``r = conjugate(c)`` is assumed;
|
32 |
+
in this case, if c[0] is real, the result is a Hermitian matrix.
|
33 |
+
r[0] is ignored; the first row of the returned matrix is
|
34 |
+
``[c[0], r[1:]]``. Whatever the actual shape of `r`, it will be
|
35 |
+
converted to a 1-D array.
|
36 |
+
|
37 |
+
Returns
|
38 |
+
-------
|
39 |
+
A : (len(c), len(r)) ndarray
|
40 |
+
The Toeplitz matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.
|
41 |
+
|
42 |
+
See Also
|
43 |
+
--------
|
44 |
+
circulant : circulant matrix
|
45 |
+
hankel : Hankel matrix
|
46 |
+
solve_toeplitz : Solve a Toeplitz system.
|
47 |
+
|
48 |
+
Notes
|
49 |
+
-----
|
50 |
+
The behavior when `c` or `r` is a scalar, or when `c` is complex and
|
51 |
+
`r` is None, was changed in version 0.8.0. The behavior in previous
|
52 |
+
versions was undocumented and is no longer supported.
|
53 |
+
|
54 |
+
Examples
|
55 |
+
--------
|
56 |
+
>>> from scipy.linalg import toeplitz
|
57 |
+
>>> toeplitz([1,2,3], [1,4,5,6])
|
58 |
+
array([[1, 4, 5, 6],
|
59 |
+
[2, 1, 4, 5],
|
60 |
+
[3, 2, 1, 4]])
|
61 |
+
>>> toeplitz([1.0, 2+3j, 4-1j])
|
62 |
+
array([[ 1.+0.j, 2.-3.j, 4.+1.j],
|
63 |
+
[ 2.+3.j, 1.+0.j, 2.-3.j],
|
64 |
+
[ 4.-1.j, 2.+3.j, 1.+0.j]])
|
65 |
+
|
66 |
+
"""
|
67 |
+
c = np.asarray(c).ravel()
|
68 |
+
if r is None:
|
69 |
+
r = c.conjugate()
|
70 |
+
else:
|
71 |
+
r = np.asarray(r).ravel()
|
72 |
+
# Form a 1-D array containing a reversed c followed by r[1:] that could be
|
73 |
+
# strided to give us toeplitz matrix.
|
74 |
+
vals = np.concatenate((c[::-1], r[1:]))
|
75 |
+
out_shp = len(c), len(r)
|
76 |
+
n = vals.strides[0]
|
77 |
+
return as_strided(vals[len(c)-1:], shape=out_shp, strides=(-n, n)).copy()
|
78 |
+
|
79 |
+
|
80 |
+
def circulant(c):
|
81 |
+
"""
|
82 |
+
Construct a circulant matrix.
|
83 |
+
|
84 |
+
Parameters
|
85 |
+
----------
|
86 |
+
c : (N,) array_like
|
87 |
+
1-D array, the first column of the matrix.
|
88 |
+
|
89 |
+
Returns
|
90 |
+
-------
|
91 |
+
A : (N, N) ndarray
|
92 |
+
A circulant matrix whose first column is `c`.
|
93 |
+
|
94 |
+
See Also
|
95 |
+
--------
|
96 |
+
toeplitz : Toeplitz matrix
|
97 |
+
hankel : Hankel matrix
|
98 |
+
solve_circulant : Solve a circulant system.
|
99 |
+
|
100 |
+
Notes
|
101 |
+
-----
|
102 |
+
.. versionadded:: 0.8.0
|
103 |
+
|
104 |
+
Examples
|
105 |
+
--------
|
106 |
+
>>> from scipy.linalg import circulant
|
107 |
+
>>> circulant([1, 2, 3])
|
108 |
+
array([[1, 3, 2],
|
109 |
+
[2, 1, 3],
|
110 |
+
[3, 2, 1]])
|
111 |
+
|
112 |
+
"""
|
113 |
+
c = np.asarray(c).ravel()
|
114 |
+
# Form an extended array that could be strided to give circulant version
|
115 |
+
c_ext = np.concatenate((c[::-1], c[:0:-1]))
|
116 |
+
L = len(c)
|
117 |
+
n = c_ext.strides[0]
|
118 |
+
return as_strided(c_ext[L-1:], shape=(L, L), strides=(-n, n)).copy()
|
119 |
+
|
120 |
+
|
121 |
+
def hankel(c, r=None):
|
122 |
+
"""
|
123 |
+
Construct a Hankel matrix.
|
124 |
+
|
125 |
+
The Hankel matrix has constant anti-diagonals, with `c` as its
|
126 |
+
first column and `r` as its last row. If `r` is not given, then
|
127 |
+
`r = zeros_like(c)` is assumed.
|
128 |
+
|
129 |
+
Parameters
|
130 |
+
----------
|
131 |
+
c : array_like
|
132 |
+
First column of the matrix. Whatever the actual shape of `c`, it
|
133 |
+
will be converted to a 1-D array.
|
134 |
+
r : array_like, optional
|
135 |
+
Last row of the matrix. If None, ``r = zeros_like(c)`` is assumed.
|
136 |
+
r[0] is ignored; the last row of the returned matrix is
|
137 |
+
``[c[-1], r[1:]]``. Whatever the actual shape of `r`, it will be
|
138 |
+
converted to a 1-D array.
|
139 |
+
|
140 |
+
Returns
|
141 |
+
-------
|
142 |
+
A : (len(c), len(r)) ndarray
|
143 |
+
The Hankel matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.
|
144 |
+
|
145 |
+
See Also
|
146 |
+
--------
|
147 |
+
toeplitz : Toeplitz matrix
|
148 |
+
circulant : circulant matrix
|
149 |
+
|
150 |
+
Examples
|
151 |
+
--------
|
152 |
+
>>> from scipy.linalg import hankel
|
153 |
+
>>> hankel([1, 17, 99])
|
154 |
+
array([[ 1, 17, 99],
|
155 |
+
[17, 99, 0],
|
156 |
+
[99, 0, 0]])
|
157 |
+
>>> hankel([1,2,3,4], [4,7,7,8,9])
|
158 |
+
array([[1, 2, 3, 4, 7],
|
159 |
+
[2, 3, 4, 7, 7],
|
160 |
+
[3, 4, 7, 7, 8],
|
161 |
+
[4, 7, 7, 8, 9]])
|
162 |
+
|
163 |
+
"""
|
164 |
+
c = np.asarray(c).ravel()
|
165 |
+
if r is None:
|
166 |
+
r = np.zeros_like(c)
|
167 |
+
else:
|
168 |
+
r = np.asarray(r).ravel()
|
169 |
+
# Form a 1-D array of values to be used in the matrix, containing `c`
|
170 |
+
# followed by r[1:].
|
171 |
+
vals = np.concatenate((c, r[1:]))
|
172 |
+
# Stride on concatenated array to get hankel matrix
|
173 |
+
out_shp = len(c), len(r)
|
174 |
+
n = vals.strides[0]
|
175 |
+
return as_strided(vals, shape=out_shp, strides=(n, n)).copy()
|
176 |
+
|
177 |
+
|
178 |
+
def hadamard(n, dtype=int):
|
179 |
+
"""
|
180 |
+
Construct an Hadamard matrix.
|
181 |
+
|
182 |
+
Constructs an n-by-n Hadamard matrix, using Sylvester's
|
183 |
+
construction. `n` must be a power of 2.
|
184 |
+
|
185 |
+
Parameters
|
186 |
+
----------
|
187 |
+
n : int
|
188 |
+
The order of the matrix. `n` must be a power of 2.
|
189 |
+
dtype : dtype, optional
|
190 |
+
The data type of the array to be constructed.
|
191 |
+
|
192 |
+
Returns
|
193 |
+
-------
|
194 |
+
H : (n, n) ndarray
|
195 |
+
The Hadamard matrix.
|
196 |
+
|
197 |
+
Notes
|
198 |
+
-----
|
199 |
+
.. versionadded:: 0.8.0
|
200 |
+
|
201 |
+
Examples
|
202 |
+
--------
|
203 |
+
>>> from scipy.linalg import hadamard
|
204 |
+
>>> hadamard(2, dtype=complex)
|
205 |
+
array([[ 1.+0.j, 1.+0.j],
|
206 |
+
[ 1.+0.j, -1.-0.j]])
|
207 |
+
>>> hadamard(4)
|
208 |
+
array([[ 1, 1, 1, 1],
|
209 |
+
[ 1, -1, 1, -1],
|
210 |
+
[ 1, 1, -1, -1],
|
211 |
+
[ 1, -1, -1, 1]])
|
212 |
+
|
213 |
+
"""
|
214 |
+
|
215 |
+
# This function is a slightly modified version of the
|
216 |
+
# function contributed by Ivo in ticket #675.
|
217 |
+
|
218 |
+
if n < 1:
|
219 |
+
lg2 = 0
|
220 |
+
else:
|
221 |
+
lg2 = int(math.log(n, 2))
|
222 |
+
if 2 ** lg2 != n:
|
223 |
+
raise ValueError("n must be an positive integer, and n must be "
|
224 |
+
"a power of 2")
|
225 |
+
|
226 |
+
H = np.array([[1]], dtype=dtype)
|
227 |
+
|
228 |
+
# Sylvester's construction
|
229 |
+
for i in range(0, lg2):
|
230 |
+
H = np.vstack((np.hstack((H, H)), np.hstack((H, -H))))
|
231 |
+
|
232 |
+
return H
|
233 |
+
|
234 |
+
|
235 |
+
def leslie(f, s):
|
236 |
+
"""
|
237 |
+
Create a Leslie matrix.
|
238 |
+
|
239 |
+
Given the length n array of fecundity coefficients `f` and the length
|
240 |
+
n-1 array of survival coefficients `s`, return the associated Leslie
|
241 |
+
matrix.
|
242 |
+
|
243 |
+
Parameters
|
244 |
+
----------
|
245 |
+
f : (N,) array_like
|
246 |
+
The "fecundity" coefficients.
|
247 |
+
s : (N-1,) array_like
|
248 |
+
The "survival" coefficients, has to be 1-D. The length of `s`
|
249 |
+
must be one less than the length of `f`, and it must be at least 1.
|
250 |
+
|
251 |
+
Returns
|
252 |
+
-------
|
253 |
+
L : (N, N) ndarray
|
254 |
+
The array is zero except for the first row,
|
255 |
+
which is `f`, and the first sub-diagonal, which is `s`.
|
256 |
+
The data-type of the array will be the data-type of ``f[0]+s[0]``.
|
257 |
+
|
258 |
+
Notes
|
259 |
+
-----
|
260 |
+
.. versionadded:: 0.8.0
|
261 |
+
|
262 |
+
The Leslie matrix is used to model discrete-time, age-structured
|
263 |
+
population growth [1]_ [2]_. In a population with `n` age classes, two sets
|
264 |
+
of parameters define a Leslie matrix: the `n` "fecundity coefficients",
|
265 |
+
which give the number of offspring per-capita produced by each age
|
266 |
+
class, and the `n` - 1 "survival coefficients", which give the
|
267 |
+
per-capita survival rate of each age class.
|
268 |
+
|
269 |
+
References
|
270 |
+
----------
|
271 |
+
.. [1] P. H. Leslie, On the use of matrices in certain population
|
272 |
+
mathematics, Biometrika, Vol. 33, No. 3, 183--212 (Nov. 1945)
|
273 |
+
.. [2] P. H. Leslie, Some further notes on the use of matrices in
|
274 |
+
population mathematics, Biometrika, Vol. 35, No. 3/4, 213--245
|
275 |
+
(Dec. 1948)
|
276 |
+
|
277 |
+
Examples
|
278 |
+
--------
|
279 |
+
>>> from scipy.linalg import leslie
|
280 |
+
>>> leslie([0.1, 2.0, 1.0, 0.1], [0.2, 0.8, 0.7])
|
281 |
+
array([[ 0.1, 2. , 1. , 0.1],
|
282 |
+
[ 0.2, 0. , 0. , 0. ],
|
283 |
+
[ 0. , 0.8, 0. , 0. ],
|
284 |
+
[ 0. , 0. , 0.7, 0. ]])
|
285 |
+
|
286 |
+
"""
|
287 |
+
f = np.atleast_1d(f)
|
288 |
+
s = np.atleast_1d(s)
|
289 |
+
if f.ndim != 1:
|
290 |
+
raise ValueError("Incorrect shape for f. f must be 1D")
|
291 |
+
if s.ndim != 1:
|
292 |
+
raise ValueError("Incorrect shape for s. s must be 1D")
|
293 |
+
if f.size != s.size + 1:
|
294 |
+
raise ValueError("Incorrect lengths for f and s. The length"
|
295 |
+
" of s must be one less than the length of f.")
|
296 |
+
if s.size == 0:
|
297 |
+
raise ValueError("The length of s must be at least 1.")
|
298 |
+
|
299 |
+
tmp = f[0] + s[0]
|
300 |
+
n = f.size
|
301 |
+
a = np.zeros((n, n), dtype=tmp.dtype)
|
302 |
+
a[0] = f
|
303 |
+
a[list(range(1, n)), list(range(0, n - 1))] = s
|
304 |
+
return a
|
305 |
+
|
306 |
+
|
307 |
+
def kron(a, b):
|
308 |
+
"""
|
309 |
+
Kronecker product.
|
310 |
+
|
311 |
+
The result is the block matrix::
|
312 |
+
|
313 |
+
a[0,0]*b a[0,1]*b ... a[0,-1]*b
|
314 |
+
a[1,0]*b a[1,1]*b ... a[1,-1]*b
|
315 |
+
...
|
316 |
+
a[-1,0]*b a[-1,1]*b ... a[-1,-1]*b
|
317 |
+
|
318 |
+
Parameters
|
319 |
+
----------
|
320 |
+
a : (M, N) ndarray
|
321 |
+
Input array
|
322 |
+
b : (P, Q) ndarray
|
323 |
+
Input array
|
324 |
+
|
325 |
+
Returns
|
326 |
+
-------
|
327 |
+
A : (M*P, N*Q) ndarray
|
328 |
+
Kronecker product of `a` and `b`.
|
329 |
+
|
330 |
+
Examples
|
331 |
+
--------
|
332 |
+
>>> from numpy import array
|
333 |
+
>>> from scipy.linalg import kron
|
334 |
+
>>> kron(array([[1,2],[3,4]]), array([[1,1,1]]))
|
335 |
+
array([[1, 1, 1, 2, 2, 2],
|
336 |
+
[3, 3, 3, 4, 4, 4]])
|
337 |
+
|
338 |
+
"""
|
339 |
+
if not a.flags['CONTIGUOUS']:
|
340 |
+
a = np.reshape(a, a.shape)
|
341 |
+
if not b.flags['CONTIGUOUS']:
|
342 |
+
b = np.reshape(b, b.shape)
|
343 |
+
o = np.outer(a, b)
|
344 |
+
o = o.reshape(a.shape + b.shape)
|
345 |
+
return np.concatenate(np.concatenate(o, axis=1), axis=1)
|
346 |
+
|
347 |
+
|
348 |
+
def block_diag(*arrs):
|
349 |
+
"""
|
350 |
+
Create a block diagonal matrix from provided arrays.
|
351 |
+
|
352 |
+
Given the inputs `A`, `B` and `C`, the output will have these
|
353 |
+
arrays arranged on the diagonal::
|
354 |
+
|
355 |
+
[[A, 0, 0],
|
356 |
+
[0, B, 0],
|
357 |
+
[0, 0, C]]
|
358 |
+
|
359 |
+
Parameters
|
360 |
+
----------
|
361 |
+
A, B, C, ... : array_like, up to 2-D
|
362 |
+
Input arrays. A 1-D array or array_like sequence of length `n` is
|
363 |
+
treated as a 2-D array with shape ``(1,n)``.
|
364 |
+
|
365 |
+
Returns
|
366 |
+
-------
|
367 |
+
D : ndarray
|
368 |
+
Array with `A`, `B`, `C`, ... on the diagonal. `D` has the
|
369 |
+
same dtype as `A`.
|
370 |
+
|
371 |
+
Notes
|
372 |
+
-----
|
373 |
+
If all the input arrays are square, the output is known as a
|
374 |
+
block diagonal matrix.
|
375 |
+
|
376 |
+
Empty sequences (i.e., array-likes of zero size) will not be ignored.
|
377 |
+
Noteworthy, both [] and [[]] are treated as matrices with shape ``(1,0)``.
|
378 |
+
|
379 |
+
Examples
|
380 |
+
--------
|
381 |
+
>>> import numpy as np
|
382 |
+
>>> from scipy.linalg import block_diag
|
383 |
+
>>> A = [[1, 0],
|
384 |
+
... [0, 1]]
|
385 |
+
>>> B = [[3, 4, 5],
|
386 |
+
... [6, 7, 8]]
|
387 |
+
>>> C = [[7]]
|
388 |
+
>>> P = np.zeros((2, 0), dtype='int32')
|
389 |
+
>>> block_diag(A, B, C)
|
390 |
+
array([[1, 0, 0, 0, 0, 0],
|
391 |
+
[0, 1, 0, 0, 0, 0],
|
392 |
+
[0, 0, 3, 4, 5, 0],
|
393 |
+
[0, 0, 6, 7, 8, 0],
|
394 |
+
[0, 0, 0, 0, 0, 7]])
|
395 |
+
>>> block_diag(A, P, B, C)
|
396 |
+
array([[1, 0, 0, 0, 0, 0],
|
397 |
+
[0, 1, 0, 0, 0, 0],
|
398 |
+
[0, 0, 0, 0, 0, 0],
|
399 |
+
[0, 0, 0, 0, 0, 0],
|
400 |
+
[0, 0, 3, 4, 5, 0],
|
401 |
+
[0, 0, 6, 7, 8, 0],
|
402 |
+
[0, 0, 0, 0, 0, 7]])
|
403 |
+
>>> block_diag(1.0, [2, 3], [[4, 5], [6, 7]])
|
404 |
+
array([[ 1., 0., 0., 0., 0.],
|
405 |
+
[ 0., 2., 3., 0., 0.],
|
406 |
+
[ 0., 0., 0., 4., 5.],
|
407 |
+
[ 0., 0., 0., 6., 7.]])
|
408 |
+
|
409 |
+
"""
|
410 |
+
if arrs == ():
|
411 |
+
arrs = ([],)
|
412 |
+
arrs = [np.atleast_2d(a) for a in arrs]
|
413 |
+
|
414 |
+
bad_args = [k for k in range(len(arrs)) if arrs[k].ndim > 2]
|
415 |
+
if bad_args:
|
416 |
+
raise ValueError("arguments in the following positions have dimension "
|
417 |
+
"greater than 2: %s" % bad_args)
|
418 |
+
|
419 |
+
shapes = np.array([a.shape for a in arrs])
|
420 |
+
out_dtype = np.result_type(*[arr.dtype for arr in arrs])
|
421 |
+
out = np.zeros(np.sum(shapes, axis=0), dtype=out_dtype)
|
422 |
+
|
423 |
+
r, c = 0, 0
|
424 |
+
for i, (rr, cc) in enumerate(shapes):
|
425 |
+
out[r:r + rr, c:c + cc] = arrs[i]
|
426 |
+
r += rr
|
427 |
+
c += cc
|
428 |
+
return out
|
429 |
+
|
430 |
+
|
431 |
+
def companion(a):
|
432 |
+
"""
|
433 |
+
Create a companion matrix.
|
434 |
+
|
435 |
+
Create the companion matrix [1]_ associated with the polynomial whose
|
436 |
+
coefficients are given in `a`.
|
437 |
+
|
438 |
+
Parameters
|
439 |
+
----------
|
440 |
+
a : (N,) array_like
|
441 |
+
1-D array of polynomial coefficients. The length of `a` must be
|
442 |
+
at least two, and ``a[0]`` must not be zero.
|
443 |
+
|
444 |
+
Returns
|
445 |
+
-------
|
446 |
+
c : (N-1, N-1) ndarray
|
447 |
+
The first row of `c` is ``-a[1:]/a[0]``, and the first
|
448 |
+
sub-diagonal is all ones. The data-type of the array is the same
|
449 |
+
as the data-type of ``1.0*a[0]``.
|
450 |
+
|
451 |
+
Raises
|
452 |
+
------
|
453 |
+
ValueError
|
454 |
+
If any of the following are true: a) ``a.ndim != 1``;
|
455 |
+
b) ``a.size < 2``; c) ``a[0] == 0``.
|
456 |
+
|
457 |
+
Notes
|
458 |
+
-----
|
459 |
+
.. versionadded:: 0.8.0
|
460 |
+
|
461 |
+
References
|
462 |
+
----------
|
463 |
+
.. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*. Cambridge, UK:
|
464 |
+
Cambridge University Press, 1999, pp. 146-7.
|
465 |
+
|
466 |
+
Examples
|
467 |
+
--------
|
468 |
+
>>> from scipy.linalg import companion
|
469 |
+
>>> companion([1, -10, 31, -30])
|
470 |
+
array([[ 10., -31., 30.],
|
471 |
+
[ 1., 0., 0.],
|
472 |
+
[ 0., 1., 0.]])
|
473 |
+
|
474 |
+
"""
|
475 |
+
a = np.atleast_1d(a)
|
476 |
+
|
477 |
+
if a.ndim != 1:
|
478 |
+
raise ValueError("Incorrect shape for `a`. `a` must be "
|
479 |
+
"one-dimensional.")
|
480 |
+
|
481 |
+
if a.size < 2:
|
482 |
+
raise ValueError("The length of `a` must be at least 2.")
|
483 |
+
|
484 |
+
if a[0] == 0:
|
485 |
+
raise ValueError("The first coefficient in `a` must not be zero.")
|
486 |
+
|
487 |
+
first_row = -a[1:] / (1.0 * a[0])
|
488 |
+
n = a.size
|
489 |
+
c = np.zeros((n - 1, n - 1), dtype=first_row.dtype)
|
490 |
+
c[0] = first_row
|
491 |
+
c[list(range(1, n - 1)), list(range(0, n - 2))] = 1
|
492 |
+
return c
|
493 |
+
|
494 |
+
|
495 |
+
def helmert(n, full=False):
|
496 |
+
"""
|
497 |
+
Create an Helmert matrix of order `n`.
|
498 |
+
|
499 |
+
This has applications in statistics, compositional or simplicial analysis,
|
500 |
+
and in Aitchison geometry.
|
501 |
+
|
502 |
+
Parameters
|
503 |
+
----------
|
504 |
+
n : int
|
505 |
+
The size of the array to create.
|
506 |
+
full : bool, optional
|
507 |
+
If True the (n, n) ndarray will be returned.
|
508 |
+
Otherwise the submatrix that does not include the first
|
509 |
+
row will be returned.
|
510 |
+
Default: False.
|
511 |
+
|
512 |
+
Returns
|
513 |
+
-------
|
514 |
+
M : ndarray
|
515 |
+
The Helmert matrix.
|
516 |
+
The shape is (n, n) or (n-1, n) depending on the `full` argument.
|
517 |
+
|
518 |
+
Examples
|
519 |
+
--------
|
520 |
+
>>> from scipy.linalg import helmert
|
521 |
+
>>> helmert(5, full=True)
|
522 |
+
array([[ 0.4472136 , 0.4472136 , 0.4472136 , 0.4472136 , 0.4472136 ],
|
523 |
+
[ 0.70710678, -0.70710678, 0. , 0. , 0. ],
|
524 |
+
[ 0.40824829, 0.40824829, -0.81649658, 0. , 0. ],
|
525 |
+
[ 0.28867513, 0.28867513, 0.28867513, -0.8660254 , 0. ],
|
526 |
+
[ 0.2236068 , 0.2236068 , 0.2236068 , 0.2236068 , -0.89442719]])
|
527 |
+
|
528 |
+
"""
|
529 |
+
H = np.tril(np.ones((n, n)), -1) - np.diag(np.arange(n))
|
530 |
+
d = np.arange(n) * np.arange(1, n+1)
|
531 |
+
H[0] = 1
|
532 |
+
d[0] = n
|
533 |
+
H_full = H / np.sqrt(d)[:, np.newaxis]
|
534 |
+
if full:
|
535 |
+
return H_full
|
536 |
+
else:
|
537 |
+
return H_full[1:]
|
538 |
+
|
539 |
+
|
540 |
+
def hilbert(n):
|
541 |
+
"""
|
542 |
+
Create a Hilbert matrix of order `n`.
|
543 |
+
|
544 |
+
Returns the `n` by `n` array with entries `h[i,j] = 1 / (i + j + 1)`.
|
545 |
+
|
546 |
+
Parameters
|
547 |
+
----------
|
548 |
+
n : int
|
549 |
+
The size of the array to create.
|
550 |
+
|
551 |
+
Returns
|
552 |
+
-------
|
553 |
+
h : (n, n) ndarray
|
554 |
+
The Hilbert matrix.
|
555 |
+
|
556 |
+
See Also
|
557 |
+
--------
|
558 |
+
invhilbert : Compute the inverse of a Hilbert matrix.
|
559 |
+
|
560 |
+
Notes
|
561 |
+
-----
|
562 |
+
.. versionadded:: 0.10.0
|
563 |
+
|
564 |
+
Examples
|
565 |
+
--------
|
566 |
+
>>> from scipy.linalg import hilbert
|
567 |
+
>>> hilbert(3)
|
568 |
+
array([[ 1. , 0.5 , 0.33333333],
|
569 |
+
[ 0.5 , 0.33333333, 0.25 ],
|
570 |
+
[ 0.33333333, 0.25 , 0.2 ]])
|
571 |
+
|
572 |
+
"""
|
573 |
+
values = 1.0 / (1.0 + np.arange(2 * n - 1))
|
574 |
+
h = hankel(values[:n], r=values[n - 1:])
|
575 |
+
return h
|
576 |
+
|
577 |
+
|
578 |
+
def invhilbert(n, exact=False):
|
579 |
+
"""
|
580 |
+
Compute the inverse of the Hilbert matrix of order `n`.
|
581 |
+
|
582 |
+
The entries in the inverse of a Hilbert matrix are integers. When `n`
|
583 |
+
is greater than 14, some entries in the inverse exceed the upper limit
|
584 |
+
of 64 bit integers. The `exact` argument provides two options for
|
585 |
+
dealing with these large integers.
|
586 |
+
|
587 |
+
Parameters
|
588 |
+
----------
|
589 |
+
n : int
|
590 |
+
The order of the Hilbert matrix.
|
591 |
+
exact : bool, optional
|
592 |
+
If False, the data type of the array that is returned is np.float64,
|
593 |
+
and the array is an approximation of the inverse.
|
594 |
+
If True, the array is the exact integer inverse array. To represent
|
595 |
+
the exact inverse when n > 14, the returned array is an object array
|
596 |
+
of long integers. For n <= 14, the exact inverse is returned as an
|
597 |
+
array with data type np.int64.
|
598 |
+
|
599 |
+
Returns
|
600 |
+
-------
|
601 |
+
invh : (n, n) ndarray
|
602 |
+
The data type of the array is np.float64 if `exact` is False.
|
603 |
+
If `exact` is True, the data type is either np.int64 (for n <= 14)
|
604 |
+
or object (for n > 14). In the latter case, the objects in the
|
605 |
+
array will be long integers.
|
606 |
+
|
607 |
+
See Also
|
608 |
+
--------
|
609 |
+
hilbert : Create a Hilbert matrix.
|
610 |
+
|
611 |
+
Notes
|
612 |
+
-----
|
613 |
+
.. versionadded:: 0.10.0
|
614 |
+
|
615 |
+
Examples
|
616 |
+
--------
|
617 |
+
>>> from scipy.linalg import invhilbert
|
618 |
+
>>> invhilbert(4)
|
619 |
+
array([[ 16., -120., 240., -140.],
|
620 |
+
[ -120., 1200., -2700., 1680.],
|
621 |
+
[ 240., -2700., 6480., -4200.],
|
622 |
+
[ -140., 1680., -4200., 2800.]])
|
623 |
+
>>> invhilbert(4, exact=True)
|
624 |
+
array([[ 16, -120, 240, -140],
|
625 |
+
[ -120, 1200, -2700, 1680],
|
626 |
+
[ 240, -2700, 6480, -4200],
|
627 |
+
[ -140, 1680, -4200, 2800]], dtype=int64)
|
628 |
+
>>> invhilbert(16)[7,7]
|
629 |
+
4.2475099528537506e+19
|
630 |
+
>>> invhilbert(16, exact=True)[7,7]
|
631 |
+
42475099528537378560
|
632 |
+
|
633 |
+
"""
|
634 |
+
from scipy.special import comb
|
635 |
+
if exact:
|
636 |
+
if n > 14:
|
637 |
+
dtype = object
|
638 |
+
else:
|
639 |
+
dtype = np.int64
|
640 |
+
else:
|
641 |
+
dtype = np.float64
|
642 |
+
invh = np.empty((n, n), dtype=dtype)
|
643 |
+
for i in range(n):
|
644 |
+
for j in range(0, i + 1):
|
645 |
+
s = i + j
|
646 |
+
invh[i, j] = ((-1) ** s * (s + 1) *
|
647 |
+
comb(n + i, n - j - 1, exact=exact) *
|
648 |
+
comb(n + j, n - i - 1, exact=exact) *
|
649 |
+
comb(s, i, exact=exact) ** 2)
|
650 |
+
if i != j:
|
651 |
+
invh[j, i] = invh[i, j]
|
652 |
+
return invh
|
653 |
+
|
654 |
+
|
655 |
+
def pascal(n, kind='symmetric', exact=True):
|
656 |
+
"""
|
657 |
+
Returns the n x n Pascal matrix.
|
658 |
+
|
659 |
+
The Pascal matrix is a matrix containing the binomial coefficients as
|
660 |
+
its elements.
|
661 |
+
|
662 |
+
Parameters
|
663 |
+
----------
|
664 |
+
n : int
|
665 |
+
The size of the matrix to create; that is, the result is an n x n
|
666 |
+
matrix.
|
667 |
+
kind : str, optional
|
668 |
+
Must be one of 'symmetric', 'lower', or 'upper'.
|
669 |
+
Default is 'symmetric'.
|
670 |
+
exact : bool, optional
|
671 |
+
If `exact` is True, the result is either an array of type
|
672 |
+
numpy.uint64 (if n < 35) or an object array of Python long integers.
|
673 |
+
If `exact` is False, the coefficients in the matrix are computed using
|
674 |
+
`scipy.special.comb` with `exact=False`. The result will be a floating
|
675 |
+
point array, and the values in the array will not be the exact
|
676 |
+
coefficients, but this version is much faster than `exact=True`.
|
677 |
+
|
678 |
+
Returns
|
679 |
+
-------
|
680 |
+
p : (n, n) ndarray
|
681 |
+
The Pascal matrix.
|
682 |
+
|
683 |
+
See Also
|
684 |
+
--------
|
685 |
+
invpascal
|
686 |
+
|
687 |
+
Notes
|
688 |
+
-----
|
689 |
+
See https://en.wikipedia.org/wiki/Pascal_matrix for more information
|
690 |
+
about Pascal matrices.
|
691 |
+
|
692 |
+
.. versionadded:: 0.11.0
|
693 |
+
|
694 |
+
Examples
|
695 |
+
--------
|
696 |
+
>>> from scipy.linalg import pascal
|
697 |
+
>>> pascal(4)
|
698 |
+
array([[ 1, 1, 1, 1],
|
699 |
+
[ 1, 2, 3, 4],
|
700 |
+
[ 1, 3, 6, 10],
|
701 |
+
[ 1, 4, 10, 20]], dtype=uint64)
|
702 |
+
>>> pascal(4, kind='lower')
|
703 |
+
array([[1, 0, 0, 0],
|
704 |
+
[1, 1, 0, 0],
|
705 |
+
[1, 2, 1, 0],
|
706 |
+
[1, 3, 3, 1]], dtype=uint64)
|
707 |
+
>>> pascal(50)[-1, -1]
|
708 |
+
25477612258980856902730428600
|
709 |
+
>>> from scipy.special import comb
|
710 |
+
>>> comb(98, 49, exact=True)
|
711 |
+
25477612258980856902730428600
|
712 |
+
|
713 |
+
"""
|
714 |
+
|
715 |
+
from scipy.special import comb
|
716 |
+
if kind not in ['symmetric', 'lower', 'upper']:
|
717 |
+
raise ValueError("kind must be 'symmetric', 'lower', or 'upper'")
|
718 |
+
|
719 |
+
if exact:
|
720 |
+
if n >= 35:
|
721 |
+
L_n = np.empty((n, n), dtype=object)
|
722 |
+
L_n.fill(0)
|
723 |
+
else:
|
724 |
+
L_n = np.zeros((n, n), dtype=np.uint64)
|
725 |
+
for i in range(n):
|
726 |
+
for j in range(i + 1):
|
727 |
+
L_n[i, j] = comb(i, j, exact=True)
|
728 |
+
else:
|
729 |
+
L_n = comb(*np.ogrid[:n, :n])
|
730 |
+
|
731 |
+
if kind == 'lower':
|
732 |
+
p = L_n
|
733 |
+
elif kind == 'upper':
|
734 |
+
p = L_n.T
|
735 |
+
else:
|
736 |
+
p = np.dot(L_n, L_n.T)
|
737 |
+
|
738 |
+
return p
|
739 |
+
|
740 |
+
|
741 |
+
def invpascal(n, kind='symmetric', exact=True):
|
742 |
+
"""
|
743 |
+
Returns the inverse of the n x n Pascal matrix.
|
744 |
+
|
745 |
+
The Pascal matrix is a matrix containing the binomial coefficients as
|
746 |
+
its elements.
|
747 |
+
|
748 |
+
Parameters
|
749 |
+
----------
|
750 |
+
n : int
|
751 |
+
The size of the matrix to create; that is, the result is an n x n
|
752 |
+
matrix.
|
753 |
+
kind : str, optional
|
754 |
+
Must be one of 'symmetric', 'lower', or 'upper'.
|
755 |
+
Default is 'symmetric'.
|
756 |
+
exact : bool, optional
|
757 |
+
If `exact` is True, the result is either an array of type
|
758 |
+
``numpy.int64`` (if `n` <= 35) or an object array of Python integers.
|
759 |
+
If `exact` is False, the coefficients in the matrix are computed using
|
760 |
+
`scipy.special.comb` with `exact=False`. The result will be a floating
|
761 |
+
point array, and for large `n`, the values in the array will not be the
|
762 |
+
exact coefficients.
|
763 |
+
|
764 |
+
Returns
|
765 |
+
-------
|
766 |
+
invp : (n, n) ndarray
|
767 |
+
The inverse of the Pascal matrix.
|
768 |
+
|
769 |
+
See Also
|
770 |
+
--------
|
771 |
+
pascal
|
772 |
+
|
773 |
+
Notes
|
774 |
+
-----
|
775 |
+
|
776 |
+
.. versionadded:: 0.16.0
|
777 |
+
|
778 |
+
References
|
779 |
+
----------
|
780 |
+
.. [1] "Pascal matrix", https://en.wikipedia.org/wiki/Pascal_matrix
|
781 |
+
.. [2] Cohen, A. M., "The inverse of a Pascal matrix", Mathematical
|
782 |
+
Gazette, 59(408), pp. 111-112, 1975.
|
783 |
+
|
784 |
+
Examples
|
785 |
+
--------
|
786 |
+
>>> from scipy.linalg import invpascal, pascal
|
787 |
+
>>> invp = invpascal(5)
|
788 |
+
>>> invp
|
789 |
+
array([[ 5, -10, 10, -5, 1],
|
790 |
+
[-10, 30, -35, 19, -4],
|
791 |
+
[ 10, -35, 46, -27, 6],
|
792 |
+
[ -5, 19, -27, 17, -4],
|
793 |
+
[ 1, -4, 6, -4, 1]])
|
794 |
+
|
795 |
+
>>> p = pascal(5)
|
796 |
+
>>> p.dot(invp)
|
797 |
+
array([[ 1., 0., 0., 0., 0.],
|
798 |
+
[ 0., 1., 0., 0., 0.],
|
799 |
+
[ 0., 0., 1., 0., 0.],
|
800 |
+
[ 0., 0., 0., 1., 0.],
|
801 |
+
[ 0., 0., 0., 0., 1.]])
|
802 |
+
|
803 |
+
An example of the use of `kind` and `exact`:
|
804 |
+
|
805 |
+
>>> invpascal(5, kind='lower', exact=False)
|
806 |
+
array([[ 1., -0., 0., -0., 0.],
|
807 |
+
[-1., 1., -0., 0., -0.],
|
808 |
+
[ 1., -2., 1., -0., 0.],
|
809 |
+
[-1., 3., -3., 1., -0.],
|
810 |
+
[ 1., -4., 6., -4., 1.]])
|
811 |
+
|
812 |
+
"""
|
813 |
+
from scipy.special import comb
|
814 |
+
|
815 |
+
if kind not in ['symmetric', 'lower', 'upper']:
|
816 |
+
raise ValueError("'kind' must be 'symmetric', 'lower' or 'upper'.")
|
817 |
+
|
818 |
+
if kind == 'symmetric':
|
819 |
+
if exact:
|
820 |
+
if n > 34:
|
821 |
+
dt = object
|
822 |
+
else:
|
823 |
+
dt = np.int64
|
824 |
+
else:
|
825 |
+
dt = np.float64
|
826 |
+
invp = np.empty((n, n), dtype=dt)
|
827 |
+
for i in range(n):
|
828 |
+
for j in range(0, i + 1):
|
829 |
+
v = 0
|
830 |
+
for k in range(n - i):
|
831 |
+
v += comb(i + k, k, exact=exact) * comb(i + k, i + k - j,
|
832 |
+
exact=exact)
|
833 |
+
invp[i, j] = (-1)**(i - j) * v
|
834 |
+
if i != j:
|
835 |
+
invp[j, i] = invp[i, j]
|
836 |
+
else:
|
837 |
+
# For the 'lower' and 'upper' cases, we computer the inverse by
|
838 |
+
# changing the sign of every other diagonal of the pascal matrix.
|
839 |
+
invp = pascal(n, kind=kind, exact=exact)
|
840 |
+
if invp.dtype == np.uint64:
|
841 |
+
# This cast from np.uint64 to int64 OK, because if `kind` is not
|
842 |
+
# "symmetric", the values in invp are all much less than 2**63.
|
843 |
+
invp = invp.view(np.int64)
|
844 |
+
|
845 |
+
# The toeplitz matrix has alternating bands of 1 and -1.
|
846 |
+
invp *= toeplitz((-1)**np.arange(n)).astype(invp.dtype)
|
847 |
+
|
848 |
+
return invp
|
849 |
+
|
850 |
+
|
851 |
+
def dft(n, scale=None):
|
852 |
+
"""
|
853 |
+
Discrete Fourier transform matrix.
|
854 |
+
|
855 |
+
Create the matrix that computes the discrete Fourier transform of a
|
856 |
+
sequence [1]_. The nth primitive root of unity used to generate the
|
857 |
+
matrix is exp(-2*pi*i/n), where i = sqrt(-1).
|
858 |
+
|
859 |
+
Parameters
|
860 |
+
----------
|
861 |
+
n : int
|
862 |
+
Size the matrix to create.
|
863 |
+
scale : str, optional
|
864 |
+
Must be None, 'sqrtn', or 'n'.
|
865 |
+
If `scale` is 'sqrtn', the matrix is divided by `sqrt(n)`.
|
866 |
+
If `scale` is 'n', the matrix is divided by `n`.
|
867 |
+
If `scale` is None (the default), the matrix is not normalized, and the
|
868 |
+
return value is simply the Vandermonde matrix of the roots of unity.
|
869 |
+
|
870 |
+
Returns
|
871 |
+
-------
|
872 |
+
m : (n, n) ndarray
|
873 |
+
The DFT matrix.
|
874 |
+
|
875 |
+
Notes
|
876 |
+
-----
|
877 |
+
When `scale` is None, multiplying a vector by the matrix returned by
|
878 |
+
`dft` is mathematically equivalent to (but much less efficient than)
|
879 |
+
the calculation performed by `scipy.fft.fft`.
|
880 |
+
|
881 |
+
.. versionadded:: 0.14.0
|
882 |
+
|
883 |
+
References
|
884 |
+
----------
|
885 |
+
.. [1] "DFT matrix", https://en.wikipedia.org/wiki/DFT_matrix
|
886 |
+
|
887 |
+
Examples
|
888 |
+
--------
|
889 |
+
>>> import numpy as np
|
890 |
+
>>> from scipy.linalg import dft
|
891 |
+
>>> np.set_printoptions(precision=2, suppress=True) # for compact output
|
892 |
+
>>> m = dft(5)
|
893 |
+
>>> m
|
894 |
+
array([[ 1. +0.j , 1. +0.j , 1. +0.j , 1. +0.j , 1. +0.j ],
|
895 |
+
[ 1. +0.j , 0.31-0.95j, -0.81-0.59j, -0.81+0.59j, 0.31+0.95j],
|
896 |
+
[ 1. +0.j , -0.81-0.59j, 0.31+0.95j, 0.31-0.95j, -0.81+0.59j],
|
897 |
+
[ 1. +0.j , -0.81+0.59j, 0.31-0.95j, 0.31+0.95j, -0.81-0.59j],
|
898 |
+
[ 1. +0.j , 0.31+0.95j, -0.81+0.59j, -0.81-0.59j, 0.31-0.95j]])
|
899 |
+
>>> x = np.array([1, 2, 3, 0, 3])
|
900 |
+
>>> m @ x # Compute the DFT of x
|
901 |
+
array([ 9. +0.j , 0.12-0.81j, -2.12+3.44j, -2.12-3.44j, 0.12+0.81j])
|
902 |
+
|
903 |
+
Verify that ``m @ x`` is the same as ``fft(x)``.
|
904 |
+
|
905 |
+
>>> from scipy.fft import fft
|
906 |
+
>>> fft(x) # Same result as m @ x
|
907 |
+
array([ 9. +0.j , 0.12-0.81j, -2.12+3.44j, -2.12-3.44j, 0.12+0.81j])
|
908 |
+
"""
|
909 |
+
if scale not in [None, 'sqrtn', 'n']:
|
910 |
+
raise ValueError("scale must be None, 'sqrtn', or 'n'; "
|
911 |
+
f"{scale!r} is not valid.")
|
912 |
+
|
913 |
+
omegas = np.exp(-2j * np.pi * np.arange(n) / n).reshape(-1, 1)
|
914 |
+
m = omegas ** np.arange(n)
|
915 |
+
if scale == 'sqrtn':
|
916 |
+
m /= math.sqrt(n)
|
917 |
+
elif scale == 'n':
|
918 |
+
m /= n
|
919 |
+
return m
|
920 |
+
|
921 |
+
|
922 |
+
def fiedler(a):
|
923 |
+
"""Returns a symmetric Fiedler matrix
|
924 |
+
|
925 |
+
Given an sequence of numbers `a`, Fiedler matrices have the structure
|
926 |
+
``F[i, j] = np.abs(a[i] - a[j])``, and hence zero diagonals and nonnegative
|
927 |
+
entries. A Fiedler matrix has a dominant positive eigenvalue and other
|
928 |
+
eigenvalues are negative. Although not valid generally, for certain inputs,
|
929 |
+
the inverse and the determinant can be derived explicitly as given in [1]_.
|
930 |
+
|
931 |
+
Parameters
|
932 |
+
----------
|
933 |
+
a : (n,) array_like
|
934 |
+
coefficient array
|
935 |
+
|
936 |
+
Returns
|
937 |
+
-------
|
938 |
+
F : (n, n) ndarray
|
939 |
+
|
940 |
+
See Also
|
941 |
+
--------
|
942 |
+
circulant, toeplitz
|
943 |
+
|
944 |
+
Notes
|
945 |
+
-----
|
946 |
+
|
947 |
+
.. versionadded:: 1.3.0
|
948 |
+
|
949 |
+
References
|
950 |
+
----------
|
951 |
+
.. [1] J. Todd, "Basic Numerical Mathematics: Vol.2 : Numerical Algebra",
|
952 |
+
1977, Birkhauser, :doi:`10.1007/978-3-0348-7286-7`
|
953 |
+
|
954 |
+
Examples
|
955 |
+
--------
|
956 |
+
>>> import numpy as np
|
957 |
+
>>> from scipy.linalg import det, inv, fiedler
|
958 |
+
>>> a = [1, 4, 12, 45, 77]
|
959 |
+
>>> n = len(a)
|
960 |
+
>>> A = fiedler(a)
|
961 |
+
>>> A
|
962 |
+
array([[ 0, 3, 11, 44, 76],
|
963 |
+
[ 3, 0, 8, 41, 73],
|
964 |
+
[11, 8, 0, 33, 65],
|
965 |
+
[44, 41, 33, 0, 32],
|
966 |
+
[76, 73, 65, 32, 0]])
|
967 |
+
|
968 |
+
The explicit formulas for determinant and inverse seem to hold only for
|
969 |
+
monotonically increasing/decreasing arrays. Note the tridiagonal structure
|
970 |
+
and the corners.
|
971 |
+
|
972 |
+
>>> Ai = inv(A)
|
973 |
+
>>> Ai[np.abs(Ai) < 1e-12] = 0. # cleanup the numerical noise for display
|
974 |
+
>>> Ai
|
975 |
+
array([[-0.16008772, 0.16666667, 0. , 0. , 0.00657895],
|
976 |
+
[ 0.16666667, -0.22916667, 0.0625 , 0. , 0. ],
|
977 |
+
[ 0. , 0.0625 , -0.07765152, 0.01515152, 0. ],
|
978 |
+
[ 0. , 0. , 0.01515152, -0.03077652, 0.015625 ],
|
979 |
+
[ 0.00657895, 0. , 0. , 0.015625 , -0.00904605]])
|
980 |
+
>>> det(A)
|
981 |
+
15409151.999999998
|
982 |
+
>>> (-1)**(n-1) * 2**(n-2) * np.diff(a).prod() * (a[-1] - a[0])
|
983 |
+
15409152
|
984 |
+
|
985 |
+
"""
|
986 |
+
a = np.atleast_1d(a)
|
987 |
+
|
988 |
+
if a.ndim != 1:
|
989 |
+
raise ValueError("Input 'a' must be a 1D array.")
|
990 |
+
|
991 |
+
if a.size == 0:
|
992 |
+
return np.array([], dtype=float)
|
993 |
+
elif a.size == 1:
|
994 |
+
return np.array([[0.]])
|
995 |
+
else:
|
996 |
+
return np.abs(a[:, None] - a)
|
997 |
+
|
998 |
+
|
999 |
+
def fiedler_companion(a):
|
1000 |
+
""" Returns a Fiedler companion matrix
|
1001 |
+
|
1002 |
+
Given a polynomial coefficient array ``a``, this function forms a
|
1003 |
+
pentadiagonal matrix with a special structure whose eigenvalues coincides
|
1004 |
+
with the roots of ``a``.
|
1005 |
+
|
1006 |
+
Parameters
|
1007 |
+
----------
|
1008 |
+
a : (N,) array_like
|
1009 |
+
1-D array of polynomial coefficients in descending order with a nonzero
|
1010 |
+
leading coefficient. For ``N < 2``, an empty array is returned.
|
1011 |
+
|
1012 |
+
Returns
|
1013 |
+
-------
|
1014 |
+
c : (N-1, N-1) ndarray
|
1015 |
+
Resulting companion matrix
|
1016 |
+
|
1017 |
+
See Also
|
1018 |
+
--------
|
1019 |
+
companion
|
1020 |
+
|
1021 |
+
Notes
|
1022 |
+
-----
|
1023 |
+
Similar to `companion` the leading coefficient should be nonzero. In the case
|
1024 |
+
the leading coefficient is not 1, other coefficients are rescaled before
|
1025 |
+
the array generation. To avoid numerical issues, it is best to provide a
|
1026 |
+
monic polynomial.
|
1027 |
+
|
1028 |
+
.. versionadded:: 1.3.0
|
1029 |
+
|
1030 |
+
References
|
1031 |
+
----------
|
1032 |
+
.. [1] M. Fiedler, " A note on companion matrices", Linear Algebra and its
|
1033 |
+
Applications, 2003, :doi:`10.1016/S0024-3795(03)00548-2`
|
1034 |
+
|
1035 |
+
Examples
|
1036 |
+
--------
|
1037 |
+
>>> import numpy as np
|
1038 |
+
>>> from scipy.linalg import fiedler_companion, eigvals
|
1039 |
+
>>> p = np.poly(np.arange(1, 9, 2)) # [1., -16., 86., -176., 105.]
|
1040 |
+
>>> fc = fiedler_companion(p)
|
1041 |
+
>>> fc
|
1042 |
+
array([[ 16., -86., 1., 0.],
|
1043 |
+
[ 1., 0., 0., 0.],
|
1044 |
+
[ 0., 176., 0., -105.],
|
1045 |
+
[ 0., 1., 0., 0.]])
|
1046 |
+
>>> eigvals(fc)
|
1047 |
+
array([7.+0.j, 5.+0.j, 3.+0.j, 1.+0.j])
|
1048 |
+
|
1049 |
+
"""
|
1050 |
+
a = np.atleast_1d(a)
|
1051 |
+
|
1052 |
+
if a.ndim != 1:
|
1053 |
+
raise ValueError("Input 'a' must be a 1-D array.")
|
1054 |
+
|
1055 |
+
if a.size <= 2:
|
1056 |
+
if a.size == 2:
|
1057 |
+
return np.array([[-(a/a[0])[-1]]])
|
1058 |
+
return np.array([], dtype=a.dtype)
|
1059 |
+
|
1060 |
+
if a[0] == 0.:
|
1061 |
+
raise ValueError('Leading coefficient is zero.')
|
1062 |
+
|
1063 |
+
a = a/a[0]
|
1064 |
+
n = a.size - 1
|
1065 |
+
c = np.zeros((n, n), dtype=a.dtype)
|
1066 |
+
# subdiagonals
|
1067 |
+
c[range(3, n, 2), range(1, n-2, 2)] = 1.
|
1068 |
+
c[range(2, n, 2), range(1, n-1, 2)] = -a[3::2]
|
1069 |
+
# superdiagonals
|
1070 |
+
c[range(0, n-2, 2), range(2, n, 2)] = 1.
|
1071 |
+
c[range(0, n-1, 2), range(1, n, 2)] = -a[2::2]
|
1072 |
+
c[[0, 1], 0] = [-a[1], 1]
|
1073 |
+
|
1074 |
+
return c
|
1075 |
+
|
1076 |
+
|
1077 |
+
def convolution_matrix(a, n, mode='full'):
|
1078 |
+
"""
|
1079 |
+
Construct a convolution matrix.
|
1080 |
+
|
1081 |
+
Constructs the Toeplitz matrix representing one-dimensional
|
1082 |
+
convolution [1]_. See the notes below for details.
|
1083 |
+
|
1084 |
+
Parameters
|
1085 |
+
----------
|
1086 |
+
a : (m,) array_like
|
1087 |
+
The 1-D array to convolve.
|
1088 |
+
n : int
|
1089 |
+
The number of columns in the resulting matrix. It gives the length
|
1090 |
+
of the input to be convolved with `a`. This is analogous to the
|
1091 |
+
length of `v` in ``numpy.convolve(a, v)``.
|
1092 |
+
mode : str
|
1093 |
+
This is analogous to `mode` in ``numpy.convolve(v, a, mode)``.
|
1094 |
+
It must be one of ('full', 'valid', 'same').
|
1095 |
+
See below for how `mode` determines the shape of the result.
|
1096 |
+
|
1097 |
+
Returns
|
1098 |
+
-------
|
1099 |
+
A : (k, n) ndarray
|
1100 |
+
The convolution matrix whose row count `k` depends on `mode`::
|
1101 |
+
|
1102 |
+
======= =========================
|
1103 |
+
mode k
|
1104 |
+
======= =========================
|
1105 |
+
'full' m + n -1
|
1106 |
+
'same' max(m, n)
|
1107 |
+
'valid' max(m, n) - min(m, n) + 1
|
1108 |
+
======= =========================
|
1109 |
+
|
1110 |
+
See Also
|
1111 |
+
--------
|
1112 |
+
toeplitz : Toeplitz matrix
|
1113 |
+
|
1114 |
+
Notes
|
1115 |
+
-----
|
1116 |
+
The code::
|
1117 |
+
|
1118 |
+
A = convolution_matrix(a, n, mode)
|
1119 |
+
|
1120 |
+
creates a Toeplitz matrix `A` such that ``A @ v`` is equivalent to
|
1121 |
+
using ``convolve(a, v, mode)``. The returned array always has `n`
|
1122 |
+
columns. The number of rows depends on the specified `mode`, as
|
1123 |
+
explained above.
|
1124 |
+
|
1125 |
+
In the default 'full' mode, the entries of `A` are given by::
|
1126 |
+
|
1127 |
+
A[i, j] == (a[i-j] if (0 <= (i-j) < m) else 0)
|
1128 |
+
|
1129 |
+
where ``m = len(a)``. Suppose, for example, the input array is
|
1130 |
+
``[x, y, z]``. The convolution matrix has the form::
|
1131 |
+
|
1132 |
+
[x, 0, 0, ..., 0, 0]
|
1133 |
+
[y, x, 0, ..., 0, 0]
|
1134 |
+
[z, y, x, ..., 0, 0]
|
1135 |
+
...
|
1136 |
+
[0, 0, 0, ..., x, 0]
|
1137 |
+
[0, 0, 0, ..., y, x]
|
1138 |
+
[0, 0, 0, ..., z, y]
|
1139 |
+
[0, 0, 0, ..., 0, z]
|
1140 |
+
|
1141 |
+
In 'valid' mode, the entries of `A` are given by::
|
1142 |
+
|
1143 |
+
A[i, j] == (a[i-j+m-1] if (0 <= (i-j+m-1) < m) else 0)
|
1144 |
+
|
1145 |
+
This corresponds to a matrix whose rows are the subset of those from
|
1146 |
+
the 'full' case where all the coefficients in `a` are contained in the
|
1147 |
+
row. For input ``[x, y, z]``, this array looks like::
|
1148 |
+
|
1149 |
+
[z, y, x, 0, 0, ..., 0, 0, 0]
|
1150 |
+
[0, z, y, x, 0, ..., 0, 0, 0]
|
1151 |
+
[0, 0, z, y, x, ..., 0, 0, 0]
|
1152 |
+
...
|
1153 |
+
[0, 0, 0, 0, 0, ..., x, 0, 0]
|
1154 |
+
[0, 0, 0, 0, 0, ..., y, x, 0]
|
1155 |
+
[0, 0, 0, 0, 0, ..., z, y, x]
|
1156 |
+
|
1157 |
+
In the 'same' mode, the entries of `A` are given by::
|
1158 |
+
|
1159 |
+
d = (m - 1) // 2
|
1160 |
+
A[i, j] == (a[i-j+d] if (0 <= (i-j+d) < m) else 0)
|
1161 |
+
|
1162 |
+
The typical application of the 'same' mode is when one has a signal of
|
1163 |
+
length `n` (with `n` greater than ``len(a)``), and the desired output
|
1164 |
+
is a filtered signal that is still of length `n`.
|
1165 |
+
|
1166 |
+
For input ``[x, y, z]``, this array looks like::
|
1167 |
+
|
1168 |
+
[y, x, 0, 0, ..., 0, 0, 0]
|
1169 |
+
[z, y, x, 0, ..., 0, 0, 0]
|
1170 |
+
[0, z, y, x, ..., 0, 0, 0]
|
1171 |
+
[0, 0, z, y, ..., 0, 0, 0]
|
1172 |
+
...
|
1173 |
+
[0, 0, 0, 0, ..., y, x, 0]
|
1174 |
+
[0, 0, 0, 0, ..., z, y, x]
|
1175 |
+
[0, 0, 0, 0, ..., 0, z, y]
|
1176 |
+
|
1177 |
+
.. versionadded:: 1.5.0
|
1178 |
+
|
1179 |
+
References
|
1180 |
+
----------
|
1181 |
+
.. [1] "Convolution", https://en.wikipedia.org/wiki/Convolution
|
1182 |
+
|
1183 |
+
Examples
|
1184 |
+
--------
|
1185 |
+
>>> import numpy as np
|
1186 |
+
>>> from scipy.linalg import convolution_matrix
|
1187 |
+
>>> A = convolution_matrix([-1, 4, -2], 5, mode='same')
|
1188 |
+
>>> A
|
1189 |
+
array([[ 4, -1, 0, 0, 0],
|
1190 |
+
[-2, 4, -1, 0, 0],
|
1191 |
+
[ 0, -2, 4, -1, 0],
|
1192 |
+
[ 0, 0, -2, 4, -1],
|
1193 |
+
[ 0, 0, 0, -2, 4]])
|
1194 |
+
|
1195 |
+
Compare multiplication by `A` with the use of `numpy.convolve`.
|
1196 |
+
|
1197 |
+
>>> x = np.array([1, 2, 0, -3, 0.5])
|
1198 |
+
>>> A @ x
|
1199 |
+
array([ 2. , 6. , -1. , -12.5, 8. ])
|
1200 |
+
|
1201 |
+
Verify that ``A @ x`` produced the same result as applying the
|
1202 |
+
convolution function.
|
1203 |
+
|
1204 |
+
>>> np.convolve([-1, 4, -2], x, mode='same')
|
1205 |
+
array([ 2. , 6. , -1. , -12.5, 8. ])
|
1206 |
+
|
1207 |
+
For comparison to the case ``mode='same'`` shown above, here are the
|
1208 |
+
matrices produced by ``mode='full'`` and ``mode='valid'`` for the
|
1209 |
+
same coefficients and size.
|
1210 |
+
|
1211 |
+
>>> convolution_matrix([-1, 4, -2], 5, mode='full')
|
1212 |
+
array([[-1, 0, 0, 0, 0],
|
1213 |
+
[ 4, -1, 0, 0, 0],
|
1214 |
+
[-2, 4, -1, 0, 0],
|
1215 |
+
[ 0, -2, 4, -1, 0],
|
1216 |
+
[ 0, 0, -2, 4, -1],
|
1217 |
+
[ 0, 0, 0, -2, 4],
|
1218 |
+
[ 0, 0, 0, 0, -2]])
|
1219 |
+
|
1220 |
+
>>> convolution_matrix([-1, 4, -2], 5, mode='valid')
|
1221 |
+
array([[-2, 4, -1, 0, 0],
|
1222 |
+
[ 0, -2, 4, -1, 0],
|
1223 |
+
[ 0, 0, -2, 4, -1]])
|
1224 |
+
"""
|
1225 |
+
if n <= 0:
|
1226 |
+
raise ValueError('n must be a positive integer.')
|
1227 |
+
|
1228 |
+
a = np.asarray(a)
|
1229 |
+
if a.ndim != 1:
|
1230 |
+
raise ValueError('convolution_matrix expects a one-dimensional '
|
1231 |
+
'array as input')
|
1232 |
+
if a.size == 0:
|
1233 |
+
raise ValueError('len(a) must be at least 1.')
|
1234 |
+
|
1235 |
+
if mode not in ('full', 'valid', 'same'):
|
1236 |
+
raise ValueError(
|
1237 |
+
"'mode' argument must be one of ('full', 'valid', 'same')")
|
1238 |
+
|
1239 |
+
# create zero padded versions of the array
|
1240 |
+
az = np.pad(a, (0, n-1), 'constant')
|
1241 |
+
raz = np.pad(a[::-1], (0, n-1), 'constant')
|
1242 |
+
|
1243 |
+
if mode == 'same':
|
1244 |
+
trim = min(n, len(a)) - 1
|
1245 |
+
tb = trim//2
|
1246 |
+
te = trim - tb
|
1247 |
+
col0 = az[tb:len(az)-te]
|
1248 |
+
row0 = raz[-n-tb:len(raz)-tb]
|
1249 |
+
elif mode == 'valid':
|
1250 |
+
tb = min(n, len(a)) - 1
|
1251 |
+
te = tb
|
1252 |
+
col0 = az[tb:len(az)-te]
|
1253 |
+
row0 = raz[-n-tb:len(raz)-tb]
|
1254 |
+
else: # 'full'
|
1255 |
+
col0 = az
|
1256 |
+
row0 = raz[-n:]
|
1257 |
+
return toeplitz(col0, row0)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/basic.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
2 |
+
# Use the `scipy.linalg` namespace for importing the functions
|
3 |
+
# included below.
|
4 |
+
|
5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
6 |
+
|
7 |
+
|
8 |
+
__all__ = [ # noqa: F822
|
9 |
+
'solve', 'solve_triangular', 'solveh_banded', 'solve_banded',
|
10 |
+
'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq',
|
11 |
+
'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz',
|
12 |
+
'atleast_1d', 'atleast_2d', 'get_lapack_funcs',
|
13 |
+
'LinAlgError', 'LinAlgWarning', 'levinson',
|
14 |
+
]
|
15 |
+
|
16 |
+
|
17 |
+
def __dir__():
|
18 |
+
return __all__
|
19 |
+
|
20 |
+
|
21 |
+
def __getattr__(name):
|
22 |
+
return _sub_module_deprecation(sub_package="linalg", module="basic",
|
23 |
+
private_modules=["_basic"], all=__all__,
|
24 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/blas.py
ADDED
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Low-level BLAS functions (:mod:`scipy.linalg.blas`)
|
3 |
+
===================================================
|
4 |
+
|
5 |
+
This module contains low-level functions from the BLAS library.
|
6 |
+
|
7 |
+
.. versionadded:: 0.12.0
|
8 |
+
|
9 |
+
.. note::
|
10 |
+
|
11 |
+
The common ``overwrite_<>`` option in many routines, allows the
|
12 |
+
input arrays to be overwritten to avoid extra memory allocation.
|
13 |
+
However this requires the array to satisfy two conditions
|
14 |
+
which are memory order and the data type to match exactly the
|
15 |
+
order and the type expected by the routine.
|
16 |
+
|
17 |
+
As an example, if you pass a double precision float array to any
|
18 |
+
``S....`` routine which expects single precision arguments, f2py
|
19 |
+
will create an intermediate array to match the argument types and
|
20 |
+
overwriting will be performed on that intermediate array.
|
21 |
+
|
22 |
+
Similarly, if a C-contiguous array is passed, f2py will pass a
|
23 |
+
FORTRAN-contiguous array internally. Please make sure that these
|
24 |
+
details are satisfied. More information can be found in the f2py
|
25 |
+
documentation.
|
26 |
+
|
27 |
+
.. warning::
|
28 |
+
|
29 |
+
These functions do little to no error checking.
|
30 |
+
It is possible to cause crashes by mis-using them,
|
31 |
+
so prefer using the higher-level routines in `scipy.linalg`.
|
32 |
+
|
33 |
+
Finding functions
|
34 |
+
-----------------
|
35 |
+
|
36 |
+
.. autosummary::
|
37 |
+
:toctree: generated/
|
38 |
+
|
39 |
+
get_blas_funcs
|
40 |
+
find_best_blas_type
|
41 |
+
|
42 |
+
BLAS Level 1 functions
|
43 |
+
----------------------
|
44 |
+
|
45 |
+
.. autosummary::
|
46 |
+
:toctree: generated/
|
47 |
+
|
48 |
+
caxpy
|
49 |
+
ccopy
|
50 |
+
cdotc
|
51 |
+
cdotu
|
52 |
+
crotg
|
53 |
+
cscal
|
54 |
+
csrot
|
55 |
+
csscal
|
56 |
+
cswap
|
57 |
+
dasum
|
58 |
+
daxpy
|
59 |
+
dcopy
|
60 |
+
ddot
|
61 |
+
dnrm2
|
62 |
+
drot
|
63 |
+
drotg
|
64 |
+
drotm
|
65 |
+
drotmg
|
66 |
+
dscal
|
67 |
+
dswap
|
68 |
+
dzasum
|
69 |
+
dznrm2
|
70 |
+
icamax
|
71 |
+
idamax
|
72 |
+
isamax
|
73 |
+
izamax
|
74 |
+
sasum
|
75 |
+
saxpy
|
76 |
+
scasum
|
77 |
+
scnrm2
|
78 |
+
scopy
|
79 |
+
sdot
|
80 |
+
snrm2
|
81 |
+
srot
|
82 |
+
srotg
|
83 |
+
srotm
|
84 |
+
srotmg
|
85 |
+
sscal
|
86 |
+
sswap
|
87 |
+
zaxpy
|
88 |
+
zcopy
|
89 |
+
zdotc
|
90 |
+
zdotu
|
91 |
+
zdrot
|
92 |
+
zdscal
|
93 |
+
zrotg
|
94 |
+
zscal
|
95 |
+
zswap
|
96 |
+
|
97 |
+
BLAS Level 2 functions
|
98 |
+
----------------------
|
99 |
+
|
100 |
+
.. autosummary::
|
101 |
+
:toctree: generated/
|
102 |
+
|
103 |
+
sgbmv
|
104 |
+
sgemv
|
105 |
+
sger
|
106 |
+
ssbmv
|
107 |
+
sspr
|
108 |
+
sspr2
|
109 |
+
ssymv
|
110 |
+
ssyr
|
111 |
+
ssyr2
|
112 |
+
stbmv
|
113 |
+
stpsv
|
114 |
+
strmv
|
115 |
+
strsv
|
116 |
+
dgbmv
|
117 |
+
dgemv
|
118 |
+
dger
|
119 |
+
dsbmv
|
120 |
+
dspr
|
121 |
+
dspr2
|
122 |
+
dsymv
|
123 |
+
dsyr
|
124 |
+
dsyr2
|
125 |
+
dtbmv
|
126 |
+
dtpsv
|
127 |
+
dtrmv
|
128 |
+
dtrsv
|
129 |
+
cgbmv
|
130 |
+
cgemv
|
131 |
+
cgerc
|
132 |
+
cgeru
|
133 |
+
chbmv
|
134 |
+
chemv
|
135 |
+
cher
|
136 |
+
cher2
|
137 |
+
chpmv
|
138 |
+
chpr
|
139 |
+
chpr2
|
140 |
+
ctbmv
|
141 |
+
ctbsv
|
142 |
+
ctpmv
|
143 |
+
ctpsv
|
144 |
+
ctrmv
|
145 |
+
ctrsv
|
146 |
+
csyr
|
147 |
+
zgbmv
|
148 |
+
zgemv
|
149 |
+
zgerc
|
150 |
+
zgeru
|
151 |
+
zhbmv
|
152 |
+
zhemv
|
153 |
+
zher
|
154 |
+
zher2
|
155 |
+
zhpmv
|
156 |
+
zhpr
|
157 |
+
zhpr2
|
158 |
+
ztbmv
|
159 |
+
ztbsv
|
160 |
+
ztpmv
|
161 |
+
ztrmv
|
162 |
+
ztrsv
|
163 |
+
zsyr
|
164 |
+
|
165 |
+
BLAS Level 3 functions
|
166 |
+
----------------------
|
167 |
+
|
168 |
+
.. autosummary::
|
169 |
+
:toctree: generated/
|
170 |
+
|
171 |
+
sgemm
|
172 |
+
ssymm
|
173 |
+
ssyr2k
|
174 |
+
ssyrk
|
175 |
+
strmm
|
176 |
+
strsm
|
177 |
+
dgemm
|
178 |
+
dsymm
|
179 |
+
dsyr2k
|
180 |
+
dsyrk
|
181 |
+
dtrmm
|
182 |
+
dtrsm
|
183 |
+
cgemm
|
184 |
+
chemm
|
185 |
+
cher2k
|
186 |
+
cherk
|
187 |
+
csymm
|
188 |
+
csyr2k
|
189 |
+
csyrk
|
190 |
+
ctrmm
|
191 |
+
ctrsm
|
192 |
+
zgemm
|
193 |
+
zhemm
|
194 |
+
zher2k
|
195 |
+
zherk
|
196 |
+
zsymm
|
197 |
+
zsyr2k
|
198 |
+
zsyrk
|
199 |
+
ztrmm
|
200 |
+
ztrsm
|
201 |
+
|
202 |
+
"""
|
203 |
+
#
|
204 |
+
# Author: Pearu Peterson, March 2002
|
205 |
+
# refactoring by Fabian Pedregosa, March 2010
|
206 |
+
#
|
207 |
+
|
208 |
+
__all__ = ['get_blas_funcs', 'find_best_blas_type']
|
209 |
+
|
210 |
+
import numpy as _np
|
211 |
+
import functools
|
212 |
+
|
213 |
+
from scipy.linalg import _fblas
|
214 |
+
try:
|
215 |
+
from scipy.linalg import _cblas
|
216 |
+
except ImportError:
|
217 |
+
_cblas = None
|
218 |
+
|
219 |
+
try:
|
220 |
+
from scipy.linalg import _fblas_64
|
221 |
+
HAS_ILP64 = True
|
222 |
+
except ImportError:
|
223 |
+
HAS_ILP64 = False
|
224 |
+
_fblas_64 = None
|
225 |
+
|
226 |
+
# Expose all functions (only fblas --- cblas is an implementation detail)
|
227 |
+
empty_module = None
|
228 |
+
from scipy.linalg._fblas import * # noqa: E402, F403
|
229 |
+
del empty_module
|
230 |
+
|
231 |
+
# all numeric dtypes '?bBhHiIlLqQefdgFDGO' that are safe to be converted to
|
232 |
+
|
233 |
+
# single precision float : '?bBhH!!!!!!ef!!!!!!'
|
234 |
+
# double precision float : '?bBhHiIlLqQefdg!!!!'
|
235 |
+
# single precision complex : '?bBhH!!!!!!ef!!F!!!'
|
236 |
+
# double precision complex : '?bBhHiIlLqQefdgFDG!'
|
237 |
+
|
238 |
+
_type_score = {x: 1 for x in '?bBhHef'}
|
239 |
+
_type_score.update({x: 2 for x in 'iIlLqQd'})
|
240 |
+
|
241 |
+
# Handle float128(g) and complex256(G) separately in case non-Windows systems.
|
242 |
+
# On Windows, the values will be rewritten to the same key with the same value.
|
243 |
+
_type_score.update({'F': 3, 'D': 4, 'g': 2, 'G': 4})
|
244 |
+
|
245 |
+
# Final mapping to the actual prefixes and dtypes
|
246 |
+
_type_conv = {1: ('s', _np.dtype('float32')),
|
247 |
+
2: ('d', _np.dtype('float64')),
|
248 |
+
3: ('c', _np.dtype('complex64')),
|
249 |
+
4: ('z', _np.dtype('complex128'))}
|
250 |
+
|
251 |
+
# some convenience alias for complex functions
|
252 |
+
_blas_alias = {'cnrm2': 'scnrm2', 'znrm2': 'dznrm2',
|
253 |
+
'cdot': 'cdotc', 'zdot': 'zdotc',
|
254 |
+
'cger': 'cgerc', 'zger': 'zgerc',
|
255 |
+
'sdotc': 'sdot', 'sdotu': 'sdot',
|
256 |
+
'ddotc': 'ddot', 'ddotu': 'ddot'}
|
257 |
+
|
258 |
+
|
259 |
+
def find_best_blas_type(arrays=(), dtype=None):
|
260 |
+
"""Find best-matching BLAS/LAPACK type.
|
261 |
+
|
262 |
+
Arrays are used to determine the optimal prefix of BLAS routines.
|
263 |
+
|
264 |
+
Parameters
|
265 |
+
----------
|
266 |
+
arrays : sequence of ndarrays, optional
|
267 |
+
Arrays can be given to determine optimal prefix of BLAS
|
268 |
+
routines. If not given, double-precision routines will be
|
269 |
+
used, otherwise the most generic type in arrays will be used.
|
270 |
+
dtype : str or dtype, optional
|
271 |
+
Data-type specifier. Not used if `arrays` is non-empty.
|
272 |
+
|
273 |
+
Returns
|
274 |
+
-------
|
275 |
+
prefix : str
|
276 |
+
BLAS/LAPACK prefix character.
|
277 |
+
dtype : dtype
|
278 |
+
Inferred Numpy data type.
|
279 |
+
prefer_fortran : bool
|
280 |
+
Whether to prefer Fortran order routines over C order.
|
281 |
+
|
282 |
+
Examples
|
283 |
+
--------
|
284 |
+
>>> import numpy as np
|
285 |
+
>>> import scipy.linalg.blas as bla
|
286 |
+
>>> rng = np.random.default_rng()
|
287 |
+
>>> a = rng.random((10,15))
|
288 |
+
>>> b = np.asfortranarray(a) # Change the memory layout order
|
289 |
+
>>> bla.find_best_blas_type((a,))
|
290 |
+
('d', dtype('float64'), False)
|
291 |
+
>>> bla.find_best_blas_type((a*1j,))
|
292 |
+
('z', dtype('complex128'), False)
|
293 |
+
>>> bla.find_best_blas_type((b,))
|
294 |
+
('d', dtype('float64'), True)
|
295 |
+
|
296 |
+
"""
|
297 |
+
dtype = _np.dtype(dtype)
|
298 |
+
max_score = _type_score.get(dtype.char, 5)
|
299 |
+
prefer_fortran = False
|
300 |
+
|
301 |
+
if arrays:
|
302 |
+
# In most cases, single element is passed through, quicker route
|
303 |
+
if len(arrays) == 1:
|
304 |
+
max_score = _type_score.get(arrays[0].dtype.char, 5)
|
305 |
+
prefer_fortran = arrays[0].flags['FORTRAN']
|
306 |
+
else:
|
307 |
+
# use the most generic type in arrays
|
308 |
+
scores = [_type_score.get(x.dtype.char, 5) for x in arrays]
|
309 |
+
max_score = max(scores)
|
310 |
+
ind_max_score = scores.index(max_score)
|
311 |
+
# safe upcasting for mix of float64 and complex64 --> prefix 'z'
|
312 |
+
if max_score == 3 and (2 in scores):
|
313 |
+
max_score = 4
|
314 |
+
|
315 |
+
if arrays[ind_max_score].flags['FORTRAN']:
|
316 |
+
# prefer Fortran for leading array with column major order
|
317 |
+
prefer_fortran = True
|
318 |
+
|
319 |
+
# Get the LAPACK prefix and the corresponding dtype if not fall back
|
320 |
+
# to 'd' and double precision float.
|
321 |
+
prefix, dtype = _type_conv.get(max_score, ('d', _np.dtype('float64')))
|
322 |
+
|
323 |
+
return prefix, dtype, prefer_fortran
|
324 |
+
|
325 |
+
|
326 |
+
def _get_funcs(names, arrays, dtype,
|
327 |
+
lib_name, fmodule, cmodule,
|
328 |
+
fmodule_name, cmodule_name, alias,
|
329 |
+
ilp64=False):
|
330 |
+
"""
|
331 |
+
Return available BLAS/LAPACK functions.
|
332 |
+
|
333 |
+
Used also in lapack.py. See get_blas_funcs for docstring.
|
334 |
+
"""
|
335 |
+
|
336 |
+
funcs = []
|
337 |
+
unpack = False
|
338 |
+
dtype = _np.dtype(dtype)
|
339 |
+
module1 = (cmodule, cmodule_name)
|
340 |
+
module2 = (fmodule, fmodule_name)
|
341 |
+
|
342 |
+
if isinstance(names, str):
|
343 |
+
names = (names,)
|
344 |
+
unpack = True
|
345 |
+
|
346 |
+
prefix, dtype, prefer_fortran = find_best_blas_type(arrays, dtype)
|
347 |
+
|
348 |
+
if prefer_fortran:
|
349 |
+
module1, module2 = module2, module1
|
350 |
+
|
351 |
+
for name in names:
|
352 |
+
func_name = prefix + name
|
353 |
+
func_name = alias.get(func_name, func_name)
|
354 |
+
func = getattr(module1[0], func_name, None)
|
355 |
+
module_name = module1[1]
|
356 |
+
if func is None:
|
357 |
+
func = getattr(module2[0], func_name, None)
|
358 |
+
module_name = module2[1]
|
359 |
+
if func is None:
|
360 |
+
raise ValueError(
|
361 |
+
f'{lib_name} function {func_name} could not be found')
|
362 |
+
func.module_name, func.typecode = module_name, prefix
|
363 |
+
func.dtype = dtype
|
364 |
+
if not ilp64:
|
365 |
+
func.int_dtype = _np.dtype(_np.intc)
|
366 |
+
else:
|
367 |
+
func.int_dtype = _np.dtype(_np.int64)
|
368 |
+
func.prefix = prefix # Backward compatibility
|
369 |
+
funcs.append(func)
|
370 |
+
|
371 |
+
if unpack:
|
372 |
+
return funcs[0]
|
373 |
+
else:
|
374 |
+
return funcs
|
375 |
+
|
376 |
+
|
377 |
+
def _memoize_get_funcs(func):
|
378 |
+
"""
|
379 |
+
Memoized fast path for _get_funcs instances
|
380 |
+
"""
|
381 |
+
memo = {}
|
382 |
+
func.memo = memo
|
383 |
+
|
384 |
+
@functools.wraps(func)
|
385 |
+
def getter(names, arrays=(), dtype=None, ilp64=False):
|
386 |
+
key = (names, dtype, ilp64)
|
387 |
+
for array in arrays:
|
388 |
+
# cf. find_blas_funcs
|
389 |
+
key += (array.dtype.char, array.flags.fortran)
|
390 |
+
|
391 |
+
try:
|
392 |
+
value = memo.get(key)
|
393 |
+
except TypeError:
|
394 |
+
# unhashable key etc.
|
395 |
+
key = None
|
396 |
+
value = None
|
397 |
+
|
398 |
+
if value is not None:
|
399 |
+
return value
|
400 |
+
|
401 |
+
value = func(names, arrays, dtype, ilp64)
|
402 |
+
|
403 |
+
if key is not None:
|
404 |
+
memo[key] = value
|
405 |
+
|
406 |
+
return value
|
407 |
+
|
408 |
+
return getter
|
409 |
+
|
410 |
+
|
411 |
+
@_memoize_get_funcs
|
412 |
+
def get_blas_funcs(names, arrays=(), dtype=None, ilp64=False):
|
413 |
+
"""Return available BLAS function objects from names.
|
414 |
+
|
415 |
+
Arrays are used to determine the optimal prefix of BLAS routines.
|
416 |
+
|
417 |
+
Parameters
|
418 |
+
----------
|
419 |
+
names : str or sequence of str
|
420 |
+
Name(s) of BLAS functions without type prefix.
|
421 |
+
|
422 |
+
arrays : sequence of ndarrays, optional
|
423 |
+
Arrays can be given to determine optimal prefix of BLAS
|
424 |
+
routines. If not given, double-precision routines will be
|
425 |
+
used, otherwise the most generic type in arrays will be used.
|
426 |
+
|
427 |
+
dtype : str or dtype, optional
|
428 |
+
Data-type specifier. Not used if `arrays` is non-empty.
|
429 |
+
|
430 |
+
ilp64 : {True, False, 'preferred'}, optional
|
431 |
+
Whether to return ILP64 routine variant.
|
432 |
+
Choosing 'preferred' returns ILP64 routine if available,
|
433 |
+
and otherwise the 32-bit routine. Default: False
|
434 |
+
|
435 |
+
Returns
|
436 |
+
-------
|
437 |
+
funcs : list
|
438 |
+
List containing the found function(s).
|
439 |
+
|
440 |
+
|
441 |
+
Notes
|
442 |
+
-----
|
443 |
+
This routine automatically chooses between Fortran/C
|
444 |
+
interfaces. Fortran code is used whenever possible for arrays with
|
445 |
+
column major order. In all other cases, C code is preferred.
|
446 |
+
|
447 |
+
In BLAS, the naming convention is that all functions start with a
|
448 |
+
type prefix, which depends on the type of the principal
|
449 |
+
matrix. These can be one of {'s', 'd', 'c', 'z'} for the NumPy
|
450 |
+
types {float32, float64, complex64, complex128} respectively.
|
451 |
+
The code and the dtype are stored in attributes `typecode` and `dtype`
|
452 |
+
of the returned functions.
|
453 |
+
|
454 |
+
Examples
|
455 |
+
--------
|
456 |
+
>>> import numpy as np
|
457 |
+
>>> import scipy.linalg as LA
|
458 |
+
>>> rng = np.random.default_rng()
|
459 |
+
>>> a = rng.random((3,2))
|
460 |
+
>>> x_gemv = LA.get_blas_funcs('gemv', (a,))
|
461 |
+
>>> x_gemv.typecode
|
462 |
+
'd'
|
463 |
+
>>> x_gemv = LA.get_blas_funcs('gemv',(a*1j,))
|
464 |
+
>>> x_gemv.typecode
|
465 |
+
'z'
|
466 |
+
|
467 |
+
"""
|
468 |
+
if isinstance(ilp64, str):
|
469 |
+
if ilp64 == 'preferred':
|
470 |
+
ilp64 = HAS_ILP64
|
471 |
+
else:
|
472 |
+
raise ValueError("Invalid value for 'ilp64'")
|
473 |
+
|
474 |
+
if not ilp64:
|
475 |
+
return _get_funcs(names, arrays, dtype,
|
476 |
+
"BLAS", _fblas, _cblas, "fblas", "cblas",
|
477 |
+
_blas_alias, ilp64=False)
|
478 |
+
else:
|
479 |
+
if not HAS_ILP64:
|
480 |
+
raise RuntimeError("BLAS ILP64 routine requested, but Scipy "
|
481 |
+
"compiled only with 32-bit BLAS")
|
482 |
+
return _get_funcs(names, arrays, dtype,
|
483 |
+
"BLAS", _fblas_64, None, "fblas_64", None,
|
484 |
+
_blas_alias, ilp64=True)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_blas.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (349 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/cython_lapack.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (838 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
2 |
+
# Use the `scipy.linalg` namespace for importing the functions
|
3 |
+
# included below.
|
4 |
+
|
5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
6 |
+
|
7 |
+
|
8 |
+
__all__ = [ # noqa: F822
|
9 |
+
'lu', 'lu_solve', 'lu_factor',
|
10 |
+
'asarray_chkfinite', 'LinAlgWarning', 'get_lapack_funcs',
|
11 |
+
]
|
12 |
+
|
13 |
+
|
14 |
+
def __dir__():
|
15 |
+
return __all__
|
16 |
+
|
17 |
+
|
18 |
+
def __getattr__(name):
|
19 |
+
return _sub_module_deprecation(sub_package="linalg", module="decomp_lu",
|
20 |
+
private_modules=["_decomp_lu"], all=__all__,
|
21 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
2 |
+
# Use the `scipy.linalg` namespace for importing the functions
|
3 |
+
# included below.
|
4 |
+
|
5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
6 |
+
|
7 |
+
|
8 |
+
__all__ = [ # noqa: F822
|
9 |
+
'svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space',
|
10 |
+
'LinAlgError', 'get_lapack_funcs'
|
11 |
+
]
|
12 |
+
|
13 |
+
|
14 |
+
def __dir__():
|
15 |
+
return __all__
|
16 |
+
|
17 |
+
|
18 |
+
def __getattr__(name):
|
19 |
+
return _sub_module_deprecation(sub_package="linalg", module="decomp_svd",
|
20 |
+
private_modules=["_decomp_svd"], all=__all__,
|
21 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py
ADDED
@@ -0,0 +1,1114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# Created by: Pearu Peterson, April 2002
|
3 |
+
#
|
4 |
+
|
5 |
+
import math
|
6 |
+
import pytest
|
7 |
+
import numpy as np
|
8 |
+
from numpy.testing import (assert_equal, assert_almost_equal, assert_,
|
9 |
+
assert_array_almost_equal, assert_allclose)
|
10 |
+
from pytest import raises as assert_raises
|
11 |
+
|
12 |
+
from numpy import float32, float64, complex64, complex128, arange, triu, \
|
13 |
+
tril, zeros, tril_indices, ones, mod, diag, append, eye, \
|
14 |
+
nonzero
|
15 |
+
|
16 |
+
from numpy.random import rand, seed
|
17 |
+
import scipy
|
18 |
+
from scipy.linalg import _fblas as fblas, get_blas_funcs, toeplitz, solve
|
19 |
+
|
20 |
+
try:
|
21 |
+
from scipy.linalg import _cblas as cblas
|
22 |
+
except ImportError:
|
23 |
+
cblas = None
|
24 |
+
|
25 |
+
REAL_DTYPES = [float32, float64]
|
26 |
+
COMPLEX_DTYPES = [complex64, complex128]
|
27 |
+
DTYPES = REAL_DTYPES + COMPLEX_DTYPES
|
28 |
+
|
29 |
+
|
30 |
+
def test_get_blas_funcs():
|
31 |
+
# check that it returns Fortran code for arrays that are
|
32 |
+
# fortran-ordered
|
33 |
+
f1, f2, f3 = get_blas_funcs(
|
34 |
+
('axpy', 'axpy', 'axpy'),
|
35 |
+
(np.empty((2, 2), dtype=np.complex64, order='F'),
|
36 |
+
np.empty((2, 2), dtype=np.complex128, order='C'))
|
37 |
+
)
|
38 |
+
|
39 |
+
# get_blas_funcs will choose libraries depending on most generic
|
40 |
+
# array
|
41 |
+
assert_equal(f1.typecode, 'z')
|
42 |
+
assert_equal(f2.typecode, 'z')
|
43 |
+
if cblas is not None:
|
44 |
+
assert_equal(f1.module_name, 'cblas')
|
45 |
+
assert_equal(f2.module_name, 'cblas')
|
46 |
+
|
47 |
+
# check defaults.
|
48 |
+
f1 = get_blas_funcs('rotg')
|
49 |
+
assert_equal(f1.typecode, 'd')
|
50 |
+
|
51 |
+
# check also dtype interface
|
52 |
+
f1 = get_blas_funcs('gemm', dtype=np.complex64)
|
53 |
+
assert_equal(f1.typecode, 'c')
|
54 |
+
f1 = get_blas_funcs('gemm', dtype='F')
|
55 |
+
assert_equal(f1.typecode, 'c')
|
56 |
+
|
57 |
+
# extended precision complex
|
58 |
+
f1 = get_blas_funcs('gemm', dtype=np.clongdouble)
|
59 |
+
assert_equal(f1.typecode, 'z')
|
60 |
+
|
61 |
+
# check safe complex upcasting
|
62 |
+
f1 = get_blas_funcs('axpy',
|
63 |
+
(np.empty((2, 2), dtype=np.float64),
|
64 |
+
np.empty((2, 2), dtype=np.complex64))
|
65 |
+
)
|
66 |
+
assert_equal(f1.typecode, 'z')
|
67 |
+
|
68 |
+
|
69 |
+
def test_get_blas_funcs_alias():
|
70 |
+
# check alias for get_blas_funcs
|
71 |
+
f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64)
|
72 |
+
assert f.typecode == 'c'
|
73 |
+
assert g.typecode == 'c'
|
74 |
+
|
75 |
+
f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64)
|
76 |
+
assert f is g
|
77 |
+
assert f is h
|
78 |
+
|
79 |
+
|
80 |
+
class TestCBLAS1Simple:
|
81 |
+
|
82 |
+
def test_axpy(self):
|
83 |
+
for p in 'sd':
|
84 |
+
f = getattr(cblas, p+'axpy', None)
|
85 |
+
if f is None:
|
86 |
+
continue
|
87 |
+
assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
|
88 |
+
[7, 9, 18])
|
89 |
+
for p in 'cz':
|
90 |
+
f = getattr(cblas, p+'axpy', None)
|
91 |
+
if f is None:
|
92 |
+
continue
|
93 |
+
assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
|
94 |
+
[7, 10j-1, 18])
|
95 |
+
|
96 |
+
|
97 |
+
class TestFBLAS1Simple:
|
98 |
+
|
99 |
+
def test_axpy(self):
|
100 |
+
for p in 'sd':
|
101 |
+
f = getattr(fblas, p+'axpy', None)
|
102 |
+
if f is None:
|
103 |
+
continue
|
104 |
+
assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
|
105 |
+
[7, 9, 18])
|
106 |
+
for p in 'cz':
|
107 |
+
f = getattr(fblas, p+'axpy', None)
|
108 |
+
if f is None:
|
109 |
+
continue
|
110 |
+
assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
|
111 |
+
[7, 10j-1, 18])
|
112 |
+
|
113 |
+
def test_copy(self):
|
114 |
+
for p in 'sd':
|
115 |
+
f = getattr(fblas, p+'copy', None)
|
116 |
+
if f is None:
|
117 |
+
continue
|
118 |
+
assert_array_almost_equal(f([3, 4, 5], [8]*3), [3, 4, 5])
|
119 |
+
for p in 'cz':
|
120 |
+
f = getattr(fblas, p+'copy', None)
|
121 |
+
if f is None:
|
122 |
+
continue
|
123 |
+
assert_array_almost_equal(f([3, 4j, 5+3j], [8]*3), [3, 4j, 5+3j])
|
124 |
+
|
125 |
+
def test_asum(self):
|
126 |
+
for p in 'sd':
|
127 |
+
f = getattr(fblas, p+'asum', None)
|
128 |
+
if f is None:
|
129 |
+
continue
|
130 |
+
assert_almost_equal(f([3, -4, 5]), 12)
|
131 |
+
for p in ['sc', 'dz']:
|
132 |
+
f = getattr(fblas, p+'asum', None)
|
133 |
+
if f is None:
|
134 |
+
continue
|
135 |
+
assert_almost_equal(f([3j, -4, 3-4j]), 14)
|
136 |
+
|
137 |
+
def test_dot(self):
|
138 |
+
for p in 'sd':
|
139 |
+
f = getattr(fblas, p+'dot', None)
|
140 |
+
if f is None:
|
141 |
+
continue
|
142 |
+
assert_almost_equal(f([3, -4, 5], [2, 5, 1]), -9)
|
143 |
+
|
144 |
+
def test_complex_dotu(self):
|
145 |
+
for p in 'cz':
|
146 |
+
f = getattr(fblas, p+'dotu', None)
|
147 |
+
if f is None:
|
148 |
+
continue
|
149 |
+
assert_almost_equal(f([3j, -4, 3-4j], [2, 3, 1]), -9+2j)
|
150 |
+
|
151 |
+
def test_complex_dotc(self):
|
152 |
+
for p in 'cz':
|
153 |
+
f = getattr(fblas, p+'dotc', None)
|
154 |
+
if f is None:
|
155 |
+
continue
|
156 |
+
assert_almost_equal(f([3j, -4, 3-4j], [2, 3j, 1]), 3-14j)
|
157 |
+
|
158 |
+
def test_nrm2(self):
|
159 |
+
for p in 'sd':
|
160 |
+
f = getattr(fblas, p+'nrm2', None)
|
161 |
+
if f is None:
|
162 |
+
continue
|
163 |
+
assert_almost_equal(f([3, -4, 5]), math.sqrt(50))
|
164 |
+
for p in ['c', 'z', 'sc', 'dz']:
|
165 |
+
f = getattr(fblas, p+'nrm2', None)
|
166 |
+
if f is None:
|
167 |
+
continue
|
168 |
+
assert_almost_equal(f([3j, -4, 3-4j]), math.sqrt(50))
|
169 |
+
|
170 |
+
def test_scal(self):
|
171 |
+
for p in 'sd':
|
172 |
+
f = getattr(fblas, p+'scal', None)
|
173 |
+
if f is None:
|
174 |
+
continue
|
175 |
+
assert_array_almost_equal(f(2, [3, -4, 5]), [6, -8, 10])
|
176 |
+
for p in 'cz':
|
177 |
+
f = getattr(fblas, p+'scal', None)
|
178 |
+
if f is None:
|
179 |
+
continue
|
180 |
+
assert_array_almost_equal(f(3j, [3j, -4, 3-4j]), [-9, -12j, 12+9j])
|
181 |
+
for p in ['cs', 'zd']:
|
182 |
+
f = getattr(fblas, p+'scal', None)
|
183 |
+
if f is None:
|
184 |
+
continue
|
185 |
+
assert_array_almost_equal(f(3, [3j, -4, 3-4j]), [9j, -12, 9-12j])
|
186 |
+
|
187 |
+
def test_swap(self):
|
188 |
+
for p in 'sd':
|
189 |
+
f = getattr(fblas, p+'swap', None)
|
190 |
+
if f is None:
|
191 |
+
continue
|
192 |
+
x, y = [2, 3, 1], [-2, 3, 7]
|
193 |
+
x1, y1 = f(x, y)
|
194 |
+
assert_array_almost_equal(x1, y)
|
195 |
+
assert_array_almost_equal(y1, x)
|
196 |
+
for p in 'cz':
|
197 |
+
f = getattr(fblas, p+'swap', None)
|
198 |
+
if f is None:
|
199 |
+
continue
|
200 |
+
x, y = [2, 3j, 1], [-2, 3, 7-3j]
|
201 |
+
x1, y1 = f(x, y)
|
202 |
+
assert_array_almost_equal(x1, y)
|
203 |
+
assert_array_almost_equal(y1, x)
|
204 |
+
|
205 |
+
def test_amax(self):
|
206 |
+
for p in 'sd':
|
207 |
+
f = getattr(fblas, 'i'+p+'amax')
|
208 |
+
assert_equal(f([-2, 4, 3]), 1)
|
209 |
+
for p in 'cz':
|
210 |
+
f = getattr(fblas, 'i'+p+'amax')
|
211 |
+
assert_equal(f([-5, 4+3j, 6]), 1)
|
212 |
+
# XXX: need tests for rot,rotm,rotg,rotmg
|
213 |
+
|
214 |
+
|
215 |
+
class TestFBLAS2Simple:
|
216 |
+
|
217 |
+
def test_gemv(self):
|
218 |
+
for p in 'sd':
|
219 |
+
f = getattr(fblas, p+'gemv', None)
|
220 |
+
if f is None:
|
221 |
+
continue
|
222 |
+
assert_array_almost_equal(f(3, [[3]], [-4]), [-36])
|
223 |
+
assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21])
|
224 |
+
for p in 'cz':
|
225 |
+
f = getattr(fblas, p+'gemv', None)
|
226 |
+
if f is None:
|
227 |
+
continue
|
228 |
+
assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-48-36j])
|
229 |
+
assert_array_almost_equal(f(3j, [[3-4j]], [-4], 3, [5j]),
|
230 |
+
[-48-21j])
|
231 |
+
|
232 |
+
def test_ger(self):
|
233 |
+
|
234 |
+
for p in 'sd':
|
235 |
+
f = getattr(fblas, p+'ger', None)
|
236 |
+
if f is None:
|
237 |
+
continue
|
238 |
+
assert_array_almost_equal(f(1, [1, 2], [3, 4]), [[3, 4], [6, 8]])
|
239 |
+
assert_array_almost_equal(f(2, [1, 2, 3], [3, 4]),
|
240 |
+
[[6, 8], [12, 16], [18, 24]])
|
241 |
+
|
242 |
+
assert_array_almost_equal(f(1, [1, 2], [3, 4],
|
243 |
+
a=[[1, 2], [3, 4]]), [[4, 6], [9, 12]])
|
244 |
+
|
245 |
+
for p in 'cz':
|
246 |
+
f = getattr(fblas, p+'geru', None)
|
247 |
+
if f is None:
|
248 |
+
continue
|
249 |
+
assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
|
250 |
+
[[3j, 4j], [6, 8]])
|
251 |
+
assert_array_almost_equal(f(-2, [1j, 2j, 3j], [3j, 4j]),
|
252 |
+
[[6, 8], [12, 16], [18, 24]])
|
253 |
+
|
254 |
+
for p in 'cz':
|
255 |
+
for name in ('ger', 'gerc'):
|
256 |
+
f = getattr(fblas, p+name, None)
|
257 |
+
if f is None:
|
258 |
+
continue
|
259 |
+
assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
|
260 |
+
[[3j, 4j], [6, 8]])
|
261 |
+
assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]),
|
262 |
+
[[6, 8], [12, 16], [18, 24]])
|
263 |
+
|
264 |
+
def test_syr_her(self):
|
265 |
+
x = np.arange(1, 5, dtype='d')
|
266 |
+
resx = np.triu(x[:, np.newaxis] * x)
|
267 |
+
resx_reverse = np.triu(x[::-1, np.newaxis] * x[::-1])
|
268 |
+
|
269 |
+
y = np.linspace(0, 8.5, 17, endpoint=False)
|
270 |
+
|
271 |
+
z = np.arange(1, 9, dtype='d').view('D')
|
272 |
+
resz = np.triu(z[:, np.newaxis] * z)
|
273 |
+
resz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1])
|
274 |
+
rehz = np.triu(z[:, np.newaxis] * z.conj())
|
275 |
+
rehz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1].conj())
|
276 |
+
|
277 |
+
w = np.c_[np.zeros(4), z, np.zeros(4)].ravel()
|
278 |
+
|
279 |
+
for p, rtol in zip('sd', [1e-7, 1e-14]):
|
280 |
+
f = getattr(fblas, p+'syr', None)
|
281 |
+
if f is None:
|
282 |
+
continue
|
283 |
+
assert_allclose(f(1.0, x), resx, rtol=rtol)
|
284 |
+
assert_allclose(f(1.0, x, lower=True), resx.T, rtol=rtol)
|
285 |
+
assert_allclose(f(1.0, y, incx=2, offx=2, n=4), resx, rtol=rtol)
|
286 |
+
# negative increments imply reversed vectors in blas
|
287 |
+
assert_allclose(f(1.0, y, incx=-2, offx=2, n=4),
|
288 |
+
resx_reverse, rtol=rtol)
|
289 |
+
|
290 |
+
a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F')
|
291 |
+
b = f(1.0, x, a=a, overwrite_a=True)
|
292 |
+
assert_allclose(a, resx, rtol=rtol)
|
293 |
+
|
294 |
+
b = f(2.0, x, a=a)
|
295 |
+
assert_(a is not b)
|
296 |
+
assert_allclose(b, 3*resx, rtol=rtol)
|
297 |
+
|
298 |
+
assert_raises(Exception, f, 1.0, x, incx=0)
|
299 |
+
assert_raises(Exception, f, 1.0, x, offx=5)
|
300 |
+
assert_raises(Exception, f, 1.0, x, offx=-2)
|
301 |
+
assert_raises(Exception, f, 1.0, x, n=-2)
|
302 |
+
assert_raises(Exception, f, 1.0, x, n=5)
|
303 |
+
assert_raises(Exception, f, 1.0, x, lower=2)
|
304 |
+
assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
|
305 |
+
|
306 |
+
for p, rtol in zip('cz', [1e-7, 1e-14]):
|
307 |
+
f = getattr(fblas, p+'syr', None)
|
308 |
+
if f is None:
|
309 |
+
continue
|
310 |
+
assert_allclose(f(1.0, z), resz, rtol=rtol)
|
311 |
+
assert_allclose(f(1.0, z, lower=True), resz.T, rtol=rtol)
|
312 |
+
assert_allclose(f(1.0, w, incx=3, offx=1, n=4), resz, rtol=rtol)
|
313 |
+
# negative increments imply reversed vectors in blas
|
314 |
+
assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
|
315 |
+
resz_reverse, rtol=rtol)
|
316 |
+
|
317 |
+
a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
|
318 |
+
b = f(1.0, z, a=a, overwrite_a=True)
|
319 |
+
assert_allclose(a, resz, rtol=rtol)
|
320 |
+
|
321 |
+
b = f(2.0, z, a=a)
|
322 |
+
assert_(a is not b)
|
323 |
+
assert_allclose(b, 3*resz, rtol=rtol)
|
324 |
+
|
325 |
+
assert_raises(Exception, f, 1.0, x, incx=0)
|
326 |
+
assert_raises(Exception, f, 1.0, x, offx=5)
|
327 |
+
assert_raises(Exception, f, 1.0, x, offx=-2)
|
328 |
+
assert_raises(Exception, f, 1.0, x, n=-2)
|
329 |
+
assert_raises(Exception, f, 1.0, x, n=5)
|
330 |
+
assert_raises(Exception, f, 1.0, x, lower=2)
|
331 |
+
assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
|
332 |
+
|
333 |
+
for p, rtol in zip('cz', [1e-7, 1e-14]):
|
334 |
+
f = getattr(fblas, p+'her', None)
|
335 |
+
if f is None:
|
336 |
+
continue
|
337 |
+
assert_allclose(f(1.0, z), rehz, rtol=rtol)
|
338 |
+
assert_allclose(f(1.0, z, lower=True), rehz.T.conj(), rtol=rtol)
|
339 |
+
assert_allclose(f(1.0, w, incx=3, offx=1, n=4), rehz, rtol=rtol)
|
340 |
+
# negative increments imply reversed vectors in blas
|
341 |
+
assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
|
342 |
+
rehz_reverse, rtol=rtol)
|
343 |
+
|
344 |
+
a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
|
345 |
+
b = f(1.0, z, a=a, overwrite_a=True)
|
346 |
+
assert_allclose(a, rehz, rtol=rtol)
|
347 |
+
|
348 |
+
b = f(2.0, z, a=a)
|
349 |
+
assert_(a is not b)
|
350 |
+
assert_allclose(b, 3*rehz, rtol=rtol)
|
351 |
+
|
352 |
+
assert_raises(Exception, f, 1.0, x, incx=0)
|
353 |
+
assert_raises(Exception, f, 1.0, x, offx=5)
|
354 |
+
assert_raises(Exception, f, 1.0, x, offx=-2)
|
355 |
+
assert_raises(Exception, f, 1.0, x, n=-2)
|
356 |
+
assert_raises(Exception, f, 1.0, x, n=5)
|
357 |
+
assert_raises(Exception, f, 1.0, x, lower=2)
|
358 |
+
assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
|
359 |
+
|
360 |
+
def test_syr2(self):
|
361 |
+
x = np.arange(1, 5, dtype='d')
|
362 |
+
y = np.arange(5, 9, dtype='d')
|
363 |
+
resxy = np.triu(x[:, np.newaxis] * y + y[:, np.newaxis] * x)
|
364 |
+
resxy_reverse = np.triu(x[::-1, np.newaxis] * y[::-1]
|
365 |
+
+ y[::-1, np.newaxis] * x[::-1])
|
366 |
+
|
367 |
+
q = np.linspace(0, 8.5, 17, endpoint=False)
|
368 |
+
|
369 |
+
for p, rtol in zip('sd', [1e-7, 1e-14]):
|
370 |
+
f = getattr(fblas, p+'syr2', None)
|
371 |
+
if f is None:
|
372 |
+
continue
|
373 |
+
assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
|
374 |
+
assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
|
375 |
+
assert_allclose(f(1.0, x, y, lower=True), resxy.T, rtol=rtol)
|
376 |
+
|
377 |
+
assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10),
|
378 |
+
resxy, rtol=rtol)
|
379 |
+
assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10, n=3),
|
380 |
+
resxy[:3, :3], rtol=rtol)
|
381 |
+
# negative increments imply reversed vectors in blas
|
382 |
+
assert_allclose(f(1.0, q, q, incx=-2, offx=2, incy=-2, offy=10),
|
383 |
+
resxy_reverse, rtol=rtol)
|
384 |
+
|
385 |
+
a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F')
|
386 |
+
b = f(1.0, x, y, a=a, overwrite_a=True)
|
387 |
+
assert_allclose(a, resxy, rtol=rtol)
|
388 |
+
|
389 |
+
b = f(2.0, x, y, a=a)
|
390 |
+
assert_(a is not b)
|
391 |
+
assert_allclose(b, 3*resxy, rtol=rtol)
|
392 |
+
|
393 |
+
assert_raises(Exception, f, 1.0, x, y, incx=0)
|
394 |
+
assert_raises(Exception, f, 1.0, x, y, offx=5)
|
395 |
+
assert_raises(Exception, f, 1.0, x, y, offx=-2)
|
396 |
+
assert_raises(Exception, f, 1.0, x, y, incy=0)
|
397 |
+
assert_raises(Exception, f, 1.0, x, y, offy=5)
|
398 |
+
assert_raises(Exception, f, 1.0, x, y, offy=-2)
|
399 |
+
assert_raises(Exception, f, 1.0, x, y, n=-2)
|
400 |
+
assert_raises(Exception, f, 1.0, x, y, n=5)
|
401 |
+
assert_raises(Exception, f, 1.0, x, y, lower=2)
|
402 |
+
assert_raises(Exception, f, 1.0, x, y,
|
403 |
+
a=np.zeros((2, 2), 'd', 'F'))
|
404 |
+
|
405 |
+
def test_her2(self):
|
406 |
+
x = np.arange(1, 9, dtype='d').view('D')
|
407 |
+
y = np.arange(9, 17, dtype='d').view('D')
|
408 |
+
resxy = x[:, np.newaxis] * y.conj() + y[:, np.newaxis] * x.conj()
|
409 |
+
resxy = np.triu(resxy)
|
410 |
+
|
411 |
+
resxy_reverse = x[::-1, np.newaxis] * y[::-1].conj()
|
412 |
+
resxy_reverse += y[::-1, np.newaxis] * x[::-1].conj()
|
413 |
+
resxy_reverse = np.triu(resxy_reverse)
|
414 |
+
|
415 |
+
u = np.c_[np.zeros(4), x, np.zeros(4)].ravel()
|
416 |
+
v = np.c_[np.zeros(4), y, np.zeros(4)].ravel()
|
417 |
+
|
418 |
+
for p, rtol in zip('cz', [1e-7, 1e-14]):
|
419 |
+
f = getattr(fblas, p+'her2', None)
|
420 |
+
if f is None:
|
421 |
+
continue
|
422 |
+
assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
|
423 |
+
assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
|
424 |
+
assert_allclose(f(1.0, x, y, lower=True), resxy.T.conj(),
|
425 |
+
rtol=rtol)
|
426 |
+
|
427 |
+
assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1),
|
428 |
+
resxy, rtol=rtol)
|
429 |
+
assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1, n=3),
|
430 |
+
resxy[:3, :3], rtol=rtol)
|
431 |
+
# negative increments imply reversed vectors in blas
|
432 |
+
assert_allclose(f(1.0, u, v, incx=-3, offx=1, incy=-3, offy=1),
|
433 |
+
resxy_reverse, rtol=rtol)
|
434 |
+
|
435 |
+
a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
|
436 |
+
b = f(1.0, x, y, a=a, overwrite_a=True)
|
437 |
+
assert_allclose(a, resxy, rtol=rtol)
|
438 |
+
|
439 |
+
b = f(2.0, x, y, a=a)
|
440 |
+
assert_(a is not b)
|
441 |
+
assert_allclose(b, 3*resxy, rtol=rtol)
|
442 |
+
|
443 |
+
assert_raises(Exception, f, 1.0, x, y, incx=0)
|
444 |
+
assert_raises(Exception, f, 1.0, x, y, offx=5)
|
445 |
+
assert_raises(Exception, f, 1.0, x, y, offx=-2)
|
446 |
+
assert_raises(Exception, f, 1.0, x, y, incy=0)
|
447 |
+
assert_raises(Exception, f, 1.0, x, y, offy=5)
|
448 |
+
assert_raises(Exception, f, 1.0, x, y, offy=-2)
|
449 |
+
assert_raises(Exception, f, 1.0, x, y, n=-2)
|
450 |
+
assert_raises(Exception, f, 1.0, x, y, n=5)
|
451 |
+
assert_raises(Exception, f, 1.0, x, y, lower=2)
|
452 |
+
assert_raises(Exception, f, 1.0, x, y,
|
453 |
+
a=np.zeros((2, 2), 'd', 'F'))
|
454 |
+
|
455 |
+
def test_gbmv(self):
|
456 |
+
seed(1234)
|
457 |
+
for ind, dtype in enumerate(DTYPES):
|
458 |
+
n = 7
|
459 |
+
m = 5
|
460 |
+
kl = 1
|
461 |
+
ku = 2
|
462 |
+
# fake a banded matrix via toeplitz
|
463 |
+
A = toeplitz(append(rand(kl+1), zeros(m-kl-1)),
|
464 |
+
append(rand(ku+1), zeros(n-ku-1)))
|
465 |
+
A = A.astype(dtype)
|
466 |
+
Ab = zeros((kl+ku+1, n), dtype=dtype)
|
467 |
+
|
468 |
+
# Form the banded storage
|
469 |
+
Ab[2, :5] = A[0, 0] # diag
|
470 |
+
Ab[1, 1:6] = A[0, 1] # sup1
|
471 |
+
Ab[0, 2:7] = A[0, 2] # sup2
|
472 |
+
Ab[3, :4] = A[1, 0] # sub1
|
473 |
+
|
474 |
+
x = rand(n).astype(dtype)
|
475 |
+
y = rand(m).astype(dtype)
|
476 |
+
alpha, beta = dtype(3), dtype(-5)
|
477 |
+
|
478 |
+
func, = get_blas_funcs(('gbmv',), dtype=dtype)
|
479 |
+
y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
|
480 |
+
x=x, y=y, beta=beta)
|
481 |
+
y2 = alpha * A.dot(x) + beta * y
|
482 |
+
assert_array_almost_equal(y1, y2)
|
483 |
+
|
484 |
+
y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
|
485 |
+
x=y, y=x, beta=beta, trans=1)
|
486 |
+
y2 = alpha * A.T.dot(y) + beta * x
|
487 |
+
assert_array_almost_equal(y1, y2)
|
488 |
+
|
489 |
+
def test_sbmv_hbmv(self):
|
490 |
+
seed(1234)
|
491 |
+
for ind, dtype in enumerate(DTYPES):
|
492 |
+
n = 6
|
493 |
+
k = 2
|
494 |
+
A = zeros((n, n), dtype=dtype)
|
495 |
+
Ab = zeros((k+1, n), dtype=dtype)
|
496 |
+
|
497 |
+
# Form the array and its packed banded storage
|
498 |
+
A[arange(n), arange(n)] = rand(n)
|
499 |
+
for ind2 in range(1, k+1):
|
500 |
+
temp = rand(n-ind2)
|
501 |
+
A[arange(n-ind2), arange(ind2, n)] = temp
|
502 |
+
Ab[-1-ind2, ind2:] = temp
|
503 |
+
A = A.astype(dtype)
|
504 |
+
A = A + A.T if ind < 2 else A + A.conj().T
|
505 |
+
Ab[-1, :] = diag(A)
|
506 |
+
x = rand(n).astype(dtype)
|
507 |
+
y = rand(n).astype(dtype)
|
508 |
+
alpha, beta = dtype(1.25), dtype(3)
|
509 |
+
|
510 |
+
if ind > 1:
|
511 |
+
func, = get_blas_funcs(('hbmv',), dtype=dtype)
|
512 |
+
else:
|
513 |
+
func, = get_blas_funcs(('sbmv',), dtype=dtype)
|
514 |
+
y1 = func(k=k, alpha=alpha, a=Ab, x=x, y=y, beta=beta)
|
515 |
+
y2 = alpha * A.dot(x) + beta * y
|
516 |
+
assert_array_almost_equal(y1, y2)
|
517 |
+
|
518 |
+
def test_spmv_hpmv(self):
|
519 |
+
seed(1234)
|
520 |
+
for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
|
521 |
+
n = 3
|
522 |
+
A = rand(n, n).astype(dtype)
|
523 |
+
if ind > 1:
|
524 |
+
A += rand(n, n)*1j
|
525 |
+
A = A.astype(dtype)
|
526 |
+
A = A + A.T if ind < 4 else A + A.conj().T
|
527 |
+
c, r = tril_indices(n)
|
528 |
+
Ap = A[r, c]
|
529 |
+
x = rand(n).astype(dtype)
|
530 |
+
y = rand(n).astype(dtype)
|
531 |
+
xlong = arange(2*n).astype(dtype)
|
532 |
+
ylong = ones(2*n).astype(dtype)
|
533 |
+
alpha, beta = dtype(1.25), dtype(2)
|
534 |
+
|
535 |
+
if ind > 3:
|
536 |
+
func, = get_blas_funcs(('hpmv',), dtype=dtype)
|
537 |
+
else:
|
538 |
+
func, = get_blas_funcs(('spmv',), dtype=dtype)
|
539 |
+
y1 = func(n=n, alpha=alpha, ap=Ap, x=x, y=y, beta=beta)
|
540 |
+
y2 = alpha * A.dot(x) + beta * y
|
541 |
+
assert_array_almost_equal(y1, y2)
|
542 |
+
|
543 |
+
# Test inc and offsets
|
544 |
+
y1 = func(n=n-1, alpha=alpha, beta=beta, x=xlong, y=ylong, ap=Ap,
|
545 |
+
incx=2, incy=2, offx=n, offy=n)
|
546 |
+
y2 = (alpha * A[:-1, :-1]).dot(xlong[3::2]) + beta * ylong[3::2]
|
547 |
+
assert_array_almost_equal(y1[3::2], y2)
|
548 |
+
assert_almost_equal(y1[4], ylong[4])
|
549 |
+
|
550 |
+
def test_spr_hpr(self):
|
551 |
+
seed(1234)
|
552 |
+
for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
|
553 |
+
n = 3
|
554 |
+
A = rand(n, n).astype(dtype)
|
555 |
+
if ind > 1:
|
556 |
+
A += rand(n, n)*1j
|
557 |
+
A = A.astype(dtype)
|
558 |
+
A = A + A.T if ind < 4 else A + A.conj().T
|
559 |
+
c, r = tril_indices(n)
|
560 |
+
Ap = A[r, c]
|
561 |
+
x = rand(n).astype(dtype)
|
562 |
+
alpha = (DTYPES+COMPLEX_DTYPES)[mod(ind, 4)](2.5)
|
563 |
+
|
564 |
+
if ind > 3:
|
565 |
+
func, = get_blas_funcs(('hpr',), dtype=dtype)
|
566 |
+
y2 = alpha * x[:, None].dot(x[None, :].conj()) + A
|
567 |
+
else:
|
568 |
+
func, = get_blas_funcs(('spr',), dtype=dtype)
|
569 |
+
y2 = alpha * x[:, None].dot(x[None, :]) + A
|
570 |
+
|
571 |
+
y1 = func(n=n, alpha=alpha, ap=Ap, x=x)
|
572 |
+
y1f = zeros((3, 3), dtype=dtype)
|
573 |
+
y1f[r, c] = y1
|
574 |
+
y1f[c, r] = y1.conj() if ind > 3 else y1
|
575 |
+
assert_array_almost_equal(y1f, y2)
|
576 |
+
|
577 |
+
def test_spr2_hpr2(self):
|
578 |
+
seed(1234)
|
579 |
+
for ind, dtype in enumerate(DTYPES):
|
580 |
+
n = 3
|
581 |
+
A = rand(n, n).astype(dtype)
|
582 |
+
if ind > 1:
|
583 |
+
A += rand(n, n)*1j
|
584 |
+
A = A.astype(dtype)
|
585 |
+
A = A + A.T if ind < 2 else A + A.conj().T
|
586 |
+
c, r = tril_indices(n)
|
587 |
+
Ap = A[r, c]
|
588 |
+
x = rand(n).astype(dtype)
|
589 |
+
y = rand(n).astype(dtype)
|
590 |
+
alpha = dtype(2)
|
591 |
+
|
592 |
+
if ind > 1:
|
593 |
+
func, = get_blas_funcs(('hpr2',), dtype=dtype)
|
594 |
+
else:
|
595 |
+
func, = get_blas_funcs(('spr2',), dtype=dtype)
|
596 |
+
|
597 |
+
u = alpha.conj() * x[:, None].dot(y[None, :].conj())
|
598 |
+
y2 = A + u + u.conj().T
|
599 |
+
y1 = func(n=n, alpha=alpha, x=x, y=y, ap=Ap)
|
600 |
+
y1f = zeros((3, 3), dtype=dtype)
|
601 |
+
y1f[r, c] = y1
|
602 |
+
y1f[[1, 2, 2], [0, 0, 1]] = y1[[1, 3, 4]].conj()
|
603 |
+
assert_array_almost_equal(y1f, y2)
|
604 |
+
|
605 |
+
def test_tbmv(self):
|
606 |
+
seed(1234)
|
607 |
+
for ind, dtype in enumerate(DTYPES):
|
608 |
+
n = 10
|
609 |
+
k = 3
|
610 |
+
x = rand(n).astype(dtype)
|
611 |
+
A = zeros((n, n), dtype=dtype)
|
612 |
+
# Banded upper triangular array
|
613 |
+
for sup in range(k+1):
|
614 |
+
A[arange(n-sup), arange(sup, n)] = rand(n-sup)
|
615 |
+
|
616 |
+
# Add complex parts for c,z
|
617 |
+
if ind > 1:
|
618 |
+
A[nonzero(A)] += 1j * rand((k+1)*n-(k*(k+1)//2)).astype(dtype)
|
619 |
+
|
620 |
+
# Form the banded storage
|
621 |
+
Ab = zeros((k+1, n), dtype=dtype)
|
622 |
+
for row in range(k+1):
|
623 |
+
Ab[-row-1, row:] = diag(A, k=row)
|
624 |
+
func, = get_blas_funcs(('tbmv',), dtype=dtype)
|
625 |
+
|
626 |
+
y1 = func(k=k, a=Ab, x=x)
|
627 |
+
y2 = A.dot(x)
|
628 |
+
assert_array_almost_equal(y1, y2)
|
629 |
+
|
630 |
+
y1 = func(k=k, a=Ab, x=x, diag=1)
|
631 |
+
A[arange(n), arange(n)] = dtype(1)
|
632 |
+
y2 = A.dot(x)
|
633 |
+
assert_array_almost_equal(y1, y2)
|
634 |
+
|
635 |
+
y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
|
636 |
+
y2 = A.T.dot(x)
|
637 |
+
assert_array_almost_equal(y1, y2)
|
638 |
+
|
639 |
+
y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
|
640 |
+
y2 = A.conj().T.dot(x)
|
641 |
+
assert_array_almost_equal(y1, y2)
|
642 |
+
|
643 |
+
def test_tbsv(self):
|
644 |
+
seed(1234)
|
645 |
+
for ind, dtype in enumerate(DTYPES):
|
646 |
+
n = 6
|
647 |
+
k = 3
|
648 |
+
x = rand(n).astype(dtype)
|
649 |
+
A = zeros((n, n), dtype=dtype)
|
650 |
+
# Banded upper triangular array
|
651 |
+
for sup in range(k+1):
|
652 |
+
A[arange(n-sup), arange(sup, n)] = rand(n-sup)
|
653 |
+
|
654 |
+
# Add complex parts for c,z
|
655 |
+
if ind > 1:
|
656 |
+
A[nonzero(A)] += 1j * rand((k+1)*n-(k*(k+1)//2)).astype(dtype)
|
657 |
+
|
658 |
+
# Form the banded storage
|
659 |
+
Ab = zeros((k+1, n), dtype=dtype)
|
660 |
+
for row in range(k+1):
|
661 |
+
Ab[-row-1, row:] = diag(A, k=row)
|
662 |
+
func, = get_blas_funcs(('tbsv',), dtype=dtype)
|
663 |
+
|
664 |
+
y1 = func(k=k, a=Ab, x=x)
|
665 |
+
y2 = solve(A, x)
|
666 |
+
assert_array_almost_equal(y1, y2)
|
667 |
+
|
668 |
+
y1 = func(k=k, a=Ab, x=x, diag=1)
|
669 |
+
A[arange(n), arange(n)] = dtype(1)
|
670 |
+
y2 = solve(A, x)
|
671 |
+
assert_array_almost_equal(y1, y2)
|
672 |
+
|
673 |
+
y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
|
674 |
+
y2 = solve(A.T, x)
|
675 |
+
assert_array_almost_equal(y1, y2)
|
676 |
+
|
677 |
+
y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
|
678 |
+
y2 = solve(A.conj().T, x)
|
679 |
+
assert_array_almost_equal(y1, y2)
|
680 |
+
|
681 |
+
def test_tpmv(self):
|
682 |
+
seed(1234)
|
683 |
+
for ind, dtype in enumerate(DTYPES):
|
684 |
+
n = 10
|
685 |
+
x = rand(n).astype(dtype)
|
686 |
+
# Upper triangular array
|
687 |
+
A = triu(rand(n, n)) if ind < 2 else triu(rand(n, n)+rand(n, n)*1j)
|
688 |
+
# Form the packed storage
|
689 |
+
c, r = tril_indices(n)
|
690 |
+
Ap = A[r, c]
|
691 |
+
func, = get_blas_funcs(('tpmv',), dtype=dtype)
|
692 |
+
|
693 |
+
y1 = func(n=n, ap=Ap, x=x)
|
694 |
+
y2 = A.dot(x)
|
695 |
+
assert_array_almost_equal(y1, y2)
|
696 |
+
|
697 |
+
y1 = func(n=n, ap=Ap, x=x, diag=1)
|
698 |
+
A[arange(n), arange(n)] = dtype(1)
|
699 |
+
y2 = A.dot(x)
|
700 |
+
assert_array_almost_equal(y1, y2)
|
701 |
+
|
702 |
+
y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
|
703 |
+
y2 = A.T.dot(x)
|
704 |
+
assert_array_almost_equal(y1, y2)
|
705 |
+
|
706 |
+
y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
|
707 |
+
y2 = A.conj().T.dot(x)
|
708 |
+
assert_array_almost_equal(y1, y2)
|
709 |
+
|
710 |
+
def test_tpsv(self):
|
711 |
+
seed(1234)
|
712 |
+
for ind, dtype in enumerate(DTYPES):
|
713 |
+
n = 10
|
714 |
+
x = rand(n).astype(dtype)
|
715 |
+
# Upper triangular array
|
716 |
+
A = triu(rand(n, n)) if ind < 2 else triu(rand(n, n)+rand(n, n)*1j)
|
717 |
+
A += eye(n)
|
718 |
+
# Form the packed storage
|
719 |
+
c, r = tril_indices(n)
|
720 |
+
Ap = A[r, c]
|
721 |
+
func, = get_blas_funcs(('tpsv',), dtype=dtype)
|
722 |
+
|
723 |
+
y1 = func(n=n, ap=Ap, x=x)
|
724 |
+
y2 = solve(A, x)
|
725 |
+
assert_array_almost_equal(y1, y2)
|
726 |
+
|
727 |
+
y1 = func(n=n, ap=Ap, x=x, diag=1)
|
728 |
+
A[arange(n), arange(n)] = dtype(1)
|
729 |
+
y2 = solve(A, x)
|
730 |
+
assert_array_almost_equal(y1, y2)
|
731 |
+
|
732 |
+
y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
|
733 |
+
y2 = solve(A.T, x)
|
734 |
+
assert_array_almost_equal(y1, y2)
|
735 |
+
|
736 |
+
y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
|
737 |
+
y2 = solve(A.conj().T, x)
|
738 |
+
assert_array_almost_equal(y1, y2)
|
739 |
+
|
740 |
+
def test_trmv(self):
|
741 |
+
seed(1234)
|
742 |
+
for ind, dtype in enumerate(DTYPES):
|
743 |
+
n = 3
|
744 |
+
A = (rand(n, n)+eye(n)).astype(dtype)
|
745 |
+
x = rand(3).astype(dtype)
|
746 |
+
func, = get_blas_funcs(('trmv',), dtype=dtype)
|
747 |
+
|
748 |
+
y1 = func(a=A, x=x)
|
749 |
+
y2 = triu(A).dot(x)
|
750 |
+
assert_array_almost_equal(y1, y2)
|
751 |
+
|
752 |
+
y1 = func(a=A, x=x, diag=1)
|
753 |
+
A[arange(n), arange(n)] = dtype(1)
|
754 |
+
y2 = triu(A).dot(x)
|
755 |
+
assert_array_almost_equal(y1, y2)
|
756 |
+
|
757 |
+
y1 = func(a=A, x=x, diag=1, trans=1)
|
758 |
+
y2 = triu(A).T.dot(x)
|
759 |
+
assert_array_almost_equal(y1, y2)
|
760 |
+
|
761 |
+
y1 = func(a=A, x=x, diag=1, trans=2)
|
762 |
+
y2 = triu(A).conj().T.dot(x)
|
763 |
+
assert_array_almost_equal(y1, y2)
|
764 |
+
|
765 |
+
def test_trsv(self):
|
766 |
+
seed(1234)
|
767 |
+
for ind, dtype in enumerate(DTYPES):
|
768 |
+
n = 15
|
769 |
+
A = (rand(n, n)+eye(n)).astype(dtype)
|
770 |
+
x = rand(n).astype(dtype)
|
771 |
+
func, = get_blas_funcs(('trsv',), dtype=dtype)
|
772 |
+
|
773 |
+
y1 = func(a=A, x=x)
|
774 |
+
y2 = solve(triu(A), x)
|
775 |
+
assert_array_almost_equal(y1, y2)
|
776 |
+
|
777 |
+
y1 = func(a=A, x=x, lower=1)
|
778 |
+
y2 = solve(tril(A), x)
|
779 |
+
assert_array_almost_equal(y1, y2)
|
780 |
+
|
781 |
+
y1 = func(a=A, x=x, diag=1)
|
782 |
+
A[arange(n), arange(n)] = dtype(1)
|
783 |
+
y2 = solve(triu(A), x)
|
784 |
+
assert_array_almost_equal(y1, y2)
|
785 |
+
|
786 |
+
y1 = func(a=A, x=x, diag=1, trans=1)
|
787 |
+
y2 = solve(triu(A).T, x)
|
788 |
+
assert_array_almost_equal(y1, y2)
|
789 |
+
|
790 |
+
y1 = func(a=A, x=x, diag=1, trans=2)
|
791 |
+
y2 = solve(triu(A).conj().T, x)
|
792 |
+
assert_array_almost_equal(y1, y2)
|
793 |
+
|
794 |
+
|
795 |
+
class TestFBLAS3Simple:
|
796 |
+
|
797 |
+
def test_gemm(self):
|
798 |
+
for p in 'sd':
|
799 |
+
f = getattr(fblas, p+'gemm', None)
|
800 |
+
if f is None:
|
801 |
+
continue
|
802 |
+
assert_array_almost_equal(f(3, [3], [-4]), [[-36]])
|
803 |
+
assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21])
|
804 |
+
for p in 'cz':
|
805 |
+
f = getattr(fblas, p+'gemm', None)
|
806 |
+
if f is None:
|
807 |
+
continue
|
808 |
+
assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-36j]])
|
809 |
+
assert_array_almost_equal(f(3j, [3-4j], [-4], 3, [5j]), [-48-21j])
|
810 |
+
|
811 |
+
|
812 |
+
def _get_func(func, ps='sdzc'):
|
813 |
+
"""Just a helper: return a specified BLAS function w/typecode."""
|
814 |
+
for p in ps:
|
815 |
+
f = getattr(fblas, p+func, None)
|
816 |
+
if f is None:
|
817 |
+
continue
|
818 |
+
yield f
|
819 |
+
|
820 |
+
|
821 |
+
class TestBLAS3Symm:
|
822 |
+
|
823 |
+
def setup_method(self):
|
824 |
+
self.a = np.array([[1., 2.],
|
825 |
+
[0., 1.]])
|
826 |
+
self.b = np.array([[1., 0., 3.],
|
827 |
+
[0., -1., 2.]])
|
828 |
+
self.c = np.ones((2, 3))
|
829 |
+
self.t = np.array([[2., -1., 8.],
|
830 |
+
[3., 0., 9.]])
|
831 |
+
|
832 |
+
def test_symm(self):
|
833 |
+
for f in _get_func('symm'):
|
834 |
+
res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
|
835 |
+
assert_array_almost_equal(res, self.t)
|
836 |
+
|
837 |
+
res = f(a=self.a.T, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
|
838 |
+
assert_array_almost_equal(res, self.t)
|
839 |
+
|
840 |
+
res = f(a=self.a, b=self.b.T, side=1, c=self.c.T,
|
841 |
+
alpha=1., beta=1.)
|
842 |
+
assert_array_almost_equal(res, self.t.T)
|
843 |
+
|
844 |
+
def test_summ_wrong_side(self):
|
845 |
+
f = getattr(fblas, 'dsymm', None)
|
846 |
+
if f is not None:
|
847 |
+
assert_raises(Exception, f, **{'a': self.a, 'b': self.b,
|
848 |
+
'alpha': 1, 'side': 1})
|
849 |
+
# `side=1` means C <- B*A, hence shapes of A and B are to be
|
850 |
+
# compatible. Otherwise, f2py exception is raised
|
851 |
+
|
852 |
+
def test_symm_wrong_uplo(self):
|
853 |
+
"""SYMM only considers the upper/lower part of A. Hence setting
|
854 |
+
wrong value for `lower` (default is lower=0, meaning upper triangle)
|
855 |
+
gives a wrong result.
|
856 |
+
"""
|
857 |
+
f = getattr(fblas, 'dsymm', None)
|
858 |
+
if f is not None:
|
859 |
+
res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
|
860 |
+
assert np.allclose(res, self.t)
|
861 |
+
|
862 |
+
res = f(a=self.a, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
|
863 |
+
assert not np.allclose(res, self.t)
|
864 |
+
|
865 |
+
|
866 |
+
class TestBLAS3Syrk:
|
867 |
+
def setup_method(self):
|
868 |
+
self.a = np.array([[1., 0.],
|
869 |
+
[0., -2.],
|
870 |
+
[2., 3.]])
|
871 |
+
self.t = np.array([[1., 0., 2.],
|
872 |
+
[0., 4., -6.],
|
873 |
+
[2., -6., 13.]])
|
874 |
+
self.tt = np.array([[5., 6.],
|
875 |
+
[6., 13.]])
|
876 |
+
|
877 |
+
def test_syrk(self):
|
878 |
+
for f in _get_func('syrk'):
|
879 |
+
c = f(a=self.a, alpha=1.)
|
880 |
+
assert_array_almost_equal(np.triu(c), np.triu(self.t))
|
881 |
+
|
882 |
+
c = f(a=self.a, alpha=1., lower=1)
|
883 |
+
assert_array_almost_equal(np.tril(c), np.tril(self.t))
|
884 |
+
|
885 |
+
c0 = np.ones(self.t.shape)
|
886 |
+
c = f(a=self.a, alpha=1., beta=1., c=c0)
|
887 |
+
assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
|
888 |
+
|
889 |
+
c = f(a=self.a, alpha=1., trans=1)
|
890 |
+
assert_array_almost_equal(np.triu(c), np.triu(self.tt))
|
891 |
+
|
892 |
+
# prints '0-th dimension must be fixed to 3 but got 5',
|
893 |
+
# FIXME: suppress?
|
894 |
+
# FIXME: how to catch the _fblas.error?
|
895 |
+
def test_syrk_wrong_c(self):
|
896 |
+
f = getattr(fblas, 'dsyrk', None)
|
897 |
+
if f is not None:
|
898 |
+
assert_raises(Exception, f, **{'a': self.a, 'alpha': 1.,
|
899 |
+
'c': np.ones((5, 8))})
|
900 |
+
# if C is supplied, it must have compatible dimensions
|
901 |
+
|
902 |
+
|
903 |
+
class TestBLAS3Syr2k:
|
904 |
+
def setup_method(self):
|
905 |
+
self.a = np.array([[1., 0.],
|
906 |
+
[0., -2.],
|
907 |
+
[2., 3.]])
|
908 |
+
self.b = np.array([[0., 1.],
|
909 |
+
[1., 0.],
|
910 |
+
[0, 1.]])
|
911 |
+
self.t = np.array([[0., -1., 3.],
|
912 |
+
[-1., 0., 0.],
|
913 |
+
[3., 0., 6.]])
|
914 |
+
self.tt = np.array([[0., 1.],
|
915 |
+
[1., 6]])
|
916 |
+
|
917 |
+
def test_syr2k(self):
|
918 |
+
for f in _get_func('syr2k'):
|
919 |
+
c = f(a=self.a, b=self.b, alpha=1.)
|
920 |
+
assert_array_almost_equal(np.triu(c), np.triu(self.t))
|
921 |
+
|
922 |
+
c = f(a=self.a, b=self.b, alpha=1., lower=1)
|
923 |
+
assert_array_almost_equal(np.tril(c), np.tril(self.t))
|
924 |
+
|
925 |
+
c0 = np.ones(self.t.shape)
|
926 |
+
c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0)
|
927 |
+
assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
|
928 |
+
|
929 |
+
c = f(a=self.a, b=self.b, alpha=1., trans=1)
|
930 |
+
assert_array_almost_equal(np.triu(c), np.triu(self.tt))
|
931 |
+
|
932 |
+
# prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress?
|
933 |
+
def test_syr2k_wrong_c(self):
|
934 |
+
f = getattr(fblas, 'dsyr2k', None)
|
935 |
+
if f is not None:
|
936 |
+
assert_raises(Exception, f, **{'a': self.a,
|
937 |
+
'b': self.b,
|
938 |
+
'alpha': 1.,
|
939 |
+
'c': np.zeros((15, 8))})
|
940 |
+
# if C is supplied, it must have compatible dimensions
|
941 |
+
|
942 |
+
|
943 |
+
class TestSyHe:
|
944 |
+
"""Quick and simple tests for (zc)-symm, syrk, syr2k."""
|
945 |
+
|
946 |
+
def setup_method(self):
|
947 |
+
self.sigma_y = np.array([[0., -1.j],
|
948 |
+
[1.j, 0.]])
|
949 |
+
|
950 |
+
def test_symm_zc(self):
|
951 |
+
for f in _get_func('symm', 'zc'):
|
952 |
+
# NB: a is symmetric w/upper diag of ONLY
|
953 |
+
res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
|
954 |
+
assert_array_almost_equal(np.triu(res), np.diag([1, -1]))
|
955 |
+
|
956 |
+
def test_hemm_zc(self):
|
957 |
+
for f in _get_func('hemm', 'zc'):
|
958 |
+
# NB: a is hermitian w/upper diag of ONLY
|
959 |
+
res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
|
960 |
+
assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
|
961 |
+
|
962 |
+
def test_syrk_zr(self):
|
963 |
+
for f in _get_func('syrk', 'zc'):
|
964 |
+
res = f(a=self.sigma_y, alpha=1.)
|
965 |
+
assert_array_almost_equal(np.triu(res), np.diag([-1, -1]))
|
966 |
+
|
967 |
+
def test_herk_zr(self):
|
968 |
+
for f in _get_func('herk', 'zc'):
|
969 |
+
res = f(a=self.sigma_y, alpha=1.)
|
970 |
+
assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
|
971 |
+
|
972 |
+
def test_syr2k_zr(self):
|
973 |
+
for f in _get_func('syr2k', 'zc'):
|
974 |
+
res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
|
975 |
+
assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1]))
|
976 |
+
|
977 |
+
def test_her2k_zr(self):
|
978 |
+
for f in _get_func('her2k', 'zc'):
|
979 |
+
res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
|
980 |
+
assert_array_almost_equal(np.triu(res), 2.*np.diag([1, 1]))
|
981 |
+
|
982 |
+
|
983 |
+
class TestTRMM:
|
984 |
+
"""Quick and simple tests for dtrmm."""
|
985 |
+
|
986 |
+
def setup_method(self):
|
987 |
+
self.a = np.array([[1., 2., ],
|
988 |
+
[-2., 1.]])
|
989 |
+
self.b = np.array([[3., 4., -1.],
|
990 |
+
[5., 6., -2.]])
|
991 |
+
|
992 |
+
self.a2 = np.array([[1, 1, 2, 3],
|
993 |
+
[0, 1, 4, 5],
|
994 |
+
[0, 0, 1, 6],
|
995 |
+
[0, 0, 0, 1]], order="f")
|
996 |
+
self.b2 = np.array([[1, 4], [2, 5], [3, 6], [7, 8], [9, 10]],
|
997 |
+
order="f")
|
998 |
+
|
999 |
+
@pytest.mark.parametrize("dtype_", DTYPES)
|
1000 |
+
def test_side(self, dtype_):
|
1001 |
+
trmm = get_blas_funcs("trmm", dtype=dtype_)
|
1002 |
+
# Provide large A array that works for side=1 but not 0 (see gh-10841)
|
1003 |
+
assert_raises(Exception, trmm, 1.0, self.a2, self.b2)
|
1004 |
+
res = trmm(1.0, self.a2.astype(dtype_), self.b2.astype(dtype_),
|
1005 |
+
side=1)
|
1006 |
+
k = self.b2.shape[1]
|
1007 |
+
assert_allclose(res, self.b2 @ self.a2[:k, :k], rtol=0.,
|
1008 |
+
atol=100*np.finfo(dtype_).eps)
|
1009 |
+
|
1010 |
+
def test_ab(self):
|
1011 |
+
f = getattr(fblas, 'dtrmm', None)
|
1012 |
+
if f is not None:
|
1013 |
+
result = f(1., self.a, self.b)
|
1014 |
+
# default a is upper triangular
|
1015 |
+
expected = np.array([[13., 16., -5.],
|
1016 |
+
[5., 6., -2.]])
|
1017 |
+
assert_array_almost_equal(result, expected)
|
1018 |
+
|
1019 |
+
def test_ab_lower(self):
|
1020 |
+
f = getattr(fblas, 'dtrmm', None)
|
1021 |
+
if f is not None:
|
1022 |
+
result = f(1., self.a, self.b, lower=True)
|
1023 |
+
expected = np.array([[3., 4., -1.],
|
1024 |
+
[-1., -2., 0.]]) # now a is lower triangular
|
1025 |
+
assert_array_almost_equal(result, expected)
|
1026 |
+
|
1027 |
+
def test_b_overwrites(self):
|
1028 |
+
# BLAS dtrmm modifies B argument in-place.
|
1029 |
+
# Here the default is to copy, but this can be overridden
|
1030 |
+
f = getattr(fblas, 'dtrmm', None)
|
1031 |
+
if f is not None:
|
1032 |
+
for overwr in [True, False]:
|
1033 |
+
bcopy = self.b.copy()
|
1034 |
+
result = f(1., self.a, bcopy, overwrite_b=overwr)
|
1035 |
+
# C-contiguous arrays are copied
|
1036 |
+
assert_(bcopy.flags.f_contiguous is False and
|
1037 |
+
np.may_share_memory(bcopy, result) is False)
|
1038 |
+
assert_equal(bcopy, self.b)
|
1039 |
+
|
1040 |
+
bcopy = np.asfortranarray(self.b.copy()) # or just transpose it
|
1041 |
+
result = f(1., self.a, bcopy, overwrite_b=True)
|
1042 |
+
assert_(bcopy.flags.f_contiguous is True and
|
1043 |
+
np.may_share_memory(bcopy, result) is True)
|
1044 |
+
assert_array_almost_equal(bcopy, result)
|
1045 |
+
|
1046 |
+
|
1047 |
+
def test_trsm():
|
1048 |
+
seed(1234)
|
1049 |
+
for ind, dtype in enumerate(DTYPES):
|
1050 |
+
tol = np.finfo(dtype).eps*1000
|
1051 |
+
func, = get_blas_funcs(('trsm',), dtype=dtype)
|
1052 |
+
|
1053 |
+
# Test protection against size mismatches
|
1054 |
+
A = rand(4, 5).astype(dtype)
|
1055 |
+
B = rand(4, 4).astype(dtype)
|
1056 |
+
alpha = dtype(1)
|
1057 |
+
assert_raises(Exception, func, alpha, A, B)
|
1058 |
+
assert_raises(Exception, func, alpha, A.T, B)
|
1059 |
+
|
1060 |
+
n = 8
|
1061 |
+
m = 7
|
1062 |
+
alpha = dtype(-2.5)
|
1063 |
+
A = (rand(m, m) if ind < 2 else rand(m, m) + rand(m, m)*1j) + eye(m)
|
1064 |
+
A = A.astype(dtype)
|
1065 |
+
Au = triu(A)
|
1066 |
+
Al = tril(A)
|
1067 |
+
B1 = rand(m, n).astype(dtype)
|
1068 |
+
B2 = rand(n, m).astype(dtype)
|
1069 |
+
|
1070 |
+
x1 = func(alpha=alpha, a=A, b=B1)
|
1071 |
+
assert_equal(B1.shape, x1.shape)
|
1072 |
+
x2 = solve(Au, alpha*B1)
|
1073 |
+
assert_allclose(x1, x2, atol=tol)
|
1074 |
+
|
1075 |
+
x1 = func(alpha=alpha, a=A, b=B1, trans_a=1)
|
1076 |
+
x2 = solve(Au.T, alpha*B1)
|
1077 |
+
assert_allclose(x1, x2, atol=tol)
|
1078 |
+
|
1079 |
+
x1 = func(alpha=alpha, a=A, b=B1, trans_a=2)
|
1080 |
+
x2 = solve(Au.conj().T, alpha*B1)
|
1081 |
+
assert_allclose(x1, x2, atol=tol)
|
1082 |
+
|
1083 |
+
x1 = func(alpha=alpha, a=A, b=B1, diag=1)
|
1084 |
+
Au[arange(m), arange(m)] = dtype(1)
|
1085 |
+
x2 = solve(Au, alpha*B1)
|
1086 |
+
assert_allclose(x1, x2, atol=tol)
|
1087 |
+
|
1088 |
+
x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1)
|
1089 |
+
x2 = solve(Au.conj().T, alpha*B2.conj().T)
|
1090 |
+
assert_allclose(x1, x2.conj().T, atol=tol)
|
1091 |
+
|
1092 |
+
x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1, lower=1)
|
1093 |
+
Al[arange(m), arange(m)] = dtype(1)
|
1094 |
+
x2 = solve(Al.conj().T, alpha*B2.conj().T)
|
1095 |
+
assert_allclose(x1, x2.conj().T, atol=tol)
|
1096 |
+
|
1097 |
+
|
1098 |
+
@pytest.mark.xfail(run=False,
|
1099 |
+
reason="gh-16930")
|
1100 |
+
def test_gh_169309():
|
1101 |
+
x = np.repeat(10, 9)
|
1102 |
+
actual = scipy.linalg.blas.dnrm2(x, 5, 3, -1)
|
1103 |
+
expected = math.sqrt(500)
|
1104 |
+
assert_allclose(actual, expected)
|
1105 |
+
|
1106 |
+
|
1107 |
+
def test_dnrm2_neg_incx():
|
1108 |
+
# check that dnrm2(..., incx < 0) raises
|
1109 |
+
# XXX: remove the test after the lowest supported BLAS implements
|
1110 |
+
# negative incx (new in LAPACK 3.10)
|
1111 |
+
x = np.repeat(10, 9)
|
1112 |
+
incx = -1
|
1113 |
+
with assert_raises(fblas.__fblas_error):
|
1114 |
+
scipy.linalg.blas.dnrm2(x, 5, 3, incx)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from numpy.testing import (assert_allclose,
|
3 |
+
assert_equal)
|
4 |
+
import scipy.linalg.cython_blas as blas
|
5 |
+
|
6 |
+
class TestDGEMM:
|
7 |
+
|
8 |
+
def test_transposes(self):
|
9 |
+
|
10 |
+
a = np.arange(12, dtype='d').reshape((3, 4))[:2,:2]
|
11 |
+
b = np.arange(1, 13, dtype='d').reshape((4, 3))[:2,:2]
|
12 |
+
c = np.empty((2, 4))[:2,:2]
|
13 |
+
|
14 |
+
blas._test_dgemm(1., a, b, 0., c)
|
15 |
+
assert_allclose(c, a.dot(b))
|
16 |
+
|
17 |
+
blas._test_dgemm(1., a.T, b, 0., c)
|
18 |
+
assert_allclose(c, a.T.dot(b))
|
19 |
+
|
20 |
+
blas._test_dgemm(1., a, b.T, 0., c)
|
21 |
+
assert_allclose(c, a.dot(b.T))
|
22 |
+
|
23 |
+
blas._test_dgemm(1., a.T, b.T, 0., c)
|
24 |
+
assert_allclose(c, a.T.dot(b.T))
|
25 |
+
|
26 |
+
blas._test_dgemm(1., a, b, 0., c.T)
|
27 |
+
assert_allclose(c, a.dot(b).T)
|
28 |
+
|
29 |
+
blas._test_dgemm(1., a.T, b, 0., c.T)
|
30 |
+
assert_allclose(c, a.T.dot(b).T)
|
31 |
+
|
32 |
+
blas._test_dgemm(1., a, b.T, 0., c.T)
|
33 |
+
assert_allclose(c, a.dot(b.T).T)
|
34 |
+
|
35 |
+
blas._test_dgemm(1., a.T, b.T, 0., c.T)
|
36 |
+
assert_allclose(c, a.T.dot(b.T).T)
|
37 |
+
|
38 |
+
def test_shapes(self):
|
39 |
+
a = np.arange(6, dtype='d').reshape((3, 2))
|
40 |
+
b = np.arange(-6, 2, dtype='d').reshape((2, 4))
|
41 |
+
c = np.empty((3, 4))
|
42 |
+
|
43 |
+
blas._test_dgemm(1., a, b, 0., c)
|
44 |
+
assert_allclose(c, a.dot(b))
|
45 |
+
|
46 |
+
blas._test_dgemm(1., b.T, a.T, 0., c.T)
|
47 |
+
assert_allclose(c, b.T.dot(a.T).T)
|
48 |
+
|
49 |
+
class TestWfuncPointers:
|
50 |
+
""" Test the function pointers that are expected to fail on
|
51 |
+
Mac OS X without the additional entry statement in their definitions
|
52 |
+
in fblas_l1.pyf.src. """
|
53 |
+
|
54 |
+
def test_complex_args(self):
|
55 |
+
|
56 |
+
cx = np.array([.5 + 1.j, .25 - .375j, 12.5 - 4.j], np.complex64)
|
57 |
+
cy = np.array([.8 + 2.j, .875 - .625j, -1. + 2.j], np.complex64)
|
58 |
+
|
59 |
+
assert_allclose(blas._test_cdotc(cx, cy),
|
60 |
+
-17.6468753815+21.3718757629j)
|
61 |
+
assert_allclose(blas._test_cdotu(cx, cy),
|
62 |
+
-6.11562538147+30.3156242371j)
|
63 |
+
|
64 |
+
assert_equal(blas._test_icamax(cx), 3)
|
65 |
+
|
66 |
+
assert_allclose(blas._test_scasum(cx), 18.625)
|
67 |
+
assert_allclose(blas._test_scnrm2(cx), 13.1796483994)
|
68 |
+
|
69 |
+
assert_allclose(blas._test_cdotc(cx[::2], cy[::2]),
|
70 |
+
-18.1000003815+21.2000007629j)
|
71 |
+
assert_allclose(blas._test_cdotu(cx[::2], cy[::2]),
|
72 |
+
-6.10000038147+30.7999992371j)
|
73 |
+
assert_allclose(blas._test_scasum(cx[::2]), 18.)
|
74 |
+
assert_allclose(blas._test_scnrm2(cx[::2]), 13.1719398499)
|
75 |
+
|
76 |
+
def test_double_args(self):
|
77 |
+
|
78 |
+
x = np.array([5., -3, -.5], np.float64)
|
79 |
+
y = np.array([2, 1, .5], np.float64)
|
80 |
+
|
81 |
+
assert_allclose(blas._test_dasum(x), 8.5)
|
82 |
+
assert_allclose(blas._test_ddot(x, y), 6.75)
|
83 |
+
assert_allclose(blas._test_dnrm2(x), 5.85234975815)
|
84 |
+
|
85 |
+
assert_allclose(blas._test_dasum(x[::2]), 5.5)
|
86 |
+
assert_allclose(blas._test_ddot(x[::2], y[::2]), 9.75)
|
87 |
+
assert_allclose(blas._test_dnrm2(x[::2]), 5.0249376297)
|
88 |
+
|
89 |
+
assert_equal(blas._test_idamax(x), 1)
|
90 |
+
|
91 |
+
def test_float_args(self):
|
92 |
+
|
93 |
+
x = np.array([5., -3, -.5], np.float32)
|
94 |
+
y = np.array([2, 1, .5], np.float32)
|
95 |
+
|
96 |
+
assert_equal(blas._test_isamax(x), 1)
|
97 |
+
|
98 |
+
assert_allclose(blas._test_sasum(x), 8.5)
|
99 |
+
assert_allclose(blas._test_sdot(x, y), 6.75)
|
100 |
+
assert_allclose(blas._test_snrm2(x), 5.85234975815)
|
101 |
+
|
102 |
+
assert_allclose(blas._test_sasum(x[::2]), 5.5)
|
103 |
+
assert_allclose(blas._test_sdot(x[::2], y[::2]), 9.75)
|
104 |
+
assert_allclose(blas._test_snrm2(x[::2]), 5.0249376297)
|
105 |
+
|
106 |
+
def test_double_complex_args(self):
|
107 |
+
|
108 |
+
cx = np.array([.5 + 1.j, .25 - .375j, 13. - 4.j], np.complex128)
|
109 |
+
cy = np.array([.875 + 2.j, .875 - .625j, -1. + 2.j], np.complex128)
|
110 |
+
|
111 |
+
assert_equal(blas._test_izamax(cx), 3)
|
112 |
+
|
113 |
+
assert_allclose(blas._test_zdotc(cx, cy), -18.109375+22.296875j)
|
114 |
+
assert_allclose(blas._test_zdotu(cx, cy), -6.578125+31.390625j)
|
115 |
+
|
116 |
+
assert_allclose(blas._test_zdotc(cx[::2], cy[::2]), -18.5625+22.125j)
|
117 |
+
assert_allclose(blas._test_zdotu(cx[::2], cy[::2]), -6.5625+31.875j)
|
118 |
+
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from numpy.testing import assert_allclose
|
2 |
+
from scipy.linalg import cython_lapack as cython_lapack
|
3 |
+
from scipy.linalg import lapack
|
4 |
+
|
5 |
+
|
6 |
+
class TestLamch:
|
7 |
+
|
8 |
+
def test_slamch(self):
|
9 |
+
for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
|
10 |
+
assert_allclose(cython_lapack._test_slamch(c),
|
11 |
+
lapack.slamch(c))
|
12 |
+
|
13 |
+
def test_dlamch(self):
|
14 |
+
for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
|
15 |
+
assert_allclose(cython_lapack._test_dlamch(c),
|
16 |
+
lapack.dlamch(c))
|
17 |
+
|
18 |
+
def test_complex_ladiv(self):
|
19 |
+
cx = .5 + 1.j
|
20 |
+
cy = .875 + 2.j
|
21 |
+
assert_allclose(cython_lapack._test_zladiv(cy, cx), 1.95+0.1j)
|
22 |
+
assert_allclose(cython_lapack._test_cladiv(cy, cx), 1.95+0.1j)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from scipy.linalg import bandwidth, issymmetric, ishermitian
|
3 |
+
import pytest
|
4 |
+
from pytest import raises
|
5 |
+
|
6 |
+
|
7 |
+
def test_bandwidth_dtypes():
|
8 |
+
n = 5
|
9 |
+
for t in np.typecodes['All']:
|
10 |
+
A = np.zeros([n, n], dtype=t)
|
11 |
+
if t in 'eUVOMm':
|
12 |
+
raises(TypeError, bandwidth, A)
|
13 |
+
elif t == 'G': # No-op test. On win these pass on others fail.
|
14 |
+
pass
|
15 |
+
else:
|
16 |
+
_ = bandwidth(A)
|
17 |
+
|
18 |
+
|
19 |
+
def test_bandwidth_non2d_input():
|
20 |
+
A = np.array([1, 2, 3])
|
21 |
+
raises(ValueError, bandwidth, A)
|
22 |
+
A = np.array([[[1, 2, 3], [4, 5, 6]]])
|
23 |
+
raises(ValueError, bandwidth, A)
|
24 |
+
|
25 |
+
|
26 |
+
@pytest.mark.parametrize('T', [x for x in np.typecodes['All']
|
27 |
+
if x not in 'eGUVOMm'])
|
28 |
+
def test_bandwidth_square_inputs(T):
|
29 |
+
n = 20
|
30 |
+
k = 4
|
31 |
+
R = np.zeros([n, n], dtype=T, order='F')
|
32 |
+
# form a banded matrix inplace
|
33 |
+
R[[x for x in range(n)], [x for x in range(n)]] = 1
|
34 |
+
R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1
|
35 |
+
R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1
|
36 |
+
R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1
|
37 |
+
assert bandwidth(R) == (k, k)
|
38 |
+
|
39 |
+
|
40 |
+
@pytest.mark.parametrize('T', [x for x in np.typecodes['All']
|
41 |
+
if x not in 'eGUVOMm'])
|
42 |
+
def test_bandwidth_rect_inputs(T):
|
43 |
+
n, m = 10, 20
|
44 |
+
k = 5
|
45 |
+
R = np.zeros([n, m], dtype=T, order='F')
|
46 |
+
# form a banded matrix inplace
|
47 |
+
R[[x for x in range(n)], [x for x in range(n)]] = 1
|
48 |
+
R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1
|
49 |
+
R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1
|
50 |
+
R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1
|
51 |
+
assert bandwidth(R) == (k, k)
|
52 |
+
|
53 |
+
|
54 |
+
def test_issymetric_ishermitian_dtypes():
|
55 |
+
n = 5
|
56 |
+
for t in np.typecodes['All']:
|
57 |
+
A = np.zeros([n, n], dtype=t)
|
58 |
+
if t in 'eUVOMm':
|
59 |
+
raises(TypeError, issymmetric, A)
|
60 |
+
raises(TypeError, ishermitian, A)
|
61 |
+
elif t == 'G': # No-op test. On win these pass on others fail.
|
62 |
+
pass
|
63 |
+
else:
|
64 |
+
assert issymmetric(A)
|
65 |
+
assert ishermitian(A)
|
66 |
+
|
67 |
+
|
68 |
+
def test_issymmetric_ishermitian_invalid_input():
|
69 |
+
A = np.array([1, 2, 3])
|
70 |
+
raises(ValueError, issymmetric, A)
|
71 |
+
raises(ValueError, ishermitian, A)
|
72 |
+
A = np.array([[[1, 2, 3], [4, 5, 6]]])
|
73 |
+
raises(ValueError, issymmetric, A)
|
74 |
+
raises(ValueError, ishermitian, A)
|
75 |
+
A = np.array([[1, 2, 3], [4, 5, 6]])
|
76 |
+
raises(ValueError, issymmetric, A)
|
77 |
+
raises(ValueError, ishermitian, A)
|
78 |
+
|
79 |
+
|
80 |
+
def test_issymetric_complex_decimals():
|
81 |
+
A = np.arange(1, 10).astype(complex).reshape(3, 3)
|
82 |
+
A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j
|
83 |
+
# make entries decimal
|
84 |
+
A /= np.pi
|
85 |
+
A = A + A.T
|
86 |
+
assert issymmetric(A)
|
87 |
+
|
88 |
+
|
89 |
+
def test_ishermitian_complex_decimals():
|
90 |
+
A = np.arange(1, 10).astype(complex).reshape(3, 3)
|
91 |
+
A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j
|
92 |
+
# make entries decimal
|
93 |
+
A /= np.pi
|
94 |
+
A = A + A.T.conj()
|
95 |
+
assert ishermitian(A)
|
96 |
+
|
97 |
+
|
98 |
+
def test_issymmetric_approximate_results():
|
99 |
+
n = 20
|
100 |
+
rng = np.random.RandomState(123456789)
|
101 |
+
x = rng.uniform(high=5., size=[n, n])
|
102 |
+
y = x @ x.T # symmetric
|
103 |
+
p = rng.standard_normal([n, n])
|
104 |
+
z = p @ y @ p.T
|
105 |
+
assert issymmetric(z, atol=1e-10)
|
106 |
+
assert issymmetric(z, atol=1e-10, rtol=0.)
|
107 |
+
assert issymmetric(z, atol=0., rtol=1e-12)
|
108 |
+
assert issymmetric(z, atol=1e-13, rtol=1e-12)
|
109 |
+
|
110 |
+
|
111 |
+
def test_ishermitian_approximate_results():
|
112 |
+
n = 20
|
113 |
+
rng = np.random.RandomState(987654321)
|
114 |
+
x = rng.uniform(high=5., size=[n, n])
|
115 |
+
y = x @ x.T # symmetric
|
116 |
+
p = rng.standard_normal([n, n]) + rng.standard_normal([n, n])*1j
|
117 |
+
z = p @ y @ p.conj().T
|
118 |
+
assert ishermitian(z, atol=1e-10)
|
119 |
+
assert ishermitian(z, atol=1e-10, rtol=0.)
|
120 |
+
assert ishermitian(z, atol=0., rtol=1e-12)
|
121 |
+
assert ishermitian(z, atol=1e-13, rtol=1e-12)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py
ADDED
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
from numpy.testing import assert_array_almost_equal, assert_array_equal
|
3 |
+
from pytest import raises as assert_raises
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
from numpy import array, transpose, dot, conjugate, zeros_like, empty
|
7 |
+
from numpy.random import random
|
8 |
+
from scipy.linalg import cholesky, cholesky_banded, cho_solve_banded, \
|
9 |
+
cho_factor, cho_solve
|
10 |
+
|
11 |
+
from scipy.linalg._testutils import assert_no_overwrite
|
12 |
+
|
13 |
+
|
14 |
+
class TestCholesky:
|
15 |
+
|
16 |
+
def test_simple(self):
|
17 |
+
a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
|
18 |
+
c = cholesky(a)
|
19 |
+
assert_array_almost_equal(dot(transpose(c), c), a)
|
20 |
+
c = transpose(c)
|
21 |
+
a = dot(c, transpose(c))
|
22 |
+
assert_array_almost_equal(cholesky(a, lower=1), c)
|
23 |
+
|
24 |
+
def test_check_finite(self):
|
25 |
+
a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
|
26 |
+
c = cholesky(a, check_finite=False)
|
27 |
+
assert_array_almost_equal(dot(transpose(c), c), a)
|
28 |
+
c = transpose(c)
|
29 |
+
a = dot(c, transpose(c))
|
30 |
+
assert_array_almost_equal(cholesky(a, lower=1, check_finite=False), c)
|
31 |
+
|
32 |
+
def test_simple_complex(self):
|
33 |
+
m = array([[3+1j, 3+4j, 5], [0, 2+2j, 2+7j], [0, 0, 7+4j]])
|
34 |
+
a = dot(transpose(conjugate(m)), m)
|
35 |
+
c = cholesky(a)
|
36 |
+
a1 = dot(transpose(conjugate(c)), c)
|
37 |
+
assert_array_almost_equal(a, a1)
|
38 |
+
c = transpose(c)
|
39 |
+
a = dot(c, transpose(conjugate(c)))
|
40 |
+
assert_array_almost_equal(cholesky(a, lower=1), c)
|
41 |
+
|
42 |
+
def test_random(self):
|
43 |
+
n = 20
|
44 |
+
for k in range(2):
|
45 |
+
m = random([n, n])
|
46 |
+
for i in range(n):
|
47 |
+
m[i, i] = 20*(.1+m[i, i])
|
48 |
+
a = dot(transpose(m), m)
|
49 |
+
c = cholesky(a)
|
50 |
+
a1 = dot(transpose(c), c)
|
51 |
+
assert_array_almost_equal(a, a1)
|
52 |
+
c = transpose(c)
|
53 |
+
a = dot(c, transpose(c))
|
54 |
+
assert_array_almost_equal(cholesky(a, lower=1), c)
|
55 |
+
|
56 |
+
def test_random_complex(self):
|
57 |
+
n = 20
|
58 |
+
for k in range(2):
|
59 |
+
m = random([n, n])+1j*random([n, n])
|
60 |
+
for i in range(n):
|
61 |
+
m[i, i] = 20*(.1+abs(m[i, i]))
|
62 |
+
a = dot(transpose(conjugate(m)), m)
|
63 |
+
c = cholesky(a)
|
64 |
+
a1 = dot(transpose(conjugate(c)), c)
|
65 |
+
assert_array_almost_equal(a, a1)
|
66 |
+
c = transpose(c)
|
67 |
+
a = dot(c, transpose(conjugate(c)))
|
68 |
+
assert_array_almost_equal(cholesky(a, lower=1), c)
|
69 |
+
|
70 |
+
@pytest.mark.xslow
|
71 |
+
def test_int_overflow(self):
|
72 |
+
# regression test for
|
73 |
+
# https://github.com/scipy/scipy/issues/17436
|
74 |
+
# the problem was an int overflow in zeroing out
|
75 |
+
# the unused triangular part
|
76 |
+
n = 47_000
|
77 |
+
x = np.eye(n, dtype=np.float64, order='F')
|
78 |
+
x[:4, :4] = np.array([[4, -2, 3, -1],
|
79 |
+
[-2, 4, -3, 1],
|
80 |
+
[3, -3, 5, 0],
|
81 |
+
[-1, 1, 0, 5]])
|
82 |
+
|
83 |
+
cholesky(x, check_finite=False, overwrite_a=True) # should not segfault
|
84 |
+
|
85 |
+
|
86 |
+
class TestCholeskyBanded:
|
87 |
+
"""Tests for cholesky_banded() and cho_solve_banded."""
|
88 |
+
|
89 |
+
def test_check_finite(self):
|
90 |
+
# Symmetric positive definite banded matrix `a`
|
91 |
+
a = array([[4.0, 1.0, 0.0, 0.0],
|
92 |
+
[1.0, 4.0, 0.5, 0.0],
|
93 |
+
[0.0, 0.5, 4.0, 0.2],
|
94 |
+
[0.0, 0.0, 0.2, 4.0]])
|
95 |
+
# Banded storage form of `a`.
|
96 |
+
ab = array([[-1.0, 1.0, 0.5, 0.2],
|
97 |
+
[4.0, 4.0, 4.0, 4.0]])
|
98 |
+
c = cholesky_banded(ab, lower=False, check_finite=False)
|
99 |
+
ufac = zeros_like(a)
|
100 |
+
ufac[list(range(4)), list(range(4))] = c[-1]
|
101 |
+
ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
|
102 |
+
assert_array_almost_equal(a, dot(ufac.T, ufac))
|
103 |
+
|
104 |
+
b = array([0.0, 0.5, 4.2, 4.2])
|
105 |
+
x = cho_solve_banded((c, False), b, check_finite=False)
|
106 |
+
assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
|
107 |
+
|
108 |
+
def test_upper_real(self):
|
109 |
+
# Symmetric positive definite banded matrix `a`
|
110 |
+
a = array([[4.0, 1.0, 0.0, 0.0],
|
111 |
+
[1.0, 4.0, 0.5, 0.0],
|
112 |
+
[0.0, 0.5, 4.0, 0.2],
|
113 |
+
[0.0, 0.0, 0.2, 4.0]])
|
114 |
+
# Banded storage form of `a`.
|
115 |
+
ab = array([[-1.0, 1.0, 0.5, 0.2],
|
116 |
+
[4.0, 4.0, 4.0, 4.0]])
|
117 |
+
c = cholesky_banded(ab, lower=False)
|
118 |
+
ufac = zeros_like(a)
|
119 |
+
ufac[list(range(4)), list(range(4))] = c[-1]
|
120 |
+
ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
|
121 |
+
assert_array_almost_equal(a, dot(ufac.T, ufac))
|
122 |
+
|
123 |
+
b = array([0.0, 0.5, 4.2, 4.2])
|
124 |
+
x = cho_solve_banded((c, False), b)
|
125 |
+
assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
|
126 |
+
|
127 |
+
def test_upper_complex(self):
|
128 |
+
# Hermitian positive definite banded matrix `a`
|
129 |
+
a = array([[4.0, 1.0, 0.0, 0.0],
|
130 |
+
[1.0, 4.0, 0.5, 0.0],
|
131 |
+
[0.0, 0.5, 4.0, -0.2j],
|
132 |
+
[0.0, 0.0, 0.2j, 4.0]])
|
133 |
+
# Banded storage form of `a`.
|
134 |
+
ab = array([[-1.0, 1.0, 0.5, -0.2j],
|
135 |
+
[4.0, 4.0, 4.0, 4.0]])
|
136 |
+
c = cholesky_banded(ab, lower=False)
|
137 |
+
ufac = zeros_like(a)
|
138 |
+
ufac[list(range(4)), list(range(4))] = c[-1]
|
139 |
+
ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
|
140 |
+
assert_array_almost_equal(a, dot(ufac.conj().T, ufac))
|
141 |
+
|
142 |
+
b = array([0.0, 0.5, 4.0-0.2j, 0.2j + 4.0])
|
143 |
+
x = cho_solve_banded((c, False), b)
|
144 |
+
assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
|
145 |
+
|
146 |
+
def test_lower_real(self):
|
147 |
+
# Symmetric positive definite banded matrix `a`
|
148 |
+
a = array([[4.0, 1.0, 0.0, 0.0],
|
149 |
+
[1.0, 4.0, 0.5, 0.0],
|
150 |
+
[0.0, 0.5, 4.0, 0.2],
|
151 |
+
[0.0, 0.0, 0.2, 4.0]])
|
152 |
+
# Banded storage form of `a`.
|
153 |
+
ab = array([[4.0, 4.0, 4.0, 4.0],
|
154 |
+
[1.0, 0.5, 0.2, -1.0]])
|
155 |
+
c = cholesky_banded(ab, lower=True)
|
156 |
+
lfac = zeros_like(a)
|
157 |
+
lfac[list(range(4)), list(range(4))] = c[0]
|
158 |
+
lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3]
|
159 |
+
assert_array_almost_equal(a, dot(lfac, lfac.T))
|
160 |
+
|
161 |
+
b = array([0.0, 0.5, 4.2, 4.2])
|
162 |
+
x = cho_solve_banded((c, True), b)
|
163 |
+
assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
|
164 |
+
|
165 |
+
def test_lower_complex(self):
|
166 |
+
# Hermitian positive definite banded matrix `a`
|
167 |
+
a = array([[4.0, 1.0, 0.0, 0.0],
|
168 |
+
[1.0, 4.0, 0.5, 0.0],
|
169 |
+
[0.0, 0.5, 4.0, -0.2j],
|
170 |
+
[0.0, 0.0, 0.2j, 4.0]])
|
171 |
+
# Banded storage form of `a`.
|
172 |
+
ab = array([[4.0, 4.0, 4.0, 4.0],
|
173 |
+
[1.0, 0.5, 0.2j, -1.0]])
|
174 |
+
c = cholesky_banded(ab, lower=True)
|
175 |
+
lfac = zeros_like(a)
|
176 |
+
lfac[list(range(4)), list(range(4))] = c[0]
|
177 |
+
lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3]
|
178 |
+
assert_array_almost_equal(a, dot(lfac, lfac.conj().T))
|
179 |
+
|
180 |
+
b = array([0.0, 0.5j, 3.8j, 3.8])
|
181 |
+
x = cho_solve_banded((c, True), b)
|
182 |
+
assert_array_almost_equal(x, [0.0, 0.0, 1.0j, 1.0])
|
183 |
+
|
184 |
+
|
185 |
+
class TestOverwrite:
|
186 |
+
def test_cholesky(self):
|
187 |
+
assert_no_overwrite(cholesky, [(3, 3)])
|
188 |
+
|
189 |
+
def test_cho_factor(self):
|
190 |
+
assert_no_overwrite(cho_factor, [(3, 3)])
|
191 |
+
|
192 |
+
def test_cho_solve(self):
|
193 |
+
x = array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
|
194 |
+
xcho = cho_factor(x)
|
195 |
+
assert_no_overwrite(lambda b: cho_solve(xcho, b), [(3,)])
|
196 |
+
|
197 |
+
def test_cholesky_banded(self):
|
198 |
+
assert_no_overwrite(cholesky_banded, [(2, 3)])
|
199 |
+
|
200 |
+
def test_cho_solve_banded(self):
|
201 |
+
x = array([[0, -1, -1], [2, 2, 2]])
|
202 |
+
xcho = cholesky_banded(x)
|
203 |
+
assert_no_overwrite(lambda b: cho_solve_banded((xcho, False), b),
|
204 |
+
[(3,)])
|
205 |
+
|
206 |
+
|
207 |
+
class TestEmptyArray:
|
208 |
+
def test_cho_factor_empty_square(self):
|
209 |
+
a = empty((0, 0))
|
210 |
+
b = array([])
|
211 |
+
c = array([[]])
|
212 |
+
d = []
|
213 |
+
e = [[]]
|
214 |
+
|
215 |
+
x, _ = cho_factor(a)
|
216 |
+
assert_array_equal(x, a)
|
217 |
+
|
218 |
+
for x in ([b, c, d, e]):
|
219 |
+
assert_raises(ValueError, cho_factor, x)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
import numpy as np
|
3 |
+
from numpy.random import default_rng
|
4 |
+
from numpy.testing import assert_allclose
|
5 |
+
|
6 |
+
from scipy.linalg.lapack import _compute_lwork
|
7 |
+
from scipy.stats import ortho_group, unitary_group
|
8 |
+
from scipy.linalg import cossin, get_lapack_funcs
|
9 |
+
|
10 |
+
REAL_DTYPES = (np.float32, np.float64)
|
11 |
+
COMPLEX_DTYPES = (np.complex64, np.complex128)
|
12 |
+
DTYPES = REAL_DTYPES + COMPLEX_DTYPES
|
13 |
+
|
14 |
+
|
15 |
+
@pytest.mark.parametrize('dtype_', DTYPES)
|
16 |
+
@pytest.mark.parametrize('m, p, q',
|
17 |
+
[
|
18 |
+
(2, 1, 1),
|
19 |
+
(3, 2, 1),
|
20 |
+
(3, 1, 2),
|
21 |
+
(4, 2, 2),
|
22 |
+
(4, 1, 2),
|
23 |
+
(40, 12, 20),
|
24 |
+
(40, 30, 1),
|
25 |
+
(40, 1, 30),
|
26 |
+
(100, 50, 1),
|
27 |
+
(100, 50, 50),
|
28 |
+
])
|
29 |
+
@pytest.mark.parametrize('swap_sign', [True, False])
|
30 |
+
def test_cossin(dtype_, m, p, q, swap_sign):
|
31 |
+
rng = default_rng(1708093570726217)
|
32 |
+
if dtype_ in COMPLEX_DTYPES:
|
33 |
+
x = np.array(unitary_group.rvs(m, random_state=rng), dtype=dtype_)
|
34 |
+
else:
|
35 |
+
x = np.array(ortho_group.rvs(m, random_state=rng), dtype=dtype_)
|
36 |
+
|
37 |
+
u, cs, vh = cossin(x, p, q,
|
38 |
+
swap_sign=swap_sign)
|
39 |
+
assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps)
|
40 |
+
assert u.dtype == dtype_
|
41 |
+
# Test for float32 or float 64
|
42 |
+
assert cs.dtype == np.real(u).dtype
|
43 |
+
assert vh.dtype == dtype_
|
44 |
+
|
45 |
+
u, cs, vh = cossin([x[:p, :q], x[:p, q:], x[p:, :q], x[p:, q:]],
|
46 |
+
swap_sign=swap_sign)
|
47 |
+
assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps)
|
48 |
+
assert u.dtype == dtype_
|
49 |
+
assert cs.dtype == np.real(u).dtype
|
50 |
+
assert vh.dtype == dtype_
|
51 |
+
|
52 |
+
_, cs2, vh2 = cossin(x, p, q,
|
53 |
+
compute_u=False,
|
54 |
+
swap_sign=swap_sign)
|
55 |
+
assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
|
56 |
+
assert_allclose(vh, vh2, rtol=0., atol=10*np.finfo(dtype_).eps)
|
57 |
+
|
58 |
+
u2, cs2, _ = cossin(x, p, q,
|
59 |
+
compute_vh=False,
|
60 |
+
swap_sign=swap_sign)
|
61 |
+
assert_allclose(u, u2, rtol=0., atol=10*np.finfo(dtype_).eps)
|
62 |
+
assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
|
63 |
+
|
64 |
+
_, cs2, _ = cossin(x, p, q,
|
65 |
+
compute_u=False,
|
66 |
+
compute_vh=False,
|
67 |
+
swap_sign=swap_sign)
|
68 |
+
assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
|
69 |
+
|
70 |
+
|
71 |
+
def test_cossin_mixed_types():
|
72 |
+
rng = default_rng(1708093736390459)
|
73 |
+
x = np.array(ortho_group.rvs(4, random_state=rng), dtype=np.float64)
|
74 |
+
u, cs, vh = cossin([x[:2, :2],
|
75 |
+
np.array(x[:2, 2:], dtype=np.complex128),
|
76 |
+
x[2:, :2],
|
77 |
+
x[2:, 2:]])
|
78 |
+
|
79 |
+
assert u.dtype == np.complex128
|
80 |
+
assert cs.dtype == np.float64
|
81 |
+
assert vh.dtype == np.complex128
|
82 |
+
assert_allclose(x, u @ cs @ vh, rtol=0.,
|
83 |
+
atol=1e4 * np.finfo(np.complex128).eps)
|
84 |
+
|
85 |
+
|
86 |
+
def test_cossin_error_incorrect_subblocks():
|
87 |
+
with pytest.raises(ValueError, match="be due to missing p, q arguments."):
|
88 |
+
cossin(([1, 2], [3, 4, 5], [6, 7], [8, 9, 10]))
|
89 |
+
|
90 |
+
|
91 |
+
def test_cossin_error_empty_subblocks():
|
92 |
+
with pytest.raises(ValueError, match="x11.*empty"):
|
93 |
+
cossin(([], [], [], []))
|
94 |
+
with pytest.raises(ValueError, match="x12.*empty"):
|
95 |
+
cossin(([1, 2], [], [6, 7], [8, 9, 10]))
|
96 |
+
with pytest.raises(ValueError, match="x21.*empty"):
|
97 |
+
cossin(([1, 2], [3, 4, 5], [], [8, 9, 10]))
|
98 |
+
with pytest.raises(ValueError, match="x22.*empty"):
|
99 |
+
cossin(([1, 2], [3, 4, 5], [2], []))
|
100 |
+
|
101 |
+
|
102 |
+
def test_cossin_error_missing_partitioning():
|
103 |
+
with pytest.raises(ValueError, match=".*exactly four arrays.* got 2"):
|
104 |
+
cossin(unitary_group.rvs(2))
|
105 |
+
|
106 |
+
with pytest.raises(ValueError, match=".*might be due to missing p, q"):
|
107 |
+
cossin(unitary_group.rvs(4))
|
108 |
+
|
109 |
+
|
110 |
+
def test_cossin_error_non_iterable():
|
111 |
+
with pytest.raises(ValueError, match="containing the subblocks of X"):
|
112 |
+
cossin(12j)
|
113 |
+
|
114 |
+
|
115 |
+
def test_cossin_error_non_square():
|
116 |
+
with pytest.raises(ValueError, match="only supports square"):
|
117 |
+
cossin(np.array([[1, 2]]), 1, 1)
|
118 |
+
|
119 |
+
|
120 |
+
def test_cossin_error_partitioning():
|
121 |
+
x = np.array(ortho_group.rvs(4), dtype=np.float64)
|
122 |
+
with pytest.raises(ValueError, match="invalid p=0.*0<p<4.*"):
|
123 |
+
cossin(x, 0, 1)
|
124 |
+
with pytest.raises(ValueError, match="invalid p=4.*0<p<4.*"):
|
125 |
+
cossin(x, 4, 1)
|
126 |
+
with pytest.raises(ValueError, match="invalid q=-2.*0<q<4.*"):
|
127 |
+
cossin(x, 1, -2)
|
128 |
+
with pytest.raises(ValueError, match="invalid q=5.*0<q<4.*"):
|
129 |
+
cossin(x, 1, 5)
|
130 |
+
|
131 |
+
|
132 |
+
@pytest.mark.parametrize("dtype_", DTYPES)
|
133 |
+
def test_cossin_separate(dtype_):
|
134 |
+
rng = default_rng(1708093590167096)
|
135 |
+
m, p, q = 98, 37, 61
|
136 |
+
|
137 |
+
pfx = 'or' if dtype_ in REAL_DTYPES else 'un'
|
138 |
+
X = (ortho_group.rvs(m, random_state=rng) if pfx == 'or'
|
139 |
+
else unitary_group.rvs(m, random_state=rng))
|
140 |
+
X = np.array(X, dtype=dtype_)
|
141 |
+
|
142 |
+
drv, dlw = get_lapack_funcs((pfx + 'csd', pfx + 'csd_lwork'), [X])
|
143 |
+
lwval = _compute_lwork(dlw, m, p, q)
|
144 |
+
lwvals = {'lwork': lwval} if pfx == 'or' else dict(zip(['lwork',
|
145 |
+
'lrwork'],
|
146 |
+
lwval))
|
147 |
+
|
148 |
+
*_, theta, u1, u2, v1t, v2t, _ = \
|
149 |
+
drv(X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:], **lwvals)
|
150 |
+
|
151 |
+
(u1_2, u2_2), theta2, (v1t_2, v2t_2) = cossin(X, p, q, separate=True)
|
152 |
+
|
153 |
+
assert_allclose(u1_2, u1, rtol=0., atol=10*np.finfo(dtype_).eps)
|
154 |
+
assert_allclose(u2_2, u2, rtol=0., atol=10*np.finfo(dtype_).eps)
|
155 |
+
assert_allclose(v1t_2, v1t, rtol=0., atol=10*np.finfo(dtype_).eps)
|
156 |
+
assert_allclose(v2t_2, v2t, rtol=0., atol=10*np.finfo(dtype_).eps)
|
157 |
+
assert_allclose(theta2, theta, rtol=0., atol=10*np.finfo(dtype_).eps)
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from numpy.linalg import norm
|
3 |
+
from numpy.testing import (assert_, assert_allclose, assert_equal)
|
4 |
+
from scipy.linalg import polar, eigh
|
5 |
+
|
6 |
+
|
7 |
+
diag2 = np.array([[2, 0], [0, 3]])
|
8 |
+
a13 = np.array([[1, 2, 2]])
|
9 |
+
|
10 |
+
precomputed_cases = [
|
11 |
+
[[[0]], 'right', [[1]], [[0]]],
|
12 |
+
[[[0]], 'left', [[1]], [[0]]],
|
13 |
+
[[[9]], 'right', [[1]], [[9]]],
|
14 |
+
[[[9]], 'left', [[1]], [[9]]],
|
15 |
+
[diag2, 'right', np.eye(2), diag2],
|
16 |
+
[diag2, 'left', np.eye(2), diag2],
|
17 |
+
[a13, 'right', a13/norm(a13[0]), a13.T.dot(a13)/norm(a13[0])],
|
18 |
+
]
|
19 |
+
|
20 |
+
verify_cases = [
|
21 |
+
[[1, 2], [3, 4]],
|
22 |
+
[[1, 2, 3]],
|
23 |
+
[[1], [2], [3]],
|
24 |
+
[[1, 2, 3], [3, 4, 0]],
|
25 |
+
[[1, 2], [3, 4], [5, 5]],
|
26 |
+
[[1, 2], [3, 4+5j]],
|
27 |
+
[[1, 2, 3j]],
|
28 |
+
[[1], [2], [3j]],
|
29 |
+
[[1, 2, 3+2j], [3, 4-1j, -4j]],
|
30 |
+
[[1, 2], [3-2j, 4+0.5j], [5, 5]],
|
31 |
+
[[10000, 10, 1], [-1, 2, 3j], [0, 1, 2]],
|
32 |
+
]
|
33 |
+
|
34 |
+
|
35 |
+
def check_precomputed_polar(a, side, expected_u, expected_p):
|
36 |
+
# Compare the result of the polar decomposition to a
|
37 |
+
# precomputed result.
|
38 |
+
u, p = polar(a, side=side)
|
39 |
+
assert_allclose(u, expected_u, atol=1e-15)
|
40 |
+
assert_allclose(p, expected_p, atol=1e-15)
|
41 |
+
|
42 |
+
|
43 |
+
def verify_polar(a):
|
44 |
+
# Compute the polar decomposition, and then verify that
|
45 |
+
# the result has all the expected properties.
|
46 |
+
product_atol = np.sqrt(np.finfo(float).eps)
|
47 |
+
|
48 |
+
aa = np.asarray(a)
|
49 |
+
m, n = aa.shape
|
50 |
+
|
51 |
+
u, p = polar(a, side='right')
|
52 |
+
assert_equal(u.shape, (m, n))
|
53 |
+
assert_equal(p.shape, (n, n))
|
54 |
+
# a = up
|
55 |
+
assert_allclose(u.dot(p), a, atol=product_atol)
|
56 |
+
if m >= n:
|
57 |
+
assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15)
|
58 |
+
else:
|
59 |
+
assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15)
|
60 |
+
# p is Hermitian positive semidefinite.
|
61 |
+
assert_allclose(p.conj().T, p)
|
62 |
+
evals = eigh(p, eigvals_only=True)
|
63 |
+
nonzero_evals = evals[abs(evals) > 1e-14]
|
64 |
+
assert_((nonzero_evals >= 0).all())
|
65 |
+
|
66 |
+
u, p = polar(a, side='left')
|
67 |
+
assert_equal(u.shape, (m, n))
|
68 |
+
assert_equal(p.shape, (m, m))
|
69 |
+
# a = pu
|
70 |
+
assert_allclose(p.dot(u), a, atol=product_atol)
|
71 |
+
if m >= n:
|
72 |
+
assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15)
|
73 |
+
else:
|
74 |
+
assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15)
|
75 |
+
# p is Hermitian positive semidefinite.
|
76 |
+
assert_allclose(p.conj().T, p)
|
77 |
+
evals = eigh(p, eigvals_only=True)
|
78 |
+
nonzero_evals = evals[abs(evals) > 1e-14]
|
79 |
+
assert_((nonzero_evals >= 0).all())
|
80 |
+
|
81 |
+
|
82 |
+
def test_precomputed_cases():
|
83 |
+
for a, side, expected_u, expected_p in precomputed_cases:
|
84 |
+
check_precomputed_polar(a, side, expected_u, expected_p)
|
85 |
+
|
86 |
+
|
87 |
+
def test_verify_cases():
|
88 |
+
for a in verify_cases:
|
89 |
+
verify_polar(a)
|
90 |
+
|
env-llmeval/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py
ADDED
@@ -0,0 +1,1700 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import itertools
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
from numpy.testing import assert_, assert_allclose, assert_equal
|
5 |
+
from pytest import raises as assert_raises
|
6 |
+
from scipy import linalg
|
7 |
+
import scipy.linalg._decomp_update as _decomp_update
|
8 |
+
from scipy.linalg._decomp_update import qr_delete, qr_update, qr_insert
|
9 |
+
|
10 |
+
def assert_unitary(a, rtol=None, atol=None, assert_sqr=True):
|
11 |
+
if rtol is None:
|
12 |
+
rtol = 10.0 ** -(np.finfo(a.dtype).precision-2)
|
13 |
+
if atol is None:
|
14 |
+
atol = 10*np.finfo(a.dtype).eps
|
15 |
+
|
16 |
+
if assert_sqr:
|
17 |
+
assert_(a.shape[0] == a.shape[1], 'unitary matrices must be square')
|
18 |
+
aTa = np.dot(a.T.conj(), a)
|
19 |
+
assert_allclose(aTa, np.eye(a.shape[1]), rtol=rtol, atol=atol)
|
20 |
+
|
21 |
+
def assert_upper_tri(a, rtol=None, atol=None):
|
22 |
+
if rtol is None:
|
23 |
+
rtol = 10.0 ** -(np.finfo(a.dtype).precision-2)
|
24 |
+
if atol is None:
|
25 |
+
atol = 2*np.finfo(a.dtype).eps
|
26 |
+
mask = np.tri(a.shape[0], a.shape[1], -1, np.bool_)
|
27 |
+
assert_allclose(a[mask], 0.0, rtol=rtol, atol=atol)
|
28 |
+
|
29 |
+
def check_qr(q, r, a, rtol, atol, assert_sqr=True):
|
30 |
+
assert_unitary(q, rtol, atol, assert_sqr)
|
31 |
+
assert_upper_tri(r, rtol, atol)
|
32 |
+
assert_allclose(q.dot(r), a, rtol=rtol, atol=atol)
|
33 |
+
|
34 |
+
def make_strided(arrs):
|
35 |
+
strides = [(3, 7), (2, 2), (3, 4), (4, 2), (5, 4), (2, 3), (2, 1), (4, 5)]
|
36 |
+
kmax = len(strides)
|
37 |
+
k = 0
|
38 |
+
ret = []
|
39 |
+
for a in arrs:
|
40 |
+
if a.ndim == 1:
|
41 |
+
s = strides[k % kmax]
|
42 |
+
k += 1
|
43 |
+
base = np.zeros(s[0]*a.shape[0]+s[1], a.dtype)
|
44 |
+
view = base[s[1]::s[0]]
|
45 |
+
view[...] = a
|
46 |
+
elif a.ndim == 2:
|
47 |
+
s = strides[k % kmax]
|
48 |
+
t = strides[(k+1) % kmax]
|
49 |
+
k += 2
|
50 |
+
base = np.zeros((s[0]*a.shape[0]+s[1], t[0]*a.shape[1]+t[1]),
|
51 |
+
a.dtype)
|
52 |
+
view = base[s[1]::s[0], t[1]::t[0]]
|
53 |
+
view[...] = a
|
54 |
+
else:
|
55 |
+
raise ValueError('make_strided only works for ndim = 1 or'
|
56 |
+
' 2 arrays')
|
57 |
+
ret.append(view)
|
58 |
+
return ret
|
59 |
+
|
60 |
+
def negate_strides(arrs):
|
61 |
+
ret = []
|
62 |
+
for a in arrs:
|
63 |
+
b = np.zeros_like(a)
|
64 |
+
if b.ndim == 2:
|
65 |
+
b = b[::-1, ::-1]
|
66 |
+
elif b.ndim == 1:
|
67 |
+
b = b[::-1]
|
68 |
+
else:
|
69 |
+
raise ValueError('negate_strides only works for ndim = 1 or'
|
70 |
+
' 2 arrays')
|
71 |
+
b[...] = a
|
72 |
+
ret.append(b)
|
73 |
+
return ret
|
74 |
+
|
75 |
+
def nonitemsize_strides(arrs):
|
76 |
+
out = []
|
77 |
+
for a in arrs:
|
78 |
+
a_dtype = a.dtype
|
79 |
+
b = np.zeros(a.shape, [('a', a_dtype), ('junk', 'S1')])
|
80 |
+
c = b.getfield(a_dtype)
|
81 |
+
c[...] = a
|
82 |
+
out.append(c)
|
83 |
+
return out
|
84 |
+
|
85 |
+
|
86 |
+
def make_nonnative(arrs):
|
87 |
+
return [a.astype(a.dtype.newbyteorder()) for a in arrs]
|
88 |
+
|
89 |
+
|
90 |
+
class BaseQRdeltas:
|
91 |
+
def setup_method(self):
|
92 |
+
self.rtol = 10.0 ** -(np.finfo(self.dtype).precision-2)
|
93 |
+
self.atol = 10 * np.finfo(self.dtype).eps
|
94 |
+
|
95 |
+
def generate(self, type, mode='full'):
|
96 |
+
np.random.seed(29382)
|
97 |
+
shape = {'sqr': (8, 8), 'tall': (12, 7), 'fat': (7, 12),
|
98 |
+
'Mx1': (8, 1), '1xN': (1, 8), '1x1': (1, 1)}[type]
|
99 |
+
a = np.random.random(shape)
|
100 |
+
if np.iscomplexobj(self.dtype.type(1)):
|
101 |
+
b = np.random.random(shape)
|
102 |
+
a = a + 1j * b
|
103 |
+
a = a.astype(self.dtype)
|
104 |
+
q, r = linalg.qr(a, mode=mode)
|
105 |
+
return a, q, r
|
106 |
+
|
107 |
+
class BaseQRdelete(BaseQRdeltas):
|
108 |
+
def test_sqr_1_row(self):
|
109 |
+
a, q, r = self.generate('sqr')
|
110 |
+
for row in range(r.shape[0]):
|
111 |
+
q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
|
112 |
+
a1 = np.delete(a, row, 0)
|
113 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
114 |
+
|
115 |
+
def test_sqr_p_row(self):
|
116 |
+
a, q, r = self.generate('sqr')
|
117 |
+
for ndel in range(2, 6):
|
118 |
+
for row in range(a.shape[0]-ndel):
|
119 |
+
q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
|
120 |
+
a1 = np.delete(a, slice(row, row+ndel), 0)
|
121 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
122 |
+
|
123 |
+
def test_sqr_1_col(self):
|
124 |
+
a, q, r = self.generate('sqr')
|
125 |
+
for col in range(r.shape[1]):
|
126 |
+
q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
|
127 |
+
a1 = np.delete(a, col, 1)
|
128 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
129 |
+
|
130 |
+
def test_sqr_p_col(self):
|
131 |
+
a, q, r = self.generate('sqr')
|
132 |
+
for ndel in range(2, 6):
|
133 |
+
for col in range(r.shape[1]-ndel):
|
134 |
+
q1, r1 = qr_delete(q, r, col, ndel, which='col',
|
135 |
+
overwrite_qr=False)
|
136 |
+
a1 = np.delete(a, slice(col, col+ndel), 1)
|
137 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
138 |
+
|
139 |
+
def test_tall_1_row(self):
|
140 |
+
a, q, r = self.generate('tall')
|
141 |
+
for row in range(r.shape[0]):
|
142 |
+
q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
|
143 |
+
a1 = np.delete(a, row, 0)
|
144 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
145 |
+
|
146 |
+
def test_tall_p_row(self):
|
147 |
+
a, q, r = self.generate('tall')
|
148 |
+
for ndel in range(2, 6):
|
149 |
+
for row in range(a.shape[0]-ndel):
|
150 |
+
q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
|
151 |
+
a1 = np.delete(a, slice(row, row+ndel), 0)
|
152 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
153 |
+
|
154 |
+
def test_tall_1_col(self):
|
155 |
+
a, q, r = self.generate('tall')
|
156 |
+
for col in range(r.shape[1]):
|
157 |
+
q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
|
158 |
+
a1 = np.delete(a, col, 1)
|
159 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
160 |
+
|
161 |
+
def test_tall_p_col(self):
|
162 |
+
a, q, r = self.generate('tall')
|
163 |
+
for ndel in range(2, 6):
|
164 |
+
for col in range(r.shape[1]-ndel):
|
165 |
+
q1, r1 = qr_delete(q, r, col, ndel, which='col',
|
166 |
+
overwrite_qr=False)
|
167 |
+
a1 = np.delete(a, slice(col, col+ndel), 1)
|
168 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
169 |
+
|
170 |
+
def test_fat_1_row(self):
|
171 |
+
a, q, r = self.generate('fat')
|
172 |
+
for row in range(r.shape[0]):
|
173 |
+
q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
|
174 |
+
a1 = np.delete(a, row, 0)
|
175 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
176 |
+
|
177 |
+
def test_fat_p_row(self):
|
178 |
+
a, q, r = self.generate('fat')
|
179 |
+
for ndel in range(2, 6):
|
180 |
+
for row in range(a.shape[0]-ndel):
|
181 |
+
q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
|
182 |
+
a1 = np.delete(a, slice(row, row+ndel), 0)
|
183 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
184 |
+
|
185 |
+
def test_fat_1_col(self):
|
186 |
+
a, q, r = self.generate('fat')
|
187 |
+
for col in range(r.shape[1]):
|
188 |
+
q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
|
189 |
+
a1 = np.delete(a, col, 1)
|
190 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
191 |
+
|
192 |
+
def test_fat_p_col(self):
|
193 |
+
a, q, r = self.generate('fat')
|
194 |
+
for ndel in range(2, 6):
|
195 |
+
for col in range(r.shape[1]-ndel):
|
196 |
+
q1, r1 = qr_delete(q, r, col, ndel, which='col',
|
197 |
+
overwrite_qr=False)
|
198 |
+
a1 = np.delete(a, slice(col, col+ndel), 1)
|
199 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
200 |
+
|
201 |
+
def test_economic_1_row(self):
|
202 |
+
# this test always starts and ends with an economic decomp.
|
203 |
+
a, q, r = self.generate('tall', 'economic')
|
204 |
+
for row in range(r.shape[0]):
|
205 |
+
q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
|
206 |
+
a1 = np.delete(a, row, 0)
|
207 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
208 |
+
|
209 |
+
# for economic row deletes
|
210 |
+
# eco - prow = eco
|
211 |
+
# eco - prow = sqr
|
212 |
+
# eco - prow = fat
|
213 |
+
def base_economic_p_row_xxx(self, ndel):
|
214 |
+
a, q, r = self.generate('tall', 'economic')
|
215 |
+
for row in range(a.shape[0]-ndel):
|
216 |
+
q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
|
217 |
+
a1 = np.delete(a, slice(row, row+ndel), 0)
|
218 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
219 |
+
|
220 |
+
def test_economic_p_row_economic(self):
|
221 |
+
# (12, 7) - (3, 7) = (9,7) --> stays economic
|
222 |
+
self.base_economic_p_row_xxx(3)
|
223 |
+
|
224 |
+
def test_economic_p_row_sqr(self):
|
225 |
+
# (12, 7) - (5, 7) = (7, 7) --> becomes square
|
226 |
+
self.base_economic_p_row_xxx(5)
|
227 |
+
|
228 |
+
def test_economic_p_row_fat(self):
|
229 |
+
# (12, 7) - (7,7) = (5, 7) --> becomes fat
|
230 |
+
self.base_economic_p_row_xxx(7)
|
231 |
+
|
232 |
+
def test_economic_1_col(self):
|
233 |
+
a, q, r = self.generate('tall', 'economic')
|
234 |
+
for col in range(r.shape[1]):
|
235 |
+
q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
|
236 |
+
a1 = np.delete(a, col, 1)
|
237 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
238 |
+
|
239 |
+
def test_economic_p_col(self):
|
240 |
+
a, q, r = self.generate('tall', 'economic')
|
241 |
+
for ndel in range(2, 6):
|
242 |
+
for col in range(r.shape[1]-ndel):
|
243 |
+
q1, r1 = qr_delete(q, r, col, ndel, which='col',
|
244 |
+
overwrite_qr=False)
|
245 |
+
a1 = np.delete(a, slice(col, col+ndel), 1)
|
246 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
247 |
+
|
248 |
+
def test_Mx1_1_row(self):
|
249 |
+
a, q, r = self.generate('Mx1')
|
250 |
+
for row in range(r.shape[0]):
|
251 |
+
q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
|
252 |
+
a1 = np.delete(a, row, 0)
|
253 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
254 |
+
|
255 |
+
def test_Mx1_p_row(self):
|
256 |
+
a, q, r = self.generate('Mx1')
|
257 |
+
for ndel in range(2, 6):
|
258 |
+
for row in range(a.shape[0]-ndel):
|
259 |
+
q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
|
260 |
+
a1 = np.delete(a, slice(row, row+ndel), 0)
|
261 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
262 |
+
|
263 |
+
def test_1xN_1_col(self):
|
264 |
+
a, q, r = self.generate('1xN')
|
265 |
+
for col in range(r.shape[1]):
|
266 |
+
q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
|
267 |
+
a1 = np.delete(a, col, 1)
|
268 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
269 |
+
|
270 |
+
def test_1xN_p_col(self):
|
271 |
+
a, q, r = self.generate('1xN')
|
272 |
+
for ndel in range(2, 6):
|
273 |
+
for col in range(r.shape[1]-ndel):
|
274 |
+
q1, r1 = qr_delete(q, r, col, ndel, which='col',
|
275 |
+
overwrite_qr=False)
|
276 |
+
a1 = np.delete(a, slice(col, col+ndel), 1)
|
277 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
278 |
+
|
279 |
+
def test_Mx1_economic_1_row(self):
|
280 |
+
a, q, r = self.generate('Mx1', 'economic')
|
281 |
+
for row in range(r.shape[0]):
|
282 |
+
q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
|
283 |
+
a1 = np.delete(a, row, 0)
|
284 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
285 |
+
|
286 |
+
def test_Mx1_economic_p_row(self):
|
287 |
+
a, q, r = self.generate('Mx1', 'economic')
|
288 |
+
for ndel in range(2, 6):
|
289 |
+
for row in range(a.shape[0]-ndel):
|
290 |
+
q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
|
291 |
+
a1 = np.delete(a, slice(row, row+ndel), 0)
|
292 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
293 |
+
|
294 |
+
def test_delete_last_1_row(self):
|
295 |
+
# full and eco are the same for 1xN
|
296 |
+
a, q, r = self.generate('1xN')
|
297 |
+
q1, r1 = qr_delete(q, r, 0, 1, 'row')
|
298 |
+
assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
|
299 |
+
assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
|
300 |
+
|
301 |
+
def test_delete_last_p_row(self):
|
302 |
+
a, q, r = self.generate('tall', 'full')
|
303 |
+
q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row')
|
304 |
+
assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
|
305 |
+
assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
|
306 |
+
|
307 |
+
a, q, r = self.generate('tall', 'economic')
|
308 |
+
q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row')
|
309 |
+
assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
|
310 |
+
assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
|
311 |
+
|
312 |
+
def test_delete_last_1_col(self):
|
313 |
+
a, q, r = self.generate('Mx1', 'economic')
|
314 |
+
q1, r1 = qr_delete(q, r, 0, 1, 'col')
|
315 |
+
assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype))
|
316 |
+
assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
|
317 |
+
|
318 |
+
a, q, r = self.generate('Mx1', 'full')
|
319 |
+
q1, r1 = qr_delete(q, r, 0, 1, 'col')
|
320 |
+
assert_unitary(q1)
|
321 |
+
assert_(q1.dtype == q.dtype)
|
322 |
+
assert_(q1.shape == q.shape)
|
323 |
+
assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
|
324 |
+
|
325 |
+
def test_delete_last_p_col(self):
|
326 |
+
a, q, r = self.generate('tall', 'full')
|
327 |
+
q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col')
|
328 |
+
assert_unitary(q1)
|
329 |
+
assert_(q1.dtype == q.dtype)
|
330 |
+
assert_(q1.shape == q.shape)
|
331 |
+
assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
|
332 |
+
|
333 |
+
a, q, r = self.generate('tall', 'economic')
|
334 |
+
q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col')
|
335 |
+
assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype))
|
336 |
+
assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
|
337 |
+
|
338 |
+
def test_delete_1x1_row_col(self):
|
339 |
+
a, q, r = self.generate('1x1')
|
340 |
+
q1, r1 = qr_delete(q, r, 0, 1, 'row')
|
341 |
+
assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
|
342 |
+
assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
|
343 |
+
|
344 |
+
a, q, r = self.generate('1x1')
|
345 |
+
q1, r1 = qr_delete(q, r, 0, 1, 'col')
|
346 |
+
assert_unitary(q1)
|
347 |
+
assert_(q1.dtype == q.dtype)
|
348 |
+
assert_(q1.shape == q.shape)
|
349 |
+
assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
|
350 |
+
|
351 |
+
# all full qr, row deletes and single column deletes should be able to
|
352 |
+
# handle any non negative strides. (only row and column vector
|
353 |
+
# operations are used.) p column delete require fortran ordered
|
354 |
+
# Q and R and will make a copy as necessary. Economic qr row deletes
|
355 |
+
# require a contiguous q.
|
356 |
+
|
357 |
+
def base_non_simple_strides(self, adjust_strides, ks, p, which,
|
358 |
+
overwriteable):
|
359 |
+
if which == 'row':
|
360 |
+
qind = (slice(p,None), slice(p,None))
|
361 |
+
rind = (slice(p,None), slice(None))
|
362 |
+
else:
|
363 |
+
qind = (slice(None), slice(None))
|
364 |
+
rind = (slice(None), slice(None,-p))
|
365 |
+
|
366 |
+
for type, k in itertools.product(['sqr', 'tall', 'fat'], ks):
|
367 |
+
a, q0, r0, = self.generate(type)
|
368 |
+
qs, rs = adjust_strides((q0, r0))
|
369 |
+
if p == 1:
|
370 |
+
a1 = np.delete(a, k, 0 if which == 'row' else 1)
|
371 |
+
else:
|
372 |
+
s = slice(k,k+p)
|
373 |
+
if k < 0:
|
374 |
+
s = slice(k, k + p +
|
375 |
+
(a.shape[0] if which == 'row' else a.shape[1]))
|
376 |
+
a1 = np.delete(a, s, 0 if which == 'row' else 1)
|
377 |
+
|
378 |
+
# for each variable, q, r we try with it strided and
|
379 |
+
# overwrite=False. Then we try with overwrite=True, and make
|
380 |
+
# sure that q and r are still overwritten.
|
381 |
+
|
382 |
+
q = q0.copy('F')
|
383 |
+
r = r0.copy('F')
|
384 |
+
q1, r1 = qr_delete(qs, r, k, p, which, False)
|
385 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
386 |
+
q1o, r1o = qr_delete(qs, r, k, p, which, True)
|
387 |
+
check_qr(q1o, r1o, a1, self.rtol, self.atol)
|
388 |
+
if overwriteable:
|
389 |
+
assert_allclose(q1o, qs[qind], rtol=self.rtol, atol=self.atol)
|
390 |
+
assert_allclose(r1o, r[rind], rtol=self.rtol, atol=self.atol)
|
391 |
+
|
392 |
+
q = q0.copy('F')
|
393 |
+
r = r0.copy('F')
|
394 |
+
q2, r2 = qr_delete(q, rs, k, p, which, False)
|
395 |
+
check_qr(q2, r2, a1, self.rtol, self.atol)
|
396 |
+
q2o, r2o = qr_delete(q, rs, k, p, which, True)
|
397 |
+
check_qr(q2o, r2o, a1, self.rtol, self.atol)
|
398 |
+
if overwriteable:
|
399 |
+
assert_allclose(q2o, q[qind], rtol=self.rtol, atol=self.atol)
|
400 |
+
assert_allclose(r2o, rs[rind], rtol=self.rtol, atol=self.atol)
|
401 |
+
|
402 |
+
q = q0.copy('F')
|
403 |
+
r = r0.copy('F')
|
404 |
+
# since some of these were consumed above
|
405 |
+
qs, rs = adjust_strides((q, r))
|
406 |
+
q3, r3 = qr_delete(qs, rs, k, p, which, False)
|
407 |
+
check_qr(q3, r3, a1, self.rtol, self.atol)
|
408 |
+
q3o, r3o = qr_delete(qs, rs, k, p, which, True)
|
409 |
+
check_qr(q3o, r3o, a1, self.rtol, self.atol)
|
410 |
+
if overwriteable:
|
411 |
+
assert_allclose(q2o, qs[qind], rtol=self.rtol, atol=self.atol)
|
412 |
+
assert_allclose(r3o, rs[rind], rtol=self.rtol, atol=self.atol)
|
413 |
+
|
414 |
+
def test_non_unit_strides_1_row(self):
|
415 |
+
self.base_non_simple_strides(make_strided, [0], 1, 'row', True)
|
416 |
+
|
417 |
+
def test_non_unit_strides_p_row(self):
|
418 |
+
self.base_non_simple_strides(make_strided, [0], 3, 'row', True)
|
419 |
+
|
420 |
+
def test_non_unit_strides_1_col(self):
|
421 |
+
self.base_non_simple_strides(make_strided, [0], 1, 'col', True)
|
422 |
+
|
423 |
+
def test_non_unit_strides_p_col(self):
|
424 |
+
self.base_non_simple_strides(make_strided, [0], 3, 'col', False)
|
425 |
+
|
426 |
+
def test_neg_strides_1_row(self):
|
427 |
+
self.base_non_simple_strides(negate_strides, [0], 1, 'row', False)
|
428 |
+
|
429 |
+
def test_neg_strides_p_row(self):
|
430 |
+
self.base_non_simple_strides(negate_strides, [0], 3, 'row', False)
|
431 |
+
|
432 |
+
def test_neg_strides_1_col(self):
|
433 |
+
self.base_non_simple_strides(negate_strides, [0], 1, 'col', False)
|
434 |
+
|
435 |
+
def test_neg_strides_p_col(self):
|
436 |
+
self.base_non_simple_strides(negate_strides, [0], 3, 'col', False)
|
437 |
+
|
438 |
+
def test_non_itemize_strides_1_row(self):
|
439 |
+
self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'row', False)
|
440 |
+
|
441 |
+
def test_non_itemize_strides_p_row(self):
|
442 |
+
self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'row', False)
|
443 |
+
|
444 |
+
def test_non_itemize_strides_1_col(self):
|
445 |
+
self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'col', False)
|
446 |
+
|
447 |
+
def test_non_itemize_strides_p_col(self):
|
448 |
+
self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'col', False)
|
449 |
+
|
450 |
+
def test_non_native_byte_order_1_row(self):
|
451 |
+
self.base_non_simple_strides(make_nonnative, [0], 1, 'row', False)
|
452 |
+
|
453 |
+
def test_non_native_byte_order_p_row(self):
|
454 |
+
self.base_non_simple_strides(make_nonnative, [0], 3, 'row', False)
|
455 |
+
|
456 |
+
def test_non_native_byte_order_1_col(self):
|
457 |
+
self.base_non_simple_strides(make_nonnative, [0], 1, 'col', False)
|
458 |
+
|
459 |
+
def test_non_native_byte_order_p_col(self):
|
460 |
+
self.base_non_simple_strides(make_nonnative, [0], 3, 'col', False)
|
461 |
+
|
462 |
+
def test_neg_k(self):
|
463 |
+
a, q, r = self.generate('sqr')
|
464 |
+
for k, p, w in itertools.product([-3, -7], [1, 3], ['row', 'col']):
|
465 |
+
q1, r1 = qr_delete(q, r, k, p, w, overwrite_qr=False)
|
466 |
+
if w == 'row':
|
467 |
+
a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[0]), 0)
|
468 |
+
else:
|
469 |
+
a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[1]), 1)
|
470 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
471 |
+
|
472 |
+
def base_overwrite_qr(self, which, p, test_C, test_F, mode='full'):
|
473 |
+
assert_sqr = True if mode == 'full' else False
|
474 |
+
if which == 'row':
|
475 |
+
qind = (slice(p,None), slice(p,None))
|
476 |
+
rind = (slice(p,None), slice(None))
|
477 |
+
else:
|
478 |
+
qind = (slice(None), slice(None))
|
479 |
+
rind = (slice(None), slice(None,-p))
|
480 |
+
a, q0, r0 = self.generate('sqr', mode)
|
481 |
+
if p == 1:
|
482 |
+
a1 = np.delete(a, 3, 0 if which == 'row' else 1)
|
483 |
+
else:
|
484 |
+
a1 = np.delete(a, slice(3, 3+p), 0 if which == 'row' else 1)
|
485 |
+
|
486 |
+
# don't overwrite
|
487 |
+
q = q0.copy('F')
|
488 |
+
r = r0.copy('F')
|
489 |
+
q1, r1 = qr_delete(q, r, 3, p, which, False)
|
490 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, assert_sqr)
|
491 |
+
check_qr(q, r, a, self.rtol, self.atol, assert_sqr)
|
492 |
+
|
493 |
+
if test_F:
|
494 |
+
q = q0.copy('F')
|
495 |
+
r = r0.copy('F')
|
496 |
+
q2, r2 = qr_delete(q, r, 3, p, which, True)
|
497 |
+
check_qr(q2, r2, a1, self.rtol, self.atol, assert_sqr)
|
498 |
+
# verify the overwriting
|
499 |
+
assert_allclose(q2, q[qind], rtol=self.rtol, atol=self.atol)
|
500 |
+
assert_allclose(r2, r[rind], rtol=self.rtol, atol=self.atol)
|
501 |
+
|
502 |
+
if test_C:
|
503 |
+
q = q0.copy('C')
|
504 |
+
r = r0.copy('C')
|
505 |
+
q3, r3 = qr_delete(q, r, 3, p, which, True)
|
506 |
+
check_qr(q3, r3, a1, self.rtol, self.atol, assert_sqr)
|
507 |
+
assert_allclose(q3, q[qind], rtol=self.rtol, atol=self.atol)
|
508 |
+
assert_allclose(r3, r[rind], rtol=self.rtol, atol=self.atol)
|
509 |
+
|
510 |
+
def test_overwrite_qr_1_row(self):
|
511 |
+
# any positively strided q and r.
|
512 |
+
self.base_overwrite_qr('row', 1, True, True)
|
513 |
+
|
514 |
+
def test_overwrite_economic_qr_1_row(self):
|
515 |
+
# Any contiguous q and positively strided r.
|
516 |
+
self.base_overwrite_qr('row', 1, True, True, 'economic')
|
517 |
+
|
518 |
+
def test_overwrite_qr_1_col(self):
|
519 |
+
# any positively strided q and r.
|
520 |
+
# full and eco share code paths
|
521 |
+
self.base_overwrite_qr('col', 1, True, True)
|
522 |
+
|
523 |
+
def test_overwrite_qr_p_row(self):
|
524 |
+
# any positively strided q and r.
|
525 |
+
self.base_overwrite_qr('row', 3, True, True)
|
526 |
+
|
527 |
+
def test_overwrite_economic_qr_p_row(self):
|
528 |
+
# any contiguous q and positively strided r
|
529 |
+
self.base_overwrite_qr('row', 3, True, True, 'economic')
|
530 |
+
|
531 |
+
def test_overwrite_qr_p_col(self):
|
532 |
+
# only F ordered q and r can be overwritten for cols
|
533 |
+
# full and eco share code paths
|
534 |
+
self.base_overwrite_qr('col', 3, False, True)
|
535 |
+
|
536 |
+
def test_bad_which(self):
|
537 |
+
a, q, r = self.generate('sqr')
|
538 |
+
assert_raises(ValueError, qr_delete, q, r, 0, which='foo')
|
539 |
+
|
540 |
+
def test_bad_k(self):
|
541 |
+
a, q, r = self.generate('tall')
|
542 |
+
assert_raises(ValueError, qr_delete, q, r, q.shape[0], 1)
|
543 |
+
assert_raises(ValueError, qr_delete, q, r, -q.shape[0]-1, 1)
|
544 |
+
assert_raises(ValueError, qr_delete, q, r, r.shape[0], 1, 'col')
|
545 |
+
assert_raises(ValueError, qr_delete, q, r, -r.shape[0]-1, 1, 'col')
|
546 |
+
|
547 |
+
def test_bad_p(self):
|
548 |
+
a, q, r = self.generate('tall')
|
549 |
+
# p must be positive
|
550 |
+
assert_raises(ValueError, qr_delete, q, r, 0, -1)
|
551 |
+
assert_raises(ValueError, qr_delete, q, r, 0, -1, 'col')
|
552 |
+
|
553 |
+
# and nonzero
|
554 |
+
assert_raises(ValueError, qr_delete, q, r, 0, 0)
|
555 |
+
assert_raises(ValueError, qr_delete, q, r, 0, 0, 'col')
|
556 |
+
|
557 |
+
# must have at least k+p rows or cols, depending.
|
558 |
+
assert_raises(ValueError, qr_delete, q, r, 3, q.shape[0]-2)
|
559 |
+
assert_raises(ValueError, qr_delete, q, r, 3, r.shape[1]-2, 'col')
|
560 |
+
|
561 |
+
def test_empty_q(self):
|
562 |
+
a, q, r = self.generate('tall')
|
563 |
+
# same code path for 'row' and 'col'
|
564 |
+
assert_raises(ValueError, qr_delete, np.array([]), r, 0, 1)
|
565 |
+
|
566 |
+
def test_empty_r(self):
|
567 |
+
a, q, r = self.generate('tall')
|
568 |
+
# same code path for 'row' and 'col'
|
569 |
+
assert_raises(ValueError, qr_delete, q, np.array([]), 0, 1)
|
570 |
+
|
571 |
+
def test_mismatched_q_and_r(self):
|
572 |
+
a, q, r = self.generate('tall')
|
573 |
+
r = r[1:]
|
574 |
+
assert_raises(ValueError, qr_delete, q, r, 0, 1)
|
575 |
+
|
576 |
+
def test_unsupported_dtypes(self):
|
577 |
+
dts = ['int8', 'int16', 'int32', 'int64',
|
578 |
+
'uint8', 'uint16', 'uint32', 'uint64',
|
579 |
+
'float16', 'longdouble', 'clongdouble',
|
580 |
+
'bool']
|
581 |
+
a, q0, r0 = self.generate('tall')
|
582 |
+
for dtype in dts:
|
583 |
+
q = q0.real.astype(dtype)
|
584 |
+
with np.errstate(invalid="ignore"):
|
585 |
+
r = r0.real.astype(dtype)
|
586 |
+
assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row')
|
587 |
+
assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'row')
|
588 |
+
assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col')
|
589 |
+
assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'col')
|
590 |
+
|
591 |
+
assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row')
|
592 |
+
assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'row')
|
593 |
+
assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col')
|
594 |
+
assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'col')
|
595 |
+
|
596 |
+
def test_check_finite(self):
|
597 |
+
a0, q0, r0 = self.generate('tall')
|
598 |
+
|
599 |
+
q = q0.copy('F')
|
600 |
+
q[1,1] = np.nan
|
601 |
+
assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row')
|
602 |
+
assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'row')
|
603 |
+
assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col')
|
604 |
+
assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'col')
|
605 |
+
|
606 |
+
r = r0.copy('F')
|
607 |
+
r[1,1] = np.nan
|
608 |
+
assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row')
|
609 |
+
assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'row')
|
610 |
+
assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col')
|
611 |
+
assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'col')
|
612 |
+
|
613 |
+
def test_qr_scalar(self):
|
614 |
+
a, q, r = self.generate('1x1')
|
615 |
+
assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'row')
|
616 |
+
assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'row')
|
617 |
+
assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'col')
|
618 |
+
assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'col')
|
619 |
+
|
620 |
+
class TestQRdelete_f(BaseQRdelete):
|
621 |
+
dtype = np.dtype('f')
|
622 |
+
|
623 |
+
class TestQRdelete_F(BaseQRdelete):
|
624 |
+
dtype = np.dtype('F')
|
625 |
+
|
626 |
+
class TestQRdelete_d(BaseQRdelete):
|
627 |
+
dtype = np.dtype('d')
|
628 |
+
|
629 |
+
class TestQRdelete_D(BaseQRdelete):
|
630 |
+
dtype = np.dtype('D')
|
631 |
+
|
632 |
+
class BaseQRinsert(BaseQRdeltas):
|
633 |
+
def generate(self, type, mode='full', which='row', p=1):
|
634 |
+
a, q, r = super().generate(type, mode)
|
635 |
+
|
636 |
+
assert_(p > 0)
|
637 |
+
|
638 |
+
# super call set the seed...
|
639 |
+
if which == 'row':
|
640 |
+
if p == 1:
|
641 |
+
u = np.random.random(a.shape[1])
|
642 |
+
else:
|
643 |
+
u = np.random.random((p, a.shape[1]))
|
644 |
+
elif which == 'col':
|
645 |
+
if p == 1:
|
646 |
+
u = np.random.random(a.shape[0])
|
647 |
+
else:
|
648 |
+
u = np.random.random((a.shape[0], p))
|
649 |
+
else:
|
650 |
+
ValueError('which should be either "row" or "col"')
|
651 |
+
|
652 |
+
if np.iscomplexobj(self.dtype.type(1)):
|
653 |
+
b = np.random.random(u.shape)
|
654 |
+
u = u + 1j * b
|
655 |
+
|
656 |
+
u = u.astype(self.dtype)
|
657 |
+
return a, q, r, u
|
658 |
+
|
659 |
+
def test_sqr_1_row(self):
|
660 |
+
a, q, r, u = self.generate('sqr', which='row')
|
661 |
+
for row in range(r.shape[0] + 1):
|
662 |
+
q1, r1 = qr_insert(q, r, u, row)
|
663 |
+
a1 = np.insert(a, row, u, 0)
|
664 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
665 |
+
|
666 |
+
def test_sqr_p_row(self):
|
667 |
+
# sqr + rows --> fat always
|
668 |
+
a, q, r, u = self.generate('sqr', which='row', p=3)
|
669 |
+
for row in range(r.shape[0] + 1):
|
670 |
+
q1, r1 = qr_insert(q, r, u, row)
|
671 |
+
a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
|
672 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
673 |
+
|
674 |
+
def test_sqr_1_col(self):
|
675 |
+
a, q, r, u = self.generate('sqr', which='col')
|
676 |
+
for col in range(r.shape[1] + 1):
|
677 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
678 |
+
a1 = np.insert(a, col, u, 1)
|
679 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
680 |
+
|
681 |
+
def test_sqr_p_col(self):
|
682 |
+
# sqr + cols --> fat always
|
683 |
+
a, q, r, u = self.generate('sqr', which='col', p=3)
|
684 |
+
for col in range(r.shape[1] + 1):
|
685 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
686 |
+
a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
|
687 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
688 |
+
|
689 |
+
def test_tall_1_row(self):
|
690 |
+
a, q, r, u = self.generate('tall', which='row')
|
691 |
+
for row in range(r.shape[0] + 1):
|
692 |
+
q1, r1 = qr_insert(q, r, u, row)
|
693 |
+
a1 = np.insert(a, row, u, 0)
|
694 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
695 |
+
|
696 |
+
def test_tall_p_row(self):
|
697 |
+
# tall + rows --> tall always
|
698 |
+
a, q, r, u = self.generate('tall', which='row', p=3)
|
699 |
+
for row in range(r.shape[0] + 1):
|
700 |
+
q1, r1 = qr_insert(q, r, u, row)
|
701 |
+
a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
|
702 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
703 |
+
|
704 |
+
def test_tall_1_col(self):
|
705 |
+
a, q, r, u = self.generate('tall', which='col')
|
706 |
+
for col in range(r.shape[1] + 1):
|
707 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
708 |
+
a1 = np.insert(a, col, u, 1)
|
709 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
710 |
+
|
711 |
+
# for column adds to tall matrices there are three cases to test
|
712 |
+
# tall + pcol --> tall
|
713 |
+
# tall + pcol --> sqr
|
714 |
+
# tall + pcol --> fat
|
715 |
+
def base_tall_p_col_xxx(self, p):
|
716 |
+
a, q, r, u = self.generate('tall', which='col', p=p)
|
717 |
+
for col in range(r.shape[1] + 1):
|
718 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
719 |
+
a1 = np.insert(a, np.full(p, col, np.intp), u, 1)
|
720 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
721 |
+
|
722 |
+
def test_tall_p_col_tall(self):
|
723 |
+
# 12x7 + 12x3 = 12x10 --> stays tall
|
724 |
+
self.base_tall_p_col_xxx(3)
|
725 |
+
|
726 |
+
def test_tall_p_col_sqr(self):
|
727 |
+
# 12x7 + 12x5 = 12x12 --> becomes sqr
|
728 |
+
self.base_tall_p_col_xxx(5)
|
729 |
+
|
730 |
+
def test_tall_p_col_fat(self):
|
731 |
+
# 12x7 + 12x7 = 12x14 --> becomes fat
|
732 |
+
self.base_tall_p_col_xxx(7)
|
733 |
+
|
734 |
+
def test_fat_1_row(self):
|
735 |
+
a, q, r, u = self.generate('fat', which='row')
|
736 |
+
for row in range(r.shape[0] + 1):
|
737 |
+
q1, r1 = qr_insert(q, r, u, row)
|
738 |
+
a1 = np.insert(a, row, u, 0)
|
739 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
740 |
+
|
741 |
+
# for row adds to fat matrices there are three cases to test
|
742 |
+
# fat + prow --> fat
|
743 |
+
# fat + prow --> sqr
|
744 |
+
# fat + prow --> tall
|
745 |
+
def base_fat_p_row_xxx(self, p):
|
746 |
+
a, q, r, u = self.generate('fat', which='row', p=p)
|
747 |
+
for row in range(r.shape[0] + 1):
|
748 |
+
q1, r1 = qr_insert(q, r, u, row)
|
749 |
+
a1 = np.insert(a, np.full(p, row, np.intp), u, 0)
|
750 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
751 |
+
|
752 |
+
def test_fat_p_row_fat(self):
|
753 |
+
# 7x12 + 3x12 = 10x12 --> stays fat
|
754 |
+
self.base_fat_p_row_xxx(3)
|
755 |
+
|
756 |
+
def test_fat_p_row_sqr(self):
|
757 |
+
# 7x12 + 5x12 = 12x12 --> becomes sqr
|
758 |
+
self.base_fat_p_row_xxx(5)
|
759 |
+
|
760 |
+
def test_fat_p_row_tall(self):
|
761 |
+
# 7x12 + 7x12 = 14x12 --> becomes tall
|
762 |
+
self.base_fat_p_row_xxx(7)
|
763 |
+
|
764 |
+
def test_fat_1_col(self):
|
765 |
+
a, q, r, u = self.generate('fat', which='col')
|
766 |
+
for col in range(r.shape[1] + 1):
|
767 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
768 |
+
a1 = np.insert(a, col, u, 1)
|
769 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
770 |
+
|
771 |
+
def test_fat_p_col(self):
|
772 |
+
# fat + cols --> fat always
|
773 |
+
a, q, r, u = self.generate('fat', which='col', p=3)
|
774 |
+
for col in range(r.shape[1] + 1):
|
775 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
776 |
+
a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
|
777 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
778 |
+
|
779 |
+
def test_economic_1_row(self):
|
780 |
+
a, q, r, u = self.generate('tall', 'economic', 'row')
|
781 |
+
for row in range(r.shape[0] + 1):
|
782 |
+
q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False)
|
783 |
+
a1 = np.insert(a, row, u, 0)
|
784 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
785 |
+
|
786 |
+
def test_economic_p_row(self):
|
787 |
+
# tall + rows --> tall always
|
788 |
+
a, q, r, u = self.generate('tall', 'economic', 'row', 3)
|
789 |
+
for row in range(r.shape[0] + 1):
|
790 |
+
q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False)
|
791 |
+
a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
|
792 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
793 |
+
|
794 |
+
def test_economic_1_col(self):
|
795 |
+
a, q, r, u = self.generate('tall', 'economic', which='col')
|
796 |
+
for col in range(r.shape[1] + 1):
|
797 |
+
q1, r1 = qr_insert(q, r, u.copy(), col, 'col', overwrite_qru=False)
|
798 |
+
a1 = np.insert(a, col, u, 1)
|
799 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
800 |
+
|
801 |
+
def test_economic_1_col_bad_update(self):
|
802 |
+
# When the column to be added lies in the span of Q, the update is
|
803 |
+
# not meaningful. This is detected, and a LinAlgError is issued.
|
804 |
+
q = np.eye(5, 3, dtype=self.dtype)
|
805 |
+
r = np.eye(3, dtype=self.dtype)
|
806 |
+
u = np.array([1, 0, 0, 0, 0], self.dtype)
|
807 |
+
assert_raises(linalg.LinAlgError, qr_insert, q, r, u, 0, 'col')
|
808 |
+
|
809 |
+
# for column adds to economic matrices there are three cases to test
|
810 |
+
# eco + pcol --> eco
|
811 |
+
# eco + pcol --> sqr
|
812 |
+
# eco + pcol --> fat
|
813 |
+
def base_economic_p_col_xxx(self, p):
|
814 |
+
a, q, r, u = self.generate('tall', 'economic', which='col', p=p)
|
815 |
+
for col in range(r.shape[1] + 1):
|
816 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
817 |
+
a1 = np.insert(a, np.full(p, col, np.intp), u, 1)
|
818 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
819 |
+
|
820 |
+
def test_economic_p_col_eco(self):
|
821 |
+
# 12x7 + 12x3 = 12x10 --> stays eco
|
822 |
+
self.base_economic_p_col_xxx(3)
|
823 |
+
|
824 |
+
def test_economic_p_col_sqr(self):
|
825 |
+
# 12x7 + 12x5 = 12x12 --> becomes sqr
|
826 |
+
self.base_economic_p_col_xxx(5)
|
827 |
+
|
828 |
+
def test_economic_p_col_fat(self):
|
829 |
+
# 12x7 + 12x7 = 12x14 --> becomes fat
|
830 |
+
self.base_economic_p_col_xxx(7)
|
831 |
+
|
832 |
+
def test_Mx1_1_row(self):
|
833 |
+
a, q, r, u = self.generate('Mx1', which='row')
|
834 |
+
for row in range(r.shape[0] + 1):
|
835 |
+
q1, r1 = qr_insert(q, r, u, row)
|
836 |
+
a1 = np.insert(a, row, u, 0)
|
837 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
838 |
+
|
839 |
+
def test_Mx1_p_row(self):
|
840 |
+
a, q, r, u = self.generate('Mx1', which='row', p=3)
|
841 |
+
for row in range(r.shape[0] + 1):
|
842 |
+
q1, r1 = qr_insert(q, r, u, row)
|
843 |
+
a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
|
844 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
845 |
+
|
846 |
+
def test_Mx1_1_col(self):
|
847 |
+
a, q, r, u = self.generate('Mx1', which='col')
|
848 |
+
for col in range(r.shape[1] + 1):
|
849 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
850 |
+
a1 = np.insert(a, col, u, 1)
|
851 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
852 |
+
|
853 |
+
def test_Mx1_p_col(self):
|
854 |
+
a, q, r, u = self.generate('Mx1', which='col', p=3)
|
855 |
+
for col in range(r.shape[1] + 1):
|
856 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
857 |
+
a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
|
858 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
859 |
+
|
860 |
+
def test_Mx1_economic_1_row(self):
|
861 |
+
a, q, r, u = self.generate('Mx1', 'economic', 'row')
|
862 |
+
for row in range(r.shape[0] + 1):
|
863 |
+
q1, r1 = qr_insert(q, r, u, row)
|
864 |
+
a1 = np.insert(a, row, u, 0)
|
865 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
866 |
+
|
867 |
+
def test_Mx1_economic_p_row(self):
|
868 |
+
a, q, r, u = self.generate('Mx1', 'economic', 'row', 3)
|
869 |
+
for row in range(r.shape[0] + 1):
|
870 |
+
q1, r1 = qr_insert(q, r, u, row)
|
871 |
+
a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
|
872 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
873 |
+
|
874 |
+
def test_Mx1_economic_1_col(self):
|
875 |
+
a, q, r, u = self.generate('Mx1', 'economic', 'col')
|
876 |
+
for col in range(r.shape[1] + 1):
|
877 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
878 |
+
a1 = np.insert(a, col, u, 1)
|
879 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
880 |
+
|
881 |
+
def test_Mx1_economic_p_col(self):
|
882 |
+
a, q, r, u = self.generate('Mx1', 'economic', 'col', 3)
|
883 |
+
for col in range(r.shape[1] + 1):
|
884 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
885 |
+
a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
|
886 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
887 |
+
|
888 |
+
def test_1xN_1_row(self):
|
889 |
+
a, q, r, u = self.generate('1xN', which='row')
|
890 |
+
for row in range(r.shape[0] + 1):
|
891 |
+
q1, r1 = qr_insert(q, r, u, row)
|
892 |
+
a1 = np.insert(a, row, u, 0)
|
893 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
894 |
+
|
895 |
+
def test_1xN_p_row(self):
|
896 |
+
a, q, r, u = self.generate('1xN', which='row', p=3)
|
897 |
+
for row in range(r.shape[0] + 1):
|
898 |
+
q1, r1 = qr_insert(q, r, u, row)
|
899 |
+
a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
|
900 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
901 |
+
|
902 |
+
def test_1xN_1_col(self):
|
903 |
+
a, q, r, u = self.generate('1xN', which='col')
|
904 |
+
for col in range(r.shape[1] + 1):
|
905 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
906 |
+
a1 = np.insert(a, col, u, 1)
|
907 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
908 |
+
|
909 |
+
def test_1xN_p_col(self):
|
910 |
+
a, q, r, u = self.generate('1xN', which='col', p=3)
|
911 |
+
for col in range(r.shape[1] + 1):
|
912 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
913 |
+
a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
|
914 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
915 |
+
|
916 |
+
def test_1x1_1_row(self):
|
917 |
+
a, q, r, u = self.generate('1x1', which='row')
|
918 |
+
for row in range(r.shape[0] + 1):
|
919 |
+
q1, r1 = qr_insert(q, r, u, row)
|
920 |
+
a1 = np.insert(a, row, u, 0)
|
921 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
922 |
+
|
923 |
+
def test_1x1_p_row(self):
|
924 |
+
a, q, r, u = self.generate('1x1', which='row', p=3)
|
925 |
+
for row in range(r.shape[0] + 1):
|
926 |
+
q1, r1 = qr_insert(q, r, u, row)
|
927 |
+
a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
|
928 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
929 |
+
|
930 |
+
def test_1x1_1_col(self):
|
931 |
+
a, q, r, u = self.generate('1x1', which='col')
|
932 |
+
for col in range(r.shape[1] + 1):
|
933 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
934 |
+
a1 = np.insert(a, col, u, 1)
|
935 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
936 |
+
|
937 |
+
def test_1x1_p_col(self):
|
938 |
+
a, q, r, u = self.generate('1x1', which='col', p=3)
|
939 |
+
for col in range(r.shape[1] + 1):
|
940 |
+
q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
|
941 |
+
a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
|
942 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
943 |
+
|
944 |
+
def test_1x1_1_scalar(self):
|
945 |
+
a, q, r, u = self.generate('1x1', which='row')
|
946 |
+
assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'row')
|
947 |
+
assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'row')
|
948 |
+
assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'row')
|
949 |
+
|
950 |
+
assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'col')
|
951 |
+
assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'col')
|
952 |
+
assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'col')
|
953 |
+
|
954 |
+
def base_non_simple_strides(self, adjust_strides, k, p, which):
|
955 |
+
for type in ['sqr', 'tall', 'fat']:
|
956 |
+
a, q0, r0, u0 = self.generate(type, which=which, p=p)
|
957 |
+
qs, rs, us = adjust_strides((q0, r0, u0))
|
958 |
+
if p == 1:
|
959 |
+
ai = np.insert(a, k, u0, 0 if which == 'row' else 1)
|
960 |
+
else:
|
961 |
+
ai = np.insert(a, np.full(p, k, np.intp),
|
962 |
+
u0 if which == 'row' else u0,
|
963 |
+
0 if which == 'row' else 1)
|
964 |
+
|
965 |
+
# for each variable, q, r, u we try with it strided and
|
966 |
+
# overwrite=False. Then we try with overwrite=True. Nothing
|
967 |
+
# is checked to see if it can be overwritten, since only
|
968 |
+
# F ordered Q can be overwritten when adding columns.
|
969 |
+
|
970 |
+
q = q0.copy('F')
|
971 |
+
r = r0.copy('F')
|
972 |
+
u = u0.copy('F')
|
973 |
+
q1, r1 = qr_insert(qs, r, u, k, which, overwrite_qru=False)
|
974 |
+
check_qr(q1, r1, ai, self.rtol, self.atol)
|
975 |
+
q1o, r1o = qr_insert(qs, r, u, k, which, overwrite_qru=True)
|
976 |
+
check_qr(q1o, r1o, ai, self.rtol, self.atol)
|
977 |
+
|
978 |
+
q = q0.copy('F')
|
979 |
+
r = r0.copy('F')
|
980 |
+
u = u0.copy('F')
|
981 |
+
q2, r2 = qr_insert(q, rs, u, k, which, overwrite_qru=False)
|
982 |
+
check_qr(q2, r2, ai, self.rtol, self.atol)
|
983 |
+
q2o, r2o = qr_insert(q, rs, u, k, which, overwrite_qru=True)
|
984 |
+
check_qr(q2o, r2o, ai, self.rtol, self.atol)
|
985 |
+
|
986 |
+
q = q0.copy('F')
|
987 |
+
r = r0.copy('F')
|
988 |
+
u = u0.copy('F')
|
989 |
+
q3, r3 = qr_insert(q, r, us, k, which, overwrite_qru=False)
|
990 |
+
check_qr(q3, r3, ai, self.rtol, self.atol)
|
991 |
+
q3o, r3o = qr_insert(q, r, us, k, which, overwrite_qru=True)
|
992 |
+
check_qr(q3o, r3o, ai, self.rtol, self.atol)
|
993 |
+
|
994 |
+
q = q0.copy('F')
|
995 |
+
r = r0.copy('F')
|
996 |
+
u = u0.copy('F')
|
997 |
+
# since some of these were consumed above
|
998 |
+
qs, rs, us = adjust_strides((q, r, u))
|
999 |
+
q5, r5 = qr_insert(qs, rs, us, k, which, overwrite_qru=False)
|
1000 |
+
check_qr(q5, r5, ai, self.rtol, self.atol)
|
1001 |
+
q5o, r5o = qr_insert(qs, rs, us, k, which, overwrite_qru=True)
|
1002 |
+
check_qr(q5o, r5o, ai, self.rtol, self.atol)
|
1003 |
+
|
1004 |
+
def test_non_unit_strides_1_row(self):
|
1005 |
+
self.base_non_simple_strides(make_strided, 0, 1, 'row')
|
1006 |
+
|
1007 |
+
def test_non_unit_strides_p_row(self):
|
1008 |
+
self.base_non_simple_strides(make_strided, 0, 3, 'row')
|
1009 |
+
|
1010 |
+
def test_non_unit_strides_1_col(self):
|
1011 |
+
self.base_non_simple_strides(make_strided, 0, 1, 'col')
|
1012 |
+
|
1013 |
+
def test_non_unit_strides_p_col(self):
|
1014 |
+
self.base_non_simple_strides(make_strided, 0, 3, 'col')
|
1015 |
+
|
1016 |
+
def test_neg_strides_1_row(self):
|
1017 |
+
self.base_non_simple_strides(negate_strides, 0, 1, 'row')
|
1018 |
+
|
1019 |
+
def test_neg_strides_p_row(self):
|
1020 |
+
self.base_non_simple_strides(negate_strides, 0, 3, 'row')
|
1021 |
+
|
1022 |
+
def test_neg_strides_1_col(self):
|
1023 |
+
self.base_non_simple_strides(negate_strides, 0, 1, 'col')
|
1024 |
+
|
1025 |
+
def test_neg_strides_p_col(self):
|
1026 |
+
self.base_non_simple_strides(negate_strides, 0, 3, 'col')
|
1027 |
+
|
1028 |
+
def test_non_itemsize_strides_1_row(self):
|
1029 |
+
self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'row')
|
1030 |
+
|
1031 |
+
def test_non_itemsize_strides_p_row(self):
|
1032 |
+
self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'row')
|
1033 |
+
|
1034 |
+
def test_non_itemsize_strides_1_col(self):
|
1035 |
+
self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'col')
|
1036 |
+
|
1037 |
+
def test_non_itemsize_strides_p_col(self):
|
1038 |
+
self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'col')
|
1039 |
+
|
1040 |
+
def test_non_native_byte_order_1_row(self):
|
1041 |
+
self.base_non_simple_strides(make_nonnative, 0, 1, 'row')
|
1042 |
+
|
1043 |
+
def test_non_native_byte_order_p_row(self):
|
1044 |
+
self.base_non_simple_strides(make_nonnative, 0, 3, 'row')
|
1045 |
+
|
1046 |
+
def test_non_native_byte_order_1_col(self):
|
1047 |
+
self.base_non_simple_strides(make_nonnative, 0, 1, 'col')
|
1048 |
+
|
1049 |
+
def test_non_native_byte_order_p_col(self):
|
1050 |
+
self.base_non_simple_strides(make_nonnative, 0, 3, 'col')
|
1051 |
+
|
1052 |
+
def test_overwrite_qu_rank_1(self):
|
1053 |
+
# when inserting rows, the size of both Q and R change, so only
|
1054 |
+
# column inserts can overwrite q. Only complex column inserts
|
1055 |
+
# with C ordered Q overwrite u. Any contiguous Q is overwritten
|
1056 |
+
# when inserting 1 column
|
1057 |
+
a, q0, r, u, = self.generate('sqr', which='col', p=1)
|
1058 |
+
q = q0.copy('C')
|
1059 |
+
u0 = u.copy()
|
1060 |
+
# don't overwrite
|
1061 |
+
q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False)
|
1062 |
+
a1 = np.insert(a, 0, u0, 1)
|
1063 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1064 |
+
check_qr(q, r, a, self.rtol, self.atol)
|
1065 |
+
|
1066 |
+
# try overwriting
|
1067 |
+
q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True)
|
1068 |
+
check_qr(q2, r2, a1, self.rtol, self.atol)
|
1069 |
+
# verify the overwriting
|
1070 |
+
assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
|
1071 |
+
assert_allclose(u, u0.conj(), self.rtol, self.atol)
|
1072 |
+
|
1073 |
+
# now try with a fortran ordered Q
|
1074 |
+
qF = q0.copy('F')
|
1075 |
+
u1 = u0.copy()
|
1076 |
+
q3, r3 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=False)
|
1077 |
+
check_qr(q3, r3, a1, self.rtol, self.atol)
|
1078 |
+
check_qr(qF, r, a, self.rtol, self.atol)
|
1079 |
+
|
1080 |
+
# try overwriting
|
1081 |
+
q4, r4 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=True)
|
1082 |
+
check_qr(q4, r4, a1, self.rtol, self.atol)
|
1083 |
+
assert_allclose(q4, qF, rtol=self.rtol, atol=self.atol)
|
1084 |
+
|
1085 |
+
def test_overwrite_qu_rank_p(self):
|
1086 |
+
# when inserting rows, the size of both Q and R change, so only
|
1087 |
+
# column inserts can potentially overwrite Q. In practice, only
|
1088 |
+
# F ordered Q are overwritten with a rank p update.
|
1089 |
+
a, q0, r, u, = self.generate('sqr', which='col', p=3)
|
1090 |
+
q = q0.copy('F')
|
1091 |
+
a1 = np.insert(a, np.zeros(3, np.intp), u, 1)
|
1092 |
+
|
1093 |
+
# don't overwrite
|
1094 |
+
q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False)
|
1095 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1096 |
+
check_qr(q, r, a, self.rtol, self.atol)
|
1097 |
+
|
1098 |
+
# try overwriting
|
1099 |
+
q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True)
|
1100 |
+
check_qr(q2, r2, a1, self.rtol, self.atol)
|
1101 |
+
assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
|
1102 |
+
|
1103 |
+
def test_empty_inputs(self):
|
1104 |
+
a, q, r, u = self.generate('sqr', which='row')
|
1105 |
+
assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'row')
|
1106 |
+
assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'row')
|
1107 |
+
assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'row')
|
1108 |
+
assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'col')
|
1109 |
+
assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'col')
|
1110 |
+
assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'col')
|
1111 |
+
|
1112 |
+
def test_mismatched_shapes(self):
|
1113 |
+
a, q, r, u = self.generate('tall', which='row')
|
1114 |
+
assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'row')
|
1115 |
+
assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'row')
|
1116 |
+
assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'row')
|
1117 |
+
assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'col')
|
1118 |
+
assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'col')
|
1119 |
+
assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'col')
|
1120 |
+
|
1121 |
+
def test_unsupported_dtypes(self):
|
1122 |
+
dts = ['int8', 'int16', 'int32', 'int64',
|
1123 |
+
'uint8', 'uint16', 'uint32', 'uint64',
|
1124 |
+
'float16', 'longdouble', 'clongdouble',
|
1125 |
+
'bool']
|
1126 |
+
a, q0, r0, u0 = self.generate('sqr', which='row')
|
1127 |
+
for dtype in dts:
|
1128 |
+
q = q0.real.astype(dtype)
|
1129 |
+
with np.errstate(invalid="ignore"):
|
1130 |
+
r = r0.real.astype(dtype)
|
1131 |
+
u = u0.real.astype(dtype)
|
1132 |
+
assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row')
|
1133 |
+
assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col')
|
1134 |
+
assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row')
|
1135 |
+
assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col')
|
1136 |
+
assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row')
|
1137 |
+
assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
|
1138 |
+
|
1139 |
+
def test_check_finite(self):
|
1140 |
+
a0, q0, r0, u0 = self.generate('sqr', which='row', p=3)
|
1141 |
+
|
1142 |
+
q = q0.copy('F')
|
1143 |
+
q[1,1] = np.nan
|
1144 |
+
assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'row')
|
1145 |
+
assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row')
|
1146 |
+
assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'col')
|
1147 |
+
assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col')
|
1148 |
+
|
1149 |
+
r = r0.copy('F')
|
1150 |
+
r[1,1] = np.nan
|
1151 |
+
assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'row')
|
1152 |
+
assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row')
|
1153 |
+
assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'col')
|
1154 |
+
assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col')
|
1155 |
+
|
1156 |
+
u = u0.copy('F')
|
1157 |
+
u[0,0] = np.nan
|
1158 |
+
assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'row')
|
1159 |
+
assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row')
|
1160 |
+
assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'col')
|
1161 |
+
assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
|
1162 |
+
|
1163 |
+
class TestQRinsert_f(BaseQRinsert):
|
1164 |
+
dtype = np.dtype('f')
|
1165 |
+
|
1166 |
+
class TestQRinsert_F(BaseQRinsert):
|
1167 |
+
dtype = np.dtype('F')
|
1168 |
+
|
1169 |
+
class TestQRinsert_d(BaseQRinsert):
|
1170 |
+
dtype = np.dtype('d')
|
1171 |
+
|
1172 |
+
class TestQRinsert_D(BaseQRinsert):
|
1173 |
+
dtype = np.dtype('D')
|
1174 |
+
|
1175 |
+
class BaseQRupdate(BaseQRdeltas):
|
1176 |
+
def generate(self, type, mode='full', p=1):
|
1177 |
+
a, q, r = super().generate(type, mode)
|
1178 |
+
|
1179 |
+
# super call set the seed...
|
1180 |
+
if p == 1:
|
1181 |
+
u = np.random.random(q.shape[0])
|
1182 |
+
v = np.random.random(r.shape[1])
|
1183 |
+
else:
|
1184 |
+
u = np.random.random((q.shape[0], p))
|
1185 |
+
v = np.random.random((r.shape[1], p))
|
1186 |
+
|
1187 |
+
if np.iscomplexobj(self.dtype.type(1)):
|
1188 |
+
b = np.random.random(u.shape)
|
1189 |
+
u = u + 1j * b
|
1190 |
+
|
1191 |
+
c = np.random.random(v.shape)
|
1192 |
+
v = v + 1j * c
|
1193 |
+
|
1194 |
+
u = u.astype(self.dtype)
|
1195 |
+
v = v.astype(self.dtype)
|
1196 |
+
return a, q, r, u, v
|
1197 |
+
|
1198 |
+
def test_sqr_rank_1(self):
|
1199 |
+
a, q, r, u, v = self.generate('sqr')
|
1200 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1201 |
+
a1 = a + np.outer(u, v.conj())
|
1202 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1203 |
+
|
1204 |
+
def test_sqr_rank_p(self):
|
1205 |
+
# test ndim = 2, rank 1 updates here too
|
1206 |
+
for p in [1, 2, 3, 5]:
|
1207 |
+
a, q, r, u, v = self.generate('sqr', p=p)
|
1208 |
+
if p == 1:
|
1209 |
+
u = u.reshape(u.size, 1)
|
1210 |
+
v = v.reshape(v.size, 1)
|
1211 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1212 |
+
a1 = a + np.dot(u, v.T.conj())
|
1213 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1214 |
+
|
1215 |
+
def test_tall_rank_1(self):
|
1216 |
+
a, q, r, u, v = self.generate('tall')
|
1217 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1218 |
+
a1 = a + np.outer(u, v.conj())
|
1219 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1220 |
+
|
1221 |
+
def test_tall_rank_p(self):
|
1222 |
+
for p in [1, 2, 3, 5]:
|
1223 |
+
a, q, r, u, v = self.generate('tall', p=p)
|
1224 |
+
if p == 1:
|
1225 |
+
u = u.reshape(u.size, 1)
|
1226 |
+
v = v.reshape(v.size, 1)
|
1227 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1228 |
+
a1 = a + np.dot(u, v.T.conj())
|
1229 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1230 |
+
|
1231 |
+
def test_fat_rank_1(self):
|
1232 |
+
a, q, r, u, v = self.generate('fat')
|
1233 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1234 |
+
a1 = a + np.outer(u, v.conj())
|
1235 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1236 |
+
|
1237 |
+
def test_fat_rank_p(self):
|
1238 |
+
for p in [1, 2, 3, 5]:
|
1239 |
+
a, q, r, u, v = self.generate('fat', p=p)
|
1240 |
+
if p == 1:
|
1241 |
+
u = u.reshape(u.size, 1)
|
1242 |
+
v = v.reshape(v.size, 1)
|
1243 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1244 |
+
a1 = a + np.dot(u, v.T.conj())
|
1245 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1246 |
+
|
1247 |
+
def test_economic_rank_1(self):
|
1248 |
+
a, q, r, u, v = self.generate('tall', 'economic')
|
1249 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1250 |
+
a1 = a + np.outer(u, v.conj())
|
1251 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
1252 |
+
|
1253 |
+
def test_economic_rank_p(self):
|
1254 |
+
for p in [1, 2, 3, 5]:
|
1255 |
+
a, q, r, u, v = self.generate('tall', 'economic', p)
|
1256 |
+
if p == 1:
|
1257 |
+
u = u.reshape(u.size, 1)
|
1258 |
+
v = v.reshape(v.size, 1)
|
1259 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1260 |
+
a1 = a + np.dot(u, v.T.conj())
|
1261 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
1262 |
+
|
1263 |
+
def test_Mx1_rank_1(self):
|
1264 |
+
a, q, r, u, v = self.generate('Mx1')
|
1265 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1266 |
+
a1 = a + np.outer(u, v.conj())
|
1267 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1268 |
+
|
1269 |
+
def test_Mx1_rank_p(self):
|
1270 |
+
# when M or N == 1, only a rank 1 update is allowed. This isn't
|
1271 |
+
# fundamental limitation, but the code does not support it.
|
1272 |
+
a, q, r, u, v = self.generate('Mx1', p=1)
|
1273 |
+
u = u.reshape(u.size, 1)
|
1274 |
+
v = v.reshape(v.size, 1)
|
1275 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1276 |
+
a1 = a + np.dot(u, v.T.conj())
|
1277 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1278 |
+
|
1279 |
+
def test_Mx1_economic_rank_1(self):
|
1280 |
+
a, q, r, u, v = self.generate('Mx1', 'economic')
|
1281 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1282 |
+
a1 = a + np.outer(u, v.conj())
|
1283 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
1284 |
+
|
1285 |
+
def test_Mx1_economic_rank_p(self):
|
1286 |
+
# when M or N == 1, only a rank 1 update is allowed. This isn't
|
1287 |
+
# fundamental limitation, but the code does not support it.
|
1288 |
+
a, q, r, u, v = self.generate('Mx1', 'economic', p=1)
|
1289 |
+
u = u.reshape(u.size, 1)
|
1290 |
+
v = v.reshape(v.size, 1)
|
1291 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1292 |
+
a1 = a + np.dot(u, v.T.conj())
|
1293 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
1294 |
+
|
1295 |
+
def test_1xN_rank_1(self):
|
1296 |
+
a, q, r, u, v = self.generate('1xN')
|
1297 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1298 |
+
a1 = a + np.outer(u, v.conj())
|
1299 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1300 |
+
|
1301 |
+
def test_1xN_rank_p(self):
|
1302 |
+
# when M or N == 1, only a rank 1 update is allowed. This isn't
|
1303 |
+
# fundamental limitation, but the code does not support it.
|
1304 |
+
a, q, r, u, v = self.generate('1xN', p=1)
|
1305 |
+
u = u.reshape(u.size, 1)
|
1306 |
+
v = v.reshape(v.size, 1)
|
1307 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1308 |
+
a1 = a + np.dot(u, v.T.conj())
|
1309 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1310 |
+
|
1311 |
+
def test_1x1_rank_1(self):
|
1312 |
+
a, q, r, u, v = self.generate('1x1')
|
1313 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1314 |
+
a1 = a + np.outer(u, v.conj())
|
1315 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1316 |
+
|
1317 |
+
def test_1x1_rank_p(self):
|
1318 |
+
# when M or N == 1, only a rank 1 update is allowed. This isn't
|
1319 |
+
# fundamental limitation, but the code does not support it.
|
1320 |
+
a, q, r, u, v = self.generate('1x1', p=1)
|
1321 |
+
u = u.reshape(u.size, 1)
|
1322 |
+
v = v.reshape(v.size, 1)
|
1323 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1324 |
+
a1 = a + np.dot(u, v.T.conj())
|
1325 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1326 |
+
|
1327 |
+
def test_1x1_rank_1_scalar(self):
|
1328 |
+
a, q, r, u, v = self.generate('1x1')
|
1329 |
+
assert_raises(ValueError, qr_update, q[0, 0], r, u, v)
|
1330 |
+
assert_raises(ValueError, qr_update, q, r[0, 0], u, v)
|
1331 |
+
assert_raises(ValueError, qr_update, q, r, u[0], v)
|
1332 |
+
assert_raises(ValueError, qr_update, q, r, u, v[0])
|
1333 |
+
|
1334 |
+
def base_non_simple_strides(self, adjust_strides, mode, p, overwriteable):
|
1335 |
+
assert_sqr = False if mode == 'economic' else True
|
1336 |
+
for type in ['sqr', 'tall', 'fat']:
|
1337 |
+
a, q0, r0, u0, v0 = self.generate(type, mode, p)
|
1338 |
+
qs, rs, us, vs = adjust_strides((q0, r0, u0, v0))
|
1339 |
+
if p == 1:
|
1340 |
+
aup = a + np.outer(u0, v0.conj())
|
1341 |
+
else:
|
1342 |
+
aup = a + np.dot(u0, v0.T.conj())
|
1343 |
+
|
1344 |
+
# for each variable, q, r, u, v we try with it strided and
|
1345 |
+
# overwrite=False. Then we try with overwrite=True, and make
|
1346 |
+
# sure that if p == 1, r and v are still overwritten.
|
1347 |
+
# a strided q and u must always be copied.
|
1348 |
+
|
1349 |
+
q = q0.copy('F')
|
1350 |
+
r = r0.copy('F')
|
1351 |
+
u = u0.copy('F')
|
1352 |
+
v = v0.copy('C')
|
1353 |
+
q1, r1 = qr_update(qs, r, u, v, False)
|
1354 |
+
check_qr(q1, r1, aup, self.rtol, self.atol, assert_sqr)
|
1355 |
+
q1o, r1o = qr_update(qs, r, u, v, True)
|
1356 |
+
check_qr(q1o, r1o, aup, self.rtol, self.atol, assert_sqr)
|
1357 |
+
if overwriteable:
|
1358 |
+
assert_allclose(r1o, r, rtol=self.rtol, atol=self.atol)
|
1359 |
+
assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
|
1360 |
+
|
1361 |
+
q = q0.copy('F')
|
1362 |
+
r = r0.copy('F')
|
1363 |
+
u = u0.copy('F')
|
1364 |
+
v = v0.copy('C')
|
1365 |
+
q2, r2 = qr_update(q, rs, u, v, False)
|
1366 |
+
check_qr(q2, r2, aup, self.rtol, self.atol, assert_sqr)
|
1367 |
+
q2o, r2o = qr_update(q, rs, u, v, True)
|
1368 |
+
check_qr(q2o, r2o, aup, self.rtol, self.atol, assert_sqr)
|
1369 |
+
if overwriteable:
|
1370 |
+
assert_allclose(r2o, rs, rtol=self.rtol, atol=self.atol)
|
1371 |
+
assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
|
1372 |
+
|
1373 |
+
q = q0.copy('F')
|
1374 |
+
r = r0.copy('F')
|
1375 |
+
u = u0.copy('F')
|
1376 |
+
v = v0.copy('C')
|
1377 |
+
q3, r3 = qr_update(q, r, us, v, False)
|
1378 |
+
check_qr(q3, r3, aup, self.rtol, self.atol, assert_sqr)
|
1379 |
+
q3o, r3o = qr_update(q, r, us, v, True)
|
1380 |
+
check_qr(q3o, r3o, aup, self.rtol, self.atol, assert_sqr)
|
1381 |
+
if overwriteable:
|
1382 |
+
assert_allclose(r3o, r, rtol=self.rtol, atol=self.atol)
|
1383 |
+
assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
|
1384 |
+
|
1385 |
+
q = q0.copy('F')
|
1386 |
+
r = r0.copy('F')
|
1387 |
+
u = u0.copy('F')
|
1388 |
+
v = v0.copy('C')
|
1389 |
+
q4, r4 = qr_update(q, r, u, vs, False)
|
1390 |
+
check_qr(q4, r4, aup, self.rtol, self.atol, assert_sqr)
|
1391 |
+
q4o, r4o = qr_update(q, r, u, vs, True)
|
1392 |
+
check_qr(q4o, r4o, aup, self.rtol, self.atol, assert_sqr)
|
1393 |
+
if overwriteable:
|
1394 |
+
assert_allclose(r4o, r, rtol=self.rtol, atol=self.atol)
|
1395 |
+
assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
|
1396 |
+
|
1397 |
+
q = q0.copy('F')
|
1398 |
+
r = r0.copy('F')
|
1399 |
+
u = u0.copy('F')
|
1400 |
+
v = v0.copy('C')
|
1401 |
+
# since some of these were consumed above
|
1402 |
+
qs, rs, us, vs = adjust_strides((q, r, u, v))
|
1403 |
+
q5, r5 = qr_update(qs, rs, us, vs, False)
|
1404 |
+
check_qr(q5, r5, aup, self.rtol, self.atol, assert_sqr)
|
1405 |
+
q5o, r5o = qr_update(qs, rs, us, vs, True)
|
1406 |
+
check_qr(q5o, r5o, aup, self.rtol, self.atol, assert_sqr)
|
1407 |
+
if overwriteable:
|
1408 |
+
assert_allclose(r5o, rs, rtol=self.rtol, atol=self.atol)
|
1409 |
+
assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
|
1410 |
+
|
1411 |
+
def test_non_unit_strides_rank_1(self):
|
1412 |
+
self.base_non_simple_strides(make_strided, 'full', 1, True)
|
1413 |
+
|
1414 |
+
def test_non_unit_strides_economic_rank_1(self):
|
1415 |
+
self.base_non_simple_strides(make_strided, 'economic', 1, True)
|
1416 |
+
|
1417 |
+
def test_non_unit_strides_rank_p(self):
|
1418 |
+
self.base_non_simple_strides(make_strided, 'full', 3, False)
|
1419 |
+
|
1420 |
+
def test_non_unit_strides_economic_rank_p(self):
|
1421 |
+
self.base_non_simple_strides(make_strided, 'economic', 3, False)
|
1422 |
+
|
1423 |
+
def test_neg_strides_rank_1(self):
|
1424 |
+
self.base_non_simple_strides(negate_strides, 'full', 1, False)
|
1425 |
+
|
1426 |
+
def test_neg_strides_economic_rank_1(self):
|
1427 |
+
self.base_non_simple_strides(negate_strides, 'economic', 1, False)
|
1428 |
+
|
1429 |
+
def test_neg_strides_rank_p(self):
|
1430 |
+
self.base_non_simple_strides(negate_strides, 'full', 3, False)
|
1431 |
+
|
1432 |
+
def test_neg_strides_economic_rank_p(self):
|
1433 |
+
self.base_non_simple_strides(negate_strides, 'economic', 3, False)
|
1434 |
+
|
1435 |
+
def test_non_itemsize_strides_rank_1(self):
|
1436 |
+
self.base_non_simple_strides(nonitemsize_strides, 'full', 1, False)
|
1437 |
+
|
1438 |
+
def test_non_itemsize_strides_economic_rank_1(self):
|
1439 |
+
self.base_non_simple_strides(nonitemsize_strides, 'economic', 1, False)
|
1440 |
+
|
1441 |
+
def test_non_itemsize_strides_rank_p(self):
|
1442 |
+
self.base_non_simple_strides(nonitemsize_strides, 'full', 3, False)
|
1443 |
+
|
1444 |
+
def test_non_itemsize_strides_economic_rank_p(self):
|
1445 |
+
self.base_non_simple_strides(nonitemsize_strides, 'economic', 3, False)
|
1446 |
+
|
1447 |
+
def test_non_native_byte_order_rank_1(self):
|
1448 |
+
self.base_non_simple_strides(make_nonnative, 'full', 1, False)
|
1449 |
+
|
1450 |
+
def test_non_native_byte_order_economic_rank_1(self):
|
1451 |
+
self.base_non_simple_strides(make_nonnative, 'economic', 1, False)
|
1452 |
+
|
1453 |
+
def test_non_native_byte_order_rank_p(self):
|
1454 |
+
self.base_non_simple_strides(make_nonnative, 'full', 3, False)
|
1455 |
+
|
1456 |
+
def test_non_native_byte_order_economic_rank_p(self):
|
1457 |
+
self.base_non_simple_strides(make_nonnative, 'economic', 3, False)
|
1458 |
+
|
1459 |
+
def test_overwrite_qruv_rank_1(self):
|
1460 |
+
# Any positive strided q, r, u, and v can be overwritten for a rank 1
|
1461 |
+
# update, only checking C and F contiguous.
|
1462 |
+
a, q0, r0, u0, v0 = self.generate('sqr')
|
1463 |
+
a1 = a + np.outer(u0, v0.conj())
|
1464 |
+
q = q0.copy('F')
|
1465 |
+
r = r0.copy('F')
|
1466 |
+
u = u0.copy('F')
|
1467 |
+
v = v0.copy('F')
|
1468 |
+
|
1469 |
+
# don't overwrite
|
1470 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1471 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1472 |
+
check_qr(q, r, a, self.rtol, self.atol)
|
1473 |
+
|
1474 |
+
q2, r2 = qr_update(q, r, u, v, True)
|
1475 |
+
check_qr(q2, r2, a1, self.rtol, self.atol)
|
1476 |
+
# verify the overwriting, no good way to check u and v.
|
1477 |
+
assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
|
1478 |
+
assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
|
1479 |
+
|
1480 |
+
q = q0.copy('C')
|
1481 |
+
r = r0.copy('C')
|
1482 |
+
u = u0.copy('C')
|
1483 |
+
v = v0.copy('C')
|
1484 |
+
q3, r3 = qr_update(q, r, u, v, True)
|
1485 |
+
check_qr(q3, r3, a1, self.rtol, self.atol)
|
1486 |
+
assert_allclose(q3, q, rtol=self.rtol, atol=self.atol)
|
1487 |
+
assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
|
1488 |
+
|
1489 |
+
def test_overwrite_qruv_rank_1_economic(self):
|
1490 |
+
# updating economic decompositions can overwrite any contiguous r,
|
1491 |
+
# and positively strided r and u. V is only ever read.
|
1492 |
+
# only checking C and F contiguous.
|
1493 |
+
a, q0, r0, u0, v0 = self.generate('tall', 'economic')
|
1494 |
+
a1 = a + np.outer(u0, v0.conj())
|
1495 |
+
q = q0.copy('F')
|
1496 |
+
r = r0.copy('F')
|
1497 |
+
u = u0.copy('F')
|
1498 |
+
v = v0.copy('F')
|
1499 |
+
|
1500 |
+
# don't overwrite
|
1501 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1502 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
1503 |
+
check_qr(q, r, a, self.rtol, self.atol, False)
|
1504 |
+
|
1505 |
+
q2, r2 = qr_update(q, r, u, v, True)
|
1506 |
+
check_qr(q2, r2, a1, self.rtol, self.atol, False)
|
1507 |
+
# verify the overwriting, no good way to check u and v.
|
1508 |
+
assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
|
1509 |
+
assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
|
1510 |
+
|
1511 |
+
q = q0.copy('C')
|
1512 |
+
r = r0.copy('C')
|
1513 |
+
u = u0.copy('C')
|
1514 |
+
v = v0.copy('C')
|
1515 |
+
q3, r3 = qr_update(q, r, u, v, True)
|
1516 |
+
check_qr(q3, r3, a1, self.rtol, self.atol, False)
|
1517 |
+
assert_allclose(q3, q, rtol=self.rtol, atol=self.atol)
|
1518 |
+
assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
|
1519 |
+
|
1520 |
+
def test_overwrite_qruv_rank_p(self):
|
1521 |
+
# for rank p updates, q r must be F contiguous, v must be C (v.T --> F)
|
1522 |
+
# and u can be C or F, but is only overwritten if Q is C and complex
|
1523 |
+
a, q0, r0, u0, v0 = self.generate('sqr', p=3)
|
1524 |
+
a1 = a + np.dot(u0, v0.T.conj())
|
1525 |
+
q = q0.copy('F')
|
1526 |
+
r = r0.copy('F')
|
1527 |
+
u = u0.copy('F')
|
1528 |
+
v = v0.copy('C')
|
1529 |
+
|
1530 |
+
# don't overwrite
|
1531 |
+
q1, r1 = qr_update(q, r, u, v, False)
|
1532 |
+
check_qr(q1, r1, a1, self.rtol, self.atol)
|
1533 |
+
check_qr(q, r, a, self.rtol, self.atol)
|
1534 |
+
|
1535 |
+
q2, r2 = qr_update(q, r, u, v, True)
|
1536 |
+
check_qr(q2, r2, a1, self.rtol, self.atol)
|
1537 |
+
# verify the overwriting, no good way to check u and v.
|
1538 |
+
assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
|
1539 |
+
assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
|
1540 |
+
|
1541 |
+
def test_empty_inputs(self):
|
1542 |
+
a, q, r, u, v = self.generate('tall')
|
1543 |
+
assert_raises(ValueError, qr_update, np.array([]), r, u, v)
|
1544 |
+
assert_raises(ValueError, qr_update, q, np.array([]), u, v)
|
1545 |
+
assert_raises(ValueError, qr_update, q, r, np.array([]), v)
|
1546 |
+
assert_raises(ValueError, qr_update, q, r, u, np.array([]))
|
1547 |
+
|
1548 |
+
def test_mismatched_shapes(self):
|
1549 |
+
a, q, r, u, v = self.generate('tall')
|
1550 |
+
assert_raises(ValueError, qr_update, q, r[1:], u, v)
|
1551 |
+
assert_raises(ValueError, qr_update, q[:-2], r, u, v)
|
1552 |
+
assert_raises(ValueError, qr_update, q, r, u[1:], v)
|
1553 |
+
assert_raises(ValueError, qr_update, q, r, u, v[1:])
|
1554 |
+
|
1555 |
+
def test_unsupported_dtypes(self):
|
1556 |
+
dts = ['int8', 'int16', 'int32', 'int64',
|
1557 |
+
'uint8', 'uint16', 'uint32', 'uint64',
|
1558 |
+
'float16', 'longdouble', 'clongdouble',
|
1559 |
+
'bool']
|
1560 |
+
a, q0, r0, u0, v0 = self.generate('tall')
|
1561 |
+
for dtype in dts:
|
1562 |
+
q = q0.real.astype(dtype)
|
1563 |
+
with np.errstate(invalid="ignore"):
|
1564 |
+
r = r0.real.astype(dtype)
|
1565 |
+
u = u0.real.astype(dtype)
|
1566 |
+
v = v0.real.astype(dtype)
|
1567 |
+
assert_raises(ValueError, qr_update, q, r0, u0, v0)
|
1568 |
+
assert_raises(ValueError, qr_update, q0, r, u0, v0)
|
1569 |
+
assert_raises(ValueError, qr_update, q0, r0, u, v0)
|
1570 |
+
assert_raises(ValueError, qr_update, q0, r0, u0, v)
|
1571 |
+
|
1572 |
+
def test_integer_input(self):
|
1573 |
+
q = np.arange(16).reshape(4, 4)
|
1574 |
+
r = q.copy() # doesn't matter
|
1575 |
+
u = q[:, 0].copy()
|
1576 |
+
v = r[0, :].copy()
|
1577 |
+
assert_raises(ValueError, qr_update, q, r, u, v)
|
1578 |
+
|
1579 |
+
def test_check_finite(self):
|
1580 |
+
a0, q0, r0, u0, v0 = self.generate('tall', p=3)
|
1581 |
+
|
1582 |
+
q = q0.copy('F')
|
1583 |
+
q[1,1] = np.nan
|
1584 |
+
assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0])
|
1585 |
+
assert_raises(ValueError, qr_update, q, r0, u0, v0)
|
1586 |
+
|
1587 |
+
r = r0.copy('F')
|
1588 |
+
r[1,1] = np.nan
|
1589 |
+
assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0])
|
1590 |
+
assert_raises(ValueError, qr_update, q0, r, u0, v0)
|
1591 |
+
|
1592 |
+
u = u0.copy('F')
|
1593 |
+
u[0,0] = np.nan
|
1594 |
+
assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0])
|
1595 |
+
assert_raises(ValueError, qr_update, q0, r0, u, v0)
|
1596 |
+
|
1597 |
+
v = v0.copy('F')
|
1598 |
+
v[0,0] = np.nan
|
1599 |
+
assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0])
|
1600 |
+
assert_raises(ValueError, qr_update, q0, r0, u, v)
|
1601 |
+
|
1602 |
+
def test_economic_check_finite(self):
|
1603 |
+
a0, q0, r0, u0, v0 = self.generate('tall', mode='economic', p=3)
|
1604 |
+
|
1605 |
+
q = q0.copy('F')
|
1606 |
+
q[1,1] = np.nan
|
1607 |
+
assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0])
|
1608 |
+
assert_raises(ValueError, qr_update, q, r0, u0, v0)
|
1609 |
+
|
1610 |
+
r = r0.copy('F')
|
1611 |
+
r[1,1] = np.nan
|
1612 |
+
assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0])
|
1613 |
+
assert_raises(ValueError, qr_update, q0, r, u0, v0)
|
1614 |
+
|
1615 |
+
u = u0.copy('F')
|
1616 |
+
u[0,0] = np.nan
|
1617 |
+
assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0])
|
1618 |
+
assert_raises(ValueError, qr_update, q0, r0, u, v0)
|
1619 |
+
|
1620 |
+
v = v0.copy('F')
|
1621 |
+
v[0,0] = np.nan
|
1622 |
+
assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0])
|
1623 |
+
assert_raises(ValueError, qr_update, q0, r0, u, v)
|
1624 |
+
|
1625 |
+
def test_u_exactly_in_span_q(self):
|
1626 |
+
q = np.array([[0, 0], [0, 0], [1, 0], [0, 1]], self.dtype)
|
1627 |
+
r = np.array([[1, 0], [0, 1]], self.dtype)
|
1628 |
+
u = np.array([0, 0, 0, -1], self.dtype)
|
1629 |
+
v = np.array([1, 2], self.dtype)
|
1630 |
+
q1, r1 = qr_update(q, r, u, v)
|
1631 |
+
a1 = np.dot(q, r) + np.outer(u, v.conj())
|
1632 |
+
check_qr(q1, r1, a1, self.rtol, self.atol, False)
|
1633 |
+
|
1634 |
+
class TestQRupdate_f(BaseQRupdate):
|
1635 |
+
dtype = np.dtype('f')
|
1636 |
+
|
1637 |
+
class TestQRupdate_F(BaseQRupdate):
|
1638 |
+
dtype = np.dtype('F')
|
1639 |
+
|
1640 |
+
class TestQRupdate_d(BaseQRupdate):
|
1641 |
+
dtype = np.dtype('d')
|
1642 |
+
|
1643 |
+
class TestQRupdate_D(BaseQRupdate):
|
1644 |
+
dtype = np.dtype('D')
|
1645 |
+
|
1646 |
+
def test_form_qTu():
|
1647 |
+
# We want to ensure that all of the code paths through this function are
|
1648 |
+
# tested. Most of them should be hit with the rest of test suite, but
|
1649 |
+
# explicit tests make clear precisely what is being tested.
|
1650 |
+
#
|
1651 |
+
# This function expects that Q is either C or F contiguous and square.
|
1652 |
+
# Economic mode decompositions (Q is (M, N), M != N) do not go through this
|
1653 |
+
# function. U may have any positive strides.
|
1654 |
+
#
|
1655 |
+
# Some of these test are duplicates, since contiguous 1d arrays are both C
|
1656 |
+
# and F.
|
1657 |
+
|
1658 |
+
q_order = ['F', 'C']
|
1659 |
+
q_shape = [(8, 8), ]
|
1660 |
+
u_order = ['F', 'C', 'A'] # here A means is not F not C
|
1661 |
+
u_shape = [1, 3]
|
1662 |
+
dtype = ['f', 'd', 'F', 'D']
|
1663 |
+
|
1664 |
+
for qo, qs, uo, us, d in \
|
1665 |
+
itertools.product(q_order, q_shape, u_order, u_shape, dtype):
|
1666 |
+
if us == 1:
|
1667 |
+
check_form_qTu(qo, qs, uo, us, 1, d)
|
1668 |
+
check_form_qTu(qo, qs, uo, us, 2, d)
|
1669 |
+
else:
|
1670 |
+
check_form_qTu(qo, qs, uo, us, 2, d)
|
1671 |
+
|
1672 |
+
def check_form_qTu(q_order, q_shape, u_order, u_shape, u_ndim, dtype):
|
1673 |
+
np.random.seed(47)
|
1674 |
+
if u_shape == 1 and u_ndim == 1:
|
1675 |
+
u_shape = (q_shape[0],)
|
1676 |
+
else:
|
1677 |
+
u_shape = (q_shape[0], u_shape)
|
1678 |
+
dtype = np.dtype(dtype)
|
1679 |
+
|
1680 |
+
if dtype.char in 'fd':
|
1681 |
+
q = np.random.random(q_shape)
|
1682 |
+
u = np.random.random(u_shape)
|
1683 |
+
elif dtype.char in 'FD':
|
1684 |
+
q = np.random.random(q_shape) + 1j*np.random.random(q_shape)
|
1685 |
+
u = np.random.random(u_shape) + 1j*np.random.random(u_shape)
|
1686 |
+
else:
|
1687 |
+
ValueError("form_qTu doesn't support this dtype")
|
1688 |
+
|
1689 |
+
q = np.require(q, dtype, q_order)
|
1690 |
+
if u_order != 'A':
|
1691 |
+
u = np.require(u, dtype, u_order)
|
1692 |
+
else:
|
1693 |
+
u, = make_strided((u.astype(dtype),))
|
1694 |
+
|
1695 |
+
rtol = 10.0 ** -(np.finfo(dtype).precision-2)
|
1696 |
+
atol = 2*np.finfo(dtype).eps
|
1697 |
+
|
1698 |
+
expected = np.dot(q.T.conj(), u)
|
1699 |
+
res = _decomp_update._form_qTu(q, u)
|
1700 |
+
assert_allclose(res, expected, rtol=rtol, atol=atol)
|