applied-ai-018 commited on
Commit
d9d012b
·
verified ·
1 Parent(s): a4d299a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step40/zero/12.attention.query_key_value.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step40/zero/12.attention.query_key_value.weight/fp32.pt +3 -0
  3. ckpts/universal/global_step40/zero/5.attention.query_key_value.weight/exp_avg_sq.pt +3 -0
  4. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc +0 -0
  5. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc +0 -0
  6. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_interpolative_backend.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_inv_ssq.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_testutils.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py +0 -0
  25. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_basic.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_blas.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cython_blas.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cython_lapack.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cythonized_array_utils.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cholesky.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cossin.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_ldl.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_lu.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_polar.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_update.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_fblas.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_interpolative.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_lapack.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_matfuncs.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_matmul_toeplitz.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_misc.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_procrustes.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_sketches.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_solve_toeplitz.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_solvers.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_special_matrices.cpython-310.pyc +0 -0
  49. venv/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py +1817 -0
  50. venv/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py +1114 -0
ckpts/universal/global_step40/zero/12.attention.query_key_value.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58de09e8fbaf0f4d960197f4a498a7398ad067b07f332edfe717718ef01530a2
3
+ size 50332828
ckpts/universal/global_step40/zero/12.attention.query_key_value.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a682f878ac4c5cfcf03a221f68168cd1c0f8c9dda07fcc28fba91e00a1329630
3
+ size 50332749
ckpts/universal/global_step40/zero/5.attention.query_key_value.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a4a982f870c12d4d6ad3c888be7a38add8529f91b462285165e3bfe72fabe2d4
3
+ size 50332843
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc ADDED
Binary file (57.8 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc ADDED
Binary file (8.12 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_interpolative_backend.cpython-310.pyc ADDED
Binary file (40.3 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc ADDED
Binary file (22.1 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_inv_ssq.cpython-310.pyc ADDED
Binary file (23.7 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc ADDED
Binary file (5.54 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc ADDED
Binary file (5.81 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc ADDED
Binary file (6.31 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_testutils.cpython-310.pyc ADDED
Binary file (2.48 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc ADDED
Binary file (819 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc ADDED
Binary file (9.64 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc ADDED
Binary file (678 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc ADDED
Binary file (650 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc ADDED
Binary file (717 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc ADDED
Binary file (693 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc ADDED
Binary file (28.8 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc ADDED
Binary file (875 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_basic.cpython-310.pyc ADDED
Binary file (57.4 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_blas.cpython-310.pyc ADDED
Binary file (31 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cython_blas.cpython-310.pyc ADDED
Binary file (4.24 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cython_lapack.cpython-310.pyc ADDED
Binary file (1.19 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_cythonized_array_utils.cpython-310.pyc ADDED
Binary file (4.84 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp.cpython-310.pyc ADDED
Binary file (87.3 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cholesky.cpython-310.pyc ADDED
Binary file (7.99 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_cossin.cpython-310.pyc ADDED
Binary file (5.63 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_ldl.cpython-310.pyc ADDED
Binary file (4.98 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_lu.cpython-310.pyc ADDED
Binary file (9.79 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_polar.cpython-310.pyc ADDED
Binary file (2.55 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_decomp_update.cpython-310.pyc ADDED
Binary file (53.4 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_fblas.cpython-310.pyc ADDED
Binary file (16 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_interpolative.cpython-310.pyc ADDED
Binary file (7.88 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_lapack.cpython-310.pyc ADDED
Binary file (84.1 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_matfuncs.cpython-310.pyc ADDED
Binary file (34 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_matmul_toeplitz.cpython-310.pyc ADDED
Binary file (3.36 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_misc.cpython-310.pyc ADDED
Binary file (357 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_procrustes.cpython-310.pyc ADDED
Binary file (5.24 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_sketches.cpython-310.pyc ADDED
Binary file (3.22 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_solve_toeplitz.cpython-310.pyc ADDED
Binary file (3.39 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_solvers.cpython-310.pyc ADDED
Binary file (22.4 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/__pycache__/test_special_matrices.cpython-310.pyc ADDED
Binary file (20.1 kB). View file
 
venv/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py ADDED
@@ -0,0 +1,1817 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import warnings
3
+
4
+ import numpy as np
5
+ from numpy import (arange, array, dot, zeros, identity, conjugate, transpose,
6
+ float32)
7
+ from numpy.random import random
8
+
9
+ from numpy.testing import (assert_equal, assert_almost_equal, assert_,
10
+ assert_array_almost_equal, assert_allclose,
11
+ assert_array_equal, suppress_warnings)
12
+ import pytest
13
+ from pytest import raises as assert_raises
14
+
15
+ from scipy.linalg import (solve, inv, det, lstsq, pinv, pinvh, norm,
16
+ solve_banded, solveh_banded, solve_triangular,
17
+ solve_circulant, circulant, LinAlgError, block_diag,
18
+ matrix_balance, qr, LinAlgWarning)
19
+
20
+ from scipy.linalg._testutils import assert_no_overwrite
21
+ from scipy._lib._testutils import check_free_memory, IS_MUSL
22
+ from scipy.linalg.blas import HAS_ILP64
23
+ from scipy._lib.deprecation import _NoValue
24
+
25
+ REAL_DTYPES = (np.float32, np.float64, np.longdouble)
26
+ COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
27
+ DTYPES = REAL_DTYPES + COMPLEX_DTYPES
28
+
29
+
30
+ def _eps_cast(dtyp):
31
+ """Get the epsilon for dtype, possibly downcast to BLAS types."""
32
+ dt = dtyp
33
+ if dt == np.longdouble:
34
+ dt = np.float64
35
+ elif dt == np.clongdouble:
36
+ dt = np.complex128
37
+ return np.finfo(dt).eps
38
+
39
+
40
+ class TestSolveBanded:
41
+
42
+ def test_real(self):
43
+ a = array([[1.0, 20, 0, 0],
44
+ [-30, 4, 6, 0],
45
+ [2, 1, 20, 2],
46
+ [0, -1, 7, 14]])
47
+ ab = array([[0.0, 20, 6, 2],
48
+ [1, 4, 20, 14],
49
+ [-30, 1, 7, 0],
50
+ [2, -1, 0, 0]])
51
+ l, u = 2, 1
52
+ b4 = array([10.0, 0.0, 2.0, 14.0])
53
+ b4by1 = b4.reshape(-1, 1)
54
+ b4by2 = array([[2, 1],
55
+ [-30, 4],
56
+ [2, 3],
57
+ [1, 3]])
58
+ b4by4 = array([[1, 0, 0, 0],
59
+ [0, 0, 0, 1],
60
+ [0, 1, 0, 0],
61
+ [0, 1, 0, 0]])
62
+ for b in [b4, b4by1, b4by2, b4by4]:
63
+ x = solve_banded((l, u), ab, b)
64
+ assert_array_almost_equal(dot(a, x), b)
65
+
66
+ def test_complex(self):
67
+ a = array([[1.0, 20, 0, 0],
68
+ [-30, 4, 6, 0],
69
+ [2j, 1, 20, 2j],
70
+ [0, -1, 7, 14]])
71
+ ab = array([[0.0, 20, 6, 2j],
72
+ [1, 4, 20, 14],
73
+ [-30, 1, 7, 0],
74
+ [2j, -1, 0, 0]])
75
+ l, u = 2, 1
76
+ b4 = array([10.0, 0.0, 2.0, 14.0j])
77
+ b4by1 = b4.reshape(-1, 1)
78
+ b4by2 = array([[2, 1],
79
+ [-30, 4],
80
+ [2, 3],
81
+ [1, 3]])
82
+ b4by4 = array([[1, 0, 0, 0],
83
+ [0, 0, 0, 1j],
84
+ [0, 1, 0, 0],
85
+ [0, 1, 0, 0]])
86
+ for b in [b4, b4by1, b4by2, b4by4]:
87
+ x = solve_banded((l, u), ab, b)
88
+ assert_array_almost_equal(dot(a, x), b)
89
+
90
+ def test_tridiag_real(self):
91
+ ab = array([[0.0, 20, 6, 2],
92
+ [1, 4, 20, 14],
93
+ [-30, 1, 7, 0]])
94
+ a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag(
95
+ ab[2, :-1], -1)
96
+ b4 = array([10.0, 0.0, 2.0, 14.0])
97
+ b4by1 = b4.reshape(-1, 1)
98
+ b4by2 = array([[2, 1],
99
+ [-30, 4],
100
+ [2, 3],
101
+ [1, 3]])
102
+ b4by4 = array([[1, 0, 0, 0],
103
+ [0, 0, 0, 1],
104
+ [0, 1, 0, 0],
105
+ [0, 1, 0, 0]])
106
+ for b in [b4, b4by1, b4by2, b4by4]:
107
+ x = solve_banded((1, 1), ab, b)
108
+ assert_array_almost_equal(dot(a, x), b)
109
+
110
+ def test_tridiag_complex(self):
111
+ ab = array([[0.0, 20, 6, 2j],
112
+ [1, 4, 20, 14],
113
+ [-30, 1, 7, 0]])
114
+ a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag(
115
+ ab[2, :-1], -1)
116
+ b4 = array([10.0, 0.0, 2.0, 14.0j])
117
+ b4by1 = b4.reshape(-1, 1)
118
+ b4by2 = array([[2, 1],
119
+ [-30, 4],
120
+ [2, 3],
121
+ [1, 3]])
122
+ b4by4 = array([[1, 0, 0, 0],
123
+ [0, 0, 0, 1],
124
+ [0, 1, 0, 0],
125
+ [0, 1, 0, 0]])
126
+ for b in [b4, b4by1, b4by2, b4by4]:
127
+ x = solve_banded((1, 1), ab, b)
128
+ assert_array_almost_equal(dot(a, x), b)
129
+
130
+ def test_check_finite(self):
131
+ a = array([[1.0, 20, 0, 0],
132
+ [-30, 4, 6, 0],
133
+ [2, 1, 20, 2],
134
+ [0, -1, 7, 14]])
135
+ ab = array([[0.0, 20, 6, 2],
136
+ [1, 4, 20, 14],
137
+ [-30, 1, 7, 0],
138
+ [2, -1, 0, 0]])
139
+ l, u = 2, 1
140
+ b4 = array([10.0, 0.0, 2.0, 14.0])
141
+ x = solve_banded((l, u), ab, b4, check_finite=False)
142
+ assert_array_almost_equal(dot(a, x), b4)
143
+
144
+ def test_bad_shape(self):
145
+ ab = array([[0.0, 20, 6, 2],
146
+ [1, 4, 20, 14],
147
+ [-30, 1, 7, 0],
148
+ [2, -1, 0, 0]])
149
+ l, u = 2, 1
150
+ bad = array([1.0, 2.0, 3.0, 4.0]).reshape(-1, 4)
151
+ assert_raises(ValueError, solve_banded, (l, u), ab, bad)
152
+ assert_raises(ValueError, solve_banded, (l, u), ab, [1.0, 2.0])
153
+
154
+ # Values of (l,u) are not compatible with ab.
155
+ assert_raises(ValueError, solve_banded, (1, 1), ab, [1.0, 2.0])
156
+
157
+ def test_1x1(self):
158
+ b = array([[1., 2., 3.]])
159
+ x = solve_banded((1, 1), [[0], [2], [0]], b)
160
+ assert_array_equal(x, [[0.5, 1.0, 1.5]])
161
+ assert_equal(x.dtype, np.dtype('f8'))
162
+ assert_array_equal(b, [[1.0, 2.0, 3.0]])
163
+
164
+ def test_native_list_arguments(self):
165
+ a = [[1.0, 20, 0, 0],
166
+ [-30, 4, 6, 0],
167
+ [2, 1, 20, 2],
168
+ [0, -1, 7, 14]]
169
+ ab = [[0.0, 20, 6, 2],
170
+ [1, 4, 20, 14],
171
+ [-30, 1, 7, 0],
172
+ [2, -1, 0, 0]]
173
+ l, u = 2, 1
174
+ b = [10.0, 0.0, 2.0, 14.0]
175
+ x = solve_banded((l, u), ab, b)
176
+ assert_array_almost_equal(dot(a, x), b)
177
+
178
+
179
+ class TestSolveHBanded:
180
+
181
+ def test_01_upper(self):
182
+ # Solve
183
+ # [ 4 1 2 0] [1]
184
+ # [ 1 4 1 2] X = [4]
185
+ # [ 2 1 4 1] [1]
186
+ # [ 0 2 1 4] [2]
187
+ # with the RHS as a 1D array.
188
+ ab = array([[0.0, 0.0, 2.0, 2.0],
189
+ [-99, 1.0, 1.0, 1.0],
190
+ [4.0, 4.0, 4.0, 4.0]])
191
+ b = array([1.0, 4.0, 1.0, 2.0])
192
+ x = solveh_banded(ab, b)
193
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
194
+
195
+ def test_02_upper(self):
196
+ # Solve
197
+ # [ 4 1 2 0] [1 6]
198
+ # [ 1 4 1 2] X = [4 2]
199
+ # [ 2 1 4 1] [1 6]
200
+ # [ 0 2 1 4] [2 1]
201
+ #
202
+ ab = array([[0.0, 0.0, 2.0, 2.0],
203
+ [-99, 1.0, 1.0, 1.0],
204
+ [4.0, 4.0, 4.0, 4.0]])
205
+ b = array([[1.0, 6.0],
206
+ [4.0, 2.0],
207
+ [1.0, 6.0],
208
+ [2.0, 1.0]])
209
+ x = solveh_banded(ab, b)
210
+ expected = array([[0.0, 1.0],
211
+ [1.0, 0.0],
212
+ [0.0, 1.0],
213
+ [0.0, 0.0]])
214
+ assert_array_almost_equal(x, expected)
215
+
216
+ def test_03_upper(self):
217
+ # Solve
218
+ # [ 4 1 2 0] [1]
219
+ # [ 1 4 1 2] X = [4]
220
+ # [ 2 1 4 1] [1]
221
+ # [ 0 2 1 4] [2]
222
+ # with the RHS as a 2D array with shape (3,1).
223
+ ab = array([[0.0, 0.0, 2.0, 2.0],
224
+ [-99, 1.0, 1.0, 1.0],
225
+ [4.0, 4.0, 4.0, 4.0]])
226
+ b = array([1.0, 4.0, 1.0, 2.0]).reshape(-1, 1)
227
+ x = solveh_banded(ab, b)
228
+ assert_array_almost_equal(x, array([0., 1., 0., 0.]).reshape(-1, 1))
229
+
230
+ def test_01_lower(self):
231
+ # Solve
232
+ # [ 4 1 2 0] [1]
233
+ # [ 1 4 1 2] X = [4]
234
+ # [ 2 1 4 1] [1]
235
+ # [ 0 2 1 4] [2]
236
+ #
237
+ ab = array([[4.0, 4.0, 4.0, 4.0],
238
+ [1.0, 1.0, 1.0, -99],
239
+ [2.0, 2.0, 0.0, 0.0]])
240
+ b = array([1.0, 4.0, 1.0, 2.0])
241
+ x = solveh_banded(ab, b, lower=True)
242
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
243
+
244
+ def test_02_lower(self):
245
+ # Solve
246
+ # [ 4 1 2 0] [1 6]
247
+ # [ 1 4 1 2] X = [4 2]
248
+ # [ 2 1 4 1] [1 6]
249
+ # [ 0 2 1 4] [2 1]
250
+ #
251
+ ab = array([[4.0, 4.0, 4.0, 4.0],
252
+ [1.0, 1.0, 1.0, -99],
253
+ [2.0, 2.0, 0.0, 0.0]])
254
+ b = array([[1.0, 6.0],
255
+ [4.0, 2.0],
256
+ [1.0, 6.0],
257
+ [2.0, 1.0]])
258
+ x = solveh_banded(ab, b, lower=True)
259
+ expected = array([[0.0, 1.0],
260
+ [1.0, 0.0],
261
+ [0.0, 1.0],
262
+ [0.0, 0.0]])
263
+ assert_array_almost_equal(x, expected)
264
+
265
+ def test_01_float32(self):
266
+ # Solve
267
+ # [ 4 1 2 0] [1]
268
+ # [ 1 4 1 2] X = [4]
269
+ # [ 2 1 4 1] [1]
270
+ # [ 0 2 1 4] [2]
271
+ #
272
+ ab = array([[0.0, 0.0, 2.0, 2.0],
273
+ [-99, 1.0, 1.0, 1.0],
274
+ [4.0, 4.0, 4.0, 4.0]], dtype=float32)
275
+ b = array([1.0, 4.0, 1.0, 2.0], dtype=float32)
276
+ x = solveh_banded(ab, b)
277
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
278
+
279
+ def test_02_float32(self):
280
+ # Solve
281
+ # [ 4 1 2 0] [1 6]
282
+ # [ 1 4 1 2] X = [4 2]
283
+ # [ 2 1 4 1] [1 6]
284
+ # [ 0 2 1 4] [2 1]
285
+ #
286
+ ab = array([[0.0, 0.0, 2.0, 2.0],
287
+ [-99, 1.0, 1.0, 1.0],
288
+ [4.0, 4.0, 4.0, 4.0]], dtype=float32)
289
+ b = array([[1.0, 6.0],
290
+ [4.0, 2.0],
291
+ [1.0, 6.0],
292
+ [2.0, 1.0]], dtype=float32)
293
+ x = solveh_banded(ab, b)
294
+ expected = array([[0.0, 1.0],
295
+ [1.0, 0.0],
296
+ [0.0, 1.0],
297
+ [0.0, 0.0]])
298
+ assert_array_almost_equal(x, expected)
299
+
300
+ def test_01_complex(self):
301
+ # Solve
302
+ # [ 4 -j 2 0] [2-j]
303
+ # [ j 4 -j 2] X = [4-j]
304
+ # [ 2 j 4 -j] [4+j]
305
+ # [ 0 2 j 4] [2+j]
306
+ #
307
+ ab = array([[0.0, 0.0, 2.0, 2.0],
308
+ [-99, -1.0j, -1.0j, -1.0j],
309
+ [4.0, 4.0, 4.0, 4.0]])
310
+ b = array([2-1.0j, 4.0-1j, 4+1j, 2+1j])
311
+ x = solveh_banded(ab, b)
312
+ assert_array_almost_equal(x, [0.0, 1.0, 1.0, 0.0])
313
+
314
+ def test_02_complex(self):
315
+ # Solve
316
+ # [ 4 -j 2 0] [2-j 2+4j]
317
+ # [ j 4 -j 2] X = [4-j -1-j]
318
+ # [ 2 j 4 -j] [4+j 4+2j]
319
+ # [ 0 2 j 4] [2+j j]
320
+ #
321
+ ab = array([[0.0, 0.0, 2.0, 2.0],
322
+ [-99, -1.0j, -1.0j, -1.0j],
323
+ [4.0, 4.0, 4.0, 4.0]])
324
+ b = array([[2-1j, 2+4j],
325
+ [4.0-1j, -1-1j],
326
+ [4.0+1j, 4+2j],
327
+ [2+1j, 1j]])
328
+ x = solveh_banded(ab, b)
329
+ expected = array([[0.0, 1.0j],
330
+ [1.0, 0.0],
331
+ [1.0, 1.0],
332
+ [0.0, 0.0]])
333
+ assert_array_almost_equal(x, expected)
334
+
335
+ def test_tridiag_01_upper(self):
336
+ # Solve
337
+ # [ 4 1 0] [1]
338
+ # [ 1 4 1] X = [4]
339
+ # [ 0 1 4] [1]
340
+ # with the RHS as a 1D array.
341
+ ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
342
+ b = array([1.0, 4.0, 1.0])
343
+ x = solveh_banded(ab, b)
344
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0])
345
+
346
+ def test_tridiag_02_upper(self):
347
+ # Solve
348
+ # [ 4 1 0] [1 4]
349
+ # [ 1 4 1] X = [4 2]
350
+ # [ 0 1 4] [1 4]
351
+ #
352
+ ab = array([[-99, 1.0, 1.0],
353
+ [4.0, 4.0, 4.0]])
354
+ b = array([[1.0, 4.0],
355
+ [4.0, 2.0],
356
+ [1.0, 4.0]])
357
+ x = solveh_banded(ab, b)
358
+ expected = array([[0.0, 1.0],
359
+ [1.0, 0.0],
360
+ [0.0, 1.0]])
361
+ assert_array_almost_equal(x, expected)
362
+
363
+ def test_tridiag_03_upper(self):
364
+ # Solve
365
+ # [ 4 1 0] [1]
366
+ # [ 1 4 1] X = [4]
367
+ # [ 0 1 4] [1]
368
+ # with the RHS as a 2D array with shape (3,1).
369
+ ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
370
+ b = array([1.0, 4.0, 1.0]).reshape(-1, 1)
371
+ x = solveh_banded(ab, b)
372
+ assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1, 1))
373
+
374
+ def test_tridiag_01_lower(self):
375
+ # Solve
376
+ # [ 4 1 0] [1]
377
+ # [ 1 4 1] X = [4]
378
+ # [ 0 1 4] [1]
379
+ #
380
+ ab = array([[4.0, 4.0, 4.0],
381
+ [1.0, 1.0, -99]])
382
+ b = array([1.0, 4.0, 1.0])
383
+ x = solveh_banded(ab, b, lower=True)
384
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0])
385
+
386
+ def test_tridiag_02_lower(self):
387
+ # Solve
388
+ # [ 4 1 0] [1 4]
389
+ # [ 1 4 1] X = [4 2]
390
+ # [ 0 1 4] [1 4]
391
+ #
392
+ ab = array([[4.0, 4.0, 4.0],
393
+ [1.0, 1.0, -99]])
394
+ b = array([[1.0, 4.0],
395
+ [4.0, 2.0],
396
+ [1.0, 4.0]])
397
+ x = solveh_banded(ab, b, lower=True)
398
+ expected = array([[0.0, 1.0],
399
+ [1.0, 0.0],
400
+ [0.0, 1.0]])
401
+ assert_array_almost_equal(x, expected)
402
+
403
+ def test_tridiag_01_float32(self):
404
+ # Solve
405
+ # [ 4 1 0] [1]
406
+ # [ 1 4 1] X = [4]
407
+ # [ 0 1 4] [1]
408
+ #
409
+ ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32)
410
+ b = array([1.0, 4.0, 1.0], dtype=float32)
411
+ x = solveh_banded(ab, b)
412
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0])
413
+
414
+ def test_tridiag_02_float32(self):
415
+ # Solve
416
+ # [ 4 1 0] [1 4]
417
+ # [ 1 4 1] X = [4 2]
418
+ # [ 0 1 4] [1 4]
419
+ #
420
+ ab = array([[-99, 1.0, 1.0],
421
+ [4.0, 4.0, 4.0]], dtype=float32)
422
+ b = array([[1.0, 4.0],
423
+ [4.0, 2.0],
424
+ [1.0, 4.0]], dtype=float32)
425
+ x = solveh_banded(ab, b)
426
+ expected = array([[0.0, 1.0],
427
+ [1.0, 0.0],
428
+ [0.0, 1.0]])
429
+ assert_array_almost_equal(x, expected)
430
+
431
+ def test_tridiag_01_complex(self):
432
+ # Solve
433
+ # [ 4 -j 0] [ -j]
434
+ # [ j 4 -j] X = [4-j]
435
+ # [ 0 j 4] [4+j]
436
+ #
437
+ ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]])
438
+ b = array([-1.0j, 4.0-1j, 4+1j])
439
+ x = solveh_banded(ab, b)
440
+ assert_array_almost_equal(x, [0.0, 1.0, 1.0])
441
+
442
+ def test_tridiag_02_complex(self):
443
+ # Solve
444
+ # [ 4 -j 0] [ -j 4j]
445
+ # [ j 4 -j] X = [4-j -1-j]
446
+ # [ 0 j 4] [4+j 4 ]
447
+ #
448
+ ab = array([[-99, -1.0j, -1.0j],
449
+ [4.0, 4.0, 4.0]])
450
+ b = array([[-1j, 4.0j],
451
+ [4.0-1j, -1.0-1j],
452
+ [4.0+1j, 4.0]])
453
+ x = solveh_banded(ab, b)
454
+ expected = array([[0.0, 1.0j],
455
+ [1.0, 0.0],
456
+ [1.0, 1.0]])
457
+ assert_array_almost_equal(x, expected)
458
+
459
+ def test_check_finite(self):
460
+ # Solve
461
+ # [ 4 1 0] [1]
462
+ # [ 1 4 1] X = [4]
463
+ # [ 0 1 4] [1]
464
+ # with the RHS as a 1D array.
465
+ ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
466
+ b = array([1.0, 4.0, 1.0])
467
+ x = solveh_banded(ab, b, check_finite=False)
468
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0])
469
+
470
+ def test_bad_shapes(self):
471
+ ab = array([[-99, 1.0, 1.0],
472
+ [4.0, 4.0, 4.0]])
473
+ b = array([[1.0, 4.0],
474
+ [4.0, 2.0]])
475
+ assert_raises(ValueError, solveh_banded, ab, b)
476
+ assert_raises(ValueError, solveh_banded, ab, [1.0, 2.0])
477
+ assert_raises(ValueError, solveh_banded, ab, [1.0])
478
+
479
+ def test_1x1(self):
480
+ x = solveh_banded([[1]], [[1, 2, 3]])
481
+ assert_array_equal(x, [[1.0, 2.0, 3.0]])
482
+ assert_equal(x.dtype, np.dtype('f8'))
483
+
484
+ def test_native_list_arguments(self):
485
+ # Same as test_01_upper, using python's native list.
486
+ ab = [[0.0, 0.0, 2.0, 2.0],
487
+ [-99, 1.0, 1.0, 1.0],
488
+ [4.0, 4.0, 4.0, 4.0]]
489
+ b = [1.0, 4.0, 1.0, 2.0]
490
+ x = solveh_banded(ab, b)
491
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
492
+
493
+
494
+ class TestSolve:
495
+ def setup_method(self):
496
+ np.random.seed(1234)
497
+
498
+ def test_20Feb04_bug(self):
499
+ a = [[1, 1], [1.0, 0]] # ok
500
+ x0 = solve(a, [1, 0j])
501
+ assert_array_almost_equal(dot(a, x0), [1, 0])
502
+
503
+ # gives failure with clapack.zgesv(..,rowmajor=0)
504
+ a = [[1, 1], [1.2, 0]]
505
+ b = [1, 0j]
506
+ x0 = solve(a, b)
507
+ assert_array_almost_equal(dot(a, x0), [1, 0])
508
+
509
+ def test_simple(self):
510
+ a = [[1, 20], [-30, 4]]
511
+ for b in ([[1, 0], [0, 1]],
512
+ [1, 0],
513
+ [[2, 1], [-30, 4]]
514
+ ):
515
+ x = solve(a, b)
516
+ assert_array_almost_equal(dot(a, x), b)
517
+
518
+ def test_simple_complex(self):
519
+ a = array([[5, 2], [2j, 4]], 'D')
520
+ for b in ([1j, 0],
521
+ [[1j, 1j], [0, 2]],
522
+ [1, 0j],
523
+ array([1, 0], 'D'),
524
+ ):
525
+ x = solve(a, b)
526
+ assert_array_almost_equal(dot(a, x), b)
527
+
528
+ def test_simple_pos(self):
529
+ a = [[2, 3], [3, 5]]
530
+ for lower in [0, 1]:
531
+ for b in ([[1, 0], [0, 1]],
532
+ [1, 0]
533
+ ):
534
+ x = solve(a, b, assume_a='pos', lower=lower)
535
+ assert_array_almost_equal(dot(a, x), b)
536
+
537
+ def test_simple_pos_complexb(self):
538
+ a = [[5, 2], [2, 4]]
539
+ for b in ([1j, 0],
540
+ [[1j, 1j], [0, 2]],
541
+ ):
542
+ x = solve(a, b, assume_a='pos')
543
+ assert_array_almost_equal(dot(a, x), b)
544
+
545
+ def test_simple_sym(self):
546
+ a = [[2, 3], [3, -5]]
547
+ for lower in [0, 1]:
548
+ for b in ([[1, 0], [0, 1]],
549
+ [1, 0]
550
+ ):
551
+ x = solve(a, b, assume_a='sym', lower=lower)
552
+ assert_array_almost_equal(dot(a, x), b)
553
+
554
+ def test_simple_sym_complexb(self):
555
+ a = [[5, 2], [2, -4]]
556
+ for b in ([1j, 0],
557
+ [[1j, 1j], [0, 2]]
558
+ ):
559
+ x = solve(a, b, assume_a='sym')
560
+ assert_array_almost_equal(dot(a, x), b)
561
+
562
+ def test_simple_sym_complex(self):
563
+ a = [[5, 2+1j], [2+1j, -4]]
564
+ for b in ([1j, 0],
565
+ [1, 0],
566
+ [[1j, 1j], [0, 2]]
567
+ ):
568
+ x = solve(a, b, assume_a='sym')
569
+ assert_array_almost_equal(dot(a, x), b)
570
+
571
+ def test_simple_her_actuallysym(self):
572
+ a = [[2, 3], [3, -5]]
573
+ for lower in [0, 1]:
574
+ for b in ([[1, 0], [0, 1]],
575
+ [1, 0],
576
+ [1j, 0],
577
+ ):
578
+ x = solve(a, b, assume_a='her', lower=lower)
579
+ assert_array_almost_equal(dot(a, x), b)
580
+
581
+ def test_simple_her(self):
582
+ a = [[5, 2+1j], [2-1j, -4]]
583
+ for b in ([1j, 0],
584
+ [1, 0],
585
+ [[1j, 1j], [0, 2]]
586
+ ):
587
+ x = solve(a, b, assume_a='her')
588
+ assert_array_almost_equal(dot(a, x), b)
589
+
590
+ def test_nils_20Feb04(self):
591
+ n = 2
592
+ A = random([n, n])+random([n, n])*1j
593
+ X = zeros((n, n), 'D')
594
+ Ainv = inv(A)
595
+ R = identity(n)+identity(n)*0j
596
+ for i in arange(0, n):
597
+ r = R[:, i]
598
+ X[:, i] = solve(A, r)
599
+ assert_array_almost_equal(X, Ainv)
600
+
601
+ def test_random(self):
602
+
603
+ n = 20
604
+ a = random([n, n])
605
+ for i in range(n):
606
+ a[i, i] = 20*(.1+a[i, i])
607
+ for i in range(4):
608
+ b = random([n, 3])
609
+ x = solve(a, b)
610
+ assert_array_almost_equal(dot(a, x), b)
611
+
612
+ def test_random_complex(self):
613
+ n = 20
614
+ a = random([n, n]) + 1j * random([n, n])
615
+ for i in range(n):
616
+ a[i, i] = 20*(.1+a[i, i])
617
+ for i in range(2):
618
+ b = random([n, 3])
619
+ x = solve(a, b)
620
+ assert_array_almost_equal(dot(a, x), b)
621
+
622
+ def test_random_sym(self):
623
+ n = 20
624
+ a = random([n, n])
625
+ for i in range(n):
626
+ a[i, i] = abs(20*(.1+a[i, i]))
627
+ for j in range(i):
628
+ a[i, j] = a[j, i]
629
+ for i in range(4):
630
+ b = random([n])
631
+ x = solve(a, b, assume_a="pos")
632
+ assert_array_almost_equal(dot(a, x), b)
633
+
634
+ def test_random_sym_complex(self):
635
+ n = 20
636
+ a = random([n, n])
637
+ a = a + 1j*random([n, n])
638
+ for i in range(n):
639
+ a[i, i] = abs(20*(.1+a[i, i]))
640
+ for j in range(i):
641
+ a[i, j] = conjugate(a[j, i])
642
+ b = random([n])+2j*random([n])
643
+ for i in range(2):
644
+ x = solve(a, b, assume_a="pos")
645
+ assert_array_almost_equal(dot(a, x), b)
646
+
647
+ def test_check_finite(self):
648
+ a = [[1, 20], [-30, 4]]
649
+ for b in ([[1, 0], [0, 1]], [1, 0],
650
+ [[2, 1], [-30, 4]]):
651
+ x = solve(a, b, check_finite=False)
652
+ assert_array_almost_equal(dot(a, x), b)
653
+
654
+ def test_scalar_a_and_1D_b(self):
655
+ a = 1
656
+ b = [1, 2, 3]
657
+ x = solve(a, b)
658
+ assert_array_almost_equal(x.ravel(), b)
659
+ assert_(x.shape == (3,), 'Scalar_a_1D_b test returned wrong shape')
660
+
661
+ def test_simple2(self):
662
+ a = np.array([[1.80, 2.88, 2.05, -0.89],
663
+ [525.00, -295.00, -95.00, -380.00],
664
+ [1.58, -2.69, -2.90, -1.04],
665
+ [-1.11, -0.66, -0.59, 0.80]])
666
+
667
+ b = np.array([[9.52, 18.47],
668
+ [2435.00, 225.00],
669
+ [0.77, -13.28],
670
+ [-6.22, -6.21]])
671
+
672
+ x = solve(a, b)
673
+ assert_array_almost_equal(x, np.array([[1., -1, 3, -5],
674
+ [3, 2, 4, 1]]).T)
675
+
676
+ def test_simple_complex2(self):
677
+ a = np.array([[-1.34+2.55j, 0.28+3.17j, -6.39-2.20j, 0.72-0.92j],
678
+ [-1.70-14.10j, 33.10-1.50j, -1.50+13.40j, 12.90+13.80j],
679
+ [-3.29-2.39j, -1.91+4.42j, -0.14-1.35j, 1.72+1.35j],
680
+ [2.41+0.39j, -0.56+1.47j, -0.83-0.69j, -1.96+0.67j]])
681
+
682
+ b = np.array([[26.26+51.78j, 31.32-6.70j],
683
+ [64.30-86.80j, 158.60-14.20j],
684
+ [-5.75+25.31j, -2.15+30.19j],
685
+ [1.16+2.57j, -2.56+7.55j]])
686
+
687
+ x = solve(a, b)
688
+ assert_array_almost_equal(x, np. array([[1+1.j, -1-2.j],
689
+ [2-3.j, 5+1.j],
690
+ [-4-5.j, -3+4.j],
691
+ [6.j, 2-3.j]]))
692
+
693
+ def test_hermitian(self):
694
+ # An upper triangular matrix will be used for hermitian matrix a
695
+ a = np.array([[-1.84, 0.11-0.11j, -1.78-1.18j, 3.91-1.50j],
696
+ [0, -4.63, -1.84+0.03j, 2.21+0.21j],
697
+ [0, 0, -8.87, 1.58-0.90j],
698
+ [0, 0, 0, -1.36]])
699
+ b = np.array([[2.98-10.18j, 28.68-39.89j],
700
+ [-9.58+3.88j, -24.79-8.40j],
701
+ [-0.77-16.05j, 4.23-70.02j],
702
+ [7.79+5.48j, -35.39+18.01j]])
703
+ res = np.array([[2.+1j, -8+6j],
704
+ [3.-2j, 7-2j],
705
+ [-1+2j, -1+5j],
706
+ [1.-1j, 3-4j]])
707
+ x = solve(a, b, assume_a='her')
708
+ assert_array_almost_equal(x, res)
709
+ # Also conjugate a and test for lower triangular data
710
+ x = solve(a.conj().T, b, assume_a='her', lower=True)
711
+ assert_array_almost_equal(x, res)
712
+
713
+ def test_pos_and_sym(self):
714
+ A = np.arange(1, 10).reshape(3, 3)
715
+ x = solve(np.tril(A)/9, np.ones(3), assume_a='pos')
716
+ assert_array_almost_equal(x, [9., 1.8, 1.])
717
+ x = solve(np.tril(A)/9, np.ones(3), assume_a='sym')
718
+ assert_array_almost_equal(x, [9., 1.8, 1.])
719
+
720
+ def test_singularity(self):
721
+ a = np.array([[1, 0, 0, 0, 0, 0, 1, 0, 1],
722
+ [1, 1, 1, 0, 0, 0, 1, 0, 1],
723
+ [0, 1, 1, 0, 0, 0, 1, 0, 1],
724
+ [1, 0, 1, 1, 1, 1, 0, 0, 0],
725
+ [1, 0, 1, 1, 1, 1, 0, 0, 0],
726
+ [1, 0, 1, 1, 1, 1, 0, 0, 0],
727
+ [1, 0, 1, 1, 1, 1, 0, 0, 0],
728
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
729
+ [1, 1, 1, 1, 1, 1, 1, 1, 1]])
730
+ b = np.arange(9)[:, None]
731
+ assert_raises(LinAlgError, solve, a, b)
732
+
733
+ def test_ill_condition_warning(self):
734
+ a = np.array([[1, 1], [1+1e-16, 1-1e-16]])
735
+ b = np.ones(2)
736
+ with warnings.catch_warnings():
737
+ warnings.simplefilter('error')
738
+ assert_raises(LinAlgWarning, solve, a, b)
739
+
740
+ def test_empty_rhs(self):
741
+ a = np.eye(2)
742
+ b = [[], []]
743
+ x = solve(a, b)
744
+ assert_(x.size == 0, 'Returned array is not empty')
745
+ assert_(x.shape == (2, 0), 'Returned empty array shape is wrong')
746
+
747
+ def test_multiple_rhs(self):
748
+ a = np.eye(2)
749
+ b = np.random.rand(2, 3, 4)
750
+ x = solve(a, b)
751
+ assert_array_almost_equal(x, b)
752
+
753
+ def test_transposed_keyword(self):
754
+ A = np.arange(9).reshape(3, 3) + 1
755
+ x = solve(np.tril(A)/9, np.ones(3), transposed=True)
756
+ assert_array_almost_equal(x, [1.2, 0.2, 1])
757
+ x = solve(np.tril(A)/9, np.ones(3), transposed=False)
758
+ assert_array_almost_equal(x, [9, -5.4, -1.2])
759
+
760
+ def test_transposed_notimplemented(self):
761
+ a = np.eye(3).astype(complex)
762
+ with assert_raises(NotImplementedError):
763
+ solve(a, a, transposed=True)
764
+
765
+ def test_nonsquare_a(self):
766
+ assert_raises(ValueError, solve, [1, 2], 1)
767
+
768
+ def test_size_mismatch_with_1D_b(self):
769
+ assert_array_almost_equal(solve(np.eye(3), np.ones(3)), np.ones(3))
770
+ assert_raises(ValueError, solve, np.eye(3), np.ones(4))
771
+
772
+ def test_assume_a_keyword(self):
773
+ assert_raises(ValueError, solve, 1, 1, assume_a='zxcv')
774
+
775
+ @pytest.mark.skip(reason="Failure on OS X (gh-7500), "
776
+ "crash on Windows (gh-8064)")
777
+ def test_all_type_size_routine_combinations(self):
778
+ sizes = [10, 100]
779
+ assume_as = ['gen', 'sym', 'pos', 'her']
780
+ dtypes = [np.float32, np.float64, np.complex64, np.complex128]
781
+ for size, assume_a, dtype in itertools.product(sizes, assume_as,
782
+ dtypes):
783
+ is_complex = dtype in (np.complex64, np.complex128)
784
+ if assume_a == 'her' and not is_complex:
785
+ continue
786
+
787
+ err_msg = (f"Failed for size: {size}, assume_a: {assume_a},"
788
+ f"dtype: {dtype}")
789
+
790
+ a = np.random.randn(size, size).astype(dtype)
791
+ b = np.random.randn(size).astype(dtype)
792
+ if is_complex:
793
+ a = a + (1j*np.random.randn(size, size)).astype(dtype)
794
+
795
+ if assume_a == 'sym': # Can still be complex but only symmetric
796
+ a = a + a.T
797
+ elif assume_a == 'her': # Handle hermitian matrices here instead
798
+ a = a + a.T.conj()
799
+ elif assume_a == 'pos':
800
+ a = a.conj().T.dot(a) + 0.1*np.eye(size)
801
+
802
+ tol = 1e-12 if dtype in (np.float64, np.complex128) else 1e-6
803
+
804
+ if assume_a in ['gen', 'sym', 'her']:
805
+ # We revert the tolerance from before
806
+ # 4b4a6e7c34fa4060533db38f9a819b98fa81476c
807
+ if dtype in (np.float32, np.complex64):
808
+ tol *= 10
809
+
810
+ x = solve(a, b, assume_a=assume_a)
811
+ assert_allclose(a.dot(x), b,
812
+ atol=tol * size,
813
+ rtol=tol * size,
814
+ err_msg=err_msg)
815
+
816
+ if assume_a == 'sym' and dtype not in (np.complex64,
817
+ np.complex128):
818
+ x = solve(a, b, assume_a=assume_a, transposed=True)
819
+ assert_allclose(a.dot(x), b,
820
+ atol=tol * size,
821
+ rtol=tol * size,
822
+ err_msg=err_msg)
823
+
824
+
825
+ class TestSolveTriangular:
826
+
827
+ def test_simple(self):
828
+ """
829
+ solve_triangular on a simple 2x2 matrix.
830
+ """
831
+ A = array([[1, 0], [1, 2]])
832
+ b = [1, 1]
833
+ sol = solve_triangular(A, b, lower=True)
834
+ assert_array_almost_equal(sol, [1, 0])
835
+
836
+ # check that it works also for non-contiguous matrices
837
+ sol = solve_triangular(A.T, b, lower=False)
838
+ assert_array_almost_equal(sol, [.5, .5])
839
+
840
+ # and that it gives the same result as trans=1
841
+ sol = solve_triangular(A, b, lower=True, trans=1)
842
+ assert_array_almost_equal(sol, [.5, .5])
843
+
844
+ b = identity(2)
845
+ sol = solve_triangular(A, b, lower=True, trans=1)
846
+ assert_array_almost_equal(sol, [[1., -.5], [0, 0.5]])
847
+
848
+ def test_simple_complex(self):
849
+ """
850
+ solve_triangular on a simple 2x2 complex matrix
851
+ """
852
+ A = array([[1+1j, 0], [1j, 2]])
853
+ b = identity(2)
854
+ sol = solve_triangular(A, b, lower=True, trans=1)
855
+ assert_array_almost_equal(sol, [[.5-.5j, -.25-.25j], [0, 0.5]])
856
+
857
+ # check other option combinations with complex rhs
858
+ b = np.diag([1+1j, 1+2j])
859
+ sol = solve_triangular(A, b, lower=True, trans=0)
860
+ assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]])
861
+
862
+ sol = solve_triangular(A, b, lower=True, trans=1)
863
+ assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]])
864
+
865
+ sol = solve_triangular(A, b, lower=True, trans=2)
866
+ assert_array_almost_equal(sol, [[1j, -0.75-0.25j], [0, 0.5+1j]])
867
+
868
+ sol = solve_triangular(A.T, b, lower=False, trans=0)
869
+ assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]])
870
+
871
+ sol = solve_triangular(A.T, b, lower=False, trans=1)
872
+ assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]])
873
+
874
+ sol = solve_triangular(A.T, b, lower=False, trans=2)
875
+ assert_array_almost_equal(sol, [[1j, 0], [-0.5, 0.5+1j]])
876
+
877
+ def test_check_finite(self):
878
+ """
879
+ solve_triangular on a simple 2x2 matrix.
880
+ """
881
+ A = array([[1, 0], [1, 2]])
882
+ b = [1, 1]
883
+ sol = solve_triangular(A, b, lower=True, check_finite=False)
884
+ assert_array_almost_equal(sol, [1, 0])
885
+
886
+
887
+ class TestInv:
888
+ def setup_method(self):
889
+ np.random.seed(1234)
890
+
891
+ def test_simple(self):
892
+ a = [[1, 2], [3, 4]]
893
+ a_inv = inv(a)
894
+ assert_array_almost_equal(dot(a, a_inv), np.eye(2))
895
+ a = [[1, 2, 3], [4, 5, 6], [7, 8, 10]]
896
+ a_inv = inv(a)
897
+ assert_array_almost_equal(dot(a, a_inv), np.eye(3))
898
+
899
+ def test_random(self):
900
+ n = 20
901
+ for i in range(4):
902
+ a = random([n, n])
903
+ for i in range(n):
904
+ a[i, i] = 20*(.1+a[i, i])
905
+ a_inv = inv(a)
906
+ assert_array_almost_equal(dot(a, a_inv),
907
+ identity(n))
908
+
909
+ def test_simple_complex(self):
910
+ a = [[1, 2], [3, 4j]]
911
+ a_inv = inv(a)
912
+ assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]])
913
+
914
+ def test_random_complex(self):
915
+ n = 20
916
+ for i in range(4):
917
+ a = random([n, n])+2j*random([n, n])
918
+ for i in range(n):
919
+ a[i, i] = 20*(.1+a[i, i])
920
+ a_inv = inv(a)
921
+ assert_array_almost_equal(dot(a, a_inv),
922
+ identity(n))
923
+
924
+ def test_check_finite(self):
925
+ a = [[1, 2], [3, 4]]
926
+ a_inv = inv(a, check_finite=False)
927
+ assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]])
928
+
929
+
930
+ class TestDet:
931
+ def setup_method(self):
932
+ self.rng = np.random.default_rng(1680305949878959)
933
+
934
+ def test_1x1_all_singleton_dims(self):
935
+ a = np.array([[1]])
936
+ deta = det(a)
937
+ assert deta.dtype.char == 'd'
938
+ assert np.isscalar(deta)
939
+ assert deta == 1.
940
+ a = np.array([[[[1]]]], dtype='f')
941
+ deta = det(a)
942
+ assert deta.dtype.char == 'd'
943
+ assert np.isscalar(deta)
944
+ assert deta == 1.
945
+ a = np.array([[[1 + 3.j]]], dtype=np.complex64)
946
+ deta = det(a)
947
+ assert deta.dtype.char == 'D'
948
+ assert np.isscalar(deta)
949
+ assert deta == 1.+3.j
950
+
951
+ def test_1by1_stacked_input_output(self):
952
+ a = self.rng.random([4, 5, 1, 1], dtype=np.float32)
953
+ deta = det(a)
954
+ assert deta.dtype.char == 'd'
955
+ assert deta.shape == (4, 5)
956
+ assert_allclose(deta, np.squeeze(a))
957
+
958
+ a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j)
959
+ deta = det(a)
960
+ assert deta.dtype.char == 'D'
961
+ assert deta.shape == (4, 5)
962
+ assert_allclose(deta, np.squeeze(a))
963
+
964
+ @pytest.mark.parametrize('shape', [[2, 2], [20, 20], [3, 2, 20, 20]])
965
+ def test_simple_det_shapes_real_complex(self, shape):
966
+ a = self.rng.uniform(-1., 1., size=shape)
967
+ d1, d2 = det(a), np.linalg.det(a)
968
+ assert_allclose(d1, d2)
969
+
970
+ b = self.rng.uniform(-1., 1., size=shape)*1j
971
+ b += self.rng.uniform(-0.5, 0.5, size=shape)
972
+ d3, d4 = det(b), np.linalg.det(b)
973
+ assert_allclose(d3, d4)
974
+
975
+ def test_for_known_det_values(self):
976
+ # Hadamard8
977
+ a = np.array([[1, 1, 1, 1, 1, 1, 1, 1],
978
+ [1, -1, 1, -1, 1, -1, 1, -1],
979
+ [1, 1, -1, -1, 1, 1, -1, -1],
980
+ [1, -1, -1, 1, 1, -1, -1, 1],
981
+ [1, 1, 1, 1, -1, -1, -1, -1],
982
+ [1, -1, 1, -1, -1, 1, -1, 1],
983
+ [1, 1, -1, -1, -1, -1, 1, 1],
984
+ [1, -1, -1, 1, -1, 1, 1, -1]])
985
+ assert_allclose(det(a), 4096.)
986
+
987
+ # consecutive number array always singular
988
+ assert_allclose(det(np.arange(25).reshape(5, 5)), 0.)
989
+
990
+ # simple anti-diagonal block array
991
+ # Upper right has det (-2+1j) and lower right has (-2-1j)
992
+ # det(a) = - (-2+1j) (-2-1j) = 5.
993
+ a = np.array([[0.+0.j, 0.+0.j, 0.-1.j, 1.-1.j],
994
+ [0.+0.j, 0.+0.j, 1.+0.j, 0.-1.j],
995
+ [0.+1.j, 1.+1.j, 0.+0.j, 0.+0.j],
996
+ [1.+0.j, 0.+1.j, 0.+0.j, 0.+0.j]], dtype=np.complex64)
997
+ assert_allclose(det(a), 5.+0.j)
998
+
999
+ # Fiedler companion complexified
1000
+ # >>> a = scipy.linalg.fiedler_companion(np.arange(1, 10))
1001
+ a = np.array([[-2., -3., 1., 0., 0., 0., 0., 0.],
1002
+ [1., 0., 0., 0., 0., 0., 0., 0.],
1003
+ [0., -4., 0., -5., 1., 0., 0., 0.],
1004
+ [0., 1., 0., 0., 0., 0., 0., 0.],
1005
+ [0., 0., 0., -6., 0., -7., 1., 0.],
1006
+ [0., 0., 0., 1., 0., 0., 0., 0.],
1007
+ [0., 0., 0., 0., 0., -8., 0., -9.],
1008
+ [0., 0., 0., 0., 0., 1., 0., 0.]])*1.j
1009
+ assert_allclose(det(a), 9.)
1010
+
1011
+ # g and G dtypes are handled differently in windows and other platforms
1012
+ @pytest.mark.parametrize('typ', [x for x in np.typecodes['All'][:20]
1013
+ if x not in 'gG'])
1014
+ def test_sample_compatible_dtype_input(self, typ):
1015
+ n = 4
1016
+ a = self.rng.random([n, n]).astype(typ) # value is not important
1017
+ assert isinstance(det(a), (np.float64, np.complex128))
1018
+
1019
+ def test_incompatible_dtype_input(self):
1020
+ # Double backslashes needed for escaping pytest regex.
1021
+ msg = 'cannot be cast to float\\(32, 64\\)'
1022
+
1023
+ for c, t in zip('SUO', ['bytes8', 'str32', 'object']):
1024
+ with assert_raises(TypeError, match=msg):
1025
+ det(np.array([['a', 'b']]*2, dtype=c))
1026
+ with assert_raises(TypeError, match=msg):
1027
+ det(np.array([[b'a', b'b']]*2, dtype='V'))
1028
+ with assert_raises(TypeError, match=msg):
1029
+ det(np.array([[100, 200]]*2, dtype='datetime64[s]'))
1030
+ with assert_raises(TypeError, match=msg):
1031
+ det(np.array([[100, 200]]*2, dtype='timedelta64[s]'))
1032
+
1033
+ def test_empty_edge_cases(self):
1034
+ assert_allclose(det(np.empty([0, 0])), 1.)
1035
+ assert_allclose(det(np.empty([0, 0, 0])), np.array([]))
1036
+ assert_allclose(det(np.empty([3, 0, 0])), np.array([1., 1., 1.]))
1037
+ with assert_raises(ValueError, match='Last 2 dimensions'):
1038
+ det(np.empty([0, 0, 3]))
1039
+ with assert_raises(ValueError, match='at least two-dimensional'):
1040
+ det(np.array([]))
1041
+ with assert_raises(ValueError, match='Last 2 dimensions'):
1042
+ det(np.array([[]]))
1043
+ with assert_raises(ValueError, match='Last 2 dimensions'):
1044
+ det(np.array([[[]]]))
1045
+
1046
+ def test_overwrite_a(self):
1047
+ # If all conditions are met then input should be overwritten;
1048
+ # - dtype is one of 'fdFD'
1049
+ # - C-contiguous
1050
+ # - writeable
1051
+ a = np.arange(9).reshape(3, 3).astype(np.float32)
1052
+ ac = a.copy()
1053
+ deta = det(ac, overwrite_a=True)
1054
+ assert_allclose(deta, 0.)
1055
+ assert not (a == ac).all()
1056
+
1057
+ def test_readonly_array(self):
1058
+ a = np.array([[2., 0., 1.], [5., 3., -1.], [1., 1., 1.]])
1059
+ a.setflags(write=False)
1060
+ # overwrite_a will be overridden
1061
+ assert_allclose(det(a, overwrite_a=True), 10.)
1062
+
1063
+ def test_simple_check_finite(self):
1064
+ a = [[1, 2], [3, np.inf]]
1065
+ with assert_raises(ValueError, match='array must not contain'):
1066
+ det(a)
1067
+
1068
+
1069
+ def direct_lstsq(a, b, cmplx=0):
1070
+ at = transpose(a)
1071
+ if cmplx:
1072
+ at = conjugate(at)
1073
+ a1 = dot(at, a)
1074
+ b1 = dot(at, b)
1075
+ return solve(a1, b1)
1076
+
1077
+
1078
+ class TestLstsq:
1079
+ lapack_drivers = ('gelsd', 'gelss', 'gelsy', None)
1080
+
1081
+ def test_simple_exact(self):
1082
+ for dtype in REAL_DTYPES:
1083
+ a = np.array([[1, 20], [-30, 4]], dtype=dtype)
1084
+ for lapack_driver in TestLstsq.lapack_drivers:
1085
+ for overwrite in (True, False):
1086
+ for bt in (((1, 0), (0, 1)), (1, 0),
1087
+ ((2, 1), (-30, 4))):
1088
+ # Store values in case they are overwritten
1089
+ # later
1090
+ a1 = a.copy()
1091
+ b = np.array(bt, dtype=dtype)
1092
+ b1 = b.copy()
1093
+ out = lstsq(a1, b1,
1094
+ lapack_driver=lapack_driver,
1095
+ overwrite_a=overwrite,
1096
+ overwrite_b=overwrite)
1097
+ x = out[0]
1098
+ r = out[2]
1099
+ assert_(r == 2,
1100
+ 'expected efficient rank 2, got %s' % r)
1101
+ assert_allclose(dot(a, x), b,
1102
+ atol=25 * _eps_cast(a1.dtype),
1103
+ rtol=25 * _eps_cast(a1.dtype),
1104
+ err_msg="driver: %s" % lapack_driver)
1105
+
1106
+ def test_simple_overdet(self):
1107
+ for dtype in REAL_DTYPES:
1108
+ a = np.array([[1, 2], [4, 5], [3, 4]], dtype=dtype)
1109
+ b = np.array([1, 2, 3], dtype=dtype)
1110
+ for lapack_driver in TestLstsq.lapack_drivers:
1111
+ for overwrite in (True, False):
1112
+ # Store values in case they are overwritten later
1113
+ a1 = a.copy()
1114
+ b1 = b.copy()
1115
+ out = lstsq(a1, b1, lapack_driver=lapack_driver,
1116
+ overwrite_a=overwrite,
1117
+ overwrite_b=overwrite)
1118
+ x = out[0]
1119
+ if lapack_driver == 'gelsy':
1120
+ residuals = np.sum((b - a.dot(x))**2)
1121
+ else:
1122
+ residuals = out[1]
1123
+ r = out[2]
1124
+ assert_(r == 2, 'expected efficient rank 2, got %s' % r)
1125
+ assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0),
1126
+ residuals,
1127
+ rtol=25 * _eps_cast(a1.dtype),
1128
+ atol=25 * _eps_cast(a1.dtype),
1129
+ err_msg="driver: %s" % lapack_driver)
1130
+ assert_allclose(x, (-0.428571428571429, 0.85714285714285),
1131
+ rtol=25 * _eps_cast(a1.dtype),
1132
+ atol=25 * _eps_cast(a1.dtype),
1133
+ err_msg="driver: %s" % lapack_driver)
1134
+
1135
+ def test_simple_overdet_complex(self):
1136
+ for dtype in COMPLEX_DTYPES:
1137
+ a = np.array([[1+2j, 2], [4, 5], [3, 4]], dtype=dtype)
1138
+ b = np.array([1, 2+4j, 3], dtype=dtype)
1139
+ for lapack_driver in TestLstsq.lapack_drivers:
1140
+ for overwrite in (True, False):
1141
+ # Store values in case they are overwritten later
1142
+ a1 = a.copy()
1143
+ b1 = b.copy()
1144
+ out = lstsq(a1, b1, lapack_driver=lapack_driver,
1145
+ overwrite_a=overwrite,
1146
+ overwrite_b=overwrite)
1147
+
1148
+ x = out[0]
1149
+ if lapack_driver == 'gelsy':
1150
+ res = b - a.dot(x)
1151
+ residuals = np.sum(res * res.conj())
1152
+ else:
1153
+ residuals = out[1]
1154
+ r = out[2]
1155
+ assert_(r == 2, 'expected efficient rank 2, got %s' % r)
1156
+ assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0),
1157
+ residuals,
1158
+ rtol=25 * _eps_cast(a1.dtype),
1159
+ atol=25 * _eps_cast(a1.dtype),
1160
+ err_msg="driver: %s" % lapack_driver)
1161
+ assert_allclose(
1162
+ x, (-0.4831460674157303 + 0.258426966292135j,
1163
+ 0.921348314606741 + 0.292134831460674j),
1164
+ rtol=25 * _eps_cast(a1.dtype),
1165
+ atol=25 * _eps_cast(a1.dtype),
1166
+ err_msg="driver: %s" % lapack_driver)
1167
+
1168
+ def test_simple_underdet(self):
1169
+ for dtype in REAL_DTYPES:
1170
+ a = np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype)
1171
+ b = np.array([1, 2], dtype=dtype)
1172
+ for lapack_driver in TestLstsq.lapack_drivers:
1173
+ for overwrite in (True, False):
1174
+ # Store values in case they are overwritten later
1175
+ a1 = a.copy()
1176
+ b1 = b.copy()
1177
+ out = lstsq(a1, b1, lapack_driver=lapack_driver,
1178
+ overwrite_a=overwrite,
1179
+ overwrite_b=overwrite)
1180
+
1181
+ x = out[0]
1182
+ r = out[2]
1183
+ assert_(r == 2, 'expected efficient rank 2, got %s' % r)
1184
+ assert_allclose(x, (-0.055555555555555, 0.111111111111111,
1185
+ 0.277777777777777),
1186
+ rtol=25 * _eps_cast(a1.dtype),
1187
+ atol=25 * _eps_cast(a1.dtype),
1188
+ err_msg="driver: %s" % lapack_driver)
1189
+
1190
+ def test_random_exact(self):
1191
+ rng = np.random.RandomState(1234)
1192
+ for dtype in REAL_DTYPES:
1193
+ for n in (20, 200):
1194
+ for lapack_driver in TestLstsq.lapack_drivers:
1195
+ for overwrite in (True, False):
1196
+ a = np.asarray(rng.random([n, n]), dtype=dtype)
1197
+ for i in range(n):
1198
+ a[i, i] = 20 * (0.1 + a[i, i])
1199
+ for i in range(4):
1200
+ b = np.asarray(rng.random([n, 3]), dtype=dtype)
1201
+ # Store values in case they are overwritten later
1202
+ a1 = a.copy()
1203
+ b1 = b.copy()
1204
+ out = lstsq(a1, b1,
1205
+ lapack_driver=lapack_driver,
1206
+ overwrite_a=overwrite,
1207
+ overwrite_b=overwrite)
1208
+ x = out[0]
1209
+ r = out[2]
1210
+ assert_(r == n, f'expected efficient rank {n}, '
1211
+ f'got {r}')
1212
+ if dtype is np.float32:
1213
+ assert_allclose(
1214
+ dot(a, x), b,
1215
+ rtol=500 * _eps_cast(a1.dtype),
1216
+ atol=500 * _eps_cast(a1.dtype),
1217
+ err_msg="driver: %s" % lapack_driver)
1218
+ else:
1219
+ assert_allclose(
1220
+ dot(a, x), b,
1221
+ rtol=1000 * _eps_cast(a1.dtype),
1222
+ atol=1000 * _eps_cast(a1.dtype),
1223
+ err_msg="driver: %s" % lapack_driver)
1224
+
1225
+ @pytest.mark.skipif(IS_MUSL, reason="may segfault on Alpine, see gh-17630")
1226
+ def test_random_complex_exact(self):
1227
+ rng = np.random.RandomState(1234)
1228
+ for dtype in COMPLEX_DTYPES:
1229
+ for n in (20, 200):
1230
+ for lapack_driver in TestLstsq.lapack_drivers:
1231
+ for overwrite in (True, False):
1232
+ a = np.asarray(rng.random([n, n]) + 1j*rng.random([n, n]),
1233
+ dtype=dtype)
1234
+ for i in range(n):
1235
+ a[i, i] = 20 * (0.1 + a[i, i])
1236
+ for i in range(2):
1237
+ b = np.asarray(rng.random([n, 3]), dtype=dtype)
1238
+ # Store values in case they are overwritten later
1239
+ a1 = a.copy()
1240
+ b1 = b.copy()
1241
+ out = lstsq(a1, b1, lapack_driver=lapack_driver,
1242
+ overwrite_a=overwrite,
1243
+ overwrite_b=overwrite)
1244
+ x = out[0]
1245
+ r = out[2]
1246
+ assert_(r == n, f'expected efficient rank {n}, '
1247
+ f'got {r}')
1248
+ if dtype is np.complex64:
1249
+ assert_allclose(
1250
+ dot(a, x), b,
1251
+ rtol=400 * _eps_cast(a1.dtype),
1252
+ atol=400 * _eps_cast(a1.dtype),
1253
+ err_msg="driver: %s" % lapack_driver)
1254
+ else:
1255
+ assert_allclose(
1256
+ dot(a, x), b,
1257
+ rtol=1000 * _eps_cast(a1.dtype),
1258
+ atol=1000 * _eps_cast(a1.dtype),
1259
+ err_msg="driver: %s" % lapack_driver)
1260
+
1261
+ def test_random_overdet(self):
1262
+ rng = np.random.RandomState(1234)
1263
+ for dtype in REAL_DTYPES:
1264
+ for (n, m) in ((20, 15), (200, 2)):
1265
+ for lapack_driver in TestLstsq.lapack_drivers:
1266
+ for overwrite in (True, False):
1267
+ a = np.asarray(rng.random([n, m]), dtype=dtype)
1268
+ for i in range(m):
1269
+ a[i, i] = 20 * (0.1 + a[i, i])
1270
+ for i in range(4):
1271
+ b = np.asarray(rng.random([n, 3]), dtype=dtype)
1272
+ # Store values in case they are overwritten later
1273
+ a1 = a.copy()
1274
+ b1 = b.copy()
1275
+ out = lstsq(a1, b1,
1276
+ lapack_driver=lapack_driver,
1277
+ overwrite_a=overwrite,
1278
+ overwrite_b=overwrite)
1279
+ x = out[0]
1280
+ r = out[2]
1281
+ assert_(r == m, f'expected efficient rank {m}, '
1282
+ f'got {r}')
1283
+ assert_allclose(
1284
+ x, direct_lstsq(a, b, cmplx=0),
1285
+ rtol=25 * _eps_cast(a1.dtype),
1286
+ atol=25 * _eps_cast(a1.dtype),
1287
+ err_msg="driver: %s" % lapack_driver)
1288
+
1289
+ def test_random_complex_overdet(self):
1290
+ rng = np.random.RandomState(1234)
1291
+ for dtype in COMPLEX_DTYPES:
1292
+ for (n, m) in ((20, 15), (200, 2)):
1293
+ for lapack_driver in TestLstsq.lapack_drivers:
1294
+ for overwrite in (True, False):
1295
+ a = np.asarray(rng.random([n, m]) + 1j*rng.random([n, m]),
1296
+ dtype=dtype)
1297
+ for i in range(m):
1298
+ a[i, i] = 20 * (0.1 + a[i, i])
1299
+ for i in range(2):
1300
+ b = np.asarray(rng.random([n, 3]), dtype=dtype)
1301
+ # Store values in case they are overwritten
1302
+ # later
1303
+ a1 = a.copy()
1304
+ b1 = b.copy()
1305
+ out = lstsq(a1, b1,
1306
+ lapack_driver=lapack_driver,
1307
+ overwrite_a=overwrite,
1308
+ overwrite_b=overwrite)
1309
+ x = out[0]
1310
+ r = out[2]
1311
+ assert_(r == m, f'expected efficient rank {m}, '
1312
+ f'got {r}')
1313
+ assert_allclose(
1314
+ x, direct_lstsq(a, b, cmplx=1),
1315
+ rtol=25 * _eps_cast(a1.dtype),
1316
+ atol=25 * _eps_cast(a1.dtype),
1317
+ err_msg="driver: %s" % lapack_driver)
1318
+
1319
+ def test_check_finite(self):
1320
+ with suppress_warnings() as sup:
1321
+ # On (some) OSX this tests triggers a warning (gh-7538)
1322
+ sup.filter(RuntimeWarning,
1323
+ "internal gelsd driver lwork query error,.*"
1324
+ "Falling back to 'gelss' driver.")
1325
+
1326
+ at = np.array(((1, 20), (-30, 4)))
1327
+ for dtype, bt, lapack_driver, overwrite, check_finite in \
1328
+ itertools.product(REAL_DTYPES,
1329
+ (((1, 0), (0, 1)), (1, 0), ((2, 1), (-30, 4))),
1330
+ TestLstsq.lapack_drivers,
1331
+ (True, False),
1332
+ (True, False)):
1333
+
1334
+ a = at.astype(dtype)
1335
+ b = np.array(bt, dtype=dtype)
1336
+ # Store values in case they are overwritten
1337
+ # later
1338
+ a1 = a.copy()
1339
+ b1 = b.copy()
1340
+ out = lstsq(a1, b1, lapack_driver=lapack_driver,
1341
+ check_finite=check_finite, overwrite_a=overwrite,
1342
+ overwrite_b=overwrite)
1343
+ x = out[0]
1344
+ r = out[2]
1345
+ assert_(r == 2, 'expected efficient rank 2, got %s' % r)
1346
+ assert_allclose(dot(a, x), b,
1347
+ rtol=25 * _eps_cast(a.dtype),
1348
+ atol=25 * _eps_cast(a.dtype),
1349
+ err_msg="driver: %s" % lapack_driver)
1350
+
1351
+ def test_zero_size(self):
1352
+ for a_shape, b_shape in (((0, 2), (0,)),
1353
+ ((0, 4), (0, 2)),
1354
+ ((4, 0), (4,)),
1355
+ ((4, 0), (4, 2))):
1356
+ b = np.ones(b_shape)
1357
+ x, residues, rank, s = lstsq(np.zeros(a_shape), b)
1358
+ assert_equal(x, np.zeros((a_shape[1],) + b_shape[1:]))
1359
+ residues_should_be = (np.empty((0,)) if a_shape[1]
1360
+ else np.linalg.norm(b, axis=0)**2)
1361
+ assert_equal(residues, residues_should_be)
1362
+ assert_(rank == 0, 'expected rank 0')
1363
+ assert_equal(s, np.empty((0,)))
1364
+
1365
+
1366
+ class TestPinv:
1367
+ def setup_method(self):
1368
+ np.random.seed(1234)
1369
+
1370
+ def test_simple_real(self):
1371
+ a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
1372
+ a_pinv = pinv(a)
1373
+ assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
1374
+
1375
+ def test_simple_complex(self):
1376
+ a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]],
1377
+ dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]],
1378
+ dtype=float))
1379
+ a_pinv = pinv(a)
1380
+ assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
1381
+
1382
+ def test_simple_singular(self):
1383
+ a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float)
1384
+ a_pinv = pinv(a)
1385
+ expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01],
1386
+ [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02],
1387
+ [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]])
1388
+ assert_array_almost_equal(a_pinv, expected)
1389
+
1390
+ def test_simple_cols(self):
1391
+ a = array([[1, 2, 3], [4, 5, 6]], dtype=float)
1392
+ a_pinv = pinv(a)
1393
+ expected = array([[-0.94444444, 0.44444444],
1394
+ [-0.11111111, 0.11111111],
1395
+ [0.72222222, -0.22222222]])
1396
+ assert_array_almost_equal(a_pinv, expected)
1397
+
1398
+ def test_simple_rows(self):
1399
+ a = array([[1, 2], [3, 4], [5, 6]], dtype=float)
1400
+ a_pinv = pinv(a)
1401
+ expected = array([[-1.33333333, -0.33333333, 0.66666667],
1402
+ [1.08333333, 0.33333333, -0.41666667]])
1403
+ assert_array_almost_equal(a_pinv, expected)
1404
+
1405
+ def test_check_finite(self):
1406
+ a = array([[1, 2, 3], [4, 5, 6.], [7, 8, 10]])
1407
+ a_pinv = pinv(a, check_finite=False)
1408
+ assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
1409
+
1410
+ def test_native_list_argument(self):
1411
+ a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
1412
+ a_pinv = pinv(a)
1413
+ expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01],
1414
+ [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02],
1415
+ [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]])
1416
+ assert_array_almost_equal(a_pinv, expected)
1417
+
1418
+ def test_atol_rtol(self):
1419
+ n = 12
1420
+ # get a random ortho matrix for shuffling
1421
+ q, _ = qr(np.random.rand(n, n))
1422
+ a_m = np.arange(35.0).reshape(7, 5)
1423
+ a = a_m.copy()
1424
+ a[0, 0] = 0.001
1425
+ atol = 1e-5
1426
+ rtol = 0.05
1427
+ # svds of a_m is ~ [116.906, 4.234, tiny, tiny, tiny]
1428
+ # svds of a is ~ [116.906, 4.234, 4.62959e-04, tiny, tiny]
1429
+ # Just abs cutoff such that we arrive at a_modified
1430
+ a_p = pinv(a_m, atol=atol, rtol=0.)
1431
+ adiff1 = a @ a_p @ a - a
1432
+ adiff2 = a_m @ a_p @ a_m - a_m
1433
+ # Now adiff1 should be around atol value while adiff2 should be
1434
+ # relatively tiny
1435
+ assert_allclose(np.linalg.norm(adiff1), 5e-4, atol=5.e-4)
1436
+ assert_allclose(np.linalg.norm(adiff2), 5e-14, atol=5.e-14)
1437
+
1438
+ # Now do the same but remove another sv ~4.234 via rtol
1439
+ a_p = pinv(a_m, atol=atol, rtol=rtol)
1440
+ adiff1 = a @ a_p @ a - a
1441
+ adiff2 = a_m @ a_p @ a_m - a_m
1442
+ assert_allclose(np.linalg.norm(adiff1), 4.233, rtol=0.01)
1443
+ assert_allclose(np.linalg.norm(adiff2), 4.233, rtol=0.01)
1444
+
1445
+ @pytest.mark.parametrize("cond", [1, None, _NoValue])
1446
+ @pytest.mark.parametrize("rcond", [1, None, _NoValue])
1447
+ def test_cond_rcond_deprecation(self, cond, rcond):
1448
+ if cond is _NoValue and rcond is _NoValue:
1449
+ # the defaults if cond/rcond aren't set -> no warning
1450
+ pinv(np.ones((2,2)), cond=cond, rcond=rcond)
1451
+ else:
1452
+ # at least one of cond/rcond has a user-supplied value -> warn
1453
+ with pytest.deprecated_call(match='"cond" and "rcond"'):
1454
+ pinv(np.ones((2,2)), cond=cond, rcond=rcond)
1455
+
1456
+ def test_positional_deprecation(self):
1457
+ with pytest.deprecated_call(match="use keyword arguments"):
1458
+ pinv(np.ones((2,2)), 0., 1e-10)
1459
+
1460
+
1461
+ class TestPinvSymmetric:
1462
+
1463
+ def setup_method(self):
1464
+ np.random.seed(1234)
1465
+
1466
+ def test_simple_real(self):
1467
+ a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
1468
+ a = np.dot(a, a.T)
1469
+ a_pinv = pinvh(a)
1470
+ assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
1471
+
1472
+ def test_nonpositive(self):
1473
+ a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float)
1474
+ a = np.dot(a, a.T)
1475
+ u, s, vt = np.linalg.svd(a)
1476
+ s[0] *= -1
1477
+ a = np.dot(u * s, vt) # a is now symmetric non-positive and singular
1478
+ a_pinv = pinv(a)
1479
+ a_pinvh = pinvh(a)
1480
+ assert_array_almost_equal(a_pinv, a_pinvh)
1481
+
1482
+ def test_simple_complex(self):
1483
+ a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]],
1484
+ dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]],
1485
+ dtype=float))
1486
+ a = np.dot(a, a.conj().T)
1487
+ a_pinv = pinvh(a)
1488
+ assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
1489
+
1490
+ def test_native_list_argument(self):
1491
+ a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
1492
+ a = np.dot(a, a.T)
1493
+ a_pinv = pinvh(a.tolist())
1494
+ assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
1495
+
1496
+ def test_atol_rtol(self):
1497
+ n = 12
1498
+ # get a random ortho matrix for shuffling
1499
+ q, _ = qr(np.random.rand(n, n))
1500
+ a = np.diag([4, 3, 2, 1, 0.99e-4, 0.99e-5] + [0.99e-6]*(n-6))
1501
+ a = q.T @ a @ q
1502
+ a_m = np.diag([4, 3, 2, 1, 0.99e-4, 0.] + [0.]*(n-6))
1503
+ a_m = q.T @ a_m @ q
1504
+ atol = 1e-5
1505
+ rtol = (4.01e-4 - 4e-5)/4
1506
+ # Just abs cutoff such that we arrive at a_modified
1507
+ a_p = pinvh(a, atol=atol, rtol=0.)
1508
+ adiff1 = a @ a_p @ a - a
1509
+ adiff2 = a_m @ a_p @ a_m - a_m
1510
+ # Now adiff1 should dance around atol value since truncation
1511
+ # while adiff2 should be relatively tiny
1512
+ assert_allclose(norm(adiff1), atol, rtol=0.1)
1513
+ assert_allclose(norm(adiff2), 1e-12, atol=1e-11)
1514
+
1515
+ # Now do the same but through rtol cancelling atol value
1516
+ a_p = pinvh(a, atol=atol, rtol=rtol)
1517
+ adiff1 = a @ a_p @ a - a
1518
+ adiff2 = a_m @ a_p @ a_m - a_m
1519
+ # adiff1 and adiff2 should be elevated to ~1e-4 due to mismatch
1520
+ assert_allclose(norm(adiff1), 1e-4, rtol=0.1)
1521
+ assert_allclose(norm(adiff2), 1e-4, rtol=0.1)
1522
+
1523
+
1524
+ @pytest.mark.parametrize('scale', (1e-20, 1., 1e20))
1525
+ @pytest.mark.parametrize('pinv_', (pinv, pinvh))
1526
+ def test_auto_rcond(scale, pinv_):
1527
+ x = np.array([[1, 0], [0, 1e-10]]) * scale
1528
+ expected = np.diag(1. / np.diag(x))
1529
+ x_inv = pinv_(x)
1530
+ assert_allclose(x_inv, expected)
1531
+
1532
+
1533
+ class TestVectorNorms:
1534
+
1535
+ def test_types(self):
1536
+ for dtype in np.typecodes['AllFloat']:
1537
+ x = np.array([1, 2, 3], dtype=dtype)
1538
+ tol = max(1e-15, np.finfo(dtype).eps.real * 20)
1539
+ assert_allclose(norm(x), np.sqrt(14), rtol=tol)
1540
+ assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
1541
+
1542
+ for dtype in np.typecodes['Complex']:
1543
+ x = np.array([1j, 2j, 3j], dtype=dtype)
1544
+ tol = max(1e-15, np.finfo(dtype).eps.real * 20)
1545
+ assert_allclose(norm(x), np.sqrt(14), rtol=tol)
1546
+ assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
1547
+
1548
+ def test_overflow(self):
1549
+ # unlike numpy's norm, this one is
1550
+ # safer on overflow
1551
+ a = array([1e20], dtype=float32)
1552
+ assert_almost_equal(norm(a), a)
1553
+
1554
+ def test_stable(self):
1555
+ # more stable than numpy's norm
1556
+ a = array([1e4] + [1]*10000, dtype=float32)
1557
+ try:
1558
+ # snrm in double precision; we obtain the same as for float64
1559
+ # -- large atol needed due to varying blas implementations
1560
+ assert_allclose(norm(a) - 1e4, 0.5, atol=1e-2)
1561
+ except AssertionError:
1562
+ # snrm implemented in single precision, == np.linalg.norm result
1563
+ msg = ": Result should equal either 0.0 or 0.5 (depending on " \
1564
+ "implementation of snrm2)."
1565
+ assert_almost_equal(norm(a) - 1e4, 0.0, err_msg=msg)
1566
+
1567
+ def test_zero_norm(self):
1568
+ assert_equal(norm([1, 0, 3], 0), 2)
1569
+ assert_equal(norm([1, 2, 3], 0), 3)
1570
+
1571
+ def test_axis_kwd(self):
1572
+ a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
1573
+ assert_allclose(norm(a, axis=1), [[3.60555128, 4.12310563]] * 2)
1574
+ assert_allclose(norm(a, 1, axis=1), [[5.] * 2] * 2)
1575
+
1576
+ def test_keepdims_kwd(self):
1577
+ a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
1578
+ b = norm(a, axis=1, keepdims=True)
1579
+ assert_allclose(b, [[[3.60555128, 4.12310563]]] * 2)
1580
+ assert_(b.shape == (2, 1, 2))
1581
+ assert_allclose(norm(a, 1, axis=2, keepdims=True), [[[3.], [7.]]] * 2)
1582
+
1583
+ @pytest.mark.skipif(not HAS_ILP64, reason="64-bit BLAS required")
1584
+ def test_large_vector(self):
1585
+ check_free_memory(free_mb=17000)
1586
+ x = np.zeros([2**31], dtype=np.float64)
1587
+ x[-1] = 1
1588
+ res = norm(x)
1589
+ del x
1590
+ assert_allclose(res, 1.0)
1591
+
1592
+
1593
+ class TestMatrixNorms:
1594
+
1595
+ def test_matrix_norms(self):
1596
+ # Not all of these are matrix norms in the most technical sense.
1597
+ np.random.seed(1234)
1598
+ for n, m in (1, 1), (1, 3), (3, 1), (4, 4), (4, 5), (5, 4):
1599
+ for t in np.float32, np.float64, np.complex64, np.complex128, np.int64:
1600
+ A = 10 * np.random.randn(n, m).astype(t)
1601
+ if np.issubdtype(A.dtype, np.complexfloating):
1602
+ A = (A + 10j * np.random.randn(n, m)).astype(t)
1603
+ t_high = np.complex128
1604
+ else:
1605
+ t_high = np.float64
1606
+ for order in (None, 'fro', 1, -1, 2, -2, np.inf, -np.inf):
1607
+ actual = norm(A, ord=order)
1608
+ desired = np.linalg.norm(A, ord=order)
1609
+ # SciPy may return higher precision matrix norms.
1610
+ # This is a consequence of using LAPACK.
1611
+ if not np.allclose(actual, desired):
1612
+ desired = np.linalg.norm(A.astype(t_high), ord=order)
1613
+ assert_allclose(actual, desired)
1614
+
1615
+ def test_axis_kwd(self):
1616
+ a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
1617
+ b = norm(a, ord=np.inf, axis=(1, 0))
1618
+ c = norm(np.swapaxes(a, 0, 1), ord=np.inf, axis=(0, 1))
1619
+ d = norm(a, ord=1, axis=(0, 1))
1620
+ assert_allclose(b, c)
1621
+ assert_allclose(c, d)
1622
+ assert_allclose(b, d)
1623
+ assert_(b.shape == c.shape == d.shape)
1624
+ b = norm(a, ord=1, axis=(1, 0))
1625
+ c = norm(np.swapaxes(a, 0, 1), ord=1, axis=(0, 1))
1626
+ d = norm(a, ord=np.inf, axis=(0, 1))
1627
+ assert_allclose(b, c)
1628
+ assert_allclose(c, d)
1629
+ assert_allclose(b, d)
1630
+ assert_(b.shape == c.shape == d.shape)
1631
+
1632
+ def test_keepdims_kwd(self):
1633
+ a = np.arange(120, dtype='d').reshape(2, 3, 4, 5)
1634
+ b = norm(a, ord=np.inf, axis=(1, 0), keepdims=True)
1635
+ c = norm(a, ord=1, axis=(0, 1), keepdims=True)
1636
+ assert_allclose(b, c)
1637
+ assert_(b.shape == c.shape)
1638
+
1639
+
1640
+ class TestOverwrite:
1641
+ def test_solve(self):
1642
+ assert_no_overwrite(solve, [(3, 3), (3,)])
1643
+
1644
+ def test_solve_triangular(self):
1645
+ assert_no_overwrite(solve_triangular, [(3, 3), (3,)])
1646
+
1647
+ def test_solve_banded(self):
1648
+ assert_no_overwrite(lambda ab, b: solve_banded((2, 1), ab, b),
1649
+ [(4, 6), (6,)])
1650
+
1651
+ def test_solveh_banded(self):
1652
+ assert_no_overwrite(solveh_banded, [(2, 6), (6,)])
1653
+
1654
+ def test_inv(self):
1655
+ assert_no_overwrite(inv, [(3, 3)])
1656
+
1657
+ def test_det(self):
1658
+ assert_no_overwrite(det, [(3, 3)])
1659
+
1660
+ def test_lstsq(self):
1661
+ assert_no_overwrite(lstsq, [(3, 2), (3,)])
1662
+
1663
+ def test_pinv(self):
1664
+ assert_no_overwrite(pinv, [(3, 3)])
1665
+
1666
+ def test_pinvh(self):
1667
+ assert_no_overwrite(pinvh, [(3, 3)])
1668
+
1669
+
1670
+ class TestSolveCirculant:
1671
+
1672
+ def test_basic1(self):
1673
+ c = np.array([1, 2, 3, 5])
1674
+ b = np.array([1, -1, 1, 0])
1675
+ x = solve_circulant(c, b)
1676
+ y = solve(circulant(c), b)
1677
+ assert_allclose(x, y)
1678
+
1679
+ def test_basic2(self):
1680
+ # b is a 2-d matrix.
1681
+ c = np.array([1, 2, -3, -5])
1682
+ b = np.arange(12).reshape(4, 3)
1683
+ x = solve_circulant(c, b)
1684
+ y = solve(circulant(c), b)
1685
+ assert_allclose(x, y)
1686
+
1687
+ def test_basic3(self):
1688
+ # b is a 3-d matrix.
1689
+ c = np.array([1, 2, -3, -5])
1690
+ b = np.arange(24).reshape(4, 3, 2)
1691
+ x = solve_circulant(c, b)
1692
+ y = solve(circulant(c), b)
1693
+ assert_allclose(x, y)
1694
+
1695
+ def test_complex(self):
1696
+ # Complex b and c
1697
+ c = np.array([1+2j, -3, 4j, 5])
1698
+ b = np.arange(8).reshape(4, 2) + 0.5j
1699
+ x = solve_circulant(c, b)
1700
+ y = solve(circulant(c), b)
1701
+ assert_allclose(x, y)
1702
+
1703
+ def test_random_b_and_c(self):
1704
+ # Random b and c
1705
+ np.random.seed(54321)
1706
+ c = np.random.randn(50)
1707
+ b = np.random.randn(50)
1708
+ x = solve_circulant(c, b)
1709
+ y = solve(circulant(c), b)
1710
+ assert_allclose(x, y)
1711
+
1712
+ def test_singular(self):
1713
+ # c gives a singular circulant matrix.
1714
+ c = np.array([1, 1, 0, 0])
1715
+ b = np.array([1, 2, 3, 4])
1716
+ x = solve_circulant(c, b, singular='lstsq')
1717
+ y, res, rnk, s = lstsq(circulant(c), b)
1718
+ assert_allclose(x, y)
1719
+ assert_raises(LinAlgError, solve_circulant, x, y)
1720
+
1721
+ def test_axis_args(self):
1722
+ # Test use of caxis, baxis and outaxis.
1723
+
1724
+ # c has shape (2, 1, 4)
1725
+ c = np.array([[[-1, 2.5, 3, 3.5]], [[1, 6, 6, 6.5]]])
1726
+
1727
+ # b has shape (3, 4)
1728
+ b = np.array([[0, 0, 1, 1], [1, 1, 0, 0], [1, -1, 0, 0]])
1729
+
1730
+ x = solve_circulant(c, b, baxis=1)
1731
+ assert_equal(x.shape, (4, 2, 3))
1732
+ expected = np.empty_like(x)
1733
+ expected[:, 0, :] = solve(circulant(c[0]), b.T)
1734
+ expected[:, 1, :] = solve(circulant(c[1]), b.T)
1735
+ assert_allclose(x, expected)
1736
+
1737
+ x = solve_circulant(c, b, baxis=1, outaxis=-1)
1738
+ assert_equal(x.shape, (2, 3, 4))
1739
+ assert_allclose(np.moveaxis(x, -1, 0), expected)
1740
+
1741
+ # np.swapaxes(c, 1, 2) has shape (2, 4, 1); b.T has shape (4, 3).
1742
+ x = solve_circulant(np.swapaxes(c, 1, 2), b.T, caxis=1)
1743
+ assert_equal(x.shape, (4, 2, 3))
1744
+ assert_allclose(x, expected)
1745
+
1746
+ def test_native_list_arguments(self):
1747
+ # Same as test_basic1 using python's native list.
1748
+ c = [1, 2, 3, 5]
1749
+ b = [1, -1, 1, 0]
1750
+ x = solve_circulant(c, b)
1751
+ y = solve(circulant(c), b)
1752
+ assert_allclose(x, y)
1753
+
1754
+
1755
+ class TestMatrix_Balance:
1756
+
1757
+ def test_string_arg(self):
1758
+ assert_raises(ValueError, matrix_balance, 'Some string for fail')
1759
+
1760
+ def test_infnan_arg(self):
1761
+ assert_raises(ValueError, matrix_balance,
1762
+ np.array([[1, 2], [3, np.inf]]))
1763
+ assert_raises(ValueError, matrix_balance,
1764
+ np.array([[1, 2], [3, np.nan]]))
1765
+
1766
+ def test_scaling(self):
1767
+ _, y = matrix_balance(np.array([[1000, 1], [1000, 0]]))
1768
+ # Pre/post LAPACK 3.5.0 gives the same result up to an offset
1769
+ # since in each case col norm is x1000 greater and
1770
+ # 1000 / 32 ~= 1 * 32 hence balanced with 2 ** 5.
1771
+ assert_allclose(np.diff(np.log2(np.diag(y))), [5])
1772
+
1773
+ def test_scaling_order(self):
1774
+ A = np.array([[1, 0, 1e-4], [1, 1, 1e-2], [1e4, 1e2, 1]])
1775
+ x, y = matrix_balance(A)
1776
+ assert_allclose(solve(y, A).dot(y), x)
1777
+
1778
+ def test_separate(self):
1779
+ _, (y, z) = matrix_balance(np.array([[1000, 1], [1000, 0]]),
1780
+ separate=1)
1781
+ assert_equal(np.diff(np.log2(y)), [5])
1782
+ assert_allclose(z, np.arange(2))
1783
+
1784
+ def test_permutation(self):
1785
+ A = block_diag(np.ones((2, 2)), np.tril(np.ones((2, 2))),
1786
+ np.ones((3, 3)))
1787
+ x, (y, z) = matrix_balance(A, separate=1)
1788
+ assert_allclose(y, np.ones_like(y))
1789
+ assert_allclose(z, np.array([0, 1, 6, 5, 4, 3, 2]))
1790
+
1791
+ def test_perm_and_scaling(self):
1792
+ # Matrix with its diagonal removed
1793
+ cases = ( # Case 0
1794
+ np.array([[0., 0., 0., 0., 0.000002],
1795
+ [0., 0., 0., 0., 0.],
1796
+ [2., 2., 0., 0., 0.],
1797
+ [2., 2., 0., 0., 0.],
1798
+ [0., 0., 0.000002, 0., 0.]]),
1799
+ # Case 1 user reported GH-7258
1800
+ np.array([[-0.5, 0., 0., 0.],
1801
+ [0., -1., 0., 0.],
1802
+ [1., 0., -0.5, 0.],
1803
+ [0., 1., 0., -1.]]),
1804
+ # Case 2 user reported GH-7258
1805
+ np.array([[-3., 0., 1., 0.],
1806
+ [-1., -1., -0., 1.],
1807
+ [-3., -0., -0., 0.],
1808
+ [-1., -0., 1., -1.]])
1809
+ )
1810
+
1811
+ for A in cases:
1812
+ x, y = matrix_balance(A)
1813
+ x, (s, p) = matrix_balance(A, separate=1)
1814
+ ip = np.empty_like(p)
1815
+ ip[p] = np.arange(A.shape[0])
1816
+ assert_allclose(y, np.diag(s)[ip, :])
1817
+ assert_allclose(solve(y, A).dot(y), x)
venv/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py ADDED
@@ -0,0 +1,1114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Created by: Pearu Peterson, April 2002
3
+ #
4
+
5
+ import math
6
+ import pytest
7
+ import numpy as np
8
+ from numpy.testing import (assert_equal, assert_almost_equal, assert_,
9
+ assert_array_almost_equal, assert_allclose)
10
+ from pytest import raises as assert_raises
11
+
12
+ from numpy import float32, float64, complex64, complex128, arange, triu, \
13
+ tril, zeros, tril_indices, ones, mod, diag, append, eye, \
14
+ nonzero
15
+
16
+ from numpy.random import rand, seed
17
+ import scipy
18
+ from scipy.linalg import _fblas as fblas, get_blas_funcs, toeplitz, solve
19
+
20
+ try:
21
+ from scipy.linalg import _cblas as cblas
22
+ except ImportError:
23
+ cblas = None
24
+
25
+ REAL_DTYPES = [float32, float64]
26
+ COMPLEX_DTYPES = [complex64, complex128]
27
+ DTYPES = REAL_DTYPES + COMPLEX_DTYPES
28
+
29
+
30
+ def test_get_blas_funcs():
31
+ # check that it returns Fortran code for arrays that are
32
+ # fortran-ordered
33
+ f1, f2, f3 = get_blas_funcs(
34
+ ('axpy', 'axpy', 'axpy'),
35
+ (np.empty((2, 2), dtype=np.complex64, order='F'),
36
+ np.empty((2, 2), dtype=np.complex128, order='C'))
37
+ )
38
+
39
+ # get_blas_funcs will choose libraries depending on most generic
40
+ # array
41
+ assert_equal(f1.typecode, 'z')
42
+ assert_equal(f2.typecode, 'z')
43
+ if cblas is not None:
44
+ assert_equal(f1.module_name, 'cblas')
45
+ assert_equal(f2.module_name, 'cblas')
46
+
47
+ # check defaults.
48
+ f1 = get_blas_funcs('rotg')
49
+ assert_equal(f1.typecode, 'd')
50
+
51
+ # check also dtype interface
52
+ f1 = get_blas_funcs('gemm', dtype=np.complex64)
53
+ assert_equal(f1.typecode, 'c')
54
+ f1 = get_blas_funcs('gemm', dtype='F')
55
+ assert_equal(f1.typecode, 'c')
56
+
57
+ # extended precision complex
58
+ f1 = get_blas_funcs('gemm', dtype=np.clongdouble)
59
+ assert_equal(f1.typecode, 'z')
60
+
61
+ # check safe complex upcasting
62
+ f1 = get_blas_funcs('axpy',
63
+ (np.empty((2, 2), dtype=np.float64),
64
+ np.empty((2, 2), dtype=np.complex64))
65
+ )
66
+ assert_equal(f1.typecode, 'z')
67
+
68
+
69
+ def test_get_blas_funcs_alias():
70
+ # check alias for get_blas_funcs
71
+ f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64)
72
+ assert f.typecode == 'c'
73
+ assert g.typecode == 'c'
74
+
75
+ f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64)
76
+ assert f is g
77
+ assert f is h
78
+
79
+
80
+ class TestCBLAS1Simple:
81
+
82
+ def test_axpy(self):
83
+ for p in 'sd':
84
+ f = getattr(cblas, p+'axpy', None)
85
+ if f is None:
86
+ continue
87
+ assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
88
+ [7, 9, 18])
89
+ for p in 'cz':
90
+ f = getattr(cblas, p+'axpy', None)
91
+ if f is None:
92
+ continue
93
+ assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
94
+ [7, 10j-1, 18])
95
+
96
+
97
+ class TestFBLAS1Simple:
98
+
99
+ def test_axpy(self):
100
+ for p in 'sd':
101
+ f = getattr(fblas, p+'axpy', None)
102
+ if f is None:
103
+ continue
104
+ assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
105
+ [7, 9, 18])
106
+ for p in 'cz':
107
+ f = getattr(fblas, p+'axpy', None)
108
+ if f is None:
109
+ continue
110
+ assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
111
+ [7, 10j-1, 18])
112
+
113
+ def test_copy(self):
114
+ for p in 'sd':
115
+ f = getattr(fblas, p+'copy', None)
116
+ if f is None:
117
+ continue
118
+ assert_array_almost_equal(f([3, 4, 5], [8]*3), [3, 4, 5])
119
+ for p in 'cz':
120
+ f = getattr(fblas, p+'copy', None)
121
+ if f is None:
122
+ continue
123
+ assert_array_almost_equal(f([3, 4j, 5+3j], [8]*3), [3, 4j, 5+3j])
124
+
125
+ def test_asum(self):
126
+ for p in 'sd':
127
+ f = getattr(fblas, p+'asum', None)
128
+ if f is None:
129
+ continue
130
+ assert_almost_equal(f([3, -4, 5]), 12)
131
+ for p in ['sc', 'dz']:
132
+ f = getattr(fblas, p+'asum', None)
133
+ if f is None:
134
+ continue
135
+ assert_almost_equal(f([3j, -4, 3-4j]), 14)
136
+
137
+ def test_dot(self):
138
+ for p in 'sd':
139
+ f = getattr(fblas, p+'dot', None)
140
+ if f is None:
141
+ continue
142
+ assert_almost_equal(f([3, -4, 5], [2, 5, 1]), -9)
143
+
144
+ def test_complex_dotu(self):
145
+ for p in 'cz':
146
+ f = getattr(fblas, p+'dotu', None)
147
+ if f is None:
148
+ continue
149
+ assert_almost_equal(f([3j, -4, 3-4j], [2, 3, 1]), -9+2j)
150
+
151
+ def test_complex_dotc(self):
152
+ for p in 'cz':
153
+ f = getattr(fblas, p+'dotc', None)
154
+ if f is None:
155
+ continue
156
+ assert_almost_equal(f([3j, -4, 3-4j], [2, 3j, 1]), 3-14j)
157
+
158
+ def test_nrm2(self):
159
+ for p in 'sd':
160
+ f = getattr(fblas, p+'nrm2', None)
161
+ if f is None:
162
+ continue
163
+ assert_almost_equal(f([3, -4, 5]), math.sqrt(50))
164
+ for p in ['c', 'z', 'sc', 'dz']:
165
+ f = getattr(fblas, p+'nrm2', None)
166
+ if f is None:
167
+ continue
168
+ assert_almost_equal(f([3j, -4, 3-4j]), math.sqrt(50))
169
+
170
+ def test_scal(self):
171
+ for p in 'sd':
172
+ f = getattr(fblas, p+'scal', None)
173
+ if f is None:
174
+ continue
175
+ assert_array_almost_equal(f(2, [3, -4, 5]), [6, -8, 10])
176
+ for p in 'cz':
177
+ f = getattr(fblas, p+'scal', None)
178
+ if f is None:
179
+ continue
180
+ assert_array_almost_equal(f(3j, [3j, -4, 3-4j]), [-9, -12j, 12+9j])
181
+ for p in ['cs', 'zd']:
182
+ f = getattr(fblas, p+'scal', None)
183
+ if f is None:
184
+ continue
185
+ assert_array_almost_equal(f(3, [3j, -4, 3-4j]), [9j, -12, 9-12j])
186
+
187
+ def test_swap(self):
188
+ for p in 'sd':
189
+ f = getattr(fblas, p+'swap', None)
190
+ if f is None:
191
+ continue
192
+ x, y = [2, 3, 1], [-2, 3, 7]
193
+ x1, y1 = f(x, y)
194
+ assert_array_almost_equal(x1, y)
195
+ assert_array_almost_equal(y1, x)
196
+ for p in 'cz':
197
+ f = getattr(fblas, p+'swap', None)
198
+ if f is None:
199
+ continue
200
+ x, y = [2, 3j, 1], [-2, 3, 7-3j]
201
+ x1, y1 = f(x, y)
202
+ assert_array_almost_equal(x1, y)
203
+ assert_array_almost_equal(y1, x)
204
+
205
+ def test_amax(self):
206
+ for p in 'sd':
207
+ f = getattr(fblas, 'i'+p+'amax')
208
+ assert_equal(f([-2, 4, 3]), 1)
209
+ for p in 'cz':
210
+ f = getattr(fblas, 'i'+p+'amax')
211
+ assert_equal(f([-5, 4+3j, 6]), 1)
212
+ # XXX: need tests for rot,rotm,rotg,rotmg
213
+
214
+
215
+ class TestFBLAS2Simple:
216
+
217
+ def test_gemv(self):
218
+ for p in 'sd':
219
+ f = getattr(fblas, p+'gemv', None)
220
+ if f is None:
221
+ continue
222
+ assert_array_almost_equal(f(3, [[3]], [-4]), [-36])
223
+ assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21])
224
+ for p in 'cz':
225
+ f = getattr(fblas, p+'gemv', None)
226
+ if f is None:
227
+ continue
228
+ assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-48-36j])
229
+ assert_array_almost_equal(f(3j, [[3-4j]], [-4], 3, [5j]),
230
+ [-48-21j])
231
+
232
+ def test_ger(self):
233
+
234
+ for p in 'sd':
235
+ f = getattr(fblas, p+'ger', None)
236
+ if f is None:
237
+ continue
238
+ assert_array_almost_equal(f(1, [1, 2], [3, 4]), [[3, 4], [6, 8]])
239
+ assert_array_almost_equal(f(2, [1, 2, 3], [3, 4]),
240
+ [[6, 8], [12, 16], [18, 24]])
241
+
242
+ assert_array_almost_equal(f(1, [1, 2], [3, 4],
243
+ a=[[1, 2], [3, 4]]), [[4, 6], [9, 12]])
244
+
245
+ for p in 'cz':
246
+ f = getattr(fblas, p+'geru', None)
247
+ if f is None:
248
+ continue
249
+ assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
250
+ [[3j, 4j], [6, 8]])
251
+ assert_array_almost_equal(f(-2, [1j, 2j, 3j], [3j, 4j]),
252
+ [[6, 8], [12, 16], [18, 24]])
253
+
254
+ for p in 'cz':
255
+ for name in ('ger', 'gerc'):
256
+ f = getattr(fblas, p+name, None)
257
+ if f is None:
258
+ continue
259
+ assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
260
+ [[3j, 4j], [6, 8]])
261
+ assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]),
262
+ [[6, 8], [12, 16], [18, 24]])
263
+
264
+ def test_syr_her(self):
265
+ x = np.arange(1, 5, dtype='d')
266
+ resx = np.triu(x[:, np.newaxis] * x)
267
+ resx_reverse = np.triu(x[::-1, np.newaxis] * x[::-1])
268
+
269
+ y = np.linspace(0, 8.5, 17, endpoint=False)
270
+
271
+ z = np.arange(1, 9, dtype='d').view('D')
272
+ resz = np.triu(z[:, np.newaxis] * z)
273
+ resz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1])
274
+ rehz = np.triu(z[:, np.newaxis] * z.conj())
275
+ rehz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1].conj())
276
+
277
+ w = np.c_[np.zeros(4), z, np.zeros(4)].ravel()
278
+
279
+ for p, rtol in zip('sd', [1e-7, 1e-14]):
280
+ f = getattr(fblas, p+'syr', None)
281
+ if f is None:
282
+ continue
283
+ assert_allclose(f(1.0, x), resx, rtol=rtol)
284
+ assert_allclose(f(1.0, x, lower=True), resx.T, rtol=rtol)
285
+ assert_allclose(f(1.0, y, incx=2, offx=2, n=4), resx, rtol=rtol)
286
+ # negative increments imply reversed vectors in blas
287
+ assert_allclose(f(1.0, y, incx=-2, offx=2, n=4),
288
+ resx_reverse, rtol=rtol)
289
+
290
+ a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F')
291
+ b = f(1.0, x, a=a, overwrite_a=True)
292
+ assert_allclose(a, resx, rtol=rtol)
293
+
294
+ b = f(2.0, x, a=a)
295
+ assert_(a is not b)
296
+ assert_allclose(b, 3*resx, rtol=rtol)
297
+
298
+ assert_raises(Exception, f, 1.0, x, incx=0)
299
+ assert_raises(Exception, f, 1.0, x, offx=5)
300
+ assert_raises(Exception, f, 1.0, x, offx=-2)
301
+ assert_raises(Exception, f, 1.0, x, n=-2)
302
+ assert_raises(Exception, f, 1.0, x, n=5)
303
+ assert_raises(Exception, f, 1.0, x, lower=2)
304
+ assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
305
+
306
+ for p, rtol in zip('cz', [1e-7, 1e-14]):
307
+ f = getattr(fblas, p+'syr', None)
308
+ if f is None:
309
+ continue
310
+ assert_allclose(f(1.0, z), resz, rtol=rtol)
311
+ assert_allclose(f(1.0, z, lower=True), resz.T, rtol=rtol)
312
+ assert_allclose(f(1.0, w, incx=3, offx=1, n=4), resz, rtol=rtol)
313
+ # negative increments imply reversed vectors in blas
314
+ assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
315
+ resz_reverse, rtol=rtol)
316
+
317
+ a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
318
+ b = f(1.0, z, a=a, overwrite_a=True)
319
+ assert_allclose(a, resz, rtol=rtol)
320
+
321
+ b = f(2.0, z, a=a)
322
+ assert_(a is not b)
323
+ assert_allclose(b, 3*resz, rtol=rtol)
324
+
325
+ assert_raises(Exception, f, 1.0, x, incx=0)
326
+ assert_raises(Exception, f, 1.0, x, offx=5)
327
+ assert_raises(Exception, f, 1.0, x, offx=-2)
328
+ assert_raises(Exception, f, 1.0, x, n=-2)
329
+ assert_raises(Exception, f, 1.0, x, n=5)
330
+ assert_raises(Exception, f, 1.0, x, lower=2)
331
+ assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
332
+
333
+ for p, rtol in zip('cz', [1e-7, 1e-14]):
334
+ f = getattr(fblas, p+'her', None)
335
+ if f is None:
336
+ continue
337
+ assert_allclose(f(1.0, z), rehz, rtol=rtol)
338
+ assert_allclose(f(1.0, z, lower=True), rehz.T.conj(), rtol=rtol)
339
+ assert_allclose(f(1.0, w, incx=3, offx=1, n=4), rehz, rtol=rtol)
340
+ # negative increments imply reversed vectors in blas
341
+ assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
342
+ rehz_reverse, rtol=rtol)
343
+
344
+ a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
345
+ b = f(1.0, z, a=a, overwrite_a=True)
346
+ assert_allclose(a, rehz, rtol=rtol)
347
+
348
+ b = f(2.0, z, a=a)
349
+ assert_(a is not b)
350
+ assert_allclose(b, 3*rehz, rtol=rtol)
351
+
352
+ assert_raises(Exception, f, 1.0, x, incx=0)
353
+ assert_raises(Exception, f, 1.0, x, offx=5)
354
+ assert_raises(Exception, f, 1.0, x, offx=-2)
355
+ assert_raises(Exception, f, 1.0, x, n=-2)
356
+ assert_raises(Exception, f, 1.0, x, n=5)
357
+ assert_raises(Exception, f, 1.0, x, lower=2)
358
+ assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
359
+
360
+ def test_syr2(self):
361
+ x = np.arange(1, 5, dtype='d')
362
+ y = np.arange(5, 9, dtype='d')
363
+ resxy = np.triu(x[:, np.newaxis] * y + y[:, np.newaxis] * x)
364
+ resxy_reverse = np.triu(x[::-1, np.newaxis] * y[::-1]
365
+ + y[::-1, np.newaxis] * x[::-1])
366
+
367
+ q = np.linspace(0, 8.5, 17, endpoint=False)
368
+
369
+ for p, rtol in zip('sd', [1e-7, 1e-14]):
370
+ f = getattr(fblas, p+'syr2', None)
371
+ if f is None:
372
+ continue
373
+ assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
374
+ assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
375
+ assert_allclose(f(1.0, x, y, lower=True), resxy.T, rtol=rtol)
376
+
377
+ assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10),
378
+ resxy, rtol=rtol)
379
+ assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10, n=3),
380
+ resxy[:3, :3], rtol=rtol)
381
+ # negative increments imply reversed vectors in blas
382
+ assert_allclose(f(1.0, q, q, incx=-2, offx=2, incy=-2, offy=10),
383
+ resxy_reverse, rtol=rtol)
384
+
385
+ a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F')
386
+ b = f(1.0, x, y, a=a, overwrite_a=True)
387
+ assert_allclose(a, resxy, rtol=rtol)
388
+
389
+ b = f(2.0, x, y, a=a)
390
+ assert_(a is not b)
391
+ assert_allclose(b, 3*resxy, rtol=rtol)
392
+
393
+ assert_raises(Exception, f, 1.0, x, y, incx=0)
394
+ assert_raises(Exception, f, 1.0, x, y, offx=5)
395
+ assert_raises(Exception, f, 1.0, x, y, offx=-2)
396
+ assert_raises(Exception, f, 1.0, x, y, incy=0)
397
+ assert_raises(Exception, f, 1.0, x, y, offy=5)
398
+ assert_raises(Exception, f, 1.0, x, y, offy=-2)
399
+ assert_raises(Exception, f, 1.0, x, y, n=-2)
400
+ assert_raises(Exception, f, 1.0, x, y, n=5)
401
+ assert_raises(Exception, f, 1.0, x, y, lower=2)
402
+ assert_raises(Exception, f, 1.0, x, y,
403
+ a=np.zeros((2, 2), 'd', 'F'))
404
+
405
+ def test_her2(self):
406
+ x = np.arange(1, 9, dtype='d').view('D')
407
+ y = np.arange(9, 17, dtype='d').view('D')
408
+ resxy = x[:, np.newaxis] * y.conj() + y[:, np.newaxis] * x.conj()
409
+ resxy = np.triu(resxy)
410
+
411
+ resxy_reverse = x[::-1, np.newaxis] * y[::-1].conj()
412
+ resxy_reverse += y[::-1, np.newaxis] * x[::-1].conj()
413
+ resxy_reverse = np.triu(resxy_reverse)
414
+
415
+ u = np.c_[np.zeros(4), x, np.zeros(4)].ravel()
416
+ v = np.c_[np.zeros(4), y, np.zeros(4)].ravel()
417
+
418
+ for p, rtol in zip('cz', [1e-7, 1e-14]):
419
+ f = getattr(fblas, p+'her2', None)
420
+ if f is None:
421
+ continue
422
+ assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
423
+ assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
424
+ assert_allclose(f(1.0, x, y, lower=True), resxy.T.conj(),
425
+ rtol=rtol)
426
+
427
+ assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1),
428
+ resxy, rtol=rtol)
429
+ assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1, n=3),
430
+ resxy[:3, :3], rtol=rtol)
431
+ # negative increments imply reversed vectors in blas
432
+ assert_allclose(f(1.0, u, v, incx=-3, offx=1, incy=-3, offy=1),
433
+ resxy_reverse, rtol=rtol)
434
+
435
+ a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
436
+ b = f(1.0, x, y, a=a, overwrite_a=True)
437
+ assert_allclose(a, resxy, rtol=rtol)
438
+
439
+ b = f(2.0, x, y, a=a)
440
+ assert_(a is not b)
441
+ assert_allclose(b, 3*resxy, rtol=rtol)
442
+
443
+ assert_raises(Exception, f, 1.0, x, y, incx=0)
444
+ assert_raises(Exception, f, 1.0, x, y, offx=5)
445
+ assert_raises(Exception, f, 1.0, x, y, offx=-2)
446
+ assert_raises(Exception, f, 1.0, x, y, incy=0)
447
+ assert_raises(Exception, f, 1.0, x, y, offy=5)
448
+ assert_raises(Exception, f, 1.0, x, y, offy=-2)
449
+ assert_raises(Exception, f, 1.0, x, y, n=-2)
450
+ assert_raises(Exception, f, 1.0, x, y, n=5)
451
+ assert_raises(Exception, f, 1.0, x, y, lower=2)
452
+ assert_raises(Exception, f, 1.0, x, y,
453
+ a=np.zeros((2, 2), 'd', 'F'))
454
+
455
+ def test_gbmv(self):
456
+ seed(1234)
457
+ for ind, dtype in enumerate(DTYPES):
458
+ n = 7
459
+ m = 5
460
+ kl = 1
461
+ ku = 2
462
+ # fake a banded matrix via toeplitz
463
+ A = toeplitz(append(rand(kl+1), zeros(m-kl-1)),
464
+ append(rand(ku+1), zeros(n-ku-1)))
465
+ A = A.astype(dtype)
466
+ Ab = zeros((kl+ku+1, n), dtype=dtype)
467
+
468
+ # Form the banded storage
469
+ Ab[2, :5] = A[0, 0] # diag
470
+ Ab[1, 1:6] = A[0, 1] # sup1
471
+ Ab[0, 2:7] = A[0, 2] # sup2
472
+ Ab[3, :4] = A[1, 0] # sub1
473
+
474
+ x = rand(n).astype(dtype)
475
+ y = rand(m).astype(dtype)
476
+ alpha, beta = dtype(3), dtype(-5)
477
+
478
+ func, = get_blas_funcs(('gbmv',), dtype=dtype)
479
+ y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
480
+ x=x, y=y, beta=beta)
481
+ y2 = alpha * A.dot(x) + beta * y
482
+ assert_array_almost_equal(y1, y2)
483
+
484
+ y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
485
+ x=y, y=x, beta=beta, trans=1)
486
+ y2 = alpha * A.T.dot(y) + beta * x
487
+ assert_array_almost_equal(y1, y2)
488
+
489
+ def test_sbmv_hbmv(self):
490
+ seed(1234)
491
+ for ind, dtype in enumerate(DTYPES):
492
+ n = 6
493
+ k = 2
494
+ A = zeros((n, n), dtype=dtype)
495
+ Ab = zeros((k+1, n), dtype=dtype)
496
+
497
+ # Form the array and its packed banded storage
498
+ A[arange(n), arange(n)] = rand(n)
499
+ for ind2 in range(1, k+1):
500
+ temp = rand(n-ind2)
501
+ A[arange(n-ind2), arange(ind2, n)] = temp
502
+ Ab[-1-ind2, ind2:] = temp
503
+ A = A.astype(dtype)
504
+ A = A + A.T if ind < 2 else A + A.conj().T
505
+ Ab[-1, :] = diag(A)
506
+ x = rand(n).astype(dtype)
507
+ y = rand(n).astype(dtype)
508
+ alpha, beta = dtype(1.25), dtype(3)
509
+
510
+ if ind > 1:
511
+ func, = get_blas_funcs(('hbmv',), dtype=dtype)
512
+ else:
513
+ func, = get_blas_funcs(('sbmv',), dtype=dtype)
514
+ y1 = func(k=k, alpha=alpha, a=Ab, x=x, y=y, beta=beta)
515
+ y2 = alpha * A.dot(x) + beta * y
516
+ assert_array_almost_equal(y1, y2)
517
+
518
+ def test_spmv_hpmv(self):
519
+ seed(1234)
520
+ for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
521
+ n = 3
522
+ A = rand(n, n).astype(dtype)
523
+ if ind > 1:
524
+ A += rand(n, n)*1j
525
+ A = A.astype(dtype)
526
+ A = A + A.T if ind < 4 else A + A.conj().T
527
+ c, r = tril_indices(n)
528
+ Ap = A[r, c]
529
+ x = rand(n).astype(dtype)
530
+ y = rand(n).astype(dtype)
531
+ xlong = arange(2*n).astype(dtype)
532
+ ylong = ones(2*n).astype(dtype)
533
+ alpha, beta = dtype(1.25), dtype(2)
534
+
535
+ if ind > 3:
536
+ func, = get_blas_funcs(('hpmv',), dtype=dtype)
537
+ else:
538
+ func, = get_blas_funcs(('spmv',), dtype=dtype)
539
+ y1 = func(n=n, alpha=alpha, ap=Ap, x=x, y=y, beta=beta)
540
+ y2 = alpha * A.dot(x) + beta * y
541
+ assert_array_almost_equal(y1, y2)
542
+
543
+ # Test inc and offsets
544
+ y1 = func(n=n-1, alpha=alpha, beta=beta, x=xlong, y=ylong, ap=Ap,
545
+ incx=2, incy=2, offx=n, offy=n)
546
+ y2 = (alpha * A[:-1, :-1]).dot(xlong[3::2]) + beta * ylong[3::2]
547
+ assert_array_almost_equal(y1[3::2], y2)
548
+ assert_almost_equal(y1[4], ylong[4])
549
+
550
+ def test_spr_hpr(self):
551
+ seed(1234)
552
+ for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
553
+ n = 3
554
+ A = rand(n, n).astype(dtype)
555
+ if ind > 1:
556
+ A += rand(n, n)*1j
557
+ A = A.astype(dtype)
558
+ A = A + A.T if ind < 4 else A + A.conj().T
559
+ c, r = tril_indices(n)
560
+ Ap = A[r, c]
561
+ x = rand(n).astype(dtype)
562
+ alpha = (DTYPES+COMPLEX_DTYPES)[mod(ind, 4)](2.5)
563
+
564
+ if ind > 3:
565
+ func, = get_blas_funcs(('hpr',), dtype=dtype)
566
+ y2 = alpha * x[:, None].dot(x[None, :].conj()) + A
567
+ else:
568
+ func, = get_blas_funcs(('spr',), dtype=dtype)
569
+ y2 = alpha * x[:, None].dot(x[None, :]) + A
570
+
571
+ y1 = func(n=n, alpha=alpha, ap=Ap, x=x)
572
+ y1f = zeros((3, 3), dtype=dtype)
573
+ y1f[r, c] = y1
574
+ y1f[c, r] = y1.conj() if ind > 3 else y1
575
+ assert_array_almost_equal(y1f, y2)
576
+
577
+ def test_spr2_hpr2(self):
578
+ seed(1234)
579
+ for ind, dtype in enumerate(DTYPES):
580
+ n = 3
581
+ A = rand(n, n).astype(dtype)
582
+ if ind > 1:
583
+ A += rand(n, n)*1j
584
+ A = A.astype(dtype)
585
+ A = A + A.T if ind < 2 else A + A.conj().T
586
+ c, r = tril_indices(n)
587
+ Ap = A[r, c]
588
+ x = rand(n).astype(dtype)
589
+ y = rand(n).astype(dtype)
590
+ alpha = dtype(2)
591
+
592
+ if ind > 1:
593
+ func, = get_blas_funcs(('hpr2',), dtype=dtype)
594
+ else:
595
+ func, = get_blas_funcs(('spr2',), dtype=dtype)
596
+
597
+ u = alpha.conj() * x[:, None].dot(y[None, :].conj())
598
+ y2 = A + u + u.conj().T
599
+ y1 = func(n=n, alpha=alpha, x=x, y=y, ap=Ap)
600
+ y1f = zeros((3, 3), dtype=dtype)
601
+ y1f[r, c] = y1
602
+ y1f[[1, 2, 2], [0, 0, 1]] = y1[[1, 3, 4]].conj()
603
+ assert_array_almost_equal(y1f, y2)
604
+
605
+ def test_tbmv(self):
606
+ seed(1234)
607
+ for ind, dtype in enumerate(DTYPES):
608
+ n = 10
609
+ k = 3
610
+ x = rand(n).astype(dtype)
611
+ A = zeros((n, n), dtype=dtype)
612
+ # Banded upper triangular array
613
+ for sup in range(k+1):
614
+ A[arange(n-sup), arange(sup, n)] = rand(n-sup)
615
+
616
+ # Add complex parts for c,z
617
+ if ind > 1:
618
+ A[nonzero(A)] += 1j * rand((k+1)*n-(k*(k+1)//2)).astype(dtype)
619
+
620
+ # Form the banded storage
621
+ Ab = zeros((k+1, n), dtype=dtype)
622
+ for row in range(k+1):
623
+ Ab[-row-1, row:] = diag(A, k=row)
624
+ func, = get_blas_funcs(('tbmv',), dtype=dtype)
625
+
626
+ y1 = func(k=k, a=Ab, x=x)
627
+ y2 = A.dot(x)
628
+ assert_array_almost_equal(y1, y2)
629
+
630
+ y1 = func(k=k, a=Ab, x=x, diag=1)
631
+ A[arange(n), arange(n)] = dtype(1)
632
+ y2 = A.dot(x)
633
+ assert_array_almost_equal(y1, y2)
634
+
635
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
636
+ y2 = A.T.dot(x)
637
+ assert_array_almost_equal(y1, y2)
638
+
639
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
640
+ y2 = A.conj().T.dot(x)
641
+ assert_array_almost_equal(y1, y2)
642
+
643
+ def test_tbsv(self):
644
+ seed(1234)
645
+ for ind, dtype in enumerate(DTYPES):
646
+ n = 6
647
+ k = 3
648
+ x = rand(n).astype(dtype)
649
+ A = zeros((n, n), dtype=dtype)
650
+ # Banded upper triangular array
651
+ for sup in range(k+1):
652
+ A[arange(n-sup), arange(sup, n)] = rand(n-sup)
653
+
654
+ # Add complex parts for c,z
655
+ if ind > 1:
656
+ A[nonzero(A)] += 1j * rand((k+1)*n-(k*(k+1)//2)).astype(dtype)
657
+
658
+ # Form the banded storage
659
+ Ab = zeros((k+1, n), dtype=dtype)
660
+ for row in range(k+1):
661
+ Ab[-row-1, row:] = diag(A, k=row)
662
+ func, = get_blas_funcs(('tbsv',), dtype=dtype)
663
+
664
+ y1 = func(k=k, a=Ab, x=x)
665
+ y2 = solve(A, x)
666
+ assert_array_almost_equal(y1, y2)
667
+
668
+ y1 = func(k=k, a=Ab, x=x, diag=1)
669
+ A[arange(n), arange(n)] = dtype(1)
670
+ y2 = solve(A, x)
671
+ assert_array_almost_equal(y1, y2)
672
+
673
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
674
+ y2 = solve(A.T, x)
675
+ assert_array_almost_equal(y1, y2)
676
+
677
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
678
+ y2 = solve(A.conj().T, x)
679
+ assert_array_almost_equal(y1, y2)
680
+
681
+ def test_tpmv(self):
682
+ seed(1234)
683
+ for ind, dtype in enumerate(DTYPES):
684
+ n = 10
685
+ x = rand(n).astype(dtype)
686
+ # Upper triangular array
687
+ A = triu(rand(n, n)) if ind < 2 else triu(rand(n, n)+rand(n, n)*1j)
688
+ # Form the packed storage
689
+ c, r = tril_indices(n)
690
+ Ap = A[r, c]
691
+ func, = get_blas_funcs(('tpmv',), dtype=dtype)
692
+
693
+ y1 = func(n=n, ap=Ap, x=x)
694
+ y2 = A.dot(x)
695
+ assert_array_almost_equal(y1, y2)
696
+
697
+ y1 = func(n=n, ap=Ap, x=x, diag=1)
698
+ A[arange(n), arange(n)] = dtype(1)
699
+ y2 = A.dot(x)
700
+ assert_array_almost_equal(y1, y2)
701
+
702
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
703
+ y2 = A.T.dot(x)
704
+ assert_array_almost_equal(y1, y2)
705
+
706
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
707
+ y2 = A.conj().T.dot(x)
708
+ assert_array_almost_equal(y1, y2)
709
+
710
+ def test_tpsv(self):
711
+ seed(1234)
712
+ for ind, dtype in enumerate(DTYPES):
713
+ n = 10
714
+ x = rand(n).astype(dtype)
715
+ # Upper triangular array
716
+ A = triu(rand(n, n)) if ind < 2 else triu(rand(n, n)+rand(n, n)*1j)
717
+ A += eye(n)
718
+ # Form the packed storage
719
+ c, r = tril_indices(n)
720
+ Ap = A[r, c]
721
+ func, = get_blas_funcs(('tpsv',), dtype=dtype)
722
+
723
+ y1 = func(n=n, ap=Ap, x=x)
724
+ y2 = solve(A, x)
725
+ assert_array_almost_equal(y1, y2)
726
+
727
+ y1 = func(n=n, ap=Ap, x=x, diag=1)
728
+ A[arange(n), arange(n)] = dtype(1)
729
+ y2 = solve(A, x)
730
+ assert_array_almost_equal(y1, y2)
731
+
732
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
733
+ y2 = solve(A.T, x)
734
+ assert_array_almost_equal(y1, y2)
735
+
736
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
737
+ y2 = solve(A.conj().T, x)
738
+ assert_array_almost_equal(y1, y2)
739
+
740
+ def test_trmv(self):
741
+ seed(1234)
742
+ for ind, dtype in enumerate(DTYPES):
743
+ n = 3
744
+ A = (rand(n, n)+eye(n)).astype(dtype)
745
+ x = rand(3).astype(dtype)
746
+ func, = get_blas_funcs(('trmv',), dtype=dtype)
747
+
748
+ y1 = func(a=A, x=x)
749
+ y2 = triu(A).dot(x)
750
+ assert_array_almost_equal(y1, y2)
751
+
752
+ y1 = func(a=A, x=x, diag=1)
753
+ A[arange(n), arange(n)] = dtype(1)
754
+ y2 = triu(A).dot(x)
755
+ assert_array_almost_equal(y1, y2)
756
+
757
+ y1 = func(a=A, x=x, diag=1, trans=1)
758
+ y2 = triu(A).T.dot(x)
759
+ assert_array_almost_equal(y1, y2)
760
+
761
+ y1 = func(a=A, x=x, diag=1, trans=2)
762
+ y2 = triu(A).conj().T.dot(x)
763
+ assert_array_almost_equal(y1, y2)
764
+
765
+ def test_trsv(self):
766
+ seed(1234)
767
+ for ind, dtype in enumerate(DTYPES):
768
+ n = 15
769
+ A = (rand(n, n)+eye(n)).astype(dtype)
770
+ x = rand(n).astype(dtype)
771
+ func, = get_blas_funcs(('trsv',), dtype=dtype)
772
+
773
+ y1 = func(a=A, x=x)
774
+ y2 = solve(triu(A), x)
775
+ assert_array_almost_equal(y1, y2)
776
+
777
+ y1 = func(a=A, x=x, lower=1)
778
+ y2 = solve(tril(A), x)
779
+ assert_array_almost_equal(y1, y2)
780
+
781
+ y1 = func(a=A, x=x, diag=1)
782
+ A[arange(n), arange(n)] = dtype(1)
783
+ y2 = solve(triu(A), x)
784
+ assert_array_almost_equal(y1, y2)
785
+
786
+ y1 = func(a=A, x=x, diag=1, trans=1)
787
+ y2 = solve(triu(A).T, x)
788
+ assert_array_almost_equal(y1, y2)
789
+
790
+ y1 = func(a=A, x=x, diag=1, trans=2)
791
+ y2 = solve(triu(A).conj().T, x)
792
+ assert_array_almost_equal(y1, y2)
793
+
794
+
795
+ class TestFBLAS3Simple:
796
+
797
+ def test_gemm(self):
798
+ for p in 'sd':
799
+ f = getattr(fblas, p+'gemm', None)
800
+ if f is None:
801
+ continue
802
+ assert_array_almost_equal(f(3, [3], [-4]), [[-36]])
803
+ assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21])
804
+ for p in 'cz':
805
+ f = getattr(fblas, p+'gemm', None)
806
+ if f is None:
807
+ continue
808
+ assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-36j]])
809
+ assert_array_almost_equal(f(3j, [3-4j], [-4], 3, [5j]), [-48-21j])
810
+
811
+
812
+ def _get_func(func, ps='sdzc'):
813
+ """Just a helper: return a specified BLAS function w/typecode."""
814
+ for p in ps:
815
+ f = getattr(fblas, p+func, None)
816
+ if f is None:
817
+ continue
818
+ yield f
819
+
820
+
821
+ class TestBLAS3Symm:
822
+
823
+ def setup_method(self):
824
+ self.a = np.array([[1., 2.],
825
+ [0., 1.]])
826
+ self.b = np.array([[1., 0., 3.],
827
+ [0., -1., 2.]])
828
+ self.c = np.ones((2, 3))
829
+ self.t = np.array([[2., -1., 8.],
830
+ [3., 0., 9.]])
831
+
832
+ def test_symm(self):
833
+ for f in _get_func('symm'):
834
+ res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
835
+ assert_array_almost_equal(res, self.t)
836
+
837
+ res = f(a=self.a.T, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
838
+ assert_array_almost_equal(res, self.t)
839
+
840
+ res = f(a=self.a, b=self.b.T, side=1, c=self.c.T,
841
+ alpha=1., beta=1.)
842
+ assert_array_almost_equal(res, self.t.T)
843
+
844
+ def test_summ_wrong_side(self):
845
+ f = getattr(fblas, 'dsymm', None)
846
+ if f is not None:
847
+ assert_raises(Exception, f, **{'a': self.a, 'b': self.b,
848
+ 'alpha': 1, 'side': 1})
849
+ # `side=1` means C <- B*A, hence shapes of A and B are to be
850
+ # compatible. Otherwise, f2py exception is raised
851
+
852
+ def test_symm_wrong_uplo(self):
853
+ """SYMM only considers the upper/lower part of A. Hence setting
854
+ wrong value for `lower` (default is lower=0, meaning upper triangle)
855
+ gives a wrong result.
856
+ """
857
+ f = getattr(fblas, 'dsymm', None)
858
+ if f is not None:
859
+ res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
860
+ assert np.allclose(res, self.t)
861
+
862
+ res = f(a=self.a, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
863
+ assert not np.allclose(res, self.t)
864
+
865
+
866
+ class TestBLAS3Syrk:
867
+ def setup_method(self):
868
+ self.a = np.array([[1., 0.],
869
+ [0., -2.],
870
+ [2., 3.]])
871
+ self.t = np.array([[1., 0., 2.],
872
+ [0., 4., -6.],
873
+ [2., -6., 13.]])
874
+ self.tt = np.array([[5., 6.],
875
+ [6., 13.]])
876
+
877
+ def test_syrk(self):
878
+ for f in _get_func('syrk'):
879
+ c = f(a=self.a, alpha=1.)
880
+ assert_array_almost_equal(np.triu(c), np.triu(self.t))
881
+
882
+ c = f(a=self.a, alpha=1., lower=1)
883
+ assert_array_almost_equal(np.tril(c), np.tril(self.t))
884
+
885
+ c0 = np.ones(self.t.shape)
886
+ c = f(a=self.a, alpha=1., beta=1., c=c0)
887
+ assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
888
+
889
+ c = f(a=self.a, alpha=1., trans=1)
890
+ assert_array_almost_equal(np.triu(c), np.triu(self.tt))
891
+
892
+ # prints '0-th dimension must be fixed to 3 but got 5',
893
+ # FIXME: suppress?
894
+ # FIXME: how to catch the _fblas.error?
895
+ def test_syrk_wrong_c(self):
896
+ f = getattr(fblas, 'dsyrk', None)
897
+ if f is not None:
898
+ assert_raises(Exception, f, **{'a': self.a, 'alpha': 1.,
899
+ 'c': np.ones((5, 8))})
900
+ # if C is supplied, it must have compatible dimensions
901
+
902
+
903
+ class TestBLAS3Syr2k:
904
+ def setup_method(self):
905
+ self.a = np.array([[1., 0.],
906
+ [0., -2.],
907
+ [2., 3.]])
908
+ self.b = np.array([[0., 1.],
909
+ [1., 0.],
910
+ [0, 1.]])
911
+ self.t = np.array([[0., -1., 3.],
912
+ [-1., 0., 0.],
913
+ [3., 0., 6.]])
914
+ self.tt = np.array([[0., 1.],
915
+ [1., 6]])
916
+
917
+ def test_syr2k(self):
918
+ for f in _get_func('syr2k'):
919
+ c = f(a=self.a, b=self.b, alpha=1.)
920
+ assert_array_almost_equal(np.triu(c), np.triu(self.t))
921
+
922
+ c = f(a=self.a, b=self.b, alpha=1., lower=1)
923
+ assert_array_almost_equal(np.tril(c), np.tril(self.t))
924
+
925
+ c0 = np.ones(self.t.shape)
926
+ c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0)
927
+ assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
928
+
929
+ c = f(a=self.a, b=self.b, alpha=1., trans=1)
930
+ assert_array_almost_equal(np.triu(c), np.triu(self.tt))
931
+
932
+ # prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress?
933
+ def test_syr2k_wrong_c(self):
934
+ f = getattr(fblas, 'dsyr2k', None)
935
+ if f is not None:
936
+ assert_raises(Exception, f, **{'a': self.a,
937
+ 'b': self.b,
938
+ 'alpha': 1.,
939
+ 'c': np.zeros((15, 8))})
940
+ # if C is supplied, it must have compatible dimensions
941
+
942
+
943
+ class TestSyHe:
944
+ """Quick and simple tests for (zc)-symm, syrk, syr2k."""
945
+
946
+ def setup_method(self):
947
+ self.sigma_y = np.array([[0., -1.j],
948
+ [1.j, 0.]])
949
+
950
+ def test_symm_zc(self):
951
+ for f in _get_func('symm', 'zc'):
952
+ # NB: a is symmetric w/upper diag of ONLY
953
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
954
+ assert_array_almost_equal(np.triu(res), np.diag([1, -1]))
955
+
956
+ def test_hemm_zc(self):
957
+ for f in _get_func('hemm', 'zc'):
958
+ # NB: a is hermitian w/upper diag of ONLY
959
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
960
+ assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
961
+
962
+ def test_syrk_zr(self):
963
+ for f in _get_func('syrk', 'zc'):
964
+ res = f(a=self.sigma_y, alpha=1.)
965
+ assert_array_almost_equal(np.triu(res), np.diag([-1, -1]))
966
+
967
+ def test_herk_zr(self):
968
+ for f in _get_func('herk', 'zc'):
969
+ res = f(a=self.sigma_y, alpha=1.)
970
+ assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
971
+
972
+ def test_syr2k_zr(self):
973
+ for f in _get_func('syr2k', 'zc'):
974
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
975
+ assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1]))
976
+
977
+ def test_her2k_zr(self):
978
+ for f in _get_func('her2k', 'zc'):
979
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
980
+ assert_array_almost_equal(np.triu(res), 2.*np.diag([1, 1]))
981
+
982
+
983
+ class TestTRMM:
984
+ """Quick and simple tests for dtrmm."""
985
+
986
+ def setup_method(self):
987
+ self.a = np.array([[1., 2., ],
988
+ [-2., 1.]])
989
+ self.b = np.array([[3., 4., -1.],
990
+ [5., 6., -2.]])
991
+
992
+ self.a2 = np.array([[1, 1, 2, 3],
993
+ [0, 1, 4, 5],
994
+ [0, 0, 1, 6],
995
+ [0, 0, 0, 1]], order="f")
996
+ self.b2 = np.array([[1, 4], [2, 5], [3, 6], [7, 8], [9, 10]],
997
+ order="f")
998
+
999
+ @pytest.mark.parametrize("dtype_", DTYPES)
1000
+ def test_side(self, dtype_):
1001
+ trmm = get_blas_funcs("trmm", dtype=dtype_)
1002
+ # Provide large A array that works for side=1 but not 0 (see gh-10841)
1003
+ assert_raises(Exception, trmm, 1.0, self.a2, self.b2)
1004
+ res = trmm(1.0, self.a2.astype(dtype_), self.b2.astype(dtype_),
1005
+ side=1)
1006
+ k = self.b2.shape[1]
1007
+ assert_allclose(res, self.b2 @ self.a2[:k, :k], rtol=0.,
1008
+ atol=100*np.finfo(dtype_).eps)
1009
+
1010
+ def test_ab(self):
1011
+ f = getattr(fblas, 'dtrmm', None)
1012
+ if f is not None:
1013
+ result = f(1., self.a, self.b)
1014
+ # default a is upper triangular
1015
+ expected = np.array([[13., 16., -5.],
1016
+ [5., 6., -2.]])
1017
+ assert_array_almost_equal(result, expected)
1018
+
1019
+ def test_ab_lower(self):
1020
+ f = getattr(fblas, 'dtrmm', None)
1021
+ if f is not None:
1022
+ result = f(1., self.a, self.b, lower=True)
1023
+ expected = np.array([[3., 4., -1.],
1024
+ [-1., -2., 0.]]) # now a is lower triangular
1025
+ assert_array_almost_equal(result, expected)
1026
+
1027
+ def test_b_overwrites(self):
1028
+ # BLAS dtrmm modifies B argument in-place.
1029
+ # Here the default is to copy, but this can be overridden
1030
+ f = getattr(fblas, 'dtrmm', None)
1031
+ if f is not None:
1032
+ for overwr in [True, False]:
1033
+ bcopy = self.b.copy()
1034
+ result = f(1., self.a, bcopy, overwrite_b=overwr)
1035
+ # C-contiguous arrays are copied
1036
+ assert_(bcopy.flags.f_contiguous is False and
1037
+ np.may_share_memory(bcopy, result) is False)
1038
+ assert_equal(bcopy, self.b)
1039
+
1040
+ bcopy = np.asfortranarray(self.b.copy()) # or just transpose it
1041
+ result = f(1., self.a, bcopy, overwrite_b=True)
1042
+ assert_(bcopy.flags.f_contiguous is True and
1043
+ np.may_share_memory(bcopy, result) is True)
1044
+ assert_array_almost_equal(bcopy, result)
1045
+
1046
+
1047
+ def test_trsm():
1048
+ seed(1234)
1049
+ for ind, dtype in enumerate(DTYPES):
1050
+ tol = np.finfo(dtype).eps*1000
1051
+ func, = get_blas_funcs(('trsm',), dtype=dtype)
1052
+
1053
+ # Test protection against size mismatches
1054
+ A = rand(4, 5).astype(dtype)
1055
+ B = rand(4, 4).astype(dtype)
1056
+ alpha = dtype(1)
1057
+ assert_raises(Exception, func, alpha, A, B)
1058
+ assert_raises(Exception, func, alpha, A.T, B)
1059
+
1060
+ n = 8
1061
+ m = 7
1062
+ alpha = dtype(-2.5)
1063
+ A = (rand(m, m) if ind < 2 else rand(m, m) + rand(m, m)*1j) + eye(m)
1064
+ A = A.astype(dtype)
1065
+ Au = triu(A)
1066
+ Al = tril(A)
1067
+ B1 = rand(m, n).astype(dtype)
1068
+ B2 = rand(n, m).astype(dtype)
1069
+
1070
+ x1 = func(alpha=alpha, a=A, b=B1)
1071
+ assert_equal(B1.shape, x1.shape)
1072
+ x2 = solve(Au, alpha*B1)
1073
+ assert_allclose(x1, x2, atol=tol)
1074
+
1075
+ x1 = func(alpha=alpha, a=A, b=B1, trans_a=1)
1076
+ x2 = solve(Au.T, alpha*B1)
1077
+ assert_allclose(x1, x2, atol=tol)
1078
+
1079
+ x1 = func(alpha=alpha, a=A, b=B1, trans_a=2)
1080
+ x2 = solve(Au.conj().T, alpha*B1)
1081
+ assert_allclose(x1, x2, atol=tol)
1082
+
1083
+ x1 = func(alpha=alpha, a=A, b=B1, diag=1)
1084
+ Au[arange(m), arange(m)] = dtype(1)
1085
+ x2 = solve(Au, alpha*B1)
1086
+ assert_allclose(x1, x2, atol=tol)
1087
+
1088
+ x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1)
1089
+ x2 = solve(Au.conj().T, alpha*B2.conj().T)
1090
+ assert_allclose(x1, x2.conj().T, atol=tol)
1091
+
1092
+ x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1, lower=1)
1093
+ Al[arange(m), arange(m)] = dtype(1)
1094
+ x2 = solve(Al.conj().T, alpha*B2.conj().T)
1095
+ assert_allclose(x1, x2.conj().T, atol=tol)
1096
+
1097
+
1098
+ @pytest.mark.xfail(run=False,
1099
+ reason="gh-16930")
1100
+ def test_gh_169309():
1101
+ x = np.repeat(10, 9)
1102
+ actual = scipy.linalg.blas.dnrm2(x, 5, 3, -1)
1103
+ expected = math.sqrt(500)
1104
+ assert_allclose(actual, expected)
1105
+
1106
+
1107
+ def test_dnrm2_neg_incx():
1108
+ # check that dnrm2(..., incx < 0) raises
1109
+ # XXX: remove the test after the lowest supported BLAS implements
1110
+ # negative incx (new in LAPACK 3.10)
1111
+ x = np.repeat(10, 9)
1112
+ incx = -1
1113
+ with assert_raises(fblas.__fblas_error):
1114
+ scipy.linalg.blas.dnrm2(x, 5, 3, incx)