Commit ·
2b111dd
1
Parent(s): 97093c8
Upload folder using huggingface_hub (part 14)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+67
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_blas.pxdAdded+169
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_blas.pyxAdded+1432
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_lapack.cpython-311-x86_64-linux-gnu.soAdded+3
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_lapack.pxdAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_lapack.pyxAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp.pyAdded+23
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp_cholesky.pyAdded+21
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp_lu.pyAdded+21
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp_qr.pyAdded+20
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp_schur.pyAdded+21
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp_svd.pyAdded+21
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/interpolative.pyAdded+989
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/lapack.pyAdded+1061
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/matfuncs.pyAdded+23
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/misc.pyAdded+21
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/special_matrices.pyAdded+22
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/__init__.pyAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/_cython_examples/extending.pyxAdded+23
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/_cython_examples/meson.buildAdded+27
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/carex_15_data.npzAdded+3
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/carex_18_data.npzAdded+3
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/carex_19_data.npzAdded+3
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/carex_20_data.npzAdded+3
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/carex_6_data.npzAdded+3
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npzAdded+3
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_basic.pyAdded+2059
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_blas.pyAdded+1127
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_cython_blas.pyAdded+118
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_cython_lapack.pyAdded+22
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_cythonized_array_utils.pyAdded+132
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp.pyAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_cholesky.pyAdded+268
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_cossin.pyAdded+300
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_ldl.pyAdded+137
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_lu.pyAdded+308
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_polar.pyAdded+110
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_update.pyAdded+1701
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_extending.pyAdded+46
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_fblas.pyAdded+607
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_interpolative.pyAdded+232
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_lapack.pyAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_matfuncs.pyAdded+1063
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_matmul_toeplitz.pyAdded+136
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_procrustes.pyAdded+221
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_sketches.pyAdded+118
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_solve_toeplitz.pyAdded+150
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_solvers.pyAdded+844
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_special_matrices.pyAdded+640
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/misc/__init__.pyAdded+6
1133 unmodified lines1134113511361133 unmodified linespace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/_solve_toeplitz.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_blas.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text1133 unmodified lines11341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031133 unmodified linespace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/_solve_toeplitz.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_blas.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_lapack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/ndimage/_nd_image.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/ndimage/_ni_label.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/odr/__odrpack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/__pycache__/_optimize.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/_bglu_dense.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/_cobyla.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/_cython_nnls.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/_highspy/_core.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/_highspy/_highs_options.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/_lbfgsb.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/_lsq/givens_elimination.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/_moduleTNC.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/_pava_pybind.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/_trlib/_trlib.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/signal/__pycache__/_filter_design.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/signal/__pycache__/_ltisys.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/signal/__pycache__/_signaltools.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/signal/_peak_finding_utils.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/signal/_sosfilt.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/signal/_upfirdn_apply.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/_csparsetools.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/_sparsetools.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/csgraph/_flow.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/csgraph/_matching.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/csgraph/_min_spanning_tree.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/csgraph/_reordering.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/csgraph/_shortest_path.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/csgraph/_tools.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/csgraph/_traversal.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/linalg/_dsolve/_superlu.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/linalg/_eigen/arpack/_arpack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/linalg/_propack/_cpropack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/linalg/_propack/_dpropack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/linalg/_propack/_spropack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/sparse/linalg/_propack/_zpropack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/spatial/__pycache__/distance.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/spatial/_ckdtree.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/spatial/_distance_pybind.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/spatial/_distance_wrap.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/spatial/_hausdorff.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/spatial/_qhull.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/spatial/_voronoi.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/spatial/transform/_rotation.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/special/__pycache__/_basic.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/special/_ellip_harm_2.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/special/_gufuncs.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/special/_specfun.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/special/_special_ufuncs.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/special/_test_internal.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/special/_ufuncs.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/special/_ufuncs_cxx.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/special/cython_special.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_continuous_distns.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_discrete_distns.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_distn_infrastructure.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_distribution_infrastructure.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_morestats.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_mstats_basic.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_multivariate.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_qmc.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_resampling.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/__pycache__/_stats_py.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_ansari_swilk_statistics.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/stats/_biasedurn.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169"""This file was generated by _generate_pyx.py.Do not edit this file directly."""
# Within scipy, these wrappers can be used via relative or absolute cimport.# Examples:# from ..linalg cimport cython_blas# from scipy.linalg cimport cython_blas# cimport scipy.linalg.cython_blas as cython_blas# cimport ..linalg.cython_blas as cython_blas
# Within SciPy, if BLAS functions are needed in C/C++/Fortran,# these wrappers should not be used.# The original libraries should be linked directly.
ctypedef float sctypedef double dctypedef float complex cctypedef double complex z
cdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogilcdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogilcdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogilcdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogilcdef void cgbmv(char *trans, int *m, int *n, int *kl, int *ku, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogilcdef void cgemm(char *transa, char *transb, int *m, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogilcdef void cgemv(char *trans, int *m, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogilcdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogilcdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogilcdef void chbmv(char *uplo, int *n, int *k, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogilcdef void chemm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogilcdef void chemv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogilcdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogilcdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogilcdef void cher2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, s *beta, c *c, int *ldc) noexcept nogilcdef void cherk(char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c, int *ldc) noexcept nogilcdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogilcdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogilcdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogilcdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogilcdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogilcdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogilcdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogilcdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogilcdef void csymm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogilcdef void csyr2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogilcdef void csyrk(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *beta, c *c, int *ldc) noexcept nogilcdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogilcdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogilcdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogilcdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogilcdef void ctrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogilcdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogilcdef void ctrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogilcdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogilcdef d dasum(int *n, d *dx, int *incx) noexcept nogilcdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogilcdef d dcabs1(z *z) noexcept nogilcdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogilcdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogilcdef void dgbmv(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogilcdef void dgemm(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogilcdef void dgemv(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogilcdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogilcdef d dnrm2(int *n, d *x, int *incx) noexcept nogilcdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogilcdef void drotg(d *da, d *db, d *c, d *s) noexcept nogilcdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogilcdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogilcdef void dsbmv(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogilcdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogilcdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogilcdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogilcdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogilcdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogilcdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogilcdef void dsymm(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogilcdef void dsymv(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogilcdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogilcdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogilcdef void dsyr2k(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogilcdef void dsyrk(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) noexcept nogilcdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogilcdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogilcdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogilcdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogilcdef void dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogilcdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogilcdef void dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogilcdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogilcdef d dzasum(int *n, z *zx, int *incx) noexcept nogilcdef d dznrm2(int *n, z *x, int *incx) noexcept nogilcdef int icamax(int *n, c *cx, int *incx) noexcept nogilcdef int idamax(int *n, d *dx, int *incx) noexcept nogilcdef int isamax(int *n, s *sx, int *incx) noexcept nogilcdef int izamax(int *n, z *zx, int *incx) noexcept nogilcdef bint lsame(char *ca, char *cb) noexcept nogilcdef s sasum(int *n, s *sx, int *incx) noexcept nogilcdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogilcdef s scasum(int *n, c *cx, int *incx) noexcept nogilcdef s scnrm2(int *n, c *x, int *incx) noexcept nogilcdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogilcdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogilcdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogilcdef void sgbmv(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogilcdef void sgemm(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogilcdef void sgemv(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogilcdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogilcdef s snrm2(int *n, s *x, int *incx) noexcept nogilcdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogilcdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogilcdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogilcdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogilcdef void ssbmv(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogilcdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogilcdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogilcdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogilcdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogilcdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogilcdef void ssymm(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogilcdef void ssymv(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogilcdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogilcdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogilcdef void ssyr2k(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogilcdef void ssyrk(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) noexcept nogilcdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogilcdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogilcdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogilcdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogilcdef void strmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogilcdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogilcdef void strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogilcdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogilcdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogilcdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogilcdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogilcdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogilcdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogilcdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogilcdef void zgbmv(char *trans, int *m, int *n, int *kl, int *ku, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogilcdef void zgemm(char *transa, char *transb, int *m, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogilcdef void zgemv(char *trans, int *m, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogilcdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogilcdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogilcdef void zhbmv(char *uplo, int *n, int *k, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogilcdef void zhemm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogilcdef void zhemv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogilcdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogilcdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogilcdef void zher2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, d *beta, z *c, int *ldc) noexcept nogilcdef void zherk(char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c, int *ldc) noexcept nogilcdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogilcdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogilcdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogilcdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogilcdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogilcdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogilcdef void zsymm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogilcdef void zsyr2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogilcdef void zsyrk(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *beta, z *c, int *ldc) noexcept nogilcdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogilcdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogilcdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogilcdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogilcdef void ztrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogilcdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogilcdef void ztrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogilcdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432# This file was generated by _generate_pyx.py.# Do not edit this file directly.# cython: boundscheck = False# cython: wraparound = False# cython: cdivision = True
"""BLAS Functions for Cython=========================
Usable from Cython via::
cimport scipy.linalg.cython_blas
These wrappers do not check for alignment of arrays.Alignment should be checked before these wrappers are used.
If using ``cdotu``, ``cdotc``, ``zdotu``, ``zdotc``, ``sladiv``, or ``dladiv``,the ``CYTHON_CCOMPLEX`` define must be set to 0 during compilation. Forexample, in a ``meson.build`` file when using Meson::
py.extension_module('ext_module' 'ext_module.pyx', c_args: ['-DCYTHON_CCOMPLEX=0'], ... )
Raw function pointers (Fortran-style pointer arguments):
- caxpy- ccopy- cdotc- cdotu- cgbmv- cgemm- cgemv- cgerc- cgeru- chbmv- chemm- chemv- cher- cher2- cher2k- cherk- chpmv- chpr- chpr2- crotg- cscal- csrot- csscal- cswap- csymm- csyr2k- csyrk- ctbmv- ctbsv- ctpmv- ctpsv- ctrmm- ctrmv- ctrsm- ctrsv- dasum- daxpy- dcabs1- dcopy- ddot- dgbmv- dgemm- dgemv- dger- dnrm2- drot- drotg- drotm- drotmg- dsbmv- dscal- dsdot- dspmv- dspr- dspr2- dswap- dsymm- dsymv- dsyr- dsyr2- dsyr2k- dsyrk- dtbmv- dtbsv- dtpmv- dtpsv- dtrmm- dtrmv- dtrsm- dtrsv- dzasum- dznrm2- icamax- idamax- isamax- izamax- lsame- sasum- saxpy- scasum- scnrm2- scopy- sdot- sdsdot- sgbmv- sgemm- sgemv- sger- snrm2- srot- srotg- srotm- srotmg- ssbmv- sscal- sspmv- sspr- sspr2- sswap- ssymm- ssymv- ssyr- ssyr2- ssyr2k- ssyrk- stbmv- stbsv- stpmv- stpsv- strmm- strmv- strsm- strsv- zaxpy- zcopy- zdotc- zdotu- zdrot- zdscal- zgbmv- zgemm- zgemv- zgerc- zgeru- zhbmv- zhemm- zhemv- zher- zher2- zher2k- zherk- zhpmv- zhpr- zhpr2- zrotg- zscal- zswap- zsymm- zsyr2k- zsyrk- ztbmv- ztbsv- ztpmv- ztpsv- ztrmm- ztrmv- ztrsm- ztrsv
"""
# Within SciPy, these wrappers can be used via relative or absolute cimport.# Examples:# from ..linalg cimport cython_blas# from scipy.linalg cimport cython_blas# cimport scipy.linalg.cython_blas as cython_blas# cimport ..linalg.cython_blas as cython_blas
# Within SciPy, if BLAS functions are needed in C/C++/Fortran,# these wrappers should not be used.# The original libraries should be linked directly.
cdef extern from "fortran_defs.h": pass
from numpy cimport npy_complex64, npy_complex128
cdef extern from "_blas_subroutines.h": void _fortran_caxpy "BLAS_FUNC(caxpy)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogilcdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogil: _fortran_caxpy(n, <npy_complex64*>ca, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy)
cdef extern from "_blas_subroutines.h": void _fortran_ccopy "BLAS_FUNC(ccopy)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogilcdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil: _fortran_ccopy(n, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy)
cdef extern from "_blas_subroutines.h": void _fortran_cdotc "F_FUNC(cdotcwrp,CDOTCWRP)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogilcdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil: cdef c out _fortran_cdotc(<npy_complex64*>&out, n, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy) return out
cdef extern from "_blas_subroutines.h": void _fortran_cdotu "F_FUNC(cdotuwrp,CDOTUWRP)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogilcdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil: cdef c out _fortran_cdotu(<npy_complex64*>&out, n, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy) return out
cdef extern from "_blas_subroutines.h": void _fortran_cgbmv "BLAS_FUNC(cgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogilcdef void cgbmv(char *trans, int *m, int *n, int *kl, int *ku, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: _fortran_cgbmv(trans, m, n, kl, ku, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>x, incx, <npy_complex64*>beta, <npy_complex64*>y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_cgemm "BLAS_FUNC(cgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogilcdef void cgemm(char *transa, char *transb, int *m, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil: _fortran_cgemm(transa, transb, m, n, k, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb, <npy_complex64*>beta, <npy_complex64*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_cgemv "BLAS_FUNC(cgemv)"(char *trans, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogilcdef void cgemv(char *trans, int *m, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: _fortran_cgemv(trans, m, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>x, incx, <npy_complex64*>beta, <npy_complex64*>y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_cgerc "BLAS_FUNC(cgerc)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogilcdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil: _fortran_cgerc(m, n, <npy_complex64*>alpha, <npy_complex64*>x, incx, <npy_complex64*>y, incy, <npy_complex64*>a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_cgeru "BLAS_FUNC(cgeru)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogilcdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil: _fortran_cgeru(m, n, <npy_complex64*>alpha, <npy_complex64*>x, incx, <npy_complex64*>y, incy, <npy_complex64*>a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_chbmv "BLAS_FUNC(chbmv)"(char *uplo, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogilcdef void chbmv(char *uplo, int *n, int *k, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: _fortran_chbmv(uplo, n, k, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>x, incx, <npy_complex64*>beta, <npy_complex64*>y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_chemm "BLAS_FUNC(chemm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogilcdef void chemm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil: _fortran_chemm(side, uplo, m, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb, <npy_complex64*>beta, <npy_complex64*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_chemv "BLAS_FUNC(chemv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogilcdef void chemv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: _fortran_chemv(uplo, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>x, incx, <npy_complex64*>beta, <npy_complex64*>y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_cher "BLAS_FUNC(cher)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda) nogilcdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil: _fortran_cher(uplo, n, alpha, <npy_complex64*>x, incx, <npy_complex64*>a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_cher2 "BLAS_FUNC(cher2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogilcdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil: _fortran_cher2(uplo, n, <npy_complex64*>alpha, <npy_complex64*>x, incx, <npy_complex64*>y, incy, <npy_complex64*>a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_cher2k "BLAS_FUNC(cher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *beta, npy_complex64 *c, int *ldc) nogilcdef void cher2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, s *beta, c *c, int *ldc) noexcept nogil: _fortran_cher2k(uplo, trans, n, k, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb, beta, <npy_complex64*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_cherk "BLAS_FUNC(cherk)"(char *uplo, char *trans, int *n, int *k, s *alpha, npy_complex64 *a, int *lda, s *beta, npy_complex64 *c, int *ldc) nogilcdef void cherk(char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c, int *ldc) noexcept nogil: _fortran_cherk(uplo, trans, n, k, alpha, <npy_complex64*>a, lda, beta, <npy_complex64*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_chpmv "BLAS_FUNC(chpmv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogilcdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: _fortran_chpmv(uplo, n, <npy_complex64*>alpha, <npy_complex64*>ap, <npy_complex64*>x, incx, <npy_complex64*>beta, <npy_complex64*>y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_chpr "BLAS_FUNC(chpr)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap) nogilcdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogil: _fortran_chpr(uplo, n, alpha, <npy_complex64*>x, incx, <npy_complex64*>ap)
cdef extern from "_blas_subroutines.h": void _fortran_chpr2 "BLAS_FUNC(chpr2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *ap) nogilcdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogil: _fortran_chpr2(uplo, n, <npy_complex64*>alpha, <npy_complex64*>x, incx, <npy_complex64*>y, incy, <npy_complex64*>ap)
cdef extern from "_blas_subroutines.h": void _fortran_crotg "BLAS_FUNC(crotg)"(npy_complex64 *ca, npy_complex64 *cb, s *c, npy_complex64 *s) nogilcdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogil: _fortran_crotg(<npy_complex64*>ca, <npy_complex64*>cb, c, <npy_complex64*>s)
cdef extern from "_blas_subroutines.h": void _fortran_cscal "BLAS_FUNC(cscal)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx) nogilcdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogil: _fortran_cscal(n, <npy_complex64*>ca, <npy_complex64*>cx, incx)
cdef extern from "_blas_subroutines.h": void _fortran_csrot "BLAS_FUNC(csrot)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, s *c, s *s) nogilcdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogil: _fortran_csrot(n, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy, c, s)
cdef extern from "_blas_subroutines.h": void _fortran_csscal "BLAS_FUNC(csscal)"(int *n, s *sa, npy_complex64 *cx, int *incx) nogilcdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogil: _fortran_csscal(n, sa, <npy_complex64*>cx, incx)
cdef extern from "_blas_subroutines.h": void _fortran_cswap "BLAS_FUNC(cswap)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogilcdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil: _fortran_cswap(n, <npy_complex64*>cx, incx, <npy_complex64*>cy, incy)
cdef extern from "_blas_subroutines.h": void _fortran_csymm "BLAS_FUNC(csymm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogilcdef void csymm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil: _fortran_csymm(side, uplo, m, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb, <npy_complex64*>beta, <npy_complex64*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_csyr2k "BLAS_FUNC(csyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogilcdef void csyr2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil: _fortran_csyr2k(uplo, trans, n, k, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb, <npy_complex64*>beta, <npy_complex64*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_csyrk "BLAS_FUNC(csyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogilcdef void csyrk(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *beta, c *c, int *ldc) noexcept nogil: _fortran_csyrk(uplo, trans, n, k, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>beta, <npy_complex64*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_ctbmv "BLAS_FUNC(ctbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogilcdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil: _fortran_ctbmv(uplo, trans, diag, n, k, <npy_complex64*>a, lda, <npy_complex64*>x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_ctbsv "BLAS_FUNC(ctbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogilcdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil: _fortran_ctbsv(uplo, trans, diag, n, k, <npy_complex64*>a, lda, <npy_complex64*>x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_ctpmv "BLAS_FUNC(ctpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogilcdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil: _fortran_ctpmv(uplo, trans, diag, n, <npy_complex64*>ap, <npy_complex64*>x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_ctpsv "BLAS_FUNC(ctpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogilcdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil: _fortran_ctpsv(uplo, trans, diag, n, <npy_complex64*>ap, <npy_complex64*>x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_ctrmm "BLAS_FUNC(ctrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogilcdef void ctrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil: _fortran_ctrmm(side, uplo, transa, diag, m, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb)
cdef extern from "_blas_subroutines.h": void _fortran_ctrmv "BLAS_FUNC(ctrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogilcdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil: _fortran_ctrmv(uplo, trans, diag, n, <npy_complex64*>a, lda, <npy_complex64*>x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_ctrsm "BLAS_FUNC(ctrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogilcdef void ctrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil: _fortran_ctrsm(side, uplo, transa, diag, m, n, <npy_complex64*>alpha, <npy_complex64*>a, lda, <npy_complex64*>b, ldb)
cdef extern from "_blas_subroutines.h": void _fortran_ctrsv "BLAS_FUNC(ctrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogilcdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil: _fortran_ctrsv(uplo, trans, diag, n, <npy_complex64*>a, lda, <npy_complex64*>x, incx)
cdef extern from "_blas_subroutines.h": d _fortran_dasum "BLAS_FUNC(dasum)"(int *n, d *dx, int *incx) nogilcdef d dasum(int *n, d *dx, int *incx) noexcept nogil: return _fortran_dasum(n, dx, incx)
cdef extern from "_blas_subroutines.h": void _fortran_daxpy "BLAS_FUNC(daxpy)"(int *n, d *da, d *dx, int *incx, d *dy, int *incy) nogilcdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogil: _fortran_daxpy(n, da, dx, incx, dy, incy)
cdef extern from "_blas_subroutines.h": d _fortran_dcabs1 "BLAS_FUNC(dcabs1)"(npy_complex128 *z) nogilcdef d dcabs1(z *z) noexcept nogil: return _fortran_dcabs1(<npy_complex128*>z)
cdef extern from "_blas_subroutines.h": void _fortran_dcopy "BLAS_FUNC(dcopy)"(int *n, d *dx, int *incx, d *dy, int *incy) nogilcdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil: _fortran_dcopy(n, dx, incx, dy, incy)
cdef extern from "_blas_subroutines.h": d _fortran_ddot "BLAS_FUNC(ddot)"(int *n, d *dx, int *incx, d *dy, int *incy) nogilcdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil: return _fortran_ddot(n, dx, incx, dy, incy)
cdef extern from "_blas_subroutines.h": void _fortran_dgbmv "BLAS_FUNC(dgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogilcdef void dgbmv(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil: _fortran_dgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_dgemm "BLAS_FUNC(dgemm)"(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogilcdef void dgemm(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil: _fortran_dgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_dgemv "BLAS_FUNC(dgemv)"(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogilcdef void dgemv(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil: _fortran_dgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_dger "BLAS_FUNC(dger)"(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogilcdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil: _fortran_dger(m, n, alpha, x, incx, y, incy, a, lda)
cdef extern from "_blas_subroutines.h": d _fortran_dnrm2 "BLAS_FUNC(dnrm2)"(int *n, d *x, int *incx) nogilcdef d dnrm2(int *n, d *x, int *incx) noexcept nogil: return _fortran_dnrm2(n, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_drot "BLAS_FUNC(drot)"(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) nogilcdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogil: _fortran_drot(n, dx, incx, dy, incy, c, s)
cdef extern from "_blas_subroutines.h": void _fortran_drotg "BLAS_FUNC(drotg)"(d *da, d *db, d *c, d *s) nogilcdef void drotg(d *da, d *db, d *c, d *s) noexcept nogil: _fortran_drotg(da, db, c, s)
cdef extern from "_blas_subroutines.h": void _fortran_drotm "BLAS_FUNC(drotm)"(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) nogilcdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogil: _fortran_drotm(n, dx, incx, dy, incy, dparam)
cdef extern from "_blas_subroutines.h": void _fortran_drotmg "BLAS_FUNC(drotmg)"(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) nogilcdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogil: _fortran_drotmg(dd1, dd2, dx1, dy1, dparam)
cdef extern from "_blas_subroutines.h": void _fortran_dsbmv "BLAS_FUNC(dsbmv)"(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogilcdef void dsbmv(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil: _fortran_dsbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_dscal "BLAS_FUNC(dscal)"(int *n, d *da, d *dx, int *incx) nogilcdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogil: _fortran_dscal(n, da, dx, incx)
cdef extern from "_blas_subroutines.h": d _fortran_dsdot "BLAS_FUNC(dsdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogilcdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil: return _fortran_dsdot(n, sx, incx, sy, incy)
cdef extern from "_blas_subroutines.h": void _fortran_dspmv "BLAS_FUNC(dspmv)"(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) nogilcdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil: _fortran_dspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_dspr "BLAS_FUNC(dspr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) nogilcdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogil: _fortran_dspr(uplo, n, alpha, x, incx, ap)
cdef extern from "_blas_subroutines.h": void _fortran_dspr2 "BLAS_FUNC(dspr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) nogilcdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogil: _fortran_dspr2(uplo, n, alpha, x, incx, y, incy, ap)
cdef extern from "_blas_subroutines.h": void _fortran_dswap "BLAS_FUNC(dswap)"(int *n, d *dx, int *incx, d *dy, int *incy) nogilcdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil: _fortran_dswap(n, dx, incx, dy, incy)
cdef extern from "_blas_subroutines.h": void _fortran_dsymm "BLAS_FUNC(dsymm)"(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogilcdef void dsymm(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil: _fortran_dsymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_dsymv "BLAS_FUNC(dsymv)"(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogilcdef void dsymv(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil: _fortran_dsymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_dsyr "BLAS_FUNC(dsyr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) nogilcdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogil: _fortran_dsyr(uplo, n, alpha, x, incx, a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_dsyr2 "BLAS_FUNC(dsyr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogilcdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil: _fortran_dsyr2(uplo, n, alpha, x, incx, y, incy, a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_dsyr2k "BLAS_FUNC(dsyr2k)"(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogilcdef void dsyr2k(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil: _fortran_dsyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_dsyrk "BLAS_FUNC(dsyrk)"(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) nogilcdef void dsyrk(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) noexcept nogil: _fortran_dsyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_dtbmv "BLAS_FUNC(dtbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogilcdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil: _fortran_dtbmv(uplo, trans, diag, n, k, a, lda, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_dtbsv "BLAS_FUNC(dtbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogilcdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil: _fortran_dtbsv(uplo, trans, diag, n, k, a, lda, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_dtpmv "BLAS_FUNC(dtpmv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogilcdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil: _fortran_dtpmv(uplo, trans, diag, n, ap, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_dtpsv "BLAS_FUNC(dtpsv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogilcdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil: _fortran_dtpsv(uplo, trans, diag, n, ap, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_dtrmm "BLAS_FUNC(dtrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) nogilcdef void dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil: _fortran_dtrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
cdef extern from "_blas_subroutines.h": void _fortran_dtrmv "BLAS_FUNC(dtrmv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogilcdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil: _fortran_dtrmv(uplo, trans, diag, n, a, lda, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_dtrsm "BLAS_FUNC(dtrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) nogilcdef void dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil: _fortran_dtrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
cdef extern from "_blas_subroutines.h": void _fortran_dtrsv "BLAS_FUNC(dtrsv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogilcdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil: _fortran_dtrsv(uplo, trans, diag, n, a, lda, x, incx)
cdef extern from "_blas_subroutines.h": d _fortran_dzasum "BLAS_FUNC(dzasum)"(int *n, npy_complex128 *zx, int *incx) nogilcdef d dzasum(int *n, z *zx, int *incx) noexcept nogil: return _fortran_dzasum(n, <npy_complex128*>zx, incx)
cdef extern from "_blas_subroutines.h": d _fortran_dznrm2 "BLAS_FUNC(dznrm2)"(int *n, npy_complex128 *x, int *incx) nogilcdef d dznrm2(int *n, z *x, int *incx) noexcept nogil: return _fortran_dznrm2(n, <npy_complex128*>x, incx)
cdef extern from "_blas_subroutines.h": int _fortran_icamax "BLAS_FUNC(icamax)"(int *n, npy_complex64 *cx, int *incx) nogilcdef int icamax(int *n, c *cx, int *incx) noexcept nogil: return _fortran_icamax(n, <npy_complex64*>cx, incx)
cdef extern from "_blas_subroutines.h": int _fortran_idamax "BLAS_FUNC(idamax)"(int *n, d *dx, int *incx) nogilcdef int idamax(int *n, d *dx, int *incx) noexcept nogil: return _fortran_idamax(n, dx, incx)
cdef extern from "_blas_subroutines.h": int _fortran_isamax "BLAS_FUNC(isamax)"(int *n, s *sx, int *incx) nogilcdef int isamax(int *n, s *sx, int *incx) noexcept nogil: return _fortran_isamax(n, sx, incx)
cdef extern from "_blas_subroutines.h": int _fortran_izamax "BLAS_FUNC(izamax)"(int *n, npy_complex128 *zx, int *incx) nogilcdef int izamax(int *n, z *zx, int *incx) noexcept nogil: return _fortran_izamax(n, <npy_complex128*>zx, incx)
cdef extern from "_blas_subroutines.h": bint _fortran_lsame "BLAS_FUNC(lsame)"(char *ca, char *cb) nogilcdef bint lsame(char *ca, char *cb) noexcept nogil: return _fortran_lsame(ca, cb)
cdef extern from "_blas_subroutines.h": s _fortran_sasum "BLAS_FUNC(sasum)"(int *n, s *sx, int *incx) nogilcdef s sasum(int *n, s *sx, int *incx) noexcept nogil: return _fortran_sasum(n, sx, incx)
cdef extern from "_blas_subroutines.h": void _fortran_saxpy "BLAS_FUNC(saxpy)"(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) nogilcdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogil: _fortran_saxpy(n, sa, sx, incx, sy, incy)
cdef extern from "_blas_subroutines.h": s _fortran_scasum "BLAS_FUNC(scasum)"(int *n, npy_complex64 *cx, int *incx) nogilcdef s scasum(int *n, c *cx, int *incx) noexcept nogil: return _fortran_scasum(n, <npy_complex64*>cx, incx)
cdef extern from "_blas_subroutines.h": s _fortran_scnrm2 "BLAS_FUNC(scnrm2)"(int *n, npy_complex64 *x, int *incx) nogilcdef s scnrm2(int *n, c *x, int *incx) noexcept nogil: return _fortran_scnrm2(n, <npy_complex64*>x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_scopy "BLAS_FUNC(scopy)"(int *n, s *sx, int *incx, s *sy, int *incy) nogilcdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil: _fortran_scopy(n, sx, incx, sy, incy)
cdef extern from "_blas_subroutines.h": s _fortran_sdot "BLAS_FUNC(sdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogilcdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil: return _fortran_sdot(n, sx, incx, sy, incy)
cdef extern from "_blas_subroutines.h": s _fortran_sdsdot "BLAS_FUNC(sdsdot)"(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) nogilcdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogil: return _fortran_sdsdot(n, sb, sx, incx, sy, incy)
cdef extern from "_blas_subroutines.h": void _fortran_sgbmv "BLAS_FUNC(sgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogilcdef void sgbmv(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil: _fortran_sgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_sgemm "BLAS_FUNC(sgemm)"(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogilcdef void sgemm(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil: _fortran_sgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_sgemv "BLAS_FUNC(sgemv)"(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogilcdef void sgemv(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil: _fortran_sgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_sger "BLAS_FUNC(sger)"(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogilcdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil: _fortran_sger(m, n, alpha, x, incx, y, incy, a, lda)
cdef extern from "_blas_subroutines.h": s _fortran_snrm2 "BLAS_FUNC(snrm2)"(int *n, s *x, int *incx) nogilcdef s snrm2(int *n, s *x, int *incx) noexcept nogil: return _fortran_snrm2(n, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_srot "BLAS_FUNC(srot)"(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) nogilcdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogil: _fortran_srot(n, sx, incx, sy, incy, c, s)
cdef extern from "_blas_subroutines.h": void _fortran_srotg "BLAS_FUNC(srotg)"(s *sa, s *sb, s *c, s *s) nogilcdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogil: _fortran_srotg(sa, sb, c, s)
cdef extern from "_blas_subroutines.h": void _fortran_srotm "BLAS_FUNC(srotm)"(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) nogilcdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogil: _fortran_srotm(n, sx, incx, sy, incy, sparam)
cdef extern from "_blas_subroutines.h": void _fortran_srotmg "BLAS_FUNC(srotmg)"(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) nogilcdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogil: _fortran_srotmg(sd1, sd2, sx1, sy1, sparam)
cdef extern from "_blas_subroutines.h": void _fortran_ssbmv "BLAS_FUNC(ssbmv)"(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogilcdef void ssbmv(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil: _fortran_ssbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_sscal "BLAS_FUNC(sscal)"(int *n, s *sa, s *sx, int *incx) nogilcdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogil: _fortran_sscal(n, sa, sx, incx)
cdef extern from "_blas_subroutines.h": void _fortran_sspmv "BLAS_FUNC(sspmv)"(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) nogilcdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil: _fortran_sspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_sspr "BLAS_FUNC(sspr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) nogilcdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogil: _fortran_sspr(uplo, n, alpha, x, incx, ap)
cdef extern from "_blas_subroutines.h": void _fortran_sspr2 "BLAS_FUNC(sspr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) nogilcdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogil: _fortran_sspr2(uplo, n, alpha, x, incx, y, incy, ap)
cdef extern from "_blas_subroutines.h": void _fortran_sswap "BLAS_FUNC(sswap)"(int *n, s *sx, int *incx, s *sy, int *incy) nogilcdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil: _fortran_sswap(n, sx, incx, sy, incy)
cdef extern from "_blas_subroutines.h": void _fortran_ssymm "BLAS_FUNC(ssymm)"(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogilcdef void ssymm(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil: _fortran_ssymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_ssymv "BLAS_FUNC(ssymv)"(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogilcdef void ssymv(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil: _fortran_ssymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_ssyr "BLAS_FUNC(ssyr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) nogilcdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogil: _fortran_ssyr(uplo, n, alpha, x, incx, a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_ssyr2 "BLAS_FUNC(ssyr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogilcdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil: _fortran_ssyr2(uplo, n, alpha, x, incx, y, incy, a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_ssyr2k "BLAS_FUNC(ssyr2k)"(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogilcdef void ssyr2k(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil: _fortran_ssyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_ssyrk "BLAS_FUNC(ssyrk)"(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) nogilcdef void ssyrk(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) noexcept nogil: _fortran_ssyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_stbmv "BLAS_FUNC(stbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogilcdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil: _fortran_stbmv(uplo, trans, diag, n, k, a, lda, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_stbsv "BLAS_FUNC(stbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogilcdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil: _fortran_stbsv(uplo, trans, diag, n, k, a, lda, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_stpmv "BLAS_FUNC(stpmv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogilcdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil: _fortran_stpmv(uplo, trans, diag, n, ap, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_stpsv "BLAS_FUNC(stpsv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogilcdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil: _fortran_stpsv(uplo, trans, diag, n, ap, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_strmm "BLAS_FUNC(strmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) nogilcdef void strmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil: _fortran_strmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
cdef extern from "_blas_subroutines.h": void _fortran_strmv "BLAS_FUNC(strmv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogilcdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil: _fortran_strmv(uplo, trans, diag, n, a, lda, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_strsm "BLAS_FUNC(strsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) nogilcdef void strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil: _fortran_strsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
cdef extern from "_blas_subroutines.h": void _fortran_strsv "BLAS_FUNC(strsv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogilcdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil: _fortran_strsv(uplo, trans, diag, n, a, lda, x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_zaxpy "BLAS_FUNC(zaxpy)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogilcdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogil: _fortran_zaxpy(n, <npy_complex128*>za, <npy_complex128*>zx, incx, <npy_complex128*>zy, incy)
cdef extern from "_blas_subroutines.h": void _fortran_zcopy "BLAS_FUNC(zcopy)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogilcdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil: _fortran_zcopy(n, <npy_complex128*>zx, incx, <npy_complex128*>zy, incy)
cdef extern from "_blas_subroutines.h": void _fortran_zdotc "F_FUNC(zdotcwrp,ZDOTCWRP)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogilcdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil: cdef z out _fortran_zdotc(<npy_complex128*>&out, n, <npy_complex128*>zx, incx, <npy_complex128*>zy, incy) return out
cdef extern from "_blas_subroutines.h": void _fortran_zdotu "F_FUNC(zdotuwrp,ZDOTUWRP)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogilcdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil: cdef z out _fortran_zdotu(<npy_complex128*>&out, n, <npy_complex128*>zx, incx, <npy_complex128*>zy, incy) return out
cdef extern from "_blas_subroutines.h": void _fortran_zdrot "BLAS_FUNC(zdrot)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, d *c, d *s) nogilcdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogil: _fortran_zdrot(n, <npy_complex128*>cx, incx, <npy_complex128*>cy, incy, c, s)
cdef extern from "_blas_subroutines.h": void _fortran_zdscal "BLAS_FUNC(zdscal)"(int *n, d *da, npy_complex128 *zx, int *incx) nogilcdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogil: _fortran_zdscal(n, da, <npy_complex128*>zx, incx)
cdef extern from "_blas_subroutines.h": void _fortran_zgbmv "BLAS_FUNC(zgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogilcdef void zgbmv(char *trans, int *m, int *n, int *kl, int *ku, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: _fortran_zgbmv(trans, m, n, kl, ku, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>x, incx, <npy_complex128*>beta, <npy_complex128*>y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_zgemm "BLAS_FUNC(zgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogilcdef void zgemm(char *transa, char *transb, int *m, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil: _fortran_zgemm(transa, transb, m, n, k, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb, <npy_complex128*>beta, <npy_complex128*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_zgemv "BLAS_FUNC(zgemv)"(char *trans, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogilcdef void zgemv(char *trans, int *m, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: _fortran_zgemv(trans, m, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>x, incx, <npy_complex128*>beta, <npy_complex128*>y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_zgerc "BLAS_FUNC(zgerc)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogilcdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil: _fortran_zgerc(m, n, <npy_complex128*>alpha, <npy_complex128*>x, incx, <npy_complex128*>y, incy, <npy_complex128*>a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_zgeru "BLAS_FUNC(zgeru)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogilcdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil: _fortran_zgeru(m, n, <npy_complex128*>alpha, <npy_complex128*>x, incx, <npy_complex128*>y, incy, <npy_complex128*>a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_zhbmv "BLAS_FUNC(zhbmv)"(char *uplo, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogilcdef void zhbmv(char *uplo, int *n, int *k, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: _fortran_zhbmv(uplo, n, k, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>x, incx, <npy_complex128*>beta, <npy_complex128*>y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_zhemm "BLAS_FUNC(zhemm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogilcdef void zhemm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil: _fortran_zhemm(side, uplo, m, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb, <npy_complex128*>beta, <npy_complex128*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_zhemv "BLAS_FUNC(zhemv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogilcdef void zhemv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: _fortran_zhemv(uplo, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>x, incx, <npy_complex128*>beta, <npy_complex128*>y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_zher "BLAS_FUNC(zher)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda) nogilcdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil: _fortran_zher(uplo, n, alpha, <npy_complex128*>x, incx, <npy_complex128*>a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_zher2 "BLAS_FUNC(zher2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogilcdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil: _fortran_zher2(uplo, n, <npy_complex128*>alpha, <npy_complex128*>x, incx, <npy_complex128*>y, incy, <npy_complex128*>a, lda)
cdef extern from "_blas_subroutines.h": void _fortran_zher2k "BLAS_FUNC(zher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *beta, npy_complex128 *c, int *ldc) nogilcdef void zher2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, d *beta, z *c, int *ldc) noexcept nogil: _fortran_zher2k(uplo, trans, n, k, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb, beta, <npy_complex128*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_zherk "BLAS_FUNC(zherk)"(char *uplo, char *trans, int *n, int *k, d *alpha, npy_complex128 *a, int *lda, d *beta, npy_complex128 *c, int *ldc) nogilcdef void zherk(char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c, int *ldc) noexcept nogil: _fortran_zherk(uplo, trans, n, k, alpha, <npy_complex128*>a, lda, beta, <npy_complex128*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_zhpmv "BLAS_FUNC(zhpmv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogilcdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: _fortran_zhpmv(uplo, n, <npy_complex128*>alpha, <npy_complex128*>ap, <npy_complex128*>x, incx, <npy_complex128*>beta, <npy_complex128*>y, incy)
cdef extern from "_blas_subroutines.h": void _fortran_zhpr "BLAS_FUNC(zhpr)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap) nogilcdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogil: _fortran_zhpr(uplo, n, alpha, <npy_complex128*>x, incx, <npy_complex128*>ap)
cdef extern from "_blas_subroutines.h": void _fortran_zhpr2 "BLAS_FUNC(zhpr2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *ap) nogilcdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogil: _fortran_zhpr2(uplo, n, <npy_complex128*>alpha, <npy_complex128*>x, incx, <npy_complex128*>y, incy, <npy_complex128*>ap)
cdef extern from "_blas_subroutines.h": void _fortran_zrotg "BLAS_FUNC(zrotg)"(npy_complex128 *ca, npy_complex128 *cb, d *c, npy_complex128 *s) nogilcdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogil: _fortran_zrotg(<npy_complex128*>ca, <npy_complex128*>cb, c, <npy_complex128*>s)
cdef extern from "_blas_subroutines.h": void _fortran_zscal "BLAS_FUNC(zscal)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx) nogilcdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogil: _fortran_zscal(n, <npy_complex128*>za, <npy_complex128*>zx, incx)
cdef extern from "_blas_subroutines.h": void _fortran_zswap "BLAS_FUNC(zswap)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogilcdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil: _fortran_zswap(n, <npy_complex128*>zx, incx, <npy_complex128*>zy, incy)
cdef extern from "_blas_subroutines.h": void _fortran_zsymm "BLAS_FUNC(zsymm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogilcdef void zsymm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil: _fortran_zsymm(side, uplo, m, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb, <npy_complex128*>beta, <npy_complex128*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_zsyr2k "BLAS_FUNC(zsyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogilcdef void zsyr2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil: _fortran_zsyr2k(uplo, trans, n, k, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb, <npy_complex128*>beta, <npy_complex128*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_zsyrk "BLAS_FUNC(zsyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogilcdef void zsyrk(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *beta, z *c, int *ldc) noexcept nogil: _fortran_zsyrk(uplo, trans, n, k, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>beta, <npy_complex128*>c, ldc)
cdef extern from "_blas_subroutines.h": void _fortran_ztbmv "BLAS_FUNC(ztbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogilcdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil: _fortran_ztbmv(uplo, trans, diag, n, k, <npy_complex128*>a, lda, <npy_complex128*>x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_ztbsv "BLAS_FUNC(ztbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogilcdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil: _fortran_ztbsv(uplo, trans, diag, n, k, <npy_complex128*>a, lda, <npy_complex128*>x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_ztpmv "BLAS_FUNC(ztpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogilcdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil: _fortran_ztpmv(uplo, trans, diag, n, <npy_complex128*>ap, <npy_complex128*>x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_ztpsv "BLAS_FUNC(ztpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogilcdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil: _fortran_ztpsv(uplo, trans, diag, n, <npy_complex128*>ap, <npy_complex128*>x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_ztrmm "BLAS_FUNC(ztrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogilcdef void ztrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil: _fortran_ztrmm(side, uplo, transa, diag, m, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb)
cdef extern from "_blas_subroutines.h": void _fortran_ztrmv "BLAS_FUNC(ztrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogilcdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil: _fortran_ztrmv(uplo, trans, diag, n, <npy_complex128*>a, lda, <npy_complex128*>x, incx)
cdef extern from "_blas_subroutines.h": void _fortran_ztrsm "BLAS_FUNC(ztrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogilcdef void ztrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil: _fortran_ztrsm(side, uplo, transa, diag, m, n, <npy_complex128*>alpha, <npy_complex128*>a, lda, <npy_complex128*>b, ldb)
cdef extern from "_blas_subroutines.h": void _fortran_ztrsv "BLAS_FUNC(ztrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogilcdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil: _fortran_ztrsv(uplo, trans, diag, n, <npy_complex128*>a, lda, <npy_complex128*>x, incx)
# Python-accessible wrappers for testing:
cdef inline bint _is_contiguous(double[:,:] a, int axis) noexcept nogil: return (a.strides[axis] == sizeof(a[0,0]) or a.shape[axis] == 1)
cpdef float complex _test_cdotc(float complex[:] cx, float complex[:] cy) noexcept nogil: cdef: int n = cx.shape[0] int incx = cx.strides[0] // sizeof(cx[0]) int incy = cy.strides[0] // sizeof(cy[0]) return cdotc(&n, &cx[0], &incx, &cy[0], &incy)
cpdef float complex _test_cdotu(float complex[:] cx, float complex[:] cy) noexcept nogil: cdef: int n = cx.shape[0] int incx = cx.strides[0] // sizeof(cx[0]) int incy = cy.strides[0] // sizeof(cy[0]) return cdotu(&n, &cx[0], &incx, &cy[0], &incy)
cpdef double _test_dasum(double[:] dx) noexcept nogil: cdef: int n = dx.shape[0] int incx = dx.strides[0] // sizeof(dx[0]) return dasum(&n, &dx[0], &incx)
cpdef double _test_ddot(double[:] dx, double[:] dy) noexcept nogil: cdef: int n = dx.shape[0] int incx = dx.strides[0] // sizeof(dx[0]) int incy = dy.strides[0] // sizeof(dy[0]) return ddot(&n, &dx[0], &incx, &dy[0], &incy)
cpdef int _test_dgemm(double alpha, double[:,:] a, double[:,:] b, double beta, double[:,:] c) except -1 nogil: cdef: char *transa char *transb int m, n, k, lda, ldb, ldc double *a0=&a[0,0] double *b0=&b[0,0] double *c0=&c[0,0] # In the case that c is C contiguous, swap a and b and # swap whether or not each of them is transposed. # This can be done because a.dot(b) = b.T.dot(a.T).T. if _is_contiguous(c, 1): if _is_contiguous(a, 1): transb = 'n' ldb = (&a[1,0]) - a0 if a.shape[0] > 1 else 1 elif _is_contiguous(a, 0): transb = 't' ldb = (&a[0,1]) - a0 if a.shape[1] > 1 else 1 else: with gil: raise ValueError("Input 'a' is neither C nor Fortran contiguous.") if _is_contiguous(b, 1): transa = 'n' lda = (&b[1,0]) - b0 if b.shape[0] > 1 else 1 elif _is_contiguous(b, 0): transa = 't' lda = (&b[0,1]) - b0 if b.shape[1] > 1 else 1 else: with gil: raise ValueError("Input 'b' is neither C nor Fortran contiguous.") k = b.shape[0] if k != a.shape[1]: with gil: raise ValueError("Shape mismatch in input arrays.") m = b.shape[1] n = a.shape[0] if n != c.shape[0] or m != c.shape[1]: with gil: raise ValueError("Output array does not have the correct shape.") ldc = (&c[1,0]) - c0 if c.shape[0] > 1 else 1 dgemm(transa, transb, &m, &n, &k, &alpha, b0, &lda, a0, &ldb, &beta, c0, &ldc) elif _is_contiguous(c, 0): if _is_contiguous(a, 1): transa = 't' lda = (&a[1,0]) - a0 if a.shape[0] > 1 else 1 elif _is_contiguous(a, 0): transa = 'n' lda = (&a[0,1]) - a0 if a.shape[1] > 1 else 1 else: with gil: raise ValueError("Input 'a' is neither C nor Fortran contiguous.") if _is_contiguous(b, 1): transb = 't' ldb = (&b[1,0]) - b0 if b.shape[0] > 1 else 1 elif _is_contiguous(b, 0): transb = 'n' ldb = (&b[0,1]) - b0 if b.shape[1] > 1 else 1 else: with gil: raise ValueError("Input 'b' is neither C nor Fortran contiguous.") m = a.shape[0] k = a.shape[1] if k != b.shape[0]: with gil: raise ValueError("Shape mismatch in input arrays.") n = b.shape[1] if m != c.shape[0] or n != c.shape[1]: with gil: raise ValueError("Output array does not have the correct shape.") ldc = (&c[0,1]) - c0 if c.shape[1] > 1 else 1 dgemm(transa, transb, &m, &n, &k, &alpha, a0, &lda, b0, &ldb, &beta, c0, &ldc) else: with gil: raise ValueError("Input 'c' is neither C nor Fortran contiguous.") return 0
cpdef double _test_dnrm2(double[:] x) noexcept nogil: cdef: int n = x.shape[0] int incx = x.strides[0] // sizeof(x[0]) return dnrm2(&n, &x[0], &incx)
cpdef double _test_dzasum(double complex[:] zx) noexcept nogil: cdef: int n = zx.shape[0] int incx = zx.strides[0] // sizeof(zx[0]) return dzasum(&n, &zx[0], &incx)
cpdef double _test_dznrm2(double complex[:] x) noexcept nogil: cdef: int n = x.shape[0] int incx = x.strides[0] // sizeof(x[0]) return dznrm2(&n, &x[0], &incx)
cpdef int _test_icamax(float complex[:] cx) noexcept nogil: cdef: int n = cx.shape[0] int incx = cx.strides[0] // sizeof(cx[0]) return icamax(&n, &cx[0], &incx)
cpdef int _test_idamax(double[:] dx) noexcept nogil: cdef: int n = dx.shape[0] int incx = dx.strides[0] // sizeof(dx[0]) return idamax(&n, &dx[0], &incx)
cpdef int _test_isamax(float[:] sx) noexcept nogil: cdef: int n = sx.shape[0] int incx = sx.strides[0] // sizeof(sx[0]) return isamax(&n, &sx[0], &incx)
cpdef int _test_izamax(double complex[:] zx) noexcept nogil: cdef: int n = zx.shape[0] int incx = zx.strides[0] // sizeof(zx[0]) return izamax(&n, &zx[0], &incx)
cpdef float _test_sasum(float[:] sx) noexcept nogil: cdef: int n = sx.shape[0] int incx = sx.strides[0] // sizeof(sx[0]) return sasum(&n, &sx[0], &incx)
cpdef float _test_scasum(float complex[:] cx) noexcept nogil: cdef: int n = cx.shape[0] int incx = cx.strides[0] // sizeof(cx[0]) return scasum(&n, &cx[0], &incx)
cpdef float _test_scnrm2(float complex[:] x) noexcept nogil: cdef: int n = x.shape[0] int incx = x.strides[0] // sizeof(x[0]) return scnrm2(&n, &x[0], &incx)
cpdef float _test_sdot(float[:] sx, float[:] sy) noexcept nogil: cdef: int n = sx.shape[0] int incx = sx.strides[0] // sizeof(sx[0]) int incy = sy.strides[0] // sizeof(sy[0]) return sdot(&n, &sx[0], &incx, &sy[0], &incy)
cpdef float _test_snrm2(float[:] x) noexcept nogil: cdef: int n = x.shape[0] int incx = x.strides[0] // sizeof(x[0]) return snrm2(&n, &x[0], &incx)
cpdef double complex _test_zdotc(double complex[:] zx, double complex[:] zy) noexcept nogil: cdef: int n = zx.shape[0] int incx = zx.strides[0] // sizeof(zx[0]) int incy = zy.strides[0] // sizeof(zy[0]) return zdotc(&n, &zx[0], &incx, &zy[0], &incy)
cpdef double complex _test_zdotu(double complex[:] zx, double complex[:] zy) noexcept nogil: cdef: int n = zx.shape[0] int incx = zx.strides[0] // sizeof(zx[0]) int incy = zy.strides[0] // sizeof(zy[0]) return zdotu(&n, &zx[0], &incx, &zy[0], &incy)123version https://git-lfs.github.com/spec/v1oid sha256:35543354a907edae5d694519dd8d81ffdccea1cc64b0f7b8bb0328d584f43544size 8796091234567891011121314151617181920212223# This file is not meant for public use and will be removed in SciPy v2.0.0.# Use the `scipy.linalg` namespace for importing the functions# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822 'eig', 'eigvals', 'eigh', 'eigvalsh', 'eig_banded', 'eigvals_banded', 'eigh_tridiagonal', 'eigvalsh_tridiagonal', 'hessenberg', 'cdf2rdf', 'LinAlgError', 'norm', 'get_lapack_funcs']
def __dir__(): return __all__
def __getattr__(name): return _sub_module_deprecation(sub_package="linalg", module="decomp", private_modules=["_decomp"], all=__all__, attribute=name)123456789101112131415161718192021# This file is not meant for public use and will be removed in SciPy v2.0.0.# Use the `scipy.linalg` namespace for importing the functions# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822 'cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded', 'cho_solve_banded', 'LinAlgError', 'get_lapack_funcs']
def __dir__(): return __all__
def __getattr__(name): return _sub_module_deprecation(sub_package="linalg", module="decomp_cholesky", private_modules=["_decomp_cholesky"], all=__all__, attribute=name)123456789101112131415161718192021# This file is not meant for public use and will be removed in SciPy v2.0.0.# Use the `scipy.linalg` namespace for importing the functions# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822 'lu', 'lu_solve', 'lu_factor', 'LinAlgWarning', 'get_lapack_funcs',]
def __dir__(): return __all__
def __getattr__(name): return _sub_module_deprecation(sub_package="linalg", module="decomp_lu", private_modules=["_decomp_lu"], all=__all__, attribute=name)1234567891011121314151617181920# This file is not meant for public use and will be removed in SciPy v2.0.0.# Use the `scipy.linalg` namespace for importing the functions# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822 'qr', 'qr_multiply', 'rq', 'get_lapack_funcs']
def __dir__(): return __all__
def __getattr__(name): return _sub_module_deprecation(sub_package="linalg", module="decomp_qr", private_modules=["_decomp_qr"], all=__all__, attribute=name)123456789101112131415161718192021# This file is not meant for public use and will be removed in SciPy v2.0.0.# Use the `scipy.linalg` namespace for importing the functions# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822 'schur', 'rsf2csf', 'norm', 'LinAlgError', 'get_lapack_funcs', 'eigvals',]
def __dir__(): return __all__
def __getattr__(name): return _sub_module_deprecation(sub_package="linalg", module="decomp_schur", private_modules=["_decomp_schur"], all=__all__, attribute=name)
123456789101112131415161718192021# This file is not meant for public use and will be removed in SciPy v2.0.0.# Use the `scipy.linalg` namespace for importing the functions# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822 'svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space', 'LinAlgError', 'get_lapack_funcs']
def __dir__(): return __all__
def __getattr__(name): return _sub_module_deprecation(sub_package="linalg", module="decomp_svd", private_modules=["_decomp_svd"], all=__all__, attribute=name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989# ******************************************************************************# Copyright (C) 2013 Kenneth L. Ho## Redistribution and use in source and binary forms, with or without# modification, are permitted provided that the following conditions are met:## Redistributions of source code must retain the above copyright notice, this# list of conditions and the following disclaimer. Redistributions in binary# form must reproduce the above copyright notice, this list of conditions and# the following disclaimer in the documentation and/or other materials# provided with the distribution.## None of the names of the copyright holders may be used to endorse or# promote products derived from this software without specific prior written# permission.## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE# POSSIBILITY OF SUCH DAMAGE.# ******************************************************************************
r"""======================================================================Interpolative matrix decomposition (:mod:`scipy.linalg.interpolative`)======================================================================
.. versionadded:: 0.13
.. versionchanged:: 1.15.0 The underlying algorithms have been ported to Python from the original Fortran77 code. See references below for more details.
.. currentmodule:: scipy.linalg.interpolative
An interpolative decomposition (ID) of a matrix :math:`A \in\mathbb{C}^{m \times n}` of rank :math:`k \leq \min \{ m, n \}` is afactorization
.. math:: A \Pi = \begin{bmatrix} A \Pi_{1} & A \Pi_{2} \end{bmatrix} = A \Pi_{1} \begin{bmatrix} I & T \end{bmatrix},
where :math:`\Pi = [\Pi_{1}, \Pi_{2}]` is a permutation matrix with:math:`\Pi_{1} \in \{ 0, 1 \}^{n \times k}`, i.e., :math:`A \Pi_{2} =A \Pi_{1} T`. This can equivalently be written as :math:`A = BP`,where :math:`B = A \Pi_{1}` and :math:`P = [I, T] \Pi^{\mathsf{T}}`are the *skeleton* and *interpolation matrices*, respectively.
If :math:`A` does not have exact rank :math:`k`, then there exists anapproximation in the form of an ID such that :math:`A = BP + E`, where:math:`\| E \| \sim \sigma_{k + 1}` is on the order of the :math:`(k +1)`-th largest singular value of :math:`A`. Note that :math:`\sigma_{k+ 1}` is the best possible error for a rank-:math:`k` approximationand, in fact, is achieved by the singular value decomposition (SVD):math:`A \approx U S V^{*}`, where :math:`U \in \mathbb{C}^{m \timesk}` and :math:`V \in \mathbb{C}^{n \times k}` have orthonormal columnsand :math:`S = \mathop{\mathrm{diag}} (\sigma_{i}) \in \mathbb{C}^{k\times k}` is diagonal with nonnegative entries. The principaladvantages of using an ID over an SVD are that:
- it is cheaper to construct;- it preserves the structure of :math:`A`; and- it is more efficient to compute with in light of the identity submatrix of :math:`P`.
Routines========
Main functionality:
.. autosummary:: :toctree: generated/
interp_decomp reconstruct_matrix_from_id reconstruct_interp_matrix reconstruct_skel_matrix id_to_svd svd estimate_spectral_norm estimate_spectral_norm_diff estimate_rank
Following support functions are deprecated and will be removed in SciPy 1.17.0:
.. autosummary:: :toctree: generated/
seed rand
References==========
This module uses the algorithms found in ID software package [1]_ by Martinsson,Rokhlin, Shkolnisky, and Tygert, which is a Fortran library for computing IDs usingvarious algorithms, including the rank-revealing QR approach of [2]_ and the morerecent randomized methods described in [3]_, [4]_, and [5]_.
We advise the user to consult also the documentation for the `ID package<http://tygert.com/software.html>`_.
.. [1] P.G. Martinsson, V. Rokhlin, Y. Shkolnisky, M. Tygert. "ID: a software package for low-rank approximation of matrices via interpolative decompositions, version 0.2." http://tygert.com/id_doc.4.pdf.
.. [2] H. Cheng, Z. Gimbutas, P.G. Martinsson, V. Rokhlin. "On the compression of low rank matrices." *SIAM J. Sci. Comput.* 26 (4): 1389--1404, 2005. :doi:`10.1137/030602678`.
.. [3] E. Liberty, F. Woolfe, P.G. Martinsson, V. Rokhlin, M. Tygert. "Randomized algorithms for the low-rank approximation of matrices." *Proc. Natl. Acad. Sci. U.S.A.* 104 (51): 20167--20172, 2007. :doi:`10.1073/pnas.0709640104`.
.. [4] P.G. Martinsson, V. Rokhlin, M. Tygert. "A randomized algorithm for the decomposition of matrices." *Appl. Comput. Harmon. Anal.* 30 (1): 47--68, 2011. :doi:`10.1016/j.acha.2010.02.003`.
.. [5] F. Woolfe, E. Liberty, V. Rokhlin, M. Tygert. "A fast randomized algorithm for the approximation of matrices." *Appl. Comput. Harmon. Anal.* 25 (3): 335--366, 2008. :doi:`10.1016/j.acha.2007.12.002`.
Tutorial========
Initializing------------
The first step is to import :mod:`scipy.linalg.interpolative` by issuing thecommand:
>>> import scipy.linalg.interpolative as sli
Now let's build a matrix. For this, we consider a Hilbert matrix, which is wellknow to have low rank:
>>> from scipy.linalg import hilbert>>> n = 1000>>> A = hilbert(n)
We can also do this explicitly via:
>>> import numpy as np>>> n = 1000>>> A = np.empty((n, n), order='F')>>> for j in range(n):... for i in range(n):... A[i,j] = 1. / (i + j + 1)
Note the use of the flag ``order='F'`` in :func:`numpy.empty`. Thisinstantiates the matrix in Fortran-contiguous order and is important foravoiding data copying when passing to the backend.
We then define multiplication routines for the matrix by regarding it as a:class:`scipy.sparse.linalg.LinearOperator`:
>>> from scipy.sparse.linalg import aslinearoperator>>> L = aslinearoperator(A)
This automatically sets up methods describing the action of the matrix and itsadjoint on a vector.
Computing an ID---------------
We have several choices of algorithm to compute an ID. These fall largelyaccording to two dichotomies:
1. how the matrix is represented, i.e., via its entries or via its action on a vector; and2. whether to approximate it to a fixed relative precision or to a fixed rank.
We step through each choice in turn below.
In all cases, the ID is represented by three parameters:
1. a rank ``k``;2. an index array ``idx``; and3. interpolation coefficients ``proj``.
The ID is specified by the relation``np.dot(A[:,idx[:k]], proj) == A[:,idx[k:]]``.
From matrix entries...................
We first consider a matrix given in terms of its entries.
To compute an ID to a fixed precision, type:
>>> eps = 1e-3>>> k, idx, proj = sli.interp_decomp(A, eps)
where ``eps < 1`` is the desired precision.
To compute an ID to a fixed rank, use:
>>> idx, proj = sli.interp_decomp(A, k)
where ``k >= 1`` is the desired rank.
Both algorithms use random sampling and are usually faster than thecorresponding older, deterministic algorithms, which can be accessed via thecommands:
>>> k, idx, proj = sli.interp_decomp(A, eps, rand=False)
and:
>>> idx, proj = sli.interp_decomp(A, k, rand=False)
respectively.
From matrix action..................
Now consider a matrix given in terms of its action on a vector as a:class:`scipy.sparse.linalg.LinearOperator`.
To compute an ID to a fixed precision, type:
>>> k, idx, proj = sli.interp_decomp(L, eps)
To compute an ID to a fixed rank, use:
>>> idx, proj = sli.interp_decomp(L, k)
These algorithms are randomized.
Reconstructing an ID--------------------
The ID routines above do not output the skeleton and interpolation matricesexplicitly but instead return the relevant information in a more compact (andsometimes more useful) form. To build these matrices, write:
>>> B = sli.reconstruct_skel_matrix(A, k, idx)
for the skeleton matrix and:
>>> P = sli.reconstruct_interp_matrix(idx, proj)
for the interpolation matrix. The ID approximation can then be computed as:
>>> C = np.dot(B, P)
This can also be constructed directly using:
>>> C = sli.reconstruct_matrix_from_id(B, idx, proj)
without having to first compute ``P``.
Alternatively, this can be done explicitly as well using:
>>> B = A[:,idx[:k]]>>> P = np.hstack([np.eye(k), proj])[:,np.argsort(idx)]>>> C = np.dot(B, P)
Computing an SVD----------------
An ID can be converted to an SVD via the command:
>>> U, S, V = sli.id_to_svd(B, idx, proj)
The SVD approximation is then:
>>> approx = U @ np.diag(S) @ V.conj().T
The SVD can also be computed "fresh" by combining both the ID and conversionsteps into one command. Following the various ID algorithms above, there arecorrespondingly various SVD algorithms that one can employ.
From matrix entries...................
We consider first SVD algorithms for a matrix given in terms of its entries.
To compute an SVD to a fixed precision, type:
>>> U, S, V = sli.svd(A, eps)
To compute an SVD to a fixed rank, use:
>>> U, S, V = sli.svd(A, k)
Both algorithms use random sampling; for the deterministic versions, issue thekeyword ``rand=False`` as above.
From matrix action..................
Now consider a matrix given in terms of its action on a vector.
To compute an SVD to a fixed precision, type:
>>> U, S, V = sli.svd(L, eps)
To compute an SVD to a fixed rank, use:
>>> U, S, V = sli.svd(L, k)
Utility routines----------------
Several utility routines are also available.
To estimate the spectral norm of a matrix, use:
>>> snorm = sli.estimate_spectral_norm(A)
This algorithm is based on the randomized power method and thus requires onlymatrix-vector products. The number of iterations to take can be set using thekeyword ``its`` (default: ``its=20``). The matrix is interpreted as a:class:`scipy.sparse.linalg.LinearOperator`, but it is also valid to supply itas a :class:`numpy.ndarray`, in which case it is trivially converted using:func:`scipy.sparse.linalg.aslinearoperator`.
The same algorithm can also estimate the spectral norm of the difference of twomatrices ``A1`` and ``A2`` as follows:
>>> A1, A2 = A**2, A>>> diff = sli.estimate_spectral_norm_diff(A1, A2)
This is often useful for checking the accuracy of a matrix approximation.
Some routines in :mod:`scipy.linalg.interpolative` require estimating the rankof a matrix as well. This can be done with either:
>>> k = sli.estimate_rank(A, eps)
or:
>>> k = sli.estimate_rank(L, eps)
depending on the representation. The parameter ``eps`` controls the definitionof the numerical rank.
Finally, the random number generation required for all randomized routines canbe controlled via providing NumPy pseudo-random generators with a fixed seed. See:class:`numpy.random.Generator` and :func:`numpy.random.default_rng` for more details.
Remarks-------
The above functions all automatically detect the appropriate interface and workwith both real and complex data types, passing input arguments to the properbackend routine.
"""
import scipy.linalg._decomp_interpolative as _backendimport numpy as npimport warnings
__all__ = [ 'estimate_rank', 'estimate_spectral_norm', 'estimate_spectral_norm_diff', 'id_to_svd', 'interp_decomp', 'rand', 'reconstruct_interp_matrix', 'reconstruct_matrix_from_id', 'reconstruct_skel_matrix', 'seed', 'svd',]
_DTYPE_ERROR = ValueError("invalid input dtype (input must be float64 or complex128)")_TYPE_ERROR = TypeError("invalid input type (must be array or LinearOperator)")
def _C_contiguous_copy(A): """ Same as np.ascontiguousarray, but ensure a copy """ A = np.asarray(A) if A.flags.c_contiguous: A = A.copy() else: A = np.ascontiguousarray(A) return A
def _is_real(A): try: if A.dtype == np.complex128: return False elif A.dtype == np.float64: return True else: raise _DTYPE_ERROR except AttributeError as e: raise _TYPE_ERROR from e
def seed(seed=None): """ This function, historically, used to set the seed of the randomization algorithms used in the `scipy.linalg.interpolative` functions written in Fortran77.
The library has been ported to Python and now the functions use the native NumPy generators and this function has no content and returns None. Thus this function should not be used and will be removed in SciPy version 1.17.0. """ warnings.warn("`scipy.linalg.interpolative.seed` is deprecated and will be " "removed in SciPy 1.17.0.", DeprecationWarning, stacklevel=3)
def rand(*shape): """ This function, historically, used to generate uniformly distributed random number for the randomization algorithms used in the `scipy.linalg.interpolative` functions written in Fortran77.
The library has been ported to Python and now the functions use the native NumPy generators. Thus this function should not be used and will be removed in the SciPy version 1.17.0.
If pseudo-random numbers are needed, NumPy pseudo-random generators should be used instead.
Parameters ---------- *shape Shape of output array
""" warnings.warn("`scipy.linalg.interpolative.rand` is deprecated and will be " "removed in SciPy 1.17.0.", DeprecationWarning, stacklevel=3) rng = np.random.default_rng() return rng.uniform(low=0., high=1.0, size=shape)
def interp_decomp(A, eps_or_k, rand=True, rng=None): """ Compute ID of a matrix.
An ID of a matrix `A` is a factorization defined by a rank `k`, a column index array `idx`, and interpolation coefficients `proj` such that::
numpy.dot(A[:,idx[:k]], proj) = A[:,idx[k:]]
The original matrix can then be reconstructed as::
numpy.hstack([A[:,idx[:k]], numpy.dot(A[:,idx[:k]], proj)] )[:,numpy.argsort(idx)]
or via the routine :func:`reconstruct_matrix_from_id`. This can equivalently be written as::
numpy.dot(A[:,idx[:k]], numpy.hstack([numpy.eye(k), proj]) )[:,np.argsort(idx)]
in terms of the skeleton and interpolation matrices::
B = A[:,idx[:k]]
and::
P = numpy.hstack([numpy.eye(k), proj])[:,np.argsort(idx)]
respectively. See also :func:`reconstruct_interp_matrix` and :func:`reconstruct_skel_matrix`.
The ID can be computed to any relative precision or rank (depending on the value of `eps_or_k`). If a precision is specified (`eps_or_k < 1`), then this function has the output signature::
k, idx, proj = interp_decomp(A, eps_or_k)
Otherwise, if a rank is specified (`eps_or_k >= 1`), then the output signature is::
idx, proj = interp_decomp(A, eps_or_k)
.. This function automatically detects the form of the input parameters and passes them to the appropriate backend. For details, see :func:`_backend.iddp_id`, :func:`_backend.iddp_aid`, :func:`_backend.iddp_rid`, :func:`_backend.iddr_id`, :func:`_backend.iddr_aid`, :func:`_backend.iddr_rid`, :func:`_backend.idzp_id`, :func:`_backend.idzp_aid`, :func:`_backend.idzp_rid`, :func:`_backend.idzr_id`, :func:`_backend.idzr_aid`, and :func:`_backend.idzr_rid`.
Parameters ---------- A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator` with `rmatvec` Matrix to be factored eps_or_k : float or int Relative error (if ``eps_or_k < 1``) or rank (if ``eps_or_k >= 1``) of approximation. rand : bool, optional Whether to use random sampling if `A` is of type :class:`numpy.ndarray` (randomized algorithms are always used if `A` is of type :class:`scipy.sparse.linalg.LinearOperator`). rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. If `rand` is ``False``, the argument is ignored.
Returns ------- k : int Rank required to achieve specified relative precision if ``eps_or_k < 1``. idx : :class:`numpy.ndarray` Column index array. proj : :class:`numpy.ndarray` Interpolation coefficients. """ # numpy/numpydoc#87 # noqa: E501 from scipy.sparse.linalg import LinearOperator rng = np.random.default_rng(rng) real = _is_real(A)
if isinstance(A, np.ndarray): A = _C_contiguous_copy(A) if eps_or_k < 1: eps = eps_or_k if rand: if real: k, idx, proj = _backend.iddp_aid(A, eps, rng=rng) else: k, idx, proj = _backend.idzp_aid(A, eps, rng=rng) else: if real: k, idx, proj = _backend.iddp_id(A, eps) else: k, idx, proj = _backend.idzp_id(A, eps) return k, idx, proj else: k = int(eps_or_k) if rand: if real: idx, proj = _backend.iddr_aid(A, k, rng=rng) else: idx, proj = _backend.idzr_aid(A, k, rng=rng) else: if real: idx, proj = _backend.iddr_id(A, k) else: idx, proj = _backend.idzr_id(A, k) return idx, proj elif isinstance(A, LinearOperator):
if eps_or_k < 1: eps = eps_or_k if real: k, idx, proj = _backend.iddp_rid(A, eps, rng=rng) else: k, idx, proj = _backend.idzp_rid(A, eps, rng=rng) return k, idx, proj else: k = int(eps_or_k) if real: idx, proj = _backend.iddr_rid(A, k, rng=rng) else: idx, proj = _backend.idzr_rid(A, k, rng=rng) return idx, proj else: raise _TYPE_ERROR
def reconstruct_matrix_from_id(B, idx, proj): """ Reconstruct matrix from its ID.
A matrix `A` with skeleton matrix `B` and ID indices and coefficients `idx` and `proj`, respectively, can be reconstructed as::
numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)]
See also :func:`reconstruct_interp_matrix` and :func:`reconstruct_skel_matrix`.
.. This function automatically detects the matrix data type and calls the appropriate backend. For details, see :func:`_backend.idd_reconid` and :func:`_backend.idz_reconid`.
Parameters ---------- B : :class:`numpy.ndarray` Skeleton matrix. idx : :class:`numpy.ndarray` Column index array. proj : :class:`numpy.ndarray` Interpolation coefficients.
Returns ------- :class:`numpy.ndarray` Reconstructed matrix. """ if _is_real(B): return _backend.idd_reconid(B, idx, proj) else: return _backend.idz_reconid(B, idx, proj)
def reconstruct_interp_matrix(idx, proj): """ Reconstruct interpolation matrix from ID.
The interpolation matrix can be reconstructed from the ID indices and coefficients `idx` and `proj`, respectively, as::
P = numpy.hstack([numpy.eye(proj.shape[0]), proj])[:,numpy.argsort(idx)]
The original matrix can then be reconstructed from its skeleton matrix ``B`` via ``A = B @ P``
See also :func:`reconstruct_matrix_from_id` and :func:`reconstruct_skel_matrix`.
.. This function automatically detects the matrix data type and calls the appropriate backend. For details, see :func:`_backend.idd_reconint` and :func:`_backend.idz_reconint`.
Parameters ---------- idx : :class:`numpy.ndarray` 1D column index array. proj : :class:`numpy.ndarray` Interpolation coefficients.
Returns ------- :class:`numpy.ndarray` Interpolation matrix. """ n, krank = len(idx), proj.shape[0] if _is_real(proj): p = np.zeros([krank, n], dtype=np.float64) else: p = np.zeros([krank, n], dtype=np.complex128)
for ci in range(krank): p[ci, idx[ci]] = 1.0 p[:, idx[krank:]] = proj[:, :]
return p
def reconstruct_skel_matrix(A, k, idx): """ Reconstruct skeleton matrix from ID.
The skeleton matrix can be reconstructed from the original matrix `A` and its ID rank and indices `k` and `idx`, respectively, as::
B = A[:,idx[:k]]
The original matrix can then be reconstructed via::
numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)]
See also :func:`reconstruct_matrix_from_id` and :func:`reconstruct_interp_matrix`.
.. This function automatically detects the matrix data type and calls the appropriate backend. For details, see :func:`_backend.idd_copycols` and :func:`_backend.idz_copycols`.
Parameters ---------- A : :class:`numpy.ndarray` Original matrix. k : int Rank of ID. idx : :class:`numpy.ndarray` Column index array.
Returns ------- :class:`numpy.ndarray` Skeleton matrix. """ return A[:, idx[:k]]
def id_to_svd(B, idx, proj): """ Convert ID to SVD.
The SVD reconstruction of a matrix with skeleton matrix `B` and ID indices and coefficients `idx` and `proj`, respectively, is::
U, S, V = id_to_svd(B, idx, proj) A = numpy.dot(U, numpy.dot(numpy.diag(S), V.conj().T))
See also :func:`svd`.
.. This function automatically detects the matrix data type and calls the appropriate backend. For details, see :func:`_backend.idd_id2svd` and :func:`_backend.idz_id2svd`.
Parameters ---------- B : :class:`numpy.ndarray` Skeleton matrix. idx : :class:`numpy.ndarray` 1D column index array. proj : :class:`numpy.ndarray` Interpolation coefficients.
Returns ------- U : :class:`numpy.ndarray` Left singular vectors. S : :class:`numpy.ndarray` Singular values. V : :class:`numpy.ndarray` Right singular vectors. """ B = _C_contiguous_copy(B) if _is_real(B): U, S, V = _backend.idd_id2svd(B, idx, proj) else: U, S, V = _backend.idz_id2svd(B, idx, proj)
return U, S, V
def estimate_spectral_norm(A, its=20, rng=None): """ Estimate spectral norm of a matrix by the randomized power method.
.. This function automatically detects the matrix data type and calls the appropriate backend. For details, see :func:`_backend.idd_snorm` and :func:`_backend.idz_snorm`.
Parameters ---------- A : :class:`scipy.sparse.linalg.LinearOperator` Matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the `matvec` and `rmatvec` methods (to apply the matrix and its adjoint). its : int, optional Number of power method iterations. rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. If `rand` is ``False``, the argument is ignored.
Returns ------- float Spectral norm estimate. """ from scipy.sparse.linalg import aslinearoperator rng = np.random.default_rng(rng) A = aslinearoperator(A)
if _is_real(A): return _backend.idd_snorm(A, its=its, rng=rng) else: return _backend.idz_snorm(A, its=its, rng=rng)
def estimate_spectral_norm_diff(A, B, its=20, rng=None): """ Estimate spectral norm of the difference of two matrices by the randomized power method.
.. This function automatically detects the matrix data type and calls the appropriate backend. For details, see :func:`_backend.idd_diffsnorm` and :func:`_backend.idz_diffsnorm`.
Parameters ---------- A : :class:`scipy.sparse.linalg.LinearOperator` First matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the `matvec` and `rmatvec` methods (to apply the matrix and its adjoint). B : :class:`scipy.sparse.linalg.LinearOperator` Second matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the `matvec` and `rmatvec` methods (to apply the matrix and its adjoint). its : int, optional Number of power method iterations. rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. If `rand` is ``False``, the argument is ignored.
Returns ------- float Spectral norm estimate of matrix difference. """ from scipy.sparse.linalg import aslinearoperator rng = np.random.default_rng(rng) A = aslinearoperator(A) B = aslinearoperator(B)
if _is_real(A): return _backend.idd_diffsnorm(A, B, its=its, rng=rng) else: return _backend.idz_diffsnorm(A, B, its=its, rng=rng)
def svd(A, eps_or_k, rand=True, rng=None): """ Compute SVD of a matrix via an ID.
An SVD of a matrix `A` is a factorization::
A = U @ np.diag(S) @ V.conj().T
where `U` and `V` have orthonormal columns and `S` is nonnegative.
The SVD can be computed to any relative precision or rank (depending on the value of `eps_or_k`).
See also :func:`interp_decomp` and :func:`id_to_svd`.
.. This function automatically detects the form of the input parameters and passes them to the appropriate backend. For details, see :func:`_backend.iddp_svd`, :func:`_backend.iddp_asvd`, :func:`_backend.iddp_rsvd`, :func:`_backend.iddr_svd`, :func:`_backend.iddr_asvd`, :func:`_backend.iddr_rsvd`, :func:`_backend.idzp_svd`, :func:`_backend.idzp_asvd`, :func:`_backend.idzp_rsvd`, :func:`_backend.idzr_svd`, :func:`_backend.idzr_asvd`, and :func:`_backend.idzr_rsvd`.
Parameters ---------- A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator` Matrix to be factored, given as either a :class:`numpy.ndarray` or a :class:`scipy.sparse.linalg.LinearOperator` with the `matvec` and `rmatvec` methods (to apply the matrix and its adjoint). eps_or_k : float or int Relative error (if ``eps_or_k < 1``) or rank (if ``eps_or_k >= 1``) of approximation. rand : bool, optional Whether to use random sampling if `A` is of type :class:`numpy.ndarray` (randomized algorithms are always used if `A` is of type :class:`scipy.sparse.linalg.LinearOperator`). rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. If `rand` is ``False``, the argument is ignored.
Returns ------- U : :class:`numpy.ndarray` 2D array of left singular vectors. S : :class:`numpy.ndarray` 1D array of singular values. V : :class:`numpy.ndarray` 2D array right singular vectors. """ from scipy.sparse.linalg import LinearOperator rng = np.random.default_rng(rng)
real = _is_real(A)
if isinstance(A, np.ndarray): A = _C_contiguous_copy(A) if eps_or_k < 1: eps = eps_or_k if rand: if real: U, S, V = _backend.iddp_asvd(A, eps, rng=rng) else: U, S, V = _backend.idzp_asvd(A, eps, rng=rng) else: if real: U, S, V = _backend.iddp_svd(A, eps) V = V.T.conj() else: U, S, V = _backend.idzp_svd(A, eps) V = V.T.conj() else: k = int(eps_or_k) if k > min(A.shape): raise ValueError(f"Approximation rank {k} exceeds min(A.shape) = " f" {min(A.shape)} ") if rand: if real: U, S, V = _backend.iddr_asvd(A, k, rng=rng) else: U, S, V = _backend.idzr_asvd(A, k, rng=rng) else: if real: U, S, V = _backend.iddr_svd(A, k) V = V.T.conj() else: U, S, V = _backend.idzr_svd(A, k) V = V.T.conj() elif isinstance(A, LinearOperator): if eps_or_k < 1: eps = eps_or_k if real: U, S, V = _backend.iddp_rsvd(A, eps, rng=rng) else: U, S, V = _backend.idzp_rsvd(A, eps, rng=rng) else: k = int(eps_or_k) if real: U, S, V = _backend.iddr_rsvd(A, k, rng=rng) else: U, S, V = _backend.idzr_rsvd(A, k, rng=rng) else: raise _TYPE_ERROR return U, S, V
def estimate_rank(A, eps, rng=None): """ Estimate matrix rank to a specified relative precision using randomized methods.
The matrix `A` can be given as either a :class:`numpy.ndarray` or a :class:`scipy.sparse.linalg.LinearOperator`, with different algorithms used for each case. If `A` is of type :class:`numpy.ndarray`, then the output rank is typically about 8 higher than the actual numerical rank.
.. This function automatically detects the form of the input parameters and passes them to the appropriate backend. For details, see :func:`_backend.idd_estrank`, :func:`_backend.idd_findrank`, :func:`_backend.idz_estrank`, and :func:`_backend.idz_findrank`.
Parameters ---------- A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator` Matrix whose rank is to be estimated, given as either a :class:`numpy.ndarray` or a :class:`scipy.sparse.linalg.LinearOperator` with the `rmatvec` method (to apply the matrix adjoint). eps : float Relative error for numerical rank definition. rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. If `rand` is ``False``, the argument is ignored.
Returns ------- int Estimated matrix rank. """ from scipy.sparse.linalg import LinearOperator
rng = np.random.default_rng(rng) real = _is_real(A)
if isinstance(A, np.ndarray): A = _C_contiguous_copy(A) if real: rank, _ = _backend.idd_estrank(A, eps, rng=rng) else: rank, _ = _backend.idz_estrank(A, eps, rng=rng) if rank == 0: # special return value for nearly full rank rank = min(A.shape) return rank elif isinstance(A, LinearOperator): if real: return _backend.idd_findrank(A, eps, rng=rng)[0] else: return _backend.idz_findrank(A, eps, rng=rng)[0] else: raise _TYPE_ERROR12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061"""Low-level LAPACK functions (:mod:`scipy.linalg.lapack`)=======================================================
This module contains low-level functions from the LAPACK library.
.. versionadded:: 0.12.0
.. note::
The common ``overwrite_<>`` option in many routines, allows the input arrays to be overwritten to avoid extra memory allocation. However this requires the array to satisfy two conditions which are memory order and the data type to match exactly the order and the type expected by the routine.
As an example, if you pass a double precision float array to any ``S....`` routine which expects single precision arguments, f2py will create an intermediate array to match the argument types and overwriting will be performed on that intermediate array.
Similarly, if a C-contiguous array is passed, f2py will pass a FORTRAN-contiguous array internally. Please make sure that these details are satisfied. More information can be found in the f2py documentation.
.. warning::
These functions do little to no error checking. It is possible to cause crashes by mis-using them, so prefer using the higher-level routines in `scipy.linalg`.
Finding functions-----------------
.. autosummary:: :toctree: generated/
get_lapack_funcs
All functions-------------
.. autosummary:: :toctree: generated/
sgbsv dgbsv cgbsv zgbsv
sgbtrf dgbtrf cgbtrf zgbtrf
sgbtrs dgbtrs cgbtrs zgbtrs
sgebal dgebal cgebal zgebal
sgecon dgecon cgecon zgecon
sgeequ dgeequ cgeequ zgeequ
sgeequb dgeequb cgeequb zgeequb
sgees dgees cgees zgees
sgeev dgeev cgeev zgeev
sgeev_lwork dgeev_lwork cgeev_lwork zgeev_lwork
sgehrd dgehrd cgehrd zgehrd
sgehrd_lwork dgehrd_lwork cgehrd_lwork zgehrd_lwork
sgejsv dgejsv
sgels dgels cgels zgels
sgels_lwork dgels_lwork cgels_lwork zgels_lwork
sgelsd dgelsd cgelsd zgelsd
sgelsd_lwork dgelsd_lwork cgelsd_lwork zgelsd_lwork
sgelss dgelss cgelss zgelss
sgelss_lwork dgelss_lwork cgelss_lwork zgelss_lwork
sgelsy dgelsy cgelsy zgelsy
sgelsy_lwork dgelsy_lwork cgelsy_lwork zgelsy_lwork
sgeqp3 dgeqp3 cgeqp3 zgeqp3
sgeqrf dgeqrf cgeqrf zgeqrf
sgeqrf_lwork dgeqrf_lwork cgeqrf_lwork zgeqrf_lwork
sgeqrfp dgeqrfp cgeqrfp zgeqrfp
sgeqrfp_lwork dgeqrfp_lwork cgeqrfp_lwork zgeqrfp_lwork
sgerqf dgerqf cgerqf zgerqf
sgesdd dgesdd cgesdd zgesdd
sgesdd_lwork dgesdd_lwork cgesdd_lwork zgesdd_lwork
sgesv dgesv cgesv zgesv
sgesvd dgesvd cgesvd zgesvd
sgesvd_lwork dgesvd_lwork cgesvd_lwork zgesvd_lwork
sgesvx dgesvx cgesvx zgesvx
sgetrf dgetrf cgetrf zgetrf
sgetc2 dgetc2 cgetc2 zgetc2
sgetri dgetri cgetri zgetri
sgetri_lwork dgetri_lwork cgetri_lwork zgetri_lwork
sgetrs dgetrs cgetrs zgetrs
sgesc2 dgesc2 cgesc2 zgesc2
sgges dgges cgges zgges
sggev dggev cggev zggev
sgglse dgglse cgglse zgglse
sgglse_lwork dgglse_lwork cgglse_lwork zgglse_lwork
sgtsv dgtsv cgtsv zgtsv
sgtsvx dgtsvx cgtsvx zgtsvx
chbevd zhbevd
chbevx zhbevx
checon zhecon
cheequb zheequb
cheev zheev
cheev_lwork zheev_lwork
cheevd zheevd
cheevd_lwork zheevd_lwork
cheevr zheevr
cheevr_lwork zheevr_lwork
cheevx zheevx
cheevx_lwork zheevx_lwork
chegst zhegst
chegv zhegv
chegv_lwork zhegv_lwork
chegvd zhegvd
chegvx zhegvx
chegvx_lwork zhegvx_lwork
chesv zhesv
chesv_lwork zhesv_lwork
chesvx zhesvx
chesvx_lwork zhesvx_lwork
chetrd zhetrd
chetrd_lwork zhetrd_lwork
chetrf zhetrf
chetrf_lwork zhetrf_lwork
chetrs zhetrs
chfrk zhfrk
slamch dlamch
slange dlange clange zlange
slantr dlantr clantr zlantr
slarf dlarf clarf zlarf
slarfg dlarfg clarfg zlarfg
slartg dlartg clartg zlartg
slasd4 dlasd4
slaswp dlaswp claswp zlaswp
slauum dlauum clauum zlauum
sorcsd dorcsd sorcsd_lwork dorcsd_lwork
sorghr dorghr sorghr_lwork dorghr_lwork
sorgqr dorgqr
sorgrq dorgrq
sormqr dormqr
sormrz dormrz
sormrz_lwork dormrz_lwork
spbsv dpbsv cpbsv zpbsv
spbtrf dpbtrf cpbtrf zpbtrf
spbtrs dpbtrs cpbtrs zpbtrs
spftrf dpftrf cpftrf zpftrf
spftri dpftri cpftri zpftri
spftrs dpftrs cpftrs zpftrs
spocon dpocon cpocon zpocon
spstrf dpstrf cpstrf zpstrf
spstf2 dpstf2 cpstf2 zpstf2
sposv dposv cposv zposv
sposvx dposvx cposvx zposvx
spotrf dpotrf cpotrf zpotrf
spotri dpotri cpotri zpotri
spotrs dpotrs cpotrs zpotrs
sppcon dppcon cppcon zppcon
sppsv dppsv cppsv zppsv
spptrf dpptrf cpptrf zpptrf
spptri dpptri cpptri zpptri
spptrs dpptrs cpptrs zpptrs
sptsv dptsv cptsv zptsv
sptsvx dptsvx cptsvx zptsvx
spttrf dpttrf cpttrf zpttrf
spttrs dpttrs cpttrs zpttrs
spteqr dpteqr cpteqr zpteqr
crot zrot
ssbev dsbev
ssbevd dsbevd
ssbevx dsbevx
ssfrk dsfrk
sstebz dstebz
sstein dstein
sstemr dstemr
sstemr_lwork dstemr_lwork
ssterf dsterf
sstev dstev
ssycon dsycon csycon zsycon
ssyconv dsyconv csyconv zsyconv
ssyequb dsyequb csyequb zsyequb
ssyev dsyev
ssyev_lwork dsyev_lwork
ssyevd dsyevd
ssyevd_lwork dsyevd_lwork
ssyevr dsyevr
ssyevr_lwork dsyevr_lwork
ssyevx dsyevx
ssyevx_lwork dsyevx_lwork
ssygst dsygst
ssygv dsygv
ssygv_lwork dsygv_lwork
ssygvd dsygvd
ssygvx dsygvx
ssygvx_lwork dsygvx_lwork
ssysv dsysv csysv zsysv
ssysv_lwork dsysv_lwork csysv_lwork zsysv_lwork
ssysvx dsysvx csysvx zsysvx
ssysvx_lwork dsysvx_lwork csysvx_lwork zsysvx_lwork
ssytf2 dsytf2 csytf2 zsytf2
ssytrd dsytrd
ssytrd_lwork dsytrd_lwork
ssytrf dsytrf csytrf zsytrf
ssytrf_lwork dsytrf_lwork csytrf_lwork zsytrf_lwork
ssytrs dsytrs csytrs zsytrs
stbtrs dtbtrs ctbtrs ztbtrs
stfsm dtfsm ctfsm ztfsm
stfttp dtfttp ctfttp ztfttp
stfttr dtfttr ctfttr ztfttr
stgexc dtgexc ctgexc ztgexc
stgsen dtgsen ctgsen ztgsen
stgsen_lwork dtgsen_lwork ctgsen_lwork ztgsen_lwork
stgsyl dtgsyl
stpttf dtpttf ctpttf ztpttf
stpttr dtpttr ctpttr ztpttr
strcon dtrcon ctrcon ztrcon
strexc dtrexc ctrexc ztrexc
strsen dtrsen ctrsen ztrsen
strsen_lwork dtrsen_lwork ctrsen_lwork ztrsen_lwork
strsyl dtrsyl ctrsyl ztrsyl
strtri dtrtri ctrtri ztrtri
strtrs dtrtrs ctrtrs ztrtrs
strttf dtrttf ctrttf ztrttf
strttp dtrttp ctrttp ztrttp
stzrzf dtzrzf ctzrzf ztzrzf
stzrzf_lwork dtzrzf_lwork ctzrzf_lwork ztzrzf_lwork
cunghr zunghr
cunghr_lwork zunghr_lwork
cungqr zungqr
cungrq zungrq
cunmqr zunmqr
sgeqrt dgeqrt cgeqrt zgeqrt
sgemqrt dgemqrt cgemqrt zgemqrt
sgttrf dgttrf cgttrf zgttrf
sgttrs dgttrs cgttrs zgttrs
sgtcon dgtcon cgtcon zgtcon
stpqrt dtpqrt ctpqrt ztpqrt
stpmqrt dtpmqrt ctpmqrt ztpmqrt
cuncsd zuncsd
cuncsd_lwork zuncsd_lwork
cunmrz zunmrz
cunmrz_lwork zunmrz_lwork
ilaver
"""## Author: Pearu Peterson, March 2002#
import numpy as npfrom .blas import _get_funcs, _memoize_get_funcsfrom scipy.linalg import _flapackfrom re import compile as regex_compiletry: from scipy.linalg import _clapackexcept ImportError: _clapack = None
try: from scipy.linalg import _flapack_64 HAS_ILP64 = Trueexcept ImportError: HAS_ILP64 = False _flapack_64 = None
# Expose all functions (only flapack --- clapack is an implementation detail)empty_module = Nonefrom scipy.linalg._flapack import * # noqa: E402, F403del empty_module
__all__ = ['get_lapack_funcs']
# some convenience alias for complex functions_lapack_alias = { 'corghr': 'cunghr', 'zorghr': 'zunghr', 'corghr_lwork': 'cunghr_lwork', 'zorghr_lwork': 'zunghr_lwork', 'corgqr': 'cungqr', 'zorgqr': 'zungqr', 'cormqr': 'cunmqr', 'zormqr': 'zunmqr', 'corgrq': 'cungrq', 'zorgrq': 'zungrq',}
# Place guards against docstring rendering issues with special charactersp1 = regex_compile(r'with bounds (?P<b>.*?)( and (?P<s>.*?) storage){0,1}\n')p2 = regex_compile(r'Default: (?P<d>.*?)\n')
def backtickrepl(m): if m.group('s'): return (f"with bounds ``{m.group('b')}`` with ``{m.group('s')}`` storage\n") else: return f"with bounds ``{m.group('b')}``\n"
for routine in [ssyevr, dsyevr, cheevr, zheevr, ssyevx, dsyevx, cheevx, zheevx, ssygvd, dsygvd, chegvd, zhegvd]: if routine.__doc__: routine.__doc__ = p1.sub(backtickrepl, routine.__doc__) routine.__doc__ = p2.sub('Default ``\\1``\n', routine.__doc__) else: continue
del regex_compile, p1, p2, backtickrepl
@_memoize_get_funcsdef get_lapack_funcs(names, arrays=(), dtype=None, ilp64=False): """Return available LAPACK function objects from names.
Arrays are used to determine the optimal prefix of LAPACK routines.
Parameters ---------- names : str or sequence of str Name(s) of LAPACK functions without type prefix.
arrays : sequence of ndarrays, optional Arrays can be given to determine optimal prefix of LAPACK routines. If not given, double-precision routines will be used, otherwise the most generic type in arrays will be used.
dtype : str or dtype, optional Data-type specifier. Not used if `arrays` is non-empty.
ilp64 : {True, False, 'preferred'}, optional Whether to return ILP64 routine variant. Choosing 'preferred' returns ILP64 routine if available, and otherwise the 32-bit routine. Default: False
Returns ------- funcs : list List containing the found function(s).
Notes ----- This routine automatically chooses between Fortran/C interfaces. Fortran code is used whenever possible for arrays with column major order. In all other cases, C code is preferred.
In LAPACK, the naming convention is that all functions start with a type prefix, which depends on the type of the principal matrix. These can be one of {'s', 'd', 'c', 'z'} for the NumPy types {float32, float64, complex64, complex128} respectively, and are stored in attribute ``typecode`` of the returned functions.
Examples -------- Suppose we would like to use '?lange' routine which computes the selected norm of an array. We pass our array in order to get the correct 'lange' flavor.
>>> import numpy as np >>> import scipy.linalg as LA >>> rng = np.random.default_rng()
>>> a = rng.random((3,2)) >>> x_lange = LA.get_lapack_funcs('lange', (a,)) >>> x_lange.typecode 'd' >>> x_lange = LA.get_lapack_funcs('lange',(a*1j,)) >>> x_lange.typecode 'z'
Several LAPACK routines work best when its internal WORK array has the optimal size (big enough for fast computation and small enough to avoid waste of memory). This size is determined also by a dedicated query to the function which is often wrapped as a standalone function and commonly denoted as ``###_lwork``. Below is an example for ``?sysv``
>>> a = rng.random((1000, 1000)) >>> b = rng.random((1000, 1)) * 1j >>> # We pick up zsysv and zsysv_lwork due to b array ... xsysv, xlwork = LA.get_lapack_funcs(('sysv', 'sysv_lwork'), (a, b)) >>> opt_lwork, _ = xlwork(a.shape[0]) # returns a complex for 'z' prefix >>> udut, ipiv, x, info = xsysv(a, b, lwork=int(opt_lwork.real))
""" if isinstance(ilp64, str): if ilp64 == 'preferred': ilp64 = HAS_ILP64 else: raise ValueError("Invalid value for 'ilp64'")
if not ilp64: return _get_funcs(names, arrays, dtype, "LAPACK", _flapack, _clapack, "flapack", "clapack", _lapack_alias, ilp64=False) else: if not HAS_ILP64: raise RuntimeError("LAPACK ILP64 routine requested, but Scipy " "compiled only with 32-bit BLAS") return _get_funcs(names, arrays, dtype, "LAPACK", _flapack_64, None, "flapack_64", None, _lapack_alias, ilp64=True)
_int32_max = np.iinfo(np.int32).max_int64_max = np.iinfo(np.int64).max
def _compute_lwork(routine, *args, **kwargs): """ Round floating-point lwork returned by lapack to integer.
Several LAPACK routines compute optimal values for LWORK, which they return in a floating-point variable. However, for large values of LWORK, single-precision floating point is not sufficient to hold the exact value --- some LAPACK versions (<= 3.5.0 at least) truncate the returned integer to single precision and in some cases this can be smaller than the required value.
Examples -------- >>> from scipy.linalg import lapack >>> n = 5000 >>> s_r, s_lw = lapack.get_lapack_funcs(('sysvx', 'sysvx_lwork')) >>> lwork = lapack._compute_lwork(s_lw, n) >>> lwork 32000
""" dtype = getattr(routine, 'dtype', None) int_dtype = getattr(routine, 'int_dtype', None) ret = routine(*args, **kwargs) if ret[-1] != 0: raise ValueError("Internal work array size computation failed: " "%d" % (ret[-1],))
if len(ret) == 2: return _check_work_float(ret[0].real, dtype, int_dtype) else: return tuple(_check_work_float(x.real, dtype, int_dtype) for x in ret[:-1])
def _check_work_float(value, dtype, int_dtype): """ Convert LAPACK-returned work array size float to integer, carefully for single-precision types. """
if dtype == np.float32 or dtype == np.complex64: # Single-precision routine -- take next fp value to work # around possible truncation in LAPACK code value = np.nextafter(value, np.inf, dtype=np.float32)
value = int(value) if int_dtype.itemsize == 4: if value < 0 or value > _int32_max: raise ValueError("Too large work array required -- computation " "cannot be performed with standard 32-bit" " LAPACK.") elif int_dtype.itemsize == 8: if value < 0 or value > _int64_max: raise ValueError("Too large work array required -- computation" " cannot be performed with standard 64-bit" " LAPACK.") return value1234567891011121314151617181920212223# This file is not meant for public use and will be removed in SciPy v2.0.0.# Use the `scipy.linalg` namespace for importing the functions# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822 'expm', 'cosm', 'sinm', 'tanm', 'coshm', 'sinhm', 'tanhm', 'logm', 'funm', 'signm', 'sqrtm', 'expm_frechet', 'expm_cond', 'fractional_matrix_power', 'khatri_rao', 'norm', 'solve', 'inv', 'svd', 'schur', 'rsf2csf']
def __dir__(): return __all__
def __getattr__(name): return _sub_module_deprecation(sub_package="linalg", module="matfuncs", private_modules=["_matfuncs"], all=__all__, attribute=name)123456789101112131415161718192021# This file is not meant for public use and will be removed in SciPy v2.0.0.# Use the `scipy.linalg` namespace for importing the functions# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822 'LinAlgError', 'LinAlgWarning', 'norm', 'get_blas_funcs', 'get_lapack_funcs']
def __dir__(): return __all__
def __getattr__(name): return _sub_module_deprecation(sub_package="linalg", module="misc", private_modules=["_misc"], all=__all__, attribute=name)12345678910111213141516171819202122# This file is not meant for public use and will be removed in SciPy v2.0.0.# Use the `scipy.linalg` namespace for importing the functions# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822 'toeplitz', 'circulant', 'hankel', 'hadamard', 'leslie', 'kron', 'block_diag', 'companion', 'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft', 'fiedler', 'fiedler_companion', 'convolution_matrix']
def __dir__(): return __all__
def __getattr__(name): return _sub_module_deprecation(sub_package="linalg", module="special_matrices", private_modules=["_special_matrices"], all=__all__, attribute=name)1234567891011121314151617181920212223#!/usr/bin/env python3#cython: language_level=3#cython: boundscheck=False#cython: wraparound=False
cimport scipy.linalgfrom scipy.linalg.cython_blas cimport cdotufrom scipy.linalg.cython_lapack cimport dgtsv
cpdef tridiag(double[:] a, double[:] b, double[:] c, double[:] x): """ Solve the system A y = x for y where A is the tridiagonal matrix with subdiagonal 'a', diagonal 'b', and superdiagonal 'c'. """ cdef int n=b.shape[0], nrhs=1, info # Solution is written over the values in x. dgtsv(&n, &nrhs, &a[0], &b[0], &c[0], &x[0], &n, &info)
cpdef float complex complex_dot(float complex[:] cx, float complex[:] cy): """ Take dot product of two complex vectors """ cdef: int n = cx.shape[0] int incx = cx.strides[0] // sizeof(cx[0]) int incy = cy.strides[0] // sizeof(cy[0]) return cdotu(&n, &cx[0], &incx, &cy[0], &incy)123456789101112131415161718192021222324252627project('random-build-examples', 'c', 'cpp', 'cython')
fs = import('fs')
py3 = import('python').find_installation(pure: false)
cy = meson.get_compiler('cython')
if not cy.version().version_compare('>=3.0.8') error('tests requires Cython >= 3.0.8')endif
py3.extension_module( 'extending', 'extending.pyx', install: false, c_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this)
extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx')py3.extension_module( 'extending_cpp', extending_cpp, install: false, override_options : ['cython_language=cpp'], cpp_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this)123version https://git-lfs.github.com/spec/v1oid sha256:13f3e1491a876bbf59d7ea10ad29c1f9b5996a2ab99216f31d5bfcd659012c1esize 34462123version https://git-lfs.github.com/spec/v1oid sha256:59f839467f2752b7df6fb6d4094396edd32a5929b764f7ffa1e6666431e6cac6size 161487123version https://git-lfs.github.com/spec/v1oid sha256:38e8fc7b041df0b23d7e5ca15ead1a065e6467611ef9a848cc7db93f80adfd87size 34050123version https://git-lfs.github.com/spec/v1oid sha256:14e222d34a7118c7284a1675c6feceee77b84df951a5c6ba2a5ee9ff3054fa1dsize 31231123version https://git-lfs.github.com/spec/v1oid sha256:1b2a0736b541ebf5c4b9b4c00d6dab281e73c9fb9913c6e2581a781b37b602f9size 15878123version https://git-lfs.github.com/spec/v1oid sha256:a3dfab451d9d5c20243e0ed85cd8b6c9657669fb9a0f83b5be165585783d55b5size 21641234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059import itertools
import numpy as npfrom numpy import (arange, array, dot, zeros, identity, conjugate, transpose, float32)from numpy.random import random
from numpy.testing import (assert_equal, assert_almost_equal, assert_, assert_array_almost_equal, assert_allclose, assert_array_equal, suppress_warnings)import pytestfrom pytest import raises as assert_raises
from scipy.linalg import (solve, inv, det, lstsq, pinv, pinvh, norm, solve_banded, solveh_banded, solve_triangular, solve_circulant, circulant, LinAlgError, block_diag, matrix_balance, qr, LinAlgWarning)
from scipy.linalg._testutils import assert_no_overwritefrom scipy._lib._testutils import check_free_memory, IS_MUSLfrom scipy.linalg.blas import HAS_ILP64
REAL_DTYPES = (np.float32, np.float64, np.longdouble)COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)DTYPES = REAL_DTYPES + COMPLEX_DTYPES
def _eps_cast(dtyp): """Get the epsilon for dtype, possibly downcast to BLAS types.""" dt = dtyp if dt == np.longdouble: dt = np.float64 elif dt == np.clongdouble: dt = np.complex128 return np.finfo(dt).eps
class TestSolveBanded:
def test_real(self): a = array([[1.0, 20, 0, 0], [-30, 4, 6, 0], [2, 1, 20, 2], [0, -1, 7, 14]]) ab = array([[0.0, 20, 6, 2], [1, 4, 20, 14], [-30, 1, 7, 0], [2, -1, 0, 0]]) l, u = 2, 1 b4 = array([10.0, 0.0, 2.0, 14.0]) b4by1 = b4.reshape(-1, 1) b4by2 = array([[2, 1], [-30, 4], [2, 3], [1, 3]]) b4by4 = array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 1, 0, 0]]) for b in [b4, b4by1, b4by2, b4by4]: x = solve_banded((l, u), ab, b) assert_array_almost_equal(dot(a, x), b)
def test_complex(self): a = array([[1.0, 20, 0, 0], [-30, 4, 6, 0], [2j, 1, 20, 2j], [0, -1, 7, 14]]) ab = array([[0.0, 20, 6, 2j], [1, 4, 20, 14], [-30, 1, 7, 0], [2j, -1, 0, 0]]) l, u = 2, 1 b4 = array([10.0, 0.0, 2.0, 14.0j]) b4by1 = b4.reshape(-1, 1) b4by2 = array([[2, 1], [-30, 4], [2, 3], [1, 3]]) b4by4 = array([[1, 0, 0, 0], [0, 0, 0, 1j], [0, 1, 0, 0], [0, 1, 0, 0]]) for b in [b4, b4by1, b4by2, b4by4]: x = solve_banded((l, u), ab, b) assert_array_almost_equal(dot(a, x), b)
def test_tridiag_real(self): ab = array([[0.0, 20, 6, 2], [1, 4, 20, 14], [-30, 1, 7, 0]]) a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag( ab[2, :-1], -1) b4 = array([10.0, 0.0, 2.0, 14.0]) b4by1 = b4.reshape(-1, 1) b4by2 = array([[2, 1], [-30, 4], [2, 3], [1, 3]]) b4by4 = array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 1, 0, 0]]) for b in [b4, b4by1, b4by2, b4by4]: x = solve_banded((1, 1), ab, b) assert_array_almost_equal(dot(a, x), b)
def test_tridiag_complex(self): ab = array([[0.0, 20, 6, 2j], [1, 4, 20, 14], [-30, 1, 7, 0]]) a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag( ab[2, :-1], -1) b4 = array([10.0, 0.0, 2.0, 14.0j]) b4by1 = b4.reshape(-1, 1) b4by2 = array([[2, 1], [-30, 4], [2, 3], [1, 3]]) b4by4 = array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 1, 0, 0]]) for b in [b4, b4by1, b4by2, b4by4]: x = solve_banded((1, 1), ab, b) assert_array_almost_equal(dot(a, x), b)
def test_check_finite(self): a = array([[1.0, 20, 0, 0], [-30, 4, 6, 0], [2, 1, 20, 2], [0, -1, 7, 14]]) ab = array([[0.0, 20, 6, 2], [1, 4, 20, 14], [-30, 1, 7, 0], [2, -1, 0, 0]]) l, u = 2, 1 b4 = array([10.0, 0.0, 2.0, 14.0]) x = solve_banded((l, u), ab, b4, check_finite=False) assert_array_almost_equal(dot(a, x), b4)
def test_bad_shape(self): ab = array([[0.0, 20, 6, 2], [1, 4, 20, 14], [-30, 1, 7, 0], [2, -1, 0, 0]]) l, u = 2, 1 bad = array([1.0, 2.0, 3.0, 4.0]).reshape(-1, 4) assert_raises(ValueError, solve_banded, (l, u), ab, bad) assert_raises(ValueError, solve_banded, (l, u), ab, [1.0, 2.0])
# Values of (l,u) are not compatible with ab. assert_raises(ValueError, solve_banded, (1, 1), ab, [1.0, 2.0])
def test_1x1(self): # gh-8906 noted that the case of A@x = b with 1x1 A was handled # incorrectly; check that this is resolved. Typical case: # nupper == nlower == 0 # A = [[2]] b = array([[1., 2., 3.]]) ref = array([[0.5, 1.0, 1.5]]) x = solve_banded((0, 0), [[2]], b) assert_allclose(x, ref, rtol=1e-15)
# However, the user *can* represent the same system with garbage rows # in `ab`. Test the case with `nupper == 1, nlower == 1`. x = solve_banded((1, 1), [[0], [2], [0]], b) assert_allclose(x, ref, rtol=1e-15) assert_equal(x.dtype, np.dtype('f8')) assert_array_equal(b, [[1.0, 2.0, 3.0]])
def test_native_list_arguments(self): a = [[1.0, 20, 0, 0], [-30, 4, 6, 0], [2, 1, 20, 2], [0, -1, 7, 14]] ab = [[0.0, 20, 6, 2], [1, 4, 20, 14], [-30, 1, 7, 0], [2, -1, 0, 0]] l, u = 2, 1 b = [10.0, 0.0, 2.0, 14.0] x = solve_banded((l, u), ab, b) assert_array_almost_equal(dot(a, x), b)
@pytest.mark.thread_unsafe # due to Cython fused types, see cython#6506 @pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64]) @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt_ab, dt_b): # ab contains one empty row corresponding to the diagonal ab = np.array([[]], dtype=dt_ab) b = np.array([], dtype=dt_b) x = solve_banded((0, 0), ab, b)
assert x.shape == (0,) assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
b = np.empty((0, 0), dtype=dt_b) x = solve_banded((0, 0), ab, b)
assert x.shape == (0, 0) assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
class TestSolveHBanded:
def test_01_upper(self): # Solve # [ 4 1 2 0] [1] # [ 1 4 1 2] X = [4] # [ 2 1 4 1] [1] # [ 0 2 1 4] [2] # with the RHS as a 1D array. ab = array([[0.0, 0.0, 2.0, 2.0], [-99, 1.0, 1.0, 1.0], [4.0, 4.0, 4.0, 4.0]]) b = array([1.0, 4.0, 1.0, 2.0]) x = solveh_banded(ab, b) assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
def test_02_upper(self): # Solve # [ 4 1 2 0] [1 6] # [ 1 4 1 2] X = [4 2] # [ 2 1 4 1] [1 6] # [ 0 2 1 4] [2 1] # ab = array([[0.0, 0.0, 2.0, 2.0], [-99, 1.0, 1.0, 1.0], [4.0, 4.0, 4.0, 4.0]]) b = array([[1.0, 6.0], [4.0, 2.0], [1.0, 6.0], [2.0, 1.0]]) x = solveh_banded(ab, b) expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0]]) assert_array_almost_equal(x, expected)
def test_03_upper(self): # Solve # [ 4 1 2 0] [1] # [ 1 4 1 2] X = [4] # [ 2 1 4 1] [1] # [ 0 2 1 4] [2] # with the RHS as a 2D array with shape (3,1). ab = array([[0.0, 0.0, 2.0, 2.0], [-99, 1.0, 1.0, 1.0], [4.0, 4.0, 4.0, 4.0]]) b = array([1.0, 4.0, 1.0, 2.0]).reshape(-1, 1) x = solveh_banded(ab, b) assert_array_almost_equal(x, array([0., 1., 0., 0.]).reshape(-1, 1))
def test_01_lower(self): # Solve # [ 4 1 2 0] [1] # [ 1 4 1 2] X = [4] # [ 2 1 4 1] [1] # [ 0 2 1 4] [2] # ab = array([[4.0, 4.0, 4.0, 4.0], [1.0, 1.0, 1.0, -99], [2.0, 2.0, 0.0, 0.0]]) b = array([1.0, 4.0, 1.0, 2.0]) x = solveh_banded(ab, b, lower=True) assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
def test_02_lower(self): # Solve # [ 4 1 2 0] [1 6] # [ 1 4 1 2] X = [4 2] # [ 2 1 4 1] [1 6] # [ 0 2 1 4] [2 1] # ab = array([[4.0, 4.0, 4.0, 4.0], [1.0, 1.0, 1.0, -99], [2.0, 2.0, 0.0, 0.0]]) b = array([[1.0, 6.0], [4.0, 2.0], [1.0, 6.0], [2.0, 1.0]]) x = solveh_banded(ab, b, lower=True) expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0]]) assert_array_almost_equal(x, expected)
def test_01_float32(self): # Solve # [ 4 1 2 0] [1] # [ 1 4 1 2] X = [4] # [ 2 1 4 1] [1] # [ 0 2 1 4] [2] # ab = array([[0.0, 0.0, 2.0, 2.0], [-99, 1.0, 1.0, 1.0], [4.0, 4.0, 4.0, 4.0]], dtype=float32) b = array([1.0, 4.0, 1.0, 2.0], dtype=float32) x = solveh_banded(ab, b) assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
def test_02_float32(self): # Solve # [ 4 1 2 0] [1 6] # [ 1 4 1 2] X = [4 2] # [ 2 1 4 1] [1 6] # [ 0 2 1 4] [2 1] # ab = array([[0.0, 0.0, 2.0, 2.0], [-99, 1.0, 1.0, 1.0], [4.0, 4.0, 4.0, 4.0]], dtype=float32) b = array([[1.0, 6.0], [4.0, 2.0], [1.0, 6.0], [2.0, 1.0]], dtype=float32) x = solveh_banded(ab, b) expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0]]) assert_array_almost_equal(x, expected)
def test_01_complex(self): # Solve # [ 4 -j 2 0] [2-j] # [ j 4 -j 2] X = [4-j] # [ 2 j 4 -j] [4+j] # [ 0 2 j 4] [2+j] # ab = array([[0.0, 0.0, 2.0, 2.0], [-99, -1.0j, -1.0j, -1.0j], [4.0, 4.0, 4.0, 4.0]]) b = array([2-1.0j, 4.0-1j, 4+1j, 2+1j]) x = solveh_banded(ab, b) assert_array_almost_equal(x, [0.0, 1.0, 1.0, 0.0])
def test_02_complex(self): # Solve # [ 4 -j 2 0] [2-j 2+4j] # [ j 4 -j 2] X = [4-j -1-j] # [ 2 j 4 -j] [4+j 4+2j] # [ 0 2 j 4] [2+j j] # ab = array([[0.0, 0.0, 2.0, 2.0], [-99, -1.0j, -1.0j, -1.0j], [4.0, 4.0, 4.0, 4.0]]) b = array([[2-1j, 2+4j], [4.0-1j, -1-1j], [4.0+1j, 4+2j], [2+1j, 1j]]) x = solveh_banded(ab, b) expected = array([[0.0, 1.0j], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]]) assert_array_almost_equal(x, expected)
def test_tridiag_01_upper(self): # Solve # [ 4 1 0] [1] # [ 1 4 1] X = [4] # [ 0 1 4] [1] # with the RHS as a 1D array. ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]]) b = array([1.0, 4.0, 1.0]) x = solveh_banded(ab, b) assert_array_almost_equal(x, [0.0, 1.0, 0.0])
def test_tridiag_02_upper(self): # Solve # [ 4 1 0] [1 4] # [ 1 4 1] X = [4 2] # [ 0 1 4] [1 4] # ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]]) b = array([[1.0, 4.0], [4.0, 2.0], [1.0, 4.0]]) x = solveh_banded(ab, b) expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]]) assert_array_almost_equal(x, expected)
def test_tridiag_03_upper(self): # Solve # [ 4 1 0] [1] # [ 1 4 1] X = [4] # [ 0 1 4] [1] # with the RHS as a 2D array with shape (3,1). ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]]) b = array([1.0, 4.0, 1.0]).reshape(-1, 1) x = solveh_banded(ab, b) assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1, 1))
def test_tridiag_01_lower(self): # Solve # [ 4 1 0] [1] # [ 1 4 1] X = [4] # [ 0 1 4] [1] # ab = array([[4.0, 4.0, 4.0], [1.0, 1.0, -99]]) b = array([1.0, 4.0, 1.0]) x = solveh_banded(ab, b, lower=True) assert_array_almost_equal(x, [0.0, 1.0, 0.0])
def test_tridiag_02_lower(self): # Solve # [ 4 1 0] [1 4] # [ 1 4 1] X = [4 2] # [ 0 1 4] [1 4] # ab = array([[4.0, 4.0, 4.0], [1.0, 1.0, -99]]) b = array([[1.0, 4.0], [4.0, 2.0], [1.0, 4.0]]) x = solveh_banded(ab, b, lower=True) expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]]) assert_array_almost_equal(x, expected)
def test_tridiag_01_float32(self): # Solve # [ 4 1 0] [1] # [ 1 4 1] X = [4] # [ 0 1 4] [1] # ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32) b = array([1.0, 4.0, 1.0], dtype=float32) x = solveh_banded(ab, b) assert_array_almost_equal(x, [0.0, 1.0, 0.0])
def test_tridiag_02_float32(self): # Solve # [ 4 1 0] [1 4] # [ 1 4 1] X = [4 2] # [ 0 1 4] [1 4] # ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32) b = array([[1.0, 4.0], [4.0, 2.0], [1.0, 4.0]], dtype=float32) x = solveh_banded(ab, b) expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]]) assert_array_almost_equal(x, expected)
def test_tridiag_01_complex(self): # Solve # [ 4 -j 0] [ -j] # [ j 4 -j] X = [4-j] # [ 0 j 4] [4+j] # ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]]) b = array([-1.0j, 4.0-1j, 4+1j]) x = solveh_banded(ab, b) assert_array_almost_equal(x, [0.0, 1.0, 1.0])
def test_tridiag_02_complex(self): # Solve # [ 4 -j 0] [ -j 4j] # [ j 4 -j] X = [4-j -1-j] # [ 0 j 4] [4+j 4 ] # ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]]) b = array([[-1j, 4.0j], [4.0-1j, -1.0-1j], [4.0+1j, 4.0]]) x = solveh_banded(ab, b) expected = array([[0.0, 1.0j], [1.0, 0.0], [1.0, 1.0]]) assert_array_almost_equal(x, expected)
def test_check_finite(self): # Solve # [ 4 1 0] [1] # [ 1 4 1] X = [4] # [ 0 1 4] [1] # with the RHS as a 1D array. ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]]) b = array([1.0, 4.0, 1.0]) x = solveh_banded(ab, b, check_finite=False) assert_array_almost_equal(x, [0.0, 1.0, 0.0])
def test_bad_shapes(self): ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]]) b = array([[1.0, 4.0], [4.0, 2.0]]) assert_raises(ValueError, solveh_banded, ab, b) assert_raises(ValueError, solveh_banded, ab, [1.0, 2.0]) assert_raises(ValueError, solveh_banded, ab, [1.0])
def test_1x1(self): x = solveh_banded([[1]], [[1, 2, 3]]) assert_array_equal(x, [[1.0, 2.0, 3.0]]) assert_equal(x.dtype, np.dtype('f8'))
def test_native_list_arguments(self): # Same as test_01_upper, using python's native list. ab = [[0.0, 0.0, 2.0, 2.0], [-99, 1.0, 1.0, 1.0], [4.0, 4.0, 4.0, 4.0]] b = [1.0, 4.0, 1.0, 2.0] x = solveh_banded(ab, b) assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
@pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64]) @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt_ab, dt_b): # ab contains one empty row corresponding to the diagonal ab = np.array([[]], dtype=dt_ab) b = np.array([], dtype=dt_b) x = solveh_banded(ab, b)
assert x.shape == (0,) assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
b = np.empty((0, 0), dtype=dt_b) x = solveh_banded(ab, b)
assert x.shape == (0, 0) assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
class TestSolve: def setup_method(self): np.random.seed(1234)
@pytest.mark.thread_unsafe def test_20Feb04_bug(self): a = [[1, 1], [1.0, 0]] # ok x0 = solve(a, [1, 0j]) assert_array_almost_equal(dot(a, x0), [1, 0])
# gives failure with clapack.zgesv(..,rowmajor=0) a = [[1, 1], [1.2, 0]] b = [1, 0j] x0 = solve(a, b) assert_array_almost_equal(dot(a, x0), [1, 0])
def test_simple(self): a = [[1, 20], [-30, 4]] for b in ([[1, 0], [0, 1]], [1, 0], [[2, 1], [-30, 4]] ): x = solve(a, b) assert_array_almost_equal(dot(a, x), b)
def test_simple_complex(self): a = array([[5, 2], [2j, 4]], 'D') for b in ([1j, 0], [[1j, 1j], [0, 2]], [1, 0j], array([1, 0], 'D'), ): x = solve(a, b) assert_array_almost_equal(dot(a, x), b)
def test_simple_pos(self): a = [[2, 3], [3, 5]] for lower in [0, 1]: for b in ([[1, 0], [0, 1]], [1, 0] ): x = solve(a, b, assume_a='pos', lower=lower) assert_array_almost_equal(dot(a, x), b)
def test_simple_pos_complexb(self): a = [[5, 2], [2, 4]] for b in ([1j, 0], [[1j, 1j], [0, 2]], ): x = solve(a, b, assume_a='pos') assert_array_almost_equal(dot(a, x), b)
def test_simple_sym(self): a = [[2, 3], [3, -5]] for lower in [0, 1]: for b in ([[1, 0], [0, 1]], [1, 0] ): x = solve(a, b, assume_a='sym', lower=lower) assert_array_almost_equal(dot(a, x), b)
def test_simple_sym_complexb(self): a = [[5, 2], [2, -4]] for b in ([1j, 0], [[1j, 1j], [0, 2]] ): x = solve(a, b, assume_a='sym') assert_array_almost_equal(dot(a, x), b)
def test_simple_sym_complex(self): a = [[5, 2+1j], [2+1j, -4]] for b in ([1j, 0], [1, 0], [[1j, 1j], [0, 2]] ): x = solve(a, b, assume_a='sym') assert_array_almost_equal(dot(a, x), b)
def test_simple_her_actuallysym(self): a = [[2, 3], [3, -5]] for lower in [0, 1]: for b in ([[1, 0], [0, 1]], [1, 0], [1j, 0], ): x = solve(a, b, assume_a='her', lower=lower) assert_array_almost_equal(dot(a, x), b)
def test_simple_her(self): a = [[5, 2+1j], [2-1j, -4]] for b in ([1j, 0], [1, 0], [[1j, 1j], [0, 2]] ): x = solve(a, b, assume_a='her') assert_array_almost_equal(dot(a, x), b)
def test_nils_20Feb04(self): n = 2 A = random([n, n])+random([n, n])*1j X = zeros((n, n), 'D') Ainv = inv(A) R = identity(n)+identity(n)*0j for i in arange(0, n): r = R[:, i] X[:, i] = solve(A, r) assert_array_almost_equal(X, Ainv)
def test_random(self):
n = 20 a = random([n, n]) for i in range(n): a[i, i] = 20*(.1+a[i, i]) for i in range(4): b = random([n, 3]) x = solve(a, b) assert_array_almost_equal(dot(a, x), b)
def test_random_complex(self): n = 20 a = random([n, n]) + 1j * random([n, n]) for i in range(n): a[i, i] = 20*(.1+a[i, i]) for i in range(2): b = random([n, 3]) x = solve(a, b) assert_array_almost_equal(dot(a, x), b)
def test_random_sym(self): n = 20 a = random([n, n]) for i in range(n): a[i, i] = abs(20*(.1+a[i, i])) for j in range(i): a[i, j] = a[j, i] for i in range(4): b = random([n]) x = solve(a, b, assume_a="pos") assert_array_almost_equal(dot(a, x), b)
def test_random_sym_complex(self): n = 20 a = random([n, n]) a = a + 1j*random([n, n]) for i in range(n): a[i, i] = abs(20*(.1+a[i, i])) for j in range(i): a[i, j] = conjugate(a[j, i]) b = random([n])+2j*random([n]) for i in range(2): x = solve(a, b, assume_a="pos") assert_array_almost_equal(dot(a, x), b)
def test_check_finite(self): a = [[1, 20], [-30, 4]] for b in ([[1, 0], [0, 1]], [1, 0], [[2, 1], [-30, 4]]): x = solve(a, b, check_finite=False) assert_array_almost_equal(dot(a, x), b)
def test_scalar_a_and_1D_b(self): a = 1 b = [1, 2, 3] x = solve(a, b) assert_array_almost_equal(x.ravel(), b) assert_(x.shape == (3,), 'Scalar_a_1D_b test returned wrong shape')
def test_simple2(self): a = np.array([[1.80, 2.88, 2.05, -0.89], [525.00, -295.00, -95.00, -380.00], [1.58, -2.69, -2.90, -1.04], [-1.11, -0.66, -0.59, 0.80]])
b = np.array([[9.52, 18.47], [2435.00, 225.00], [0.77, -13.28], [-6.22, -6.21]])
x = solve(a, b) assert_array_almost_equal(x, np.array([[1., -1, 3, -5], [3, 2, 4, 1]]).T)
def test_simple_complex2(self): a = np.array([[-1.34+2.55j, 0.28+3.17j, -6.39-2.20j, 0.72-0.92j], [-1.70-14.10j, 33.10-1.50j, -1.50+13.40j, 12.90+13.80j], [-3.29-2.39j, -1.91+4.42j, -0.14-1.35j, 1.72+1.35j], [2.41+0.39j, -0.56+1.47j, -0.83-0.69j, -1.96+0.67j]])
b = np.array([[26.26+51.78j, 31.32-6.70j], [64.30-86.80j, 158.60-14.20j], [-5.75+25.31j, -2.15+30.19j], [1.16+2.57j, -2.56+7.55j]])
x = solve(a, b) assert_array_almost_equal(x, np. array([[1+1.j, -1-2.j], [2-3.j, 5+1.j], [-4-5.j, -3+4.j], [6.j, 2-3.j]]))
def test_hermitian(self): # An upper triangular matrix will be used for hermitian matrix a a = np.array([[-1.84, 0.11-0.11j, -1.78-1.18j, 3.91-1.50j], [0, -4.63, -1.84+0.03j, 2.21+0.21j], [0, 0, -8.87, 1.58-0.90j], [0, 0, 0, -1.36]]) b = np.array([[2.98-10.18j, 28.68-39.89j], [-9.58+3.88j, -24.79-8.40j], [-0.77-16.05j, 4.23-70.02j], [7.79+5.48j, -35.39+18.01j]]) res = np.array([[2.+1j, -8+6j], [3.-2j, 7-2j], [-1+2j, -1+5j], [1.-1j, 3-4j]]) x = solve(a, b, assume_a='her') assert_array_almost_equal(x, res) # Also conjugate a and test for lower triangular data x = solve(a.conj().T, b, assume_a='her', lower=True) assert_array_almost_equal(x, res)
def test_pos_and_sym(self): A = np.arange(1, 10).reshape(3, 3) x = solve(np.tril(A)/9, np.ones(3), assume_a='pos') assert_array_almost_equal(x, [9., 1.8, 1.]) x = solve(np.tril(A)/9, np.ones(3), assume_a='sym') assert_array_almost_equal(x, [9., 1.8, 1.])
def test_singularity(self): a = np.array([[1, 0, 0, 0, 0, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 1, 0, 1], [0, 1, 1, 0, 0, 0, 1, 0, 1], [1, 0, 1, 1, 1, 1, 0, 0, 0], [1, 0, 1, 1, 1, 1, 0, 0, 0], [1, 0, 1, 1, 1, 1, 0, 0, 0], [1, 0, 1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1]]) b = np.arange(9)[:, None] assert_raises(LinAlgError, solve, a, b)
@pytest.mark.thread_unsafe @pytest.mark.parametrize('structure', ('diagonal', 'tridiagonal', 'lower triangular', 'upper triangular', 'symmetric', 'hermitian', 'positive definite', 'general', None)) def test_ill_condition_warning(self, structure): rng = np.random.default_rng(234859349452) n = 10 d = np.logspace(0, 50, n) A = np.diag(d) b = rng.random(size=n) message = "Ill-conditioned matrix..." with pytest.warns(LinAlgWarning, match=message): solve(A, b, assume_a=structure)
def test_multiple_rhs(self): a = np.eye(2) b = np.random.rand(2, 3, 4) x = solve(a, b) assert_array_almost_equal(x, b)
def test_transposed_keyword(self): A = np.arange(9).reshape(3, 3) + 1 x = solve(np.tril(A)/9, np.ones(3), transposed=True) assert_array_almost_equal(x, [1.2, 0.2, 1]) x = solve(np.tril(A)/9, np.ones(3), transposed=False) assert_array_almost_equal(x, [9, -5.4, -1.2])
def test_transposed_notimplemented(self): a = np.eye(3).astype(complex) with assert_raises(NotImplementedError): solve(a, a, transposed=True)
def test_nonsquare_a(self): assert_raises(ValueError, solve, [1, 2], 1)
def test_size_mismatch_with_1D_b(self): assert_array_almost_equal(solve(np.eye(3), np.ones(3)), np.ones(3)) assert_raises(ValueError, solve, np.eye(3), np.ones(4))
def test_assume_a_keyword(self): assert_raises(ValueError, solve, 1, 1, assume_a='zxcv')
@pytest.mark.skip(reason="Failure on OS X (gh-7500), " "crash on Windows (gh-8064)") def test_all_type_size_routine_combinations(self): sizes = [10, 100] assume_as = ['gen', 'sym', 'pos', 'her'] dtypes = [np.float32, np.float64, np.complex64, np.complex128] for size, assume_a, dtype in itertools.product(sizes, assume_as, dtypes): is_complex = dtype in (np.complex64, np.complex128) if assume_a == 'her' and not is_complex: continue
err_msg = (f"Failed for size: {size}, assume_a: {assume_a}," f"dtype: {dtype}")
a = np.random.randn(size, size).astype(dtype) b = np.random.randn(size).astype(dtype) if is_complex: a = a + (1j*np.random.randn(size, size)).astype(dtype)
if assume_a == 'sym': # Can still be complex but only symmetric a = a + a.T elif assume_a == 'her': # Handle hermitian matrices here instead a = a + a.T.conj() elif assume_a == 'pos': a = a.conj().T.dot(a) + 0.1*np.eye(size)
tol = 1e-12 if dtype in (np.float64, np.complex128) else 1e-6
if assume_a in ['gen', 'sym', 'her']: # We revert the tolerance from before # 4b4a6e7c34fa4060533db38f9a819b98fa81476c if dtype in (np.float32, np.complex64): tol *= 10
x = solve(a, b, assume_a=assume_a) assert_allclose(a.dot(x), b, atol=tol * size, rtol=tol * size, err_msg=err_msg)
if assume_a == 'sym' and dtype not in (np.complex64, np.complex128): x = solve(a, b, assume_a=assume_a, transposed=True) assert_allclose(a.dot(x), b, atol=tol * size, rtol=tol * size, err_msg=err_msg)
@pytest.mark.thread_unsafe @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64]) @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt_a, dt_b): a = np.empty((0, 0), dtype=dt_a) b = np.empty(0, dtype=dt_b) x = solve(a, b)
assert x.size == 0 dt_nonempty = solve(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b)).dtype assert x.dtype == dt_nonempty
def test_empty_rhs(self): a = np.eye(2) b = [[], []] x = solve(a, b) assert_(x.size == 0, 'Returned array is not empty') assert_(x.shape == (2, 0), 'Returned empty array shape is wrong')
@pytest.mark.parametrize('dtype', [np.float64, np.complex128]) # "pos" and "positive definite" need to be added @pytest.mark.parametrize('assume_a', ['diagonal', 'tridiagonal', 'banded', 'lower triangular', 'upper triangular', 'symmetric', 'hermitian', 'general', 'sym', 'her', 'gen']) @pytest.mark.parametrize('nrhs', [(), (5,)]) @pytest.mark.parametrize('transposed', [True, False]) @pytest.mark.parametrize('overwrite', [True, False]) @pytest.mark.parametrize('fortran', [True, False]) def test_structure_detection(self, dtype, assume_a, nrhs, transposed, overwrite, fortran): rng = np.random.default_rng(982345982439826) n = 5 if not assume_a == 'banded' else 20 b = rng.random(size=(n,) + nrhs) A = rng.random(size=(n, n))
if np.issubdtype(dtype, np.complexfloating): b = b + rng.random(size=(n,) + nrhs) * 1j A = A + rng.random(size=(n, n)) * 1j
if assume_a == 'diagonal': A = np.diag(np.diag(A)) elif assume_a == 'lower triangular': A = np.tril(A) elif assume_a == 'upper triangular': A = np.triu(A) elif assume_a == 'tridiagonal': A = (np.diag(np.diag(A)) + np.diag(np.diag(A, -1), -1) + np.diag(np.diag(A, 1), 1)) elif assume_a == 'banded': A = np.triu(np.tril(A, 2), -1) elif assume_a in {'symmetric', 'sym'}: A = A + A.T elif assume_a in {'hermitian', 'her'}: A = A + A.conj().T elif assume_a in {'positive definite', 'pos'}: A = A + A.T A += np.diag(A.sum(axis=1))
if fortran: A = np.asfortranarray(A)
A_copy = A.copy(order='A') b_copy = b.copy()
if np.issubdtype(dtype, np.complexfloating) and transposed: message = "scipy.linalg.solve can currently..." with pytest.raises(NotImplementedError, match=message): solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite, transposed=transposed) return
res = solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite, transposed=transposed, assume_a=assume_a)
# Check that solution this solution is *correct* ref = np.linalg.solve(A_copy.T if transposed else A_copy, b_copy) assert_allclose(res, ref)
# Check that `solve` correctly identifies the structure and returns # *exactly* the same solution whether `assume_a` is specified or not if assume_a != 'banded': # structure detection removed for banded assert_equal(solve(A_copy, b_copy, transposed=transposed), res)
# Check that overwrite was respected if not overwrite: assert_equal(A, A_copy) assert_equal(b, b_copy)
class TestSolveTriangular:
def test_simple(self): """ solve_triangular on a simple 2x2 matrix. """ A = array([[1, 0], [1, 2]]) b = [1, 1] sol = solve_triangular(A, b, lower=True) assert_array_almost_equal(sol, [1, 0])
# check that it works also for non-contiguous matrices sol = solve_triangular(A.T, b, lower=False) assert_array_almost_equal(sol, [.5, .5])
# and that it gives the same result as trans=1 sol = solve_triangular(A, b, lower=True, trans=1) assert_array_almost_equal(sol, [.5, .5])
b = identity(2) sol = solve_triangular(A, b, lower=True, trans=1) assert_array_almost_equal(sol, [[1., -.5], [0, 0.5]])
def test_simple_complex(self): """ solve_triangular on a simple 2x2 complex matrix """ A = array([[1+1j, 0], [1j, 2]]) b = identity(2) sol = solve_triangular(A, b, lower=True, trans=1) assert_array_almost_equal(sol, [[.5-.5j, -.25-.25j], [0, 0.5]])
# check other option combinations with complex rhs b = np.diag([1+1j, 1+2j]) sol = solve_triangular(A, b, lower=True, trans=0) assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]])
sol = solve_triangular(A, b, lower=True, trans=1) assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]])
sol = solve_triangular(A, b, lower=True, trans=2) assert_array_almost_equal(sol, [[1j, -0.75-0.25j], [0, 0.5+1j]])
sol = solve_triangular(A.T, b, lower=False, trans=0) assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]])
sol = solve_triangular(A.T, b, lower=False, trans=1) assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]])
sol = solve_triangular(A.T, b, lower=False, trans=2) assert_array_almost_equal(sol, [[1j, 0], [-0.5, 0.5+1j]])
def test_check_finite(self): """ solve_triangular on a simple 2x2 matrix. """ A = array([[1, 0], [1, 2]]) b = [1, 1] sol = solve_triangular(A, b, lower=True, check_finite=False) assert_array_almost_equal(sol, [1, 0])
@pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64]) @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt_a, dt_b): a = np.empty((0, 0), dtype=dt_a) b = np.empty(0, dtype=dt_b) x = solve_triangular(a, b)
assert x.size == 0 dt_nonempty = solve_triangular( np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b) ).dtype assert x.dtype == dt_nonempty
def test_empty_rhs(self): a = np.eye(2) b = [[], []] x = solve_triangular(a, b) assert_(x.size == 0, 'Returned array is not empty') assert_(x.shape == (2, 0), 'Returned empty array shape is wrong')
class TestInv: def setup_method(self): np.random.seed(1234)
def test_simple(self): a = [[1, 2], [3, 4]] a_inv = inv(a) assert_array_almost_equal(dot(a, a_inv), np.eye(2)) a = [[1, 2, 3], [4, 5, 6], [7, 8, 10]] a_inv = inv(a) assert_array_almost_equal(dot(a, a_inv), np.eye(3))
def test_random(self): n = 20 for i in range(4): a = random([n, n]) for i in range(n): a[i, i] = 20*(.1+a[i, i]) a_inv = inv(a) assert_array_almost_equal(dot(a, a_inv), identity(n))
def test_simple_complex(self): a = [[1, 2], [3, 4j]] a_inv = inv(a) assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]])
def test_random_complex(self): n = 20 for i in range(4): a = random([n, n])+2j*random([n, n]) for i in range(n): a[i, i] = 20*(.1+a[i, i]) a_inv = inv(a) assert_array_almost_equal(dot(a, a_inv), identity(n))
def test_check_finite(self): a = [[1, 2], [3, 4]] a_inv = inv(a, check_finite=False) assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]])
@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt): a = np.empty((0, 0), dtype=dt) a_inv = inv(a) assert a_inv.size == 0 assert a_inv.dtype == inv(np.eye(2, dtype=dt)).dtype
class TestDet: def setup_method(self): self.rng = np.random.default_rng(1680305949878959)
def test_1x1_all_singleton_dims(self): a = np.array([[1]]) deta = det(a) assert deta.dtype.char == 'd' assert np.isscalar(deta) assert deta == 1. a = np.array([[[[1]]]], dtype='f') deta = det(a) assert deta.dtype.char == 'd' assert deta.shape == (1, 1) assert_equal(deta, [[1.0]]) a = np.array([[[1 + 3.j]]], dtype=np.complex64) deta = det(a) assert deta.dtype.char == 'D' assert deta.shape == (1,) assert_equal(deta, [1.+3.j])
def test_1by1_stacked_input_output(self): a = self.rng.random([4, 5, 1, 1], dtype=np.float32) deta = det(a) assert deta.dtype.char == 'd' assert deta.shape == (4, 5) assert_allclose(deta, np.squeeze(a))
a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j) deta = det(a) assert deta.dtype.char == 'D' assert deta.shape == (4, 5) assert_allclose(deta, np.squeeze(a))
@pytest.mark.parametrize('shape', [[2, 2], [20, 20], [3, 2, 20, 20]]) def test_simple_det_shapes_real_complex(self, shape): a = self.rng.uniform(-1., 1., size=shape) d1, d2 = det(a), np.linalg.det(a) assert_allclose(d1, d2)
b = self.rng.uniform(-1., 1., size=shape)*1j b += self.rng.uniform(-0.5, 0.5, size=shape) d3, d4 = det(b), np.linalg.det(b) assert_allclose(d3, d4)
def test_for_known_det_values(self): # Hadamard8 a = np.array([[1, 1, 1, 1, 1, 1, 1, 1], [1, -1, 1, -1, 1, -1, 1, -1], [1, 1, -1, -1, 1, 1, -1, -1], [1, -1, -1, 1, 1, -1, -1, 1], [1, 1, 1, 1, -1, -1, -1, -1], [1, -1, 1, -1, -1, 1, -1, 1], [1, 1, -1, -1, -1, -1, 1, 1], [1, -1, -1, 1, -1, 1, 1, -1]]) assert_allclose(det(a), 4096.)
# consecutive number array always singular assert_allclose(det(np.arange(25).reshape(5, 5)), 0.)
# simple anti-diagonal block array # Upper right has det (-2+1j) and lower right has (-2-1j) # det(a) = - (-2+1j) (-2-1j) = 5. a = np.array([[0.+0.j, 0.+0.j, 0.-1.j, 1.-1.j], [0.+0.j, 0.+0.j, 1.+0.j, 0.-1.j], [0.+1.j, 1.+1.j, 0.+0.j, 0.+0.j], [1.+0.j, 0.+1.j, 0.+0.j, 0.+0.j]], dtype=np.complex64) assert_allclose(det(a), 5.+0.j)
# Fiedler companion complexified # >>> a = scipy.linalg.fiedler_companion(np.arange(1, 10)) a = np.array([[-2., -3., 1., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0., 0.], [0., -4., 0., -5., 1., 0., 0., 0.], [0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., -6., 0., -7., 1., 0.], [0., 0., 0., 1., 0., 0., 0., 0.], [0., 0., 0., 0., 0., -8., 0., -9.], [0., 0., 0., 0., 0., 1., 0., 0.]])*1.j assert_allclose(det(a), 9.)
# g and G dtypes are handled differently in windows and other platforms @pytest.mark.parametrize('typ', [x for x in np.typecodes['All'][:20] if x not in 'gG']) def test_sample_compatible_dtype_input(self, typ): n = 4 a = self.rng.random([n, n]).astype(typ) # value is not important assert isinstance(det(a), (np.float64 | np.complex128))
def test_incompatible_dtype_input(self): # Double backslashes needed for escaping pytest regex. msg = 'cannot be cast to float\\(32, 64\\)'
for c, t in zip('SUO', ['bytes8', 'str32', 'object']): with assert_raises(TypeError, match=msg): det(np.array([['a', 'b']]*2, dtype=c)) with assert_raises(TypeError, match=msg): det(np.array([[b'a', b'b']]*2, dtype='V')) with assert_raises(TypeError, match=msg): det(np.array([[100, 200]]*2, dtype='datetime64[s]')) with assert_raises(TypeError, match=msg): det(np.array([[100, 200]]*2, dtype='timedelta64[s]'))
def test_empty_edge_cases(self): assert_allclose(det(np.empty([0, 0])), 1.) assert_allclose(det(np.empty([0, 0, 0])), np.array([])) assert_allclose(det(np.empty([3, 0, 0])), np.array([1., 1., 1.])) with assert_raises(ValueError, match='Last 2 dimensions'): det(np.empty([0, 0, 3])) with assert_raises(ValueError, match='at least two-dimensional'): det(np.array([])) with assert_raises(ValueError, match='Last 2 dimensions'): det(np.array([[]])) with assert_raises(ValueError, match='Last 2 dimensions'): det(np.array([[[]]]))
@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) def test_empty_dtype(self, dt): a = np.empty((0, 0), dtype=dt) d = det(a) assert d.shape == () assert d.dtype == det(np.eye(2, dtype=dt)).dtype
a = np.empty((3, 0, 0), dtype=dt) d = det(a) assert d.shape == (3,) assert d.dtype == det(np.zeros((3, 1, 1), dtype=dt)).dtype
def test_overwrite_a(self): # If all conditions are met then input should be overwritten; # - dtype is one of 'fdFD' # - C-contiguous # - writeable a = np.arange(9).reshape(3, 3).astype(np.float32) ac = a.copy() deta = det(ac, overwrite_a=True) assert_allclose(deta, 0.) assert not (a == ac).all()
def test_readonly_array(self): a = np.array([[2., 0., 1.], [5., 3., -1.], [1., 1., 1.]]) a.setflags(write=False) # overwrite_a will be overridden assert_allclose(det(a, overwrite_a=True), 10.)
def test_simple_check_finite(self): a = [[1, 2], [3, np.inf]] with assert_raises(ValueError, match='array must not contain'): det(a)
def direct_lstsq(a, b, cmplx=0): at = transpose(a) if cmplx: at = conjugate(at) a1 = dot(at, a) b1 = dot(at, b) return solve(a1, b1)
class TestLstsq: lapack_drivers = ('gelsd', 'gelss', 'gelsy', None)
def test_simple_exact(self): for dtype in REAL_DTYPES: a = np.array([[1, 20], [-30, 4]], dtype=dtype) for lapack_driver in TestLstsq.lapack_drivers: for overwrite in (True, False): for bt in (((1, 0), (0, 1)), (1, 0), ((2, 1), (-30, 4))): # Store values in case they are overwritten # later a1 = a.copy() b = np.array(bt, dtype=dtype) b1 = b.copy() out = lstsq(a1, b1, lapack_driver=lapack_driver, overwrite_a=overwrite, overwrite_b=overwrite) x = out[0] r = out[2] assert_(r == 2, f'expected efficient rank 2, got {r}') assert_allclose(dot(a, x), b, atol=25 * _eps_cast(a1.dtype), rtol=25 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}")
def test_simple_overdet(self): for dtype in REAL_DTYPES: a = np.array([[1, 2], [4, 5], [3, 4]], dtype=dtype) b = np.array([1, 2, 3], dtype=dtype) for lapack_driver in TestLstsq.lapack_drivers: for overwrite in (True, False): # Store values in case they are overwritten later a1 = a.copy() b1 = b.copy() out = lstsq(a1, b1, lapack_driver=lapack_driver, overwrite_a=overwrite, overwrite_b=overwrite) x = out[0] if lapack_driver == 'gelsy': residuals = np.sum((b - a.dot(x))**2) else: residuals = out[1] r = out[2] assert_(r == 2, f'expected efficient rank 2, got {r}') assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0), residuals, rtol=25 * _eps_cast(a1.dtype), atol=25 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}") assert_allclose(x, (-0.428571428571429, 0.85714285714285), rtol=25 * _eps_cast(a1.dtype), atol=25 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}")
def test_simple_overdet_complex(self): for dtype in COMPLEX_DTYPES: a = np.array([[1+2j, 2], [4, 5], [3, 4]], dtype=dtype) b = np.array([1, 2+4j, 3], dtype=dtype) for lapack_driver in TestLstsq.lapack_drivers: for overwrite in (True, False): # Store values in case they are overwritten later a1 = a.copy() b1 = b.copy() out = lstsq(a1, b1, lapack_driver=lapack_driver, overwrite_a=overwrite, overwrite_b=overwrite)
x = out[0] if lapack_driver == 'gelsy': res = b - a.dot(x) residuals = np.sum(res * res.conj()) else: residuals = out[1] r = out[2] assert_(r == 2, f'expected efficient rank 2, got {r}') assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0), residuals, rtol=25 * _eps_cast(a1.dtype), atol=25 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}") assert_allclose( x, (-0.4831460674157303 + 0.258426966292135j, 0.921348314606741 + 0.292134831460674j), rtol=25 * _eps_cast(a1.dtype), atol=25 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}")
def test_simple_underdet(self): for dtype in REAL_DTYPES: a = np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype) b = np.array([1, 2], dtype=dtype) for lapack_driver in TestLstsq.lapack_drivers: for overwrite in (True, False): # Store values in case they are overwritten later a1 = a.copy() b1 = b.copy() out = lstsq(a1, b1, lapack_driver=lapack_driver, overwrite_a=overwrite, overwrite_b=overwrite)
x = out[0] r = out[2] assert_(r == 2, f'expected efficient rank 2, got {r}') assert_allclose(x, (-0.055555555555555, 0.111111111111111, 0.277777777777777), rtol=25 * _eps_cast(a1.dtype), atol=25 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}")
@pytest.mark.parametrize("dtype", REAL_DTYPES) @pytest.mark.parametrize("n", (20, 200)) @pytest.mark.parametrize("lapack_driver", lapack_drivers) @pytest.mark.parametrize("overwrite", (True, False)) def test_random_exact(self, dtype, n, lapack_driver, overwrite): rng = np.random.RandomState(1234)
a = np.asarray(rng.random([n, n]), dtype=dtype) for i in range(n): a[i, i] = 20 * (0.1 + a[i, i]) for i in range(4): b = np.asarray(rng.random([n, 3]), dtype=dtype) # Store values in case they are overwritten later a1 = a.copy() b1 = b.copy() out = lstsq(a1, b1, lapack_driver=lapack_driver, overwrite_a=overwrite, overwrite_b=overwrite) x = out[0] r = out[2] assert_(r == n, f'expected efficient rank {n}, ' f'got {r}') if dtype is np.float32: assert_allclose( dot(a, x), b, rtol=500 * _eps_cast(a1.dtype), atol=500 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}") else: assert_allclose( dot(a, x), b, rtol=1000 * _eps_cast(a1.dtype), atol=1000 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}")
@pytest.mark.skipif(IS_MUSL, reason="may segfault on Alpine, see gh-17630") @pytest.mark.parametrize("dtype", COMPLEX_DTYPES) @pytest.mark.parametrize("n", (20, 200)) @pytest.mark.parametrize("lapack_driver", lapack_drivers) @pytest.mark.parametrize("overwrite", (True, False)) def test_random_complex_exact(self, dtype, n, lapack_driver, overwrite): rng = np.random.RandomState(1234)
a = np.asarray(rng.random([n, n]) + 1j*rng.random([n, n]), dtype=dtype) for i in range(n): a[i, i] = 20 * (0.1 + a[i, i]) for i in range(2): b = np.asarray(rng.random([n, 3]), dtype=dtype) # Store values in case they are overwritten later a1 = a.copy() b1 = b.copy() out = lstsq(a1, b1, lapack_driver=lapack_driver, overwrite_a=overwrite, overwrite_b=overwrite) x = out[0] r = out[2] assert_(r == n, f'expected efficient rank {n}, ' f'got {r}') if dtype is np.complex64: assert_allclose( dot(a, x), b, rtol=400 * _eps_cast(a1.dtype), atol=400 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}") else: assert_allclose( dot(a, x), b, rtol=1000 * _eps_cast(a1.dtype), atol=1000 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}")
def test_random_overdet(self): rng = np.random.RandomState(1234) for dtype in REAL_DTYPES: for (n, m) in ((20, 15), (200, 2)): for lapack_driver in TestLstsq.lapack_drivers: for overwrite in (True, False): a = np.asarray(rng.random([n, m]), dtype=dtype) for i in range(m): a[i, i] = 20 * (0.1 + a[i, i]) for i in range(4): b = np.asarray(rng.random([n, 3]), dtype=dtype) # Store values in case they are overwritten later a1 = a.copy() b1 = b.copy() out = lstsq(a1, b1, lapack_driver=lapack_driver, overwrite_a=overwrite, overwrite_b=overwrite) x = out[0] r = out[2] assert_(r == m, f'expected efficient rank {m}, ' f'got {r}') assert_allclose( x, direct_lstsq(a, b, cmplx=0), rtol=25 * _eps_cast(a1.dtype), atol=25 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}")
def test_random_complex_overdet(self): rng = np.random.RandomState(1234) for dtype in COMPLEX_DTYPES: for (n, m) in ((20, 15), (200, 2)): for lapack_driver in TestLstsq.lapack_drivers: for overwrite in (True, False): a = np.asarray(rng.random([n, m]) + 1j*rng.random([n, m]), dtype=dtype) for i in range(m): a[i, i] = 20 * (0.1 + a[i, i]) for i in range(2): b = np.asarray(rng.random([n, 3]), dtype=dtype) # Store values in case they are overwritten # later a1 = a.copy() b1 = b.copy() out = lstsq(a1, b1, lapack_driver=lapack_driver, overwrite_a=overwrite, overwrite_b=overwrite) x = out[0] r = out[2] assert_(r == m, f'expected efficient rank {m}, ' f'got {r}') assert_allclose( x, direct_lstsq(a, b, cmplx=1), rtol=25 * _eps_cast(a1.dtype), atol=25 * _eps_cast(a1.dtype), err_msg=f"driver: {lapack_driver}")
def test_check_finite(self): with suppress_warnings() as sup: # On (some) OSX this tests triggers a warning (gh-7538) sup.filter(RuntimeWarning, "internal gelsd driver lwork query error,.*" "Falling back to 'gelss' driver.")
at = np.array(((1, 20), (-30, 4))) for dtype, bt, lapack_driver, overwrite, check_finite in \ itertools.product(REAL_DTYPES, (((1, 0), (0, 1)), (1, 0), ((2, 1), (-30, 4))), TestLstsq.lapack_drivers, (True, False), (True, False)):
a = at.astype(dtype) b = np.array(bt, dtype=dtype) # Store values in case they are overwritten # later a1 = a.copy() b1 = b.copy() out = lstsq(a1, b1, lapack_driver=lapack_driver, check_finite=check_finite, overwrite_a=overwrite, overwrite_b=overwrite) x = out[0] r = out[2] assert_(r == 2, f'expected efficient rank 2, got {r}') assert_allclose(dot(a, x), b, rtol=25 * _eps_cast(a.dtype), atol=25 * _eps_cast(a.dtype), err_msg=f"driver: {lapack_driver}")
def test_empty(self): for a_shape, b_shape in (((0, 2), (0,)), ((0, 4), (0, 2)), ((4, 0), (4,)), ((4, 0), (4, 2))): b = np.ones(b_shape) x, residues, rank, s = lstsq(np.zeros(a_shape), b) assert_equal(x, np.zeros((a_shape[1],) + b_shape[1:])) residues_should_be = (np.empty((0,)) if a_shape[1] else np.linalg.norm(b, axis=0)**2) assert_equal(residues, residues_should_be) assert_(rank == 0, 'expected rank 0') assert_equal(s, np.empty((0,)))
@pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64]) @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) def test_empty_dtype(self, dt_a, dt_b): a = np.empty((0, 0), dtype=dt_a) b = np.empty(0, dtype=dt_b) x, residues, rank, s = lstsq(a, b)
assert x.size == 0 dt_nonempty = lstsq(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b))[0].dtype assert x.dtype == dt_nonempty
class TestPinv: def setup_method(self): np.random.seed(1234)
def test_simple_real(self): a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float) a_pinv = pinv(a) assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
def test_simple_complex(self): a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]], dtype=float)) a_pinv = pinv(a) assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
def test_simple_singular(self): a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float) a_pinv = pinv(a) expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01], [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02], [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]]) assert_array_almost_equal(a_pinv, expected)
def test_simple_cols(self): a = array([[1, 2, 3], [4, 5, 6]], dtype=float) a_pinv = pinv(a) expected = array([[-0.94444444, 0.44444444], [-0.11111111, 0.11111111], [0.72222222, -0.22222222]]) assert_array_almost_equal(a_pinv, expected)
def test_simple_rows(self): a = array([[1, 2], [3, 4], [5, 6]], dtype=float) a_pinv = pinv(a) expected = array([[-1.33333333, -0.33333333, 0.66666667], [1.08333333, 0.33333333, -0.41666667]]) assert_array_almost_equal(a_pinv, expected)
def test_check_finite(self): a = array([[1, 2, 3], [4, 5, 6.], [7, 8, 10]]) a_pinv = pinv(a, check_finite=False) assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
def test_native_list_argument(self): a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] a_pinv = pinv(a) expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01], [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02], [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]]) assert_array_almost_equal(a_pinv, expected)
def test_atol_rtol(self): n = 12 # get a random ortho matrix for shuffling q, _ = qr(np.random.rand(n, n)) a_m = np.arange(35.0).reshape(7, 5) a = a_m.copy() a[0, 0] = 0.001 atol = 1e-5 rtol = 0.05 # svds of a_m is ~ [116.906, 4.234, tiny, tiny, tiny] # svds of a is ~ [116.906, 4.234, 4.62959e-04, tiny, tiny] # Just abs cutoff such that we arrive at a_modified a_p = pinv(a_m, atol=atol, rtol=0.) adiff1 = a @ a_p @ a - a adiff2 = a_m @ a_p @ a_m - a_m # Now adiff1 should be around atol value while adiff2 should be # relatively tiny assert_allclose(np.linalg.norm(adiff1), 5e-4, atol=5.e-4) assert_allclose(np.linalg.norm(adiff2), 5e-14, atol=5.e-14)
# Now do the same but remove another sv ~4.234 via rtol a_p = pinv(a_m, atol=atol, rtol=rtol) adiff1 = a @ a_p @ a - a adiff2 = a_m @ a_p @ a_m - a_m assert_allclose(np.linalg.norm(adiff1), 4.233, rtol=0.01) assert_allclose(np.linalg.norm(adiff2), 4.233, rtol=0.01)
@pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64]) def test_empty(self, dt): a = np.empty((0, 0), dtype=dt) a_pinv = pinv(a) assert a_pinv.size == 0 assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype
class TestPinvSymmetric:
def setup_method(self): np.random.seed(1234)
def test_simple_real(self): a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float) a = np.dot(a, a.T) a_pinv = pinvh(a) assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
def test_nonpositive(self): a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float) a = np.dot(a, a.T) u, s, vt = np.linalg.svd(a) s[0] *= -1 a = np.dot(u * s, vt) # a is now symmetric non-positive and singular a_pinv = pinv(a) a_pinvh = pinvh(a) assert_array_almost_equal(a_pinv, a_pinvh)
def test_simple_complex(self): a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]], dtype=float)) a = np.dot(a, a.conj().T) a_pinv = pinvh(a) assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
def test_native_list_argument(self): a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float) a = np.dot(a, a.T) a_pinv = pinvh(a.tolist()) assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
def test_zero_eigenvalue(self): # https://github.com/scipy/scipy/issues/12515 # the SYEVR eigh driver may give the zero eigenvalue > eps a = np.array([[1, -1, 0], [-1, 2, -1], [0, -1, 1]]) p = pinvh(a) assert_allclose(p @ a @ p, p, atol=1e-15) assert_allclose(a @ p @ a, a, atol=1e-15)
def test_atol_rtol(self): n = 12 # get a random ortho matrix for shuffling q, _ = qr(np.random.rand(n, n)) a = np.diag([4, 3, 2, 1, 0.99e-4, 0.99e-5] + [0.99e-6]*(n-6)) a = q.T @ a @ q a_m = np.diag([4, 3, 2, 1, 0.99e-4, 0.] + [0.]*(n-6)) a_m = q.T @ a_m @ q atol = 1e-5 rtol = (4.01e-4 - 4e-5)/4 # Just abs cutoff such that we arrive at a_modified a_p = pinvh(a, atol=atol, rtol=0.) adiff1 = a @ a_p @ a - a adiff2 = a_m @ a_p @ a_m - a_m # Now adiff1 should dance around atol value since truncation # while adiff2 should be relatively tiny assert_allclose(norm(adiff1), atol, rtol=0.1) assert_allclose(norm(adiff2), 1e-12, atol=1e-11)
# Now do the same but through rtol cancelling atol value a_p = pinvh(a, atol=atol, rtol=rtol) adiff1 = a @ a_p @ a - a adiff2 = a_m @ a_p @ a_m - a_m # adiff1 and adiff2 should be elevated to ~1e-4 due to mismatch assert_allclose(norm(adiff1), 1e-4, rtol=0.1) assert_allclose(norm(adiff2), 1e-4, rtol=0.1)
@pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64]) def test_empty(self, dt): a = np.empty((0, 0), dtype=dt) a_pinv = pinvh(a) assert a_pinv.size == 0 assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype
@pytest.mark.parametrize('scale', (1e-20, 1., 1e20))@pytest.mark.parametrize('pinv_', (pinv, pinvh))def test_auto_rcond(scale, pinv_): x = np.array([[1, 0], [0, 1e-10]]) * scale expected = np.diag(1. / np.diag(x)) x_inv = pinv_(x) assert_allclose(x_inv, expected)
class TestVectorNorms:
def test_types(self): for dtype in np.typecodes['AllFloat']: x = np.array([1, 2, 3], dtype=dtype) tol = max(1e-15, np.finfo(dtype).eps.real * 20) assert_allclose(norm(x), np.sqrt(14), rtol=tol) assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
for dtype in np.typecodes['Complex']: x = np.array([1j, 2j, 3j], dtype=dtype) tol = max(1e-15, np.finfo(dtype).eps.real * 20) assert_allclose(norm(x), np.sqrt(14), rtol=tol) assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
def test_overflow(self): # unlike numpy's norm, this one is # safer on overflow a = array([1e20], dtype=float32) assert_almost_equal(norm(a), a)
def test_stable(self): # more stable than numpy's norm a = array([1e4] + [1]*10000, dtype=float32) try: # snrm in double precision; we obtain the same as for float64 # -- large atol needed due to varying blas implementations assert_allclose(norm(a) - 1e4, 0.5, atol=1e-2) except AssertionError: # snrm implemented in single precision, == np.linalg.norm result msg = ": Result should equal either 0.0 or 0.5 (depending on " \ "implementation of snrm2)." assert_almost_equal(norm(a) - 1e4, 0.0, err_msg=msg)
def test_zero_norm(self): assert_equal(norm([1, 0, 3], 0), 2) assert_equal(norm([1, 2, 3], 0), 3)
def test_axis_kwd(self): a = np.array([[[2, 1], [3, 4]]] * 2, 'd') assert_allclose(norm(a, axis=1), [[3.60555128, 4.12310563]] * 2) assert_allclose(norm(a, 1, axis=1), [[5.] * 2] * 2)
def test_keepdims_kwd(self): a = np.array([[[2, 1], [3, 4]]] * 2, 'd') b = norm(a, axis=1, keepdims=True) assert_allclose(b, [[[3.60555128, 4.12310563]]] * 2) assert_(b.shape == (2, 1, 2)) assert_allclose(norm(a, 1, axis=2, keepdims=True), [[[3.], [7.]]] * 2)
@pytest.mark.skipif(not HAS_ILP64, reason="64-bit BLAS required") def test_large_vector(self): check_free_memory(free_mb=17000) x = np.zeros([2**31], dtype=np.float64) x[-1] = 1 res = norm(x) del x assert_allclose(res, 1.0)
class TestMatrixNorms:
def test_matrix_norms(self): # Not all of these are matrix norms in the most technical sense. np.random.seed(1234) for n, m in (1, 1), (1, 3), (3, 1), (4, 4), (4, 5), (5, 4): for t in np.float32, np.float64, np.complex64, np.complex128, np.int64: A = 10 * np.random.randn(n, m).astype(t) if np.issubdtype(A.dtype, np.complexfloating): A = (A + 10j * np.random.randn(n, m)).astype(t) t_high = np.complex128 else: t_high = np.float64 for order in (None, 'fro', 1, -1, 2, -2, np.inf, -np.inf): actual = norm(A, ord=order) desired = np.linalg.norm(A, ord=order) # SciPy may return higher precision matrix norms. # This is a consequence of using LAPACK. if not np.allclose(actual, desired): desired = np.linalg.norm(A.astype(t_high), ord=order) assert_allclose(actual, desired)
def test_axis_kwd(self): a = np.array([[[2, 1], [3, 4]]] * 2, 'd') b = norm(a, ord=np.inf, axis=(1, 0)) c = norm(np.swapaxes(a, 0, 1), ord=np.inf, axis=(0, 1)) d = norm(a, ord=1, axis=(0, 1)) assert_allclose(b, c) assert_allclose(c, d) assert_allclose(b, d) assert_(b.shape == c.shape == d.shape) b = norm(a, ord=1, axis=(1, 0)) c = norm(np.swapaxes(a, 0, 1), ord=1, axis=(0, 1)) d = norm(a, ord=np.inf, axis=(0, 1)) assert_allclose(b, c) assert_allclose(c, d) assert_allclose(b, d) assert_(b.shape == c.shape == d.shape)
def test_keepdims_kwd(self): a = np.arange(120, dtype='d').reshape(2, 3, 4, 5) b = norm(a, ord=np.inf, axis=(1, 0), keepdims=True) c = norm(a, ord=1, axis=(0, 1), keepdims=True) assert_allclose(b, c) assert_(b.shape == c.shape)
def test_empty(self): a = np.empty((0, 0)) assert_allclose(norm(a), 0.) assert_allclose(norm(a, axis=0), np.zeros((0,))) assert_allclose(norm(a, keepdims=True), np.zeros((1, 1)))
a = np.empty((0, 3)) assert_allclose(norm(a), 0.) assert_allclose(norm(a, axis=0), np.zeros((3,))) assert_allclose(norm(a, keepdims=True), np.zeros((1, 1)))
class TestOverwrite: def test_solve(self): assert_no_overwrite(solve, [(3, 3), (3,)])
def test_solve_triangular(self): assert_no_overwrite(solve_triangular, [(3, 3), (3,)])
def test_solve_banded(self): assert_no_overwrite(lambda ab, b: solve_banded((2, 1), ab, b), [(4, 6), (6,)])
def test_solveh_banded(self): assert_no_overwrite(solveh_banded, [(2, 6), (6,)])
def test_inv(self): assert_no_overwrite(inv, [(3, 3)])
def test_det(self): assert_no_overwrite(det, [(3, 3)])
def test_lstsq(self): assert_no_overwrite(lstsq, [(3, 2), (3,)])
def test_pinv(self): assert_no_overwrite(pinv, [(3, 3)])
def test_pinvh(self): assert_no_overwrite(pinvh, [(3, 3)])
class TestSolveCirculant:
def test_basic1(self): c = np.array([1, 2, 3, 5]) b = np.array([1, -1, 1, 0]) x = solve_circulant(c, b) y = solve(circulant(c), b) assert_allclose(x, y)
def test_basic2(self): # b is a 2-d matrix. c = np.array([1, 2, -3, -5]) b = np.arange(12).reshape(4, 3) x = solve_circulant(c, b) y = solve(circulant(c), b) assert_allclose(x, y)
def test_basic3(self): # b is a 3-d matrix. c = np.array([1, 2, -3, -5]) b = np.arange(24).reshape(4, 3, 2) x = solve_circulant(c, b) y = solve(circulant(c), b) assert_allclose(x, y)
def test_complex(self): # Complex b and c c = np.array([1+2j, -3, 4j, 5]) b = np.arange(8).reshape(4, 2) + 0.5j x = solve_circulant(c, b) y = solve(circulant(c), b) assert_allclose(x, y)
def test_random_b_and_c(self): # Random b and c rng = np.random.RandomState(54321) c = rng.randn(50) b = rng.randn(50) x = solve_circulant(c, b) y = solve(circulant(c), b) assert_allclose(x, y)
def test_singular(self): # c gives a singular circulant matrix. c = np.array([1, 1, 0, 0]) b = np.array([1, 2, 3, 4]) x = solve_circulant(c, b, singular='lstsq') y, res, rnk, s = lstsq(circulant(c), b) assert_allclose(x, y) assert_raises(LinAlgError, solve_circulant, x, y)
def test_axis_args(self): # Test use of caxis, baxis and outaxis.
# c has shape (2, 1, 4) c = np.array([[[-1, 2.5, 3, 3.5]], [[1, 6, 6, 6.5]]])
# b has shape (3, 4) b = np.array([[0, 0, 1, 1], [1, 1, 0, 0], [1, -1, 0, 0]])
x = solve_circulant(c, b, baxis=1) assert_equal(x.shape, (4, 2, 3)) expected = np.empty_like(x) expected[:, 0, :] = solve(circulant(c[0].ravel()), b.T) expected[:, 1, :] = solve(circulant(c[1].ravel()), b.T) assert_allclose(x, expected)
x = solve_circulant(c, b, baxis=1, outaxis=-1) assert_equal(x.shape, (2, 3, 4)) assert_allclose(np.moveaxis(x, -1, 0), expected)
# np.swapaxes(c, 1, 2) has shape (2, 4, 1); b.T has shape (4, 3). x = solve_circulant(np.swapaxes(c, 1, 2), b.T, caxis=1) assert_equal(x.shape, (4, 2, 3)) assert_allclose(x, expected)
def test_native_list_arguments(self): # Same as test_basic1 using python's native list. c = [1, 2, 3, 5] b = [1, -1, 1, 0] x = solve_circulant(c, b) y = solve(circulant(c), b) assert_allclose(x, y)
@pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64]) @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt_c, dt_b): c = np.array([], dtype=dt_c) b = np.array([], dtype=dt_b) x = solve_circulant(c, b) assert x.shape == (0,) assert x.dtype == solve_circulant(np.arange(3, dtype=dt_c), np.ones(3, dtype=dt_b)).dtype
b = np.empty((0, 0), dtype=dt_b) x1 = solve_circulant(c, b) assert x1.shape == (0, 0) assert x1.dtype == x.dtype
class TestMatrix_Balance:
def test_string_arg(self): assert_raises(ValueError, matrix_balance, 'Some string for fail')
def test_infnan_arg(self): assert_raises(ValueError, matrix_balance, np.array([[1, 2], [3, np.inf]])) assert_raises(ValueError, matrix_balance, np.array([[1, 2], [3, np.nan]]))
def test_scaling(self): _, y = matrix_balance(np.array([[1000, 1], [1000, 0]])) # Pre/post LAPACK 3.5.0 gives the same result up to an offset # since in each case col norm is x1000 greater and # 1000 / 32 ~= 1 * 32 hence balanced with 2 ** 5. assert_allclose(np.diff(np.log2(np.diag(y))), [5])
def test_scaling_order(self): A = np.array([[1, 0, 1e-4], [1, 1, 1e-2], [1e4, 1e2, 1]]) x, y = matrix_balance(A) assert_allclose(solve(y, A).dot(y), x)
def test_separate(self): _, (y, z) = matrix_balance(np.array([[1000, 1], [1000, 0]]), separate=1) assert_equal(np.diff(np.log2(y)), [5]) assert_allclose(z, np.arange(2))
def test_permutation(self): A = block_diag(np.ones((2, 2)), np.tril(np.ones((2, 2))), np.ones((3, 3))) x, (y, z) = matrix_balance(A, separate=1) assert_allclose(y, np.ones_like(y)) assert_allclose(z, np.array([0, 1, 6, 5, 4, 3, 2]))
def test_perm_and_scaling(self): # Matrix with its diagonal removed cases = ( # Case 0 np.array([[0., 0., 0., 0., 0.000002], [0., 0., 0., 0., 0.], [2., 2., 0., 0., 0.], [2., 2., 0., 0., 0.], [0., 0., 0.000002, 0., 0.]]), # Case 1 user reported GH-7258 np.array([[-0.5, 0., 0., 0.], [0., -1., 0., 0.], [1., 0., -0.5, 0.], [0., 1., 0., -1.]]), # Case 2 user reported GH-7258 np.array([[-3., 0., 1., 0.], [-1., -1., -0., 1.], [-3., -0., -0., 0.], [-1., -0., 1., -1.]]) )
for A in cases: x, y = matrix_balance(A) x, (s, p) = matrix_balance(A, separate=1) ip = np.empty_like(p) ip[p] = np.arange(A.shape[0]) assert_allclose(y, np.diag(s)[ip, :]) assert_allclose(solve(y, A).dot(y), x)
@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt): a = np.empty((0, 0), dtype=dt) b, t = matrix_balance(a)
assert b.size == 0 assert t.size == 0
b_n, t_n = matrix_balance(np.eye(2, dtype=dt)) assert b.dtype == b_n.dtype assert t.dtype == t_n.dtype
b, (scale, perm) = matrix_balance(a, separate=True) assert b.size == 0 assert scale.size == 0 assert perm.size == 0
b_n, (scale_n, perm_n) = matrix_balance(a, separate=True) assert b.dtype == b_n.dtype assert scale.dtype == scale_n.dtype assert perm.dtype == perm_n.dtype12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127## Created by: Pearu Peterson, April 2002#
import mathimport pytestimport numpy as npimport numpy.randomfrom numpy.testing import (assert_equal, assert_almost_equal, assert_, assert_array_almost_equal, assert_allclose)from pytest import raises as assert_raises
from numpy import float32, float64, complex64, complex128, arange, triu, \ tril, zeros, tril_indices, ones, mod, diag, append, eye, \ nonzero
import scipyfrom scipy.linalg import _fblas as fblas, get_blas_funcs, toeplitz, solve
try: from scipy.linalg import _cblas as cblasexcept ImportError: cblas = None
REAL_DTYPES = [float32, float64]COMPLEX_DTYPES = [complex64, complex128]DTYPES = REAL_DTYPES + COMPLEX_DTYPES
def test_get_blas_funcs(): # check that it returns Fortran code for arrays that are # fortran-ordered f1, f2, f3 = get_blas_funcs( ('axpy', 'axpy', 'axpy'), (np.empty((2, 2), dtype=np.complex64, order='F'), np.empty((2, 2), dtype=np.complex128, order='C')) )
# get_blas_funcs will choose libraries depending on most generic # array assert_equal(f1.typecode, 'z') assert_equal(f2.typecode, 'z') if cblas is not None: assert_equal(f1.module_name, 'cblas') assert_equal(f2.module_name, 'cblas')
# check defaults. f1 = get_blas_funcs('rotg') assert_equal(f1.typecode, 'd')
# check also dtype interface f1 = get_blas_funcs('gemm', dtype=np.complex64) assert_equal(f1.typecode, 'c') f1 = get_blas_funcs('gemm', dtype='F') assert_equal(f1.typecode, 'c')
# extended precision complex f1 = get_blas_funcs('gemm', dtype=np.clongdouble) assert_equal(f1.typecode, 'z')
# check safe complex upcasting f1 = get_blas_funcs('axpy', (np.empty((2, 2), dtype=np.float64), np.empty((2, 2), dtype=np.complex64)) ) assert_equal(f1.typecode, 'z')
def test_get_blas_funcs_alias(): # check alias for get_blas_funcs f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64) assert f.typecode == 'c' assert g.typecode == 'c'
f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64) assert f is g assert f is h
class TestCBLAS1Simple:
def test_axpy(self): for p in 'sd': f = getattr(cblas, p+'axpy', None) if f is None: continue assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5), [7, 9, 18]) for p in 'cz': f = getattr(cblas, p+'axpy', None) if f is None: continue assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5), [7, 10j-1, 18])
class TestFBLAS1Simple:
def test_axpy(self): for p in 'sd': f = getattr(fblas, p+'axpy', None) if f is None: continue assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5), [7, 9, 18]) for p in 'cz': f = getattr(fblas, p+'axpy', None) if f is None: continue assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5), [7, 10j-1, 18])
def test_copy(self): for p in 'sd': f = getattr(fblas, p+'copy', None) if f is None: continue assert_array_almost_equal(f([3, 4, 5], [8]*3), [3, 4, 5]) for p in 'cz': f = getattr(fblas, p+'copy', None) if f is None: continue assert_array_almost_equal(f([3, 4j, 5+3j], [8]*3), [3, 4j, 5+3j])
def test_asum(self): for p in 'sd': f = getattr(fblas, p+'asum', None) if f is None: continue assert_almost_equal(f([3, -4, 5]), 12) for p in ['sc', 'dz']: f = getattr(fblas, p+'asum', None) if f is None: continue assert_almost_equal(f([3j, -4, 3-4j]), 14)
def test_dot(self): for p in 'sd': f = getattr(fblas, p+'dot', None) if f is None: continue assert_almost_equal(f([3, -4, 5], [2, 5, 1]), -9)
def test_complex_dotu(self): for p in 'cz': f = getattr(fblas, p+'dotu', None) if f is None: continue assert_almost_equal(f([3j, -4, 3-4j], [2, 3, 1]), -9+2j)
def test_complex_dotc(self): for p in 'cz': f = getattr(fblas, p+'dotc', None) if f is None: continue assert_almost_equal(f([3j, -4, 3-4j], [2, 3j, 1]), 3-14j)
def test_nrm2(self): for p in 'sd': f = getattr(fblas, p+'nrm2', None) if f is None: continue assert_almost_equal(f([3, -4, 5]), math.sqrt(50)) for p in ['c', 'z', 'sc', 'dz']: f = getattr(fblas, p+'nrm2', None) if f is None: continue assert_almost_equal(f([3j, -4, 3-4j]), math.sqrt(50))
def test_scal(self): for p in 'sd': f = getattr(fblas, p+'scal', None) if f is None: continue assert_array_almost_equal(f(2, [3, -4, 5]), [6, -8, 10]) for p in 'cz': f = getattr(fblas, p+'scal', None) if f is None: continue assert_array_almost_equal(f(3j, [3j, -4, 3-4j]), [-9, -12j, 12+9j]) for p in ['cs', 'zd']: f = getattr(fblas, p+'scal', None) if f is None: continue assert_array_almost_equal(f(3, [3j, -4, 3-4j]), [9j, -12, 9-12j])
def test_swap(self): for p in 'sd': f = getattr(fblas, p+'swap', None) if f is None: continue x, y = [2, 3, 1], [-2, 3, 7] x1, y1 = f(x, y) assert_array_almost_equal(x1, y) assert_array_almost_equal(y1, x) for p in 'cz': f = getattr(fblas, p+'swap', None) if f is None: continue x, y = [2, 3j, 1], [-2, 3, 7-3j] x1, y1 = f(x, y) assert_array_almost_equal(x1, y) assert_array_almost_equal(y1, x)
def test_amax(self): for p in 'sd': f = getattr(fblas, 'i'+p+'amax') assert_equal(f([-2, 4, 3]), 1) for p in 'cz': f = getattr(fblas, 'i'+p+'amax') assert_equal(f([-5, 4+3j, 6]), 1) # XXX: need tests for rot,rotm,rotg,rotmg
class TestFBLAS2Simple:
def test_gemv(self): for p in 'sd': f = getattr(fblas, p+'gemv', None) if f is None: continue assert_array_almost_equal(f(3, [[3]], [-4]), [-36]) assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21]) for p in 'cz': f = getattr(fblas, p+'gemv', None) if f is None: continue assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-48-36j]) assert_array_almost_equal(f(3j, [[3-4j]], [-4], 3, [5j]), [-48-21j])
# All of these *ger* functions are segfaulting when called from multiple # threads under free-threaded CPython, see gh-21936. @pytest.mark.thread_unsafe def test_ger(self):
for p in 'sd': f = getattr(fblas, p+'ger', None) if f is None: continue assert_array_almost_equal(f(1, [1, 2], [3, 4]), [[3, 4], [6, 8]]) assert_array_almost_equal(f(2, [1, 2, 3], [3, 4]), [[6, 8], [12, 16], [18, 24]])
assert_array_almost_equal(f(1, [1, 2], [3, 4], a=[[1, 2], [3, 4]]), [[4, 6], [9, 12]])
for p in 'cz': f = getattr(fblas, p+'geru', None) if f is None: continue assert_array_almost_equal(f(1, [1j, 2], [3, 4]), [[3j, 4j], [6, 8]]) assert_array_almost_equal(f(-2, [1j, 2j, 3j], [3j, 4j]), [[6, 8], [12, 16], [18, 24]])
for p in 'cz': for name in ('ger', 'gerc'): f = getattr(fblas, p+name, None) if f is None: continue assert_array_almost_equal(f(1, [1j, 2], [3, 4]), [[3j, 4j], [6, 8]]) assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]), [[6, 8], [12, 16], [18, 24]])
def test_syr_her(self): x = np.arange(1, 5, dtype='d') resx = np.triu(x[:, np.newaxis] * x) resx_reverse = np.triu(x[::-1, np.newaxis] * x[::-1])
y = np.linspace(0, 8.5, 17, endpoint=False)
z = np.arange(1, 9, dtype='d').view('D') resz = np.triu(z[:, np.newaxis] * z) resz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1]) rehz = np.triu(z[:, np.newaxis] * z.conj()) rehz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1].conj())
w = np.c_[np.zeros(4), z, np.zeros(4)].ravel()
for p, rtol in zip('sd', [1e-7, 1e-14]): f = getattr(fblas, p+'syr', None) if f is None: continue assert_allclose(f(1.0, x), resx, rtol=rtol) assert_allclose(f(1.0, x, lower=True), resx.T, rtol=rtol) assert_allclose(f(1.0, y, incx=2, offx=2, n=4), resx, rtol=rtol) # negative increments imply reversed vectors in blas assert_allclose(f(1.0, y, incx=-2, offx=2, n=4), resx_reverse, rtol=rtol)
a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F') b = f(1.0, x, a=a, overwrite_a=True) assert_allclose(a, resx, rtol=rtol)
b = f(2.0, x, a=a) assert_(a is not b) assert_allclose(b, 3*resx, rtol=rtol)
assert_raises(Exception, f, 1.0, x, incx=0) assert_raises(Exception, f, 1.0, x, offx=5) assert_raises(Exception, f, 1.0, x, offx=-2) assert_raises(Exception, f, 1.0, x, n=-2) assert_raises(Exception, f, 1.0, x, n=5) assert_raises(Exception, f, 1.0, x, lower=2) assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
for p, rtol in zip('cz', [1e-7, 1e-14]): f = getattr(fblas, p+'syr', None) if f is None: continue assert_allclose(f(1.0, z), resz, rtol=rtol) assert_allclose(f(1.0, z, lower=True), resz.T, rtol=rtol) assert_allclose(f(1.0, w, incx=3, offx=1, n=4), resz, rtol=rtol) # negative increments imply reversed vectors in blas assert_allclose(f(1.0, w, incx=-3, offx=1, n=4), resz_reverse, rtol=rtol)
a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F') b = f(1.0, z, a=a, overwrite_a=True) assert_allclose(a, resz, rtol=rtol)
b = f(2.0, z, a=a) assert_(a is not b) assert_allclose(b, 3*resz, rtol=rtol)
assert_raises(Exception, f, 1.0, x, incx=0) assert_raises(Exception, f, 1.0, x, offx=5) assert_raises(Exception, f, 1.0, x, offx=-2) assert_raises(Exception, f, 1.0, x, n=-2) assert_raises(Exception, f, 1.0, x, n=5) assert_raises(Exception, f, 1.0, x, lower=2) assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
for p, rtol in zip('cz', [1e-7, 1e-14]): f = getattr(fblas, p+'her', None) if f is None: continue assert_allclose(f(1.0, z), rehz, rtol=rtol) assert_allclose(f(1.0, z, lower=True), rehz.T.conj(), rtol=rtol) assert_allclose(f(1.0, w, incx=3, offx=1, n=4), rehz, rtol=rtol) # negative increments imply reversed vectors in blas assert_allclose(f(1.0, w, incx=-3, offx=1, n=4), rehz_reverse, rtol=rtol)
a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F') b = f(1.0, z, a=a, overwrite_a=True) assert_allclose(a, rehz, rtol=rtol)
b = f(2.0, z, a=a) assert_(a is not b) assert_allclose(b, 3*rehz, rtol=rtol)
assert_raises(Exception, f, 1.0, x, incx=0) assert_raises(Exception, f, 1.0, x, offx=5) assert_raises(Exception, f, 1.0, x, offx=-2) assert_raises(Exception, f, 1.0, x, n=-2) assert_raises(Exception, f, 1.0, x, n=5) assert_raises(Exception, f, 1.0, x, lower=2) assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
def test_syr2(self): x = np.arange(1, 5, dtype='d') y = np.arange(5, 9, dtype='d') resxy = np.triu(x[:, np.newaxis] * y + y[:, np.newaxis] * x) resxy_reverse = np.triu(x[::-1, np.newaxis] * y[::-1] + y[::-1, np.newaxis] * x[::-1])
q = np.linspace(0, 8.5, 17, endpoint=False)
for p, rtol in zip('sd', [1e-7, 1e-14]): f = getattr(fblas, p+'syr2', None) if f is None: continue assert_allclose(f(1.0, x, y), resxy, rtol=rtol) assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol) assert_allclose(f(1.0, x, y, lower=True), resxy.T, rtol=rtol)
assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10), resxy, rtol=rtol) assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10, n=3), resxy[:3, :3], rtol=rtol) # negative increments imply reversed vectors in blas assert_allclose(f(1.0, q, q, incx=-2, offx=2, incy=-2, offy=10), resxy_reverse, rtol=rtol)
a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F') b = f(1.0, x, y, a=a, overwrite_a=True) assert_allclose(a, resxy, rtol=rtol)
b = f(2.0, x, y, a=a) assert_(a is not b) assert_allclose(b, 3*resxy, rtol=rtol)
assert_raises(Exception, f, 1.0, x, y, incx=0) assert_raises(Exception, f, 1.0, x, y, offx=5) assert_raises(Exception, f, 1.0, x, y, offx=-2) assert_raises(Exception, f, 1.0, x, y, incy=0) assert_raises(Exception, f, 1.0, x, y, offy=5) assert_raises(Exception, f, 1.0, x, y, offy=-2) assert_raises(Exception, f, 1.0, x, y, n=-2) assert_raises(Exception, f, 1.0, x, y, n=5) assert_raises(Exception, f, 1.0, x, y, lower=2) assert_raises(Exception, f, 1.0, x, y, a=np.zeros((2, 2), 'd', 'F'))
def test_her2(self): x = np.arange(1, 9, dtype='d').view('D') y = np.arange(9, 17, dtype='d').view('D') resxy = x[:, np.newaxis] * y.conj() + y[:, np.newaxis] * x.conj() resxy = np.triu(resxy)
resxy_reverse = x[::-1, np.newaxis] * y[::-1].conj() resxy_reverse += y[::-1, np.newaxis] * x[::-1].conj() resxy_reverse = np.triu(resxy_reverse)
u = np.c_[np.zeros(4), x, np.zeros(4)].ravel() v = np.c_[np.zeros(4), y, np.zeros(4)].ravel()
for p, rtol in zip('cz', [1e-7, 1e-14]): f = getattr(fblas, p+'her2', None) if f is None: continue assert_allclose(f(1.0, x, y), resxy, rtol=rtol) assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol) assert_allclose(f(1.0, x, y, lower=True), resxy.T.conj(), rtol=rtol)
assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1), resxy, rtol=rtol) assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1, n=3), resxy[:3, :3], rtol=rtol) # negative increments imply reversed vectors in blas assert_allclose(f(1.0, u, v, incx=-3, offx=1, incy=-3, offy=1), resxy_reverse, rtol=rtol)
a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F') b = f(1.0, x, y, a=a, overwrite_a=True) assert_allclose(a, resxy, rtol=rtol)
b = f(2.0, x, y, a=a) assert_(a is not b) assert_allclose(b, 3*resxy, rtol=rtol)
assert_raises(Exception, f, 1.0, x, y, incx=0) assert_raises(Exception, f, 1.0, x, y, offx=5) assert_raises(Exception, f, 1.0, x, y, offx=-2) assert_raises(Exception, f, 1.0, x, y, incy=0) assert_raises(Exception, f, 1.0, x, y, offy=5) assert_raises(Exception, f, 1.0, x, y, offy=-2) assert_raises(Exception, f, 1.0, x, y, n=-2) assert_raises(Exception, f, 1.0, x, y, n=5) assert_raises(Exception, f, 1.0, x, y, lower=2) assert_raises(Exception, f, 1.0, x, y, a=np.zeros((2, 2), 'd', 'F'))
def test_gbmv(self): rng = np.random.default_rng(1234) for ind, dtype in enumerate(DTYPES): n = 7 m = 5 kl = 1 ku = 2 # fake a banded matrix via toeplitz A = toeplitz(append(rng.random(kl+1), zeros(m-kl-1)), append(rng.random(ku+1), zeros(n-ku-1))) A = A.astype(dtype) Ab = zeros((kl+ku+1, n), dtype=dtype)
# Form the banded storage Ab[2, :5] = A[0, 0] # diag Ab[1, 1:6] = A[0, 1] # sup1 Ab[0, 2:7] = A[0, 2] # sup2 Ab[3, :4] = A[1, 0] # sub1
x = rng.random(n).astype(dtype) y = rng.random(m).astype(dtype) alpha, beta = dtype(3), dtype(-5)
func, = get_blas_funcs(('gbmv',), dtype=dtype) y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab, x=x, y=y, beta=beta) y2 = alpha * A.dot(x) + beta * y assert_array_almost_equal(y1, y2)
y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab, x=y, y=x, beta=beta, trans=1) y2 = alpha * A.T.dot(y) + beta * x assert_array_almost_equal(y1, y2)
def test_sbmv_hbmv(self): rng = np.random.default_rng(1234) for ind, dtype in enumerate(DTYPES): n = 6 k = 2 A = zeros((n, n), dtype=dtype) Ab = zeros((k+1, n), dtype=dtype)
# Form the array and its packed banded storage A[arange(n), arange(n)] = rng.random(n) for ind2 in range(1, k+1): temp = rng.random(n-ind2) A[arange(n-ind2), arange(ind2, n)] = temp Ab[-1-ind2, ind2:] = temp A = A.astype(dtype) A = A + A.T if ind < 2 else A + A.conj().T Ab[-1, :] = diag(A) x = rng.random(n).astype(dtype) y = rng.random(n).astype(dtype) alpha, beta = dtype(1.25), dtype(3)
if ind > 1: func, = get_blas_funcs(('hbmv',), dtype=dtype) else: func, = get_blas_funcs(('sbmv',), dtype=dtype) y1 = func(k=k, alpha=alpha, a=Ab, x=x, y=y, beta=beta) y2 = alpha * A.dot(x) + beta * y assert_array_almost_equal(y1, y2)
def test_spmv_hpmv(self): rng = np.random.default_rng(12345698) for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES): n = 3 A = rng.random((n, n)).astype(dtype) if ind > 1: A += rng.random((n, n))*1j A = A.astype(dtype) A = A + A.T if ind < 4 else A + A.conj().T c, r = tril_indices(n) Ap = A[r, c] x = rng.random(n).astype(dtype) y = rng.random(n).astype(dtype) xlong = arange(2*n).astype(dtype) ylong = ones(2*n).astype(dtype) alpha, beta = dtype(1.25), dtype(2)
if ind > 3: func, = get_blas_funcs(('hpmv',), dtype=dtype) else: func, = get_blas_funcs(('spmv',), dtype=dtype) y1 = func(n=n, alpha=alpha, ap=Ap, x=x, y=y, beta=beta) y2 = alpha * A.dot(x) + beta * y assert_array_almost_equal(y1, y2)
# Test inc and offsets y1 = func(n=n-1, alpha=alpha, beta=beta, x=xlong, y=ylong, ap=Ap, incx=2, incy=2, offx=n, offy=n) y2 = (alpha * A[:-1, :-1]).dot(xlong[3::2]) + beta * ylong[3::2] assert_array_almost_equal(y1[3::2], y2) assert_almost_equal(y1[4], ylong[4])
def test_spr_hpr(self): rng = np.random.default_rng(1234) for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES): n = 3 A = rng.random((n, n)).astype(dtype) if ind > 1: A += rng.random((n, n))*1j A = A.astype(dtype) A = A + A.T if ind < 4 else A + A.conj().T c, r = tril_indices(n) Ap = A[r, c] x = rng.random(n).astype(dtype) alpha = (DTYPES+COMPLEX_DTYPES)[mod(ind, 4)](2.5)
if ind > 3: func, = get_blas_funcs(('hpr',), dtype=dtype) y2 = alpha * x[:, None].dot(x[None, :].conj()) + A else: func, = get_blas_funcs(('spr',), dtype=dtype) y2 = alpha * x[:, None].dot(x[None, :]) + A
y1 = func(n=n, alpha=alpha, ap=Ap, x=x) y1f = zeros((3, 3), dtype=dtype) y1f[r, c] = y1 y1f[c, r] = y1.conj() if ind > 3 else y1 assert_array_almost_equal(y1f, y2)
def test_spr2_hpr2(self): rng = np.random.default_rng(1234) for ind, dtype in enumerate(DTYPES): n = 3 A = rng.random((n, n)).astype(dtype) if ind > 1: A += rng.random((n, n))*1j A = A.astype(dtype) A = A + A.T if ind < 2 else A + A.conj().T c, r = tril_indices(n) Ap = A[r, c] x = rng.random(n).astype(dtype) y = rng.random(n).astype(dtype) alpha = dtype(2)
if ind > 1: func, = get_blas_funcs(('hpr2',), dtype=dtype) else: func, = get_blas_funcs(('spr2',), dtype=dtype)
u = alpha.conj() * x[:, None].dot(y[None, :].conj()) y2 = A + u + u.conj().T y1 = func(n=n, alpha=alpha, x=x, y=y, ap=Ap) y1f = zeros((3, 3), dtype=dtype) y1f[r, c] = y1 y1f[[1, 2, 2], [0, 0, 1]] = y1[[1, 3, 4]].conj() assert_array_almost_equal(y1f, y2)
def test_tbmv(self): rng = np.random.default_rng(1234) for ind, dtype in enumerate(DTYPES): n = 10 k = 3 x = rng.random(n).astype(dtype) A = zeros((n, n), dtype=dtype) # Banded upper triangular array for sup in range(k+1): A[arange(n-sup), arange(sup, n)] = rng.random(n-sup)
# Add complex parts for c,z if ind > 1: A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype)
# Form the banded storage Ab = zeros((k+1, n), dtype=dtype) for row in range(k+1): Ab[-row-1, row:] = diag(A, k=row) func, = get_blas_funcs(('tbmv',), dtype=dtype)
y1 = func(k=k, a=Ab, x=x) y2 = A.dot(x) assert_array_almost_equal(y1, y2)
y1 = func(k=k, a=Ab, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = A.dot(x) assert_array_almost_equal(y1, y2)
y1 = func(k=k, a=Ab, x=x, diag=1, trans=1) y2 = A.T.dot(x) assert_array_almost_equal(y1, y2)
y1 = func(k=k, a=Ab, x=x, diag=1, trans=2) y2 = A.conj().T.dot(x) assert_array_almost_equal(y1, y2)
def test_tbsv(self): rng = np.random.default_rng(1234) for ind, dtype in enumerate(DTYPES): n = 6 k = 3 x = rng.random(n).astype(dtype) A = zeros((n, n), dtype=dtype) # Banded upper triangular array for sup in range(k+1): A[arange(n-sup), arange(sup, n)] = rng.random(n-sup)
# Add complex parts for c,z if ind > 1: A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype)
# Form the banded storage Ab = zeros((k+1, n), dtype=dtype) for row in range(k+1): Ab[-row-1, row:] = diag(A, k=row) func, = get_blas_funcs(('tbsv',), dtype=dtype)
y1 = func(k=k, a=Ab, x=x) y2 = solve(A, x) assert_array_almost_equal(y1, y2)
y1 = func(k=k, a=Ab, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = solve(A, x) assert_array_almost_equal(y1, y2)
y1 = func(k=k, a=Ab, x=x, diag=1, trans=1) y2 = solve(A.T, x) assert_array_almost_equal(y1, y2)
y1 = func(k=k, a=Ab, x=x, diag=1, trans=2) y2 = solve(A.conj().T, x) assert_array_almost_equal(y1, y2)
def test_tpmv(self): rng = np.random.default_rng(1234) for ind, dtype in enumerate(DTYPES): n = 10 x = rng.random(n).astype(dtype) # Upper triangular array if ind < 2: A = triu(rng.random((n, n))) else: A = triu(rng.random((n, n)) + rng.random((n, n))*1j)
# Form the packed storage c, r = tril_indices(n) Ap = A[r, c] func, = get_blas_funcs(('tpmv',), dtype=dtype)
y1 = func(n=n, ap=Ap, x=x) y2 = A.dot(x) assert_array_almost_equal(y1, y2)
y1 = func(n=n, ap=Ap, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = A.dot(x) assert_array_almost_equal(y1, y2)
y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1) y2 = A.T.dot(x) assert_array_almost_equal(y1, y2)
y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2) y2 = A.conj().T.dot(x) assert_array_almost_equal(y1, y2)
def test_tpsv(self): rng = np.random.default_rng(1234) for ind, dtype in enumerate(DTYPES): n = 10 x = rng.random(n).astype(dtype) # Upper triangular array if ind < 2: A = triu(rng.random((n, n))) else: A = triu(rng.random((n, n)) + rng.random((n, n))*1j) A += eye(n) # Form the packed storage c, r = tril_indices(n) Ap = A[r, c] func, = get_blas_funcs(('tpsv',), dtype=dtype)
y1 = func(n=n, ap=Ap, x=x) y2 = solve(A, x) assert_array_almost_equal(y1, y2)
y1 = func(n=n, ap=Ap, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = solve(A, x) assert_array_almost_equal(y1, y2)
y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1) y2 = solve(A.T, x) assert_array_almost_equal(y1, y2)
y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2) y2 = solve(A.conj().T, x) assert_array_almost_equal(y1, y2)
def test_trmv(self): rng = np.random.default_rng(1234) for ind, dtype in enumerate(DTYPES): n = 3 A = (rng.random((n, n))+eye(n)).astype(dtype) x = rng.random(3).astype(dtype) func, = get_blas_funcs(('trmv',), dtype=dtype)
y1 = func(a=A, x=x) y2 = triu(A).dot(x) assert_array_almost_equal(y1, y2)
y1 = func(a=A, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = triu(A).dot(x) assert_array_almost_equal(y1, y2)
y1 = func(a=A, x=x, diag=1, trans=1) y2 = triu(A).T.dot(x) assert_array_almost_equal(y1, y2)
y1 = func(a=A, x=x, diag=1, trans=2) y2 = triu(A).conj().T.dot(x) assert_array_almost_equal(y1, y2)
def test_trsv(self): rng = np.random.default_rng(1234) for ind, dtype in enumerate(DTYPES): n = 15 A = (rng.random((n, n))+eye(n)).astype(dtype) x = rng.random(n).astype(dtype) func, = get_blas_funcs(('trsv',), dtype=dtype)
y1 = func(a=A, x=x) y2 = solve(triu(A), x) assert_array_almost_equal(y1, y2)
y1 = func(a=A, x=x, lower=1) y2 = solve(tril(A), x) assert_array_almost_equal(y1, y2)
y1 = func(a=A, x=x, diag=1) A[arange(n), arange(n)] = dtype(1) y2 = solve(triu(A), x) assert_array_almost_equal(y1, y2)
y1 = func(a=A, x=x, diag=1, trans=1) y2 = solve(triu(A).T, x) assert_array_almost_equal(y1, y2)
y1 = func(a=A, x=x, diag=1, trans=2) y2 = solve(triu(A).conj().T, x) assert_array_almost_equal(y1, y2)
class TestFBLAS3Simple:
def test_gemm(self): for p in 'sd': f = getattr(fblas, p+'gemm', None) if f is None: continue assert_array_almost_equal(f(3, [3], [-4]), [[-36]]) assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21]) for p in 'cz': f = getattr(fblas, p+'gemm', None) if f is None: continue assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-36j]]) assert_array_almost_equal(f(3j, [3-4j], [-4], 3, [5j]), [-48-21j])
def _get_func(func, ps='sdzc'): """Just a helper: return a specified BLAS function w/typecode.""" for p in ps: f = getattr(fblas, p+func, None) if f is None: continue yield f
class TestBLAS3Symm:
def setup_method(self): self.a = np.array([[1., 2.], [0., 1.]]) self.b = np.array([[1., 0., 3.], [0., -1., 2.]]) self.c = np.ones((2, 3)) self.t = np.array([[2., -1., 8.], [3., 0., 9.]])
def test_symm(self): for f in _get_func('symm'): res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.) assert_array_almost_equal(res, self.t)
res = f(a=self.a.T, b=self.b, lower=1, c=self.c, alpha=1., beta=1.) assert_array_almost_equal(res, self.t)
res = f(a=self.a, b=self.b.T, side=1, c=self.c.T, alpha=1., beta=1.) assert_array_almost_equal(res, self.t.T)
def test_summ_wrong_side(self): f = getattr(fblas, 'dsymm', None) if f is not None: assert_raises(Exception, f, **{'a': self.a, 'b': self.b, 'alpha': 1, 'side': 1}) # `side=1` means C <- B*A, hence shapes of A and B are to be # compatible. Otherwise, f2py exception is raised
def test_symm_wrong_uplo(self): """SYMM only considers the upper/lower part of A. Hence setting wrong value for `lower` (default is lower=0, meaning upper triangle) gives a wrong result. """ f = getattr(fblas, 'dsymm', None) if f is not None: res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.) assert np.allclose(res, self.t)
res = f(a=self.a, b=self.b, lower=1, c=self.c, alpha=1., beta=1.) assert not np.allclose(res, self.t)
class TestBLAS3Syrk: def setup_method(self): self.a = np.array([[1., 0.], [0., -2.], [2., 3.]]) self.t = np.array([[1., 0., 2.], [0., 4., -6.], [2., -6., 13.]]) self.tt = np.array([[5., 6.], [6., 13.]])
def test_syrk(self): for f in _get_func('syrk'): c = f(a=self.a, alpha=1.) assert_array_almost_equal(np.triu(c), np.triu(self.t))
c = f(a=self.a, alpha=1., lower=1) assert_array_almost_equal(np.tril(c), np.tril(self.t))
c0 = np.ones(self.t.shape) c = f(a=self.a, alpha=1., beta=1., c=c0) assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
c = f(a=self.a, alpha=1., trans=1) assert_array_almost_equal(np.triu(c), np.triu(self.tt))
# prints '0-th dimension must be fixed to 3 but got 5', # FIXME: suppress? # FIXME: how to catch the _fblas.error? def test_syrk_wrong_c(self): f = getattr(fblas, 'dsyrk', None) if f is not None: assert_raises(Exception, f, **{'a': self.a, 'alpha': 1., 'c': np.ones((5, 8))}) # if C is supplied, it must have compatible dimensions
class TestBLAS3Syr2k: def setup_method(self): self.a = np.array([[1., 0.], [0., -2.], [2., 3.]]) self.b = np.array([[0., 1.], [1., 0.], [0, 1.]]) self.t = np.array([[0., -1., 3.], [-1., 0., 0.], [3., 0., 6.]]) self.tt = np.array([[0., 1.], [1., 6]])
def test_syr2k(self): for f in _get_func('syr2k'): c = f(a=self.a, b=self.b, alpha=1.) assert_array_almost_equal(np.triu(c), np.triu(self.t))
c = f(a=self.a, b=self.b, alpha=1., lower=1) assert_array_almost_equal(np.tril(c), np.tril(self.t))
c0 = np.ones(self.t.shape) c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0) assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
c = f(a=self.a, b=self.b, alpha=1., trans=1) assert_array_almost_equal(np.triu(c), np.triu(self.tt))
# prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress? def test_syr2k_wrong_c(self): f = getattr(fblas, 'dsyr2k', None) if f is not None: assert_raises(Exception, f, **{'a': self.a, 'b': self.b, 'alpha': 1., 'c': np.zeros((15, 8))}) # if C is supplied, it must have compatible dimensions
class TestSyHe: """Quick and simple tests for (zc)-symm, syrk, syr2k."""
def setup_method(self): self.sigma_y = np.array([[0., -1.j], [1.j, 0.]])
def test_symm_zc(self): for f in _get_func('symm', 'zc'): # NB: a is symmetric w/upper diag of ONLY res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), np.diag([1, -1]))
def test_hemm_zc(self): for f in _get_func('hemm', 'zc'): # NB: a is hermitian w/upper diag of ONLY res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
def test_syrk_zr(self): for f in _get_func('syrk', 'zc'): res = f(a=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), np.diag([-1, -1]))
def test_herk_zr(self): for f in _get_func('herk', 'zc'): res = f(a=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
def test_syr2k_zr(self): for f in _get_func('syr2k', 'zc'): res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1]))
def test_her2k_zr(self): for f in _get_func('her2k', 'zc'): res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) assert_array_almost_equal(np.triu(res), 2.*np.diag([1, 1]))
class TestTRMM: """Quick and simple tests for dtrmm."""
def setup_method(self): self.a = np.array([[1., 2., ], [-2., 1.]]) self.b = np.array([[3., 4., -1.], [5., 6., -2.]])
self.a2 = np.array([[1, 1, 2, 3], [0, 1, 4, 5], [0, 0, 1, 6], [0, 0, 0, 1]], order="f") self.b2 = np.array([[1, 4], [2, 5], [3, 6], [7, 8], [9, 10]], order="f")
@pytest.mark.parametrize("dtype_", DTYPES) def test_side(self, dtype_): trmm = get_blas_funcs("trmm", dtype=dtype_) # Provide large A array that works for side=1 but not 0 (see gh-10841) assert_raises(Exception, trmm, 1.0, self.a2, self.b2) res = trmm(1.0, self.a2.astype(dtype_), self.b2.astype(dtype_), side=1) k = self.b2.shape[1] assert_allclose(res, self.b2 @ self.a2[:k, :k], rtol=0., atol=100*np.finfo(dtype_).eps)
def test_ab(self): f = getattr(fblas, 'dtrmm', None) if f is not None: result = f(1., self.a, self.b) # default a is upper triangular expected = np.array([[13., 16., -5.], [5., 6., -2.]]) assert_array_almost_equal(result, expected)
def test_ab_lower(self): f = getattr(fblas, 'dtrmm', None) if f is not None: result = f(1., self.a, self.b, lower=True) expected = np.array([[3., 4., -1.], [-1., -2., 0.]]) # now a is lower triangular assert_array_almost_equal(result, expected)
def test_b_overwrites(self): # BLAS dtrmm modifies B argument in-place. # Here the default is to copy, but this can be overridden f = getattr(fblas, 'dtrmm', None) if f is not None: for overwr in [True, False]: bcopy = self.b.copy() result = f(1., self.a, bcopy, overwrite_b=overwr) # C-contiguous arrays are copied assert_(bcopy.flags.f_contiguous is False and np.may_share_memory(bcopy, result) is False) assert_equal(bcopy, self.b)
bcopy = np.asfortranarray(self.b.copy()) # or just transpose it result = f(1., self.a, bcopy, overwrite_b=True) assert_(bcopy.flags.f_contiguous is True and np.may_share_memory(bcopy, result) is True) assert_array_almost_equal(bcopy, result)
def test_trsm(): rng = np.random.default_rng(1234) for ind, dtype in enumerate(DTYPES): tol = np.finfo(dtype).eps*1000 func, = get_blas_funcs(('trsm',), dtype=dtype)
# Test protection against size mismatches A = rng.random((4, 5)).astype(dtype) B = rng.random((4, 4)).astype(dtype) alpha = dtype(1) assert_raises(Exception, func, alpha, A, B) assert_raises(Exception, func, alpha, A.T, B)
n = 8 m = 7 alpha = dtype(-2.5) if ind < 2: A = rng.random((m, m)) + eye(m) else: A = (rng.random((m, m)) + rng.random((m, m))*1j) + eye(m) A = A.astype(dtype) Au = triu(A) Al = tril(A) B1 = rng.random((m, n)).astype(dtype) B2 = rng.random((n, m)).astype(dtype)
x1 = func(alpha=alpha, a=A, b=B1) assert_equal(B1.shape, x1.shape) x2 = solve(Au, alpha*B1) assert_allclose(x1, x2, atol=tol)
x1 = func(alpha=alpha, a=A, b=B1, trans_a=1) x2 = solve(Au.T, alpha*B1) assert_allclose(x1, x2, atol=tol)
x1 = func(alpha=alpha, a=A, b=B1, trans_a=2) x2 = solve(Au.conj().T, alpha*B1) assert_allclose(x1, x2, atol=tol)
x1 = func(alpha=alpha, a=A, b=B1, diag=1) Au[arange(m), arange(m)] = dtype(1) x2 = solve(Au, alpha*B1) assert_allclose(x1, x2, atol=tol)
x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1) x2 = solve(Au.conj().T, alpha*B2.conj().T) assert_allclose(x1, x2.conj().T, atol=tol)
x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1, lower=1) Al[arange(m), arange(m)] = dtype(1) x2 = solve(Al.conj().T, alpha*B2.conj().T) assert_allclose(x1, x2.conj().T, atol=tol)
@pytest.mark.xfail(run=False, reason="gh-16930")def test_gh_169309(): x = np.repeat(10, 9) actual = scipy.linalg.blas.dnrm2(x, 5, 3, -1) expected = math.sqrt(500) assert_allclose(actual, expected)
def test_dnrm2_neg_incx(): # check that dnrm2(..., incx < 0) raises # XXX: remove the test after the lowest supported BLAS implements # negative incx (new in LAPACK 3.10) x = np.repeat(10, 9) incx = -1 with assert_raises(fblas.__fblas_error): scipy.linalg.blas.dnrm2(x, 5, 3, incx)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118import numpy as npfrom numpy.testing import (assert_allclose, assert_equal)import scipy.linalg.cython_blas as blas
class TestDGEMM: def test_transposes(self):
a = np.arange(12, dtype='d').reshape((3, 4))[:2,:2] b = np.arange(1, 13, dtype='d').reshape((4, 3))[:2,:2] c = np.empty((2, 4))[:2,:2]
blas._test_dgemm(1., a, b, 0., c) assert_allclose(c, a.dot(b))
blas._test_dgemm(1., a.T, b, 0., c) assert_allclose(c, a.T.dot(b))
blas._test_dgemm(1., a, b.T, 0., c) assert_allclose(c, a.dot(b.T))
blas._test_dgemm(1., a.T, b.T, 0., c) assert_allclose(c, a.T.dot(b.T))
blas._test_dgemm(1., a, b, 0., c.T) assert_allclose(c, a.dot(b).T)
blas._test_dgemm(1., a.T, b, 0., c.T) assert_allclose(c, a.T.dot(b).T)
blas._test_dgemm(1., a, b.T, 0., c.T) assert_allclose(c, a.dot(b.T).T)
blas._test_dgemm(1., a.T, b.T, 0., c.T) assert_allclose(c, a.T.dot(b.T).T) def test_shapes(self): a = np.arange(6, dtype='d').reshape((3, 2)) b = np.arange(-6, 2, dtype='d').reshape((2, 4)) c = np.empty((3, 4))
blas._test_dgemm(1., a, b, 0., c) assert_allclose(c, a.dot(b))
blas._test_dgemm(1., b.T, a.T, 0., c.T) assert_allclose(c, b.T.dot(a.T).T) class TestWfuncPointers: """ Test the function pointers that are expected to fail on Mac OS X without the additional entry statement in their definitions in fblas_l1.pyf.src. """
def test_complex_args(self):
cx = np.array([.5 + 1.j, .25 - .375j, 12.5 - 4.j], np.complex64) cy = np.array([.8 + 2.j, .875 - .625j, -1. + 2.j], np.complex64)
assert_allclose(blas._test_cdotc(cx, cy), -17.6468753815+21.3718757629j) assert_allclose(blas._test_cdotu(cx, cy), -6.11562538147+30.3156242371j)
assert_equal(blas._test_icamax(cx), 3)
assert_allclose(blas._test_scasum(cx), 18.625) assert_allclose(blas._test_scnrm2(cx), 13.1796483994)
assert_allclose(blas._test_cdotc(cx[::2], cy[::2]), -18.1000003815+21.2000007629j) assert_allclose(blas._test_cdotu(cx[::2], cy[::2]), -6.10000038147+30.7999992371j) assert_allclose(blas._test_scasum(cx[::2]), 18.) assert_allclose(blas._test_scnrm2(cx[::2]), 13.1719398499) def test_double_args(self):
x = np.array([5., -3, -.5], np.float64) y = np.array([2, 1, .5], np.float64)
assert_allclose(blas._test_dasum(x), 8.5) assert_allclose(blas._test_ddot(x, y), 6.75) assert_allclose(blas._test_dnrm2(x), 5.85234975815)
assert_allclose(blas._test_dasum(x[::2]), 5.5) assert_allclose(blas._test_ddot(x[::2], y[::2]), 9.75) assert_allclose(blas._test_dnrm2(x[::2]), 5.0249376297)
assert_equal(blas._test_idamax(x), 1)
def test_float_args(self):
x = np.array([5., -3, -.5], np.float32) y = np.array([2, 1, .5], np.float32)
assert_equal(blas._test_isamax(x), 1)
assert_allclose(blas._test_sasum(x), 8.5) assert_allclose(blas._test_sdot(x, y), 6.75) assert_allclose(blas._test_snrm2(x), 5.85234975815)
assert_allclose(blas._test_sasum(x[::2]), 5.5) assert_allclose(blas._test_sdot(x[::2], y[::2]), 9.75) assert_allclose(blas._test_snrm2(x[::2]), 5.0249376297)
def test_double_complex_args(self):
cx = np.array([.5 + 1.j, .25 - .375j, 13. - 4.j], np.complex128) cy = np.array([.875 + 2.j, .875 - .625j, -1. + 2.j], np.complex128)
assert_equal(blas._test_izamax(cx), 3)
assert_allclose(blas._test_zdotc(cx, cy), -18.109375+22.296875j) assert_allclose(blas._test_zdotu(cx, cy), -6.578125+31.390625j)
assert_allclose(blas._test_zdotc(cx[::2], cy[::2]), -18.5625+22.125j) assert_allclose(blas._test_zdotu(cx[::2], cy[::2]), -6.5625+31.875j)
12345678910111213141516171819202122from numpy.testing import assert_allclosefrom scipy.linalg import cython_lapack as cython_lapackfrom scipy.linalg import lapack
class TestLamch:
def test_slamch(self): for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']: assert_allclose(cython_lapack._test_slamch(c), lapack.slamch(c))
def test_dlamch(self): for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']: assert_allclose(cython_lapack._test_dlamch(c), lapack.dlamch(c))
def test_complex_ladiv(self): cx = .5 + 1.j cy = .875 + 2.j assert_allclose(cython_lapack._test_zladiv(cy, cx), 1.95+0.1j) assert_allclose(cython_lapack._test_cladiv(cy, cx), 1.95+0.1j)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import numpy as npfrom scipy.linalg import bandwidth, issymmetric, ishermitianimport pytestfrom pytest import raises
def test_bandwidth_dtypes(): n = 5 for t in np.typecodes['All']: A = np.zeros([n, n], dtype=t) if t in 'eUVOMm': raises(TypeError, bandwidth, A) elif t == 'G': # No-op test. On win these pass on others fail. pass else: _ = bandwidth(A)
def test_bandwidth_non2d_input(): A = np.array([1, 2, 3]) raises(ValueError, bandwidth, A) A = np.array([[[1, 2, 3], [4, 5, 6]]]) raises(ValueError, bandwidth, A)
@pytest.mark.parametrize('T', [x for x in np.typecodes['All'] if x not in 'eGUVOMm'])def test_bandwidth_square_inputs(T): n = 20 k = 4 R = np.zeros([n, n], dtype=T, order='F') # form a banded matrix inplace R[[x for x in range(n)], [x for x in range(n)]] = 1 R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1 R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1 R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1 assert bandwidth(R) == (k, k) A = np.array([ [1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], ]) assert bandwidth(A) == (2, 2)
@pytest.mark.parametrize('T', [x for x in np.typecodes['All'] if x not in 'eGUVOMm'])def test_bandwidth_rect_inputs(T): n, m = 10, 20 k = 5 R = np.zeros([n, m], dtype=T, order='F') # form a banded matrix inplace R[[x for x in range(n)], [x for x in range(n)]] = 1 R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1 R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1 R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1 assert bandwidth(R) == (k, k)
def test_issymetric_ishermitian_dtypes(): n = 5 for t in np.typecodes['All']: A = np.zeros([n, n], dtype=t) if t in 'eUVOMm': raises(TypeError, issymmetric, A) raises(TypeError, ishermitian, A) elif t == 'G': # No-op test. On win these pass on others fail. pass else: assert issymmetric(A) assert ishermitian(A)
def test_issymmetric_ishermitian_invalid_input(): A = np.array([1, 2, 3]) raises(ValueError, issymmetric, A) raises(ValueError, ishermitian, A) A = np.array([[[1, 2, 3], [4, 5, 6]]]) raises(ValueError, issymmetric, A) raises(ValueError, ishermitian, A) A = np.array([[1, 2, 3], [4, 5, 6]]) raises(ValueError, issymmetric, A) raises(ValueError, ishermitian, A)
def test_issymetric_complex_decimals(): A = np.arange(1, 10).astype(complex).reshape(3, 3) A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j # make entries decimal A /= np.pi A = A + A.T assert issymmetric(A)
def test_ishermitian_complex_decimals(): A = np.arange(1, 10).astype(complex).reshape(3, 3) A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j # make entries decimal A /= np.pi A = A + A.T.conj() assert ishermitian(A)
def test_issymmetric_approximate_results(): n = 20 rng = np.random.RandomState(123456789) x = rng.uniform(high=5., size=[n, n]) y = x @ x.T # symmetric p = rng.standard_normal([n, n]) z = p @ y @ p.T assert issymmetric(z, atol=1e-10) assert issymmetric(z, atol=1e-10, rtol=0.) assert issymmetric(z, atol=0., rtol=1e-12) assert issymmetric(z, atol=1e-13, rtol=1e-12)
def test_ishermitian_approximate_results(): n = 20 rng = np.random.RandomState(987654321) x = rng.uniform(high=5., size=[n, n]) y = x @ x.T # symmetric p = rng.standard_normal([n, n]) + rng.standard_normal([n, n])*1j z = p @ y @ p.conj().T assert ishermitian(z, atol=1e-10) assert ishermitian(z, atol=1e-10, rtol=0.) assert ishermitian(z, atol=0., rtol=1e-12) assert ishermitian(z, atol=1e-13, rtol=1e-12)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268import pytestimport numpy as npfrom numpy.testing import assert_array_almost_equalfrom pytest import raises as assert_raises
from numpy import array, transpose, dot, conjugate, zeros_like, emptyfrom numpy.random import randomfrom scipy.linalg import (cholesky, cholesky_banded, cho_solve_banded, cho_factor, cho_solve)
from scipy.linalg._testutils import assert_no_overwrite
class TestCholesky:
def test_simple(self): a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]] c = cholesky(a) assert_array_almost_equal(dot(transpose(c), c), a) c = transpose(c) a = dot(c, transpose(c)) assert_array_almost_equal(cholesky(a, lower=1), c)
def test_check_finite(self): a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]] c = cholesky(a, check_finite=False) assert_array_almost_equal(dot(transpose(c), c), a) c = transpose(c) a = dot(c, transpose(c)) assert_array_almost_equal(cholesky(a, lower=1, check_finite=False), c)
def test_simple_complex(self): m = array([[3+1j, 3+4j, 5], [0, 2+2j, 2+7j], [0, 0, 7+4j]]) a = dot(transpose(conjugate(m)), m) c = cholesky(a) a1 = dot(transpose(conjugate(c)), c) assert_array_almost_equal(a, a1) c = transpose(c) a = dot(c, transpose(conjugate(c))) assert_array_almost_equal(cholesky(a, lower=1), c)
def test_random(self): n = 20 for k in range(2): m = random([n, n]) for i in range(n): m[i, i] = 20*(.1+m[i, i]) a = dot(transpose(m), m) c = cholesky(a) a1 = dot(transpose(c), c) assert_array_almost_equal(a, a1) c = transpose(c) a = dot(c, transpose(c)) assert_array_almost_equal(cholesky(a, lower=1), c)
def test_random_complex(self): n = 20 for k in range(2): m = random([n, n])+1j*random([n, n]) for i in range(n): m[i, i] = 20*(.1+abs(m[i, i])) a = dot(transpose(conjugate(m)), m) c = cholesky(a) a1 = dot(transpose(conjugate(c)), c) assert_array_almost_equal(a, a1) c = transpose(c) a = dot(c, transpose(conjugate(c))) assert_array_almost_equal(cholesky(a, lower=1), c)
@pytest.mark.xslow def test_int_overflow(self): # regression test for # https://github.com/scipy/scipy/issues/17436 # the problem was an int overflow in zeroing out # the unused triangular part n = 47_000 x = np.eye(n, dtype=np.float64, order='F') x[:4, :4] = np.array([[4, -2, 3, -1], [-2, 4, -3, 1], [3, -3, 5, 0], [-1, 1, 0, 5]])
cholesky(x, check_finite=False, overwrite_a=True) # should not segfault
@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt, dt_b): a = empty((0, 0), dtype=dt)
c = cholesky(a) assert c.shape == (0, 0) assert c.dtype == cholesky(np.eye(2, dtype=dt)).dtype
c_and_lower = (c, True) b = np.asarray([], dtype=dt_b) x = cho_solve(c_and_lower, b) assert x.shape == (0,) assert x.dtype == cho_solve((np.eye(2, dtype=dt), True), np.ones(2, dtype=dt_b)).dtype
b = empty((0, 0), dtype=dt_b) x = cho_solve(c_and_lower, b) assert x.shape == (0, 0) assert x.dtype == cho_solve((np.eye(2, dtype=dt), True), np.ones(2, dtype=dt_b)).dtype
a1 = array([]) a2 = array([[]]) a3 = [] a4 = [[]] for x in ([a1, a2, a3, a4]): assert_raises(ValueError, cholesky, x)
class TestCholeskyBanded: """Tests for cholesky_banded() and cho_solve_banded."""
def test_check_finite(self): # Symmetric positive definite banded matrix `a` a = array([[4.0, 1.0, 0.0, 0.0], [1.0, 4.0, 0.5, 0.0], [0.0, 0.5, 4.0, 0.2], [0.0, 0.0, 0.2, 4.0]]) # Banded storage form of `a`. ab = array([[-1.0, 1.0, 0.5, 0.2], [4.0, 4.0, 4.0, 4.0]]) c = cholesky_banded(ab, lower=False, check_finite=False) ufac = zeros_like(a) ufac[list(range(4)), list(range(4))] = c[-1] ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:] assert_array_almost_equal(a, dot(ufac.T, ufac))
b = array([0.0, 0.5, 4.2, 4.2]) x = cho_solve_banded((c, False), b, check_finite=False) assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
def test_upper_real(self): # Symmetric positive definite banded matrix `a` a = array([[4.0, 1.0, 0.0, 0.0], [1.0, 4.0, 0.5, 0.0], [0.0, 0.5, 4.0, 0.2], [0.0, 0.0, 0.2, 4.0]]) # Banded storage form of `a`. ab = array([[-1.0, 1.0, 0.5, 0.2], [4.0, 4.0, 4.0, 4.0]]) c = cholesky_banded(ab, lower=False) ufac = zeros_like(a) ufac[list(range(4)), list(range(4))] = c[-1] ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:] assert_array_almost_equal(a, dot(ufac.T, ufac))
b = array([0.0, 0.5, 4.2, 4.2]) x = cho_solve_banded((c, False), b) assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
def test_upper_complex(self): # Hermitian positive definite banded matrix `a` a = array([[4.0, 1.0, 0.0, 0.0], [1.0, 4.0, 0.5, 0.0], [0.0, 0.5, 4.0, -0.2j], [0.0, 0.0, 0.2j, 4.0]]) # Banded storage form of `a`. ab = array([[-1.0, 1.0, 0.5, -0.2j], [4.0, 4.0, 4.0, 4.0]]) c = cholesky_banded(ab, lower=False) ufac = zeros_like(a) ufac[list(range(4)), list(range(4))] = c[-1] ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:] assert_array_almost_equal(a, dot(ufac.conj().T, ufac))
b = array([0.0, 0.5, 4.0-0.2j, 0.2j + 4.0]) x = cho_solve_banded((c, False), b) assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
def test_lower_real(self): # Symmetric positive definite banded matrix `a` a = array([[4.0, 1.0, 0.0, 0.0], [1.0, 4.0, 0.5, 0.0], [0.0, 0.5, 4.0, 0.2], [0.0, 0.0, 0.2, 4.0]]) # Banded storage form of `a`. ab = array([[4.0, 4.0, 4.0, 4.0], [1.0, 0.5, 0.2, -1.0]]) c = cholesky_banded(ab, lower=True) lfac = zeros_like(a) lfac[list(range(4)), list(range(4))] = c[0] lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3] assert_array_almost_equal(a, dot(lfac, lfac.T))
b = array([0.0, 0.5, 4.2, 4.2]) x = cho_solve_banded((c, True), b) assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
def test_lower_complex(self): # Hermitian positive definite banded matrix `a` a = array([[4.0, 1.0, 0.0, 0.0], [1.0, 4.0, 0.5, 0.0], [0.0, 0.5, 4.0, -0.2j], [0.0, 0.0, 0.2j, 4.0]]) # Banded storage form of `a`. ab = array([[4.0, 4.0, 4.0, 4.0], [1.0, 0.5, 0.2j, -1.0]]) c = cholesky_banded(ab, lower=True) lfac = zeros_like(a) lfac[list(range(4)), list(range(4))] = c[0] lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3] assert_array_almost_equal(a, dot(lfac, lfac.conj().T))
b = array([0.0, 0.5j, 3.8j, 3.8]) x = cho_solve_banded((c, True), b) assert_array_almost_equal(x, [0.0, 0.0, 1.0j, 1.0])
@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt, dt_b): ab = empty((0, 0), dtype=dt)
cb = cholesky_banded(ab) assert cb.shape == (0, 0)
m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=dt)) assert cb.dtype == m.dtype
cb_and_lower = (cb, True) b = np.asarray([], dtype=dt_b) x = cho_solve_banded(cb_and_lower, b) assert x.shape == (0,)
dtype_nonempty = cho_solve_banded((m, True), np.ones(2, dtype=dt_b)).dtype assert x.dtype == dtype_nonempty
b = empty((0, 0), dtype=dt_b) x = cho_solve_banded(cb_and_lower, b) assert x.shape == (0, 0) assert x.dtype == dtype_nonempty
class TestOverwrite: def test_cholesky(self): assert_no_overwrite(cholesky, [(3, 3)])
def test_cho_factor(self): assert_no_overwrite(cho_factor, [(3, 3)])
def test_cho_solve(self): x = array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]]) xcho = cho_factor(x) assert_no_overwrite(lambda b: cho_solve(xcho, b), [(3,)])
def test_cholesky_banded(self): assert_no_overwrite(cholesky_banded, [(2, 3)])
def test_cho_solve_banded(self): x = array([[0, -1, -1], [2, 2, 2]]) xcho = cholesky_banded(x) assert_no_overwrite(lambda b: cho_solve_banded((xcho, False), b), [(3,)])
class TestChoFactor: @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt): a = np.empty((0, 0), dtype=dt) x, lower = cho_factor(a)
assert x.shape == (0, 0)
xx, lower = cho_factor(np.eye(2, dtype=dt)) assert x.dtype == xx.dtype123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300import pytestimport numpy as npfrom numpy.random import default_rngfrom numpy.testing import assert_allclose
from scipy import linalgfrom scipy.linalg.lapack import _compute_lworkfrom scipy.stats import ortho_group, unitary_groupfrom scipy.linalg import cossin, get_lapack_funcs
REAL_DTYPES = (np.float32, np.float64)COMPLEX_DTYPES = (np.complex64, np.complex128)DTYPES = REAL_DTYPES + COMPLEX_DTYPES
@pytest.mark.parametrize('dtype_', DTYPES)@pytest.mark.parametrize('m, p, q', [ (2, 1, 1), (3, 2, 1), (3, 1, 2), (4, 2, 2), (4, 1, 2), (40, 12, 20), (40, 30, 1), (40, 1, 30), (100, 50, 1), (100, 50, 50), ])@pytest.mark.parametrize('swap_sign', [True, False])def test_cossin(dtype_, m, p, q, swap_sign): rng = default_rng(1708093570726217) if dtype_ in COMPLEX_DTYPES: x = np.array(unitary_group.rvs(m, random_state=rng), dtype=dtype_) else: x = np.array(ortho_group.rvs(m, random_state=rng), dtype=dtype_)
u, cs, vh = cossin(x, p, q, swap_sign=swap_sign) assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps) assert u.dtype == dtype_ # Test for float32 or float 64 assert cs.dtype == np.real(u).dtype assert vh.dtype == dtype_
u, cs, vh = cossin([x[:p, :q], x[:p, q:], x[p:, :q], x[p:, q:]], swap_sign=swap_sign) assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps) assert u.dtype == dtype_ assert cs.dtype == np.real(u).dtype assert vh.dtype == dtype_
_, cs2, vh2 = cossin(x, p, q, compute_u=False, swap_sign=swap_sign) assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps) assert_allclose(vh, vh2, rtol=0., atol=10*np.finfo(dtype_).eps)
u2, cs2, _ = cossin(x, p, q, compute_vh=False, swap_sign=swap_sign) assert_allclose(u, u2, rtol=0., atol=10*np.finfo(dtype_).eps) assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
_, cs2, _ = cossin(x, p, q, compute_u=False, compute_vh=False, swap_sign=swap_sign) assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
def test_cossin_mixed_types(): rng = default_rng(1708093736390459) x = np.array(ortho_group.rvs(4, random_state=rng), dtype=np.float64) u, cs, vh = cossin([x[:2, :2], np.array(x[:2, 2:], dtype=np.complex128), x[2:, :2], x[2:, 2:]])
assert u.dtype == np.complex128 assert cs.dtype == np.float64 assert vh.dtype == np.complex128 assert_allclose(x, u @ cs @ vh, rtol=0., atol=1e4 * np.finfo(np.complex128).eps)
def test_cossin_error_incorrect_subblocks(): with pytest.raises(ValueError, match="be due to missing p, q arguments."): cossin(([1, 2], [3, 4, 5], [6, 7], [8, 9, 10]))
def test_cossin_error_empty_subblocks(): with pytest.raises(ValueError, match="x11.*empty"): cossin(([], [], [], [])) with pytest.raises(ValueError, match="x12.*empty"): cossin(([1, 2], [], [6, 7], [8, 9, 10])) with pytest.raises(ValueError, match="x21.*empty"): cossin(([1, 2], [3, 4, 5], [], [8, 9, 10])) with pytest.raises(ValueError, match="x22.*empty"): cossin(([1, 2], [3, 4, 5], [2], []))
def test_cossin_error_missing_partitioning(): with pytest.raises(ValueError, match=".*exactly four arrays.* got 2"): cossin(unitary_group.rvs(2))
with pytest.raises(ValueError, match=".*might be due to missing p, q"): cossin(unitary_group.rvs(4))
def test_cossin_error_non_iterable(): with pytest.raises(ValueError, match="containing the subblocks of X"): cossin(12j)
def test_cossin_error_non_square(): with pytest.raises(ValueError, match="only supports square"): cossin(np.array([[1, 2]]), 1, 1)
def test_cossin_error_partitioning(): x = np.array(ortho_group.rvs(4), dtype=np.float64) with pytest.raises(ValueError, match="invalid p=0.*0<p<4.*"): cossin(x, 0, 1) with pytest.raises(ValueError, match="invalid p=4.*0<p<4.*"): cossin(x, 4, 1) with pytest.raises(ValueError, match="invalid q=-2.*0<q<4.*"): cossin(x, 1, -2) with pytest.raises(ValueError, match="invalid q=5.*0<q<4.*"): cossin(x, 1, 5)
@pytest.mark.parametrize("dtype_", DTYPES)def test_cossin_separate(dtype_): rng = default_rng(1708093590167096) m, p, q = 98, 37, 61
pfx = 'or' if dtype_ in REAL_DTYPES else 'un' X = (ortho_group.rvs(m, random_state=rng) if pfx == 'or' else unitary_group.rvs(m, random_state=rng)) X = np.array(X, dtype=dtype_)
drv, dlw = get_lapack_funcs((pfx + 'csd', pfx + 'csd_lwork'), [X]) lwval = _compute_lwork(dlw, m, p, q) lwvals = {'lwork': lwval} if pfx == 'or' else dict(zip(['lwork', 'lrwork'], lwval))
*_, theta, u1, u2, v1t, v2t, _ = \ drv(X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:], **lwvals)
(u1_2, u2_2), theta2, (v1t_2, v2t_2) = cossin(X, p, q, separate=True)
assert_allclose(u1_2, u1, rtol=0., atol=10*np.finfo(dtype_).eps) assert_allclose(u2_2, u2, rtol=0., atol=10*np.finfo(dtype_).eps) assert_allclose(v1t_2, v1t, rtol=0., atol=10*np.finfo(dtype_).eps) assert_allclose(v2t_2, v2t, rtol=0., atol=10*np.finfo(dtype_).eps) assert_allclose(theta2, theta, rtol=0., atol=10*np.finfo(dtype_).eps)
@pytest.mark.parametrize("m", [2, 5, 10, 15, 20])@pytest.mark.parametrize("p", [1, 4, 9, 14, 19])@pytest.mark.parametrize("q", [1, 4, 9, 14, 19])@pytest.mark.parametrize("swap_sign", [True, False])def test_properties(m, p, q, swap_sign): # Test all the properties advertised in `linalg.cossin` documentation. # There may be some overlap with tests above, but this is sensitive to # the bug reported in gh-19365 and more. if (p >= m) or (q >= m): pytest.skip("`0 < p < m` and `0 < q < m` must hold")
# Generate unitary input rng = np.random.default_rng(329548272348596421) X = unitary_group.rvs(m, random_state=rng) np.testing.assert_allclose(X @ X.conj().T, np.eye(m), atol=1e-15)
# Perform the decomposition u0, cs0, vh0 = linalg.cossin(X, p=p, q=q, separate=True, swap_sign=swap_sign) u1, u2 = u0 v1, v2 = vh0 v1, v2 = v1.conj().T, v2.conj().T
# "U1, U2, V1, V2 are square orthogonal/unitary matrices # of dimensions (p,p), (m-p,m-p), (q,q), and (m-q,m-q) respectively" np.testing.assert_allclose(u1 @ u1.conj().T, np.eye(p), atol=1e-13) np.testing.assert_allclose(u2 @ u2.conj().T, np.eye(m-p), atol=1e-13) np.testing.assert_allclose(v1 @ v1.conj().T, np.eye(q), atol=1e-13) np.testing.assert_allclose(v2 @ v2.conj().T, np.eye(m-q), atol=1e-13)
# "and C and S are (r, r) nonnegative diagonal matrices..." C = np.diag(np.cos(cs0)) S = np.diag(np.sin(cs0)) # "...satisfying C^2 + S^2 = I where r = min(p, m-p, q, m-q)." r = min(p, m-p, q, m-q) np.testing.assert_allclose(C**2 + S**2, np.eye(r))
# "Moreover, the rank of the identity matrices are # min(p, q) - r, min(p, m - q) - r, min(m - p, q) - r, # and min(m - p, m - q) - r respectively." I11 = np.eye(min(p, q) - r) I12 = np.eye(min(p, m - q) - r) I21 = np.eye(min(m - p, q) - r) I22 = np.eye(min(m - p, m - q) - r)
# From: # ┌ ┐ # │ I 0 0 │ 0 0 0 │ # ┌ ┐ ┌ ┐│ 0 C 0 │ 0 -S 0 │┌ ┐* # │ X11 │ X12 │ │ U1 │ ││ 0 0 0 │ 0 0 -I ││ V1 │ │ # │ ────┼──── │ = │────┼────││─────────┼─────────││────┼────│ # │ X21 │ X22 │ │ │ U2 ││ 0 0 0 │ I 0 0 ││ │ V2 │ # └ ┘ └ ┘│ 0 S 0 │ 0 C 0 │└ ┘ # │ 0 0 I │ 0 0 0 │ # └ ┘
# We can see that U and V are block diagonal matrices like so: U = linalg.block_diag(u1, u2) V = linalg.block_diag(v1, v2)
# And the center matrix, which we'll call Q here, must be: Q11 = np.zeros((u1.shape[1], v1.shape[0])) IC11 = linalg.block_diag(I11, C) Q11[:IC11.shape[0], :IC11.shape[1]] = IC11
Q12 = np.zeros((u1.shape[1], v2.shape[0])) SI12 = linalg.block_diag(S, I12) if swap_sign else linalg.block_diag(-S, -I12) Q12[-SI12.shape[0]:, -SI12.shape[1]:] = SI12
Q21 = np.zeros((u2.shape[1], v1.shape[0])) SI21 = linalg.block_diag(-S, -I21) if swap_sign else linalg.block_diag(S, I21) Q21[-SI21.shape[0]:, -SI21.shape[1]:] = SI21
Q22 = np.zeros((u2.shape[1], v2.shape[0])) IC22 = linalg.block_diag(I22, C) Q22[:IC22.shape[0], :IC22.shape[1]] = IC22
Q = np.block([[Q11, Q12], [Q21, Q22]])
# Confirm that `cossin` decomposes `X` as shown np.testing.assert_allclose(X, U @ Q @ V.conj().T)
# And check that `separate=False` agrees U0, CS0, Vh0 = linalg.cossin(X, p=p, q=q, swap_sign=swap_sign) np.testing.assert_allclose(U, U0) np.testing.assert_allclose(Q, CS0) np.testing.assert_allclose(V, Vh0.conj().T)
# Confirm that `compute_u`/`compute_vh` don't affect the results kwargs = dict(p=p, q=q, swap_sign=swap_sign)
# `compute_u=False` u, cs, vh = linalg.cossin(X, separate=True, compute_u=False, **kwargs) assert u[0].shape == (0, 0) # probably not ideal, but this is what it does assert u[1].shape == (0, 0) assert_allclose(cs, cs0, rtol=1e-15) assert_allclose(vh[0], vh0[0], rtol=1e-15) assert_allclose(vh[1], vh0[1], rtol=1e-15)
U, CS, Vh = linalg.cossin(X, compute_u=False, **kwargs) assert U.shape == (0, 0) assert_allclose(CS, CS0, rtol=1e-15) assert_allclose(Vh, Vh0, rtol=1e-15)
# `compute_vh=False` u, cs, vh = linalg.cossin(X, separate=True, compute_vh=False, **kwargs) assert_allclose(u[0], u[0], rtol=1e-15) assert_allclose(u[1], u[1], rtol=1e-15) assert_allclose(cs, cs0, rtol=1e-15) assert vh[0].shape == (0, 0) assert vh[1].shape == (0, 0)
U, CS, Vh = linalg.cossin(X, compute_vh=False, **kwargs) assert_allclose(U, U0, rtol=1e-15) assert_allclose(CS, CS0, rtol=1e-15) assert Vh.shape == (0, 0)
# `compute_u=False, compute_vh=False` u, cs, vh = linalg.cossin(X, separate=True, compute_u=False, compute_vh=False, **kwargs) assert u[0].shape == (0, 0) assert u[1].shape == (0, 0) assert_allclose(cs, cs0, rtol=1e-15) assert vh[0].shape == (0, 0) assert vh[1].shape == (0, 0)
U, CS, Vh = linalg.cossin(X, compute_u=False, compute_vh=False, **kwargs) assert U.shape == (0, 0) assert_allclose(CS, CS0, rtol=1e-15) assert Vh.shape == (0, 0)
def test_indexing_bug_gh19365(): # Regression test for gh-19365, which reported a bug with `separate=False` rng = np.random.default_rng(32954827234421) m = rng.integers(50, high=100) p = rng.integers(10, 40) # always p < m q = rng.integers(m - p + 1, m - 1) # always m-p < q < m X = unitary_group.rvs(m, random_state=rng) # random unitary matrix U, D, Vt = linalg.cossin(X, p=p, q=q, separate=False) assert np.allclose(U @ D @ Vt, X)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137from numpy.testing import assert_array_almost_equal, assert_allclose, assert_from numpy import (array, eye, zeros, empty_like, empty, tril_indices_from, tril, triu_indices_from, spacing, float32, float64, complex64, complex128)from numpy.random import rand, randint, seedfrom scipy.linalg import ldlfrom scipy._lib._util import ComplexWarningimport pytestfrom pytest import raises as assert_raises, warns
@pytest.mark.thread_unsafedef test_args(): A = eye(3) # Nonsquare array assert_raises(ValueError, ldl, A[:, :2]) # Complex matrix with imaginary diagonal entries with "hermitian=True" with warns(ComplexWarning): ldl(A*1j)
def test_empty_array(): a = empty((0, 0), dtype=complex) l, d, p = ldl(empty((0, 0))) assert_array_almost_equal(l, empty_like(a)) assert_array_almost_equal(d, empty_like(a)) assert_array_almost_equal(p, array([], dtype=int))
def test_simple(): a = array([[-0.39-0.71j, 5.14-0.64j, -7.86-2.96j, 3.80+0.92j], [5.14-0.64j, 8.86+1.81j, -3.52+0.58j, 5.32-1.59j], [-7.86-2.96j, -3.52+0.58j, -2.83-0.03j, -1.54-2.86j], [3.80+0.92j, 5.32-1.59j, -1.54-2.86j, -0.56+0.12j]]) b = array([[5., 10, 1, 18], [10., 2, 11, 1], [1., 11, 19, 9], [18., 1, 9, 0]]) c = array([[52., 97, 112, 107, 50], [97., 114, 89, 98, 13], [112., 89, 64, 33, 6], [107., 98, 33, 60, 73], [50., 13, 6, 73, 77]])
d = array([[2., 2, -4, 0, 4], [2., -2, -2, 10, -8], [-4., -2, 6, -8, -4], [0., 10, -8, 6, -6], [4., -8, -4, -6, 10]]) e = array([[-1.36+0.00j, 0+0j, 0+0j, 0+0j], [1.58-0.90j, -8.87+0j, 0+0j, 0+0j], [2.21+0.21j, -1.84+0.03j, -4.63+0j, 0+0j], [3.91-1.50j, -1.78-1.18j, 0.11-0.11j, -1.84+0.00j]]) for x in (b, c, d): l, d, p = ldl(x) assert_allclose(l.dot(d).dot(l.T), x, atol=spacing(1000.), rtol=0)
u, d, p = ldl(x, lower=False) assert_allclose(u.dot(d).dot(u.T), x, atol=spacing(1000.), rtol=0)
l, d, p = ldl(a, hermitian=False) assert_allclose(l.dot(d).dot(l.T), a, atol=spacing(1000.), rtol=0)
u, d, p = ldl(a, lower=False, hermitian=False) assert_allclose(u.dot(d).dot(u.T), a, atol=spacing(1000.), rtol=0)
# Use upper part for the computation and use the lower part for comparison l, d, p = ldl(e.conj().T, lower=0) assert_allclose(tril(l.dot(d).dot(l.conj().T)-e), zeros((4, 4)), atol=spacing(1000.), rtol=0)
def test_permutations(): seed(1234) for _ in range(10): n = randint(1, 100) # Random real/complex array x = rand(n, n) if randint(2) else rand(n, n) + rand(n, n)*1j x = x + x.conj().T x += eye(n)*randint(5, 1e6) l_ind = tril_indices_from(x, k=-1) u_ind = triu_indices_from(x, k=1)
# Test whether permutations lead to a triangular array u, d, p = ldl(x, lower=0) # lower part should be zero assert_(not any(u[p, :][l_ind]), f'Spin {_} failed')
l, d, p = ldl(x, lower=1) # upper part should be zero assert_(not any(l[p, :][u_ind]), f'Spin {_} failed')
@pytest.mark.parametrize("dtype", [float32, float64])@pytest.mark.parametrize("n", [30, 150])def test_ldl_type_size_combinations_real(n, dtype): seed(1234) msg = (f"Failed for size: {n}, dtype: {dtype}")
x = rand(n, n).astype(dtype) x = x + x.T x += eye(n, dtype=dtype)*dtype(randint(5, 1e6))
l, d1, p = ldl(x) u, d2, p = ldl(x, lower=0) rtol = 1e-4 if dtype is float32 else 1e-10 assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg) assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg)
@pytest.mark.parametrize("dtype", [complex64, complex128])@pytest.mark.parametrize("n", [30, 150])def test_ldl_type_size_combinations_complex(n, dtype): seed(1234) msg1 = (f"Her failed for size: {n}, dtype: {dtype}") msg2 = (f"Sym failed for size: {n}, dtype: {dtype}")
# Complex hermitian upper/lower x = (rand(n, n)+1j*rand(n, n)).astype(dtype) x = x+x.conj().T x += eye(n, dtype=dtype)*dtype(randint(5, 1e6))
l, d1, p = ldl(x) u, d2, p = ldl(x, lower=0) rtol = 2e-4 if dtype is complex64 else 1e-10 assert_allclose(l.dot(d1).dot(l.conj().T), x, rtol=rtol, err_msg=msg1) assert_allclose(u.dot(d2).dot(u.conj().T), x, rtol=rtol, err_msg=msg1)
# Complex symmetric upper/lower x = (rand(n, n)+1j*rand(n, n)).astype(dtype) x = x+x.T x += eye(n, dtype=dtype)*dtype(randint(5, 1e6))
l, d1, p = ldl(x, hermitian=0) u, d2, p = ldl(x, lower=0, hermitian=0) assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg2) assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308import pytestfrom pytest import raises as assert_raises
import numpy as npfrom scipy.linalg import lu, lu_factor, lu_solve, get_lapack_funcs, solvefrom numpy.testing import assert_allclose, assert_array_equal, assert_equal
REAL_DTYPES = [np.float32, np.float64]COMPLEX_DTYPES = [np.complex64, np.complex128]DTYPES = REAL_DTYPES + COMPLEX_DTYPES
class TestLU: def setup_method(self): self.rng = np.random.default_rng(1682281250228846)
def test_old_lu_smoke_tests(self): "Tests from old fortran based lu test suite" a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]]) p, l, u = lu(a) result_lu = np.array([[2., 5., 6.], [0.5, -0.5, 0.], [0.5, 1., 0.]]) assert_allclose(p, np.rot90(np.eye(3))) assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3)) assert_allclose(u, np.triu(result_lu))
a = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]]) p, l, u = lu(a) result_lu = np.array([[2., 5.j, 6.], [0.5, 2-2.5j, 0.], [0.5, 1., 0.]]) assert_allclose(p, np.rot90(np.eye(3))) assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3)) assert_allclose(u, np.triu(result_lu))
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) p, l, u = lu(b) assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]])) assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]]), rtol=0., atol=1e-14)
cb = np.array([[1.j, 2.j, 3.j], [4j, 5j, 6j], [7j, 8j, 9j]]) p, l, u = lu(cb) assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]])) assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]])*1j, rtol=0., atol=1e-14)
# Rectangular matrices hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]]) p, l, u = lu(hrect) assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]])) assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9, 15/9, 24/9], [0, 0, -0.5, 0]]), rtol=0., atol=1e-14)
chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])*1.j p, l, u = lu(chrect) assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]])) assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9, 15/9, 24/9], [0, 0, -0.5, 0]])*1j, rtol=0., atol=1e-14)
vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]]) p, l, u = lu(vrect) assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :]) assert_allclose(l, np.array([[1., 0, 0], [0.1, 1, 0], [0.7, -0.5, 1], [0.4, 0.25, 0.5]])) assert_allclose(u, np.array([[10, 12, 12], [0, 0.8, 1.8], [0, 0, 1.5]]))
cvrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])*1j p, l, u = lu(cvrect) assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :]) assert_allclose(l, np.array([[1., 0, 0], [0.1, 1, 0], [0.7, -0.5, 1], [0.4, 0.25, 0.5]])) assert_allclose(u, np.array([[10, 12, 12], [0, 0.8, 1.8], [0, 0, 1.5]])*1j)
@pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20], [20, 4], [4, 20], [3, 2, 9, 9], [2, 2, 17, 5], [2, 2, 11, 7]]) def test_simple_lu_shapes_real_complex(self, shape): a = self.rng.uniform(-10., 10., size=shape) p, l, u = lu(a) assert_allclose(a, p @ l @ u) pl, u = lu(a, permute_l=True) assert_allclose(a, pl @ u)
b = self.rng.uniform(-10., 10., size=shape)*1j b += self.rng.uniform(-10, 10, size=shape) pl, u = lu(b, permute_l=True) assert_allclose(b, pl @ u)
@pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20], [20, 4], [4, 20]]) def test_simple_lu_shapes_real_complex_2d_indices(self, shape): a = self.rng.uniform(-10., 10., size=shape) p, l, u = lu(a, p_indices=True) assert_allclose(a, l[p, :] @ u)
def test_1by1_input_output(self): a = self.rng.random([4, 5, 1, 1], dtype=np.float32) p, l, u = lu(a, p_indices=True) assert_allclose(p, np.zeros(shape=(4, 5, 1), dtype=int)) assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) assert_allclose(u, a)
a = self.rng.random([4, 5, 1, 1], dtype=np.float32) p, l, u = lu(a) assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) assert_allclose(u, a)
pl, u = lu(a, permute_l=True) assert_allclose(pl, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) assert_allclose(u, a)
a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j) p, l, u = lu(a) assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64)) assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64)) assert_allclose(u, a)
def test_empty_edge_cases(self): a = np.empty([0, 0]) p, l, u = lu(a) assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float64)) assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float64)) assert_allclose(u, np.empty(shape=(0, 0), dtype=np.float64))
a = np.empty([0, 3], dtype=np.float16) p, l, u = lu(a) assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32)) assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float32)) assert_allclose(u, np.empty(shape=(0, 3), dtype=np.float32))
a = np.empty([3, 0], dtype=np.complex64) p, l, u = lu(a) assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32)) assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64)) assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64)) p, l, u = lu(a, p_indices=True) assert_allclose(p, np.empty(shape=(0,), dtype=int)) assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64)) assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64)) pl, u = lu(a, permute_l=True) assert_allclose(pl, np.empty(shape=(3, 0), dtype=np.complex64)) assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
a = np.empty([3, 0, 0], dtype=np.complex64) p, l, u = lu(a) assert_allclose(p, np.empty(shape=(3, 0, 0), dtype=np.float32)) assert_allclose(l, np.empty(shape=(3, 0, 0), dtype=np.complex64)) assert_allclose(u, np.empty(shape=(3, 0, 0), dtype=np.complex64))
a = np.empty([0, 0, 3]) p, l, u = lu(a) assert_allclose(p, np.empty(shape=(0, 0, 0))) assert_allclose(l, np.empty(shape=(0, 0, 0))) assert_allclose(u, np.empty(shape=(0, 0, 3)))
with assert_raises(ValueError, match='at least two-dimensional'): lu(np.array([]))
a = np.array([[]]) p, l, u = lu(a) assert_allclose(p, np.empty(shape=(0, 0))) assert_allclose(l, np.empty(shape=(1, 0))) assert_allclose(u, np.empty(shape=(0, 0)))
a = np.array([[[]]]) p, l, u = lu(a) assert_allclose(p, np.empty(shape=(1, 0, 0))) assert_allclose(l, np.empty(shape=(1, 1, 0))) assert_allclose(u, np.empty(shape=(1, 0, 0)))
class TestLUFactor: def setup_method(self): self.rng = np.random.default_rng(1682281250228846)
self.a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]]) self.ca = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]]) # Those matrices are more robust to detect problems in permutation # matrices than the ones above self.b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) self.cb = np.array([[1j, 2j, 3j], [4j, 5j, 6j], [7j, 8j, 9j]])
# Rectangular matrices self.hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]]) self.chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]]) * 1.j
self.vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]]) self.cvrect = 1.j * np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])
# Medium sizes matrices self.med = self.rng.random((30, 40)) self.cmed = self.rng.random((30, 40)) + 1.j*self.rng.random((30, 40))
def _test_common_lu_factor(self, data): l_and_u1, piv1 = lu_factor(data) (getrf,) = get_lapack_funcs(("getrf",), (data,)) l_and_u2, piv2, _ = getrf(data, overwrite_a=False) assert_allclose(l_and_u1, l_and_u2) assert_allclose(piv1, piv2)
# Simple tests. # For lu_factor gives a LinAlgWarning because these matrices are singular def test_hrectangular(self): self._test_common_lu_factor(self.hrect)
def test_vrectangular(self): self._test_common_lu_factor(self.vrect)
def test_hrectangular_complex(self): self._test_common_lu_factor(self.chrect)
def test_vrectangular_complex(self): self._test_common_lu_factor(self.cvrect)
# Bigger matrices def test_medium1(self): """Check lu decomposition on medium size, rectangular matrix.""" self._test_common_lu_factor(self.med)
def test_medium1_complex(self): """Check lu decomposition on medium size, rectangular matrix.""" self._test_common_lu_factor(self.cmed)
def test_check_finite(self): p, l, u = lu(self.a, check_finite=False) assert_allclose(p @ l @ u, self.a)
def test_simple_known(self): # Ticket #1458 for order in ['C', 'F']: A = np.array([[2, 1], [0, 1.]], order=order) LU, P = lu_factor(A) assert_allclose(LU, np.array([[2, 1], [0, 1]])) assert_array_equal(P, np.array([0, 1]))
@pytest.mark.parametrize("m", [0, 1, 2]) @pytest.mark.parametrize("n", [0, 1, 2]) @pytest.mark.parametrize('dtype', DTYPES) def test_shape_dtype(self, m, n, dtype): k = min(m, n)
a = np.eye(m, n, dtype=dtype) lu, p = lu_factor(a) assert_equal(lu.shape, (m, n)) assert_equal(lu.dtype, dtype) assert_equal(p.shape, (k,)) assert_equal(p.dtype, np.int32)
@pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)]) def test_empty(self, m, n): a = np.zeros((m, n)) lu, p = lu_factor(a) assert_allclose(lu, np.empty((m, n))) assert_allclose(p, np.arange(0))
class TestLUSolve: def setup_method(self): self.rng = np.random.default_rng(1682281250228846)
def test_lu(self): a0 = self.rng.random((10, 10)) b = self.rng.random((10,))
for order in ['C', 'F']: a = np.array(a0, order=order) x1 = solve(a, b) lu_a = lu_factor(a) x2 = lu_solve(lu_a, b) assert_allclose(x1, x2)
def test_check_finite(self): a = self.rng.random((10, 10)) b = self.rng.random((10,)) x1 = solve(a, b) lu_a = lu_factor(a, check_finite=False) x2 = lu_solve(lu_a, b, check_finite=False) assert_allclose(x1, x2)
@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt, dt_b): lu_and_piv = (np.empty((0, 0), dtype=dt), np.array([])) b = np.asarray([], dtype=dt_b) x = lu_solve(lu_and_piv, b) assert x.shape == (0,)
m = lu_solve((np.eye(2, dtype=dt), [0, 1]), np.ones(2, dtype=dt_b)) assert x.dtype == m.dtype
b = np.empty((0, 0), dtype=dt_b) x = lu_solve(lu_and_piv, b) assert x.shape == (0, 0) assert x.dtype == m.dtype123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110import pytestimport numpy as npfrom numpy.linalg import normfrom numpy.testing import (assert_, assert_allclose, assert_equal)from scipy.linalg import polar, eigh
diag2 = np.array([[2, 0], [0, 3]])a13 = np.array([[1, 2, 2]])
precomputed_cases = [ [[[0]], 'right', [[1]], [[0]]], [[[0]], 'left', [[1]], [[0]]], [[[9]], 'right', [[1]], [[9]]], [[[9]], 'left', [[1]], [[9]]], [diag2, 'right', np.eye(2), diag2], [diag2, 'left', np.eye(2), diag2], [a13, 'right', a13/norm(a13[0]), a13.T.dot(a13)/norm(a13[0])],]
verify_cases = [ [[1, 2], [3, 4]], [[1, 2, 3]], [[1], [2], [3]], [[1, 2, 3], [3, 4, 0]], [[1, 2], [3, 4], [5, 5]], [[1, 2], [3, 4+5j]], [[1, 2, 3j]], [[1], [2], [3j]], [[1, 2, 3+2j], [3, 4-1j, -4j]], [[1, 2], [3-2j, 4+0.5j], [5, 5]], [[10000, 10, 1], [-1, 2, 3j], [0, 1, 2]], np.empty((0, 0)), np.empty((0, 2)), np.empty((2, 0)),]
def check_precomputed_polar(a, side, expected_u, expected_p): # Compare the result of the polar decomposition to a # precomputed result. u, p = polar(a, side=side) assert_allclose(u, expected_u, atol=1e-15) assert_allclose(p, expected_p, atol=1e-15)
def verify_polar(a): # Compute the polar decomposition, and then verify that # the result has all the expected properties. product_atol = np.sqrt(np.finfo(float).eps)
aa = np.asarray(a) m, n = aa.shape
u, p = polar(a, side='right') assert_equal(u.shape, (m, n)) assert_equal(p.shape, (n, n)) # a = up assert_allclose(u.dot(p), a, atol=product_atol) if m >= n: assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15) else: assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15) # p is Hermitian positive semidefinite. assert_allclose(p.conj().T, p) evals = eigh(p, eigvals_only=True) nonzero_evals = evals[abs(evals) > 1e-14] assert_((nonzero_evals >= 0).all())
u, p = polar(a, side='left') assert_equal(u.shape, (m, n)) assert_equal(p.shape, (m, m)) # a = pu assert_allclose(p.dot(u), a, atol=product_atol) if m >= n: assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15) else: assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15) # p is Hermitian positive semidefinite. assert_allclose(p.conj().T, p) evals = eigh(p, eigvals_only=True) nonzero_evals = evals[abs(evals) > 1e-14] assert_((nonzero_evals >= 0).all())
def test_precomputed_cases(): for a, side, expected_u, expected_p in precomputed_cases: check_precomputed_polar(a, side, expected_u, expected_p)
def test_verify_cases(): for a in verify_cases: verify_polar(a)
@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])@pytest.mark.parametrize('shape', [(0, 0), (0, 2), (2, 0)])@pytest.mark.parametrize('side', ['left', 'right'])def test_empty(dt, shape, side): a = np.empty(shape, dtype=dt) m, n = shape p_shape = (m, m) if side == 'left' else (n, n)
u, p = polar(a, side=side) u_n, p_n = polar(np.eye(5, dtype=dt))
assert_equal(u.dtype, u_n.dtype) assert_equal(p.dtype, p_n.dtype) assert u.shape == shape assert p.shape == p_shape assert np.all(p == 0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701import itertools
import numpy as npfrom numpy.testing import assert_, assert_allclose, assert_equalfrom pytest import raises as assert_raisesfrom scipy import linalgimport scipy.linalg._decomp_update as _decomp_updatefrom scipy.linalg._decomp_update import qr_delete, qr_update, qr_insert
def assert_unitary(a, rtol=None, atol=None, assert_sqr=True): if rtol is None: rtol = 10.0 ** -(np.finfo(a.dtype).precision-2) if atol is None: atol = 10*np.finfo(a.dtype).eps
if assert_sqr: assert_(a.shape[0] == a.shape[1], 'unitary matrices must be square') aTa = np.dot(a.T.conj(), a) assert_allclose(aTa, np.eye(a.shape[1]), rtol=rtol, atol=atol)
def assert_upper_tri(a, rtol=None, atol=None): if rtol is None: rtol = 10.0 ** -(np.finfo(a.dtype).precision-2) if atol is None: atol = 2*np.finfo(a.dtype).eps mask = np.tri(a.shape[0], a.shape[1], -1, np.bool_) assert_allclose(a[mask], 0.0, rtol=rtol, atol=atol)
def check_qr(q, r, a, rtol, atol, assert_sqr=True): assert_unitary(q, rtol, atol, assert_sqr) assert_upper_tri(r, rtol, atol) assert_allclose(q.dot(r), a, rtol=rtol, atol=atol)
def make_strided(arrs): strides = [(3, 7), (2, 2), (3, 4), (4, 2), (5, 4), (2, 3), (2, 1), (4, 5)] kmax = len(strides) k = 0 ret = [] for a in arrs: if a.ndim == 1: s = strides[k % kmax] k += 1 base = np.zeros(s[0]*a.shape[0]+s[1], a.dtype) view = base[s[1]::s[0]] view[...] = a elif a.ndim == 2: s = strides[k % kmax] t = strides[(k+1) % kmax] k += 2 base = np.zeros((s[0]*a.shape[0]+s[1], t[0]*a.shape[1]+t[1]), a.dtype) view = base[s[1]::s[0], t[1]::t[0]] view[...] = a else: raise ValueError('make_strided only works for ndim = 1 or' ' 2 arrays') ret.append(view) return ret
def negate_strides(arrs): ret = [] for a in arrs: b = np.zeros_like(a) if b.ndim == 2: b = b[::-1, ::-1] elif b.ndim == 1: b = b[::-1] else: raise ValueError('negate_strides only works for ndim = 1 or' ' 2 arrays') b[...] = a ret.append(b) return ret
def nonitemsize_strides(arrs): out = [] for a in arrs: a_dtype = a.dtype b = np.zeros(a.shape, [('a', a_dtype), ('junk', 'S1')]) c = b.getfield(a_dtype) c[...] = a out.append(c) return out
def make_nonnative(arrs): return [a.astype(a.dtype.newbyteorder()) for a in arrs]
class BaseQRdeltas: def setup_method(self): self.rtol = 10.0 ** -(np.finfo(self.dtype).precision-2) self.atol = 10 * np.finfo(self.dtype).eps
def generate(self, type, mode='full'): np.random.seed(29382) shape = {'sqr': (8, 8), 'tall': (12, 7), 'fat': (7, 12), 'Mx1': (8, 1), '1xN': (1, 8), '1x1': (1, 1)}[type] a = np.random.random(shape) if np.iscomplexobj(self.dtype.type(1)): b = np.random.random(shape) a = a + 1j * b a = a.astype(self.dtype) q, r = linalg.qr(a, mode=mode) return a, q, r
class BaseQRdelete(BaseQRdeltas): def test_sqr_1_row(self): a, q, r = self.generate('sqr') for row in range(r.shape[0]): q1, r1 = qr_delete(q, r, row, overwrite_qr=False) a1 = np.delete(a, row, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_sqr_p_row(self): a, q, r = self.generate('sqr') for ndel in range(2, 6): for row in range(a.shape[0]-ndel): q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) a1 = np.delete(a, slice(row, row+ndel), 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_sqr_1_col(self): a, q, r = self.generate('sqr') for col in range(r.shape[1]): q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) a1 = np.delete(a, col, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_sqr_p_col(self): a, q, r = self.generate('sqr') for ndel in range(2, 6): for col in range(r.shape[1]-ndel): q1, r1 = qr_delete(q, r, col, ndel, which='col', overwrite_qr=False) a1 = np.delete(a, slice(col, col+ndel), 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_tall_1_row(self): a, q, r = self.generate('tall') for row in range(r.shape[0]): q1, r1 = qr_delete(q, r, row, overwrite_qr=False) a1 = np.delete(a, row, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_tall_p_row(self): a, q, r = self.generate('tall') for ndel in range(2, 6): for row in range(a.shape[0]-ndel): q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) a1 = np.delete(a, slice(row, row+ndel), 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_tall_1_col(self): a, q, r = self.generate('tall') for col in range(r.shape[1]): q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) a1 = np.delete(a, col, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_tall_p_col(self): a, q, r = self.generate('tall') for ndel in range(2, 6): for col in range(r.shape[1]-ndel): q1, r1 = qr_delete(q, r, col, ndel, which='col', overwrite_qr=False) a1 = np.delete(a, slice(col, col+ndel), 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_fat_1_row(self): a, q, r = self.generate('fat') for row in range(r.shape[0]): q1, r1 = qr_delete(q, r, row, overwrite_qr=False) a1 = np.delete(a, row, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_fat_p_row(self): a, q, r = self.generate('fat') for ndel in range(2, 6): for row in range(a.shape[0]-ndel): q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) a1 = np.delete(a, slice(row, row+ndel), 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_fat_1_col(self): a, q, r = self.generate('fat') for col in range(r.shape[1]): q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) a1 = np.delete(a, col, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_fat_p_col(self): a, q, r = self.generate('fat') for ndel in range(2, 6): for col in range(r.shape[1]-ndel): q1, r1 = qr_delete(q, r, col, ndel, which='col', overwrite_qr=False) a1 = np.delete(a, slice(col, col+ndel), 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_economic_1_row(self): # this test always starts and ends with an economic decomp. a, q, r = self.generate('tall', 'economic') for row in range(r.shape[0]): q1, r1 = qr_delete(q, r, row, overwrite_qr=False) a1 = np.delete(a, row, 0) check_qr(q1, r1, a1, self.rtol, self.atol, False)
# for economic row deletes # eco - prow = eco # eco - prow = sqr # eco - prow = fat def base_economic_p_row_xxx(self, ndel): a, q, r = self.generate('tall', 'economic') for row in range(a.shape[0]-ndel): q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) a1 = np.delete(a, slice(row, row+ndel), 0) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_economic_p_row_economic(self): # (12, 7) - (3, 7) = (9,7) --> stays economic self.base_economic_p_row_xxx(3)
def test_economic_p_row_sqr(self): # (12, 7) - (5, 7) = (7, 7) --> becomes square self.base_economic_p_row_xxx(5)
def test_economic_p_row_fat(self): # (12, 7) - (7,7) = (5, 7) --> becomes fat self.base_economic_p_row_xxx(7)
def test_economic_1_col(self): a, q, r = self.generate('tall', 'economic') for col in range(r.shape[1]): q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) a1 = np.delete(a, col, 1) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_economic_p_col(self): a, q, r = self.generate('tall', 'economic') for ndel in range(2, 6): for col in range(r.shape[1]-ndel): q1, r1 = qr_delete(q, r, col, ndel, which='col', overwrite_qr=False) a1 = np.delete(a, slice(col, col+ndel), 1) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_Mx1_1_row(self): a, q, r = self.generate('Mx1') for row in range(r.shape[0]): q1, r1 = qr_delete(q, r, row, overwrite_qr=False) a1 = np.delete(a, row, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_Mx1_p_row(self): a, q, r = self.generate('Mx1') for ndel in range(2, 6): for row in range(a.shape[0]-ndel): q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) a1 = np.delete(a, slice(row, row+ndel), 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1xN_1_col(self): a, q, r = self.generate('1xN') for col in range(r.shape[1]): q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) a1 = np.delete(a, col, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1xN_p_col(self): a, q, r = self.generate('1xN') for ndel in range(2, 6): for col in range(r.shape[1]-ndel): q1, r1 = qr_delete(q, r, col, ndel, which='col', overwrite_qr=False) a1 = np.delete(a, slice(col, col+ndel), 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_Mx1_economic_1_row(self): a, q, r = self.generate('Mx1', 'economic') for row in range(r.shape[0]): q1, r1 = qr_delete(q, r, row, overwrite_qr=False) a1 = np.delete(a, row, 0) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_Mx1_economic_p_row(self): a, q, r = self.generate('Mx1', 'economic') for ndel in range(2, 6): for row in range(a.shape[0]-ndel): q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) a1 = np.delete(a, slice(row, row+ndel), 0) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_delete_last_1_row(self): # full and eco are the same for 1xN a, q, r = self.generate('1xN') q1, r1 = qr_delete(q, r, 0, 1, 'row') assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
def test_delete_last_p_row(self): a, q, r = self.generate('tall', 'full') q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row') assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
a, q, r = self.generate('tall', 'economic') q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row') assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
def test_delete_last_1_col(self): a, q, r = self.generate('Mx1', 'economic') q1, r1 = qr_delete(q, r, 0, 1, 'col') assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype)) assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
a, q, r = self.generate('Mx1', 'full') q1, r1 = qr_delete(q, r, 0, 1, 'col') assert_unitary(q1) assert_(q1.dtype == q.dtype) assert_(q1.shape == q.shape) assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
def test_delete_last_p_col(self): a, q, r = self.generate('tall', 'full') q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col') assert_unitary(q1) assert_(q1.dtype == q.dtype) assert_(q1.shape == q.shape) assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
a, q, r = self.generate('tall', 'economic') q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col') assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype)) assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
def test_delete_1x1_row_col(self): a, q, r = self.generate('1x1') q1, r1 = qr_delete(q, r, 0, 1, 'row') assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
a, q, r = self.generate('1x1') q1, r1 = qr_delete(q, r, 0, 1, 'col') assert_unitary(q1) assert_(q1.dtype == q.dtype) assert_(q1.shape == q.shape) assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
# all full qr, row deletes and single column deletes should be able to # handle any non negative strides. (only row and column vector # operations are used.) p column delete require fortran ordered # Q and R and will make a copy as necessary. Economic qr row deletes # require a contiguous q.
def base_non_simple_strides(self, adjust_strides, ks, p, which, overwriteable): if which == 'row': qind = (slice(p,None), slice(p,None)) rind = (slice(p,None), slice(None)) else: qind = (slice(None), slice(None)) rind = (slice(None), slice(None,-p))
for type, k in itertools.product(['sqr', 'tall', 'fat'], ks): a, q0, r0, = self.generate(type) qs, rs = adjust_strides((q0, r0)) if p == 1: a1 = np.delete(a, k, 0 if which == 'row' else 1) else: s = slice(k,k+p) if k < 0: s = slice(k, k + p + (a.shape[0] if which == 'row' else a.shape[1])) a1 = np.delete(a, s, 0 if which == 'row' else 1)
# for each variable, q, r we try with it strided and # overwrite=False. Then we try with overwrite=True, and make # sure that q and r are still overwritten.
q = q0.copy('F') r = r0.copy('F') q1, r1 = qr_delete(qs, r, k, p, which, False) check_qr(q1, r1, a1, self.rtol, self.atol) q1o, r1o = qr_delete(qs, r, k, p, which, True) check_qr(q1o, r1o, a1, self.rtol, self.atol) if overwriteable: assert_allclose(q1o, qs[qind], rtol=self.rtol, atol=self.atol) assert_allclose(r1o, r[rind], rtol=self.rtol, atol=self.atol)
q = q0.copy('F') r = r0.copy('F') q2, r2 = qr_delete(q, rs, k, p, which, False) check_qr(q2, r2, a1, self.rtol, self.atol) q2o, r2o = qr_delete(q, rs, k, p, which, True) check_qr(q2o, r2o, a1, self.rtol, self.atol) if overwriteable: assert_allclose(q2o, q[qind], rtol=self.rtol, atol=self.atol) assert_allclose(r2o, rs[rind], rtol=self.rtol, atol=self.atol)
q = q0.copy('F') r = r0.copy('F') # since some of these were consumed above qs, rs = adjust_strides((q, r)) q3, r3 = qr_delete(qs, rs, k, p, which, False) check_qr(q3, r3, a1, self.rtol, self.atol) q3o, r3o = qr_delete(qs, rs, k, p, which, True) check_qr(q3o, r3o, a1, self.rtol, self.atol) if overwriteable: assert_allclose(q2o, qs[qind], rtol=self.rtol, atol=self.atol) assert_allclose(r3o, rs[rind], rtol=self.rtol, atol=self.atol)
def test_non_unit_strides_1_row(self): self.base_non_simple_strides(make_strided, [0], 1, 'row', True)
def test_non_unit_strides_p_row(self): self.base_non_simple_strides(make_strided, [0], 3, 'row', True)
def test_non_unit_strides_1_col(self): self.base_non_simple_strides(make_strided, [0], 1, 'col', True)
def test_non_unit_strides_p_col(self): self.base_non_simple_strides(make_strided, [0], 3, 'col', False)
def test_neg_strides_1_row(self): self.base_non_simple_strides(negate_strides, [0], 1, 'row', False)
def test_neg_strides_p_row(self): self.base_non_simple_strides(negate_strides, [0], 3, 'row', False)
def test_neg_strides_1_col(self): self.base_non_simple_strides(negate_strides, [0], 1, 'col', False)
def test_neg_strides_p_col(self): self.base_non_simple_strides(negate_strides, [0], 3, 'col', False)
def test_non_itemize_strides_1_row(self): self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'row', False)
def test_non_itemize_strides_p_row(self): self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'row', False)
def test_non_itemize_strides_1_col(self): self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'col', False)
def test_non_itemize_strides_p_col(self): self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'col', False)
def test_non_native_byte_order_1_row(self): self.base_non_simple_strides(make_nonnative, [0], 1, 'row', False)
def test_non_native_byte_order_p_row(self): self.base_non_simple_strides(make_nonnative, [0], 3, 'row', False)
def test_non_native_byte_order_1_col(self): self.base_non_simple_strides(make_nonnative, [0], 1, 'col', False)
def test_non_native_byte_order_p_col(self): self.base_non_simple_strides(make_nonnative, [0], 3, 'col', False)
def test_neg_k(self): a, q, r = self.generate('sqr') for k, p, w in itertools.product([-3, -7], [1, 3], ['row', 'col']): q1, r1 = qr_delete(q, r, k, p, w, overwrite_qr=False) if w == 'row': a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[0]), 0) else: a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[1]), 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def base_overwrite_qr(self, which, p, test_C, test_F, mode='full'): assert_sqr = True if mode == 'full' else False if which == 'row': qind = (slice(p,None), slice(p,None)) rind = (slice(p,None), slice(None)) else: qind = (slice(None), slice(None)) rind = (slice(None), slice(None,-p)) a, q0, r0 = self.generate('sqr', mode) if p == 1: a1 = np.delete(a, 3, 0 if which == 'row' else 1) else: a1 = np.delete(a, slice(3, 3+p), 0 if which == 'row' else 1)
# don't overwrite q = q0.copy('F') r = r0.copy('F') q1, r1 = qr_delete(q, r, 3, p, which, False) check_qr(q1, r1, a1, self.rtol, self.atol, assert_sqr) check_qr(q, r, a, self.rtol, self.atol, assert_sqr)
if test_F: q = q0.copy('F') r = r0.copy('F') q2, r2 = qr_delete(q, r, 3, p, which, True) check_qr(q2, r2, a1, self.rtol, self.atol, assert_sqr) # verify the overwriting assert_allclose(q2, q[qind], rtol=self.rtol, atol=self.atol) assert_allclose(r2, r[rind], rtol=self.rtol, atol=self.atol)
if test_C: q = q0.copy('C') r = r0.copy('C') q3, r3 = qr_delete(q, r, 3, p, which, True) check_qr(q3, r3, a1, self.rtol, self.atol, assert_sqr) assert_allclose(q3, q[qind], rtol=self.rtol, atol=self.atol) assert_allclose(r3, r[rind], rtol=self.rtol, atol=self.atol)
def test_overwrite_qr_1_row(self): # any positively strided q and r. self.base_overwrite_qr('row', 1, True, True)
def test_overwrite_economic_qr_1_row(self): # Any contiguous q and positively strided r. self.base_overwrite_qr('row', 1, True, True, 'economic')
def test_overwrite_qr_1_col(self): # any positively strided q and r. # full and eco share code paths self.base_overwrite_qr('col', 1, True, True)
def test_overwrite_qr_p_row(self): # any positively strided q and r. self.base_overwrite_qr('row', 3, True, True)
def test_overwrite_economic_qr_p_row(self): # any contiguous q and positively strided r self.base_overwrite_qr('row', 3, True, True, 'economic')
def test_overwrite_qr_p_col(self): # only F ordered q and r can be overwritten for cols # full and eco share code paths self.base_overwrite_qr('col', 3, False, True)
def test_bad_which(self): a, q, r = self.generate('sqr') assert_raises(ValueError, qr_delete, q, r, 0, which='foo')
def test_bad_k(self): a, q, r = self.generate('tall') assert_raises(ValueError, qr_delete, q, r, q.shape[0], 1) assert_raises(ValueError, qr_delete, q, r, -q.shape[0]-1, 1) assert_raises(ValueError, qr_delete, q, r, r.shape[0], 1, 'col') assert_raises(ValueError, qr_delete, q, r, -r.shape[0]-1, 1, 'col')
def test_bad_p(self): a, q, r = self.generate('tall') # p must be positive assert_raises(ValueError, qr_delete, q, r, 0, -1) assert_raises(ValueError, qr_delete, q, r, 0, -1, 'col')
# and nonzero assert_raises(ValueError, qr_delete, q, r, 0, 0) assert_raises(ValueError, qr_delete, q, r, 0, 0, 'col')
# must have at least k+p rows or cols, depending. assert_raises(ValueError, qr_delete, q, r, 3, q.shape[0]-2) assert_raises(ValueError, qr_delete, q, r, 3, r.shape[1]-2, 'col')
def test_empty_q(self): a, q, r = self.generate('tall') # same code path for 'row' and 'col' assert_raises(ValueError, qr_delete, np.array([]), r, 0, 1)
def test_empty_r(self): a, q, r = self.generate('tall') # same code path for 'row' and 'col' assert_raises(ValueError, qr_delete, q, np.array([]), 0, 1)
def test_mismatched_q_and_r(self): a, q, r = self.generate('tall') r = r[1:] assert_raises(ValueError, qr_delete, q, r, 0, 1)
def test_unsupported_dtypes(self): dts = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float16', 'longdouble', 'clongdouble', 'bool'] a, q0, r0 = self.generate('tall') for dtype in dts: q = q0.real.astype(dtype) with np.errstate(invalid="ignore"): r = r0.real.astype(dtype) assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row') assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'row') assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col') assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'col')
assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row') assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'row') assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col') assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'col')
def test_check_finite(self): a0, q0, r0 = self.generate('tall')
q = q0.copy('F') q[1,1] = np.nan assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row') assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'row') assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col') assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'col')
r = r0.copy('F') r[1,1] = np.nan assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row') assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'row') assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col') assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'col')
def test_qr_scalar(self): a, q, r = self.generate('1x1') assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'row') assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'row') assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'col') assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'col')
class TestQRdelete_f(BaseQRdelete): dtype = np.dtype('f')
class TestQRdelete_F(BaseQRdelete): dtype = np.dtype('F')
class TestQRdelete_d(BaseQRdelete): dtype = np.dtype('d')
class TestQRdelete_D(BaseQRdelete): dtype = np.dtype('D')
class BaseQRinsert(BaseQRdeltas): def generate(self, type, mode='full', which='row', p=1): a, q, r = super().generate(type, mode)
assert_(p > 0) rng = np.random.RandomState(1234)
# super call set the seed... if which == 'row': if p == 1: u = rng.random(a.shape[1]) else: u = rng.random((p, a.shape[1])) elif which == 'col': if p == 1: u = rng.random(a.shape[0]) else: u = rng.random((a.shape[0], p)) else: ValueError('which should be either "row" or "col"')
if np.iscomplexobj(self.dtype.type(1)): b = rng.random(u.shape) u = u + 1j * b
u = u.astype(self.dtype) return a, q, r, u
def test_sqr_1_row(self): a, q, r, u = self.generate('sqr', which='row') for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, row, u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_sqr_p_row(self): # sqr + rows --> fat always a, q, r, u = self.generate('sqr', which='row', p=3) for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, np.full(3, row, np.intp), u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_sqr_1_col(self): a, q, r, u = self.generate('sqr', which='col') for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, col, u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_sqr_p_col(self): # sqr + cols --> fat always a, q, r, u = self.generate('sqr', which='col', p=3) for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, np.full(3, col, np.intp), u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_tall_1_row(self): a, q, r, u = self.generate('tall', which='row') for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, row, u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_tall_p_row(self): # tall + rows --> tall always a, q, r, u = self.generate('tall', which='row', p=3) for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, np.full(3, row, np.intp), u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_tall_1_col(self): a, q, r, u = self.generate('tall', which='col') for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, col, u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
# for column adds to tall matrices there are three cases to test # tall + pcol --> tall # tall + pcol --> sqr # tall + pcol --> fat def base_tall_p_col_xxx(self, p): a, q, r, u = self.generate('tall', which='col', p=p) for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, np.full(p, col, np.intp), u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_tall_p_col_tall(self): # 12x7 + 12x3 = 12x10 --> stays tall self.base_tall_p_col_xxx(3)
def test_tall_p_col_sqr(self): # 12x7 + 12x5 = 12x12 --> becomes sqr self.base_tall_p_col_xxx(5)
def test_tall_p_col_fat(self): # 12x7 + 12x7 = 12x14 --> becomes fat self.base_tall_p_col_xxx(7)
def test_fat_1_row(self): a, q, r, u = self.generate('fat', which='row') for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, row, u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
# for row adds to fat matrices there are three cases to test # fat + prow --> fat # fat + prow --> sqr # fat + prow --> tall def base_fat_p_row_xxx(self, p): a, q, r, u = self.generate('fat', which='row', p=p) for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, np.full(p, row, np.intp), u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_fat_p_row_fat(self): # 7x12 + 3x12 = 10x12 --> stays fat self.base_fat_p_row_xxx(3)
def test_fat_p_row_sqr(self): # 7x12 + 5x12 = 12x12 --> becomes sqr self.base_fat_p_row_xxx(5)
def test_fat_p_row_tall(self): # 7x12 + 7x12 = 14x12 --> becomes tall self.base_fat_p_row_xxx(7)
def test_fat_1_col(self): a, q, r, u = self.generate('fat', which='col') for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, col, u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_fat_p_col(self): # fat + cols --> fat always a, q, r, u = self.generate('fat', which='col', p=3) for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, np.full(3, col, np.intp), u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_economic_1_row(self): a, q, r, u = self.generate('tall', 'economic', 'row') for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False) a1 = np.insert(a, row, u, 0) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_economic_p_row(self): # tall + rows --> tall always a, q, r, u = self.generate('tall', 'economic', 'row', 3) for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False) a1 = np.insert(a, np.full(3, row, np.intp), u, 0) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_economic_1_col(self): a, q, r, u = self.generate('tall', 'economic', which='col') for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u.copy(), col, 'col', overwrite_qru=False) a1 = np.insert(a, col, u, 1) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_economic_1_col_bad_update(self): # When the column to be added lies in the span of Q, the update is # not meaningful. This is detected, and a LinAlgError is issued. q = np.eye(5, 3, dtype=self.dtype) r = np.eye(3, dtype=self.dtype) u = np.array([1, 0, 0, 0, 0], self.dtype) assert_raises(linalg.LinAlgError, qr_insert, q, r, u, 0, 'col')
# for column adds to economic matrices there are three cases to test # eco + pcol --> eco # eco + pcol --> sqr # eco + pcol --> fat def base_economic_p_col_xxx(self, p): a, q, r, u = self.generate('tall', 'economic', which='col', p=p) for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, np.full(p, col, np.intp), u, 1) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_economic_p_col_eco(self): # 12x7 + 12x3 = 12x10 --> stays eco self.base_economic_p_col_xxx(3)
def test_economic_p_col_sqr(self): # 12x7 + 12x5 = 12x12 --> becomes sqr self.base_economic_p_col_xxx(5)
def test_economic_p_col_fat(self): # 12x7 + 12x7 = 12x14 --> becomes fat self.base_economic_p_col_xxx(7)
def test_Mx1_1_row(self): a, q, r, u = self.generate('Mx1', which='row') for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, row, u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_Mx1_p_row(self): a, q, r, u = self.generate('Mx1', which='row', p=3) for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, np.full(3, row, np.intp), u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_Mx1_1_col(self): a, q, r, u = self.generate('Mx1', which='col') for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, col, u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_Mx1_p_col(self): a, q, r, u = self.generate('Mx1', which='col', p=3) for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, np.full(3, col, np.intp), u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_Mx1_economic_1_row(self): a, q, r, u = self.generate('Mx1', 'economic', 'row') for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, row, u, 0) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_Mx1_economic_p_row(self): a, q, r, u = self.generate('Mx1', 'economic', 'row', 3) for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, np.full(3, row, np.intp), u, 0) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_Mx1_economic_1_col(self): a, q, r, u = self.generate('Mx1', 'economic', 'col') for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, col, u, 1) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_Mx1_economic_p_col(self): a, q, r, u = self.generate('Mx1', 'economic', 'col', 3) for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, np.full(3, col, np.intp), u, 1) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_1xN_1_row(self): a, q, r, u = self.generate('1xN', which='row') for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, row, u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1xN_p_row(self): a, q, r, u = self.generate('1xN', which='row', p=3) for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, np.full(3, row, np.intp), u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1xN_1_col(self): a, q, r, u = self.generate('1xN', which='col') for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, col, u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1xN_p_col(self): a, q, r, u = self.generate('1xN', which='col', p=3) for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, np.full(3, col, np.intp), u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1x1_1_row(self): a, q, r, u = self.generate('1x1', which='row') for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, row, u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1x1_p_row(self): a, q, r, u = self.generate('1x1', which='row', p=3) for row in range(r.shape[0] + 1): q1, r1 = qr_insert(q, r, u, row) a1 = np.insert(a, np.full(3, row, np.intp), u, 0) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1x1_1_col(self): a, q, r, u = self.generate('1x1', which='col') for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, col, u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1x1_p_col(self): a, q, r, u = self.generate('1x1', which='col', p=3) for col in range(r.shape[1] + 1): q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) a1 = np.insert(a, np.full(3, col, np.intp), u, 1) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1x1_1_scalar(self): a, q, r, u = self.generate('1x1', which='row') assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'row') assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'row') assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'row')
assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'col') assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'col') assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'col')
def base_non_simple_strides(self, adjust_strides, k, p, which): for type in ['sqr', 'tall', 'fat']: a, q0, r0, u0 = self.generate(type, which=which, p=p) qs, rs, us = adjust_strides((q0, r0, u0)) if p == 1: ai = np.insert(a, k, u0, 0 if which == 'row' else 1) else: ai = np.insert(a, np.full(p, k, np.intp), u0 if which == 'row' else u0, 0 if which == 'row' else 1)
# for each variable, q, r, u we try with it strided and # overwrite=False. Then we try with overwrite=True. Nothing # is checked to see if it can be overwritten, since only # F ordered Q can be overwritten when adding columns.
q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') q1, r1 = qr_insert(qs, r, u, k, which, overwrite_qru=False) check_qr(q1, r1, ai, self.rtol, self.atol) q1o, r1o = qr_insert(qs, r, u, k, which, overwrite_qru=True) check_qr(q1o, r1o, ai, self.rtol, self.atol)
q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') q2, r2 = qr_insert(q, rs, u, k, which, overwrite_qru=False) check_qr(q2, r2, ai, self.rtol, self.atol) q2o, r2o = qr_insert(q, rs, u, k, which, overwrite_qru=True) check_qr(q2o, r2o, ai, self.rtol, self.atol)
q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') q3, r3 = qr_insert(q, r, us, k, which, overwrite_qru=False) check_qr(q3, r3, ai, self.rtol, self.atol) q3o, r3o = qr_insert(q, r, us, k, which, overwrite_qru=True) check_qr(q3o, r3o, ai, self.rtol, self.atol)
q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') # since some of these were consumed above qs, rs, us = adjust_strides((q, r, u)) q5, r5 = qr_insert(qs, rs, us, k, which, overwrite_qru=False) check_qr(q5, r5, ai, self.rtol, self.atol) q5o, r5o = qr_insert(qs, rs, us, k, which, overwrite_qru=True) check_qr(q5o, r5o, ai, self.rtol, self.atol)
def test_non_unit_strides_1_row(self): self.base_non_simple_strides(make_strided, 0, 1, 'row')
def test_non_unit_strides_p_row(self): self.base_non_simple_strides(make_strided, 0, 3, 'row')
def test_non_unit_strides_1_col(self): self.base_non_simple_strides(make_strided, 0, 1, 'col')
def test_non_unit_strides_p_col(self): self.base_non_simple_strides(make_strided, 0, 3, 'col')
def test_neg_strides_1_row(self): self.base_non_simple_strides(negate_strides, 0, 1, 'row')
def test_neg_strides_p_row(self): self.base_non_simple_strides(negate_strides, 0, 3, 'row')
def test_neg_strides_1_col(self): self.base_non_simple_strides(negate_strides, 0, 1, 'col')
def test_neg_strides_p_col(self): self.base_non_simple_strides(negate_strides, 0, 3, 'col')
def test_non_itemsize_strides_1_row(self): self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'row')
def test_non_itemsize_strides_p_row(self): self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'row')
def test_non_itemsize_strides_1_col(self): self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'col')
def test_non_itemsize_strides_p_col(self): self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'col')
def test_non_native_byte_order_1_row(self): self.base_non_simple_strides(make_nonnative, 0, 1, 'row')
def test_non_native_byte_order_p_row(self): self.base_non_simple_strides(make_nonnative, 0, 3, 'row')
def test_non_native_byte_order_1_col(self): self.base_non_simple_strides(make_nonnative, 0, 1, 'col')
def test_non_native_byte_order_p_col(self): self.base_non_simple_strides(make_nonnative, 0, 3, 'col')
def test_overwrite_qu_rank_1(self): # when inserting rows, the size of both Q and R change, so only # column inserts can overwrite q. Only complex column inserts # with C ordered Q overwrite u. Any contiguous Q is overwritten # when inserting 1 column a, q0, r, u, = self.generate('sqr', which='col', p=1) q = q0.copy('C') u0 = u.copy() # don't overwrite q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False) a1 = np.insert(a, 0, u0, 1) check_qr(q1, r1, a1, self.rtol, self.atol) check_qr(q, r, a, self.rtol, self.atol)
# try overwriting q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True) check_qr(q2, r2, a1, self.rtol, self.atol) # verify the overwriting assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) assert_allclose(u, u0.conj(), self.rtol, self.atol)
# now try with a fortran ordered Q qF = q0.copy('F') u1 = u0.copy() q3, r3 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=False) check_qr(q3, r3, a1, self.rtol, self.atol) check_qr(qF, r, a, self.rtol, self.atol)
# try overwriting q4, r4 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=True) check_qr(q4, r4, a1, self.rtol, self.atol) assert_allclose(q4, qF, rtol=self.rtol, atol=self.atol)
def test_overwrite_qu_rank_p(self): # when inserting rows, the size of both Q and R change, so only # column inserts can potentially overwrite Q. In practice, only # F ordered Q are overwritten with a rank p update. a, q0, r, u, = self.generate('sqr', which='col', p=3) q = q0.copy('F') a1 = np.insert(a, np.zeros(3, np.intp), u, 1)
# don't overwrite q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False) check_qr(q1, r1, a1, self.rtol, self.atol) check_qr(q, r, a, self.rtol, self.atol)
# try overwriting q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True) check_qr(q2, r2, a1, self.rtol, self.atol) assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
def test_empty_inputs(self): a, q, r, u = self.generate('sqr', which='row') assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'row') assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'row') assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'row') assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'col') assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'col') assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'col')
def test_mismatched_shapes(self): a, q, r, u = self.generate('tall', which='row') assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'row') assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'row') assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'row') assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'col') assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'col') assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'col')
def test_unsupported_dtypes(self): dts = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float16', 'longdouble', 'clongdouble', 'bool'] a, q0, r0, u0 = self.generate('sqr', which='row') for dtype in dts: q = q0.real.astype(dtype) with np.errstate(invalid="ignore"): r = r0.real.astype(dtype) u = u0.real.astype(dtype) assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row') assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col') assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row') assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col') assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row') assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
def test_check_finite(self): a0, q0, r0, u0 = self.generate('sqr', which='row', p=3)
q = q0.copy('F') q[1,1] = np.nan assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'row') assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row') assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'col') assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col')
r = r0.copy('F') r[1,1] = np.nan assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'row') assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row') assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'col') assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col')
u = u0.copy('F') u[0,0] = np.nan assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'row') assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row') assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'col') assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
class TestQRinsert_f(BaseQRinsert): dtype = np.dtype('f')
class TestQRinsert_F(BaseQRinsert): dtype = np.dtype('F')
class TestQRinsert_d(BaseQRinsert): dtype = np.dtype('d')
class TestQRinsert_D(BaseQRinsert): dtype = np.dtype('D')
class BaseQRupdate(BaseQRdeltas): def generate(self, type, mode='full', p=1): a, q, r = super().generate(type, mode)
# super call set the seed... if p == 1: u = np.random.random(q.shape[0]) v = np.random.random(r.shape[1]) else: u = np.random.random((q.shape[0], p)) v = np.random.random((r.shape[1], p))
if np.iscomplexobj(self.dtype.type(1)): b = np.random.random(u.shape) u = u + 1j * b
c = np.random.random(v.shape) v = v + 1j * c
u = u.astype(self.dtype) v = v.astype(self.dtype) return a, q, r, u, v
def test_sqr_rank_1(self): a, q, r, u, v = self.generate('sqr') q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.outer(u, v.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_sqr_rank_p(self): # test ndim = 2, rank 1 updates here too for p in [1, 2, 3, 5]: a, q, r, u, v = self.generate('sqr', p=p) if p == 1: u = u.reshape(u.size, 1) v = v.reshape(v.size, 1) q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.dot(u, v.T.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_tall_rank_1(self): a, q, r, u, v = self.generate('tall') q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.outer(u, v.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_tall_rank_p(self): for p in [1, 2, 3, 5]: a, q, r, u, v = self.generate('tall', p=p) if p == 1: u = u.reshape(u.size, 1) v = v.reshape(v.size, 1) q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.dot(u, v.T.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_fat_rank_1(self): a, q, r, u, v = self.generate('fat') q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.outer(u, v.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_fat_rank_p(self): for p in [1, 2, 3, 5]: a, q, r, u, v = self.generate('fat', p=p) if p == 1: u = u.reshape(u.size, 1) v = v.reshape(v.size, 1) q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.dot(u, v.T.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_economic_rank_1(self): a, q, r, u, v = self.generate('tall', 'economic') q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.outer(u, v.conj()) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_economic_rank_p(self): for p in [1, 2, 3, 5]: a, q, r, u, v = self.generate('tall', 'economic', p) if p == 1: u = u.reshape(u.size, 1) v = v.reshape(v.size, 1) q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.dot(u, v.T.conj()) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_Mx1_rank_1(self): a, q, r, u, v = self.generate('Mx1') q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.outer(u, v.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_Mx1_rank_p(self): # when M or N == 1, only a rank 1 update is allowed. This isn't # fundamental limitation, but the code does not support it. a, q, r, u, v = self.generate('Mx1', p=1) u = u.reshape(u.size, 1) v = v.reshape(v.size, 1) q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.dot(u, v.T.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_Mx1_economic_rank_1(self): a, q, r, u, v = self.generate('Mx1', 'economic') q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.outer(u, v.conj()) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_Mx1_economic_rank_p(self): # when M or N == 1, only a rank 1 update is allowed. This isn't # fundamental limitation, but the code does not support it. a, q, r, u, v = self.generate('Mx1', 'economic', p=1) u = u.reshape(u.size, 1) v = v.reshape(v.size, 1) q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.dot(u, v.T.conj()) check_qr(q1, r1, a1, self.rtol, self.atol, False)
def test_1xN_rank_1(self): a, q, r, u, v = self.generate('1xN') q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.outer(u, v.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1xN_rank_p(self): # when M or N == 1, only a rank 1 update is allowed. This isn't # fundamental limitation, but the code does not support it. a, q, r, u, v = self.generate('1xN', p=1) u = u.reshape(u.size, 1) v = v.reshape(v.size, 1) q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.dot(u, v.T.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1x1_rank_1(self): a, q, r, u, v = self.generate('1x1') q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.outer(u, v.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1x1_rank_p(self): # when M or N == 1, only a rank 1 update is allowed. This isn't # fundamental limitation, but the code does not support it. a, q, r, u, v = self.generate('1x1', p=1) u = u.reshape(u.size, 1) v = v.reshape(v.size, 1) q1, r1 = qr_update(q, r, u, v, False) a1 = a + np.dot(u, v.T.conj()) check_qr(q1, r1, a1, self.rtol, self.atol)
def test_1x1_rank_1_scalar(self): a, q, r, u, v = self.generate('1x1') assert_raises(ValueError, qr_update, q[0, 0], r, u, v) assert_raises(ValueError, qr_update, q, r[0, 0], u, v) assert_raises(ValueError, qr_update, q, r, u[0], v) assert_raises(ValueError, qr_update, q, r, u, v[0])
def base_non_simple_strides(self, adjust_strides, mode, p, overwriteable): assert_sqr = False if mode == 'economic' else True for type in ['sqr', 'tall', 'fat']: a, q0, r0, u0, v0 = self.generate(type, mode, p) qs, rs, us, vs = adjust_strides((q0, r0, u0, v0)) if p == 1: aup = a + np.outer(u0, v0.conj()) else: aup = a + np.dot(u0, v0.T.conj())
# for each variable, q, r, u, v we try with it strided and # overwrite=False. Then we try with overwrite=True, and make # sure that if p == 1, r and v are still overwritten. # a strided q and u must always be copied.
q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') v = v0.copy('C') q1, r1 = qr_update(qs, r, u, v, False) check_qr(q1, r1, aup, self.rtol, self.atol, assert_sqr) q1o, r1o = qr_update(qs, r, u, v, True) check_qr(q1o, r1o, aup, self.rtol, self.atol, assert_sqr) if overwriteable: assert_allclose(r1o, r, rtol=self.rtol, atol=self.atol) assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') v = v0.copy('C') q2, r2 = qr_update(q, rs, u, v, False) check_qr(q2, r2, aup, self.rtol, self.atol, assert_sqr) q2o, r2o = qr_update(q, rs, u, v, True) check_qr(q2o, r2o, aup, self.rtol, self.atol, assert_sqr) if overwriteable: assert_allclose(r2o, rs, rtol=self.rtol, atol=self.atol) assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') v = v0.copy('C') q3, r3 = qr_update(q, r, us, v, False) check_qr(q3, r3, aup, self.rtol, self.atol, assert_sqr) q3o, r3o = qr_update(q, r, us, v, True) check_qr(q3o, r3o, aup, self.rtol, self.atol, assert_sqr) if overwriteable: assert_allclose(r3o, r, rtol=self.rtol, atol=self.atol) assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') v = v0.copy('C') q4, r4 = qr_update(q, r, u, vs, False) check_qr(q4, r4, aup, self.rtol, self.atol, assert_sqr) q4o, r4o = qr_update(q, r, u, vs, True) check_qr(q4o, r4o, aup, self.rtol, self.atol, assert_sqr) if overwriteable: assert_allclose(r4o, r, rtol=self.rtol, atol=self.atol) assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') v = v0.copy('C') # since some of these were consumed above qs, rs, us, vs = adjust_strides((q, r, u, v)) q5, r5 = qr_update(qs, rs, us, vs, False) check_qr(q5, r5, aup, self.rtol, self.atol, assert_sqr) q5o, r5o = qr_update(qs, rs, us, vs, True) check_qr(q5o, r5o, aup, self.rtol, self.atol, assert_sqr) if overwriteable: assert_allclose(r5o, rs, rtol=self.rtol, atol=self.atol) assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
def test_non_unit_strides_rank_1(self): self.base_non_simple_strides(make_strided, 'full', 1, True)
def test_non_unit_strides_economic_rank_1(self): self.base_non_simple_strides(make_strided, 'economic', 1, True)
def test_non_unit_strides_rank_p(self): self.base_non_simple_strides(make_strided, 'full', 3, False)
def test_non_unit_strides_economic_rank_p(self): self.base_non_simple_strides(make_strided, 'economic', 3, False)
def test_neg_strides_rank_1(self): self.base_non_simple_strides(negate_strides, 'full', 1, False)
def test_neg_strides_economic_rank_1(self): self.base_non_simple_strides(negate_strides, 'economic', 1, False)
def test_neg_strides_rank_p(self): self.base_non_simple_strides(negate_strides, 'full', 3, False)
def test_neg_strides_economic_rank_p(self): self.base_non_simple_strides(negate_strides, 'economic', 3, False)
def test_non_itemsize_strides_rank_1(self): self.base_non_simple_strides(nonitemsize_strides, 'full', 1, False)
def test_non_itemsize_strides_economic_rank_1(self): self.base_non_simple_strides(nonitemsize_strides, 'economic', 1, False)
def test_non_itemsize_strides_rank_p(self): self.base_non_simple_strides(nonitemsize_strides, 'full', 3, False)
def test_non_itemsize_strides_economic_rank_p(self): self.base_non_simple_strides(nonitemsize_strides, 'economic', 3, False)
def test_non_native_byte_order_rank_1(self): self.base_non_simple_strides(make_nonnative, 'full', 1, False)
def test_non_native_byte_order_economic_rank_1(self): self.base_non_simple_strides(make_nonnative, 'economic', 1, False)
def test_non_native_byte_order_rank_p(self): self.base_non_simple_strides(make_nonnative, 'full', 3, False)
def test_non_native_byte_order_economic_rank_p(self): self.base_non_simple_strides(make_nonnative, 'economic', 3, False)
def test_overwrite_qruv_rank_1(self): # Any positive strided q, r, u, and v can be overwritten for a rank 1 # update, only checking C and F contiguous. a, q0, r0, u0, v0 = self.generate('sqr') a1 = a + np.outer(u0, v0.conj()) q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') v = v0.copy('F')
# don't overwrite q1, r1 = qr_update(q, r, u, v, False) check_qr(q1, r1, a1, self.rtol, self.atol) check_qr(q, r, a, self.rtol, self.atol)
q2, r2 = qr_update(q, r, u, v, True) check_qr(q2, r2, a1, self.rtol, self.atol) # verify the overwriting, no good way to check u and v. assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
q = q0.copy('C') r = r0.copy('C') u = u0.copy('C') v = v0.copy('C') q3, r3 = qr_update(q, r, u, v, True) check_qr(q3, r3, a1, self.rtol, self.atol) assert_allclose(q3, q, rtol=self.rtol, atol=self.atol) assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
def test_overwrite_qruv_rank_1_economic(self): # updating economic decompositions can overwrite any contiguous r, # and positively strided r and u. V is only ever read. # only checking C and F contiguous. a, q0, r0, u0, v0 = self.generate('tall', 'economic') a1 = a + np.outer(u0, v0.conj()) q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') v = v0.copy('F')
# don't overwrite q1, r1 = qr_update(q, r, u, v, False) check_qr(q1, r1, a1, self.rtol, self.atol, False) check_qr(q, r, a, self.rtol, self.atol, False)
q2, r2 = qr_update(q, r, u, v, True) check_qr(q2, r2, a1, self.rtol, self.atol, False) # verify the overwriting, no good way to check u and v. assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
q = q0.copy('C') r = r0.copy('C') u = u0.copy('C') v = v0.copy('C') q3, r3 = qr_update(q, r, u, v, True) check_qr(q3, r3, a1, self.rtol, self.atol, False) assert_allclose(q3, q, rtol=self.rtol, atol=self.atol) assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
def test_overwrite_qruv_rank_p(self): # for rank p updates, q r must be F contiguous, v must be C (v.T --> F) # and u can be C or F, but is only overwritten if Q is C and complex a, q0, r0, u0, v0 = self.generate('sqr', p=3) a1 = a + np.dot(u0, v0.T.conj()) q = q0.copy('F') r = r0.copy('F') u = u0.copy('F') v = v0.copy('C')
# don't overwrite q1, r1 = qr_update(q, r, u, v, False) check_qr(q1, r1, a1, self.rtol, self.atol) check_qr(q, r, a, self.rtol, self.atol)
q2, r2 = qr_update(q, r, u, v, True) check_qr(q2, r2, a1, self.rtol, self.atol) # verify the overwriting, no good way to check u and v. assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
def test_empty_inputs(self): a, q, r, u, v = self.generate('tall') assert_raises(ValueError, qr_update, np.array([]), r, u, v) assert_raises(ValueError, qr_update, q, np.array([]), u, v) assert_raises(ValueError, qr_update, q, r, np.array([]), v) assert_raises(ValueError, qr_update, q, r, u, np.array([]))
def test_mismatched_shapes(self): a, q, r, u, v = self.generate('tall') assert_raises(ValueError, qr_update, q, r[1:], u, v) assert_raises(ValueError, qr_update, q[:-2], r, u, v) assert_raises(ValueError, qr_update, q, r, u[1:], v) assert_raises(ValueError, qr_update, q, r, u, v[1:])
def test_unsupported_dtypes(self): dts = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float16', 'longdouble', 'clongdouble', 'bool'] a, q0, r0, u0, v0 = self.generate('tall') for dtype in dts: q = q0.real.astype(dtype) with np.errstate(invalid="ignore"): r = r0.real.astype(dtype) u = u0.real.astype(dtype) v = v0.real.astype(dtype) assert_raises(ValueError, qr_update, q, r0, u0, v0) assert_raises(ValueError, qr_update, q0, r, u0, v0) assert_raises(ValueError, qr_update, q0, r0, u, v0) assert_raises(ValueError, qr_update, q0, r0, u0, v)
def test_integer_input(self): q = np.arange(16).reshape(4, 4) r = q.copy() # doesn't matter u = q[:, 0].copy() v = r[0, :].copy() assert_raises(ValueError, qr_update, q, r, u, v)
def test_check_finite(self): a0, q0, r0, u0, v0 = self.generate('tall', p=3)
q = q0.copy('F') q[1,1] = np.nan assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0]) assert_raises(ValueError, qr_update, q, r0, u0, v0)
r = r0.copy('F') r[1,1] = np.nan assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0]) assert_raises(ValueError, qr_update, q0, r, u0, v0)
u = u0.copy('F') u[0,0] = np.nan assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0]) assert_raises(ValueError, qr_update, q0, r0, u, v0)
v = v0.copy('F') v[0,0] = np.nan assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0]) assert_raises(ValueError, qr_update, q0, r0, u, v)
def test_economic_check_finite(self): a0, q0, r0, u0, v0 = self.generate('tall', mode='economic', p=3)
q = q0.copy('F') q[1,1] = np.nan assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0]) assert_raises(ValueError, qr_update, q, r0, u0, v0)
r = r0.copy('F') r[1,1] = np.nan assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0]) assert_raises(ValueError, qr_update, q0, r, u0, v0)
u = u0.copy('F') u[0,0] = np.nan assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0]) assert_raises(ValueError, qr_update, q0, r0, u, v0)
v = v0.copy('F') v[0,0] = np.nan assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0]) assert_raises(ValueError, qr_update, q0, r0, u, v)
def test_u_exactly_in_span_q(self): q = np.array([[0, 0], [0, 0], [1, 0], [0, 1]], self.dtype) r = np.array([[1, 0], [0, 1]], self.dtype) u = np.array([0, 0, 0, -1], self.dtype) v = np.array([1, 2], self.dtype) q1, r1 = qr_update(q, r, u, v) a1 = np.dot(q, r) + np.outer(u, v.conj()) check_qr(q1, r1, a1, self.rtol, self.atol, False)
class TestQRupdate_f(BaseQRupdate): dtype = np.dtype('f')
class TestQRupdate_F(BaseQRupdate): dtype = np.dtype('F')
class TestQRupdate_d(BaseQRupdate): dtype = np.dtype('d')
class TestQRupdate_D(BaseQRupdate): dtype = np.dtype('D')
def test_form_qTu(): # We want to ensure that all of the code paths through this function are # tested. Most of them should be hit with the rest of test suite, but # explicit tests make clear precisely what is being tested. # # This function expects that Q is either C or F contiguous and square. # Economic mode decompositions (Q is (M, N), M != N) do not go through this # function. U may have any positive strides. # # Some of these test are duplicates, since contiguous 1d arrays are both C # and F.
q_order = ['F', 'C'] q_shape = [(8, 8), ] u_order = ['F', 'C', 'A'] # here A means is not F not C u_shape = [1, 3] dtype = ['f', 'd', 'F', 'D']
for qo, qs, uo, us, d in \ itertools.product(q_order, q_shape, u_order, u_shape, dtype): if us == 1: check_form_qTu(qo, qs, uo, us, 1, d) check_form_qTu(qo, qs, uo, us, 2, d) else: check_form_qTu(qo, qs, uo, us, 2, d)
def check_form_qTu(q_order, q_shape, u_order, u_shape, u_ndim, dtype): np.random.seed(47) if u_shape == 1 and u_ndim == 1: u_shape = (q_shape[0],) else: u_shape = (q_shape[0], u_shape) dtype = np.dtype(dtype)
if dtype.char in 'fd': q = np.random.random(q_shape) u = np.random.random(u_shape) elif dtype.char in 'FD': q = np.random.random(q_shape) + 1j*np.random.random(q_shape) u = np.random.random(u_shape) + 1j*np.random.random(u_shape) else: ValueError("form_qTu doesn't support this dtype")
q = np.require(q, dtype, q_order) if u_order != 'A': u = np.require(u, dtype, u_order) else: u, = make_strided((u.astype(dtype),))
rtol = 10.0 ** -(np.finfo(dtype).precision-2) atol = 2*np.finfo(dtype).eps
expected = np.dot(q.T.conj(), u) res = _decomp_update._form_qTu(q, u) assert_allclose(res, expected, rtol=rtol, atol=atol)12345678910111213141516171819202122232425262728293031323334353637383940414243444546import osimport platformimport sysconfig
import numpy as npimport pytest
from scipy._lib._testutils import IS_EDITABLE, _test_cython_extension, cythonfrom scipy.linalg.blas import cdotu # type: ignore[attr-defined]from scipy.linalg.lapack import dgtsv # type: ignore[attr-defined]
@pytest.mark.fail_slow(120)# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247@pytest.mark.skipif(IS_EDITABLE, reason='Editable install cannot find .pxd headers.')@pytest.mark.skipif((platform.system() == 'Windows' and sysconfig.get_config_var('Py_GIL_DISABLED')), reason='gh-22039')@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"], reason="Can't start subprocess")@pytest.mark.skipif(cython is None, reason="requires cython")def test_cython(tmp_path): srcdir = os.path.dirname(os.path.dirname(__file__)) extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir) # actually test the cython c-extensions a = np.ones(8) * 3 b = np.ones(9) c = np.ones(8) * 4 x = np.ones(9) _, _, _, x, _ = dgtsv(a, b, c, x) a = np.ones(8) * 3 b = np.ones(9) c = np.ones(8) * 4 x_c = np.ones(9) extensions.tridiag(a, b, c, x_c) a = np.ones(8) * 3 b = np.ones(9) c = np.ones(8) * 4 x_cpp = np.ones(9) extensions_cpp.tridiag(a, b, c, x_cpp) np.testing.assert_array_equal(x, x_cpp) cx = np.array([1-1j, 2+2j, 3-3j], dtype=np.complex64) cy = np.array([4+4j, 5-5j, 6+6j], dtype=np.complex64) np.testing.assert_array_equal(cdotu(cx, cy), extensions.complex_dot(cx, cy)) np.testing.assert_array_equal(cdotu(cx, cy), extensions_cpp.complex_dot(cx, cy))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607# Test interfaces to fortran blas.## The tests are more of interface than they are of the underlying blas.# Only very small matrices checked -- N=3 or so.## !! Complex calculations really aren't checked that carefully.# !! Only real valued complex numbers are used in tests.
from numpy import float32, float64, complex64, complex128, arange, array, \ zeros, shape, transpose, newaxis, common_type, conjugate
from scipy.linalg import _fblas as fblas
from numpy.testing import assert_array_equal, \ assert_allclose, assert_array_almost_equal, assert_
import pytest
# decimal accuracy to require between Python and LAPACK/BLAS calculationsaccuracy = 5
# Since numpy.dot likely uses the same blas, use this routine# to check.
def matrixmultiply(a, b): if len(b.shape) == 1: b_is_vector = True b = b[:, newaxis] else: b_is_vector = False assert_(a.shape[1] == b.shape[0]) c = zeros((a.shape[0], b.shape[1]), common_type(a, b)) for i in range(a.shape[0]): for j in range(b.shape[1]): s = 0 for k in range(a.shape[1]): s += a[i, k] * b[k, j] c[i, j] = s if b_is_vector: c = c.reshape((a.shape[0],)) return c
################################################### Test blas ?axpy
class BaseAxpy: ''' Mixin class for axpy tests '''
def test_default_a(self): x = arange(3., dtype=self.dtype) y = arange(3., dtype=x.dtype) real_y = x*1.+y y = self.blas_func(x, y) assert_array_equal(real_y, y)
def test_simple(self): x = arange(3., dtype=self.dtype) y = arange(3., dtype=x.dtype) real_y = x*3.+y y = self.blas_func(x, y, a=3.) assert_array_equal(real_y, y)
def test_x_stride(self): x = arange(6., dtype=self.dtype) y = zeros(3, x.dtype) y = arange(3., dtype=x.dtype) real_y = x[::2]*3.+y y = self.blas_func(x, y, a=3., n=3, incx=2) assert_array_equal(real_y, y)
def test_y_stride(self): x = arange(3., dtype=self.dtype) y = zeros(6, x.dtype) real_y = x*3.+y[::2] y = self.blas_func(x, y, a=3., n=3, incy=2) assert_array_equal(real_y, y[::2])
def test_x_and_y_stride(self): x = arange(12., dtype=self.dtype) y = zeros(6, x.dtype) real_y = x[::4]*3.+y[::2] y = self.blas_func(x, y, a=3., n=3, incx=4, incy=2) assert_array_equal(real_y, y[::2])
def test_x_bad_size(self): x = arange(12., dtype=self.dtype) y = zeros(6, x.dtype) with pytest.raises(Exception, match='failed for 1st keyword'): self.blas_func(x, y, n=4, incx=5)
def test_y_bad_size(self): x = arange(12., dtype=self.dtype) y = zeros(6, x.dtype) with pytest.raises(Exception, match='failed for 1st keyword'): self.blas_func(x, y, n=3, incy=5)
try: class TestSaxpy(BaseAxpy): blas_func = fblas.saxpy dtype = float32except AttributeError: class TestSaxpy: pass
class TestDaxpy(BaseAxpy): blas_func = fblas.daxpy dtype = float64
try: class TestCaxpy(BaseAxpy): blas_func = fblas.caxpy dtype = complex64except AttributeError: class TestCaxpy: pass
class TestZaxpy(BaseAxpy): blas_func = fblas.zaxpy dtype = complex128
################################################### Test blas ?scal
class BaseScal: ''' Mixin class for scal testing '''
def test_simple(self): x = arange(3., dtype=self.dtype) real_x = x*3. x = self.blas_func(3., x) assert_array_equal(real_x, x)
def test_x_stride(self): x = arange(6., dtype=self.dtype) real_x = x.copy() real_x[::2] = x[::2]*array(3., self.dtype) x = self.blas_func(3., x, n=3, incx=2) assert_array_equal(real_x, x)
def test_x_bad_size(self): x = arange(12., dtype=self.dtype) with pytest.raises(Exception, match='failed for 1st keyword'): self.blas_func(2., x, n=4, incx=5)
try: class TestSscal(BaseScal): blas_func = fblas.sscal dtype = float32except AttributeError: class TestSscal: pass
class TestDscal(BaseScal): blas_func = fblas.dscal dtype = float64
try: class TestCscal(BaseScal): blas_func = fblas.cscal dtype = complex64except AttributeError: class TestCscal: pass
class TestZscal(BaseScal): blas_func = fblas.zscal dtype = complex128
################################################### Test blas ?copy
class BaseCopy: ''' Mixin class for copy testing '''
def test_simple(self): x = arange(3., dtype=self.dtype) y = zeros(shape(x), x.dtype) y = self.blas_func(x, y) assert_array_equal(x, y)
def test_x_stride(self): x = arange(6., dtype=self.dtype) y = zeros(3, x.dtype) y = self.blas_func(x, y, n=3, incx=2) assert_array_equal(x[::2], y)
def test_y_stride(self): x = arange(3., dtype=self.dtype) y = zeros(6, x.dtype) y = self.blas_func(x, y, n=3, incy=2) assert_array_equal(x, y[::2])
def test_x_and_y_stride(self): x = arange(12., dtype=self.dtype) y = zeros(6, x.dtype) y = self.blas_func(x, y, n=3, incx=4, incy=2) assert_array_equal(x[::4], y[::2])
def test_x_bad_size(self): x = arange(12., dtype=self.dtype) y = zeros(6, x.dtype) with pytest.raises(Exception, match='failed for 1st keyword'): self.blas_func(x, y, n=4, incx=5)
def test_y_bad_size(self): x = arange(12., dtype=self.dtype) y = zeros(6, x.dtype) with pytest.raises(Exception, match='failed for 1st keyword'): self.blas_func(x, y, n=3, incy=5)
# def test_y_bad_type(self): ## Hmmm. Should this work? What should be the output. # x = arange(3.,dtype=self.dtype) # y = zeros(shape(x)) # self.blas_func(x,y) # assert_array_equal(x,y)
try: class TestScopy(BaseCopy): blas_func = fblas.scopy dtype = float32except AttributeError: class TestScopy: pass
class TestDcopy(BaseCopy): blas_func = fblas.dcopy dtype = float64
try: class TestCcopy(BaseCopy): blas_func = fblas.ccopy dtype = complex64except AttributeError: class TestCcopy: pass
class TestZcopy(BaseCopy): blas_func = fblas.zcopy dtype = complex128
################################################### Test blas ?swap
class BaseSwap: ''' Mixin class for swap tests '''
def test_simple(self): x = arange(3., dtype=self.dtype) y = zeros(shape(x), x.dtype) desired_x = y.copy() desired_y = x.copy() x, y = self.blas_func(x, y) assert_array_equal(desired_x, x) assert_array_equal(desired_y, y)
def test_x_stride(self): x = arange(6., dtype=self.dtype) y = zeros(3, x.dtype) desired_x = y.copy() desired_y = x.copy()[::2] x, y = self.blas_func(x, y, n=3, incx=2) assert_array_equal(desired_x, x[::2]) assert_array_equal(desired_y, y)
def test_y_stride(self): x = arange(3., dtype=self.dtype) y = zeros(6, x.dtype) desired_x = y.copy()[::2] desired_y = x.copy() x, y = self.blas_func(x, y, n=3, incy=2) assert_array_equal(desired_x, x) assert_array_equal(desired_y, y[::2])
def test_x_and_y_stride(self): x = arange(12., dtype=self.dtype) y = zeros(6, x.dtype) desired_x = y.copy()[::2] desired_y = x.copy()[::4] x, y = self.blas_func(x, y, n=3, incx=4, incy=2) assert_array_equal(desired_x, x[::4]) assert_array_equal(desired_y, y[::2])
def test_x_bad_size(self): x = arange(12., dtype=self.dtype) y = zeros(6, x.dtype) with pytest.raises(Exception, match='failed for 1st keyword'): self.blas_func(x, y, n=4, incx=5)
def test_y_bad_size(self): x = arange(12., dtype=self.dtype) y = zeros(6, x.dtype) with pytest.raises(Exception, match='failed for 1st keyword'): self.blas_func(x, y, n=3, incy=5)
try: class TestSswap(BaseSwap): blas_func = fblas.sswap dtype = float32except AttributeError: class TestSswap: pass
class TestDswap(BaseSwap): blas_func = fblas.dswap dtype = float64
try: class TestCswap(BaseSwap): blas_func = fblas.cswap dtype = complex64except AttributeError: class TestCswap: pass
class TestZswap(BaseSwap): blas_func = fblas.zswap dtype = complex128
################################################### Test blas ?gemv# This will be a mess to test all cases.
class BaseGemv: ''' Mixin class for gemv tests '''
def get_data(self, x_stride=1, y_stride=1): mult = array(1, dtype=self.dtype) if self.dtype in [complex64, complex128]: mult = array(1+1j, dtype=self.dtype) from numpy.random import normal, seed seed(1234) alpha = array(1., dtype=self.dtype) * mult beta = array(1., dtype=self.dtype) * mult a = normal(0., 1., (3, 3)).astype(self.dtype) * mult x = arange(shape(a)[0]*x_stride, dtype=self.dtype) * mult y = arange(shape(a)[1]*y_stride, dtype=self.dtype) * mult return alpha, beta, a, x, y
def test_simple(self): alpha, beta, a, x, y = self.get_data() desired_y = alpha*matrixmultiply(a, x)+beta*y y = self.blas_func(alpha, a, x, beta, y) assert_array_almost_equal(desired_y, y)
def test_default_beta_y(self): alpha, beta, a, x, y = self.get_data() desired_y = matrixmultiply(a, x) y = self.blas_func(1, a, x) assert_array_almost_equal(desired_y, y)
def test_simple_transpose(self): alpha, beta, a, x, y = self.get_data() desired_y = alpha*matrixmultiply(transpose(a), x)+beta*y y = self.blas_func(alpha, a, x, beta, y, trans=1) assert_array_almost_equal(desired_y, y)
def test_simple_transpose_conj(self): alpha, beta, a, x, y = self.get_data() desired_y = alpha*matrixmultiply(transpose(conjugate(a)), x)+beta*y y = self.blas_func(alpha, a, x, beta, y, trans=2) assert_array_almost_equal(desired_y, y)
def test_x_stride(self): alpha, beta, a, x, y = self.get_data(x_stride=2) desired_y = alpha*matrixmultiply(a, x[::2])+beta*y y = self.blas_func(alpha, a, x, beta, y, incx=2) assert_array_almost_equal(desired_y, y)
def test_x_stride_transpose(self): alpha, beta, a, x, y = self.get_data(x_stride=2) desired_y = alpha*matrixmultiply(transpose(a), x[::2])+beta*y y = self.blas_func(alpha, a, x, beta, y, trans=1, incx=2) assert_array_almost_equal(desired_y, y)
def test_x_stride_assert(self): # What is the use of this test? alpha, beta, a, x, y = self.get_data(x_stride=2) with pytest.raises(Exception, match='failed for 3rd argument'): y = self.blas_func(1, a, x, 1, y, trans=0, incx=3) with pytest.raises(Exception, match='failed for 3rd argument'): y = self.blas_func(1, a, x, 1, y, trans=1, incx=3)
def test_y_stride(self): alpha, beta, a, x, y = self.get_data(y_stride=2) desired_y = y.copy() desired_y[::2] = alpha*matrixmultiply(a, x)+beta*y[::2] y = self.blas_func(alpha, a, x, beta, y, incy=2) assert_array_almost_equal(desired_y, y)
def test_y_stride_transpose(self): alpha, beta, a, x, y = self.get_data(y_stride=2) desired_y = y.copy() desired_y[::2] = alpha*matrixmultiply(transpose(a), x)+beta*y[::2] y = self.blas_func(alpha, a, x, beta, y, trans=1, incy=2) assert_array_almost_equal(desired_y, y)
def test_y_stride_assert(self): # What is the use of this test? alpha, beta, a, x, y = self.get_data(y_stride=2) with pytest.raises(Exception, match='failed for 2nd keyword'): y = self.blas_func(1, a, x, 1, y, trans=0, incy=3) with pytest.raises(Exception, match='failed for 2nd keyword'): y = self.blas_func(1, a, x, 1, y, trans=1, incy=3)
try: class TestSgemv(BaseGemv): blas_func = fblas.sgemv dtype = float32
def test_sgemv_on_osx(self): from itertools import product import sys import numpy as np
if sys.platform != 'darwin': return
def aligned_array(shape, align, dtype, order='C'): # Make array shape `shape` with aligned at `align` bytes d = dtype() # Make array of correct size with `align` extra bytes N = np.prod(shape) tmp = np.zeros(N * d.nbytes + align, dtype=np.uint8) address = tmp.__array_interface__["data"][0] # Find offset into array giving desired alignment for offset in range(align): if (address + offset) % align == 0: break tmp = tmp[offset:offset+N*d.nbytes].view(dtype=dtype) return tmp.reshape(shape, order=order)
def as_aligned(arr, align, dtype, order='C'): # Copy `arr` into an aligned array with same shape aligned = aligned_array(arr.shape, align, dtype, order) aligned[:] = arr[:] return aligned
def assert_dot_close(A, X, desired): assert_allclose(self.blas_func(1.0, A, X), desired, rtol=1e-5, atol=1e-7)
testdata = product((15, 32), (10000,), (200, 89), ('C', 'F')) for align, m, n, a_order in testdata: A_d = np.random.rand(m, n) X_d = np.random.rand(n) desired = np.dot(A_d, X_d) # Calculation with aligned single precision A_f = as_aligned(A_d, align, np.float32, order=a_order) X_f = as_aligned(X_d, align, np.float32, order=a_order) assert_dot_close(A_f, X_f, desired)
except AttributeError: class TestSgemv: pass
class TestDgemv(BaseGemv): blas_func = fblas.dgemv dtype = float64
try: class TestCgemv(BaseGemv): blas_func = fblas.cgemv dtype = complex64except AttributeError: class TestCgemv: pass
class TestZgemv(BaseGemv): blas_func = fblas.zgemv dtype = complex128
"""##################################################### Test blas ?ger### This will be a mess to test all cases.
class BaseGer: def get_data(self,x_stride=1,y_stride=1): from numpy.random import normal, seed seed(1234) alpha = array(1., dtype = self.dtype) a = normal(0.,1.,(3,3)).astype(self.dtype) x = arange(shape(a)[0]*x_stride,dtype=self.dtype) y = arange(shape(a)[1]*y_stride,dtype=self.dtype) return alpha,a,x,y def test_simple(self): alpha,a,x,y = self.get_data() # transpose takes care of Fortran vs. C(and Python) memory layout desired_a = alpha*transpose(x[:,newaxis]*y) + a self.blas_func(x,y,a) assert_array_almost_equal(desired_a,a) def test_x_stride(self): alpha,a,x,y = self.get_data(x_stride=2) desired_a = alpha*transpose(x[::2,newaxis]*y) + a self.blas_func(x,y,a,incx=2) assert_array_almost_equal(desired_a,a) def test_x_stride_assert(self): alpha,a,x,y = self.get_data(x_stride=2) with pytest.raises(ValueError, match='foo'): self.blas_func(x,y,a,incx=3) def test_y_stride(self): alpha,a,x,y = self.get_data(y_stride=2) desired_a = alpha*transpose(x[:,newaxis]*y[::2]) + a self.blas_func(x,y,a,incy=2) assert_array_almost_equal(desired_a,a)
def test_y_stride_assert(self): alpha,a,x,y = self.get_data(y_stride=2) with pytest.raises(ValueError, match='foo'): self.blas_func(a,x,y,incy=3)
class TestSger(BaseGer): blas_func = fblas.sger dtype = float32class TestDger(BaseGer): blas_func = fblas.dger dtype = float64"""################################################### Test blas ?gerc# This will be a mess to test all cases.
"""class BaseGerComplex(BaseGer): def get_data(self,x_stride=1,y_stride=1): from numpy.random import normal, seed seed(1234) alpha = array(1+1j, dtype = self.dtype) a = normal(0.,1.,(3,3)).astype(self.dtype) a = a + normal(0.,1.,(3,3)) * array(1j, dtype = self.dtype) x = normal(0.,1.,shape(a)[0]*x_stride).astype(self.dtype) x = x + x * array(1j, dtype = self.dtype) y = normal(0.,1.,shape(a)[1]*y_stride).astype(self.dtype) y = y + y * array(1j, dtype = self.dtype) return alpha,a,x,y def test_simple(self): alpha,a,x,y = self.get_data() # transpose takes care of Fortran vs. C(and Python) memory layout a = a * array(0.,dtype = self.dtype) #desired_a = alpha*transpose(x[:,newaxis]*self.transform(y)) + a desired_a = alpha*transpose(x[:,newaxis]*y) + a #self.blas_func(x,y,a,alpha = alpha) fblas.cgeru(x,y,a,alpha = alpha) assert_array_almost_equal(desired_a,a)
#def test_x_stride(self): # alpha,a,x,y = self.get_data(x_stride=2) # desired_a = alpha*transpose(x[::2,newaxis]*self.transform(y)) + a # self.blas_func(x,y,a,incx=2) # assert_array_almost_equal(desired_a,a) #def test_y_stride(self): # alpha,a,x,y = self.get_data(y_stride=2) # desired_a = alpha*transpose(x[:,newaxis]*self.transform(y[::2])) + a # self.blas_func(x,y,a,incy=2) # assert_array_almost_equal(desired_a,a)
class TestCgeru(BaseGerComplex): blas_func = fblas.cgeru dtype = complex64 def transform(self,x): return xclass TestZgeru(BaseGerComplex): blas_func = fblas.zgeru dtype = complex128 def transform(self,x): return x
class TestCgerc(BaseGerComplex): blas_func = fblas.cgerc dtype = complex64 def transform(self,x): return conjugate(x)
class TestZgerc(BaseGerComplex): blas_func = fblas.zgerc dtype = complex128 def transform(self,x): return conjugate(x)"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232# ******************************************************************************# Copyright (C) 2013 Kenneth L. Ho# Redistribution and use in source and binary forms, with or without# modification, are permitted provided that the following conditions are met:## Redistributions of source code must retain the above copyright notice, this# list of conditions and the following disclaimer. Redistributions in binary# form must reproduce the above copyright notice, this list of conditions and# the following disclaimer in the documentation and/or other materials# provided with the distribution.## None of the names of the copyright holders may be used to endorse or# promote products derived from this software without specific prior written# permission.## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE# POSSIBILITY OF SUCH DAMAGE.# ******************************************************************************
import scipy.linalg.interpolative as pymatrixidimport numpy as npfrom scipy.linalg import hilbert, svdvals, normfrom scipy.sparse.linalg import aslinearoperatorfrom scipy.linalg.interpolative import interp_decomp
from numpy.testing import (assert_, assert_allclose, assert_equal, assert_array_equal)import pytestfrom pytest import raises as assert_raises
@pytest.fixture()def eps(): yield 1e-12
@pytest.fixture()def rng(): rng = np.random.default_rng(1718313768084012) yield rng
@pytest.fixture(params=[np.float64, np.complex128])def A(request): # construct Hilbert matrix # set parameters n = 300 yield hilbert(n).astype(request.param)
@pytest.fixture()def L(A): yield aslinearoperator(A)
@pytest.fixture()def rank(A, eps): S = np.linalg.svd(A, compute_uv=False) try: rank = np.nonzero(S < eps)[0][0] except IndexError: rank = A.shape[0] return rank
class TestInterpolativeDecomposition:
@pytest.mark.parametrize( "rand,lin_op", [(False, False), (True, False), (True, True)]) def test_real_id_fixed_precision(self, A, L, eps, rand, lin_op, rng): # Test ID routines on a Hilbert matrix. A_or_L = A if not lin_op else L
k, idx, proj = pymatrixid.interp_decomp(A_or_L, eps, rand=rand, rng=rng) B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) assert_allclose(A, B, rtol=eps, atol=1e-08)
@pytest.mark.parametrize( "rand,lin_op", [(False, False), (True, False), (True, True)]) def test_real_id_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng): k = rank A_or_L = A if not lin_op else L
idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng) B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) assert_allclose(A, B, rtol=eps, atol=1e-08)
@pytest.mark.parametrize("rand,lin_op", [(False, False)]) def test_real_id_skel_and_interp_matrices( self, A, L, eps, rank, rand, lin_op, rng): k = rank A_or_L = A if not lin_op else L
idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng) P = pymatrixid.reconstruct_interp_matrix(idx, proj) B = pymatrixid.reconstruct_skel_matrix(A, k, idx) assert_allclose(B, A[:, idx[:k]], rtol=eps, atol=1e-08) assert_allclose(B @ P, A, rtol=eps, atol=1e-08)
@pytest.mark.parametrize( "rand,lin_op", [(False, False), (True, False), (True, True)]) def test_svd_fixed_precision(self, A, L, eps, rand, lin_op, rng): A_or_L = A if not lin_op else L
U, S, V = pymatrixid.svd(A_or_L, eps, rand=rand, rng=rng) B = U * S @ V.T.conj() assert_allclose(A, B, rtol=eps, atol=1e-08)
@pytest.mark.parametrize( "rand,lin_op", [(False, False), (True, False), (True, True)]) def test_svd_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng): k = rank A_or_L = A if not lin_op else L
U, S, V = pymatrixid.svd(A_or_L, k, rand=rand, rng=rng) B = U * S @ V.T.conj() assert_allclose(A, B, rtol=eps, atol=1e-08)
def test_id_to_svd(self, A, eps, rank): k = rank
idx, proj = pymatrixid.interp_decomp(A, k, rand=False) U, S, V = pymatrixid.id_to_svd(A[:, idx[:k]], idx, proj) B = U * S @ V.T.conj() assert_allclose(A, B, rtol=eps, atol=1e-08)
def test_estimate_spectral_norm(self, A, rng): s = svdvals(A) norm_2_est = pymatrixid.estimate_spectral_norm(A, rng=rng) assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8)
def test_estimate_spectral_norm_diff(self, A, rng): B = A.copy() B[:, 0] *= 1.2 s = svdvals(A - B) norm_2_est = pymatrixid.estimate_spectral_norm_diff(A, B, rng=rng) assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8)
def test_rank_estimates_array(self, A, rng): B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype)
for M in [A, B]: rank_tol = 1e-9 rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol) rank_est = pymatrixid.estimate_rank(M, rank_tol, rng=rng) assert_(rank_est >= rank_np) assert_(rank_est <= rank_np + 10)
def test_rank_estimates_lin_op(self, A, rng): B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype)
for M in [A, B]: ML = aslinearoperator(M) rank_tol = 1e-9 rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol) rank_est = pymatrixid.estimate_rank(ML, rank_tol, rng=rng) assert_(rank_est >= rank_np - 4) assert_(rank_est <= rank_np + 4)
def test_badcall(self): A = hilbert(5).astype(np.float32) with assert_raises(ValueError): pymatrixid.interp_decomp(A, 1e-6, rand=False)
def test_rank_too_large(self): # svd(array, k) should not segfault a = np.ones((4, 3)) with assert_raises(ValueError): pymatrixid.svd(a, 4)
def test_full_rank(self): eps = 1.0e-12
# fixed precision A = np.random.rand(16, 8) k, idx, proj = pymatrixid.interp_decomp(A, eps) assert_equal(k, A.shape[1])
P = pymatrixid.reconstruct_interp_matrix(idx, proj) B = pymatrixid.reconstruct_skel_matrix(A, k, idx) assert_allclose(A, B @ P)
# fixed rank idx, proj = pymatrixid.interp_decomp(A, k)
P = pymatrixid.reconstruct_interp_matrix(idx, proj) B = pymatrixid.reconstruct_skel_matrix(A, k, idx) assert_allclose(A, B @ P)
@pytest.mark.parametrize("dtype", [np.float64, np.complex128]) @pytest.mark.parametrize("rand", [True, False]) @pytest.mark.parametrize("eps", [1, 0.1]) def test_bug_9793(self, dtype, rand, eps): A = np.array([[-1, -1, -1, 0, 0, 0], [0, 0, 0, 1, 1, 1], [1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 1]], dtype=dtype, order="C") B = A.copy() interp_decomp(A.T, eps, rand=rand) assert_array_equal(A, B)
def test_svd_aslinearoperator_shape_check(self): # See gh-issue #22451 rng = np.random.default_rng(1744580941832515) x = rng.uniform(size=[7, 5]) xl = aslinearoperator(x) u, s, v = pymatrixid.svd(xl, 3) assert_equal(u.shape, (7, 3)) assert_equal(s.shape, (3,)) assert_equal(v.shape, (5, 3))
x = rng.uniform(size=[4, 9]) xl = aslinearoperator(x) u, s, v = pymatrixid.svd(xl, 2) assert_equal(u.shape, (4, 2)) assert_equal(s.shape, (2,)) assert_equal(v.shape, (9, 2))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063## Created by: Pearu Peterson, March 2002#""" Test functions for linalg.matfuncs module
"""import functools
import numpy as npfrom numpy import array, identity, dot, sqrtfrom numpy.testing import (assert_array_almost_equal, assert_allclose, assert_, assert_array_less, assert_array_equal, assert_warns)import pytest
import scipy.linalgfrom scipy.linalg import (funm, signm, logm, sqrtm, fractional_matrix_power, expm, expm_frechet, expm_cond, norm, khatri_rao, cosm, sinm, tanm, coshm, sinhm, tanhm)from scipy.linalg import _matfuncs_inv_ssqfrom scipy.linalg._matfuncs import pick_pade_structurefrom scipy.linalg._matfuncs_inv_ssq import LogmExactlySingularWarningimport scipy.linalg._expm_frechet
from scipy.optimize import minimize
def _get_al_mohy_higham_2012_experiment_1(): """ Return the test matrix from Experiment (1) of [1]_.
References ---------- .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012) "Improved Inverse Scaling and Squaring Algorithms for the Matrix Logarithm." SIAM Journal on Scientific Computing, 34 (4). C152-C169. ISSN 1095-7197
""" A = np.array([ [3.2346e-1, 3e4, 3e4, 3e4], [0, 3.0089e-1, 3e4, 3e4], [0, 0, 3.2210e-1, 3e4], [0, 0, 0, 3.0744e-1]], dtype=float) return A
class TestSignM:
def test_nils(self): a = array([[29.2, -24.2, 69.5, 49.8, 7.], [-9.2, 5.2, -18., -16.8, -2.], [-10., 6., -20., -18., -2.], [-9.6, 9.6, -25.5, -15.4, -2.], [9.8, -4.8, 18., 18.2, 2.]]) cr = array([[11.94933333,-2.24533333,15.31733333,21.65333333,-2.24533333], [-3.84266667,0.49866667,-4.59066667,-7.18666667,0.49866667], [-4.08,0.56,-4.92,-7.6,0.56], [-4.03466667,1.04266667,-5.59866667,-7.02666667,1.04266667], [4.15733333,-0.50133333,4.90933333,7.81333333,-0.50133333]]) r = signm(a) assert_array_almost_equal(r,cr)
def test_defective1(self): a = array([[0.0,1,0,0],[1,0,1,0],[0,0,0,1],[0,0,1,0]]) signm(a, disp=False) #XXX: what would be the correct result?
def test_defective2(self): a = array(( [29.2,-24.2,69.5,49.8,7.0], [-9.2,5.2,-18.0,-16.8,-2.0], [-10.0,6.0,-20.0,-18.0,-2.0], [-9.6,9.6,-25.5,-15.4,-2.0], [9.8,-4.8,18.0,18.2,2.0])) signm(a, disp=False) #XXX: what would be the correct result?
def test_defective3(self): a = array([[-2., 25., 0., 0., 0., 0., 0.], [0., -3., 10., 3., 3., 3., 0.], [0., 0., 2., 15., 3., 3., 0.], [0., 0., 0., 0., 15., 3., 0.], [0., 0., 0., 0., 3., 10., 0.], [0., 0., 0., 0., 0., -2., 25.], [0., 0., 0., 0., 0., 0., -3.]]) signm(a, disp=False) #XXX: what would be the correct result?
class TestLogM:
def test_nils(self): a = array([[-2., 25., 0., 0., 0., 0., 0.], [0., -3., 10., 3., 3., 3., 0.], [0., 0., 2., 15., 3., 3., 0.], [0., 0., 0., 0., 15., 3., 0.], [0., 0., 0., 0., 3., 10., 0.], [0., 0., 0., 0., 0., -2., 25.], [0., 0., 0., 0., 0., 0., -3.]]) m = (identity(7)*3.1+0j)-a logm(m, disp=False) #XXX: what would be the correct result?
def test_al_mohy_higham_2012_experiment_1_logm(self): # The logm completes the round trip successfully. # Note that the expm leg of the round trip is badly conditioned. A = _get_al_mohy_higham_2012_experiment_1() A_logm, info = logm(A, disp=False) A_round_trip = expm(A_logm) assert_allclose(A_round_trip, A, rtol=5e-5, atol=1e-14)
def test_al_mohy_higham_2012_experiment_1_funm_log(self): # The raw funm with np.log does not complete the round trip. # Note that the expm leg of the round trip is badly conditioned. A = _get_al_mohy_higham_2012_experiment_1() A_funm_log, info = funm(A, np.log, disp=False) A_round_trip = expm(A_funm_log) assert_(not np.allclose(A_round_trip, A, rtol=1e-5, atol=1e-14))
def test_round_trip_random_float(self): np.random.seed(1234) for n in range(1, 6): M_unscaled = np.random.randn(n, n) for scale in np.logspace(-4, 4, 9): M = M_unscaled * scale
# Eigenvalues are related to the branch cut. W = np.linalg.eigvals(M) err_msg = f'M:{M} eivals:{W}'
# Check sqrtm round trip because it is used within logm. M_sqrtm, info = sqrtm(M, disp=False) M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm) assert_allclose(M_sqrtm_round_trip, M)
# Check logm round trip. M_logm, info = logm(M, disp=False) M_logm_round_trip = expm(M_logm) assert_allclose(M_logm_round_trip, M, err_msg=err_msg)
def test_round_trip_random_complex(self): np.random.seed(1234) for n in range(1, 6): M_unscaled = np.random.randn(n, n) + 1j * np.random.randn(n, n) for scale in np.logspace(-4, 4, 9): M = M_unscaled * scale M_logm, info = logm(M, disp=False) M_round_trip = expm(M_logm) assert_allclose(M_round_trip, M)
def test_logm_type_preservation_and_conversion(self): # The logm matrix function should preserve the type of a matrix # whose eigenvalues are positive with zero imaginary part. # Test this preservation for variously structured matrices. complex_dtype_chars = ('F', 'D', 'G') for matrix_as_list in ( [[1, 0], [0, 1]], [[1, 0], [1, 1]], [[2, 1], [1, 1]], [[2, 3], [1, 2]]):
# check that the spectrum has the expected properties W = scipy.linalg.eigvals(matrix_as_list) assert_(not any(w.imag or w.real < 0 for w in W))
# check float type preservation A = np.array(matrix_as_list, dtype=float) A_logm, info = logm(A, disp=False) assert_(A_logm.dtype.char not in complex_dtype_chars)
# check complex type preservation A = np.array(matrix_as_list, dtype=complex) A_logm, info = logm(A, disp=False) assert_(A_logm.dtype.char in complex_dtype_chars)
# check float->complex type conversion for the matrix negation A = -np.array(matrix_as_list, dtype=float) A_logm, info = logm(A, disp=False) assert_(A_logm.dtype.char in complex_dtype_chars)
def test_complex_spectrum_real_logm(self): # This matrix has complex eigenvalues and real logm. # Its output dtype depends on its input dtype. M = [[1, 1, 2], [2, 1, 1], [1, 2, 1]] for dt in float, complex: X = np.array(M, dtype=dt) w = scipy.linalg.eigvals(X) assert_(1e-2 < np.absolute(w.imag).sum()) Y, info = logm(X, disp=False) assert_(np.issubdtype(Y.dtype, np.inexact)) assert_allclose(expm(Y), X)
def test_real_mixed_sign_spectrum(self): # These matrices have real eigenvalues with mixed signs. # The output logm dtype is complex, regardless of input dtype. for M in ( [[1, 0], [0, -1]], [[0, 1], [1, 0]]): for dt in float, complex: A = np.array(M, dtype=dt) A_logm, info = logm(A, disp=False) assert_(np.issubdtype(A_logm.dtype, np.complexfloating))
@pytest.mark.thread_unsafe def test_exactly_singular(self): A = np.array([[0, 0], [1j, 1j]]) B = np.asarray([[1, 1], [0, 0]]) for M in A, A.T, B, B.T: expected_warning = _matfuncs_inv_ssq.LogmExactlySingularWarning L, info = assert_warns(expected_warning, logm, M, disp=False) E = expm(L) assert_allclose(E, M, atol=1e-14)
@pytest.mark.thread_unsafe def test_nearly_singular(self): M = np.array([[1e-100]]) expected_warning = _matfuncs_inv_ssq.LogmNearlySingularWarning L, info = assert_warns(expected_warning, logm, M, disp=False) E = expm(L) assert_allclose(E, M, atol=1e-14)
def test_opposite_sign_complex_eigenvalues(self): # See gh-6113 E = [[0, 1], [-1, 0]] L = [[0, np.pi*0.5], [-np.pi*0.5, 0]] assert_allclose(expm(L), E, atol=1e-14) assert_allclose(logm(E), L, atol=1e-14) E = [[1j, 4], [0, -1j]] L = [[1j*np.pi*0.5, 2*np.pi], [0, -1j*np.pi*0.5]] assert_allclose(expm(L), E, atol=1e-14) assert_allclose(logm(E), L, atol=1e-14) E = [[1j, 0], [0, -1j]] L = [[1j*np.pi*0.5, 0], [0, -1j*np.pi*0.5]] assert_allclose(expm(L), E, atol=1e-14) assert_allclose(logm(E), L, atol=1e-14)
def test_readonly(self): n = 5 a = np.ones((n, n)) + np.identity(n) a.flags.writeable = False logm(a)
@pytest.mark.xfail(reason="ValueError: attempt to get argmax of an empty sequence") @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt): a = np.empty((0, 0), dtype=dt) log_a = logm(a) a0 = np.eye(2, dtype=dt) log_a0 = logm(a0)
assert log_a.shape == (0, 0) assert log_a.dtype == log_a0.dtype
@pytest.mark.thread_unsafe @pytest.mark.parametrize('dtype', [int, float, np.float32, complex, np.complex64]) def test_no_ZeroDivisionError(self, dtype): # gh-17136 reported inconsistent behavior in `logm` depending on input dtype: # sometimes it raised an error, and sometimes it printed a warning message. # check that this is resolved and that the warning is emitted properly. with (pytest.warns(RuntimeWarning, match="logm result may be inaccurate"), pytest.warns(LogmExactlySingularWarning)): logm(np.zeros((2, 2), dtype=dtype))
class TestSqrtM: def test_round_trip_random_float(self): rng = np.random.RandomState(1234) for n in range(1, 6): M_unscaled = rng.randn(n, n) for scale in np.logspace(-4, 4, 9): M = M_unscaled * scale M_sqrtm, info = sqrtm(M, disp=False) M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm) assert_allclose(M_sqrtm_round_trip, M)
def test_round_trip_random_complex(self): rng = np.random.RandomState(1234) for n in range(1, 6): M_unscaled = rng.randn(n, n) + 1j * rng.randn(n, n) for scale in np.logspace(-4, 4, 9): M = M_unscaled * scale M_sqrtm, info = sqrtm(M, disp=False) M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm) assert_allclose(M_sqrtm_round_trip, M)
def test_bad(self): # See https://web.archive.org/web/20051220232650/http://www.maths.man.ac.uk/~nareports/narep336.ps.gz e = 2**-5 se = sqrt(e) a = array([[1.0,0,0,1], [0,e,0,0], [0,0,e,0], [0,0,0,1]]) sa = array([[1,0,0,0.5], [0,se,0,0], [0,0,se,0], [0,0,0,1]]) n = a.shape[0] assert_array_almost_equal(dot(sa,sa),a) # Check default sqrtm. esa = sqrtm(a, disp=False, blocksize=n)[0] assert_array_almost_equal(dot(esa,esa),a) # Check sqrtm with 2x2 blocks. esa = sqrtm(a, disp=False, blocksize=2)[0] assert_array_almost_equal(dot(esa,esa),a)
def test_sqrtm_type_preservation_and_conversion(self): # The sqrtm matrix function should preserve the type of a matrix # whose eigenvalues are nonnegative with zero imaginary part. # Test this preservation for variously structured matrices. complex_dtype_chars = ('F', 'D', 'G') for matrix_as_list in ( [[1, 0], [0, 1]], [[1, 0], [1, 1]], [[2, 1], [1, 1]], [[2, 3], [1, 2]], [[1, 1], [1, 1]]):
# check that the spectrum has the expected properties W = scipy.linalg.eigvals(matrix_as_list) assert_(not any(w.imag or w.real < 0 for w in W))
# check float type preservation A = np.array(matrix_as_list, dtype=float) A_sqrtm, info = sqrtm(A, disp=False) assert_(A_sqrtm.dtype.char not in complex_dtype_chars)
# check complex type preservation A = np.array(matrix_as_list, dtype=complex) A_sqrtm, info = sqrtm(A, disp=False) assert_(A_sqrtm.dtype.char in complex_dtype_chars)
# check float->complex type conversion for the matrix negation A = -np.array(matrix_as_list, dtype=float) A_sqrtm, info = sqrtm(A, disp=False) assert_(A_sqrtm.dtype.char in complex_dtype_chars)
def test_sqrtm_type_conversion_mixed_sign_or_complex_spectrum(self): complex_dtype_chars = ('F', 'D', 'G') for matrix_as_list in ( [[1, 0], [0, -1]], [[0, 1], [1, 0]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]):
# check that the spectrum has the expected properties W = scipy.linalg.eigvals(matrix_as_list) assert_(any(w.imag or w.real < 0 for w in W))
# check complex->complex A = np.array(matrix_as_list, dtype=complex) A_sqrtm, info = sqrtm(A, disp=False) assert_(A_sqrtm.dtype.char in complex_dtype_chars)
# check float->complex A = np.array(matrix_as_list, dtype=float) A_sqrtm, info = sqrtm(A, disp=False) assert_(A_sqrtm.dtype.char in complex_dtype_chars)
def test_blocksizes(self): # Make sure I do not goof up the blocksizes when they do not divide n. np.random.seed(1234) for n in range(1, 8): A = np.random.rand(n, n) + 1j*np.random.randn(n, n) A_sqrtm_default, info = sqrtm(A, disp=False, blocksize=n) assert_allclose(A, np.linalg.matrix_power(A_sqrtm_default, 2)) for blocksize in range(1, 10): A_sqrtm_new, info = sqrtm(A, disp=False, blocksize=blocksize) assert_allclose(A_sqrtm_default, A_sqrtm_new)
def test_al_mohy_higham_2012_experiment_1(self): # Matrix square root of a tricky upper triangular matrix. A = _get_al_mohy_higham_2012_experiment_1() A_sqrtm, info = sqrtm(A, disp=False) A_round_trip = A_sqrtm.dot(A_sqrtm) assert_allclose(A_round_trip, A, rtol=1e-5) assert_allclose(np.tril(A_round_trip), np.tril(A))
def test_strict_upper_triangular(self): # This matrix has no square root. for dt in int, float: A = np.array([ [0, 3, 0, 0], [0, 0, 3, 0], [0, 0, 0, 3], [0, 0, 0, 0]], dtype=dt) A_sqrtm, info = sqrtm(A, disp=False) assert_(np.isnan(A_sqrtm).all())
def test_weird_matrix(self): # The square root of matrix B exists. for dt in int, float: A = np.array([ [0, 0, 1], [0, 0, 0], [0, 1, 0]], dtype=dt) B = np.array([ [0, 1, 0], [0, 0, 0], [0, 0, 0]], dtype=dt) assert_array_equal(B, A.dot(A))
# But scipy sqrtm is not clever enough to find it. B_sqrtm, info = sqrtm(B, disp=False) assert_(np.isnan(B_sqrtm).all())
def test_disp(self): np.random.seed(1234)
A = np.random.rand(3, 3) B = sqrtm(A, disp=True) assert_allclose(B.dot(B), A)
def test_opposite_sign_complex_eigenvalues(self): M = [[2j, 4], [0, -2j]] R = [[1+1j, 2], [0, 1-1j]] assert_allclose(np.dot(R, R), M, atol=1e-14) assert_allclose(sqrtm(M), R, atol=1e-14)
def test_gh4866(self): M = np.array([[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 1]]) R = np.array([[sqrt(0.5), 0, 0, sqrt(0.5)], [0, 0, 0, 0], [0, 0, 0, 0], [sqrt(0.5), 0, 0, sqrt(0.5)]]) assert_allclose(np.dot(R, R), M, atol=1e-14) assert_allclose(sqrtm(M), R, atol=1e-14)
def test_gh5336(self): M = np.diag([2, 1, 0]) R = np.diag([sqrt(2), 1, 0]) assert_allclose(np.dot(R, R), M, atol=1e-14) assert_allclose(sqrtm(M), R, atol=1e-14)
def test_gh7839(self): M = np.zeros((2, 2)) R = np.zeros((2, 2)) assert_allclose(np.dot(R, R), M, atol=1e-14) assert_allclose(sqrtm(M), R, atol=1e-14)
@pytest.mark.xfail(reason="failing on macOS after gh-20212") def test_gh17918(self): M = np.empty((19, 19)) M.fill(0.94) np.fill_diagonal(M, 1) assert np.isrealobj(sqrtm(M))
def test_data_size_preservation_uint_in_float_out(self): M = np.zeros((10, 10), dtype=np.uint8) assert sqrtm(M).dtype == np.float64 M = np.zeros((10, 10), dtype=np.uint16) assert sqrtm(M).dtype == np.float64 M = np.zeros((10, 10), dtype=np.uint32) assert sqrtm(M).dtype == np.float64 M = np.zeros((10, 10), dtype=np.uint64) assert sqrtm(M).dtype == np.float64
def test_data_size_preservation_int_in_float_out(self): M = np.zeros((10, 10), dtype=np.int8) assert sqrtm(M).dtype == np.float64 M = np.zeros((10, 10), dtype=np.int16) assert sqrtm(M).dtype == np.float64 M = np.zeros((10, 10), dtype=np.int32) assert sqrtm(M).dtype == np.float64 M = np.zeros((10, 10), dtype=np.int64) assert sqrtm(M).dtype == np.float64
def test_data_size_preservation_int_in_comp_out(self): M = np.array([[2, 4], [0, -2]], dtype=np.int8) assert sqrtm(M).dtype == np.complex128 M = np.array([[2, 4], [0, -2]], dtype=np.int16) assert sqrtm(M).dtype == np.complex128 M = np.array([[2, 4], [0, -2]], dtype=np.int32) assert sqrtm(M).dtype == np.complex128 M = np.array([[2, 4], [0, -2]], dtype=np.int64) assert sqrtm(M).dtype == np.complex128
def test_data_size_preservation_float_in_float_out(self): M = np.zeros((10, 10), dtype=np.float16) assert sqrtm(M).dtype == np.float32 M = np.zeros((10, 10), dtype=np.float32) assert sqrtm(M).dtype == np.float32 M = np.zeros((10, 10), dtype=np.float64) assert sqrtm(M).dtype == np.float64 if hasattr(np, 'float128'): M = np.zeros((10, 10), dtype=np.float128) assert sqrtm(M).dtype == np.float64
def test_data_size_preservation_float_in_comp_out(self): M = np.array([[2, 4], [0, -2]], dtype=np.float16) assert sqrtm(M).dtype == np.complex64 M = np.array([[2, 4], [0, -2]], dtype=np.float32) assert sqrtm(M).dtype == np.complex64 M = np.array([[2, 4], [0, -2]], dtype=np.float64) assert sqrtm(M).dtype == np.complex128 if hasattr(np, 'float128') and hasattr(np, 'complex256'): M = np.array([[2, 4], [0, -2]], dtype=np.float128) assert sqrtm(M).dtype == np.complex128
def test_data_size_preservation_comp_in_comp_out(self): M = np.array([[2j, 4], [0, -2j]], dtype=np.complex64) assert sqrtm(M).dtype == np.complex64 M = np.array([[2j, 4], [0, -2j]], dtype=np.complex128) assert sqrtm(M).dtype == np.complex128 if hasattr(np, 'complex256'): M = np.array([[2j, 4], [0, -2j]], dtype=np.complex256) assert sqrtm(M).dtype == np.complex128
@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) def test_empty(self, dt): a = np.empty((0, 0), dtype=dt) s = sqrtm(a) a0 = np.eye(2, dtype=dt) s0 = sqrtm(a0)
assert s.shape == (0, 0) assert s.dtype == s0.dtype
class TestFractionalMatrixPower: def test_round_trip_random_complex(self): np.random.seed(1234) for p in range(1, 5): for n in range(1, 5): M_unscaled = np.random.randn(n, n) + 1j * np.random.randn(n, n) for scale in np.logspace(-4, 4, 9): M = M_unscaled * scale M_root = fractional_matrix_power(M, 1/p) M_round_trip = np.linalg.matrix_power(M_root, p) assert_allclose(M_round_trip, M)
def test_round_trip_random_float(self): # This test is more annoying because it can hit the branch cut; # this happens when the matrix has an eigenvalue # with no imaginary component and with a real negative component, # and it means that the principal branch does not exist. np.random.seed(1234) for p in range(1, 5): for n in range(1, 5): M_unscaled = np.random.randn(n, n) for scale in np.logspace(-4, 4, 9): M = M_unscaled * scale M_root = fractional_matrix_power(M, 1/p) M_round_trip = np.linalg.matrix_power(M_root, p) assert_allclose(M_round_trip, M)
def test_larger_abs_fractional_matrix_powers(self): np.random.seed(1234) for n in (2, 3, 5): for i in range(10): M = np.random.randn(n, n) + 1j * np.random.randn(n, n) M_one_fifth = fractional_matrix_power(M, 0.2) # Test the round trip. M_round_trip = np.linalg.matrix_power(M_one_fifth, 5) assert_allclose(M, M_round_trip) # Test a large abs fractional power. X = fractional_matrix_power(M, -5.4) Y = np.linalg.matrix_power(M_one_fifth, -27) assert_allclose(X, Y) # Test another large abs fractional power. X = fractional_matrix_power(M, 3.8) Y = np.linalg.matrix_power(M_one_fifth, 19) assert_allclose(X, Y)
def test_random_matrices_and_powers(self): # Each independent iteration of this fuzz test picks random parameters. # It tries to hit some edge cases. rng = np.random.default_rng(1726500458620605) nsamples = 20 for i in range(nsamples): # Sample a matrix size and a random real power. n = rng.integers(1, 5) p = rng.random()
# Sample a random real or complex matrix. matrix_scale = np.exp(rng.integers(-4, 5)) A = rng.random(size=[n, n]) if [True, False][rng.choice(2)]: A = A + 1j * rng.random(size=[n, n]) A = A * matrix_scale
# Check a couple of analytically equivalent ways # to compute the fractional matrix power. # These can be compared because they both use the principal branch. A_power = fractional_matrix_power(A, p) A_logm, info = logm(A, disp=False) A_power_expm_logm = expm(A_logm * p) assert_allclose(A_power, A_power_expm_logm)
def test_al_mohy_higham_2012_experiment_1(self): # Fractional powers of a tricky upper triangular matrix. A = _get_al_mohy_higham_2012_experiment_1()
# Test remainder matrix power. A_funm_sqrt, info = funm(A, np.sqrt, disp=False) A_sqrtm, info = sqrtm(A, disp=False) A_rem_power = _matfuncs_inv_ssq._remainder_matrix_power(A, 0.5) A_power = fractional_matrix_power(A, 0.5) assert_allclose(A_rem_power, A_power, rtol=1e-11) assert_allclose(A_sqrtm, A_power) assert_allclose(A_sqrtm, A_funm_sqrt)
# Test more fractional powers. for p in (1/2, 5/3): A_power = fractional_matrix_power(A, p) A_round_trip = fractional_matrix_power(A_power, 1/p) assert_allclose(A_round_trip, A, rtol=1e-2) assert_allclose(np.tril(A_round_trip, 1), np.tril(A, 1))
def test_briggs_helper_function(self): np.random.seed(1234) for a in np.random.randn(10) + 1j * np.random.randn(10): for k in range(5): x_observed = _matfuncs_inv_ssq._briggs_helper_function(a, k) x_expected = a ** np.exp2(-k) - 1 assert_allclose(x_observed, x_expected)
def test_type_preservation_and_conversion(self): # The fractional_matrix_power matrix function should preserve # the type of a matrix whose eigenvalues # are positive with zero imaginary part. # Test this preservation for variously structured matrices. complex_dtype_chars = ('F', 'D', 'G') for matrix_as_list in ( [[1, 0], [0, 1]], [[1, 0], [1, 1]], [[2, 1], [1, 1]], [[2, 3], [1, 2]]):
# check that the spectrum has the expected properties W = scipy.linalg.eigvals(matrix_as_list) assert_(not any(w.imag or w.real < 0 for w in W))
# Check various positive and negative powers # with absolute values bigger and smaller than 1. for p in (-2.4, -0.9, 0.2, 3.3):
# check float type preservation A = np.array(matrix_as_list, dtype=float) A_power = fractional_matrix_power(A, p) assert_(A_power.dtype.char not in complex_dtype_chars)
# check complex type preservation A = np.array(matrix_as_list, dtype=complex) A_power = fractional_matrix_power(A, p) assert_(A_power.dtype.char in complex_dtype_chars)
# check float->complex for the matrix negation A = -np.array(matrix_as_list, dtype=float) A_power = fractional_matrix_power(A, p) assert_(A_power.dtype.char in complex_dtype_chars)
def test_type_conversion_mixed_sign_or_complex_spectrum(self): complex_dtype_chars = ('F', 'D', 'G') for matrix_as_list in ( [[1, 0], [0, -1]], [[0, 1], [1, 0]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]):
# check that the spectrum has the expected properties W = scipy.linalg.eigvals(matrix_as_list) assert_(any(w.imag or w.real < 0 for w in W))
# Check various positive and negative powers # with absolute values bigger and smaller than 1. for p in (-2.4, -0.9, 0.2, 3.3):
# check complex->complex A = np.array(matrix_as_list, dtype=complex) A_power = fractional_matrix_power(A, p) assert_(A_power.dtype.char in complex_dtype_chars)
# check float->complex A = np.array(matrix_as_list, dtype=float) A_power = fractional_matrix_power(A, p) assert_(A_power.dtype.char in complex_dtype_chars)
@pytest.mark.xfail(reason='Too unstable across LAPACKs.') def test_singular(self): # Negative fractional powers do not work with singular matrices. for matrix_as_list in ( [[0, 0], [0, 0]], [[1, 1], [1, 1]], [[1, 2], [3, 6]], [[0, 0, 0], [0, 1, 1], [0, -1, 1]]):
# Check fractional powers both for float and for complex types. for newtype in (float, complex): A = np.array(matrix_as_list, dtype=newtype) for p in (-0.7, -0.9, -2.4, -1.3): A_power = fractional_matrix_power(A, p) assert_(np.isnan(A_power).all()) for p in (0.2, 1.43): A_power = fractional_matrix_power(A, p) A_round_trip = fractional_matrix_power(A_power, 1/p) assert_allclose(A_round_trip, A)
def test_opposite_sign_complex_eigenvalues(self): M = [[2j, 4], [0, -2j]] R = [[1+1j, 2], [0, 1-1j]] assert_allclose(np.dot(R, R), M, atol=1e-14) assert_allclose(fractional_matrix_power(M, 0.5), R, atol=1e-14)
class TestExpM: def test_zero(self): a = array([[0.,0],[0,0]]) assert_array_almost_equal(expm(a),[[1,0],[0,1]])
def test_single_elt(self): elt = expm(1) assert_allclose(elt, np.array([[np.e]]))
@pytest.mark.parametrize('func', [expm, cosm, sinm, tanm, coshm, sinhm, tanhm]) @pytest.mark.parametrize('dt',[int, float, np.float32, complex, np.complex64]) @pytest.mark.parametrize('shape', [(0, 0), (1, 1)]) def test_small_empty_matrix_input(self, func, dt, shape): # regression test for gh-11082 / gh-20372 - test behavior of expm # and related functions for small and zero-sized arrays. A = np.zeros(shape, dtype=dt) A0 = np.zeros((10, 10), dtype=dt) result = func(A) result0 = func(A0) assert result.shape == shape assert result.dtype == result0.dtype
def test_2x2_input(self): E = np.e a = array([[1, 4], [1, 1]]) aa = (E**4 + 1)/(2*E) bb = (E**4 - 1)/E assert_allclose(expm(a), array([[aa, bb], [bb/4, aa]])) assert expm(a.astype(np.complex64)).dtype.char == 'F' assert expm(a.astype(np.float32)).dtype.char == 'f'
def test_nx2x2_input(self): E = np.e # These are integer matrices with integer eigenvalues a = np.array([[[1, 4], [1, 1]], [[1, 3], [1, -1]], [[1, 3], [4, 5]], [[1, 3], [5, 3]], [[4, 5], [-3, -4]]], order='F') # Exact results are computed symbolically a_res = np.array([ [[(E**4+1)/(2*E), (E**4-1)/E], [(E**4-1)/4/E, (E**4+1)/(2*E)]], [[1/(4*E**2)+(3*E**2)/4, (3*E**2)/4-3/(4*E**2)], [E**2/4-1/(4*E**2), 3/(4*E**2)+E**2/4]], [[3/(4*E)+E**7/4, -3/(8*E)+(3*E**7)/8], [-1/(2*E)+E**7/2, 1/(4*E)+(3*E**7)/4]], [[5/(8*E**2)+(3*E**6)/8, -3/(8*E**2)+(3*E**6)/8], [-5/(8*E**2)+(5*E**6)/8, 3/(8*E**2)+(5*E**6)/8]], [[-3/(2*E)+(5*E)/2, -5/(2*E)+(5*E)/2], [3/(2*E)-(3*E)/2, 5/(2*E)-(3*E)/2]] ]) assert_allclose(expm(a), a_res)
def test_readonly(self): n = 7 a = np.ones((n, n)) a.flags.writeable = False expm(a)
@pytest.mark.thread_unsafe @pytest.mark.fail_slow(5) def test_gh18086(self): A = np.zeros((400, 400), dtype=float) rng = np.random.default_rng(100) i = rng.integers(0, 399, 500) j = rng.integers(0, 399, 500) A[i, j] = rng.random(500) # Problem appears when m = 9 Am = np.empty((5, 400, 400), dtype=float) Am[0] = A.copy() m, s = pick_pade_structure(Am) assert m == 9 # Check that result is accurate first_res = expm(A) np.testing.assert_array_almost_equal(logm(first_res), A) # Check that result is consistent for i in range(5): next_res = expm(A) np.testing.assert_array_almost_equal(first_res, next_res)
class TestExpmFrechet:
def test_expm_frechet(self): # a test of the basic functionality M = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [0, 0, 1, 2], [0, 0, 5, 6], ], dtype=float) A = np.array([ [1, 2], [5, 6], ], dtype=float) E = np.array([ [3, 4], [7, 8], ], dtype=float) expected_expm = scipy.linalg.expm(A) expected_frechet = scipy.linalg.expm(M)[:2, 2:] for kwargs in ({}, {'method':'SPS'}, {'method':'blockEnlarge'}): observed_expm, observed_frechet = expm_frechet(A, E, **kwargs) assert_allclose(expected_expm, observed_expm) assert_allclose(expected_frechet, observed_frechet)
def test_small_norm_expm_frechet(self): # methodically test matrices with a range of norms, for better coverage M_original = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [0, 0, 1, 2], [0, 0, 5, 6], ], dtype=float) A_original = np.array([ [1, 2], [5, 6], ], dtype=float) E_original = np.array([ [3, 4], [7, 8], ], dtype=float) A_original_norm_1 = scipy.linalg.norm(A_original, 1) selected_m_list = [1, 3, 5, 7, 9, 11, 13, 15] m_neighbor_pairs = zip(selected_m_list[:-1], selected_m_list[1:]) for ma, mb in m_neighbor_pairs: ell_a = scipy.linalg._expm_frechet.ell_table_61[ma] ell_b = scipy.linalg._expm_frechet.ell_table_61[mb] target_norm_1 = 0.5 * (ell_a + ell_b) scale = target_norm_1 / A_original_norm_1 M = scale * M_original A = scale * A_original E = scale * E_original expected_expm = scipy.linalg.expm(A) expected_frechet = scipy.linalg.expm(M)[:2, 2:] observed_expm, observed_frechet = expm_frechet(A, E) assert_allclose(expected_expm, observed_expm) assert_allclose(expected_frechet, observed_frechet)
def test_fuzz(self): rng = np.random.default_rng(1726500908359153) # try a bunch of crazy inputs rfuncs = ( np.random.uniform, np.random.normal, np.random.standard_cauchy, np.random.exponential) ntests = 100 for i in range(ntests): rfunc = rfuncs[rng.choice(4)] target_norm_1 = rng.exponential() n = rng.integers(2, 16) A_original = rfunc(size=(n,n)) E_original = rfunc(size=(n,n)) A_original_norm_1 = scipy.linalg.norm(A_original, 1) scale = target_norm_1 / A_original_norm_1 A = scale * A_original E = scale * E_original M = np.vstack([ np.hstack([A, E]), np.hstack([np.zeros_like(A), A])]) expected_expm = scipy.linalg.expm(A) expected_frechet = scipy.linalg.expm(M)[:n, n:] observed_expm, observed_frechet = expm_frechet(A, E) assert_allclose(expected_expm, observed_expm, atol=5e-8) assert_allclose(expected_frechet, observed_frechet, atol=1e-7)
def test_problematic_matrix(self): # this test case uncovered a bug which has since been fixed A = np.array([ [1.50591997, 1.93537998], [0.41203263, 0.23443516], ], dtype=float) E = np.array([ [1.87864034, 2.07055038], [1.34102727, 0.67341123], ], dtype=float) scipy.linalg.norm(A, 1) sps_expm, sps_frechet = expm_frechet( A, E, method='SPS') blockEnlarge_expm, blockEnlarge_frechet = expm_frechet( A, E, method='blockEnlarge') assert_allclose(sps_expm, blockEnlarge_expm) assert_allclose(sps_frechet, blockEnlarge_frechet)
@pytest.mark.slow @pytest.mark.skip(reason='this test is deliberately slow') def test_medium_matrix(self): # profile this to see the speed difference n = 1000 A = np.random.exponential(size=(n, n)) E = np.random.exponential(size=(n, n)) sps_expm, sps_frechet = expm_frechet( A, E, method='SPS') blockEnlarge_expm, blockEnlarge_frechet = expm_frechet( A, E, method='blockEnlarge') assert_allclose(sps_expm, blockEnlarge_expm) assert_allclose(sps_frechet, blockEnlarge_frechet)
def _help_expm_cond_search(A, A_norm, X, X_norm, eps, p): p = np.reshape(p, A.shape) p_norm = norm(p) perturbation = eps * p * (A_norm / p_norm) X_prime = expm(A + perturbation) scaled_relative_error = norm(X_prime - X) / (X_norm * eps) return -scaled_relative_error
def _normalized_like(A, B): return A * (scipy.linalg.norm(B) / scipy.linalg.norm(A))
def _relative_error(f, A, perturbation): X = f(A) X_prime = f(A + perturbation) return norm(X_prime - X) / norm(X)
class TestExpmConditionNumber: def test_expm_cond_smoke(self): np.random.seed(1234) for n in range(1, 4): A = np.random.randn(n, n) kappa = expm_cond(A) assert_array_less(0, kappa)
def test_expm_bad_condition_number(self): A = np.array([ [-1.128679820, 9.614183771e4, -4.524855739e9, 2.924969411e14], [0, -1.201010529, 9.634696872e4, -4.681048289e9], [0, 0, -1.132893222, 9.532491830e4], [0, 0, 0, -1.179475332], ]) kappa = expm_cond(A) assert_array_less(1e36, kappa)
def test_univariate(self): np.random.seed(12345) for x in np.linspace(-5, 5, num=11): A = np.array([[x]]) assert_allclose(expm_cond(A), abs(x)) for x in np.logspace(-2, 2, num=11): A = np.array([[x]]) assert_allclose(expm_cond(A), abs(x)) for i in range(10): A = np.random.randn(1, 1) assert_allclose(expm_cond(A), np.absolute(A)[0, 0])
@pytest.mark.slow def test_expm_cond_fuzz(self): rng = np.random.RandomState(12345) eps = 1e-5 nsamples = 10 for i in range(nsamples): n = rng.randint(2, 5) A = rng.randn(n, n) A_norm = scipy.linalg.norm(A) X = expm(A) X_norm = scipy.linalg.norm(X) kappa = expm_cond(A)
# Look for the small perturbation that gives the greatest # relative error. f = functools.partial(_help_expm_cond_search, A, A_norm, X, X_norm, eps) guess = np.ones(n*n) out = minimize(f, guess, method='L-BFGS-B') xopt = out.x yopt = f(xopt) p_best = eps * _normalized_like(np.reshape(xopt, A.shape), A) p_best_relerr = _relative_error(expm, A, p_best) assert_allclose(p_best_relerr, -yopt * eps)
# Check that the identified perturbation indeed gives greater # relative error than random perturbations with similar norms. for j in range(5): p_rand = eps * _normalized_like(rng.randn(*A.shape), A) assert_allclose(norm(p_best), norm(p_rand)) p_rand_relerr = _relative_error(expm, A, p_rand) assert_array_less(p_rand_relerr, p_best_relerr)
# The greatest relative error should not be much greater than # eps times the condition number kappa. # In the limit as eps approaches zero it should never be greater. assert_array_less(p_best_relerr, (1 + 2*eps) * eps * kappa)
class TestKhatriRao:
def test_basic(self): a = khatri_rao(array([[1, 2], [3, 4]]), array([[5, 6], [7, 8]]))
assert_array_equal(a, array([[5, 12], [7, 16], [15, 24], [21, 32]]))
b = khatri_rao(np.empty([2, 2]), np.empty([2, 2])) assert_array_equal(b.shape, (4, 2))
def test_number_of_columns_equality(self): with pytest.raises(ValueError): a = array([[1, 2, 3], [4, 5, 6]]) b = array([[1, 2], [3, 4]]) khatri_rao(a, b)
def test_to_assure_2d_array(self): with pytest.raises(ValueError): # both arrays are 1-D a = array([1, 2, 3]) b = array([4, 5, 6]) khatri_rao(a, b)
with pytest.raises(ValueError): # first array is 1-D a = array([1, 2, 3]) b = array([ [1, 2, 3], [4, 5, 6] ]) khatri_rao(a, b)
with pytest.raises(ValueError): # second array is 1-D a = array([ [1, 2, 3], [7, 8, 9] ]) b = array([4, 5, 6]) khatri_rao(a, b)
def test_equality_of_two_equations(self): a = array([[1, 2], [3, 4]]) b = array([[5, 6], [7, 8]])
res1 = khatri_rao(a, b) res2 = np.vstack([np.kron(a[:, k], b[:, k]) for k in range(b.shape[1])]).T
assert_array_equal(res1, res2)
def test_empty(self): a = np.empty((0, 2)) b = np.empty((3, 2)) res = khatri_rao(a, b) assert_allclose(res, np.empty((0, 2)))
a = np.empty((3, 0)) b = np.empty((5, 0)) res = khatri_rao(a, b) assert_allclose(res, np.empty((15, 0)))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""Test functions for linalg.matmul_toeplitz function"""
import numpy as npfrom scipy.linalg import toeplitz, matmul_toeplitz
from pytest import raises as assert_raisesfrom numpy.testing import assert_allclose
class TestMatmulToeplitz:
def setup_method(self): self.rng = np.random.RandomState(42) self.tolerance = 1.5e-13
def test_real(self): cases = []
n = 1 c = self.rng.normal(size=n) r = self.rng.normal(size=n) x = self.rng.normal(size=(n, 1)) cases.append((x, c, r, False))
n = 2 c = self.rng.normal(size=n) r = self.rng.normal(size=n) x = self.rng.normal(size=(n, 1)) cases.append((x, c, r, False))
n = 101 c = self.rng.normal(size=n) r = self.rng.normal(size=n) x = self.rng.normal(size=(n, 1)) cases.append((x, c, r, True))
n = 1000 c = self.rng.normal(size=n) r = self.rng.normal(size=n) x = self.rng.normal(size=(n, 1)) cases.append((x, c, r, False))
n = 100 c = self.rng.normal(size=n) r = self.rng.normal(size=n) x = self.rng.normal(size=(n, self.rng.randint(1, 10))) cases.append((x, c, r, False))
n = 100 c = self.rng.normal(size=(n, 1)) r = self.rng.normal(size=(n, 1)) x = self.rng.normal(size=(n, self.rng.randint(1, 10))) cases.append((x, c, r, True))
n = 100 c = self.rng.normal(size=(n, 1)) r = None x = self.rng.normal(size=(n, self.rng.randint(1, 10))) cases.append((x, c, r, True, -1))
n = 100 c = self.rng.normal(size=(n, 1)) r = None x = self.rng.normal(size=n) cases.append((x, c, r, False))
n = 101 c = self.rng.normal(size=n) r = self.rng.normal(size=n-27) x = self.rng.normal(size=(n-27, 1)) cases.append((x, c, r, True))
n = 100 c = self.rng.normal(size=n) r = self.rng.normal(size=n//4) x = self.rng.normal(size=(n//4, self.rng.randint(1, 10))) cases.append((x, c, r, True))
[self.do(*i) for i in cases]
def test_complex(self): n = 127 c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j r = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j x = self.rng.normal(size=(n, 3)) + self.rng.normal(size=(n, 3))*1j self.do(x, c, r, False)
n = 100 c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j r = self.rng.normal(size=(n//2, 1)) +\ self.rng.normal(size=(n//2, 1))*1j x = self.rng.normal(size=(n//2, 3)) +\ self.rng.normal(size=(n//2, 3))*1j self.do(x, c, r, False)
def test_empty(self): c = [] r = [] x = [] self.do(x, c, r, False)
x = np.empty((0, 0)) self.do(x, c, r, False)
def test_exceptions(self):
n = 100 c = self.rng.normal(size=n) r = self.rng.normal(size=2*n) x = self.rng.normal(size=n) assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
n = 100 c = self.rng.normal(size=n) r = self.rng.normal(size=n) x = self.rng.normal(size=n-1) assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
n = 100 c = self.rng.normal(size=n) r = self.rng.normal(size=n//2) x = self.rng.normal(size=n//2-1) assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
# For toeplitz matrices, matmul_toeplitz() should be equivalent to @. def do(self, x, c, r=None, check_finite=False, workers=None): c = np.ravel(c) if r is None: actual = matmul_toeplitz(c, x, check_finite, workers) else: r = np.ravel(r) actual = matmul_toeplitz((c, r), x, check_finite) desired = toeplitz(c, r) @ x assert_allclose(actual, desired, rtol=self.tolerance, atol=self.tolerance)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221from itertools import product, permutations
import numpy as npimport pytestfrom numpy.testing import assert_array_less, assert_allclosefrom pytest import raises as assert_raises
from scipy.linalg import inv, eigh, norm, svdfrom scipy.linalg import orthogonal_procrustesfrom scipy.sparse._sputils import matrix
def test_orthogonal_procrustes_ndim_too_large(): rng = np.random.RandomState(1234) A = rng.randn(3, 4, 5) B = rng.randn(3, 4, 5) assert_raises(ValueError, orthogonal_procrustes, A, B)
def test_orthogonal_procrustes_ndim_too_small(): rng = np.random.RandomState(1234) A = rng.randn(3) B = rng.randn(3) assert_raises(ValueError, orthogonal_procrustes, A, B)
def test_orthogonal_procrustes_shape_mismatch(): rng = np.random.RandomState(1234) shapes = ((3, 3), (3, 4), (4, 3), (4, 4)) for a, b in permutations(shapes, 2): A = rng.randn(*a) B = rng.randn(*b) assert_raises(ValueError, orthogonal_procrustes, A, B)
def test_orthogonal_procrustes_checkfinite_exception(): rng = np.random.RandomState(1234) m, n = 2, 3 A_good = rng.randn(m, n) B_good = rng.randn(m, n) for bad_value in np.inf, -np.inf, np.nan: A_bad = A_good.copy() A_bad[1, 2] = bad_value B_bad = B_good.copy() B_bad[1, 2] = bad_value for A, B in ((A_good, B_bad), (A_bad, B_good), (A_bad, B_bad)): assert_raises(ValueError, orthogonal_procrustes, A, B)
def test_orthogonal_procrustes_scale_invariance(): rng = np.random.RandomState(1234) m, n = 4, 3 for i in range(3): A_orig = rng.randn(m, n) B_orig = rng.randn(m, n) R_orig, s = orthogonal_procrustes(A_orig, B_orig) for A_scale in np.square(rng.randn(3)): for B_scale in np.square(rng.randn(3)): R, s = orthogonal_procrustes(A_orig * A_scale, B_orig * B_scale) assert_allclose(R, R_orig)
def test_orthogonal_procrustes_array_conversion(): rng = np.random.RandomState(1234) for m, n in ((6, 4), (4, 4), (4, 6)): A_arr = rng.randn(m, n) B_arr = rng.randn(m, n) As = (A_arr, A_arr.tolist(), matrix(A_arr)) Bs = (B_arr, B_arr.tolist(), matrix(B_arr)) R_arr, s = orthogonal_procrustes(A_arr, B_arr) AR_arr = A_arr.dot(R_arr) for A, B in product(As, Bs): R, s = orthogonal_procrustes(A, B) AR = A_arr.dot(R) assert_allclose(AR, AR_arr)
def test_orthogonal_procrustes(): rng = np.random.RandomState(1234) for m, n in ((6, 4), (4, 4), (4, 6)): # Sample a random target matrix. B = rng.randn(m, n) # Sample a random orthogonal matrix # by computing eigh of a sampled symmetric matrix. X = rng.randn(n, n) w, V = eigh(X.T + X) assert_allclose(inv(V), V.T) # Compute a matrix with a known orthogonal transformation that gives B. A = np.dot(B, V.T) # Check that an orthogonal transformation from A to B can be recovered. R, s = orthogonal_procrustes(A, B) assert_allclose(inv(R), R.T) assert_allclose(A.dot(R), B) # Create a perturbed input matrix. A_perturbed = A + 1e-2 * rng.randn(m, n) # Check that the orthogonal procrustes function can find an orthogonal # transformation that is better than the orthogonal transformation # computed from the original input matrix. R_prime, s = orthogonal_procrustes(A_perturbed, B) assert_allclose(inv(R_prime), R_prime.T) # Compute the naive and optimal transformations of the perturbed input. naive_approx = A_perturbed.dot(R) optim_approx = A_perturbed.dot(R_prime) # Compute the Frobenius norm errors of the matrix approximations. naive_approx_error = norm(naive_approx - B, ord='fro') optim_approx_error = norm(optim_approx - B, ord='fro') # Check that the orthogonal Procrustes approximation is better. assert_array_less(optim_approx_error, naive_approx_error)
def _centered(A): mu = A.mean(axis=0) return A - mu, mu
def test_orthogonal_procrustes_exact_example(): # Check a small application. # It uses translation, scaling, reflection, and rotation. # # | # a b | # | # d c | w # | # --------+--- x ----- z --- # | # | y # | # A_orig = np.array([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=float) B_orig = np.array([[3, 2], [1, 0], [3, -2], [5, 0]], dtype=float) A, A_mu = _centered(A_orig) B, B_mu = _centered(B_orig) R, s = orthogonal_procrustes(A, B) scale = s / np.square(norm(A)) B_approx = scale * np.dot(A, R) + B_mu assert_allclose(B_approx, B_orig, atol=1e-8)
def test_orthogonal_procrustes_stretched_example(): # Try again with a target with a stretched y axis. A_orig = np.array([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=float) B_orig = np.array([[3, 40], [1, 0], [3, -40], [5, 0]], dtype=float) A, A_mu = _centered(A_orig) B, B_mu = _centered(B_orig) R, s = orthogonal_procrustes(A, B) scale = s / np.square(norm(A)) B_approx = scale * np.dot(A, R) + B_mu expected = np.array([[3, 21], [-18, 0], [3, -21], [24, 0]], dtype=float) assert_allclose(B_approx, expected, atol=1e-8) # Check disparity symmetry. expected_disparity = 0.4501246882793018 AB_disparity = np.square(norm(B_approx - B_orig) / norm(B)) assert_allclose(AB_disparity, expected_disparity) R, s = orthogonal_procrustes(B, A) scale = s / np.square(norm(B)) A_approx = scale * np.dot(B, R) + A_mu BA_disparity = np.square(norm(A_approx - A_orig) / norm(A)) assert_allclose(BA_disparity, expected_disparity)
def test_orthogonal_procrustes_skbio_example(): # This transformation is also exact. # It uses translation, scaling, and reflection. # # | # | a # | b # | c d # --+--------- # | # | w # | # | x # | # | z y # | # A_orig = np.array([[4, -2], [4, -4], [4, -6], [2, -6]], dtype=float) B_orig = np.array([[1, 3], [1, 2], [1, 1], [2, 1]], dtype=float) B_standardized = np.array([ [-0.13363062, 0.6681531], [-0.13363062, 0.13363062], [-0.13363062, -0.40089186], [0.40089186, -0.40089186]]) A, A_mu = _centered(A_orig) B, B_mu = _centered(B_orig) R, s = orthogonal_procrustes(A, B) scale = s / np.square(norm(A)) B_approx = scale * np.dot(A, R) + B_mu assert_allclose(B_approx, B_orig) assert_allclose(B / norm(B), B_standardized)
def test_empty(): a = np.empty((0, 0)) r, s = orthogonal_procrustes(a, a) assert_allclose(r, np.empty((0, 0)))
a = np.empty((0, 3)) r, s = orthogonal_procrustes(a, a) assert_allclose(r, np.identity(3))
@pytest.mark.parametrize('shape', [(4, 5), (5, 5), (5, 4)])def test_unitary(shape): # gh-12071 added support for unitary matrices; check that it # works as intended. m, n = shape rng = np.random.default_rng(589234981235) A = rng.random(shape) + rng.random(shape) * 1j Q = rng.random((n, n)) + rng.random((n, n)) * 1j Q, _ = np.linalg.qr(Q) B = A @ Q R, scale = orthogonal_procrustes(A, B) assert_allclose(R @ R.conj().T, np.eye(n), atol=1e-14) assert_allclose(A @ Q, B) if shape != (4, 5): # solution is unique assert_allclose(R, Q) _, s, _ = svd(A.conj().T @ B) assert_allclose(scale, np.sum(s))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Tests for _sketches.py."""
import numpy as npfrom numpy.testing import assert_, assert_equalfrom scipy.linalg import clarkson_woodruff_transformfrom scipy.linalg._sketches import cwt_matrixfrom scipy.sparse import issparse, randfrom scipy.sparse.linalg import norm
class TestClarksonWoodruffTransform: """ Testing the Clarkson Woodruff Transform """ # set seed for generating test matrices rng = np.random.default_rng(1179103485)
# Test matrix parameters n_rows = 2000 n_cols = 100 density = 0.1
# Sketch matrix dimensions n_sketch_rows = 200
# Seeds to test with seeds = [1755490010, 934377150, 1391612830, 1752708722, 2008891431, 1302443994, 1521083269, 1501189312, 1126232505, 1533465685]
A_dense = rng.random((n_rows, n_cols)) A_csc = rand( n_rows, n_cols, density=density, format='csc', random_state=rng, ) A_csr = rand( n_rows, n_cols, density=density, format='csr', random_state=rng, ) A_coo = rand( n_rows, n_cols, density=density, format='coo', random_state=rng, )
# Collect the test matrices test_matrices = [ A_dense, A_csc, A_csr, A_coo, ]
# Test vector with norm ~1 x = rng.random((n_rows, 1)) / np.sqrt(n_rows)
def test_sketch_dimensions(self): for A in self.test_matrices: for seed in self.seeds: # seed to ensure backwards compatibility post SPEC7 sketch = clarkson_woodruff_transform( A, self.n_sketch_rows, seed=seed ) assert_(sketch.shape == (self.n_sketch_rows, self.n_cols))
def test_seed_returns_identical_transform_matrix(self): for seed in self.seeds: S1 = cwt_matrix( self.n_sketch_rows, self.n_rows, rng=seed ).toarray() S2 = cwt_matrix( self.n_sketch_rows, self.n_rows, rng=seed ).toarray() assert_equal(S1, S2)
def test_seed_returns_identically(self): for A in self.test_matrices: for seed in self.seeds: sketch1 = clarkson_woodruff_transform( A, self.n_sketch_rows, rng=seed ) sketch2 = clarkson_woodruff_transform( A, self.n_sketch_rows, rng=seed ) if issparse(sketch1): sketch1 = sketch1.toarray() if issparse(sketch2): sketch2 = sketch2.toarray() assert_equal(sketch1, sketch2)
def test_sketch_preserves_frobenius_norm(self): # Given the probabilistic nature of the sketches # we run the test multiple times and check that # we pass all/almost all the tries. n_errors = 0 for A in self.test_matrices: if issparse(A): true_norm = norm(A) else: true_norm = np.linalg.norm(A) for seed in self.seeds: sketch = clarkson_woodruff_transform( A, self.n_sketch_rows, rng=seed, ) if issparse(sketch): sketch_norm = norm(sketch) else: sketch_norm = np.linalg.norm(sketch)
if np.abs(true_norm - sketch_norm) > 0.1 * true_norm: n_errors += 1 assert_(n_errors == 0)
def test_sketch_preserves_vector_norm(self): n_errors = 0 n_sketch_rows = int(np.ceil(2. / (0.01 * 0.5**2))) true_norm = np.linalg.norm(self.x) for seed in self.seeds: sketch = clarkson_woodruff_transform( self.x, n_sketch_rows, rng=seed, ) sketch_norm = np.linalg.norm(sketch)
if np.abs(true_norm - sketch_norm) > 0.5 * true_norm: n_errors += 1 assert_(n_errors == 0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""Test functions for linalg._solve_toeplitz module"""import numpy as npfrom scipy.linalg._solve_toeplitz import levinsonfrom scipy.linalg import solve, toeplitz, solve_toeplitz, matmul_toeplitzfrom numpy.testing import assert_equal, assert_allclose
import pytestfrom pytest import raises as assert_raises
def test_solve_equivalence(): # For toeplitz matrices, solve_toeplitz() should be equivalent to solve(). random = np.random.RandomState(1234) for n in (1, 2, 3, 10): c = random.randn(n) if random.rand() < 0.5: c = c + 1j * random.randn(n) r = random.randn(n) if random.rand() < 0.5: r = r + 1j * random.randn(n) y = random.randn(n) if random.rand() < 0.5: y = y + 1j * random.randn(n)
# Check equivalence when both the column and row are provided. actual = solve_toeplitz((c,r), y) desired = solve(toeplitz(c, r=r), y) assert_allclose(actual, desired)
# Check equivalence when the column is provided but not the row. actual = solve_toeplitz(c, b=y) desired = solve(toeplitz(c), y) assert_allclose(actual, desired)
def test_multiple_rhs(): random = np.random.RandomState(1234) c = random.randn(4) r = random.randn(4) for offset in [0, 1j]: for yshape in ((4,), (4, 3), (4, 3, 2)): y = random.randn(*yshape) + offset actual = solve_toeplitz((c,r), b=y) desired = solve(toeplitz(c, r=r), y) assert_equal(actual.shape, yshape) assert_equal(desired.shape, yshape) assert_allclose(actual, desired)
def test_native_list_arguments(): c = [1,2,4,7] r = [1,3,9,12] y = [5,1,4,2] actual = solve_toeplitz((c,r), y) desired = solve(toeplitz(c, r=r), y) assert_allclose(actual, desired)
def test_zero_diag_error(): # The Levinson-Durbin implementation fails when the diagonal is zero. random = np.random.RandomState(1234) n = 4 c = random.randn(n) r = random.randn(n) y = random.randn(n) c[0] = 0 assert_raises(np.linalg.LinAlgError, solve_toeplitz, (c, r), b=y)
def test_wikipedia_counterexample(): # The Levinson-Durbin implementation also fails in other cases. # This example is from the talk page of the wikipedia article. random = np.random.RandomState(1234) c = [2, 2, 1] y = random.randn(3) assert_raises(np.linalg.LinAlgError, solve_toeplitz, c, b=y)
def test_reflection_coeffs(): # check that the partial solutions are given by the reflection # coefficients
random = np.random.RandomState(1234) y_d = random.randn(10) y_z = random.randn(10) + 1j reflection_coeffs_d = [1] reflection_coeffs_z = [1] for i in range(2, 10): reflection_coeffs_d.append(solve_toeplitz(y_d[:(i-1)], b=y_d[1:i])[-1]) reflection_coeffs_z.append(solve_toeplitz(y_z[:(i-1)], b=y_z[1:i])[-1])
y_d_concat = np.concatenate((y_d[-2:0:-1], y_d[:-1])) y_z_concat = np.concatenate((y_z[-2:0:-1].conj(), y_z[:-1])) _, ref_d = levinson(y_d_concat, b=y_d[1:]) _, ref_z = levinson(y_z_concat, b=y_z[1:])
assert_allclose(reflection_coeffs_d, ref_d[:-1]) assert_allclose(reflection_coeffs_z, ref_z[:-1])
@pytest.mark.xfail(reason='Instability of Levinson iteration')def test_unstable(): # this is a "Gaussian Toeplitz matrix", as mentioned in Example 2 of # I. Gohbert, T. Kailath and V. Olshevsky "Fast Gaussian Elimination with # Partial Pivoting for Matrices with Displacement Structure" # Mathematics of Computation, 64, 212 (1995), pp 1557-1576 # which can be unstable for levinson recursion.
# other fast toeplitz solvers such as GKO or Burg should be better. random = np.random.RandomState(1234) n = 100 c = 0.9 ** (np.arange(n)**2) y = random.randn(n)
solution1 = solve_toeplitz(c, b=y) solution2 = solve(toeplitz(c), y)
assert_allclose(solution1, solution2)
@pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64])@pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])def test_empty(dt_c, dt_b): c = np.array([], dtype=dt_c) b = np.array([], dtype=dt_b) x = solve_toeplitz(c, b) assert x.shape == (0,) assert x.dtype == solve_toeplitz(np.array([2, 1], dtype=dt_c), np.ones(2, dtype=dt_b)).dtype
b = np.empty((0, 0), dtype=dt_b) x1 = solve_toeplitz(c, b) assert x1.shape == (0, 0) assert x1.dtype == x.dtype
@pytest.mark.parametrize('fun', [solve_toeplitz, matmul_toeplitz])def test_nd_FutureWarning(fun): # Test future warnings with n-D `c`/`r` rng = np.random.default_rng(283592436523456) c = rng.random((2, 3, 4)) r = rng.random((2, 3, 4)) b_or_x = rng.random(24) message = "Beginning in SciPy 1.17, multidimensional input will be..." with pytest.warns(FutureWarning, match=message): fun(c, b_or_x) with pytest.warns(FutureWarning, match=message): fun((c, r), b_or_x)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844import osimport numpy as np
from numpy.testing import assert_array_almost_equal, assert_allcloseimport pytestfrom pytest import raises as assert_raises
from scipy.linalg import solve_sylvesterfrom scipy.linalg import solve_continuous_lyapunov, solve_discrete_lyapunovfrom scipy.linalg import solve_continuous_are, solve_discrete_arefrom scipy.linalg import block_diag, solve, LinAlgErrorfrom scipy.sparse._sputils import matrix
# dtypes for testing size-0 case following precedent set in gh-20295dtypes = [int, float, np.float32, complex, np.complex64]
def _load_data(name): """ Load npz data file under data/ Returns a copy of the data, rather than keeping the npz file open. """ filename = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data', name) with np.load(filename) as f: return dict(f.items())
class TestSolveLyapunov:
cases = [ # empty case (np.empty((0, 0)), np.empty((0, 0))), (np.array([[1, 2], [3, 4]]), np.array([[9, 10], [11, 12]])), # a, q all complex. (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), # a real; q complex. (np.array([[1.0, 2.0], [3.0, 5.0]]), np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), # a complex; q real. (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), np.array([[2.0, 2.0], [-1.0, 2.0]])), # An example from Kitagawa, 1977 (np.array([[3, 9, 5, 1, 4], [1, 2, 3, 8, 4], [4, 6, 6, 6, 3], [1, 5, 2, 0, 7], [5, 3, 3, 1, 5]]), np.array([[2, 4, 1, 0, 1], [4, 1, 0, 2, 0], [1, 0, 3, 0, 3], [0, 2, 0, 1, 0], [1, 0, 3, 0, 4]])), # Companion matrix example. a complex; q real; a.shape[0] = 11 (np.array([[0.100+0.j, 0.091+0.j, 0.082+0.j, 0.073+0.j, 0.064+0.j, 0.055+0.j, 0.046+0.j, 0.037+0.j, 0.028+0.j, 0.019+0.j, 0.010+0.j], [1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j]]), np.eye(11)), # https://github.com/scipy/scipy/issues/4176 (matrix([[0, 1], [-1/2, -1]]), (matrix([0, 3]).T @ matrix([0, 3]).T.T)), # https://github.com/scipy/scipy/issues/4176 (matrix([[0, 1], [-1/2, -1]]), (np.array(matrix([0, 3]).T @ matrix([0, 3]).T.T))), ]
def test_continuous_squareness_and_shape(self): nsq = np.ones((3, 2)) sq = np.eye(3) assert_raises(ValueError, solve_continuous_lyapunov, nsq, sq) assert_raises(ValueError, solve_continuous_lyapunov, sq, nsq) assert_raises(ValueError, solve_continuous_lyapunov, sq, np.eye(2))
def check_continuous_case(self, a, q): x = solve_continuous_lyapunov(a, q) assert_array_almost_equal( np.dot(a, x) + np.dot(x, a.conj().transpose()), q)
def check_discrete_case(self, a, q, method=None): x = solve_discrete_lyapunov(a, q, method=method) assert_array_almost_equal( np.dot(np.dot(a, x), a.conj().transpose()) - x, -1.0*q)
def test_cases(self): for case in self.cases: self.check_continuous_case(case[0], case[1]) self.check_discrete_case(case[0], case[1]) self.check_discrete_case(case[0], case[1], method='direct') self.check_discrete_case(case[0], case[1], method='bilinear')
@pytest.mark.parametrize("dtype_a", dtypes) @pytest.mark.parametrize("dtype_q", dtypes) def test_size_0(self, dtype_a, dtype_q): rng = np.random.default_rng(234598235)
a = np.zeros((0, 0), dtype=dtype_a) q = np.zeros((0, 0), dtype=dtype_q) res = solve_continuous_lyapunov(a, q)
a = (rng.random((5, 5))*100).astype(dtype_a) q = (rng.random((5, 5))*100).astype(dtype_q) ref = solve_continuous_lyapunov(a, q)
assert res.shape == (0, 0) assert res.dtype == ref.dtype
class TestSolveContinuousAre: mat6 = _load_data('carex_6_data.npz') mat15 = _load_data('carex_15_data.npz') mat18 = _load_data('carex_18_data.npz') mat19 = _load_data('carex_19_data.npz') mat20 = _load_data('carex_20_data.npz') cases = [ # Carex examples taken from (with default parameters): # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark # Examples for the Numerical Solution of Algebraic Riccati # Equations II: Continuous-Time Case', Tech. Report SPC 95_23, # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995. # # The format of the data is (a, b, q, r, knownfailure), where # knownfailure is None if the test passes or a string # indicating the reason for failure. # # Test Case 0: carex #1 (np.diag([1.], 1), np.array([[0], [1]]), block_diag(1., 2.), 1, None), # Test Case 1: carex #2 (np.array([[4, 3], [-4.5, -3.5]]), np.array([[1], [-1]]), np.array([[9, 6], [6, 4.]]), 1, None), # Test Case 2: carex #3 (np.array([[0, 1, 0, 0], [0, -1.89, 0.39, -5.53], [0, -0.034, -2.98, 2.43], [0.034, -0.0011, -0.99, -0.21]]), np.array([[0, 0], [0.36, -1.6], [-0.95, -0.032], [0.03, 0]]), np.array([[2.313, 2.727, 0.688, 0.023], [2.727, 4.271, 1.148, 0.323], [0.688, 1.148, 0.313, 0.102], [0.023, 0.323, 0.102, 0.083]]), np.eye(2), None), # Test Case 3: carex #4 (np.array([[-0.991, 0.529, 0, 0, 0, 0, 0, 0], [0.522, -1.051, 0.596, 0, 0, 0, 0, 0], [0, 0.522, -1.118, 0.596, 0, 0, 0, 0], [0, 0, 0.522, -1.548, 0.718, 0, 0, 0], [0, 0, 0, 0.922, -1.64, 0.799, 0, 0], [0, 0, 0, 0, 0.922, -1.721, 0.901, 0], [0, 0, 0, 0, 0, 0.922, -1.823, 1.021], [0, 0, 0, 0, 0, 0, 0.922, -1.943]]), np.array([[3.84, 4.00, 37.60, 3.08, 2.36, 2.88, 3.08, 3.00], [-2.88, -3.04, -2.80, -2.32, -3.32, -3.82, -4.12, -3.96]] ).T * 0.001, np.array([[1.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.1], [0.0, 1.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0], [0.5, 0.1, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0], [0.0, 0.0, 0.5, 0.0, 0.0, 0.1, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0], [0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1]]), np.eye(2), None), # Test Case 4: carex #5 (np.array( [[-4.019, 5.120, 0., 0., -2.082, 0., 0., 0., 0.870], [-0.346, 0.986, 0., 0., -2.340, 0., 0., 0., 0.970], [-7.909, 15.407, -4.069, 0., -6.450, 0., 0., 0., 2.680], [-21.816, 35.606, -0.339, -3.870, -17.800, 0., 0., 0., 7.390], [-60.196, 98.188, -7.907, 0.340, -53.008, 0., 0., 0., 20.400], [0, 0, 0, 0, 94.000, -147.200, 0., 53.200, 0.], [0, 0, 0, 0, 0, 94.000, -147.200, 0, 0], [0, 0, 0, 0, 0, 12.800, 0.000, -31.600, 0], [0, 0, 0, 0, 12.800, 0.000, 0.000, 18.800, -31.600]]), np.array([[0.010, -0.011, -0.151], [0.003, -0.021, 0.000], [0.009, -0.059, 0.000], [0.024, -0.162, 0.000], [0.068, -0.445, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000]]), np.eye(9), np.eye(3), None), # Test Case 5: carex #6 (mat6['A'], mat6['B'], mat6['Q'], mat6['R'], None), # Test Case 6: carex #7 (np.array([[1, 0], [0, -2.]]), np.array([[1e-6], [0]]), np.ones((2, 2)), 1., 'Bad residual accuracy'), # Test Case 7: carex #8 (block_diag(-0.1, -0.02), np.array([[0.100, 0.000], [0.001, 0.010]]), np.array([[100, 1000], [1000, 10000]]), np.ones((2, 2)) + block_diag(1e-6, 0), None), # Test Case 8: carex #9 (np.array([[0, 1e6], [0, 0]]), np.array([[0], [1.]]), np.eye(2), 1., None), # Test Case 9: carex #10 (np.array([[1.0000001, 1], [1., 1.0000001]]), np.eye(2), np.eye(2), np.eye(2), None), # Test Case 10: carex #11 (np.array([[3, 1.], [4, 2]]), np.array([[1], [1]]), np.array([[-11, -5], [-5, -2.]]), 1., None), # Test Case 11: carex #12 (np.array([[7000000., 2000000., -0.], [2000000., 6000000., -2000000.], [0., -2000000., 5000000.]]) / 3, np.eye(3), np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]]).dot( np.diag([1e-6, 1, 1e6])).dot( np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]])) / 9, np.eye(3) * 1e6, 'Bad Residual Accuracy'), # Test Case 12: carex #13 (np.array([[0, 0.4, 0, 0], [0, 0, 0.345, 0], [0, -0.524e6, -0.465e6, 0.262e6], [0, 0, 0, -1e6]]), np.array([[0, 0, 0, 1e6]]).T, np.diag([1, 0, 1, 0]), 1., None), # Test Case 13: carex #14 (np.array([[-1e-6, 1, 0, 0], [-1, -1e-6, 0, 0], [0, 0, 1e-6, 1], [0, 0, -1, 1e-6]]), np.ones((4, 1)), np.ones((4, 4)), 1., None), # Test Case 14: carex #15 (mat15['A'], mat15['B'], mat15['Q'], mat15['R'], None), # Test Case 15: carex #16 (np.eye(64, 64, k=-1) + np.eye(64, 64)*(-2.) + np.rot90( block_diag(1, np.zeros((62, 62)), 1)) + np.eye(64, 64, k=1), np.eye(64), np.eye(64), np.eye(64), None), # Test Case 16: carex #17 (np.diag(np.ones((20, )), 1), np.flipud(np.eye(21, 1)), np.eye(21, 1) * np.eye(21, 1).T, 1, 'Bad Residual Accuracy'), # Test Case 17: carex #18 (mat18['A'], mat18['B'], mat18['Q'], mat18['R'], None), # Test Case 18: carex #19 (mat19['A'], mat19['B'], mat19['Q'], mat19['R'], 'Bad Residual Accuracy'), # Test Case 19: carex #20 (mat20['A'], mat20['B'], mat20['Q'], mat20['R'], 'Bad Residual Accuracy') ] # Makes the minimum precision requirements customized to the test. # Here numbers represent the number of decimals that agrees with zero # matrix when the solution x is plugged in to the equation. # # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2 # # If the test is failing use "None" for that entry. # min_decimal = (14, 12, 13, 14, 11, 6, None, 5, 7, 14, 14, None, 9, 14, 13, 14, None, 12, None, None)
@pytest.mark.parametrize("j, case", enumerate(cases)) def test_solve_continuous_are(self, j, case): """Checks if 0 = XA + A'X - XB(R)^{-1} B'X + Q is true""" a, b, q, r, knownfailure = case if knownfailure: pytest.xfail(reason=knownfailure)
dec = self.min_decimal[j] x = solve_continuous_are(a, b, q, r) res = x @ a + a.conj().T @ x + q out_fact = x @ b res -= out_fact @ solve(np.atleast_2d(r), out_fact.conj().T) assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
class TestSolveDiscreteAre: cases = [ # Darex examples taken from (with default parameters): # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark # Examples for the Numerical Solution of Algebraic Riccati # Equations II: Discrete-Time Case', Tech. Report SPC 95_23, # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995. # [2] T. GUDMUNDSSON, C. KENNEY, A.J. LAUB: 'Scaling of the # Discrete-Time Algebraic Riccati Equation to Enhance Stability # of the Schur Solution Method', IEEE Trans.Aut.Cont., vol.37(4) # # The format of the data is (a, b, q, r, knownfailure), where # knownfailure is None if the test passes or a string # indicating the reason for failure. # # TEST CASE 0 : Complex a; real b, q, r (np.array([[2, 1-2j], [0, -3j]]), np.array([[0], [1]]), np.array([[1, 0], [0, 2]]), np.array([[1]]), None), # TEST CASE 1 :Real a, q, r; complex b (np.array([[2, 1], [0, -1]]), np.array([[-2j], [1j]]), np.array([[1, 0], [0, 2]]), np.array([[1]]), None), # TEST CASE 2 : Real a, b; complex q, r (np.array([[3, 1], [0, -1]]), np.array([[1, 2], [1, 3]]), np.array([[1, 1+1j], [1-1j, 2]]), np.array([[2, -2j], [2j, 3]]), None), # TEST CASE 3 : User-reported gh-2251 (Trac #1732) (np.array([[0.63399379, 0.54906824, 0.76253406], [0.5404729, 0.53745766, 0.08731853], [0.27524045, 0.84922129, 0.4681622]]), np.array([[0.96861695], [0.05532739], [0.78934047]]), np.eye(3), np.eye(1), None), # TEST CASE 4 : darex #1 (np.array([[4, 3], [-4.5, -3.5]]), np.array([[1], [-1]]), np.array([[9, 6], [6, 4]]), np.array([[1]]), None), # TEST CASE 5 : darex #2 (np.array([[0.9512, 0], [0, 0.9048]]), np.array([[4.877, 4.877], [-1.1895, 3.569]]), np.array([[0.005, 0], [0, 0.02]]), np.array([[1/3, 0], [0, 3]]), None), # TEST CASE 6 : darex #3 (np.array([[2, -1], [1, 0]]), np.array([[1], [0]]), np.array([[0, 0], [0, 1]]), np.array([[0]]), None), # TEST CASE 7 : darex #4 (skipped the gen. Ric. term S) (np.array([[0, 1], [0, -1]]), np.array([[1, 0], [2, 1]]), np.array([[-4, -4], [-4, 7]]) * (1/11), np.array([[9, 3], [3, 1]]), None), # TEST CASE 8 : darex #5 (np.array([[0, 1], [0, 0]]), np.array([[0], [1]]), np.array([[1, 2], [2, 4]]), np.array([[1]]), None), # TEST CASE 9 : darex #6 (np.array([[0.998, 0.067, 0, 0], [-.067, 0.998, 0, 0], [0, 0, 0.998, 0.153], [0, 0, -.153, 0.998]]), np.array([[0.0033, 0.0200], [0.1000, -.0007], [0.0400, 0.0073], [-.0028, 0.1000]]), np.array([[1.87, 0, 0, -0.244], [0, 0.744, 0.205, 0], [0, 0.205, 0.589, 0], [-0.244, 0, 0, 1.048]]), np.eye(2), None), # TEST CASE 10 : darex #7 (np.array([[0.984750, -.079903, 0.0009054, -.0010765], [0.041588, 0.998990, -.0358550, 0.0126840], [-.546620, 0.044916, -.3299100, 0.1931800], [2.662400, -.100450, -.9245500, -.2632500]]), np.array([[0.0037112, 0.0007361], [-.0870510, 9.3411e-6], [-1.198440, -4.1378e-4], [-3.192700, 9.2535e-4]]), np.eye(4)*1e-2, np.eye(2), None), # TEST CASE 11 : darex #8 (np.array([[-0.6000000, -2.2000000, -3.6000000, -5.4000180], [1.0000000, 0.6000000, 0.8000000, 3.3999820], [0.0000000, 1.0000000, 1.8000000, 3.7999820], [0.0000000, 0.0000000, 0.0000000, -0.9999820]]), np.array([[1.0, -1.0, -1.0, -1.0], [0.0, 1.0, -1.0, -1.0], [0.0, 0.0, 1.0, -1.0], [0.0, 0.0, 0.0, 1.0]]), np.array([[2, 1, 3, 6], [1, 2, 2, 5], [3, 2, 6, 11], [6, 5, 11, 22]]), np.eye(4), None), # TEST CASE 12 : darex #9 (np.array([[95.4070, 1.9643, 0.3597, 0.0673, 0.0190], [40.8490, 41.3170, 16.0840, 4.4679, 1.1971], [12.2170, 26.3260, 36.1490, 15.9300, 12.3830], [4.1118, 12.8580, 27.2090, 21.4420, 40.9760], [0.1305, 0.5808, 1.8750, 3.6162, 94.2800]]) * 0.01, np.array([[0.0434, -0.0122], [2.6606, -1.0453], [3.7530, -5.5100], [3.6076, -6.6000], [0.4617, -0.9148]]) * 0.01, np.eye(5), np.eye(2), None), # TEST CASE 13 : darex #10 (np.kron(np.eye(2), np.diag([1, 1], k=1)), np.kron(np.eye(2), np.array([[0], [0], [1]])), np.array([[1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 1, -1, 0], [0, 0, 0, -1, 1, 0], [0, 0, 0, 0, 0, 0]]), np.array([[3, 0], [0, 1]]), None), # TEST CASE 14 : darex #11 (0.001 * np.array( [[870.1, 135.0, 11.59, .5014, -37.22, .3484, 0, 4.242, 7.249], [76.55, 897.4, 12.72, 0.5504, -40.16, .3743, 0, 4.53, 7.499], [-127.2, 357.5, 817, 1.455, -102.8, .987, 0, 11.85, 18.72], [-363.5, 633.9, 74.91, 796.6, -273.5, 2.653, 0, 31.72, 48.82], [-960, 1645.9, -128.9, -5.597, 71.42, 7.108, 0, 84.52, 125.9], [-664.4, 112.96, -88.89, -3.854, 84.47, 13.6, 0, 144.3, 101.6], [-410.2, 693, -54.71, -2.371, 66.49, 12.49, .1063, 99.97, 69.67], [-179.9, 301.7, -23.93, -1.035, 60.59, 22.16, 0, 213.9, 35.54], [-345.1, 580.4, -45.96, -1.989, 105.6, 19.86, 0, 219.1, 215.2]]), np.array([[4.7600, -0.5701, -83.6800], [0.8790, -4.7730, -2.7300], [1.4820, -13.1200, 8.8760], [3.8920, -35.1300, 24.8000], [10.3400, -92.7500, 66.8000], [7.2030, -61.5900, 38.3400], [4.4540, -36.8300, 20.2900], [1.9710, -15.5400, 6.9370], [3.7730, -30.2800, 14.6900]]) * 0.001, np.diag([50, 0, 0, 0, 50, 0, 0, 0, 0]), np.eye(3), None), # TEST CASE 15 : darex #12 - numerically least accurate example (np.array([[0, 1e6], [0, 0]]), np.array([[0], [1]]), np.eye(2), np.array([[1]]), None), # TEST CASE 16 : darex #13 (np.array([[16, 10, -2], [10, 13, -8], [-2, -8, 7]]) * (1/9), np.eye(3), 1e6 * np.eye(3), 1e6 * np.eye(3), None), # TEST CASE 17 : darex #14 (np.array([[1 - 1/1e8, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]), np.array([[1e-08], [0], [0], [0]]), np.diag([0, 0, 0, 1]), np.array([[0.25]]), None), # TEST CASE 18 : darex #15 (np.eye(100, k=1), np.flipud(np.eye(100, 1)), np.eye(100), np.array([[1]]), None) ]
# Makes the minimum precision requirements customized to the test. # Here numbers represent the number of decimals that agrees with zero # matrix when the solution x is plugged in to the equation. # # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2 # # If the test is failing use "None" for that entry. # min_decimal = (12, 14, 13, 14, 13, 16, 18, 14, 14, 13, 14, 13, 13, 14, 12, 2, 4, 6, 10) max_tol = [1.5 * 10**-ind for ind in min_decimal] # relaxed tolerance in gh-18012 after bump to OpenBLAS max_tol[11] = 2.5e-13
# relaxed tolerance in gh-20335 for linux-aarch64 build on Cirrus # with OpenBLAS from ubuntu jammy max_tol[15] = 2.0e-2
# relaxed tolerance in gh-20335 for OpenBLAS 3.20 on ubuntu jammy # bump not needed for OpenBLAS 3.26 max_tol[16] = 2.0e-4
@pytest.mark.parametrize("j, case", enumerate(cases)) def test_solve_discrete_are(self, j, case): """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true""" a, b, q, r, knownfailure = case if knownfailure: pytest.xfail(reason=knownfailure)
atol = self.max_tol[j]
x = solve_discrete_are(a, b, q, r) bH = b.conj().T xa, xb = x @ a, x @ b
res = a.conj().T @ xa - x + q res -= a.conj().T @ xb @ (solve(r + bH @ xb, bH) @ xa)
# changed from # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec) # in gh-18012 as it's easier to relax a tolerance and allclose is # preferred assert_allclose(res, np.zeros_like(res), atol=atol)
def test_infeasible(self): # An infeasible example taken from https://arxiv.org/abs/1505.04861v1 A = np.triu(np.ones((3, 3))) A[0, 1] = -1 B = np.array([[1, 1, 0], [0, 0, 1]]).T Q = np.full_like(A, -2) + np.diag([8, -1, -1.9]) R = np.diag([-10, 0.1]) assert_raises(LinAlgError, solve_continuous_are, A, B, Q, R)
def test_solve_generalized_continuous_are(): cases = [ # Two random examples differ by s term # in the absence of any literature for demanding examples. (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], [4.617139e-02, 6.948286e-01, 3.444608e-02], [9.713178e-02, 3.170995e-01, 4.387444e-01]]), np.array([[3.815585e-01, 1.868726e-01], [7.655168e-01, 4.897644e-01], [7.951999e-01, 4.455862e-01]]), np.eye(3), np.eye(2), np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], [7.093648e-01, 6.797027e-01, 1.189977e-01], [7.546867e-01, 6.550980e-01, 4.983641e-01]]), np.zeros((3, 2)), None), (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], [4.617139e-02, 6.948286e-01, 3.444608e-02], [9.713178e-02, 3.170995e-01, 4.387444e-01]]), np.array([[3.815585e-01, 1.868726e-01], [7.655168e-01, 4.897644e-01], [7.951999e-01, 4.455862e-01]]), np.eye(3), np.eye(2), np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], [7.093648e-01, 6.797027e-01, 1.189977e-01], [7.546867e-01, 6.550980e-01, 4.983641e-01]]), np.ones((3, 2)), None) ]
min_decimal = (10, 10)
def _test_factory(case, dec): """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true""" a, b, q, r, e, s, knownfailure = case if knownfailure: pytest.xfail(reason=knownfailure)
x = solve_continuous_are(a, b, q, r, e, s) res = a.conj().T.dot(x.dot(e)) + e.conj().T.dot(x.dot(a)) + q out_fact = e.conj().T.dot(x).dot(b) + s res -= out_fact.dot(solve(np.atleast_2d(r), out_fact.conj().T)) assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
for ind, case in enumerate(cases): _test_factory(case, min_decimal[ind])
def test_solve_generalized_discrete_are(): mat20170120 = _load_data('gendare_20170120_data.npz')
cases = [ # Two random examples differ by s term # in the absence of any literature for demanding examples. (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], [4.617139e-02, 6.948286e-01, 3.444608e-02], [9.713178e-02, 3.170995e-01, 4.387444e-01]]), np.array([[3.815585e-01, 1.868726e-01], [7.655168e-01, 4.897644e-01], [7.951999e-01, 4.455862e-01]]), np.eye(3), np.eye(2), np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], [7.093648e-01, 6.797027e-01, 1.189977e-01], [7.546867e-01, 6.550980e-01, 4.983641e-01]]), np.zeros((3, 2)), None), (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], [4.617139e-02, 6.948286e-01, 3.444608e-02], [9.713178e-02, 3.170995e-01, 4.387444e-01]]), np.array([[3.815585e-01, 1.868726e-01], [7.655168e-01, 4.897644e-01], [7.951999e-01, 4.455862e-01]]), np.eye(3), np.eye(2), np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], [7.093648e-01, 6.797027e-01, 1.189977e-01], [7.546867e-01, 6.550980e-01, 4.983641e-01]]), np.ones((3, 2)), None), # user-reported (under PR-6616) 20-Jan-2017 # tests against the case where E is None but S is provided (mat20170120['A'], mat20170120['B'], mat20170120['Q'], mat20170120['R'], None, mat20170120['S'], None), ]
max_atol = (1.5e-11, 1.5e-11, 3.5e-16)
def _test_factory(case, atol): """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true""" a, b, q, r, e, s, knownfailure = case if knownfailure: pytest.xfail(reason=knownfailure)
x = solve_discrete_are(a, b, q, r, e, s) if e is None: e = np.eye(a.shape[0]) if s is None: s = np.zeros_like(b) res = a.conj().T.dot(x.dot(a)) - e.conj().T.dot(x.dot(e)) + q res -= (a.conj().T.dot(x.dot(b)) + s).dot( solve(r+b.conj().T.dot(x.dot(b)), (b.conj().T.dot(x.dot(a)) + s.conj().T) ) ) # changed from: # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec) # in gh-17950 because of a Linux 32 bit fail. assert_allclose(res, np.zeros_like(res), atol=atol)
for ind, case in enumerate(cases): _test_factory(case, max_atol[ind])
def test_are_validate_args():
def test_square_shape(): nsq = np.ones((3, 2)) sq = np.eye(3) for x in (solve_continuous_are, solve_discrete_are): assert_raises(ValueError, x, nsq, 1, 1, 1) assert_raises(ValueError, x, sq, sq, nsq, 1) assert_raises(ValueError, x, sq, sq, sq, nsq) assert_raises(ValueError, x, sq, sq, sq, sq, nsq)
def test_compatible_sizes(): nsq = np.ones((3, 2)) sq = np.eye(4) for x in (solve_continuous_are, solve_discrete_are): assert_raises(ValueError, x, sq, nsq, 1, 1) assert_raises(ValueError, x, sq, sq, sq, sq, sq, nsq) assert_raises(ValueError, x, sq, sq, np.eye(3), sq) assert_raises(ValueError, x, sq, sq, sq, np.eye(3)) assert_raises(ValueError, x, sq, sq, sq, sq, np.eye(3))
def test_symmetry(): nsym = np.arange(9).reshape(3, 3) sym = np.eye(3) for x in (solve_continuous_are, solve_discrete_are): assert_raises(ValueError, x, sym, sym, nsym, sym) assert_raises(ValueError, x, sym, sym, sym, nsym)
def test_singularity(): sing = np.full((3, 3), 1e12) sing[2, 2] -= 1 sq = np.eye(3) for x in (solve_continuous_are, solve_discrete_are): assert_raises(ValueError, x, sq, sq, sq, sq, sing)
assert_raises(ValueError, solve_continuous_are, sq, sq, sq, sing)
def test_finiteness(): nm = np.full((2, 2), np.nan) sq = np.eye(2) for x in (solve_continuous_are, solve_discrete_are): assert_raises(ValueError, x, nm, sq, sq, sq) assert_raises(ValueError, x, sq, nm, sq, sq) assert_raises(ValueError, x, sq, sq, nm, sq) assert_raises(ValueError, x, sq, sq, sq, nm) assert_raises(ValueError, x, sq, sq, sq, sq, nm) assert_raises(ValueError, x, sq, sq, sq, sq, sq, nm)
class TestSolveSylvester: cases = [ # empty cases (np.empty((0, 0)), np.empty((0, 0)), np.empty((0, 0))), (np.empty((0, 0)), np.empty((2, 2)), np.empty((0, 2))), (np.empty((2, 2)), np.empty((0, 0)), np.empty((2, 0))), # a, b, c all real. (np.array([[1, 2], [0, 4]]), np.array([[5, 6], [0, 8]]), np.array([[9, 10], [11, 12]])), # a, b, c all real, 4x4. a and b have non-trivial 2x2 blocks in their # quasi-triangular form. (np.array([[1.0, 0, 0, 0], [0, 1.0, 2.0, 0.0], [0, 0, 3.0, -4], [0, 0, 2, 5]]), np.array([[2.0, 0, 0, 1.0], [0, 1.0, 0.0, 0.0], [0, 0, 1.0, -1], [0, 0, 1, 1]]), np.array([[1.0, 0, 0, 0], [0, 1.0, 0, 0], [0, 0, 1.0, 0], [0, 0, 0, 1.0]])), # a, b, c all complex. (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), np.array([[-1.0, 2j], [3.0, 4.0]]), np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), # a and b real; c complex. (np.array([[1.0, 2.0], [3.0, 5.0]]), np.array([[-1.0, 0], [3.0, 4.0]]), np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), # a and c complex; b real. (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), np.array([[-1.0, 0], [3.0, 4.0]]), np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), # a complex; b and c real. (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), np.array([[-1.0, 0], [3.0, 4.0]]), np.array([[2.0, 2.0], [-1.0, 2.0]])), # not square matrices, real (np.array([[8, 1, 6], [3, 5, 7], [4, 9, 2]]), np.array([[2, 3], [4, 5]]), np.array([[1, 2], [3, 4], [5, 6]])), # not square matrices, complex (np.array([[8, 1j, 6+2j], [3, 5, 7], [4, 9, 2]]), np.array([[2, 3], [4, 5-1j]]), np.array([[1, 2j], [3, 4j], [5j, 6+7j]])), ]
def check_case(self, a, b, c): x = solve_sylvester(a, b, c) assert_array_almost_equal(np.dot(a, x) + np.dot(x, b), c)
def test_cases(self): for case in self.cases: self.check_case(case[0], case[1], case[2])
def test_trivial(self): a = np.array([[1.0, 0.0], [0.0, 1.0]]) b = np.array([[1.0]]) c = np.array([2.0, 2.0]).reshape(-1, 1) x = solve_sylvester(a, b, c) assert_array_almost_equal(x, np.array([1.0, 1.0]).reshape(-1, 1))
# Feel free to adjust this to test fewer dtypes or random selections rather than # the Cartesian product. It doesn't take very long to test all combinations, # though, so we'll start there and trim it down as we see fit. @pytest.mark.parametrize("dtype_a", dtypes) @pytest.mark.parametrize("dtype_b", dtypes) @pytest.mark.parametrize("dtype_q", dtypes) @pytest.mark.parametrize("m", [0, 3]) @pytest.mark.parametrize("n", [0, 3]) def test_size_0(self, m, n, dtype_a, dtype_b, dtype_q): if m == n != 0: pytest.skip('m = n != 0 is not a case that needs to be tested here.')
rng = np.random.default_rng(598435298262546)
a = np.zeros((m, m), dtype=dtype_a) b = np.zeros((n, n), dtype=dtype_b) q = np.zeros((m, n), dtype=dtype_q) res = solve_sylvester(a, b, q)
a = (rng.random((5, 5))*100).astype(dtype_a) b = (rng.random((6, 6))*100).astype(dtype_b) q = (rng.random((5, 6))*100).astype(dtype_q) ref = solve_sylvester(a, b, q)
assert res.shape == (m, n) assert res.dtype == ref.dtype123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640import pytestimport numpy as npfrom numpy import arange, array, eye, copy, sqrtfrom numpy.testing import (assert_equal, assert_array_equal, assert_array_almost_equal, assert_allclose)from pytest import raises as assert_raises
from scipy.fft import fftfrom scipy.special import combfrom scipy.linalg import (toeplitz, hankel, circulant, hadamard, leslie, dft, companion, kron, block_diag, helmert, hilbert, invhilbert, pascal, invpascal, fiedler, fiedler_companion, eigvals, convolution_matrix)from numpy.linalg import cond
class TestToeplitz:
def test_basic(self): y = toeplitz([1, 2, 3]) assert_array_equal(y, [[1, 2, 3], [2, 1, 2], [3, 2, 1]]) y = toeplitz([1, 2, 3], [1, 4, 5]) assert_array_equal(y, [[1, 4, 5], [2, 1, 4], [3, 2, 1]])
def test_complex_01(self): data = (1.0 + arange(3.0)) * (1.0 + 1.0j) x = copy(data) t = toeplitz(x) # Calling toeplitz should not change x. assert_array_equal(x, data) # According to the docstring, x should be the first column of t. col0 = t[:, 0] assert_array_equal(col0, data) assert_array_equal(t[0, 1:], data[1:].conj())
def test_scalar_00(self): """Scalar arguments still produce a 2D array.""" t = toeplitz(10) assert_array_equal(t, [[10]]) t = toeplitz(10, 20) assert_array_equal(t, [[10]])
def test_scalar_01(self): c = array([1, 2, 3]) t = toeplitz(c, 1) assert_array_equal(t, [[1], [2], [3]])
def test_scalar_02(self): c = array([1, 2, 3]) t = toeplitz(c, array(1)) assert_array_equal(t, [[1], [2], [3]])
def test_scalar_03(self): c = array([1, 2, 3]) t = toeplitz(c, array([1])) assert_array_equal(t, [[1], [2], [3]])
def test_scalar_04(self): r = array([10, 2, 3]) t = toeplitz(1, r) assert_array_equal(t, [[1, 2, 3]])
class TestHankel: def test_basic(self): y = hankel([1, 2, 3]) assert_array_equal(y, [[1, 2, 3], [2, 3, 0], [3, 0, 0]]) y = hankel([1, 2, 3], [3, 4, 5]) assert_array_equal(y, [[1, 2, 3], [2, 3, 4], [3, 4, 5]])
class TestCirculant: def test_basic(self): y = circulant([1, 2, 3]) assert_array_equal(y, [[1, 3, 2], [2, 1, 3], [3, 2, 1]])
class TestHadamard:
def test_basic(self):
y = hadamard(1) assert_array_equal(y, [[1]])
y = hadamard(2, dtype=float) assert_array_equal(y, [[1.0, 1.0], [1.0, -1.0]])
y = hadamard(4) assert_array_equal(y, [[1, 1, 1, 1], [1, -1, 1, -1], [1, 1, -1, -1], [1, -1, -1, 1]])
assert_raises(ValueError, hadamard, 0) assert_raises(ValueError, hadamard, 5)
class TestLeslie:
def test_bad_shapes(self): assert_raises(ValueError, leslie, [[1, 1], [2, 2]], [3, 4, 5]) assert_raises(ValueError, leslie, [1, 2], [1, 2]) assert_raises(ValueError, leslie, [1], [])
def test_basic(self): a = leslie([1, 2, 3], [0.25, 0.5]) expected = array([[1.0, 2.0, 3.0], [0.25, 0.0, 0.0], [0.0, 0.5, 0.0]]) assert_array_equal(a, expected)
class TestCompanion:
def test_bad_shapes(self): assert_raises(ValueError, companion, [0, 4, 5]) assert_raises(ValueError, companion, [1]) assert_raises(ValueError, companion, [])
def test_basic(self): c = companion([1, 2, 3]) expected = array([ [-2.0, -3.0], [1.0, 0.0]]) assert_array_equal(c, expected)
c = companion([2.0, 5.0, -10.0]) expected = array([ [-2.5, 5.0], [1.0, 0.0]]) assert_array_equal(c, expected)
c = companion([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)]) expected = array([ ([-2.00, -3.00], [+1.00, +0.00]), ([-1.25, -1.50], [+1.00, +0.00]) ]) assert_array_equal(c, expected)
class TestBlockDiag: def test_basic(self): x = block_diag(eye(2), [[1, 2], [3, 4], [5, 6]], [[1, 2, 3]]) assert_array_equal(x, [[1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 2, 0, 0, 0], [0, 0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0, 0, 0], [0, 0, 0, 0, 1, 2, 3]])
def test_dtype(self): x = block_diag([[1.5]]) assert_equal(x.dtype, float)
x = block_diag([[True]]) assert_equal(x.dtype, bool)
def test_mixed_dtypes(self): actual = block_diag([[1]], [[1j]]) desired = np.array([[1, 0], [0, 1j]]) assert_array_equal(actual, desired)
def test_scalar_and_1d_args(self): a = block_diag(1) assert_equal(a.shape, (1, 1)) assert_array_equal(a, [[1]])
a = block_diag([2, 3], 4) assert_array_equal(a, [[2, 3, 0], [0, 0, 4]])
def test_bad_arg(self): assert_raises(ValueError, block_diag, [[[1]]])
def test_no_args(self): a = block_diag() assert_equal(a.ndim, 2) assert_equal(a.nbytes, 0)
def test_empty_matrix_arg(self): # regression test for gh-4596: check the shape of the result # for empty matrix inputs. Empty matrices are no longer ignored # (gh-4908) it is viewed as a shape (1, 0) matrix. a = block_diag([[1, 0], [0, 1]], [], [[2, 3], [4, 5], [6, 7]]) assert_array_equal(a, [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 2, 3], [0, 0, 4, 5], [0, 0, 6, 7]])
def test_zerosized_matrix_arg(self): # test for gh-4908: check the shape of the result for # zero-sized matrix inputs, i.e. matrices with shape (0,n) or (n,0). # note that [[]] takes shape (1,0) a = block_diag([[1, 0], [0, 1]], [[]], [[2, 3], [4, 5], [6, 7]], np.zeros([0, 2], dtype='int32')) assert_array_equal(a, [[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 2, 3, 0, 0], [0, 0, 4, 5, 0, 0], [0, 0, 6, 7, 0, 0]])
class TestKron: @pytest.mark.thread_unsafe def test_dep(self): with pytest.deprecated_call(match="`kron`"): kron(np.array([[1, 2],[3, 4]]),np.array([[1, 1, 1]]))
@pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_basic(self):
a = kron(array([[1, 2], [3, 4]]), array([[1, 1, 1]])) assert_array_equal(a, array([[1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4]]))
m1 = array([[1, 2], [3, 4]]) m2 = array([[10], [11]]) a = kron(m1, m2) expected = array([[10, 20], [11, 22], [30, 40], [33, 44]]) assert_array_equal(a, expected)
@pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_empty(self): m1 = np.empty((0, 2)) m2 = np.empty((1, 3)) a = kron(m1, m2) assert_allclose(a, np.empty((0, 6)))
class TestHelmert:
def test_orthogonality(self): for n in range(1, 7): H = helmert(n, full=True) Id = np.eye(n) assert_allclose(H.dot(H.T), Id, atol=1e-12) assert_allclose(H.T.dot(H), Id, atol=1e-12)
def test_subspace(self): for n in range(2, 7): H_full = helmert(n, full=True) H_partial = helmert(n) for U in H_full[1:, :].T, H_partial.T: C = np.eye(n) - np.full((n, n), 1 / n) assert_allclose(U.dot(U.T), C) assert_allclose(U.T.dot(U), np.eye(n-1), atol=1e-12)
class TestHilbert:
def test_basic(self): h3 = array([[1.0, 1/2., 1/3.], [1/2., 1/3., 1/4.], [1/3., 1/4., 1/5.]]) assert_array_almost_equal(hilbert(3), h3)
assert_array_equal(hilbert(1), [[1.0]])
h0 = hilbert(0) assert_equal(h0.shape, (0, 0))
class TestInvHilbert:
def test_basic(self): invh1 = array([[1]]) assert_array_equal(invhilbert(1, exact=True), invh1) assert_array_equal(invhilbert(1), invh1)
invh2 = array([[4, -6], [-6, 12]]) assert_array_equal(invhilbert(2, exact=True), invh2) assert_array_almost_equal(invhilbert(2), invh2)
invh3 = array([[9, -36, 30], [-36, 192, -180], [30, -180, 180]]) assert_array_equal(invhilbert(3, exact=True), invh3) assert_array_almost_equal(invhilbert(3), invh3)
invh4 = array([[16, -120, 240, -140], [-120, 1200, -2700, 1680], [240, -2700, 6480, -4200], [-140, 1680, -4200, 2800]]) assert_array_equal(invhilbert(4, exact=True), invh4) assert_array_almost_equal(invhilbert(4), invh4)
invh5 = array([[25, -300, 1050, -1400, 630], [-300, 4800, -18900, 26880, -12600], [1050, -18900, 79380, -117600, 56700], [-1400, 26880, -117600, 179200, -88200], [630, -12600, 56700, -88200, 44100]]) assert_array_equal(invhilbert(5, exact=True), invh5) assert_array_almost_equal(invhilbert(5), invh5)
invh17 = array([ [289, -41616, 1976760, -46124400, 629598060, -5540462928, 33374693352, -143034400080, 446982500250, -1033026222800, 1774926873720, -2258997839280, 2099709530100, -1384423866000, 613101997800, -163493866080, 19835652870], [-41616, 7990272, -426980160, 10627061760, -151103534400, 1367702848512, -8410422724704, 36616806420480, -115857864064800, 270465047424000, -468580694662080, 600545887119360, -561522320049600, 372133135180800, -165537539406000, 44316454993920, -5395297580640], [1976760, -426980160, 24337869120, -630981792000, 9228108708000, -85267724461920, 532660105897920, -2348052711713280, 7504429831470000, -17664748409880000, 30818191841236800, -39732544853164800, 37341234283298400, -24857330514030000, 11100752642520000, -2982128117299200, 364182586693200], [-46124400, 10627061760, -630981792000, 16826181120000, -251209625940000, 2358021022156800, -14914482965141760, 66409571644416000, -214015221119700000, 507295338950400000, -890303319857952000, 1153715376477081600, -1089119333262870000, 727848632044800000, -326170262829600000, 87894302404608000, -10763618673376800], [629598060, -151103534400, 9228108708000, -251209625940000, 3810012660090000, -36210360321495360, 231343968720664800, -1038687206500944000, 3370739732635275000, -8037460526495400000, 14178080368737885600, -18454939322943942000, 17489975175339030000, -11728977435138600000, 5272370630081100000, -1424711708039692800, 174908803442373000], [-5540462928, 1367702848512, -85267724461920, 2358021022156800, -36210360321495360, 347619459086355456, -2239409617216035264, 10124803292907663360, -33052510749726468000, 79217210949138662400, -140362995650505067440, 183420385176741672960, -174433352415381259200, 117339159519533952000, -52892422160973595200, 14328529177999196160, -1763080738699119840], [33374693352, -8410422724704, 532660105897920, -14914482965141760, 231343968720664800, -2239409617216035264, 14527452132196331328, -66072377044391477760, 216799987176909536400, -521925895055522958000, 928414062734059661760, -1217424500995626443520, 1161358898976091015200, -783401860847777371200, 354015418167362952000, -96120549902411274240, 11851820521255194480], [-143034400080, 36616806420480, -2348052711713280, 66409571644416000, -1038687206500944000, 10124803292907663360, -66072377044391477760, 302045152202932469760, -995510145200094810000, 2405996923185123840000, -4294704507885446054400, 5649058909023744614400, -5403874060541811254400, 3654352703663101440000, -1655137020003255360000, 450325202737117593600, -55630994283442749600], [446982500250, -115857864064800, 7504429831470000, -214015221119700000, 3370739732635275000, -33052510749726468000, 216799987176909536400, -995510145200094810000, 3293967392206196062500, -7988661659013106500000, 14303908928401362270000, -18866974090684772052000, 18093328327706957325000, -12263364009096700500000, 5565847995255512250000, -1517208935002984080000, 187754605706619279900], [-1033026222800, 270465047424000, -17664748409880000, 507295338950400000, -8037460526495400000, 79217210949138662400, -521925895055522958000, 2405996923185123840000, -7988661659013106500000, 19434404971634224000000, -34894474126569249192000, 46141453390504792320000, -44349976506971935800000, 30121928988527376000000, -13697025107665828500000, 3740200989399948902400, -463591619028689580000], [1774926873720, -468580694662080, 30818191841236800, -890303319857952000, 14178080368737885600, -140362995650505067440, 928414062734059661760, -4294704507885446054400, 14303908928401362270000, -34894474126569249192000, 62810053427824648545600, -83243376594051600326400, 80177044485212743068000, -54558343880470209780000, 24851882355348879230400, -6797096028813368678400, 843736746632215035600], [-2258997839280, 600545887119360, -39732544853164800, 1153715376477081600, -18454939322943942000, 183420385176741672960, -1217424500995626443520, 5649058909023744614400, -18866974090684772052000, 46141453390504792320000, -83243376594051600326400, 110552468520163390156800, -106681852579497947388000, 72720410752415168870400, -33177973900974346080000, 9087761081682520473600, -1129631016152221783200], [2099709530100, -561522320049600, 37341234283298400, -1089119333262870000, 17489975175339030000, -174433352415381259200, 1161358898976091015200, -5403874060541811254400, 18093328327706957325000, -44349976506971935800000, 80177044485212743068000, -106681852579497947388000, 103125790826848015808400, -70409051543137015800000, 32171029219823375700000, -8824053728865840192000, 1098252376814660067000], [-1384423866000, 372133135180800, -24857330514030000, 727848632044800000, -11728977435138600000, 117339159519533952000, -783401860847777371200, 3654352703663101440000, -12263364009096700500000, 30121928988527376000000, -54558343880470209780000, 72720410752415168870400, -70409051543137015800000, 48142941226076592000000, -22027500987368499000000, 6049545098753157120000, -753830033789944188000], [613101997800, -165537539406000, 11100752642520000, -326170262829600000, 5272370630081100000, -52892422160973595200, 354015418167362952000, -1655137020003255360000, 5565847995255512250000, -13697025107665828500000, 24851882355348879230400, -33177973900974346080000, 32171029219823375700000, -22027500987368499000000, 10091416708498869000000, -2774765838662800128000, 346146444087219270000], [-163493866080, 44316454993920, -2982128117299200, 87894302404608000, -1424711708039692800, 14328529177999196160, -96120549902411274240, 450325202737117593600, -1517208935002984080000, 3740200989399948902400, -6797096028813368678400, 9087761081682520473600, -8824053728865840192000, 6049545098753157120000, -2774765838662800128000, 763806510427609497600, -95382575704033754400], [19835652870, -5395297580640, 364182586693200, -10763618673376800, 174908803442373000, -1763080738699119840, 11851820521255194480, -55630994283442749600, 187754605706619279900, -463591619028689580000, 843736746632215035600, -1129631016152221783200, 1098252376814660067000, -753830033789944188000, 346146444087219270000, -95382575704033754400, 11922821963004219300] ]) assert_array_equal(invhilbert(17, exact=True), invh17) assert_allclose(invhilbert(17), invh17.astype(float), rtol=1e-12)
def test_inverse(self): for n in range(1, 10): a = hilbert(n) b = invhilbert(n) # The Hilbert matrix is increasingly badly conditioned, # so take that into account in the test c = cond(a) assert_allclose(a.dot(b), eye(n), atol=1e-15*c, rtol=1e-15*c)
class TestPascal:
cases = [ (1, array([[1]]), array([[1]])), (2, array([[1, 1], [1, 2]]), array([[1, 0], [1, 1]])), (3, array([[1, 1, 1], [1, 2, 3], [1, 3, 6]]), array([[1, 0, 0], [1, 1, 0], [1, 2, 1]])), (4, array([[1, 1, 1, 1], [1, 2, 3, 4], [1, 3, 6, 10], [1, 4, 10, 20]]), array([[1, 0, 0, 0], [1, 1, 0, 0], [1, 2, 1, 0], [1, 3, 3, 1]])), ]
def check_case(self, n, sym, low): assert_array_equal(pascal(n), sym) assert_array_equal(pascal(n, kind='lower'), low) assert_array_equal(pascal(n, kind='upper'), low.T) assert_array_almost_equal(pascal(n, exact=False), sym) assert_array_almost_equal(pascal(n, exact=False, kind='lower'), low) assert_array_almost_equal(pascal(n, exact=False, kind='upper'), low.T)
def test_cases(self): for n, sym, low in self.cases: self.check_case(n, sym, low)
def test_big(self): p = pascal(50) assert p[-1, -1] == comb(98, 49, exact=True)
def test_threshold(self): # Regression test. An early version of `pascal` returned an # array of type np.uint64 for n=35, but that data type is too small # to hold p[-1, -1]. The second assert_equal below would fail # because p[-1, -1] overflowed. p = pascal(34) assert_equal(2*p.item(-1, -2), p.item(-1, -1), err_msg="n = 34") p = pascal(35) assert_equal(2.*p.item(-1, -2), 1.*p.item(-1, -1), err_msg="n = 35")
def test_invpascal():
def check_invpascal(n, kind, exact): ip = invpascal(n, kind=kind, exact=exact) p = pascal(n, kind=kind, exact=exact) # Matrix-multiply ip and p, and check that we get the identity matrix. # We can't use the simple expression e = ip.dot(p), because when # n < 35 and exact is True, p.dtype is np.uint64 and ip.dtype is # np.int64. The product of those dtypes is np.float64, which loses # precision when n is greater than 18. Instead we'll cast both to # object arrays, and then multiply. e = ip.astype(object).dot(p.astype(object)) assert_array_equal(e, eye(n), err_msg="n=%d kind=%r exact=%r" % (n, kind, exact))
kinds = ['symmetric', 'lower', 'upper']
ns = [1, 2, 5, 18] for n in ns: for kind in kinds: for exact in [True, False]: check_invpascal(n, kind, exact)
ns = [19, 34, 35, 50] for n in ns: for kind in kinds: check_invpascal(n, kind, True)
def test_dft(): m = dft(2) expected = array([[1.0, 1.0], [1.0, -1.0]]) assert_array_almost_equal(m, expected) m = dft(2, scale='n') assert_array_almost_equal(m, expected/2.0) m = dft(2, scale='sqrtn') assert_array_almost_equal(m, expected/sqrt(2.0))
x = array([0, 1, 2, 3, 4, 5, 0, 1]) m = dft(8) mx = m.dot(x) fx = fft(x) assert_array_almost_equal(mx, fx)
def test_fiedler(): f = fiedler([]) assert_equal(f.size, 0) f = fiedler([123.]) assert_array_equal(f, np.array([[0.]])) f = fiedler(np.arange(1, 7)) des = np.array([[0, 1, 2, 3, 4, 5], [1, 0, 1, 2, 3, 4], [2, 1, 0, 1, 2, 3], [3, 2, 1, 0, 1, 2], [4, 3, 2, 1, 0, 1], [5, 4, 3, 2, 1, 0]]) assert_array_equal(f, des)
def test_fiedler_companion(): fc = fiedler_companion([]) assert_equal(fc.size, 0) fc = fiedler_companion([1.]) assert_equal(fc.size, 0) fc = fiedler_companion([1., 2.]) assert_array_equal(fc, np.array([[-2.]])) fc = fiedler_companion([1e-12, 2., 3.]) assert_array_almost_equal(fc, companion([1e-12, 2., 3.])) with assert_raises(ValueError): fiedler_companion([0, 1, 2]) fc = fiedler_companion([1., -16., 86., -176., 105.]) assert_array_almost_equal(eigvals(fc), np.array([7., 5., 3., 1.]))
class TestConvolutionMatrix: """ Test convolution_matrix vs. numpy.convolve for various parameters. """
def create_vector(self, n, cpx): """Make a complex or real test vector of length n.""" x = np.linspace(-2.5, 2.2, n) if cpx: x = x + 1j*np.linspace(-1.5, 3.1, n) return x
def test_bad_n(self): # n must be a positive integer with pytest.raises(ValueError, match='n must be a positive integer'): convolution_matrix([1, 2, 3], 0)
def test_empty_first_arg(self): # first arg must have at least one value with pytest.raises(ValueError, match=r'len\(a\)'): convolution_matrix([], 4)
def test_bad_mode(self): # mode must be in ('full', 'valid', 'same') with pytest.raises(ValueError, match='mode.*must be one of'): convolution_matrix((1, 1), 4, mode='invalid argument')
@pytest.mark.parametrize('cpx', [False, True]) @pytest.mark.parametrize('na', [1, 2, 9]) @pytest.mark.parametrize('nv', [1, 2, 9]) @pytest.mark.parametrize('mode', [None, 'full', 'valid', 'same']) def test_against_numpy_convolve(self, cpx, na, nv, mode): a = self.create_vector(na, cpx) v = self.create_vector(nv, cpx) if mode is None: y1 = np.convolve(v, a) A = convolution_matrix(a, nv) else: y1 = np.convolve(v, a, mode) A = convolution_matrix(a, nv, mode) y2 = A @ v assert_array_almost_equal(y1, y2)
@pytest.mark.thread_unsafe@pytest.mark.fail_slow(5) # `leslie` has an import in the function@pytest.mark.parametrize('f, args', [(circulant, ()), (companion, ()), (convolution_matrix, (5, 'same')), (fiedler, ()), (fiedler_companion, ()), (leslie, (np.arange(9),)), (toeplitz, (np.arange(9),)), ])def test_batch(f, args): rng = np.random.default_rng(283592436523456) batch_shape = (2, 3) m = 10 A = rng.random(batch_shape + (m,))
if f in {toeplitz}: message = "Beginning in SciPy 1.17, multidimensional input will be..." with pytest.warns(FutureWarning, match=message): f(A, *args) return
res = f(A, *args) ref = np.asarray([f(a, *args) for a in A.reshape(-1, m)]) ref = ref.reshape(A.shape[:-1] + ref.shape[-2:]) assert_allclose(res, ref)123456import warningswarnings.warn( "scipy.misc is deprecated and will be removed in 2.0.0", DeprecationWarning, stacklevel=2).gitattributes+67
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_blas.pxdAdded+169
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_blas.pyxAdded+1432
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_lapack.cpython-311-x86_64-linux-gnu.soAdded+3
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_lapack.pxdAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/cython_lapack.pyxAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp.pyAdded+23
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp_cholesky.pyAdded+21
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp_lu.pyAdded+21
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp_qr.pyAdded+20
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp_schur.pyAdded+21
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/decomp_svd.pyAdded+21
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/interpolative.pyAdded+989
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/lapack.pyAdded+1061
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/matfuncs.pyAdded+23
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/misc.pyAdded+21
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/special_matrices.pyAdded+22
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/__init__.pyAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/_cython_examples/extending.pyxAdded+23
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/_cython_examples/meson.buildAdded+27
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/carex_15_data.npzAdded+3
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/carex_18_data.npzAdded+3
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/carex_19_data.npzAdded+3
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/carex_20_data.npzAdded+3
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/carex_6_data.npzAdded+3
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npzAdded+3
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_basic.pyAdded+2059
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_blas.pyAdded+1127
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_cython_blas.pyAdded+118
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_cython_lapack.pyAdded+22
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_cythonized_array_utils.pyAdded+132
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp.pyAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_cholesky.pyAdded+268
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_cossin.pyAdded+300
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_ldl.pyAdded+137
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_lu.pyAdded+308
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_polar.pyAdded+110
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_decomp_update.pyAdded+1701
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_extending.pyAdded+46
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_fblas.pyAdded+607
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_interpolative.pyAdded+232
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_lapack.pyAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_matfuncs.pyAdded+1063
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_matmul_toeplitz.pyAdded+136
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_procrustes.pyAdded+221
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_sketches.pyAdded+118
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_solve_toeplitz.pyAdded+150
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_solvers.pyAdded+844
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/linalg/tests/test_special_matrices.pyAdded+640
pace_revision_2/.venv-pace/lib/python3.11/site-packages/scipy/misc/__init__.pyAdded+6